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
feat(community): cache a public application shell (#1052)
Genere0827f02f341
diff --git a/src/web/.gitignore b/src/web/.gitignoreindex 5469bdf85..fbc60cd37 100644--- a/src/web/.gitignore+++ b/src/web/.gitignore@@ -35,6 +35,7 @@ src/test/e2e-ui/.auth//blog/public/fonts//out//public/sw.js+/public/community-shell/# production/builddiff --git a/src/web/eslint.config.mjs b/src/web/eslint.config.mjsindex ccf6eeeb6..2af17c656 100644--- a/src/web/eslint.config.mjs+++ b/src/web/eslint.config.mjs@@ -33,6 +33,7 @@ const eslintConfig = defineConfig([".next/**","blog/.next/**","blog/.open-next/**",+ "**/.wrangler/**","out/**","build/**","next-env.d.ts",diff --git a/src/web/next.config.ts b/src/web/next.config.tsindex a32c3fa47..a590160e5 100644--- a/src/web/next.config.ts+++ b/src/web/next.config.ts@@ -9,6 +9,14 @@ const daemonPkg = JSON.parse(readFileSync(path.resolve(__dirname, "../daemon/pacconst observation = resolveObservationBuild(process.env);const nextConfig: NextConfig = {+ async headers() {+ return [{ source: "/community-shell/:hash", headers: [+ { key: "Cache-Control", value: "public, max-age=31536000, immutable" },+ { key: "Content-Type", value: "text/html; charset=utf-8" },+ { key: "X-Content-Type-Options", value: "nosniff" },+ { key: "X-Robots-Tag", value: "noindex" },+ ] }];+ },images: { unoptimized: true },env: {NEXT_PUBLIC_APP_VERSION: pkg.version,diff --git a/src/web/package.json b/src/web/package.jsonindex b40ce1fc6..33ca6c35f 100644--- a/src/web/package.json+++ b/src/web/package.json@@ -8,7 +8,7 @@"dev:blog": "node ../../scripts/dev-with-wrangler-registry.mjs ../../.wrangler/registry next dev blog --hostname 127.0.0.1 --port 3002","dev:auth": "wrangler dev --config auth/wrangler.toml","dev:zones:worker": "node scripts/dev-zones.mjs --worker",- "build": "next build && tsx scripts/stage-service-worker.ts",+ "build": "next build && NODE_ENV=production tsx scripts/stage-service-worker.ts","build:blog:next": "pnpm validate:blog && tsx blog/scripts/stage-shared-assets.ts && next build blog && tsx blog/scripts/validate-rendered.ts && tsx blog/scripts/prepare-open-next-standalone.ts","build:blog": "tsx blog/scripts/stage-shared-assets.ts && opennextjs-cloudflare build --config blog/wrangler.toml --openNextConfigPath blog/open-next.config.ts && tsx blog/scripts/stage-cache-assets.ts","build:auth": "wrangler deploy --dry-run --config auth/wrangler.toml --outdir dist",diff --git a/src/web/public/_headers b/src/web/public/_headersindex 78762d34a..3bd63df91 100644--- a/src/web/public/_headers+++ b/src/web/public/_headers@@ -39,3 +39,9 @@/social/readme-card-58c75311e5ba.pngCache-Control: public, max-age=300, must-revalidate++/community-shell/*+ Cache-Control: public, max-age=31536000, immutable+ Content-Type: text/html; charset=utf-8+ X-Content-Type-Options: nosniff+ X-Robots-Tag: noindexdiff --git a/src/web/readme-capture/capture.test.ts b/src/web/readme-capture/capture.test.tsindex 6bda8899b..8e37a02aa 100644--- a/src/web/readme-capture/capture.test.ts+++ b/src/web/readme-capture/capture.test.ts@@ -45,7 +45,7 @@ describe("standalone README capture app contract", () => {"utf8",)const inviteSource = readFileSync(- path.join(root, "src/app/c/invite/[token]/invite-accept-client.tsx"),+ path.join(root, "src/app/(public-community)/c/invite/[token]/invite-accept-client.tsx"),"utf8",)diff --git a/src/web/scripts/stage-service-worker.test.ts b/src/web/scripts/stage-service-worker.test.tsindex ad739fbbb..ff36e024e 100644--- a/src/web/scripts/stage-service-worker.test.ts+++ b/src/web/scripts/stage-service-worker.test.ts@@ -1,45 +1,122 @@-import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"+import type { createSerwistRoute } from "@serwist/turbopack"+import { createHash } from "node:crypto"+import { mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"import { tmpdir } from "node:os"import { resolve } from "node:path"-import { afterEach, describe, expect, it } from "vitest"-import { stageServiceWorker } from "./stage-service-worker"--const temporaryRoots: string[] = []-afterEach(() => {- for (const root of temporaryRoots.splice(0)) rmSync(root, { recursive: true, force: true })-})-+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+const mocks = vi.hoisted(() => ({ options: null as Record<string, unknown> | null, status: 200, type: "application/javascript", script: true }))+vi.mock("@serwist/turbopack", () => ({ createSerwistRoute: (options: Record<string, unknown>) => {+ mocks.options = options+ return { GET: async () => {+ const { readdirSync } = await import("node:fs")+ const shell = readdirSync(`${options.cwd}/public/community-shell`)[0]+ return new Response(mocks.script ? `self.shell="/community-shell/${shell}"` : "", { status: mocks.status, headers: { "Content-Type": mocks.type, "Service-Worker-Allowed": "/" } })+ } }+} }))+import { stageCommunityShell, stageServiceWorker } from "./stage-service-worker"+type RouteOptions = Parameters<typeof createSerwistRoute>[0]+const roots: string[] = []+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })+beforeEach(() => { mocks.status = 200; mocks.type = "application/javascript"; mocks.script = true; mocks.options = null })+const html = '<html><main data-community-shell="public">Neutral</main></html>'function fixture() {- const root = mkdtempSync(resolve(tmpdir(), "alook-stage-sw-"))- temporaryRoots.push(root)- mkdirSync(resolve(root, ".next/server/app/serwist"), { recursive: true })- mkdirSync(resolve(root, "public"))- const meta = { status: 200, headers: { "content-type": "application/javascript", "service-worker-allowed": "/", "cache-control": "no-cache" } }- writeFileSync(resolve(root, ".next/server/app/serwist/sw.js.meta"), JSON.stringify(meta))- writeFileSync(resolve(root, ".next/server/app/serwist/sw.js.body"), "self.buildVersion='current';")- writeFileSync(resolve(root, "public/sw.js"), "self.buildVersion='old';")- return { root, meta }+ const root = mkdtempSync(resolve(tmpdir(), "alook-public-shell-")); roots.push(root)+ mkdirSync(resolve(root, ".next/server/app"), { recursive: true }); mkdirSync(resolve(root, "public"))+ writeFileSync(resolve(root, ".next/prerender-manifest.json"), JSON.stringify({ routes: { "/c": {} } }))+ writeFileSync(resolve(root, ".next/server/app/c.html"), html)+ writeFileSync(resolve(root, "public/sw.js"), "old-worker")+ return root}--describe("public SW static staging", () => {- it("replaces the previous public script with the exact generated bytes", () => {- const { root } = fixture()- stageServiceWorker(root)- expect(readFileSync(resolve(root, "public/sw.js"))).toEqual(readFileSync(resolve(root, ".next/server/app/serwist/sw.js.body")))+describe("complete build shell and worker staging", () => {+ it("builds a classic worker from explicit public asset globs", async () => {+ await stageServiceWorker(fixture())+ const options = mocks.options as RouteOptions | null+ expect(options?.swSrc).toBe("src/app/sw.ts")+ expect(options?.useNativeEsbuild).toBe(true)+ expect(options?.globPatterns).toEqual([+ ".next/static/chunks/**/*.{js,css}",+ ".next/static/media/**/*.{woff,woff2,ttf,png,jpg,jpeg,webp,svg,ico}",+ ".next/static/media/pdf.worker.min.*.mjs",+ ".next/static/*/_{buildManifest,clientMiddlewareManifest,ssgManifest}.js",+ "public/**/*.{svg,png,jpg,jpeg,webp,ttf,json}",+ "public/community-shell/*",+ "src/app/favicon.ico",+ ])+ expect(options?.modifyURLPrefix).toEqual({ "src/app/favicon.ico": "/favicon.ico" })+ expect(options?.maximumFileSizeToCacheInBytes).toBe(10 * 1024 * 1024)+ expect(options?.esbuildOptions).toEqual({ format: "iife", sourcemap: false, minify: true, define: { "process.env.NODE_ENV": JSON.stringify("production") } })})-- it.each(["status", "content-type", "service-worker-allowed", "cache-control"])("rejects invalid %s metadata without publishing it", field => {- const { root, meta } = fixture()- if (field === "status") meta.status = 500- else meta.headers[field as keyof typeof meta.headers] = "invalid"- writeFileSync(resolve(root, ".next/server/app/serwist/sw.js.meta"), JSON.stringify(meta))- expect(() => stageServiceWorker(root)).toThrow("Generated public service worker metadata is invalid")- expect(readFileSync(resolve(root, "public/sw.js"), "utf8")).toBe("self.buildVersion='old';")+ it("filters private documents and unknown assets while retaining only the exact current shell", async () => {+ await stageServiceWorker(fixture())+ const options = mocks.options as RouteOptions | null+ const urls = [+ ".next/static/chunks/app-a.js",+ ".next/static/chunks/styles-a.css",+ ".next/static/media/font-a.woff2",+ ".next/static/media/pdf.worker.min.35m0adryw15hm.mjs",+ ".next/static/PGQscKRC0WsRFC5mS4zSH/_buildManifest.js",+ ".next/static/PGQscKRC0WsRFC5mS4zSH/_clientMiddlewareManifest.js",+ ".next/static/PGQscKRC0WsRFC5mS4zSH/_ssgManifest.js",+ "/favicon.ico",+ "public/manifest.json",+ "public/fonts/jgs5/jgs5.ttf",+ "public/contact/gus-photo.jpeg",+ "public/alook.svg",+ "public/official-server-badge-flat.svg",+ "public/apple-touch-icon.png",+ "public/icon-192.png",+ "public/icon-512.png",+ ]+ const publicEntries = urls.map((url, i) => ({ url, revision: `public-${i}`, size: i + 1 }))+ const excluded = [+ "public/sw.js", "public/unknown.png", "public/avatar.png",+ ".next/server/app/c.html", ".next/server/app/c.rsc",+ "/c", "/c?_rsc=private", "/api/community/users/me/profile",+ "/api/community/servers/server-a/avatar?v=1", "/api/files/private-a",+ "https://other.test/_next/static/chunks/app-a.js",+ ".next/static/chunks/app-a.js?account=a",+ ".next/static/media/other-worker.mjs",+ ".next/static/media/pdf.worker.min.mjs",+ ".next/static/PGQscKRC0WsRFC5mS4zSH/unknown.js",+ ".next/static/private/nested/_buildManifest.js",+ ].map((url, i) => ({ url, revision: `excluded-${i}`, size: i + 1 }))+ const shell = { url: `public/community-shell/${createHash("sha256").update(html).digest("hex")}`, revision: "shell" }+ excluded.push({ url: `public/community-shell/${"a".repeat(64)}`, revision: "old-shell", size: 1 })+ excluded.push({ url: `${shell.url}?account=a`, revision: "query-shell", size: 1 })+ const result = await options!.manifestTransforms+ expect(result).toEqual({ manifest: [...publicEntries, shell], warnings: [] })+ expect(result.manifest[0]).toBe(publicEntries[0])})- it("fails rather than reusing a stale script when the current build is absent", () => {- const { root } = fixture()- rmSync(resolve(root, ".next/server/app/serwist/sw.js.body"))- expect(() => stageServiceWorker(root)).toThrow()+ it("publishes exact prerendered bytes at an immutable hash URL before building the worker", async () => {+ const root = fixture(); await stageServiceWorker(root)+ const hash = createHash("sha256").update(html).digest("hex")+ expect(readFileSync(resolve(root, `public/community-shell/${hash}`), "utf8")).toBe(html)+ expect(readFileSync(resolve(root, "public/sw.js"), "utf8")).toContain(`/community-shell/${hash}`)+ expect(mocks.options?.cwd).toBe(root)+ })+ it("updates the shell hash with bytes and removes only old generated shell assets", () => {+ const root = fixture(); const old = stageCommunityShell(root)+ writeFileSync(resolve(root, "public/community-shell/keep.txt"), "unowned")+ writeFileSync(resolve(root, ".next/server/app/c.html"), `${html}updated`)+ expect(stageCommunityShell(root)).not.toBe(old)+ expect(readdirSync(resolve(root, "public/community-shell"))).toContain("keep.txt")+ expect(readdirSync(resolve(root, "public/community-shell"))).not.toContain(old.split("/").at(-1))+ })+ it.each(["missing-document", "dynamic-document", "missing-marker"])("rejects %s instead of publishing a stale worker", async mode => {+ const root = fixture()+ if (mode === "missing-document") rmSync(resolve(root, ".next/server/app/c.html"))+ if (mode === "dynamic-document") writeFileSync(resolve(root, ".next/prerender-manifest.json"), JSON.stringify({ routes: {} }))+ if (mode === "missing-marker") writeFileSync(resolve(root, ".next/server/app/c.html"), "private document")+ await expect(stageServiceWorker(root)).rejects.toThrow()+ expect(readFileSync(resolve(root, "public/sw.js"), "utf8")).toBe("old-worker")+ })+ it.each(["status", "type", "empty-script"])("rejects bad worker %s before replacing the current script", async field => {+ const root = fixture()+ if (field === "status") mocks.status = 500+ if (field === "type") mocks.type = "text/html"+ if (field === "empty-script") mocks.script = false+ await expect(stageServiceWorker(root)).rejects.toThrow()+ expect(readFileSync(resolve(root, "public/sw.js"), "utf8")).toBe("old-worker")})})diff --git a/src/web/scripts/stage-service-worker.ts b/src/web/scripts/stage-service-worker.tsindex 14eb03ceb..8162b9623 100644--- a/src/web/scripts/stage-service-worker.ts+++ b/src/web/scripts/stage-service-worker.ts@@ -1,18 +1,61 @@-import { copyFileSync, mkdirSync, readFileSync } from "node:fs"+import { createSerwistRoute } from "@serwist/turbopack"+import { createHash } from "node:crypto"+import { mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"import { resolve } from "node:path"import { fileURLToPath } from "node:url"+import { isPublicAssetPath } from "../src/lib/service-worker/public-cache"+import { communityShellDirectory, communityShellHash } from "../src/lib/service-worker/community-shell"-export function stageServiceWorker(webRoot: string): void {- const source = resolve(webRoot, ".next/server/app/serwist/sw.js.body")- const metadata = JSON.parse(readFileSync(resolve(webRoot, ".next/server/app/serwist/sw.js.meta"), "utf8"))- if (metadata.status !== 200 || metadata.headers["content-type"] !== "application/javascript"- || metadata.headers["service-worker-allowed"] !== "/" || metadata.headers["cache-control"] !== "no-cache") {- throw new Error("Generated public service worker metadata is invalid")+export function stageCommunityShell(webRoot: string): string {+ const prerender = JSON.parse(readFileSync(resolve(webRoot, ".next/prerender-manifest.json"), "utf8")) as { routes: Record<string, unknown> }+ if (!Object.hasOwn(prerender.routes, "/c")) throw new Error("Community shell must be prerendered without request data")+ const html = readFileSync(resolve(webRoot, ".next/server/app/c.html"))+ if (!html.includes('data-community-shell="public"')) throw new Error("Generated community shell marker is missing")+ const hash = createHash("sha256").update(html).digest("hex")+ const filename = hash+ const directory = resolve(webRoot, `public${communityShellDirectory}`)+ mkdirSync(directory, { recursive: true })+ for (const old of readdirSync(directory)) {+ if (communityShellHash(`${communityShellDirectory}${old}`)) rmSync(resolve(directory, old))}- mkdirSync(resolve(webRoot, "public"), { recursive: true })- copyFileSync(source, resolve(webRoot, "public/sw.js"))+ writeFileSync(resolve(directory, filename), html)+ return `${communityShellDirectory}${filename}`+}++export async function stageServiceWorker(webRoot: string): Promise<void> {+ const shellUrl = stageCommunityShell(webRoot)+ const serviceWorker = createSerwistRoute({+ cwd: webRoot,+ swSrc: "src/app/sw.ts",+ useNativeEsbuild: true,+ globPatterns: [+ ".next/static/chunks/**/*.{js,css}",+ ".next/static/media/**/*.{woff,woff2,ttf,png,jpg,jpeg,webp,svg,ico}",+ ".next/static/media/pdf.worker.min.*.mjs",+ ".next/static/*/_{buildManifest,clientMiddlewareManifest,ssgManifest}.js",+ "public/**/*.{svg,png,jpg,jpeg,webp,ttf,json}",+ "public/community-shell/*",+ "src/app/favicon.ico",+ ],+ modifyURLPrefix: { "src/app/favicon.ico": "/favicon.ico" },+ maximumFileSizeToCacheInBytes: 10 * 1024 * 1024,+ manifestTransforms: [async entries => ({+ manifest: entries.filter(entry => {+ const pathname = entry.url.replace(/^\.next\//, "/_next/").replace(/^public\//, "/")+ return pathname === shellUrl || isPublicAssetPath(pathname)+ }),+ warnings: [],+ })],+ esbuildOptions: { format: "iife", sourcemap: false, minify: true, define: { "process.env.NODE_ENV": JSON.stringify("production") } },+ })+ const response = await serviceWorker.GET(new Request("https://build.invalid/sw.js"), { params: Promise.resolve({ path: "sw.js" }) })+ if (response.status !== 200 || response.headers.get("Content-Type") !== "application/javascript"+ || response.headers.get("Service-Worker-Allowed") !== "/") throw new Error("Generated public service worker metadata is invalid")+ const bytes = Buffer.from(await response.arrayBuffer())+ if (!bytes.length || !bytes.includes(shellUrl)) throw new Error("Generated service worker is missing the current community shell")+ writeFileSync(resolve(webRoot, "public/sw.js"), bytes)}if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {- stageServiceWorker(fileURLToPath(new URL("../", import.meta.url)))+ void stageServiceWorker(fileURLToPath(new URL("../", import.meta.url))).catch(error => { console.error(error); process.exitCode = 1 })}diff --git a/src/web/src/app/c/invite/[token]/invite-accept-client.test.ts b/src/web/src/app/(public-community)/c/invite/[token]/invite-accept-client.test.tssimilarity index 100%rename from src/web/src/app/c/invite/[token]/invite-accept-client.test.tsrename to src/web/src/app/(public-community)/c/invite/[token]/invite-accept-client.test.tsdiff --git a/src/web/src/app/c/invite/[token]/invite-accept-client.tsx b/src/web/src/app/(public-community)/c/invite/[token]/invite-accept-client.tsxsimilarity index 100%rename from src/web/src/app/c/invite/[token]/invite-accept-client.tsxrename to src/web/src/app/(public-community)/c/invite/[token]/invite-accept-client.tsxdiff --git a/src/web/src/app/c/invite/[token]/page.tsx b/src/web/src/app/(public-community)/c/invite/[token]/page.tsxsimilarity index 80%rename from src/web/src/app/c/invite/[token]/page.tsxrename to src/web/src/app/(public-community)/c/invite/[token]/page.tsxindex 6660e8d37..79e5f92e4 100644--- a/src/web/src/app/c/invite/[token]/page.tsx+++ b/src/web/src/app/(public-community)/c/invite/[token]/page.tsx@@ -1,4 +1,5 @@import type { Metadata } from "next"+import { SignupTracker } from "@/components/signup-tracker"import { InviteAcceptClient } from "./invite-accept-client"/**@@ -20,5 +21,5 @@ export default async function InvitePage({params: Promise<{ token: string }>}) {const { token } = await params- return <InviteAcceptClient token={token} />+ return <><SignupTracker /><InviteAcceptClient token={token} /></>}diff --git a/src/web/src/app/c/@sidebar/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/@sidebar/channels/[serverId]/[channelId]/page.tsxdeleted file mode 100644index ec02727e4..000000000--- a/src/web/src/app/c/@sidebar/channels/[serverId]/[channelId]/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-export default function SidebarLeaf() {- return null-}diff --git a/src/web/src/app/c/@sidebar/channels/[serverId]/layout.tsx b/src/web/src/app/c/@sidebar/channels/[serverId]/layout.tsxdeleted file mode 100644index ecc572698..000000000--- a/src/web/src/app/c/@sidebar/channels/[serverId]/layout.tsx+++ /dev/null@@ -1,5 +0,0 @@-import type { ReactNode } from "react"--export default function ServerSidebarLayout({ children }: { children: ReactNode }) {- return children-}diff --git a/src/web/src/app/c/@sidebar/channels/[serverId]/page.tsx b/src/web/src/app/c/@sidebar/channels/[serverId]/page.tsxdeleted file mode 100644index ad07a7472..000000000--- a/src/web/src/app/c/@sidebar/channels/[serverId]/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-export default function SidebarRoot() {- return null-}diff --git a/src/web/src/app/c/@sidebar/channels/[serverId]/settings/page.tsx b/src/web/src/app/c/@sidebar/channels/[serverId]/settings/page.tsxdeleted file mode 100644index ec02727e4..000000000--- a/src/web/src/app/c/@sidebar/channels/[serverId]/settings/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-export default function SidebarLeaf() {- return null-}diff --git a/src/web/src/app/c/@sidebar/default.tsx b/src/web/src/app/c/@sidebar/default.tsxdeleted file mode 100644index ec02727e4..000000000--- a/src/web/src/app/c/@sidebar/default.tsx+++ /dev/null@@ -1,3 +0,0 @@-export default function SidebarLeaf() {- return null-}diff --git a/src/web/src/app/c/@sidebar/invite/[token]/page.tsx b/src/web/src/app/c/@sidebar/invite/[token]/page.tsxdeleted file mode 100644index ec02727e4..000000000--- a/src/web/src/app/c/@sidebar/invite/[token]/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-export default function SidebarLeaf() {- return null-}diff --git a/src/web/src/app/c/@sidebar/me/[dmId]/page.tsx b/src/web/src/app/c/@sidebar/me/[dmId]/page.tsxdeleted file mode 100644index ec02727e4..000000000--- a/src/web/src/app/c/@sidebar/me/[dmId]/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-export default function SidebarLeaf() {- return null-}diff --git a/src/web/src/app/c/@sidebar/me/bots/page.tsx b/src/web/src/app/c/@sidebar/me/bots/page.tsxdeleted file mode 100644index ec02727e4..000000000--- a/src/web/src/app/c/@sidebar/me/bots/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-export default function SidebarLeaf() {- return null-}diff --git a/src/web/src/app/c/@sidebar/me/friends/page.tsx b/src/web/src/app/c/@sidebar/me/friends/page.tsxdeleted file mode 100644index ec02727e4..000000000--- a/src/web/src/app/c/@sidebar/me/friends/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-export default function SidebarLeaf() {- return null-}diff --git a/src/web/src/app/c/@sidebar/me/layout.tsx b/src/web/src/app/c/@sidebar/me/layout.tsxdeleted file mode 100644index 54a6cf15d..000000000--- a/src/web/src/app/c/@sidebar/me/layout.tsx+++ /dev/null@@ -1,5 +0,0 @@-import type { ReactNode } from "react"--export default function MeSidebarLayout({ children }: { children: ReactNode }) {- return children-}diff --git a/src/web/src/app/c/@sidebar/me/machines/page.tsx b/src/web/src/app/c/@sidebar/me/machines/page.tsxdeleted file mode 100644index ec02727e4..000000000--- a/src/web/src/app/c/@sidebar/me/machines/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-export default function SidebarLeaf() {- return null-}diff --git a/src/web/src/app/c/@sidebar/me/page.tsx b/src/web/src/app/c/@sidebar/me/page.tsxdeleted file mode 100644index ad07a7472..000000000--- a/src/web/src/app/c/@sidebar/me/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-export default function SidebarRoot() {- return null-}diff --git a/src/web/src/app/c/@sidebar/messages/[messageId]/page.tsx b/src/web/src/app/c/@sidebar/messages/[messageId]/page.tsxdeleted file mode 100644index 6b6e586bf..000000000--- a/src/web/src/app/c/@sidebar/messages/[messageId]/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-export default function MessageSidebar() {- return null-}diff --git a/src/web/src/app/c/@sidebar/onboarding-preview/page.tsx b/src/web/src/app/c/@sidebar/onboarding-preview/page.tsxdeleted file mode 100644index ec02727e4..000000000--- a/src/web/src/app/c/@sidebar/onboarding-preview/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-export default function SidebarLeaf() {- return null-}diff --git a/src/web/src/app/c/@sidebar/page.tsx b/src/web/src/app/c/@sidebar/page.tsxdeleted file mode 100644index ec02727e4..000000000--- a/src/web/src/app/c/@sidebar/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-export default function SidebarLeaf() {- return null-}diff --git a/src/web/src/app/c/QueryProvider.bots-document.dom.test.tsx b/src/web/src/app/c/QueryProvider.bots-document.dom.test.tsxdeleted file mode 100644index ce492574d..000000000--- a/src/web/src/app/c/QueryProvider.bots-document.dom.test.tsx+++ /dev/null@@ -1,79 +0,0 @@-import "fake-indexeddb/auto"-import React from "react"-import { useIsRestoring } from "@tanstack/react-query"-import type { Database } from "@alook/shared"-import { beforeEach, expect, it, vi } from "vitest"-import { act, render, waitFor } from "@/test/react-dom-harness"-import { useOptionalCommunityDbRegistry } from "@/lib/community-db/projections"-import type { CommunityDbRegistry } from "@/lib/community-db/collections"-import type { QualifiedPersister } from "@/lib/query-persister"-const mocks = vi.hoisted(() => ({ restore: vi.fn(), api: vi.fn(), bots: vi.fn(), machines: vi.fn(),- persistClient: vi.fn(async () => {}), removeClient: vi.fn(async () => {}), isCurrent: vi.fn(async () => true), retireAccount: vi.fn(async () => {}), retireChannels: vi.fn(async () => {}),-}))-vi.mock("@/lib/auth-client", () => ({ useSession: () => ({ data: { user: { id: "viewer" } }, isPending: false, error: null }), currentSessionViewer: () => "viewer" }))-vi.mock("next/navigation", () => ({ usePathname: () => "/c/me/bots", useRouter: () => ({ push: vi.fn(), replace: vi.fn(), refresh: vi.fn() }), useSearchParams: () => new URLSearchParams() }))-vi.mock("@tanstack/react-query-devtools", () => ({ ReactQueryDevtools: () => null }))-vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: (...args: unknown[]) => mocks.api(...args) }))-vi.mock("@/lib/query-persister", async original => ({ ...await original<typeof import("@/lib/query-persister")>(), createIdbPersister: () => ({ ...mocks, restoreClient: mocks.restore }) satisfies QualifiedPersister }))-vi.mock("@/lib/community/bots.server", () => ({ readCommunityBots: mocks.bots }))-vi.mock("@/lib/community/machines.server", () => ({ readCommunityMachineList: mocks.machines }))-vi.mock("@/components/community/bots/create-bot-sheet", () => ({ CreateBotSheet: () => null }))-vi.mock("@/components/community/billing/billing-sheet", () => ({ BillingSheet: () => null }))-vi.mock("@/components/community/onboarding-tiles/create-tile", () => ({ CreateTile: () => React.createElement("div") }))-import { readCommunityDocumentSeed } from "@/lib/community/document-seed.server"-import { QueryProvider } from "@/app/c/QueryProvider"-import { CurrentUserProvider } from "@/contexts/community/current-user"-import { BotList } from "@/components/community/bots/bot-list"-const profile = { id: "viewer", name: "Viewer", discriminator: "0042", avatar: "/avatar", avatarVersion: 1, aboutMe: "", bannerColor: null, statusEmoji: null, statusText: "" }-const bots = { bots: [], plan: { id: "free", displayName: "Free" }, isFounder: false, limit: 1, ownedCount: 0, activeCount: 0 }-beforeEach(() => {- localStorage.clear()- mocks.restore.mockReset()- mocks.api.mockReset()- mocks.bots.mockReset().mockResolvedValue(bots)- mocks.machines.mockReset().mockResolvedValue({ machines: [] })-})-it("keeps actual empty Bots heading and CTA stable through native provider restore while HTTP waits", async () => {- const seed = await readCommunityDocumentSeed({} as Database, "viewer", "/c/me/bots", profile)- let restore!: (value: undefined) => void- mocks.restore.mockReturnValue(new Promise<undefined>(resolve => { restore = resolve }))- let release!: (value: unknown) => void- const live = new Promise(resolve => { release = resolve })- mocks.api.mockImplementation((url: string) => url.includes("view=observations") ? Promise.resolve({ quotas: [] }) : live)- let registry!: CommunityDbRegistry, restoring = true- function Probe() {- const owner = useOptionalCommunityDbRegistry()!- const phase = useIsRestoring()- React.useLayoutEffect(() => { registry = owner; restoring = phase }, [owner, phase])- return <BotList />- }- const view = render(<QueryProvider userId="viewer" initialSeed={seed}><CurrentUserProvider initialUser={{ ...profile, email: "[email protected]" }}><Probe /></CurrentUserProvider></QueryProvider>)- const sample = () => ({ heading: view.container.querySelector("h2")?.textContent, button: Array.from(view.container.querySelectorAll("button")).find(button => /machine|bot/i.test(button.textContent ?? ""))?.textContent })- try {- expect(restoring).toBe(true)- const before = sample()- expect(before).toEqual({ heading: "Connect a machine first", button: "Connect a machine" })- await act(async () => restore(undefined))- await waitFor(() => expect(restoring).toBe(false))- await waitFor(() => expect(mocks.api).toHaveBeenCalledWith("/api/community/machines?view=observations", expect.anything()))- expect(sample()).toEqual(before)- expect(view.container.textContent).not.toContain("Checking machines")- expect(mocks.api.mock.calls.filter(([url]) => String(url).includes("view=list"))).toHaveLength(0)- } finally {- restore(undefined); release({ machines: [] }); view.unmount()- await waitFor(() => expect(registry.collections.messages.status).toBe("cleaned-up"))- }-})-it.each(["bots", "machines"] as const)("retains the independent successful Bots-route resource when %s loader fails", async failed => {- const warn = vi.spyOn(console, "warn").mockImplementation(() => {})- mocks[failed].mockRejectedValue(new Error("bounded fixture failure"))- try {- const seed = await readCommunityDocumentSeed({} as Database, "viewer", "/c/me/bots", profile)- expect(mocks.bots).toHaveBeenCalledWith(expect.anything(), "viewer")- expect(mocks.machines).toHaveBeenCalledWith(expect.anything(), "viewer")- if (failed === "machines") { expect(seed.bots).toEqual(bots); expect(seed.machines).toBeUndefined() }- else { expect(seed.bots).toBeUndefined(); expect(seed.machines).toEqual({ machines: [] }) }- expect(seed.selfProfile).toEqual(profile)- expect(warn).toHaveBeenCalledWith("[community] document resource prefetch unavailable", { kind: "bots", phase: "read-module", channelId: null, generatedAt: seed.generatedAt })- } finally { warn.mockRestore() }-})diff --git a/src/web/src/app/c/QueryProvider.document.dom.test.tsx b/src/web/src/app/c/QueryProvider.document.dom.test.tsxdeleted file mode 100644index 9f4453d50..000000000--- a/src/web/src/app/c/QueryProvider.document.dom.test.tsx+++ /dev/null@@ -1,443 +0,0 @@-import "fake-indexeddb/auto"-import { createRequire } from "node:module"-import React, { Suspense } from "react"-import { renderToString } from "react-dom/server"-import { hydrateRoot } from "react-dom/client"-import { dehydrate, QueryClient, useIsRestoring } from "@tanstack/react-query"-import { beforeEach, describe, expect, it, vi } from "vitest"-import { act, render, screen, waitFor } from "@/test/react-dom-harness"-import { conversationEntryFixture, dmConversationEntryFixture } from "@/test/conversation-entry-fixtures"-import { useCanonicalCommunityProfile, useOptionalCommunityDbRegistry } from "@/lib/community-db/projections"-import { projectCommunityWsEventToDb } from "@/lib/community-db/sync"-import { communityKeys } from "@/lib/query-keys"-import { PERSIST_BUSTER, type QualifiedPersister } from "@/lib/query-persister"-import { useDmMessages, useMessages } from "@/hooks/community/use-messages"-import { useMachines } from "@/hooks/community/use-machines"-import { useServerMembers } from "@/hooks/community/use-server-members"-import type { CommunityDbRegistry } from "@/lib/community-db/collections"-import { useChannelMemberViewModel } from "@/components/community/members/channel-member-view-model"-import { useComposerController } from "@/components/community/messages/use-composer-controller"-import { CommunityMentionList } from "@/components/community/messages/composer-suggestion-popups"-import { EditorContent, type Editor } from "@tiptap/react"--const mocks = vi.hoisted(() => ({- viewer: "viewer" as string | null, restore: vi.fn(), api: vi.fn(), door: vi.fn(), entry: vi.fn(),- persistClient: vi.fn(async () => {}), removeClient: vi.fn(async () => {}),- isCurrent: vi.fn(async () => true), retireAccount: vi.fn(async () => {}), retireChannels: vi.fn(async () => {}),-}))-vi.mock("@/lib/auth-client", () => ({ useSession: () => ({ data: mocks.viewer ? { user: { id: mocks.viewer } } : null, isPending: false, error: null }), currentSessionViewer: () => mocks.viewer }))-vi.mock("next/navigation", () => ({ usePathname: () => "/c/channels/s1/c1", useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) }))-vi.mock("@tanstack/react-query-devtools", () => ({ ReactQueryDevtools: () => null }))-vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: (...args: unknown[]) => mocks.api(...args) }))-vi.mock("@/lib/query-persister", async original => ({ ...await original<typeof import("@/lib/query-persister")>(), createIdbPersister: () => ({ ...mocks, restoreClient: mocks.restore }) satisfies QualifiedPersister }))-vi.mock("@/lib/community/message-door", () => ({ resolveMessageTarget: mocks.door }))-vi.mock("@/lib/community/conversation-entry.server", () => ({ readCommunityConversationEntry: mocks.entry }))-import { readCommunityDocumentSeed } from "@/lib/community/document-seed.server"-import type { Database } from "@alook/shared"-import { QueryProvider } from "./QueryProvider"-import { installCommunityDocumentSeed, type CommunityDocumentSeed } from "@/lib/community/document-seed"-import { Message } from "@/components/community/messages/message"-import { Avatar } from "@/components/community/avatar"-import { CurrentUserProvider, useCurrentUser } from "@/contexts/community/current-user"-import { profileSchema } from "@/lib/community-db/schema"--const profile = { id: "viewer", name: "Server viewer", discriminator: "0042", avatar: "/avatar", avatarVersion: 7, aboutMe: "About", bannerColor: null, statusEmoji: null, statusText: "" }-const makeSeed = () => readCommunityDocumentSeed({} as Database, "viewer", "/c/channels/s1/c1", profile)-const { createFromReadableStream } = createRequire(import.meta.url)("next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.edge.production.js") as {- createFromReadableStream<T>(stream: ReadableStream<Uint8Array>, options: { serverConsumerManifest: { moduleMap: object; serverModuleMap: object; moduleLoading: null } }): Promise<T>-}-function flightSeed() {- let controller!: ReadableStreamDefaultController<Uint8Array>- const promise = createFromReadableStream<CommunityDocumentSeed | null>(new ReadableStream<Uint8Array>({ start(value) { controller = value } }), {- serverConsumerManifest: { moduleMap: {}, serverModuleMap: {}, moduleLoading: null },- })- return {- promise,- resolve(seed: CommunityDocumentSeed | null) { controller.enqueue(new TextEncoder().encode(`0:${JSON.stringify(seed)}\n`)); controller.close() },- reject(error: Error) { controller.error(error) },- }-}-let registry: CommunityDbRegistry-let restoring: boolean-function Probe() {- const owned = useOptionalCommunityDbRegistry()!- const phase = useIsRestoring()- React.useLayoutEffect(() => { registry = owned; restoring = phase }, [owned, phase])- const self = useCanonicalCommunityProfile("viewer")- const feed = useMessages("c1", { serverId: "s1", viewerUserId: "viewer" })- return <span data-testid="main">{`${self?.name}:${feed.isLoading ? "loading" : feed.messages.map(message => message.content).join("|")}`}</span>-}-beforeEach(() => {- localStorage.clear()- mocks.viewer = "viewer"- mocks.api.mockReset().mockRejectedValue(new Error("unexpected HTTP"))- mocks.restore.mockReset().mockResolvedValue(undefined)- mocks.door.mockReset().mockResolvedValue({ ok: true, value: { access: { channel: { serverId: "s1" } } } })- mocks.entry.mockReset().mockResolvedValue({ ok: true, entry: conversationEntryFixture() })-})--describe("initial document seed in the actual native account provider", () => {- it.each([- { kind: "optional failure", diskVersion: 5, winner: 6 },- { kind: "late seed", diskVersion: 5, winner: 6 },- { kind: "newer disk", diskVersion: 7, winner: 7 },- { kind: "early seed", diskVersion: 7, winner: 7 },- { kind: "newer WS", diskVersion: 5, winner: 8 },- ])("preserves the qualified avatar across restoration and $kind while business seed waits", async ({ kind, diskVersion, winner }) => {- const initial = { ...profile, avatar: "/avatar?v=6", avatarVersion: 6 }- const currentUser = { ...initial, email: "[email protected]" }- const seed = await readCommunityDocumentSeed({} as Database, "viewer", null, initial)- let releaseSeed!: (value: CommunityDocumentSeed | null) => void- const pending = new Promise<CommunityDocumentSeed | null>(resolve => { releaseSeed = resolve })- const disk = new QueryClient()- disk.setQueryData(communityKeys.communityDbCollection("viewer", "profiles"), [profileSchema.parse({ ...initial, identityComplete: true, avatar: `/avatar?v=${diskVersion}`, avatarVersion: diskVersion, aboutMe: "Cached about" })], { updatedAt: Date.now() - 10_000 })- let releaseRestore!: (value: unknown) => void- mocks.restore.mockReturnValue(new Promise(resolve => { releaseRestore = resolve }))- const capture = vi.fn<(registry: CommunityDbRegistry, restoring: boolean) => void>()- function Self() {- const self = useCurrentUser()- capture(useOptionalCommunityDbRegistry()!, useIsRestoring())- return <section><output data-testid="avatar-version">{self.avatarVersion}</output><span data-testid="profile-about">{self.aboutMe}</span><Avatar label={self.avatar} seed={self.id} /></section>- }- let view!: ReturnType<typeof render>- try {- await act(async () => { view = render(<QueryProvider userId="viewer" initialUser={currentUser} initialSeed={pending}><CurrentUserProvider initialUser={currentUser}><Self /></CurrentUserProvider></QueryProvider>) })- await waitFor(() => expect(screen.getByTestId("avatar-version")).toHaveTextContent("6"))- const output = screen.getByTestId("avatar-version")- const image = view.container.querySelector("img")- expect(image).toHaveAttribute("src", "/avatar?v=6")- if (kind === "early seed") await act(async () => { installCommunityDocumentSeed(capture.mock.lastCall![0].queryClient, capture.mock.lastCall![0], seed, "viewer") })- if (kind === "newer WS") await act(async () => { projectCommunityWsEventToDb(capture.mock.lastCall![0].queryClient, { type: "community:identity.update", userId: "viewer", avatar: "/avatar?v=8", avatarVersion: 8 }) })- await act(async () => { releaseRestore({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(disk) }) })- await waitFor(() => expect(capture.mock.lastCall![1]).toBe(false))- const canonical = () => capture.mock.lastCall![0].queryClient.getQueryData<Array<{ id: string; avatarVersion?: number; avatar?: string | null }>>(communityKeys.communityDbCollection("viewer", "profiles"))?.find(row => row.id === "viewer")- expect(canonical()).toMatchObject({ avatarVersion: winner, avatar: `/avatar?v=${winner}` })- expect(output).toHaveTextContent(String(winner))- expect(image).toHaveAttribute("src", `/avatar?v=${winner}`)- expect(screen.getByTestId("profile-about")).toHaveTextContent("Cached about")- await act(async () => { releaseSeed(kind === "optional failure" ? null : seed); await pending })- expect(canonical()).toMatchObject({ avatarVersion: winner, avatar: `/avatar?v=${winner}` })- expect(screen.getByTestId("avatar-version")).toBe(output)- expect(view.container.querySelector("img")).toBe(image)- expect(output).toHaveTextContent(String(winner))- expect(image).toHaveAttribute("src", `/avatar?v=${winner}`)- } finally {- releaseSeed(null)- await act(async () => { await pending; view?.unmount() })- disk.clear()- }- })-- it.each([false, true])("accepts the production Flight thenable when already fulfilled=%s", async (fulfilled) => {- const seed = await makeSeed()- mocks.api.mockImplementation(() => new Promise(() => {}))- const flight = flightSeed()- expect(flight.promise.then(vi.fn(), vi.fn())).toBeUndefined()- if (fulfilled) { flight.resolve(seed); await Promise.resolve(flight.promise) }- let view!: ReturnType<typeof render>- await act(async () => { view = render(<QueryProvider userId="viewer" initialSeed={flight.promise}><Probe /></QueryProvider>) })- try {- await waitFor(() => expect(restoring).toBe(false))- if (!fulfilled) {- expect(screen.getByTestId("main")).toHaveTextContent("loading")- await act(async () => { flight.resolve(seed); await Promise.resolve(flight.promise) })- }- await waitFor(() => expect(screen.getByTestId("main")).toHaveTextContent("Server viewer:Body"))- } finally { await act(async () => { view.unmount() }) }- })-- it.each([false, true])("handles a rejected Flight seed with cancelled=%s and keeps its cache consumer mounted", async (cancelled) => {- const flight = flightSeed()- const error = cancelled ? new DOMException("Flight seed cancelled", "AbortError") : new Error("Flight seed unavailable")- const logged = vi.spyOn(console, "error").mockImplementation(() => {})- let view!: ReturnType<typeof render>- await act(async () => { view = render(<QueryProvider userId="viewer" initialSeed={flight.promise}><Probe /></QueryProvider>) })- try {- await act(async () => { flight.reject(error); await Promise.resolve(flight.promise).catch(() => {}) })- if (cancelled) expect(logged).not.toHaveBeenCalled()- else await waitFor(() => expect(logged).toHaveBeenCalledWith("Community document seed installation failed", error))- expect(screen.getByTestId("main")).toBeInTheDocument()- } finally { await act(async () => { view.unmount() }); logged.mockRestore() }- })-- it.each(["resolve", "reject"] as const)("ignores a Flight %s after the account provider unmounts", async (settlement) => {- const seed = await makeSeed()- const flight = flightSeed()- const logged = vi.spyOn(console, "error").mockImplementation(() => {})- let view!: ReturnType<typeof render>- await act(async () => { view = render(<QueryProvider userId="viewer" initialSeed={flight.promise}><Probe /></QueryProvider>) })- await waitFor(() => expect(restoring).toBe(false))- const owned = registry- await act(async () => { view.unmount() })- const hydrate = vi.spyOn(owned.dbClient, "hydrate")- try {- await act(async () => {- if (settlement === "resolve") flight.resolve(seed)- else flight.reject(new Error("Retired Flight"))- await Promise.resolve(flight.promise).catch(() => {})- })- expect(hydrate).not.toHaveBeenCalled()- expect(logged).not.toHaveBeenCalled()- expect(owned.queryClient.getQueryData(communityKeys.selfProfile())).toBeUndefined()- } finally { logged.mockRestore() }- })-- it("catches an installation exception after a Flight seed resolves", async () => {- const seed = await makeSeed()- const flight = flightSeed()- const error = new Error("Profile installation failed")- const logged = vi.spyOn(console, "error").mockImplementation(() => {})- flight.promise.then((value) => { Object.defineProperty(value!, "selfProfile", { get() { throw error } }) })- let view!: ReturnType<typeof render>- await act(async () => { view = render(<QueryProvider userId="viewer" initialSeed={flight.promise}><Probe /></QueryProvider>) })- try {- await act(async () => { flight.resolve(seed); await Promise.resolve(flight.promise) })- await waitFor(() => expect(logged).toHaveBeenCalledWith("Community document seed installation failed", error))- expect(screen.getByTestId("main")).toBeInTheDocument()- } finally { await act(async () => { view.unmount() }); logged.mockRestore() }- })-- it("hydrates the native SSR snapshot and canonical author through fulfilled Flight input", async () => {- mocks.door.mockResolvedValue({ ok: true, value: { access: { channel: { serverId: null } } } })- mocks.entry.mockResolvedValue({ ok: true, entry: dmConversationEntryFixture() })- mocks.api.mockImplementation(() => new Promise(() => {}))- const seed = await readCommunityDocumentSeed({} as Database, "viewer", "/c/me/c1", profile)- const flight = flightSeed()- flight.resolve(seed)- await Promise.resolve(flight.promise)- const captureRegistry = vi.fn<(registry: CommunityDbRegistry) => void>()- function DmBody() {- captureRegistry(useOptionalCommunityDbRegistry()!)- const feed = useDmMessages("c1", { viewerUserId: "viewer" })- return <main>{feed.isLoading ? "Loading DM" : feed.messages.map(message => <Message key={message.id} m={{ ...message, grouped: false }} onOpenThread={() => {}} />)}</main>- }- const html = renderToString(<QueryProvider userId="viewer" initialSeed={seed}><Suspense fallback={null}><DmBody /></Suspense></QueryProvider>)- const serverOwner = captureRegistry.mock.lastCall![0]- await serverOwner.cleanup()- serverOwner.queryClient.clear()- const tree = <QueryProvider userId="viewer" initialSeed={flight.promise}><DmBody /></QueryProvider>- const container = document.createElement("div")- container.innerHTML = html- document.body.appendChild(container)- const row = container.querySelector("[data-message-author-line]")- expect(row).toHaveTextContent("Peer")- expect(container.textContent).not.toContain("Loading DM")- expect(container.textContent).not.toContain("Deleted user")- const recoveries: unknown[] = []- const logged = vi.spyOn(console, "error").mockImplementation(() => {})- let root!: ReturnType<typeof hydrateRoot>- try {- await act(async () => { root = hydrateRoot(container, tree, { onRecoverableError: error => { recoveries.push(error) } }) })- await waitFor(() => expect(container.querySelector("[data-message-author-line]")).toHaveTextContent("Peer"))- expect(container.textContent).not.toContain("Deleted user")- expect({ same: container.querySelector("[data-message-author-line]") === row, recoveries: recoveries.map(String), errors: logged.mock.calls }).toEqual({ same: true, recoveries: [], errors: [] })- } finally { await act(async () => { root?.unmount() }); container.remove(); logged.mockRestore() }- })-- it("mounts the consumer before deferred seed and fills its missing entry after restore", async () => {- const seed = await makeSeed()- mocks.api.mockImplementation(() => new Promise(() => {}))- let release!: (value: CommunityDocumentSeed) => void- const pending = new Promise<CommunityDocumentSeed>(resolve => { release = resolve })- let view!: ReturnType<typeof render>- await act(async () => { view = render(<QueryProvider userId="viewer" initialSeed={pending}><Probe /></QueryProvider>) })- await waitFor(() => expect(restoring).toBe(false))- expect(screen.getByTestId("main")).toHaveTextContent("loading")- const mounted = screen.getByTestId("main")- const hydrate = vi.spyOn(registry.dbClient, "hydrate")- await act(async () => { release(seed); await pending })- await waitFor(() => expect(screen.getByTestId("main")).toHaveTextContent("Server viewer:Body"))- expect(screen.getByTestId("main")).toBe(mounted)- expect(hydrate).not.toHaveBeenCalled()- view.unmount()- })-- it("keeps newer canonical content and an existing entry when deferred seed arrives", async () => {- const seed = await makeSeed()- mocks.api.mockImplementation(() => new Promise(() => {}))- let release!: (value: CommunityDocumentSeed) => void- const pending = new Promise<CommunityDocumentSeed>(resolve => { release = resolve })- let view!: ReturnType<typeof render>- await act(async () => { view = render(<QueryProvider userId="viewer" initialSeed={pending}><Probe /></QueryProvider>) })- await waitFor(() => expect(restoring).toBe(false))- await act(async () => { installCommunityDocumentSeed(registry.queryClient, registry, seed, "viewer") })- await waitFor(() => expect(screen.getByTestId("main")).toHaveTextContent("Body"))- const entry = registry.queryClient.getQueryCache().findAll({ queryKey: communityKeys.conversationEntries("c1") }).find(query => query.state.data)- const resource = entry?.state.data- const hydrate = vi.spyOn(registry.dbClient, "hydrate")- await act(async () => projectCommunityWsEventToDb(registry.queryClient, { type: "community:message.edited", serverId: "s1", channelId: "c1", messageId: "m1", content: "New WS content" }))- await act(async () => { release(seed); await pending })- await waitFor(() => expect(screen.getByTestId("main")).toHaveTextContent("New WS content"))- expect(entry?.state.data).toBe(resource)- expect(hydrate).not.toHaveBeenCalled()- view.unmount()- })-- it("does not re-grant revoked access from a deferred document", async () => {- const seed = await makeSeed()- mocks.api.mockImplementation(() => new Promise(() => {}))- let release!: (value: CommunityDocumentSeed) => void- const pending = new Promise<CommunityDocumentSeed>(resolve => { release = resolve })- let view!: ReturnType<typeof render>- await act(async () => { view = render(<QueryProvider userId="viewer" initialSeed={pending}><Probe /></QueryProvider>) })- await waitFor(() => expect(restoring).toBe(false))- await act(async () => { registry.runtime.ws.actions.revokeChannelAccess("s1", "c1") })- await act(async () => { release(seed); await pending })- expect(registry.runtime.ws.actions.isChannelAccessRevoked("c1", "s1")).toBe(true)- expect(screen.getByTestId("main")).not.toHaveTextContent("Body")- view.unmount()- })-- it("hydrates the persisted machine list into an already mounted native query while live list waits", async () => {- const actual = await vi.importActual<typeof import("@/lib/query-persister")>("@/lib/query-persister")- const disk = new QueryClient()- const machine = { id: "machine", hostname: "Restored host", displayName: "Computer", platform: "darwin", arch: "arm64", osRelease: "24", daemonVersion: "1", createdAt: "created", updatedAt: "updated", status: "online" }- disk.setQueryData(communityKeys.machines(), { machines: [machine] }, { updatedAt: 1000 })- const persister = actual.createIdbPersister("viewer-machine-roundtrip")- await persister.persistClient({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(disk) })- const stored = await persister.restoreClient()- expect(stored!.clientState.queries[0].state.data).toMatchObject({ machines: [{ hostname: "Restored host" }] })- mocks.restore.mockResolvedValue(stored)- let release!: (value: unknown) => void- const liveList = new Promise(resolve => { release = resolve })- mocks.api.mockImplementation((url: string) => url.endsWith("view=list") ? liveList : Promise.resolve({ quotas: [], machineCapacity: { ownedCount: 1, onlineCount: 0 } }))- let current!: ReturnType<typeof useMachines>- function Machines() {- const data = useMachines()- React.useLayoutEffect(() => { current = data }, [data])- return <span data-testid="machines">{data.machines.map(row => row.hostname).join("|")}</span>- }- const seed = await makeSeed()- const view = render(<QueryProvider userId="viewer" initialSeed={seed}><Machines /></QueryProvider>)- try {- await waitFor(() => expect(mocks.api).toHaveBeenCalledWith(expect.stringContaining("view=observations"), expect.anything()))- await waitFor(() => expect(screen.getByTestId("machines")).toHaveTextContent("Restored host"))- expect(current.data?.machines[0].status).toBeUndefined()- expect(current.data?.machineCapacity).toBeUndefined()- await act(async () => release({ machines: [{ ...machine, status: "offline" }] }))- await waitFor(() => expect(current.data?.machines[0].status).toBe("offline"))- } finally {- release({ machines: [] })- view.unmount()- await persister.removeClient()- disk.clear()- }- })-- it.each([true, false])("connects real member search and popup after RSC when the directory starts ready=%s", async (serverReady) => {- const seed = await makeSeed()- const person = { id: "member-peer", userId: "peer", name: "John Doe", discriminator: "0042", avatar: "J", avatarVersion: 0, role: "member", status: "offline", sub: "" }- mocks.api.mockImplementation(async (url: string) => {- if (url.startsWith("/api/community/servers/s1/members")) return { members: [person], hasMore: false, limit: 50, total: 1 }- if (url === "/api/community/servers") return { servers: [] }- throw new Error(`Unexpected resource ${url}`)- })- let editor: Editor | null = null- function MemberComposer({ serverReady }: { serverReady: boolean }) {- const members = useChannelMemberViewModel({ serverId: "s1", channelId: "c1", channelName: "Channel", currentServer: serverReady ? { categories: [{ channels: [{ id: "c1", type: "text" }] }] } : null, channelInServer: { creatorId: "viewer" }, currentChannelMeta: null, isChildChannel: false, isNotifyUnit: false, currentUser: { id: "viewer" } })- const view = useComposerController({ channel: "Channel", context: "channel", draftKey: "rsc-members", members: members.composerMembers, mentionCandidates: members.composerMentionCandidates, sendContract: "accepted", onAcceptSend: () => true, hideAttach: true, hideEmoji: true }, null)- React.useLayoutEffect(() => { editor = view.editor }, [view.editor])- return <><EditorContent editor={view.editor} /><CommunityMentionList state={view.mentionPopup} presentation={view.mentionPresentation} /></>- }- const rect = new DOMRect(10, 20, 1, 18)- Object.defineProperty(Range.prototype, "getBoundingClientRect", { configurable: true, value: () => rect })- Object.defineProperty(Range.prototype, "getClientRects", { configurable: true, value: () => [rect] })- const tree = (ready: boolean) => <QueryProvider userId="viewer" initialSeed={seed}><MemberComposer serverReady={ready} /></QueryProvider>- const view = render(tree(serverReady))- try {- await waitFor(() => expect(editor).not.toBeNull())- await act(async () => { editor!.view.dom.focus(); editor!.commands.insertContent("@") })- if (!serverReady) await act(async () => { view.rerender(tree(true)) })- await act(async () => { for (const char of "John") editor!.commands.insertContent(char) })- await waitFor(() => expect(mocks.api).toHaveBeenCalledWith(expect.stringContaining("/members/search?q=John"), expect.anything()))- await waitFor(() => expect(screen.getByTestId("community-mention-option-member-peer")).toBeVisible())- const originalEditor = editor- await act(async () => { view.rerender(tree(false)) })- await act(async () => { view.rerender(tree(true)) })- expect(editor).toBe(originalEditor)- expect(editor!.getText()).toBe("@John")- await waitFor(() => expect(screen.getByTestId("community-mention-option-member-peer")).toBeVisible())- } finally {- view.unmount()- delete (Range.prototype as Partial<Range>).getBoundingClientRect- delete (Range.prototype as Partial<Range>).getClientRects- }- })-- it("releases real member and profile projections after the document handoff and allows mention search", async () => {- const seed = await makeSeed()- const person = { id: "member-peer", userId: "peer", name: "John Doe", discriminator: "0042", avatar: "J", avatarVersion: 0, role: "member", status: "offline", sub: "" }- mocks.api.mockImplementation(async (url: string) => {- if (url.startsWith("/api/community/servers/s1/members")) return { members: [person], hasMore: false, limit: 50, total: 1 }- throw new Error(`Unexpected resource ${url}`)- })- let members!: ReturnType<typeof useServerMembers>- function Members() {- const owned = useOptionalCommunityDbRegistry()!- const result = useServerMembers("s1")- React.useLayoutEffect(() => { registry = owned; members = result }, [owned, result])- return <span data-testid="members">{result.loading ? "pending" : result.failed ? "failed" : result.members.map(member => member.name).join("|")}</span>- }- const view = render(<QueryProvider userId="viewer" initialSeed={seed}><Members /></QueryProvider>)- await waitFor(() => expect(screen.getByTestId("members")).toHaveTextContent("John Doe"))- await act(async () => members.searchMembers("John"))- await waitFor(() => expect(members).toMatchObject({ searchStatus: "ready", loading: false, failed: false }))- expect(mocks.api).toHaveBeenCalledWith(expect.stringContaining("/members/search?q=John"), expect.anything())- view.unmount()- })-- it("paints the real message hook before disk completes, then preserves fresh WS facts over old disk", async () => {- const seed = await makeSeed()- let release!: (value: unknown) => void- mocks.restore.mockReturnValue(new Promise(resolve => { release = resolve }))- const view = render(<QueryProvider userId="viewer" initialSeed={seed}><Probe /></QueryProvider>)- expect(screen.getByTestId("main")).toHaveTextContent("Server viewer:Body")- expect(restoring).toBe(true)- expect(mocks.api).not.toHaveBeenCalled()- await act(async () => projectCommunityWsEventToDb(registry.queryClient, { type: "community:message.edited", serverId: "s1", channelId: "c1", messageId: "m1", content: "WS body" }))- const disk = new QueryClient()- disk.setQueryData(communityKeys.communityDbCollection("viewer", "profiles"), [{ ...profile, name: "Old disk", identityComplete: true }], { updatedAt: 1 })- disk.setQueryData(communityKeys.communityDbCollection("viewer", "messages"), [{ ...conversationEntryFixture().messages[0], content: "Old disk body", resourceComplete: true }], { updatedAt: 1 })- await act(async () => release({ buster: PERSIST_BUSTER, timestamp: Date.now(), clientState: dehydrate(disk) }))- await waitFor(() => expect(restoring).toBe(false))- await waitFor(() => expect(screen.getByTestId("main")).toHaveTextContent("Server viewer:WS body"))- expect(registry.hasRestoredCollection("messages")).toBe(true)- expect(registry.hasRestoredCollection("channels")).toBe(false)- expect(mocks.api).not.toHaveBeenCalled()- view.unmount()- await waitFor(() => expect(registry.collections.messages.status).toBe("cleaned-up"))- disk.clear()- })-- it("ignores later refresh seeds before hydrate after the initial owner has advanced or revoked access", async () => {- const seed = await makeSeed()- const view = render(<QueryProvider userId="viewer" initialSeed={seed}><Probe /></QueryProvider>)- await waitFor(() => expect(restoring).toBe(false))- await act(async () => { await registry.preload() })- const hydrate = vi.spyOn(registry.dbClient, "hydrate")- await act(async () => projectCommunityWsEventToDb(registry.queryClient, { type: "community:message.edited", serverId: "s1", channelId: "c1", messageId: "m1", content: "Current WS" }))- await waitFor(() => expect(screen.getByTestId("main")).toHaveTextContent("Current WS"))- view.rerender(<QueryProvider userId="viewer" initialSeed={JSON.parse(JSON.stringify(seed))}><Probe /></QueryProvider>)- expect(hydrate).not.toHaveBeenCalled()- expect(screen.getByTestId("main")).toHaveTextContent("Current WS")- await act(async () => { registry.runtime.ws.actions.revokeChannelAccess("s1", "c1") })- view.rerender(<QueryProvider userId="viewer" initialSeed={seed}><Probe /></QueryProvider>)- expect(hydrate).not.toHaveBeenCalled()- expect(registry.runtime.ws.actions.isChannelAccessRevoked("c1", "s1")).toBe(true)- expect(screen.getByTestId("main")).not.toHaveTextContent("Current WS")- view.unmount()- })-- it.each([false, true])("rejects another viewer's document before native DB hydrate with Flight=%s", async (deferred) => {- const seed = await makeSeed()- const flight = flightSeed()- mocks.viewer = "other"- function AccountProbe() { const owned = useOptionalCommunityDbRegistry()!; React.useLayoutEffect(() => { registry = owned }, [owned]); return null }- const view = render(<QueryProvider userId="other" initialSeed={deferred ? flight.promise : seed}><AccountProbe /></QueryProvider>)- await act(async () => { flight.resolve(seed); await Promise.resolve(flight.promise) })- expect(registry.queryClient.getQueryData(communityKeys.selfProfile())).toBeUndefined()- expect(registry.queryClient.getQueryCache().findAll({ queryKey: communityKeys.conversationEntries("c1") })).toEqual([])- expect(registry.collections.profiles.get("viewer")).toBeUndefined()- view.unmount()- })-})diff --git a/src/web/src/app/c/QueryProvider.late-block-restore.dom.test.tsx b/src/web/src/app/c/QueryProvider.late-block-restore.dom.test.tsxindex f954926b6..757f9c055 100644--- a/src/web/src/app/c/QueryProvider.late-block-restore.dom.test.tsx+++ b/src/web/src/app/c/QueryProvider.late-block-restore.dom.test.tsx@@ -11,9 +11,6 @@ import { CommunityRestoreBoundary } from "@/components/community/shell/communityimport { useOptionalCommunityDbRegistry } from "@/lib/community-db/projections"import { dispatchCommunityWsEvents } from "@/hooks/community/community-ws/registry"import { writeCommunityCollectionRows } from "@/lib/community-db/write"-import { installCommunityDocumentSeed, type CommunityDocumentSeed } from "@/lib/community/document-seed"-import { communityCollectionQuery, communityJoinedMessagesQuery } from "@/lib/community-db/queries"-import { preloadCommunityProjection, dehydrateCommunityProjections } from "@/lib/community-db/live-query"import { useDmMessages } from "@/hooks/community/use-messages"import { communityKeys } from "@/lib/query-keys"vi.mock("@/lib/auth-client", () => ({ useSession: () => ({ data: { user: { id: "viewer" } }, isPending: false, error: null }), currentSessionViewer: () => "viewer" }))@@ -31,16 +28,9 @@ it.each([null, false, true].flatMap(blockMode => (["accepted", "incoming"] as coconst disk = createIdbPersister("viewer")await disk.persistClient({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(old.client) })const fresh = dmConversationEntryFixture()- fresh.messages = [{ ...fresh.messages[0], id: "m2", seq: 2, content: "Fresh RSC" }]+ fresh.messages = [{ ...fresh.messages[0], id: "m2", seq: 2, content: "Fresh authorized entry" }]fresh.readState = { ...fresh.readState, lastReadMessageId: "m2", lastReadSeq: 2 }fresh.selection = { reason: "read_pointer", anchorMessageId: "m2" }- const selfProfile = { id: "viewer", name: "Viewer", discriminator: "0001", avatar: "V", avatarVersion: 0, aboutMe: "", bannerColor: null, statusEmoji: "", statusText: "" }- const source = await createCommunityQueryOwner()- const seed: CommunityDocumentSeed = { viewerId: "viewer", href: "/c/me/c1", generatedAt: Date.now(), selfProfile, entries: [{ target: { channelId: "c1", serverId: null }, data: fresh }], db: { collections: [] } }- installCommunityDocumentSeed(source.client, source.registry, seed, "viewer")- const descriptors = [communityCollectionQuery(source.registry, "profiles"), communityCollectionQuery(source.registry, "channels"), communityCollectionQuery(source.registry, "channelMemberships"), communityCollectionQuery(source.registry, "readStates"), communityJoinedMessagesQuery(source.registry, "c1", ["m2"])]- const bindings = await Promise.all(descriptors.map(d => preloadCommunityProjection(source.registry, d)))- seed.db = { ...dehydrateCommunityProjections(source.registry, bindings), collections: [] }const original = IDBObjectStore.prototype.getlet reads = 0, held = 0let release: (() => void) | undefined@@ -63,10 +53,11 @@ it.each([null, false, true].flatMap(blockMode => (["accepted", "incoming"] as colet restoring = truelet ids: string[] = []function Probe() { registry = useOptionalCommunityDbRegistry(); restoring = useIsRestoring(); const body = useDmMessages("c1"); ids = body.messages.map(m => m.id); return null }- const view = render(<QueryProvider userId="viewer" initialSeed={JSON.parse(JSON.stringify(seed))}><CommunityRestoreBoundary><Probe /></CommunityRestoreBoundary></QueryProvider>)+ const view = render(<QueryProvider userId="viewer"><CommunityRestoreBoundary><Probe /></CommunityRestoreBoundary></QueryProvider>)try {await waitFor(() => expect(held).toBe(1))expect(restoring).toBe(true)+ await act(async () => { await seedConversationEntry(registry!.queryClient, fresh) })expect(ids).toContain("m2")if (blocked) act(() => dispatchCommunityWsEvents([{ type: "community:friend.block", userId: "peer", ...(blockMode ? { blockedByViewer: true } : {}) }], {deliveryMode: "batch", contract: 2, queryClient: registry!.queryClient, communityStore: registry!.runtime.ui, wsStore: registry!.runtime.ws,@@ -87,6 +78,6 @@ it.each([null, false, true].flatMap(blockMode => (["accepted", "incoming"] as counrelatedAttention: registry!.collections.attentionItems.has("friend_request:other"),}).toEqual({ peerFriend: !blocked, peerAttention: !blocked && kind === "incoming", currentBlock: blockMode === true, unrelatedFriend: true, unrelatedAttention: true })} finally {- release?.();view.unmount();vi.restoreAllMocks();old.client.clear();source.client.clear()+ release?.();view.unmount();vi.restoreAllMocks();old.client.clear()}})diff --git a/src/web/src/app/c/QueryProvider.native-entry.dom.test.tsx b/src/web/src/app/c/QueryProvider.native-entry.dom.test.tsxnew file mode 100644index 000000000..457bb4cf1--- /dev/null+++ b/src/web/src/app/c/QueryProvider.native-entry.dom.test.tsx@@ -0,0 +1,159 @@+import "fake-indexeddb/auto"+import React from "react"+import { dehydrate, QueryClient, useIsRestoring } from "@tanstack/react-query"+import { beforeEach, describe, expect, it, vi } from "vitest"+import { act, render, screen, waitFor } from "@/test/react-dom-harness"+import { useOptionalCommunityDbRegistry } from "@/lib/community-db/projections"+import { projectCommunityWsEventToDb } from "@/lib/community-db/sync"+import { CurrentUserProvider, useCurrentUser } from "@/contexts/community/current-user"+import { Avatar } from "@/components/community/avatar"+import { profileSchema } from "@/lib/community-db/schema"+import { communityKeys } from "@/lib/query-keys"+import { PERSIST_BUSTER, type QualifiedPersister } from "@/lib/query-persister"+import { useMachines } from "@/hooks/community/use-machines"+import { useServerMembers } from "@/hooks/community/use-server-members"+import type { CommunityDbRegistry } from "@/lib/community-db/collections"+import { useChannelMemberViewModel } from "@/components/community/members/channel-member-view-model"+import { useComposerController } from "@/components/community/messages/use-composer-controller"+import { CommunityMentionList } from "@/components/community/messages/composer-suggestion-popups"+import { EditorContent, type Editor } from "@tiptap/react"+const mocks = vi.hoisted(() => ({ restore: vi.fn(), api: vi.fn(),+ persistClient: vi.fn(async () => {}), removeClient: vi.fn(async () => {}), isCurrent: vi.fn(async () => true), retireAccount: vi.fn(async () => {}), retireChannels: vi.fn(async () => {}),+}))+vi.mock("@/lib/auth-client", () => ({ useSession: () => ({ data: { user: { id: "viewer" } }, isPending: false, error: null }), currentSessionViewer: () => "viewer" }))+vi.mock("next/navigation", () => ({ usePathname: () => "/c/channels/s1/c1", useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) }))+vi.mock("@tanstack/react-query-devtools", () => ({ ReactQueryDevtools: () => null }))+vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: (...args: unknown[]) => mocks.api(...args) }))+vi.mock("@/lib/query-persister", async original => ({ ...await original<typeof import("@/lib/query-persister")>(), createIdbPersister: () => ({ ...mocks, restoreClient: mocks.restore }) satisfies QualifiedPersister }))+import { QueryProvider } from "./QueryProvider"+let registry: CommunityDbRegistry+beforeEach(() => { localStorage.clear(); mocks.api.mockReset().mockRejectedValue(new Error("unexpected HTTP")); mocks.restore.mockReset().mockResolvedValue(undefined) })+describe("native client-entry consumers", () => {+ it.each([+ { diskVersion: 5, liveVersion: null, winner: 6 },+ { diskVersion: 7, liveVersion: null, winner: 7 },+ { diskVersion: 5, liveVersion: 8, winner: 8 },+ ])("preserves qualified avatar v$winner through disk restoration and live updates", async ({ diskVersion, liveVersion, winner }) => {+ const initial = { id: "viewer", name: "Session viewer", email: "[email protected]", discriminator: "0042", avatar: "/avatar?v=6", avatarVersion: 6 }+ const disk = new QueryClient()+ disk.setQueryData(communityKeys.communityDbCollection("viewer", "profiles"), [profileSchema.parse({ ...initial, identityComplete: true, avatar: `/avatar?v=${diskVersion}`, avatarVersion: diskVersion, aboutMe: "Cached about" })], { updatedAt: Date.now() - 10_000 })+ let release!: (value: unknown) => void+ mocks.restore.mockReturnValue(new Promise(resolve => { release = resolve }))+ let restoring = true+ function Self() {+ const self = useCurrentUser()+ const owned = useOptionalCommunityDbRegistry()!+ const pending = useIsRestoring()+ React.useLayoutEffect(() => { registry = owned; restoring = pending }, [owned, pending])+ return <section><output data-testid="avatar-version">{self.avatarVersion}</output><span data-testid="profile-about">{self.aboutMe}</span><Avatar label={self.avatar} seed={self.id} /></section>+ }+ const view = render(<QueryProvider userId="viewer" initialUser={initial}><CurrentUserProvider initialUser={initial}><Self /></CurrentUserProvider></QueryProvider>)+ try {+ await waitFor(() => expect(screen.getByTestId("avatar-version")).toHaveTextContent("6"))+ const image = view.container.querySelector("img")+ expect(image).toHaveAttribute("src", "/avatar?v=6")+ if (liveVersion) await act(async () => projectCommunityWsEventToDb(registry.queryClient, { type: "community:identity.update", userId: "viewer", avatar: `/avatar?v=${liveVersion}`, avatarVersion: liveVersion }))+ await act(async () => release({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(disk) }))+ await waitFor(() => expect(restoring).toBe(false))+ await waitFor(() => expect(screen.getByTestId("avatar-version")).toHaveTextContent(String(winner)))+ expect(view.container.querySelector("img")).toBe(image)+ expect(image).toHaveAttribute("src", `/avatar?v=${winner}`)+ expect(screen.getByTestId("profile-about")).toHaveTextContent("Cached about")+ } finally { release(undefined); view.unmount(); disk.clear() }+ })+ it("hydrates the persisted machine list into an already mounted native query while live list waits", async () => {+ const actual = await vi.importActual<typeof import("@/lib/query-persister")>("@/lib/query-persister")+ const disk = new QueryClient()+ const machine = { id: "machine", hostname: "Restored host", displayName: "Computer", platform: "darwin", arch: "arm64", osRelease: "24", daemonVersion: "1", createdAt: "created", updatedAt: "updated", status: "online" }+ disk.setQueryData(communityKeys.machines(), { machines: [machine] }, { updatedAt: 1000 })+ const persister = actual.createIdbPersister("viewer-machine-roundtrip")+ await persister.persistClient({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(disk) })+ const stored = await persister.restoreClient()+ expect(stored!.clientState.queries[0].state.data).toMatchObject({ machines: [{ hostname: "Restored host" }] })+ mocks.restore.mockResolvedValue(stored)+ let release!: (value: unknown) => void+ const liveList = new Promise(resolve => { release = resolve })+ mocks.api.mockImplementation((url: string) => url.endsWith("view=list") ? liveList : Promise.resolve({ quotas: [], machineCapacity: { ownedCount: 1, onlineCount: 0 } }))+ let current!: ReturnType<typeof useMachines>+ function Machines() {+ const data = useMachines()+ React.useLayoutEffect(() => { current = data }, [data])+ return <span data-testid="machines">{data.machines.map(row => row.hostname).join("|")}</span>+ }+ const view = render(<QueryProvider userId="viewer"><Machines /></QueryProvider>)+ try {+ await waitFor(() => expect(mocks.api).toHaveBeenCalledWith(expect.stringContaining("view=observations"), expect.anything()))+ await waitFor(() => expect(screen.getByTestId("machines")).toHaveTextContent("Restored host"))+ expect(current.data?.machines[0].status).toBeUndefined()+ expect(current.data?.machineCapacity).toBeUndefined()+ await act(async () => release({ machines: [{ ...machine, status: "offline" }] }))+ await waitFor(() => expect(current.data?.machines[0].status).toBe("offline"))+ } finally {+ release({ machines: [] })+ view.unmount()+ await persister.removeClient()+ disk.clear()+ }+ })++ it.each([true, false])("connects real member search and popup after client entry when the directory starts ready=%s", async (serverReady) => {+ const person = { id: "member-peer", userId: "peer", name: "John Doe", discriminator: "0042", avatar: "J", avatarVersion: 0, role: "member", status: "offline", sub: "" }+ mocks.api.mockImplementation(async (url: string) => {+ if (url.startsWith("/api/community/servers/s1/members")) return { members: [person], hasMore: false, limit: 50, total: 1 }+ if (url === "/api/community/servers") return { servers: [] }+ throw new Error(`Unexpected resource ${url}`)+ })+ let editor: Editor | null = null+ function MemberComposer({ serverReady }: { serverReady: boolean }) {+ const members = useChannelMemberViewModel({ serverId: "s1", channelId: "c1", channelName: "Channel", currentServer: serverReady ? { categories: [{ channels: [{ id: "c1", type: "text" }] }] } : null, channelInServer: { creatorId: "viewer" }, currentChannelMeta: null, isChildChannel: false, isNotifyUnit: false, currentUser: { id: "viewer" } })+ const view = useComposerController({ channel: "Channel", context: "channel", draftKey: "rsc-members", members: members.composerMembers, mentionCandidates: members.composerMentionCandidates, sendContract: "accepted", onAcceptSend: () => true, hideAttach: true, hideEmoji: true }, null)+ React.useLayoutEffect(() => { editor = view.editor }, [view.editor])+ return <><EditorContent editor={view.editor} /><CommunityMentionList state={view.mentionPopup} presentation={view.mentionPresentation} /></>+ }+ const rect = new DOMRect(10, 20, 1, 18)+ Object.defineProperty(Range.prototype, "getBoundingClientRect", { configurable: true, value: () => rect })+ Object.defineProperty(Range.prototype, "getClientRects", { configurable: true, value: () => [rect] })+ const tree = (ready: boolean) => <QueryProvider userId="viewer"><MemberComposer serverReady={ready} /></QueryProvider>+ const view = render(tree(serverReady))+ try {+ await waitFor(() => expect(editor).not.toBeNull())+ await act(async () => { editor!.view.dom.focus(); editor!.commands.insertContent("@") })+ if (!serverReady) await act(async () => { view.rerender(tree(true)) })+ await act(async () => { for (const char of "John") editor!.commands.insertContent(char) })+ await waitFor(() => expect(mocks.api).toHaveBeenCalledWith(expect.stringContaining("/members/search?q=John"), expect.anything()))+ await waitFor(() => expect(screen.getByTestId("community-mention-option-member-peer")).toBeVisible())+ const originalEditor = editor+ await act(async () => { view.rerender(tree(false)) })+ await act(async () => { view.rerender(tree(true)) })+ expect(editor).toBe(originalEditor)+ expect(editor!.getText()).toBe("@John")+ await waitFor(() => expect(screen.getByTestId("community-mention-option-member-peer")).toBeVisible())+ } finally {+ view.unmount()+ delete (Range.prototype as Partial<Range>).getBoundingClientRect+ delete (Range.prototype as Partial<Range>).getClientRects+ }+ })++ it("releases real member and profile projections after native restore and allows mention search", async () => {+ const person = { id: "member-peer", userId: "peer", name: "John Doe", discriminator: "0042", avatar: "J", avatarVersion: 0, role: "member", status: "offline", sub: "" }+ mocks.api.mockImplementation(async (url: string) => {+ if (url.startsWith("/api/community/servers/s1/members")) return { members: [person], hasMore: false, limit: 50, total: 1 }+ throw new Error(`Unexpected resource ${url}`)+ })+ let members!: ReturnType<typeof useServerMembers>+ function Members() {+ const owned = useOptionalCommunityDbRegistry()!+ const result = useServerMembers("s1")+ React.useLayoutEffect(() => { registry = owned; members = result }, [owned, result])+ return <span data-testid="members">{result.loading ? "pending" : result.failed ? "failed" : result.members.map(member => member.name).join("|")}</span>+ }+ const view = render(<QueryProvider userId="viewer"><Members /></QueryProvider>)+ await waitFor(() => expect(screen.getByTestId("members")).toHaveTextContent("John Doe"))+ await act(async () => members.searchMembers("John"))+ await waitFor(() => expect(members).toMatchObject({ searchStatus: "ready", loading: false, failed: false }))+ expect(mocks.api).toHaveBeenCalledWith(expect.stringContaining("/members/search?q=John"), expect.anything())+ view.unmount()+ })++})diff --git a/src/web/src/app/c/QueryProvider.tsx b/src/web/src/app/c/QueryProvider.tsxindex c33e4b646..f3d09f9af 100644--- a/src/web/src/app/c/QueryProvider.tsx+++ b/src/web/src/app/c/QueryProvider.tsx@@ -1,6 +1,6 @@"use client"-import { Suspense, use, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"import { useIsRestoring, type QueryClient } from "@tanstack/react-query"import { ReactQueryDevtools } from "@tanstack/react-query-devtools"import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client"@@ -30,64 +30,17 @@ import {type CommunityDbRegistry,} from "@/lib/community-db/collections"import { useSelector } from "@tanstack/react-store"-import { HydrationBoundary } from "@tanstack/react-db"-import { useHydratedClient } from "@/components/community/shell/use-hydrated-client"import { useSession, currentSessionViewer } from "@/lib/auth-client"import { useRouter } from "next/navigation"import { usePersistedAccountLifecycle } from "@/lib/use-persisted-account-lifecycle"import { retireCommunityAccount } from "@/lib/community/account-cache-lifecycle"import { CommunityDbProvider } from "@/lib/community-db/projections"-import { captureCommunityLiveSnapshotToken, discardCommunityRestoreReplacements, installCommunityDbSync, restoreCommunityCollections } from "@/lib/community-db/sync"+import { discardCommunityRestoreReplacements, installCommunityDbSync, restoreCommunityCollections } from "@/lib/community-db/sync"import { profileSchema } from "@/lib/community-db/schema"import { avatarInitial } from "@/lib/community/avatar"import type { CurrentUser } from "@/contexts/community/current-user"import { observeHydration, discardHydration } from "@/lib/observability/restore"import { captureTelemetryIdentityRetirement, setTelemetryUser } from "@/lib/observability/client"-import { installCommunityDocumentSeed, type CommunityDocumentSeed, type CommunityDocumentSeedInput } from "@/lib/community/document-seed"--type DeferredDocumentSeed = {- promise: Promise<CommunityDocumentSeed | null>- rendering: Promise<CommunityDocumentSeed | null>- settled: boolean- installed: boolean | undefined- token: ReturnType<typeof captureCommunityLiveSnapshotToken>- presence: ReturnType<CommunityDbRegistry["runtime"]["ws"]["actions"]["beginPresenceSnapshot"]>-}--function receiveDocumentSeed(seed: CommunityDocumentSeed | null, delivery: DeferredDocumentSeed, client: QueryClient, registry: CommunityDbRegistry) {- if (!seed || !registry.runtime.lifecycle.get().active) return false- if (delivery.installed !== undefined) return delivery.installed- delivery.installed = false- try {- delivery.installed = installCommunityDocumentSeed(client, registry, seed, registry.sessionViewer(), typeof window === "undefined" ? undefined : delivery)- return delivery.installed- } catch (error) {- if (!isAbortError(error)) console.error("Community document seed installation failed", error)- return false- }-}--function SeededDocument({ delivery, client, registry, children }: { delivery: DeferredDocumentSeed; client: QueryClient; registry: CommunityDbRegistry; children: ReactNode }) {- const seed = use(delivery.rendering)- const hydrated = useHydratedClient()- const [snapshot] = useState(() => {- const installed = !hydrated && receiveDocumentSeed(seed, delivery, client, registry)- return installed && seed ? seed.db : { collections: [] }- })- return <HydrationBoundary state={snapshot}>{children}</HydrationBoundary>-}--function DocumentSeedContent({ delivery, client, registry, children }: { delivery: DeferredDocumentSeed; client: QueryClient; registry: CommunityDbRegistry; children: ReactNode }) {- const restoring = useIsRestoring()- const hydrated = useHydratedClient()- const [clientDocument, setClientDocument] = useState(hydrated)- useLayoutEffect(() => {- if (!restoring && !delivery.settled) setClientDocument(true)- }, [delivery, restoring])- return clientDocument ? children : <Suspense fallback={children}>- <SeededDocument delivery={delivery} client={client} registry={registry}>{children}</SeededDocument>- </Suspense>-}function createRestoreGate() {let release!: () => void@@ -154,7 +107,7 @@ function CommunityDbRuntime({* the previous session's cached message list. Passing `null` (pre-auth) hits* an "anon" namespace that never carries real content.*/-export function QueryProvider(props: { children: ReactNode; userId: string | null; initialUser?: CurrentUser; initialSeed?: CommunityDocumentSeedInput }) {+export function QueryProvider(props: { children: ReactNode; userId: string | null; initialUser?: CurrentUser }) {const session = useSession()return <ScopedQueryProvider key={props.userId ?? "anon"} {...props} session={session} sessionViewer={currentSessionViewer} />}@@ -163,14 +116,12 @@ function ScopedQueryProvider({children,userId,initialUser,- initialSeed,session,sessionViewer,}: {children: ReactNodeuserId: string | nullinitialUser?: CurrentUser- initialSeed?: CommunityDocumentSeedInputsession: ReturnType<typeof useSession>sessionViewer: () => string | null | undefined}) {@@ -188,32 +139,7 @@ function ScopedQueryProvider({return client})const [restoreGate] = useState(createRestoreGate)- const [communityDb] = useState(() => {- const registry = createCommunityDbRegistry(queryClient, userId, { waitForRestore: restoreGate.ready })- const viewer = !session.isPending && !session.error ? session.data?.user.id ?? null : sessionViewer()- if (initialSeed && !("then" in initialSeed)) installCommunityDocumentSeed(queryClient, registry, initialSeed, viewer)- return registry- })- const [deferredSeed] = useState<DeferredDocumentSeed | null>(() => {- if (!initialSeed || !("then" in initialSeed)) return null- const promise = Promise.resolve(initialSeed)- const delivery: DeferredDocumentSeed = {- promise, rendering: initialSeed,- settled: false, installed: undefined, token: captureCommunityLiveSnapshotToken(queryClient), presence: communityDb.runtime.ws.actions.beginPresenceSnapshot(),- }- void promise.then(() => { delivery.settled = true }, () => { delivery.settled = true })- return delivery- })- useEffect(() => {- if (!deferredSeed) return- let current = true- void Promise.resolve(deferredSeed.promise).then((seed) => {- if (current) receiveDocumentSeed(seed, deferredSeed, queryClient, communityDb)- }).catch((error: unknown) => {- if (current && !isAbortError(error)) console.error("Community document seed installation failed", error)- })- return () => { current = false }- }, [deferredSeed, queryClient, communityDb])+ const [communityDb] = useState(() => createCommunityDbRegistry(queryClient, userId, { waitForRestore: restoreGate.ready }))const unreadProjection = useMemo(() => userId ? getAccountUnreadProjection(queryClient, userId) : null,[queryClient, userId],@@ -269,8 +195,7 @@ function ScopedQueryProvider({restoreGate.release()retireCommunityAccount(communityDb)void communityDb.retireDisk().catch(() => undefined)- if (session.data?.user.id) router.refresh()- else router.replace("/sign-in")+ if (!session.data?.user.id) router.replace("/sign-in")}, [communityDb, identityChanged, restoreGate, router, session.data?.user.id, sessionViewer, userId])const onRetired = useCallback(() => {if (!communityDb.runtime.lifecycle.get().active) return@@ -320,7 +245,7 @@ function ScopedQueryProvider({queryClient={queryClient}registry={communityDb}>- {deferredSeed ? <DocumentSeedContent delivery={deferredSeed} client={queryClient} registry={communityDb}>{children}</DocumentSeedContent> : children}+ {children}{isDev ? <ReactQueryDevtools initialIsOpen={false} /> : null}</CommunityDbRuntime> : null}</PersistQueryClientProvider>diff --git a/src/web/src/app/c/[...path]/page.tsx b/src/web/src/app/c/[...path]/page.tsxnew file mode 100644index 000000000..fc18975e2--- /dev/null+++ b/src/web/src/app/c/[...path]/page.tsx@@ -0,0 +1,8 @@+import { notFound } from "next/navigation"+import { isCommunityApplicationPath } from "@/lib/community/application-route"++export default async function CommunityRoute({ params }: { params: Promise<{ path: string[] }> }) {+ const { path } = await params+ if (!isCommunityApplicationPath(`/c/${path.map(encodeURIComponent).join("/")}`)) notFound()+ return null+}diff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsxdeleted file mode 100644index a43f3f40c..000000000--- a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-export default function ChannelPage() {- return null-}diff --git a/src/web/src/app/c/channels/[serverId]/loading.tsx b/src/web/src/app/c/channels/[serverId]/loading.tsxdeleted file mode 100644index ea87b3bf4..000000000--- a/src/web/src/app/c/channels/[serverId]/loading.tsx+++ /dev/null@@ -1,5 +0,0 @@-import { ChannelLoadingFrame } from "@/components/community/channels/channel-loading-frame"--export default function ServerRouteLoading() {- return <ChannelLoadingFrame />-}diff --git a/src/web/src/app/c/channels/[serverId]/page.dom.test.ts b/src/web/src/app/c/channels/[serverId]/page.dom.test.tsindex 5875fb839..db76ee855 100644--- a/src/web/src/app/c/channels/[serverId]/page.dom.test.ts+++ b/src/web/src/app/c/channels/[serverId]/page.dom.test.ts@@ -1,7 +1,7 @@import { createElement } from "react"import { beforeEach, describe, expect, it, vi } from "vitest"import { render, screen } from "@/test/react-dom-harness"-import ServerDefaultPage from "./page"+import ServerDefaultPage from "@/components/community/shell/server-landing-route"import { tid } from "@/lib/community/testids"import { CommunityServerRouteContext } from "@/components/community/shell/community-route-context"diff --git a/src/web/src/app/c/channels/[serverId]/page.tsx b/src/web/src/app/c/channels/[serverId]/page.tsxdeleted file mode 100644index eb67a69b0..000000000--- a/src/web/src/app/c/channels/[serverId]/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-"use client"--export { default } from "@/components/community/shell/server-landing-route"diff --git a/src/web/src/app/c/channels/[serverId]/settings/page.tsx b/src/web/src/app/c/channels/[serverId]/settings/page.tsxdeleted file mode 100644index c87b55a8a..000000000--- a/src/web/src/app/c/channels/[serverId]/settings/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-"use client"--export { default } from "@/components/community/shell/server-settings-route"diff --git a/src/web/src/app/c/channels/layout.route-memory.dom.test.ts b/src/web/src/app/c/channels/layout.route-memory.dom.test.tsindex 8caeb55bb..a3e0f6955 100644--- a/src/web/src/app/c/channels/layout.route-memory.dom.test.ts+++ b/src/web/src/app/c/channels/layout.route-memory.dom.test.ts@@ -246,7 +246,7 @@ vi.mock("@/hooks/community/mutations", async () => {}})-import ServerContent from "./layout"+import { CommunityServerModuleHost as ServerContent } from "@/test/community-module-host"import { ServerSidebarSlot } from "@/components/community/shell/server-sidebar-slot"import { CommunityRouteContext } from "@/components/community/shell/community-route-context"import { normalizeCommunityHref } from "@/lib/community/community-route"diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsxdeleted file mode 100644index 1480b9a04..000000000--- a/src/web/src/app/c/channels/layout.tsx+++ /dev/null@@ -1,33 +0,0 @@-"use client"--import type { ReactNode } from "react"-import { useSelectedLayoutSegments, usePathname, useSearchParams } from "next/navigation"-import { CommunityServerRouteContext, useCommunityRouteFrame } from "@/components/community/shell/community-route-context"-import { ServerConversationRoute } from "@/components/community/channels/server-conversation-route"-import { normalizeCommunityHref, resolveCommunityModulePlan } from "@/lib/community/community-route"--export default function ServerLayout({ children }: { children: ReactNode }) {- const segments = useSelectedLayoutSegments()- const serverParam = segments[0]- const pathname = usePathname()- const searchParams = useSearchParams()- const { navigation } = useCommunityRouteFrame()- const serverId = serverParam ? decodeURIComponent(serverParam) : ""- const publishedHref = normalizeCommunityHref(`${pathname}${searchParams.size ? `?${searchParams}` : ""}`)- const framePathname = segments.length ? `/c/channels/${segments.join("/")}` : "/c/channels"- const frameHref = normalizeCommunityHref(`${framePathname}${publishedHref.pathname === framePathname && publishedHref.search ? `?${publishedHref.search}` : ""}`)- const pendingPlan = navigation.navigationPending && navigation.pendingHref- ? resolveCommunityModulePlan(navigation.pendingHref) : null- const targetHref = pendingPlan?.main.kind === "server-conversation"- && pendingPlan.main.serverId === serverId- ? normalizeCommunityHref(navigation.pendingHref!) : frameHref- const modulePlan = resolveCommunityModulePlan(targetHref.href)- const routeChannelId = modulePlan.main.kind === "server-conversation" && modulePlan.main.serverId === serverId- ? modulePlan.main.leafId : null- return <CommunityServerRouteContext value={{ serverId, serverParam: serverParam ?? "" }}>- <ServerConversationRoute serverId={serverId} serverParam={serverParam ?? ""}- channelId={routeChannelId} href={targetHref.href} routeCommitted={publishedHref.href === targetHref.href}>- {children}- </ServerConversationRoute>- </CommunityServerRouteContext>-}diff --git a/src/web/src/app/c/community-layout-client.tsx b/src/web/src/app/c/community-layout-client.tsxindex a8c45de68..570e83a81 100644--- a/src/web/src/app/c/community-layout-client.tsx+++ b/src/web/src/app/c/community-layout-client.tsx@@ -1,7 +1,9 @@"use client"-import { useEffect, type ReactNode } from "react"-import { usePathname, useRouter } from "next/navigation"+import { useEffect, useState } from "react"+import { notFound, usePathname, useRouter, useSearchParams } from "next/navigation"+import { authClient, useSession } from "@/lib/auth-client"+import { avatarInitial } from "@/lib/community/avatar"import { CommunityShell } from "./community-shell"import { CommunityRouteFrame } from "@/components/community/shell/community-route-frame"import { SignupTracker } from "@/components/signup-tracker"@@ -9,54 +11,70 @@ import { CommunitySessionPendingFrame } from "@/components/community/shell/commuimport { resolveCommunityModulePlan } from "@/lib/community/community-route"import { AuthenticatedContextMenuBoundary } from "@/components/authenticated-context-menu-boundary"import { AuthenticatedNativeOauthCleanup } from "@/components/authenticated-native-oauth-cleanup"-import {- clearCommunityColdEntryAttempts,- retireCommunityColdEntryAttempt,-} from "@/lib/community/last-community-route"+import { Button } from "@/components/ui/button"+import { useHydratedClient } from "@/components/community/shell/use-hydrated-client"+import { clearCommunityColdEntryAttempts, retireCommunityColdEntryAttempt } from "@/lib/community/last-community-route"import type { CurrentUser } from "@/contexts/community/current-user"-import type { CommunityDocumentSeedInput } from "@/lib/community/document-seed"+import { CommunityApplicationNavigation } from "@/contexts/community/application-navigation"-function isPublicCommunityPath(pathname: string): boolean {- return resolveCommunityModulePlan(pathname).route === "public-invite"+export function CommunityLayoutClient() {+ const hydrated = useHydratedClient()+ const pathname = usePathname()+ if (!hydrated) return <CommunitySessionPendingFrame pathname="/c" />+ if (resolveCommunityModulePlan(pathname).route === "unknown") notFound()+ return <CommunityApplicationNavigation value={true}><CommunityAccountEntry pathname={pathname} /></CommunityApplicationNavigation>}-export function CommunityLayoutClient({- children,- sidebar,- currentUser,- initialSeed,-}: {- children: ReactNode- sidebar: ReactNode- currentUser: CurrentUser | null- initialSeed?: CommunityDocumentSeedInput-}) {+function CommunityAccountEntry({ pathname }: { pathname: string }) {+ const session = useSession()const router = useRouter()- const pathname = usePathname()- const isPublic = isPublicCommunityPath(pathname)+ const searchParams = useSearchParams()+ const user = session.data?.user+ const invalid = !!user && (("isBot" in user && user.isBot === true)+ || ("deletedAt" in user && user.deletedAt != null))+ const ready = !session.isPending && !session.error+ const currentUser: CurrentUser | null = ready && user && !invalid ? {+ id: user.id, email: user.email, name: user.name,+ avatar: user.image || avatarInitial(user.name),+ ...("discriminator" in user && typeof user.discriminator === "string" ? { discriminator: user.discriminator } : {}),+ } : null+ const search = searchParams.toString()+ const currentUserId = currentUser?.id+ const [retry, setRetry] = useState(0)+ const [signOutFailed, setSignOutFailed] = useState(false)useEffect(() => {- if (!isPublic && !currentUser) router.replace("/sign-in")- }, [currentUser, isPublic, router])+ if (!ready || currentUserId) return+ clearCommunityColdEntryAttempts()+ const destination = `${pathname}${search ? `?${search}` : ""}${window.location.hash}`+ const redirect = () => router.replace(`/sign-in?${new URLSearchParams({ redirect: destination })}`)+ if (!invalid) { redirect(); return }+ let active = true+ setSignOutFailed(false)+ void authClient.signOut().then(result => {+ if (!active) return+ if (result.error) setSignOutFailed(true)+ else redirect()+ }).catch(() => { if (active) setSignOutFailed(true) })+ return () => { active = false }+ }, [currentUserId, invalid, pathname, ready, retry, router, search])useEffect(() => {- if (!currentUser) {- clearCommunityColdEntryAttempts()- return- }- retireCommunityColdEntryAttempt(currentUser.id, pathname)- }, [currentUser, pathname])+ if (currentUserId) retireCommunityColdEntryAttempt(currentUserId, pathname)+ }, [currentUserId, pathname])- if (isPublic) return <><SignupTracker />{children}</>- if (!currentUser) return <CommunitySessionPendingFrame pathname={pathname} />+ if (!currentUser) return <CommunitySessionPendingFrame pathname={pathname}>+ {session.error || signOutFailed ? <div className="flex flex-1 flex-col items-center justify-center gap-4 p-8" role="alert">+ <p>Couldn't check your account.</p>+ <Button variant="outline" onClick={() => { setRetry(value => value + 1); void session.refetch() }}>Retry</Button>+ </div> : undefined}+ </CommunitySessionPendingFrame>- return (- <AuthenticatedContextMenuBoundary>- <AuthenticatedNativeOauthCleanup />- <CommunityShell currentUser={currentUser} initialSeed={initialSeed}>- <SignupTracker redirectTo="/c/me/machines" />- <CommunityRouteFrame sidebar={sidebar}>{children}</CommunityRouteFrame>- </CommunityShell>- </AuthenticatedContextMenuBoundary>- )+ return <AuthenticatedContextMenuBoundary>+ <AuthenticatedNativeOauthCleanup />+ <CommunityShell key={currentUser.id} currentUser={currentUser}>+ <SignupTracker redirectTo="/c/me/machines" />+ <CommunityRouteFrame sidebar={null}>{null}</CommunityRouteFrame>+ </CommunityShell>+ </AuthenticatedContextMenuBoundary>}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.tsxdeleted file mode 100644index 004d796c8..000000000--- a/src/web/src/app/c/community-session-fallback.dom.test.tsx+++ /dev/null@@ -1,38 +0,0 @@-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.tsxdeleted file mode 100644index 7906044e8..000000000--- a/src/web/src/app/c/community-session-fallback.tsx+++ /dev/null@@ -1,9 +0,0 @@-"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/community-shell.document.server.test.ts b/src/web/src/app/c/community-shell.document.server.test.tsdeleted file mode 100644index 788fb87c3..000000000--- a/src/web/src/app/c/community-shell.document.server.test.ts+++ /dev/null@@ -1,135 +0,0 @@-import { createElement, type ReactNode } from "react"-import { renderToReadableStream, renderToString } from "react-dom/server"-import { describe, expect, it, vi } from "vitest"-import type { Database } from "@alook/shared"-import { conversationEntryFixture, dmConversationEntryFixture } from "@/test/conversation-entry-fixtures"-import { useCanonicalCommunityProfile, useOptionalCommunityDbRegistry } from "@/lib/community-db/projections"-import type { CommunityDbRegistry } from "@/lib/community-db/collections"-import { useCurrentUser } from "@/contexts/community/current-user"-import { useDmMessages, useMessages } from "@/hooks/community/use-messages"--const documentTarget = vi.hoisted(() => ({ dm: false, author: false }))--vi.mock("@/lib/auth-client", () => ({ useSession: () => ({ data: { user: { id: "viewer" } }, isPending: false, error: null }), currentSessionViewer: () => "viewer" }))-vi.mock("next/navigation", () => ({ usePathname: () => "/c/channels/s1/c1", useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) }))-vi.mock("@tanstack/react-query-devtools", () => ({ ReactQueryDevtools: () => null }))-vi.mock("@/hooks/community/use-community-ws", () => ({ useCommunityWs: vi.fn() }))-vi.mock("@/hooks/community/use-notification-settings", () => ({ useNotificationSettings: vi.fn() }))-vi.mock("@/hooks/community/use-account-attention", () => ({ useAccountAttention: vi.fn() }))-vi.mock("@/components/perf/perf-trace-bootstrap", () => ({ PerfTraceBootstrap: () => null }))-vi.mock("@/components/community/onboarding/community-onboarding-form", () => ({ CommunityOnboardingForm: () => null }))-vi.mock("@/components/community/shell/community-ws-reconnect-overlay", () => ({ CommunityWsReconnectBoundary: ({ children }: { children: ReactNode }) => children }))-vi.mock("@/components/community/shell/owner-server-delete-route-guard", () => ({ OwnerServerDeleteRouteGuard: () => null }))-vi.mock("@/lib/community/message-door", () => ({ resolveMessageTarget: async () => ({ ok: true, value: { access: { channel: { serverId: documentTarget.dm ? null : "s1" } } } }) }))-vi.mock("@/lib/community/conversation-entry.server", () => ({ readCommunityConversationEntry: async () => {- const entry = documentTarget.dm ? dmConversationEntryFixture() : conversationEntryFixture()- if (documentTarget.author) entry.messages = entry.messages.map(message => ({ ...message, authorName: "Peer", authorAvatar: "P", authorAvatarVersion: 5 }))- return { ok: true, entry }-} }))--import { readCommunityDocumentSeed } from "@/lib/community/document-seed.server"-import { CommunityShell } from "./community-shell"-import { MessageList } from "@/components/community/messages/message-list"--describe("document HTML through the actual account and profile boundaries", () => {- it.each([- { kind: "channel", qualified: true }, { kind: "dm", qualified: true },- { kind: "channel", qualified: false }, { kind: "dm", qualified: false },- ])("streams $kind rows from an initially pending document seed with qualification=$qualified", async ({ kind, qualified }) => {- documentTarget.dm = kind === "dm"- documentTarget.author = true- const profile = { id: "viewer", name: "Viewer", discriminator: "0042", avatar: "/avatar", avatarVersion: 8, aboutMe: "", bannerColor: null, statusEmoji: null, statusText: "" }- const seed = await readCommunityDocumentSeed({} as Database, "viewer", documentTarget.dm ? "/c/me/c1" : "/c/channels/s1/c1", profile)- let release!: (value: typeof seed) => void- const pending = new Promise<typeof seed>(resolve => { release = resolve })- let didRender!: () => void- const rendered = new Promise<void>(resolve => { didRender = resolve })- let registry: CommunityDbRegistry | null = null- function Conversation() {- registry = useOptionalCommunityDbRegistry()- didRender()- const channelFeed = useMessages(documentTarget.dm ? null : "c1", { serverId: "s1", viewerUserId: "viewer" })- const dmFeed = useDmMessages(documentTarget.dm ? "c1" : null, { viewerUserId: "viewer" })- const feed = documentTarget.dm ? dmFeed : channelFeed- const author = useCanonicalCommunityProfile("peer")- return createElement("section", null, createElement("span", { "data-testid": "canonical-peer" }, author?.name ?? "missing"), createElement(MessageList, { channel: "Channel", messages: feed.messages, loading: feed.isLoading, initialScrollReady: feed.initialPositionKnown, observation: feed.observation, onOpenThread: () => {}, viewerUserId: "viewer" }))- }- try {- const streaming = renderToReadableStream(createElement(CommunityShell, { currentUser: { ...profile, email: "[email protected]" }, initialSeed: pending }, createElement(Conversation)))- await rendered- expect(registry).not.toBeNull()- release(qualified ? seed : { ...seed, viewerId: "other" })- const html = await new Response(await streaming).text()- if (qualified) {- expect(html).toContain('data-testid="community-message-m1"')- expect(html).toContain("Body")- expect(html).toContain("Peer")- } else {- expect(html).not.toContain('data-testid="community-message-m1"')- expect(html).not.toContain("Body")- expect(html).not.toContain("Peer")- }- expect(html).not.toContain("Deleted user")- expect((registry! as CommunityDbRegistry).restoration.get().captured).toBe(false)- expect((registry! as CommunityDbRegistry).queryClient.getQueryCache().getAll().every(query => query.state.fetchStatus === "idle")).toBe(true)- } finally {- release(seed)- if (registry) { await (registry as CommunityDbRegistry).cleanup(); (registry as CommunityDbRegistry).queryClient.clear() }- documentTarget.dm = false- documentTarget.author = false- }- })-- it.each(["channel", "dm"])("emits laid-out %s rows beneath the positioning skeleton before mount effects", async (kind) => {- documentTarget.dm = kind === "dm"- const profile = { id: "viewer", name: "Viewer", discriminator: "0042", avatar: "/avatar", avatarVersion: 8, aboutMe: "", bannerColor: null, statusEmoji: null, statusText: "" }- const seed = await readCommunityDocumentSeed({} as Database, "viewer", documentTarget.dm ? "/c/me/c1" : "/c/channels/s1/c1", profile)- let registry: CommunityDbRegistry | null = null- function Conversation() {- registry = useOptionalCommunityDbRegistry()- const channelFeed = useMessages(documentTarget.dm ? null : "c1", { serverId: "s1", viewerUserId: "viewer" })- const dmFeed = useDmMessages(documentTarget.dm ? "c1" : null, { viewerUserId: "viewer" })- const feed = documentTarget.dm ? dmFeed : channelFeed- return createElement(MessageList, { channel: "Channel", messages: feed.messages, loading: feed.isLoading, initialScrollReady: feed.initialPositionKnown, observation: feed.observation, onOpenThread: () => {}, viewerUserId: "viewer" })- }- try {- const html = renderToString(createElement(CommunityShell, { currentUser: { ...profile, email: "[email protected]" }, initialSeed: seed }, createElement(Conversation)))- expect(html).toContain('data-testid="community-message-m1"')- expect(html).toContain("Body")- expect(html).toMatch(/data-message-list-content[^>]*aria-hidden="true"/)- expect(html).toMatch(/data-message-list-content[^>]*style="visibility:hidden"/)- expect(html).toContain("data-message-positioning-skeleton")- expect(html).toContain('aria-busy="true"')- expect(html).toMatch(/transform:translate3d\(0, [1-9]\d*(?:\.\d+)?px, 0\)/)- expect(html).toContain('data-read-position-ready="false"')- } finally {- if (registry) { await (registry as CommunityDbRegistry).cleanup(); (registry as CommunityDbRegistry).queryClient.clear() }- documentTarget.dm = false- }- })-- it("renders the real current-user and message hooks before any restore or mount effect", async () => {- const profile = { id: "viewer", name: "Canonical viewer", discriminator: "0042", avatar: "/avatar", avatarVersion: 8, aboutMe: "About", bannerColor: null, statusEmoji: null, statusText: "" }- const seed = await readCommunityDocumentSeed({} as Database, "viewer", "/c/channels/s1/c1", profile)- let registry: CommunityDbRegistry | null = null- function Probe() {- registry = useOptionalCommunityDbRegistry()- const user = useCurrentUser()- const feed = useMessages("c1", { serverId: "s1", viewerUserId: "viewer" })- return createElement("main", null, `${user.name}:${feed.isLoading ? "pending" : feed.messages.map(message => message.content).join("|")}`)- }- try {- const html = renderToString(createElement(CommunityShell, { currentUser: { ...profile, email: "[email protected]" }, initialSeed: seed }, createElement(Probe)))- expect(html).toContain("<main>Canonical viewer:Body</main>")- expect(html).not.toContain("community-session-pending")- expect(registry).not.toBeNull()- expect((registry! as CommunityDbRegistry).restoration.get().captured).toBe(false)- expect((registry! as CommunityDbRegistry).queryClient.getQueryCache().getAll().every(query => query.state.fetchStatus === "idle")).toBe(true)- } finally {- if (registry) {- await (registry as CommunityDbRegistry).cleanup()- ;(registry as CommunityDbRegistry).queryClient.clear()- }- }- })-})diff --git a/src/web/src/app/c/community-shell.tsx b/src/web/src/app/c/community-shell.tsxindex dfd75afc3..fb6b2d20b 100644--- a/src/web/src/app/c/community-shell.tsx+++ b/src/web/src/app/c/community-shell.tsx@@ -25,32 +25,16 @@ import { useCommunityWsStore } from "@/stores/community/ws"import { OwnerServerDeleteRouteGuard } from "@/components/community/shell/owner-server-delete-route-guard"import { CommunityRestoreBoundary } from "@/components/community/shell/community-restore-bootstrap"import { CommunitySessionPendingFrame } from "@/components/community/shell/community-session-pending-frame"-import type { CommunityDocumentSeedInput } from "@/lib/community/document-seed"-/**- * Client wrapper that provides the QueryClient, CurrentUser, and the- * community WebSocket handler to every community page.- *- * The server-side layout drops the initial session user into this shell.- * `<CurrentUserProvider>` holds identity for the tree; `<CommunityBootstrap>`- * mounts the single WS handler and hydrates the viewer's aboutMe field once- * on mount — the old God-context's on-mount side-effects that survived Step 3.- *- * Notification-setting hydration lives at this root so every unread source- * request is reconciled against one account policy, including `/c` routes- * that do not mount a settings consumer.- */export function CommunityShell({currentUser,children,- initialSeed,}: {currentUser: CurrentUserchildren: ReactNode- initialSeed?: CommunityDocumentSeedInput}) {return (- <QueryProvider userId={currentUser.id} initialUser={currentUser} initialSeed={initialSeed}>+ <QueryProvider userId={currentUser.id} initialUser={currentUser}><CommunityRestoreBoundary><ProfileAccountBoundary viewerId={currentUser.id}><CurrentUserProvider initialUser={currentUser}>diff --git a/src/web/src/app/c/layout.dom.test.ts b/src/web/src/app/c/layout.dom.test.tsindex 2ff0f1425..6687b0a63 100644--- a/src/web/src/app/c/layout.dom.test.ts+++ b/src/web/src/app/c/layout.dom.test.ts@@ -1,146 +1,83 @@-import { createElement } from "react"-import { readFileSync } from "node:fs"-import { resolve } from "node:path"+import { createElement, useEffect, type ReactNode } from "react"import { beforeEach, describe, expect, it, vi } from "vitest"-import { render, screen } from "@/test/react-dom-harness"+import { act, fireEvent, render, screen } from "@/test/react-dom-harness"const mocks = vi.hoisted(() => ({- pathname: "/c/me",- replace: vi.fn(),- retireAttempt: vi.fn(),- clearAttempts: vi.fn(),-}))--vi.mock("next/navigation", () => ({- usePathname: () => mocks.pathname,- useRouter: () => ({ replace: mocks.replace }),-}))-vi.mock("@/lib/community/last-community-route", () => ({- retireCommunityColdEntryAttempt: mocks.retireAttempt,- clearCommunityColdEntryAttempts: mocks.clearAttempts,-}))-vi.mock("./community-shell", () => ({- CommunityShell: (props: Record<string, unknown>) => createElement("div", {- "data-testid": "community-shell",- "data-current-user": JSON.stringify(props.currentUser),- }),-}))-vi.mock("@/components/community/shell/community-session-pending-frame", () => ({- CommunitySessionPendingFrame: ({ pathname }: { pathname: string }) => createElement("div", {- "data-testid": "session-pending",- "data-pathname": pathname,- }),-}))-vi.mock("@/components/signup-tracker", () => ({- SignupTracker: () => createElement("div", { "data-testid": "signup-tracker" }),-}))-vi.mock("@/components/authenticated-native-oauth-cleanup", () => ({- AuthenticatedNativeOauthCleanup: () => createElement("div", { "data-testid": "native-oauth-cleanup" }),+ pathname: "/c/me/machines", search: "", router: { replace: vi.fn() },+ session: { data: null as null | { user: { id: string; email: string; name: string; image: string | null; isBot?: boolean; deletedAt?: string | null } },+ isPending: true, error: null as null | Error, refetch: vi.fn(async () => {}) },+ signOut: vi.fn(async () => ({ error: null })), mounted: vi.fn(), unmounted: vi.fn(),+ retireAttempt: vi.fn(), clearAttempts: vi.fn(),}))+vi.mock("next/navigation", () => ({ usePathname: () => mocks.pathname, useSearchParams: () => new URLSearchParams(mocks.search), useRouter: () => mocks.router, notFound: () => { throw new Error("not-found") } }))+vi.mock("@/lib/auth-client", () => ({ useSession: () => mocks.session, authClient: { signOut: mocks.signOut } }))+vi.mock("@/lib/community/last-community-route", () => ({ retireCommunityColdEntryAttempt: mocks.retireAttempt, clearCommunityColdEntryAttempts: mocks.clearAttempts }))+vi.mock("./community-shell", () => ({ CommunityShell: ({ currentUser, children }: { currentUser: { id: string }; children: ReactNode }) => {+ useEffect(() => { mocks.mounted(currentUser.id); return () => mocks.unmounted(currentUser.id) }, [currentUser.id])+ return createElement("main", { "data-testid": "private-shell", "data-account": currentUser.id }, children)+} }))+vi.mock("@/components/community/shell/community-session-pending-frame", () => ({ CommunitySessionPendingFrame: ({ pathname, children }: { pathname: string; children: ReactNode }) => createElement("main", { "data-testid": "pending", "data-pathname": pathname }, children) }))+vi.mock("@/components/community/shell/community-route-frame", () => ({ CommunityRouteFrame: () => createElement("div", null, "Route") }))+vi.mock("@/components/authenticated-context-menu-boundary", () => ({ AuthenticatedContextMenuBoundary: ({ children }: { children: ReactNode }) => children }))+vi.mock("@/components/authenticated-native-oauth-cleanup", () => ({ AuthenticatedNativeOauthCleanup: () => null }))+vi.mock("@/components/signup-tracker", () => ({ SignupTracker: () => null }))+vi.mock("@/components/ui/button", () => ({ Button: ({ children, onClick }: { children: ReactNode; onClick: () => void }) => createElement("button", { onClick }, children) }))import { CommunityLayoutClient } from "./community-layout-client"+const user = (id: string) => ({ id, email: `${id}@test.local`, name: id, image: null })+beforeEach(() => {+ vi.clearAllMocks()+ mocks.pathname = "/c/me/machines"; mocks.search = ""+ mocks.session.data = null; mocks.session.isPending = true; mocks.session.error = null+ mocks.signOut.mockResolvedValue({ error: null })+ window.history.replaceState(null, "", "/")+})+const tree = () => createElement(CommunityLayoutClient)-const user = {- id: "u1",- name: "Ada",- email: "[email protected]",- avatar: "A",- avatarVersion: 0,-}--function renderLayout(currentUser: typeof user | null = null) {- return render(createElement(- CommunityLayoutClient,- { currentUser, sidebar: null },- createElement("div", { "data-testid": "child" }),- ))-}--describe("CommunityLayout session boundary", () => {- beforeEach(() => {- mocks.pathname = "/c/me"- mocks.replace.mockClear()- mocks.retireAttempt.mockClear()- mocks.clearAttempts.mockClear()- })-- it("keeps the frame mounted while a signed-out redirect commits", () => {- renderLayout()- expect(mocks.replace).toHaveBeenCalledWith("/sign-in")- expect(mocks.clearAttempts).toHaveBeenCalledTimes(1)- expect(screen.getByTestId("session-pending")).toHaveAttribute("data-pathname", "/c/me")- expect(screen.queryByTestId("native-oauth-cleanup")).not.toBeInTheDocument()- })-- it("constructs the shell from the server-seeded identity on its first render", () => {- renderLayout(user)- expect(JSON.parse(screen.getByTestId("community-shell").dataset.currentUser!)).toMatchObject({- id: "u1",- name: "Ada",- email: "[email protected]",- })- expect(screen.queryByTestId("session-pending")).not.toBeInTheDocument()- expect(mocks.retireAttempt).toHaveBeenCalledWith("u1", "/c/me")- expect(mocks.clearAttempts).not.toHaveBeenCalled()- expect(screen.getByTestId("native-oauth-cleanup")).toBeInTheDocument()- })-- it("preserves the public invite bypass", () => {- mocks.pathname = "/c/invite/token"- renderLayout()- expect(screen.getByTestId("child")).toBeInTheDocument()- expect(screen.queryByTestId("session-pending")).not.toBeInTheDocument()- expect(mocks.replace).not.toHaveBeenCalled()- expect(screen.queryByTestId("native-oauth-cleanup")).not.toBeInTheDocument()+describe("client account startup", () => {+ it("renders a neutral frame before authentication and mounts an account without a profile prerequisite", () => {+ const view = render(tree())+ expect(screen.getByTestId("pending")).toHaveAttribute("data-pathname", "/c/me/machines")+ expect(mocks.router.replace).not.toHaveBeenCalled()+ expect(mocks.mounted).not.toHaveBeenCalled()+ mocks.session.data = { user: user("a") }; mocks.session.isPending = false+ view.rerender(tree())+ expect(screen.getByTestId("private-shell")).toHaveAttribute("data-account", "a")+ expect(mocks.retireAttempt).toHaveBeenCalledWith("a", mocks.pathname)})-- it("does not broaden the public bypass to malformed invite descendants", () => {- mocks.pathname = "/c/invite/token/extra"- renderLayout()- expect(screen.getByTestId("session-pending")).toHaveAttribute(- "data-pathname",- "/c/invite/token/extra",- )- expect(screen.queryByTestId("child")).not.toBeInTheDocument()+ it("preserves deep route, search and hash when a confirmed unauthenticated session goes to sign-in", () => {+ mocks.pathname = "/c/channels/server/channel"; mocks.search = "seq=42"+ window.history.replaceState(null, "", "/#message-42")+ mocks.session.isPending = false+ render(tree())+ const destination = new URL(mocks.router.replace.mock.calls[0]![0], "http://localhost")+ expect(destination.pathname).toBe("/sign-in")+ expect(destination.searchParams.get("redirect")).toBe("/c/channels/server/channel?seq=42#message-42")+ expect(mocks.mounted).not.toHaveBeenCalled()})-- it("keeps authenticated session resolution in the server layout", () => {- const source = readFileSync(resolve(- process.cwd(),- process.cwd().endsWith("/src/web") ? "" : "src/web",- "src/app/c/layout.tsx",- ), "utf8")- expect(source).toContain("await getSession()")- expect(source).toContain("<CommunityLayoutClient currentUser={currentUser} initialSeed={authenticated?.seed} sidebar={sidebar}>")- expect(source).not.toContain("useSession")+ it("keeps lookup errors retryable without treating them as logout", () => {+ mocks.session.isPending = false; mocks.session.error = new Error("Unavailable")+ render(tree())+ expect(screen.getByRole("alert")).toHaveTextContent("Couldn't check your account")+ fireEvent.click(screen.getByRole("button", { name: "Retry" }))+ expect(mocks.session.refetch).toHaveBeenCalledOnce()+ expect(mocks.router.replace).not.toHaveBeenCalled()+ expect(mocks.signOut).not.toHaveBeenCalled()})-- it("keeps background DM refresh out of route loading semantics", () => {- const source = readFileSync(resolve(- process.cwd(),- process.cwd().endsWith("/src/web") ? "" : "src/web",- "src/app/c/me/layout.tsx",- ), "utf8")- expect(source).not.toContain("useDmRouteVerification")- expect(source).not.toContain("<DmRoute")- const host = readFileSync(resolve(process.cwd(), process.cwd().endsWith("/src/web") ? "" : "src/web", "src/components/community/shell/shell-frame-view.tsx"), "utf8")- expect(host).toContain('checkpoint.main.kind === "dm-route"')- expect(host).toContain("routeCommitted={routeCommitted}")- expect(source).not.toMatch(/isFetching:\s*dmsFetching/)+ it.each([{ isBot: true }, { deletedAt: "2026-01-01" }])("rejects an invalid session %j before private cache can mount", async flags => {+ mocks.session.isPending = false; mocks.session.data = { user: { ...user("invalid"), ...flags } }+ render(tree()); await act(async () => {})+ expect(mocks.signOut).toHaveBeenCalledOnce()+ expect(mocks.router.replace).toHaveBeenCalledOnce()+ expect(mocks.mounted).not.toHaveBeenCalled()})-- it("keeps the daemon update controller inside the authenticated Community query cache", () => {- const shell = readFileSync(resolve(- process.cwd(),- process.cwd().endsWith("/src/web") ? "" : "src/web",- "src/app/c/community-shell.tsx",- ), "utf8")- const frame = readFileSync(resolve(- process.cwd(),- process.cwd().endsWith("/src/web") ? "" : "src/web",- "src/components/community/shell/shell-frame.tsx",- ), "utf8")- expect(shell).toMatch(/<QueryProvider[\s\S]*<CurrentUserProvider[\s\S]*<CommunityBootstrap>/)- expect(shell).not.toContain("CommunityDaemonUpdateNotice")- expect(frame).toContain("useShellDaemonUpdateController")+ it("replaces the account owner on A to B and removes it before signed-out redirect", () => {+ mocks.session.isPending = false; mocks.session.data = { user: user("a") }+ const view = render(tree())+ mocks.session.data = { user: user("b") }; view.rerender(tree())+ expect(mocks.unmounted).toHaveBeenCalledWith("a")+ expect(screen.getByTestId("private-shell")).toHaveAttribute("data-account", "b")+ mocks.session.data = null; view.rerender(tree())+ expect(mocks.unmounted).toHaveBeenCalledWith("b")+ expect(screen.queryByTestId("private-shell")).not.toBeInTheDocument()})})diff --git a/src/web/src/app/c/layout.server.test.ts b/src/web/src/app/c/layout.server.test.tsindex 1b7d80a7c..d0bafcfd7 100644--- a/src/web/src/app/c/layout.server.test.ts+++ b/src/web/src/app/c/layout.server.test.ts@@ -1,291 +1,26 @@-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"+import { createElement } from "react"+import { renderToString } from "react-dom/server"+import { describe, expect, it, vi } from "vitest"-const mocks = vi.hoisted(() => ({- getSession: vi.fn(),- cloudflareContext: vi.fn(),- headers: vi.fn(),- pathname: "/c",- documentHref: "/c/channels/server-a/channel-a",- db: vi.fn(),- primaryDb: vi.fn(),- d1: { withSession: vi.fn() },- bots: vi.fn(),- machines: vi.fn(),- client: vi.fn(),- self: vi.fn(),- seed: vi.fn(),-}))--vi.mock("@/lib/session", () => ({ getSession: mocks.getSession }))-vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: mocks.cloudflareContext }))-vi.mock("@/lib/db", async original => {- const actual = await original<typeof import("@/lib/db")>()- mocks.db.mockImplementation(actual.getDb)- mocks.primaryDb.mockImplementation(actual.getPrimaryDb)- return { ...actual, getDb: mocks.db, getPrimaryDb: mocks.primaryDb }-})-vi.mock("@/lib/community/bots.server", () => ({ readCommunityBots: mocks.bots }))-vi.mock("@/lib/community/machines.server", () => ({ readCommunityMachineList: mocks.machines }))-vi.mock("next/headers", () => ({ headers: mocks.headers }))-vi.mock("@/lib/community/self-profile.server", () => ({ readCommunitySelfProfile: mocks.self }))-vi.mock("@/lib/community/document-seed.server", () => ({ readCommunityDocumentSeed: mocks.seed }))+const mocks = vi.hoisted(() => ({ pathname: "/c", session: vi.fn() }))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("@/lib/auth-client", () => ({ useSession: mocks.session, authClient: {} }))+vi.mock("@/components/community/shell/community-session-pending-frame", () => ({+ CommunitySessionPendingFrame: ({ pathname }: { pathname: string }) => createElement("main", { "data-pathname": pathname }, "Public frame"),}))-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)- },-}))-+vi.mock("./community-shell", () => ({ CommunityShell: () => { throw new Error("Private shell rendered on server") } }))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" },-}-const profile = { id: "account-a", name: "Canonical Ada", discriminator: "0042", avatar: "canonical-avatar", avatarVersion: 9, aboutMe: "About Ada", bannerColor: null, statusEmoji: null, statusText: "" }-const seed = { viewerId: "account-a", selfProfile: profile, entries: [], db: { collections: [] } }-const currentUser = { ...profile, email: "[email protected]" }--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,- // React supplies children from the third argument; its props overload requires that injected field.- createElement("body", null, createElement(CommunityLayout, { sidebar } as Parameters<typeof CommunityLayout>[0], children))), {- onShellReady: () => rendering.pipe(output),- onShellError: (error) => output.destroy(error instanceof Error ? error : new Error("SSR shell failed", { cause: error })),- onError: (error) => { errors.push(error) },- })- return { publicFrame, finished, errors, abort: rendering.abort }-}--beforeEach(() => {- mocks.getSession.mockReset()- mocks.cloudflareContext.mockReset().mockResolvedValue({ env: { DB: mocks.d1 } })- mocks.headers.mockReset().mockImplementation(async () => new Headers({ "x-alook-community-document-route": mocks.documentHref }))- mocks.client.mockClear()- mocks.pathname = "/c"- mocks.documentHref = "/c/channels/server-a/channel-a"- mocks.db.mockClear(); mocks.primaryDb.mockClear()- mocks.d1.withSession.mockReset().mockImplementation((constraint: string) => ({ constraint, prepare: vi.fn(), batch: vi.fn() }))- mocks.bots.mockReset().mockResolvedValue({ bots: [], plan: { id: "free", displayName: "Free" }, isFounder: false, limit: 1, ownedCount: 0, activeCount: 0 })- mocks.machines.mockReset().mockResolvedValue({ machines: [] })- mocks.self.mockReset().mockResolvedValue({ viewer: { ...session.user, image: "canonical-avatar", avatarVersion: 9 }, profile })- mocks.seed.mockReset().mockResolvedValue(seed)- })--describe("CommunityLayout server session streaming", () => {- it("uses the same primary D1 session as the machines HTTP list", async () => {- mocks.documentHref = "/c/me/machines"- mocks.getSession.mockResolvedValue(session)- await renderLayout().finished- expect(mocks.primaryDb).toHaveBeenCalledOnce()- expect(mocks.db).not.toHaveBeenCalled()- })-- 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,- initialSeed: expect.any(Promise),- children,- sidebar,- })- expect(rendering.errors).toEqual([])- } finally {- rendering.abort()- }- })-- it.each([- ["avatar-a", "avatar-a"],- ["", "A"],- [null, "A"],- ])("uses the canonical profile even when the session image is %s", async (image, _expectedAvatar) => {- mocks.getSession.mockResolvedValue({ user: { ...session.user, image } })- const rendering = renderLayout()- await rendering.finished- expect(mocks.client).toHaveBeenCalledWith({- currentUser,- initialSeed: expect.any(Promise),- 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, initialSeed: undefined, children, sidebar })- expect(rendering.errors).toEqual([])- })-- it("streams the authenticated client before optional document data settles", async () => {- mocks.getSession.mockResolvedValue(session)- let release!: (value: typeof seed) => void- mocks.seed.mockReturnValue(new Promise(resolve => { release = resolve }))- const rendering = renderLayout()- try {- const html = await rendering.finished- expect(html).toContain("private-child")- expect(mocks.client).toHaveBeenCalledWith(expect.objectContaining({ currentUser, initialSeed: expect.any(Promise) }))- const pending = mocks.client.mock.calls[0]![0].initialSeed- let settled = false- void pending.then(() => { settled = true })- await Promise.resolve()- expect(settled).toBe(false)- release(seed)- await expect(pending).resolves.toBe(seed)- expect(rendering.errors).toEqual([])- } finally { rendering.abort() }- })-- it("does not serialize private data when the canonical user row is missing", async () => {- mocks.getSession.mockResolvedValue(session)- mocks.self.mockResolvedValue({ viewer: null, profile })- const rendering = renderLayout()- await rendering.finished- expect(mocks.seed).not.toHaveBeenCalled()- expect(mocks.client).toHaveBeenCalledWith(expect.objectContaining({ currentUser: null, initialSeed: undefined }))- })-- 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()- })-})---describe("Bots document Machine-list primary connection", () => {- it.each(["/c/me/bots", "/c/me/bots?msg=fixture"])("carries the actual primary wrapper into both existing loaders for %s", async href => {- mocks.documentHref = href- mocks.getSession.mockResolvedValue(session)- const { readCommunityDocumentSeed } = await vi.importActual<typeof import("@/lib/community/document-seed.server")>("@/lib/community/document-seed.server")- mocks.seed.mockImplementation(readCommunityDocumentSeed)- const rendering = renderLayout()- await rendering.finished- expect(rendering.errors).toEqual([])- expect(mocks.d1.withSession).toHaveBeenCalledExactlyOnceWith("first-primary")- expect(mocks.primaryDb).toHaveBeenCalledOnce()- expect(mocks.db).not.toHaveBeenCalled()- const selected = mocks.primaryDb.mock.results[0]!.value- expect(mocks.self).toHaveBeenCalledWith(selected, "account-a")- expect(mocks.bots).toHaveBeenCalledWith(selected, "account-a")- expect(mocks.machines).toHaveBeenCalledWith(selected, "account-a")- expect(await mocks.client.mock.calls[0]![0].initialSeed).toMatchObject({ viewerId: "account-a", machines: { machines: [] }, bots: { bots: [] } })- })- it("preserves first-unconstrained for an unrelated server document", async () => {- mocks.documentHref = "/c/channels/server-a/channel-a"- mocks.getSession.mockResolvedValue(session)- const rendering = renderLayout()- await rendering.finished- expect(rendering.errors).toEqual([])- expect(mocks.d1.withSession).toHaveBeenCalledExactlyOnceWith("first-unconstrained")- expect(mocks.db).toHaveBeenCalledOnce()- expect(mocks.primaryDb).not.toHaveBeenCalled()- const selected = mocks.db.mock.results[0]!.value- expect(mocks.self).toHaveBeenCalledWith(selected, "account-a")- expect(mocks.seed).toHaveBeenCalledWith(selected, "account-a", mocks.documentHref, profile)- })-})---describe("document session eligibility before profile and seed reads", () => {- it.each(["/c/me/bots", "/c/channels/server-a/channel-a"].flatMap(href => [- { href, label: "soft-deleted", isBot: false, deletedAt: "2026-10-01T00:00:00.000Z" },- { href, label: "bot", isBot: true, deletedAt: null },- { href, label: "deleted bot", isBot: true, deletedAt: "2026-10-01T00:00:00.000Z" },- { href, label: "nonnull empty deletion field", isBot: false, deletedAt: "" },- ]))("rejects $label session on $href before any document read", async ({ href, isBot, deletedAt }) => {- mocks.documentHref = href- mocks.getSession.mockResolvedValue({ ...session, user: { ...session.user, isBot, deletedAt } })- // The profile row remains present: an absent row cannot stand in for these session flags.- const rendering = renderLayout()- const html = await rendering.finished- expect(mocks.getSession).toHaveBeenCalledOnce()- expect(mocks.cloudflareContext).not.toHaveBeenCalled()- expect(mocks.headers).not.toHaveBeenCalled()- expect(mocks.d1.withSession).not.toHaveBeenCalled()- expect(mocks.db).not.toHaveBeenCalled()- expect(mocks.primaryDb).not.toHaveBeenCalled()- expect(mocks.self).not.toHaveBeenCalled()- expect(mocks.seed).not.toHaveBeenCalled()- expect(mocks.bots).not.toHaveBeenCalled()- expect(mocks.machines).not.toHaveBeenCalled()- expect(mocks.client).toHaveBeenCalledExactlyOnceWith({ currentUser: null, initialSeed: undefined, children, sidebar })- expect(html).not.toContain("account-a")- expect(html).not.toContain("Canonical Ada")- expect(html).not.toContain("[email protected]")- expect(rendering.errors).toEqual([])- })-- it("admits an explicit live human session and keeps its original document reads", async () => {- mocks.getSession.mockResolvedValue({ ...session, user: { ...session.user, isBot: false, deletedAt: null } })- const rendering = renderLayout()- await rendering.finished- expect(mocks.getSession).toHaveBeenCalledOnce()- expect(mocks.cloudflareContext).toHaveBeenCalledOnce()- expect(mocks.self).toHaveBeenCalledOnce()- expect(mocks.seed).toHaveBeenCalledOnce()- expect(mocks.client).toHaveBeenCalledExactlyOnceWith({ currentUser, initialSeed: expect.any(Promise), children, sidebar })- expect(rendering.errors).toEqual([])+describe("public community document", () => {+ it("emits identical neutral HTML independent of route and authentication", () => {+ const home = renderToString(createElement(CommunityLayout))+ mocks.pathname = "/c/channels/private-server/private-channel"+ const deep = renderToString(createElement(CommunityLayout))+ expect(deep).toBe(home)+ expect(home).toContain('data-community-shell="public"')+ expect(home).toContain('data-pathname="/c"')+ expect(home).not.toContain("private-server")+ expect(home).not.toContain("initialSeed")+ expect(mocks.session).not.toHaveBeenCalled()})})diff --git a/src/web/src/app/c/layout.tsx b/src/web/src/app/c/layout.tsxindex 87a3ae461..894eb2ede 100644--- a/src/web/src/app/c/layout.tsx+++ b/src/web/src/app/c/layout.tsx@@ -1,54 +1,14 @@-import { Suspense, type ReactNode } from "react"-import { getSession } from "@/lib/session"-import { avatarInitial } from "@/lib/community/avatar"-import { headers } from "next/headers"-import { getCloudflareContext } from "@opennextjs/cloudflare"-import { getDb, getPrimaryDb } from "@/lib/db"-import { readCommunitySelfProfile } from "@/lib/community/self-profile.server"-import { readCommunityDocumentSeed } from "@/lib/community/document-seed.server"-import { resolveCommunityModulePlan } from "@/lib/community/community-route"-import { COMMUNITY_DOCUMENT_ROUTE_HEADER, readCommunityDocumentRoute } from "@/lib/community/document-route"+import { Suspense } from "react"+import type { Metadata } from "next"import { CommunityLayoutClient } from "./community-layout-client"-import { CommunitySessionFallback } from "./community-session-fallback"+import { CommunitySessionPendingFrame } from "@/components/community/shell/community-session-pending-frame"-type CommunityLayoutProps = { children: ReactNode; sidebar: ReactNode }+export const metadata: Metadata = { robots: { index: false, follow: false } }-export default function CommunityLayout({ children, sidebar }: CommunityLayoutProps) {- return (- <Suspense fallback={<CommunitySessionFallback />}>- <CommunitySessionLayout sidebar={sidebar}>{children}</CommunitySessionLayout>+export default function CommunityLayout() {+ return <div className="contents" data-community-shell="public">+ <Suspense fallback={<CommunitySessionPendingFrame pathname="/c" />}>+ <CommunityLayoutClient /></Suspense>- )-}--async function CommunitySessionLayout({ children, sidebar }: CommunityLayoutProps) {- const session = await getSession()- // Match the REST session guard; flags retain the existing cookie-cache freshness.- const authenticated = session && session.user.isBot !== true && (session.user.deletedAt ?? null) === null- ? await loadDocument(session.user.id) : null- const currentUser = authenticated?.viewer ? {- ...authenticated.profile,- email: authenticated.viewer.email,- avatar: authenticated.profile.avatar || avatarInitial(authenticated.profile.name),- } : null-- return (- <CommunityLayoutClient currentUser={currentUser} initialSeed={authenticated?.seed} sidebar={sidebar}>- {children}- </CommunityLayoutClient>- )-}--async function loadDocument(viewerId: string) {- const [{ env }, requestHeaders] = await Promise.all([getCloudflareContext({ async: true }), headers()])- const href = readCommunityDocumentRoute(requestHeaders.get(COMMUNITY_DOCUMENT_ROUTE_HEADER))- const kind = href ? resolveCommunityModulePlan(href).main.kind : "none"- const db = kind === "machines" || kind === "bots" ? getPrimaryDb(env.DB) : getDb(env.DB)- const { viewer, profile } = await readCommunitySelfProfile(db, viewerId)- if (!viewer) return null- const seed = readCommunityDocumentSeed(db, viewerId, href, profile).catch((error: unknown) => {- console.error("Community document prefetch failed", error)- return null- })- return { viewer, profile, seed }+ </div>}diff --git a/src/web/src/app/c/me/[dmId]/loading.tsx b/src/web/src/app/c/me/[dmId]/loading.tsxdeleted file mode 100644index bd89a5b9b..000000000--- a/src/web/src/app/c/me/[dmId]/loading.tsx+++ /dev/null@@ -1,5 +0,0 @@-import { DmLoadingFrame } from "@/components/community/channels/dm-loading-frame"--export default function DmLoading() {- return <DmLoadingFrame />-}diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsxdeleted file mode 100644index 1e78d20e9..000000000--- a/src/web/src/app/c/me/[dmId]/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-export default function DmPage() {- return null-}diff --git a/src/web/src/app/c/me/bots/loading.tsx b/src/web/src/app/c/me/bots/loading.tsxdeleted file mode 100644index d8e76aac8..000000000--- a/src/web/src/app/c/me/bots/loading.tsx+++ /dev/null@@ -1,5 +0,0 @@-import { CommunityPendingFrame } from "@/components/community/shell/community-pending-frame"--export default function BotsLoading() {- return <CommunityPendingFrame href="/c/me/bots" />-}diff --git a/src/web/src/app/c/me/bots/page.tsx b/src/web/src/app/c/me/bots/page.tsxdeleted file mode 100644index 5c025428d..000000000--- a/src/web/src/app/c/me/bots/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-"use client"--export { default } from "@/components/community/bots/me-bots-route"diff --git a/src/web/src/app/c/me/friends/loading.tsx b/src/web/src/app/c/me/friends/loading.tsxdeleted file mode 100644index 797c0f809..000000000--- a/src/web/src/app/c/me/friends/loading.tsx+++ /dev/null@@ -1,5 +0,0 @@-import { CommunityPendingFrame } from "@/components/community/shell/community-pending-frame"--export default function FriendsLoading() {- return <CommunityPendingFrame href="/c/me/friends" />-}diff --git a/src/web/src/app/c/me/friends/page.dom.test.tsx b/src/web/src/app/c/me/friends/page.dom.test.tsxindex 27ebd0534..c14752280 100644--- a/src/web/src/app/c/me/friends/page.dom.test.tsx+++ b/src/web/src/app/c/me/friends/page.dom.test.tsx@@ -2,7 +2,7 @@ import React from "react"import { renderToString } from "react-dom/server"import { act, fireEvent, render } from "@/test/react-dom-harness"import { beforeEach, describe, expect, it, vi } from "vitest"-import MeFriendsPage from "./page"+import MeFriendsPage from "@/components/community/social/friends-route"import { CommunityTestProvider } from "@/test/community-owner-fixture"import { createCommunityQueryOwner } from "@/test/community-query-owner"import { useCommunityNavigationController } from "@/components/community/shell/use-community-navigation-controller"diff --git a/src/web/src/app/c/me/friends/page.tsx b/src/web/src/app/c/me/friends/page.tsxdeleted file mode 100644index 5bf0197f3..000000000--- a/src/web/src/app/c/me/friends/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-"use client"--export { default } from "@/components/community/social/friends-route"diff --git a/src/web/src/app/c/me/layout.route-memory.dom.test.ts b/src/web/src/app/c/me/layout.route-memory.dom.test.tsindex 057349089..30888843b 100644--- a/src/web/src/app/c/me/layout.route-memory.dom.test.ts+++ b/src/web/src/app/c/me/layout.route-memory.dom.test.ts@@ -112,7 +112,7 @@ vi.mock("@/lib/community/last-community-route", () => ({consumeCommunityColdEntryFailure: (...args: unknown[]) => mocks.consumeColdEntryFailure(...args),}))-import MeContent from "./layout"+import { CommunityMeMemoryHost as MeContent } from "@/test/community-module-host"import { DmSidebarSlot } from "@/components/community/shell/dm-sidebar-slot"import { CommunityRouteContext } from "@/components/community/shell/community-route-context"import { normalizeCommunityHref } from "@/lib/community/community-route"diff --git a/src/web/src/app/c/me/layout.tsx b/src/web/src/app/c/me/layout.tsxdeleted file mode 100644index c1fc563ba..000000000--- a/src/web/src/app/c/me/layout.tsx+++ /dev/null@@ -1,15 +0,0 @@-"use client"--import type { ReactNode } from "react"-import { useSelectedLayoutSegments, usePathname } from "next/navigation"-import { useMeRouteMemory } from "@/hooks/community/use-me-route-memory"-import { resolveCommunityModulePlan } from "@/lib/community/community-route"--export default function MeLayout({ children }: { children: ReactNode }) {- const pathname = usePathname()- const segments = useSelectedLayoutSegments()- const modulePlan = resolveCommunityModulePlan(segments.length ? `/c/me/${segments.join("/")}` : "/c/me")- const dmId = modulePlan.main.kind === "dm" ? modulePlan.main.dmId : undefined- useMeRouteMemory(pathname, !dmId)- return children-}diff --git a/src/web/src/app/c/me/loading.dom.test.ts b/src/web/src/app/c/me/loading.dom.test.tsindex 909d9ba68..521e9c3fc 100644--- a/src/web/src/app/c/me/loading.dom.test.ts+++ b/src/web/src/app/c/me/loading.dom.test.ts@@ -12,11 +12,13 @@ vi.mock("@/components/community/channels/dm-loading-frame", () => ({DmLoadingFrame: () => createElement("div", { "data-testid": "dm-loading-frame" }),}))-import MeLoading from "./loading"-import FriendsLoading from "./friends/loading"-import MachinesLoading from "./machines/loading"-import BotsLoading from "./bots/loading"-import DmLoading from "./[dmId]/loading"+import { CommunityPendingFrame } from "@/components/community/shell/community-pending-frame"+import { DmLoadingFrame } from "@/components/community/channels/dm-loading-frame"+const MeLoading = () => createElement(CommunityPendingFrame, { href: "/c/me" })+const FriendsLoading = () => createElement(CommunityPendingFrame, { href: "/c/me/friends" })+const MachinesLoading = () => createElement(CommunityPendingFrame, { href: "/c/me/machines" })+const BotsLoading = () => createElement(CommunityPendingFrame, { href: "/c/me/bots" })+const DmLoading = DmLoadingFramefunction hrefFor(Component: () => React.ReactNode) {const rendered = render(createElement(Component))diff --git a/src/web/src/app/c/me/loading.tsx b/src/web/src/app/c/me/loading.tsxdeleted file mode 100644index 793021814..000000000--- a/src/web/src/app/c/me/loading.tsx+++ /dev/null@@ -1,5 +0,0 @@-import { CommunityPendingFrame } from "@/components/community/shell/community-pending-frame"--export default function MeRouteLoading() {- return <CommunityPendingFrame href="/c/me" />-}diff --git a/src/web/src/app/c/me/machines/loading.tsx b/src/web/src/app/c/me/machines/loading.tsxdeleted file mode 100644index b3a6fc765..000000000--- a/src/web/src/app/c/me/machines/loading.tsx+++ /dev/null@@ -1,5 +0,0 @@-import { CommunityPendingFrame } from "@/components/community/shell/community-pending-frame"--export default function MachinesLoading() {- return <CommunityPendingFrame href="/c/me/machines" />-}diff --git a/src/web/src/app/c/me/machines/page.tsx b/src/web/src/app/c/me/machines/page.tsxdeleted file mode 100644index 458d63b4f..000000000--- a/src/web/src/app/c/me/machines/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-"use client"--export { default } from "@/components/community/machines/me-machines-route"diff --git a/src/web/src/app/c/me/page.dom.test.ts b/src/web/src/app/c/me/page.dom.test.tsindex 9f415c17d..bdc641f4a 100644--- a/src/web/src/app/c/me/page.dom.test.ts+++ b/src/web/src/app/c/me/page.dom.test.ts@@ -30,7 +30,7 @@ vi.mock("@/components/community/shell/community-pending-frame", () => ({}),}))-import MeListPage from "./page"+import MeListPage from "@/components/community/shell/me-root-route"function StartOnboarding() {const runtime = useCommunityRuntime()diff --git a/src/web/src/app/c/me/page.tsx b/src/web/src/app/c/me/page.tsxdeleted file mode 100644index 750012b8c..000000000--- a/src/web/src/app/c/me/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-"use client"--export { default } from "@/components/community/shell/me-root-route"diff --git a/src/web/src/app/c/messages/[messageId]/page.tsx b/src/web/src/app/c/messages/[messageId]/page.tsxdeleted file mode 100644index 2880888bb..000000000--- a/src/web/src/app/c/messages/[messageId]/page.tsx+++ /dev/null@@ -1,6 +0,0 @@-import { MessageRoute } from "@/components/community/messages/message-route"--export default async function MessagePage({ params }: { params: Promise<{ messageId: string }> }) {- const { messageId } = await params- return <MessageRoute messageId={messageId} />-}diff --git a/src/web/src/app/c/onboarding-preview/page.tsx b/src/web/src/app/c/onboarding-preview/page.tsxdeleted file mode 100644index 4c180c298..000000000--- a/src/web/src/app/c/onboarding-preview/page.tsx+++ /dev/null@@ -1,5 +0,0 @@-import { redirect } from "next/navigation"--export default function OnboardingPreviewPage() {- redirect("/c/me/machines?onboarding-preview=1")-}diff --git a/src/web/src/app/c/page.dom.test.ts b/src/web/src/app/c/page.dom.test.tsindex f8725f7c2..1de22ab5e 100644--- a/src/web/src/app/c/page.dom.test.ts+++ b/src/web/src/app/c/page.dom.test.ts@@ -26,7 +26,7 @@ vi.mock("@/lib/community/last-community-route", () => ({resolveCommunityColdEntryDestination: (args: unknown) => mocks.resolve(args),}))-import CommunityIndex from "./page"+import CommunityIndex from "@/components/community/shell/community-root-route"describe("CommunityIndex", () => {beforeEach(() => {diff --git a/src/web/src/app/c/page.tsx b/src/web/src/app/c/page.tsxindex d21a30dfc..b2d2865be 100644--- a/src/web/src/app/c/page.tsx+++ b/src/web/src/app/c/page.tsx@@ -1,3 +1,5 @@-"use client"+export const dynamic = "force-static"-export { default } from "@/components/community/shell/community-root-route"+export default function CommunityPage() {+ return null+}diff --git a/src/web/src/app/serwist/[path]/route.test.ts b/src/web/src/app/serwist/[path]/route.test.tsdeleted file mode 100644index f521b30a6..000000000--- a/src/web/src/app/serwist/[path]/route.test.ts+++ /dev/null@@ -1,127 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest"-import type { createSerwistRoute } from "@serwist/turbopack"--const mocks = vi.hoisted(() => ({- createRoute: vi.fn(),- generateStaticParams: vi.fn(),- GET: vi.fn(),-}))-vi.mock("@serwist/turbopack", () => ({ createSerwistRoute: mocks.createRoute }))--type RouteOptions = Parameters<typeof createSerwistRoute>[0]--async function loadRoute() {- const route = await import("./route")- const options = mocks.createRoute.mock.calls[0][0] as RouteOptions- return { route, options }-}--describe("public service worker route", () => {- beforeEach(() => {- vi.resetModules()- mocks.createRoute.mockReset().mockReturnValue({- generateStaticParams: mocks.generateStaticParams,- GET: mocks.GET,- })- mocks.generateStaticParams.mockReset()- mocks.GET.mockReset()- })-- it("builds a classic worker from only explicit public asset globs", async () => {- const { options } = await loadRoute()- expect(options.swSrc).toBe("src/app/sw.ts")- expect(options.useNativeEsbuild).toBe(true)- expect(options.globPatterns).toEqual([- ".next/static/chunks/**/*.{js,css}",- ".next/static/media/**/*.{woff,woff2,ttf,png,jpg,jpeg,webp,svg,ico}",- ".next/static/media/pdf.worker.min.*.mjs",- ".next/static/*/_{buildManifest,clientMiddlewareManifest,ssgManifest}.js",- "public/**/*.{svg,png,jpg,jpeg,webp,ttf,json}",- "src/app/favicon.ico",- ])- expect(options.modifyURLPrefix).toEqual({ "src/app/favicon.ico": "/favicon.ico" })- expect(options.maximumFileSizeToCacheInBytes).toBe(10 * 1024 * 1024)- expect(options.esbuildOptions).toEqual({- format: "iife", sourcemap: false,- define: { "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV) },- })- })-- it("filters the generated manifest without adding account or unknown assets", async () => {- const { options } = await loadRoute()- const urls = [- ".next/static/chunks/app-a.js",- ".next/static/chunks/styles-a.css",- ".next/static/media/font-a.woff2",- ".next/static/media/pdf.worker.min.35m0adryw15hm.mjs",- ".next/static/PGQscKRC0WsRFC5mS4zSH/_buildManifest.js",- ".next/static/PGQscKRC0WsRFC5mS4zSH/_clientMiddlewareManifest.js",- ".next/static/PGQscKRC0WsRFC5mS4zSH/_ssgManifest.js",- "/favicon.ico",- "public/manifest.json",- "public/fonts/jgs5/jgs5.ttf",- "public/contact/gus-photo.jpeg",- "public/alook.svg",- "public/official-server-badge-flat.svg",- "public/apple-touch-icon.png",- "public/icon-192.png",- "public/icon-512.png",- ]- const publicEntries = urls.map((url, i) => ({ url, revision: `public-${i}`, size: i + 1 }))- const excluded = [- "public/sw.js", "public/unknown.png", "public/avatar.png",- ".next/server/app/c.html", ".next/server/app/c.rsc",- "/c", "/c?_rsc=private", "/api/community/users/me/profile",- "/api/community/servers/server-a/avatar?v=1", "/api/files/private-a",- "https://other.test/_next/static/chunks/app-a.js",- ".next/static/chunks/app-a.js?account=a",- ".next/static/media/other-worker.mjs",- ".next/static/media/pdf.worker.min.mjs",- ".next/static/PGQscKRC0WsRFC5mS4zSH/unknown.js",- ".next/static/private/nested/_buildManifest.js",- ].map((url, i) => ({ url, revision: `excluded-${i}`, size: i + 1 }))- const transform = options.manifestTransforms![0]- const result = await transform([...publicEntries, ...excluded])- expect(result).toEqual({ manifest: publicEntries, warnings: [] })- expect(result.manifest[0]).toBe(publicEntries[0])- })-- it("retains generated static params and route restrictions", async () => {- const { route } = await loadRoute()- const params = [{ path: "sw.js" }]- mocks.generateStaticParams.mockResolvedValue(params)- expect(route.generateStaticParams).toBe(mocks.generateStaticParams)- expect(await route.generateStaticParams()).toBe(params)- expect(route.dynamic).toBe("force-static")- expect(route.dynamicParams).toBe(false)- expect(route.revalidate).toBe(false)- })-- it("preserves generated worker bytes and root scope with revalidation headers", async () => {- const { route } = await loadRoute()- const request = new Request("https://alook.test/serwist/sw.js")- const context = { params: Promise.resolve({ path: "sw.js" }) }- const generated = new Response("self.__SW_PUBLIC_TEST = true", {- headers: { "Content-Type": "application/javascript", "Service-Worker-Allowed": "/", "Cache-Control": "public, max-age=3600" },- })- mocks.GET.mockResolvedValue(generated)- const response = await route.GET(request, context)- expect(mocks.GET).toHaveBeenCalledWith(request, context)- expect(response).toBe(generated)- expect(response.status).toBe(200)- expect(response.headers.get("Content-Type")).toBe("application/javascript")- expect(response.headers.get("Service-Worker-Allowed")).toBe("/")- expect(response.headers.get("Cache-Control")).toBe("no-cache")- expect(response.headers.get("X-Content-Type-Options")).toBe("nosniff")- expect(await response.text()).toBe("self.__SW_PUBLIC_TEST = true")- })-- it("propagates generated route failures without a successful worker substitute", async () => {- const { route } = await loadRoute()- const error = new Error("worker generation failed")- mocks.GET.mockRejectedValue(error)- await expect(route.GET(new Request("https://alook.test/serwist/sw.js"), {- params: Promise.resolve({ path: "sw.js" }),- })).rejects.toBe(error)- })-})diff --git a/src/web/src/app/serwist/[path]/route.ts b/src/web/src/app/serwist/[path]/route.tsdeleted file mode 100644index 75c23eaea..000000000--- a/src/web/src/app/serwist/[path]/route.ts+++ /dev/null@@ -1,37 +0,0 @@-import { createSerwistRoute } from "@serwist/turbopack"-import { isPublicAssetPath } from "@/lib/service-worker/public-cache"--const serviceWorkerRoute = createSerwistRoute({- swSrc: "src/app/sw.ts",- useNativeEsbuild: true,- globPatterns: [- ".next/static/chunks/**/*.{js,css}",- ".next/static/media/**/*.{woff,woff2,ttf,png,jpg,jpeg,webp,svg,ico}",- ".next/static/media/pdf.worker.min.*.mjs",- ".next/static/*/_{buildManifest,clientMiddlewareManifest,ssgManifest}.js",- "public/**/*.{svg,png,jpg,jpeg,webp,ttf,json}",- "src/app/favicon.ico",- ],- modifyURLPrefix: { "src/app/favicon.ico": "/favicon.ico" },- maximumFileSizeToCacheInBytes: 10 * 1024 * 1024,- manifestTransforms: [async entries => ({- manifest: entries.filter(entry => isPublicAssetPath(- entry.url.replace(/^\.next\//, "/_next/").replace(/^public\//, "/"),- )),- warnings: [],- })],- esbuildOptions: { format: "iife", sourcemap: false, define: { "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV) } },-})--export const generateStaticParams = serviceWorkerRoute.generateStaticParams--export async function GET(request: Request, context: { params: Promise<{ path: string }> }) {- const response = await serviceWorkerRoute.GET(request, context)- response.headers.set("Cache-Control", "no-cache")- response.headers.set("X-Content-Type-Options", "nosniff")- return response-}--export const dynamic = "force-static"-export const dynamicParams = false-export const revalidate = falsediff --git a/src/web/src/app/sw.test.ts b/src/web/src/app/sw.test.tsindex a5851b7f7..ae46861b1 100644--- a/src/web/src/app/sw.test.ts+++ b/src/web/src/app/sw.test.ts@@ -1,7 +1,9 @@import { afterEach, describe, expect, it, vi } from "vitest"-import { CacheFirst, NetworkFirst, Serwist, Strategy } from "serwist"+import { CacheFirst, NavigationRoute, NetworkFirst, Serwist, Strategy } from "serwist"import { publicWorkerRuntimeCacheNames } from "../lib/service-worker/cache-identity"+const shellUrl = `/community-shell/${"a".repeat(64)}`+afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); vi.unstubAllEnvs(); vi.resetModules() })describe("public worker activation", () => {@@ -10,7 +12,7 @@ describe("public worker activation", () => {const listeners = vi.spyOn(Serwist.prototype, "addEventListeners")const location = new URL("https://example.test/sw.js")vi.stubGlobal("location", location)- vi.stubGlobal("self", { location, __SW_MANIFEST: [{ url: "/icon-192.png", revision: "fixture" }, { url: "/favicon.ico", revision: "fixture-favicon" }, { url: "/_next/static/chunks/example.js", revision: "fixture-code" }], registration: { scope: `${location.origin}/` }, addEventListener: vi.fn() })+ vi.stubGlobal("self", { location, __SW_MANIFEST: [{ url: shellUrl, revision: "fixture-shell" }, { url: "/icon-192.png", revision: "fixture" }, { url: "/favicon.ico", revision: "fixture-favicon" }, { url: "/_next/static/chunks/example.js", revision: "fixture-code" }], registration: { scope: `${location.origin}/` }, addEventListener: vi.fn() })await import("./sw")const serwist = listeners.mock.contexts[0]if (!(serwist instanceof Serwist)) throw new Error("Missing actual Serwist instance")@@ -45,16 +47,88 @@ describe("public worker activation", () => {expect(match(path, { headers: { RSC: "1" } })).toBeUndefined()}for (const path of ["/favicon.ico?favicon.abc123.ico=", "/favicon.ico?favicon.abc123.ico&x=1", "/favicon.ico?%66avicon.abc123.ico", "/favicon.ico?__WB_REVISION__=fixture", "/_next/static/chunks/example.js?favicon.abc123.ico"]) expect(match(path), path).toBeUndefined()+ for (const path of ["/c", "/c/me/bots", "/c/channels/server/channel?seq=4"]) {+ const url = new URL(path, location)+ const request = new Request(url, { headers: { Cookie: "fixture" } })+ Object.defineProperty(request, "mode", { value: "navigate" })+ expect(serwist.findMatchingRoute({ url, request, sameOrigin: true, event: new Event("fetch") as FetchEvent }).route).toBeInstanceOf(NavigationRoute)+ }+ expect(match(shellUrl)).toBeDefined()+ expect(match(shellUrl, { headers: { Cookie: "fixture" } })).toBeUndefined()expect(match("/icon-192.png", { headers: { Cookie: "fixture" } })).toBeUndefined()for (const path of ["/api/auth/get-session", "/blog", "/blog/example-article", "/c/me", "https://other.test/blog/example-article/hero.webp"]) expect(match(path), path).toBeUndefined()})+ it.each(["public", "changed-shell", "private-asset"] as const)("installs only validated public shell and asset bytes: %s", async (scenario) => {+ vi.stubEnv("NODE_ENV", "production")+ const html = '<main data-community-shell="public">Application</main>'+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(html))+ const hash = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, "0")).join("")+ const path = `/community-shell/${hash}`+ const location = new URL("https://example.test/sw.js")+ const stored = new Map<string, Response>()+ const urlOf = (key: RequestInfo | URL) => typeof key === "string" ? new URL(key, location).href : key instanceof URL ? key.href : key.url+ const storage = {+ match: async (key: RequestInfo | URL) => stored.get(urlOf(key))?.clone(),+ open: async () => ({+ match: async (key: RequestInfo | URL) => stored.get(urlOf(key))?.clone(),+ put: async (key: RequestInfo | URL, response: Response) => { stored.set(urlOf(key), response.clone()) },+ }),+ }+ class WorkerEvent extends Event {+ pending: Promise<unknown>[] = []+ waitUntil(promise: Promise<unknown>) { this.pending.push(promise) }+ }+ class WorkerFetchEvent extends WorkerEvent {}+ vi.stubGlobal("ExtendableEvent", WorkerEvent)+ vi.stubGlobal("FetchEvent", WorkerFetchEvent)+ vi.stubGlobal("location", location)+ vi.stubGlobal("caches", storage)+ vi.stubGlobal("self", { location, caches: storage, registration: { scope: `${location.origin}/` }, addEventListener: vi.fn(),+ __SW_MANIFEST: [{ url: path, revision: null }, { url: "/icon-192.png", revision: "fixture" }] })+ const network = vi.fn<typeof fetch>(async input => {+ const shell = new URL(urlOf(input)).pathname === path+ return new Response(shell ? scenario === "changed-shell" ? "Changed bytes" : html : "Public icon", {+ headers: { "Content-Type": shell ? "text/html" : "image/png",+ "Cache-Control": !shell && scenario === "private-asset" ? "private, no-store" : "public, max-age=31536000, immutable" },+ })+ })+ vi.stubGlobal("fetch", network)+ const listeners = vi.spyOn(Serwist.prototype, "addEventListeners")+ await import("./sw")+ const serwist = listeners.mock.contexts[0]+ if (!(serwist instanceof Serwist)) throw new Error("Missing actual Serwist instance")+ const event = new WorkerEvent("install")+ const install = serwist.handleInstall(event as Parameters<Serwist["handleInstall"]>[0])+ const results = await Promise.allSettled([install, ...event.pending])+ if (scenario === "public") {+ expect(results.every(result => result.status === "fulfilled")).toBe(true)+ expect(stored.size).toBe(2)+ expect(await stored.get(new URL(path, location).href)?.clone().text()).toBe(html)+ const iconKey = serwist.getPrecacheKeyForUrl(new URL("/icon-192.png", location).href)!+ expect(await stored.get(iconKey)?.clone().text()).toBe("Public icon")+ } else {+ expect(results.some(result => result.status === "rejected")).toBe(true)+ const rejectedPath = scenario === "changed-shell" ? path : "/icon-192.png"+ const rejectedUrl = new URL(rejectedPath, location).href+ const key = serwist.getPrecacheKeyForUrl(rejectedUrl)!+ expect(stored.has(key)).toBe(false)+ for (const result of results) if (result.status === "rejected") {+ expect(result.reason).toMatchObject({ name: "bad-precaching-response", details: { url: rejectedUrl, status: 200 } })+ }+ }+ expect(network).toHaveBeenCalledTimes(2)+ for (const [input] of network.mock.calls) {+ expect(input).toBeInstanceOf(Request)+ expect(input).toMatchObject({ credentials: "omit", redirect: "error" })+ }+ })it("runs actual Serwist activation and deletes old custom cache names without changing the current cache", async () => {const names = new Set(["alook-public-precache-v0", "alook-public-precache-v1", "alook-public-v99-runtime", "unrelated-cache"])const storage = { keys: vi.fn(async () => [...names]), delete: vi.fn(async (name: string) => names.delete(name)),open: vi.fn(async (name: string) => { names.add(name); return { keys: async () => [] as Request[] } }) }const listeners = new Map<string, Array<(event: { waitUntil: (promise: Promise<unknown>) => void }) => unknown>>()const location = new URL("https://example.test/sw.js")- const worker = { __SW_MANIFEST: [], location, caches: storage, registration: { scope: "https://example.test/" }, clients: { claim: vi.fn(async () => undefined) },+ const worker = { __SW_MANIFEST: [{ url: shellUrl, revision: "fixture-shell" }], location, caches: storage, registration: { scope: "https://example.test/" }, clients: { claim: vi.fn(async () => undefined) },addEventListener: (type: string, listener: (event: { waitUntil: (promise: Promise<unknown>) => void }) => unknown) => listeners.set(type, [...listeners.get(type) ?? [], listener]) }vi.stubGlobal("self", worker)vi.stubGlobal("location", location)diff --git a/src/web/src/app/sw.ts b/src/web/src/app/sw.tsindex 602471119..bc9af1ea5 100644--- a/src/web/src/app/sw.ts+++ b/src/web/src/app/sw.ts@@ -1,11 +1,12 @@/// <reference lib="webworker" />import type { PrecacheEntry, SerwistGlobalConfig } from "serwist"-import { Serwist } from "serwist"+import { NavigationRoute, Serwist } from "serwist"import { isPublicAssetResponse, publicFaviconQueryParameter, restrictPublicPrecacheRoutes } from "../lib/service-worker/public-cache"import { publicWorkerCacheNames } from "../lib/service-worker/cache-identity"import { createPublicRuntimeCaching } from "../lib/service-worker/public-cache-runtime"import { clearOutdatedPublicWorkerCaches } from "../lib/service-worker/public-cache-storage"+import { communityShellHash, isCommunityShellAssetRequest, isCommunityShellNavigation, isCommunityShellResponse } from "../lib/service-worker/community-shell"declare global {interface WorkerGlobalScope extends SerwistGlobalConfig {@@ -15,8 +16,13 @@ declare global {declare const self: ServiceWorkerGlobalScope+const entries = self.__SW_MANIFEST ?? []+const shells = entries.map(entry => typeof entry === "string" ? entry : entry.url).filter(url => communityShellHash(url))+if (shells.length !== 1) throw new Error("A complete public community shell is required")+const shellUrl = shells[0]+const serwist = new Serwist({- precacheEntries: self.__SW_MANIFEST,+ precacheEntries: entries,cacheId: publicWorkerCacheNames().cacheId,clientsClaim: true,runtimeCaching: createPublicRuntimeCaching(self.location.origin, {@@ -31,12 +37,21 @@ const serwist = new Serwist({ignoreURLParametersMatching: [publicFaviconQueryParameter],plugins: [{requestWillFetch: async ({ request }) => new Request(request, { credentials: "omit", redirect: "error" }),- cacheWillUpdate: async ({ request, response }) => isPublicAssetResponse(request, response) ? response : null,+ cacheWillUpdate: async ({ request, response }) => (+ new URL(request.url).pathname === shellUrl+ ? await isCommunityShellResponse(request, response, shellUrl)+ : isPublicAssetResponse(request, response)+ ) ? response : null,}],},})restrictPublicPrecacheRoutes(serwist, self.location.origin)+serwist.registerCapture(({ request }) => isCommunityShellAssetRequest(request, self.location.origin, shellUrl), serwist.createHandlerBoundToUrl(shellUrl))+const navigation = new NavigationRoute(serwist.createHandlerBoundToUrl(shellUrl))+const matchNavigation = navigation.match+navigation.match = options => isCommunityShellNavigation(options.request, self.location.origin) && matchNavigation(options)+serwist.registerRoute(navigation)serwist.addEventListeners()self.addEventListener("activate", event => event.waitUntil(clearOutdatedPublicWorkerCaches()))diff --git a/src/web/src/components/community/bots/bot-list-controller.dom.test.ts b/src/web/src/components/community/bots/bot-list-controller.dom.test.tsindex 6b2ef6075..c088c78aa 100644--- a/src/web/src/components/community/bots/bot-list-controller.dom.test.ts+++ b/src/web/src/components/community/bots/bot-list-controller.dom.test.ts@@ -25,6 +25,7 @@ const mocks = vi.hoisted(() => ({audit: null as string | null,bots: [] as BotSummary[],botsDataReady: true,+ botsObserved: true,useActualBots: false,botsLoad: vi.fn(),isFounder: true,@@ -87,7 +88,7 @@ vi.mock("@/hooks/community/use-bots", async (importOriginal) => {mocks.hookOrder.push("bots")return {bots: mocks.bots,- data: mocks.botsDataReady ? { bots: mocks.bots, ...mocks.planSummary, isFounder: mocks.isFounder } : undefined,+ data: mocks.botsDataReady ? { bots: mocks.bots, observed: mocks.botsObserved, ...mocks.planSummary, isFounder: mocks.isFounder } : undefined,isPending: mocks.botsLoading,}},@@ -240,6 +241,7 @@ describe("useBotListController", () => {mocks.audit = nullmocks.bots = [bot("b1", "mac1")]mocks.botsDataReady = true+ mocks.botsObserved = truemocks.useActualBots = falsemocks.botsLoad.mockReset()mocks.botsLoading = false@@ -515,6 +517,35 @@ describe("useBotListController", () => {expect(mocks.replace).not.toHaveBeenCalled()})+ it.each([true, false])("keeps a missing restored audit target until current inventory resolves, present=%s", (present) => {+ mocks.audit = "b2"+ mocks.botsObserved = false+ const renderer = render()+ expect(latest.activityOpen).toBe(false)+ expect(mocks.replace).not.toHaveBeenCalled()++ mocks.botsObserved = true+ if (present) mocks.bots = [...mocks.bots, bot("b2", "mac1")]+ act(() => renderer.rerender(React.createElement(Probe)))+ expect(latest.activityOpen).toBe(present)+ if (present) {+ expect(latest.activityBot?.id).toBe("b2")+ expect(mocks.replace).not.toHaveBeenCalled()+ } else {+ expect(latest.activityBot).toBeNull()+ expect(mocks.replace).toHaveBeenCalledWith("/c/me/bots?machineId=mac1")+ }+ })++ it("opens an existing restored audit target before inventory revalidation", () => {+ mocks.audit = "b1"+ mocks.botsObserved = false+ render()+ expect(latest.activityOpen).toBe(true)+ expect(latest.activityBot?.id).toBe("b1")+ expect(mocks.replace).not.toHaveBeenCalled()+ })+it("clears invalid or nonowned audit ids without opening the modal", () => {mocks.audit = "foreign"render()diff --git a/src/web/src/components/community/bots/bot-list-controller.ts b/src/web/src/components/community/bots/bot-list-controller.tsindex 723cdbfff..91f5c1347 100644--- a/src/web/src/components/community/bots/bot-list-controller.ts+++ b/src/web/src/components/community/bots/bot-list-controller.ts@@ -51,6 +51,7 @@ export function useBotListController(): BotListController {const { bots } = botsQueryconst isLoading = botsQuery.isPending || botsQuery.profilesPending === trueconst botsResolved = botsQuery.data !== undefined && botsQuery.profilesPending !== true+ const botsObserved = botsQuery.data?.observed !== falseconst [billingOpen, setBillingOpen] = useAtom(useCreateAtom(false))const viewPlan = () => {const next = new URL(routeCommitted ? window.location.href : `/c/me/bots?${searchParams.toString()}`, window.location.origin)@@ -295,6 +296,7 @@ export function useBotListController(): BotListController {const targetBot = bots.find((bot) => bot.id === targetAuditBotId)if (!targetBot) {+ if (!botsObserved) returnpatchProtocol({ suppressedAudit: targetAuditBotId })if (activityOpen) {setActivityOpen(false)@@ -314,7 +316,7 @@ export function useBotListController(): BotListController {if (!activityOpen) {setActivityOpen(true)}- }, [routeCommitted, activityBot, activityOpen, bots, botsResolved, patchProtocol, protocol, router, searchParams, setActivityBot, setActivityGeneration, setActivityOpen, targetAuditBotId])+ }, [routeCommitted, activityBot, activityOpen, bots, botsResolved, botsObserved, patchProtocol, protocol, router, searchParams, setActivityBot, setActivityGeneration, setActivityOpen, targetAuditBotId])const openActivity = (bot: BotSummary) => {uiHandlers.cancelPendingNavigation?.()diff --git a/src/web/src/components/community/bots/bot-list-facade.contract.dom.test.ts b/src/web/src/components/community/bots/bot-list-facade.contract.dom.test.tsindex 9fd6d6588..4c6d6cefa 100644--- a/src/web/src/components/community/bots/bot-list-facade.contract.dom.test.ts+++ b/src/web/src/components/community/bots/bot-list-facade.contract.dom.test.ts@@ -64,10 +64,10 @@ describe("BotList facade contract", () => {})it("keeps the production page and existing regression on the original path", () => {- const page = source("src/app/c/me/bots/page.tsx")+ const page = source("src/components/community/shell/community-module-route.tsx")const existingTest = source("src/components/community/bots/bot-list-card.dom.test.ts")const consumer = source("src/components/community/bots/me-bots-route.tsx")- expect(page).toContain('export { default } from "@/components/community/bots/me-bots-route"')+ expect(page).toContain('import BotsRoute from "../bots/me-bots-route"')expect(consumer).toContain('from "@/components/community/bots/bot-list"')expect(existingTest).toContain('from "./bot-list"')expect(`${page}\n${existingTest}`).not.toMatch(diff --git a/src/web/src/components/community/bots/bot-list-view.dom.test.ts b/src/web/src/components/community/bots/bot-list-view.dom.test.tsindex 57b38fc50..d295ac13f 100644--- a/src/web/src/components/community/bots/bot-list-view.dom.test.ts+++ b/src/web/src/components/community/bots/bot-list-view.dom.test.ts@@ -1,5 +1,5 @@import { renderToString } from "react-dom/server"-import MeBotsPage from "@/app/c/me/bots/page"+import MeBotsPage from "@/components/community/bots/me-bots-route"import React from "react"import { beforeEach, describe, expect, it, vi } from "vitest"import type { BotListController } from "./bot-list-types"diff --git a/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.ts b/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.tsindex 5dba36d29..efc46ace3 100644--- a/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.ts+++ b/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.ts@@ -21,8 +21,8 @@ describe("adaptive navigation cutover contracts", () => {})it("shares one channel subtree consumer across the layout and shell and removes the nested leaf", () => {- const layout = readSource("../../../app/c/channels/layout.tsx")- const flatPage = readSource("../../../app/c/channels/[serverId]/[channelId]/page.tsx")+ const layout = readSource("../shell/community-route-frame.tsx")+ const flatPage = readSource("../../../app/c/[...path]/page.tsx")const nestedPage = new URL("../../../app/c/channels/[serverId]/[channelId]/[childChannelId]/page.tsx",import.meta.url,@@ -30,7 +30,7 @@ describe("adaptive navigation cutover contracts", () => {const consumer = readSource("./server-conversation-route.tsx")const shell = readSource("../shell/community-module-route.tsx")- expect(layout).toContain("<ServerConversationRoute")+ expect(layout).toContain("usePathname()")expect(shell).toContain("<ServerConversationRoute")expect(consumer).toContain("key={JSON.stringify([viewer.id, serverId])}")expect(layout).not.toContain("parentChannelId={routeParent" + "ChannelId}")diff --git a/src/web/src/components/community/channels/channel-loading-frame.test.ts b/src/web/src/components/community/channels/channel-loading-frame.test.tsindex c1b54c7d6..d3870acd0 100644--- a/src/web/src/components/community/channels/channel-loading-frame.test.ts+++ b/src/web/src/components/community/channels/channel-loading-frame.test.ts@@ -1,7 +1,7 @@import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"import { describe, expect, it } from "vitest"-import ServerLoading from "@/app/c/channels/[serverId]/loading"+import { ChannelLoadingFrame as ServerLoading } from "@/components/community/channels/channel-loading-frame"import { ChannelLoadingFrame } from "./channel-loading-frame"describe("ChannelLoadingFrame", () => {diff --git a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.tsindex d5380ea08..8d37f153b 100644--- a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts+++ b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts@@ -14,7 +14,7 @@ import { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feeimport type { ConversationNavigationTarget } from "@/lib/community/conversation-navigation-warmup"import { useCommunityRuntime } from "@/stores/community/runtime"import { runAuthoritativeServerEject } from "@/lib/community/eject-server"-import ServerLayout from "@/app/c/channels/layout"+import { CommunityServerModuleHost as ServerLayout } from "@/test/community-module-host"import { channelSchema } from "@/lib/community-db/schema"import { conversationEntryFixture } from "@/test/conversation-entry-fixtures"diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsxindex bc37f4ba5..073eff607 100644--- a/src/web/src/components/community/channels/channel-route.tsx+++ b/src/web/src/components/community/channels/channel-route.tsx@@ -3,7 +3,8 @@ import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps } from "react"-import { useRouter, useSearchParams } from "next/navigation"+import { useSearchParams } from "next/navigation"+import { useCommunityHistoryRouter as useRouter } from "@/lib/community/navigation"import { toastApiError } from "@/lib/api/client"import { ChannelHeaderSkeleton, type ChannelNotifLevel } from "@/components/community/channels/channel-header"import { ConversationMessageSkeleton } from "@/components/community/channels/conversation-message-skeleton"diff --git a/src/web/src/components/community/channels/channel-sidebar.navigation.dom.test.tsx b/src/web/src/components/community/channels/channel-sidebar.navigation.dom.test.tsxindex 9681cc039..551fae908 100644--- a/src/web/src/components/community/channels/channel-sidebar.navigation.dom.test.tsx+++ b/src/web/src/components/community/channels/channel-sidebar.navigation.dom.test.tsx@@ -73,7 +73,7 @@ describe("real sortable channel navigation surface", () => {expect(anchor).toHaveAttribute("href", "/c/channels/server/two")expect(anchor).toHaveAttribute("aria-roledescription", "draggable")fireEvent.focus(anchor)- expect(anchor).toHaveAttribute("data-prefetch", "true")+ expect(anchor).not.toHaveAttribute("data-prefetch")act(() => anchor.focus())await setupUser().keyboard("{Enter}")expect(onPick.mock.calls).toEqual([["two"]])diff --git a/src/web/src/components/community/channels/dm-route.tsx b/src/web/src/components/community/channels/dm-route.tsxindex 63b9241e1..1c1c094f6 100644--- a/src/web/src/components/community/channels/dm-route.tsx+++ b/src/web/src/components/community/channels/dm-route.tsx@@ -1,7 +1,7 @@"use client"import { useEffect, useRef } from "react"-import { useRouter } from "next/navigation"+import { useCommunityHistoryRouter as useRouter } from "@/lib/community/navigation"import { DmView } from "./dm-view"import { DmRouteErrorFrame } from "./dm-route-error-frame"import { DmLoadingFrame } from "./dm-loading-frame"diff --git a/src/web/src/components/community/channels/use-dm-seq-context.ts b/src/web/src/components/community/channels/use-dm-seq-context.tsindex c41534a1b..8b1782216 100644--- a/src/web/src/components/community/channels/use-dm-seq-context.ts+++ b/src/web/src/components/community/channels/use-dm-seq-context.ts@@ -1,7 +1,8 @@"use client"import { useEffect } from "react"-import { usePathname, useRouter, useSearchParams } from "next/navigation"+import { usePathname, useSearchParams } from "next/navigation"+import { useCommunityHistoryRouter as useRouter } from "@/lib/community/navigation"import { removeCommunityParam } from "@/lib/community/community-route"export function useDmSeqContext({diff --git a/src/web/src/components/community/machines/machine-list.dom.test.ts b/src/web/src/components/community/machines/machine-list.dom.test.tsindex a427ddba2..7567e5214 100644--- a/src/web/src/components/community/machines/machine-list.dom.test.ts+++ b/src/web/src/components/community/machines/machine-list.dom.test.ts@@ -7,7 +7,7 @@ import { render as renderNative } from "@/test/react-dom-harness"import { CommunityTestProvider } from "@/test/community-owner-fixture"import { createCommunityQueryOwner } from "@/test/community-query-owner"import { CommunityModuleRouteContext } from "@/contexts/community/module-route"-import MeMachinesPage from "@/app/c/me/machines/page"+import MeMachinesPage from "@/components/community/machines/me-machines-route"import { beforeEach, describe, expect, it, vi } from "vitest"import { act, fireEvent, waitFor } from "@/test/react-dom-harness"import { renderCommunity as render } from "@/test/community-owner-harness"diff --git a/src/web/src/components/community/messages/message-channel-controller-state.ts b/src/web/src/components/community/messages/message-channel-controller-state.tsindex b2b03be14..4cac63a2d 100644--- a/src/web/src/components/community/messages/message-channel-controller-state.ts+++ b/src/web/src/components/community/messages/message-channel-controller-state.ts@@ -14,7 +14,8 @@ import { presentCanonicalMessage } from "@/lib/community/message-wire"import { messageScopeKey } from "@/stores/community/message-stream-store"import { useConversationActivity } from "@/contexts/community/conversation-activity"import { useCommunityViewSource } from "@/hooks/community/use-community-view-source"-import { usePathname, useRouter, useSearchParams } from "next/navigation"+import { usePathname, useSearchParams } from "next/navigation"+import { useCommunityHistoryRouter as useRouter } from "@/lib/community/navigation"import type { MentionType } from "@alook/shared"import type { Msg } from "@/lib/community/models/message"diff --git a/src/web/src/components/community/messages/message-list-facade.contract.test.ts b/src/web/src/components/community/messages/message-list-facade.contract.test.tsindex d36240f9d..fde45578a 100644--- a/src/web/src/components/community/messages/message-list-facade.contract.test.ts+++ b/src/web/src/components/community/messages/message-list-facade.contract.test.ts@@ -96,7 +96,8 @@ describe("MessageList facade contract", () => {it("keeps unresolved server entries independent of message layout modules", () => {for (const path of [- "src/app/c/channels/[serverId]/page.tsx",+ "src/app/c/page.tsx",+ "src/app/c/layout.tsx","src/components/community/channels/channel-loading-frame.tsx",]) {expect(source(path)).not.toMatch(/messages\/(?:message-list|composer)|[\/."]channel-header["']/)diff --git a/src/web/src/components/community/shell/community-friend-pending-provider-order.test.ts b/src/web/src/components/community/shell/community-friend-pending-provider-order.test.tsindex 63942325e..7a583beb4 100644--- a/src/web/src/components/community/shell/community-friend-pending-provider-order.test.ts+++ b/src/web/src/components/community/shell/community-friend-pending-provider-order.test.ts@@ -10,7 +10,6 @@ vi.mock("@/components/community/shell/community-shell-layout", () => ({CommunityShellLayout: ({ main }: { main: ReactNode }) => main,}))-import FriendsLoading from "@/app/c/me/friends/loading"import { CommunityPendingFrame } from "./community-pending-frame"import { CommunitySessionPendingFrame } from "./community-session-pending-frame"@@ -37,7 +36,7 @@ describe("friends pending QueryClient provider order", () => {},{name: "the friends route loading boundary",- render: () => createElement(FriendsLoading),+ render: () => createElement(CommunityPendingFrame, { href: "/c/me/friends" }),withQueryProvider: false,},{diff --git a/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts b/src/web/src/components/community/shell/community-inbox-popover.dom.test.tsindex 8416ebdf0..e12a7a392 100644--- a/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts+++ b/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts@@ -445,9 +445,9 @@ describe("InboxPopover DM rows", () => {const row = renderer.getByTestId(tid.inboxUnreadDm(dm.channelId))expect(row).toHaveAttribute("href", "/c/me/dm-new")- expect(row).toHaveAttribute("data-prefetch", "false")+ expect(row).not.toHaveAttribute("data-prefetch")fireEvent.pointerEnter(row)- expect(row).toHaveAttribute("data-prefetch", "true")+ expect(row).not.toHaveAttribute("data-prefetch")expect(onOpenDm).not.toHaveBeenCalled()fireEvent.click(row)diff --git a/src/web/src/components/community/shell/community-navigation-link.dom.test.tsx b/src/web/src/components/community/shell/community-navigation-link.dom.test.tsxindex 451fc8d2e..d5b95685b 100644--- a/src/web/src/components/community/shell/community-navigation-link.dom.test.tsx+++ b/src/web/src/components/community/shell/community-navigation-link.dom.test.tsx@@ -4,29 +4,40 @@ import { act, fireEvent, render, setupUser } from "@/test/react-dom-harness"import type { CommunityDbRegistry } from "@/lib/community-db/collections"import { CommunityNavigationLink } from "./community-navigation-link"-const owner = vi.hoisted(() => ({ registry: null as CommunityDbRegistry | null }))+const owner = vi.hoisted(() => ({ registry: null as CommunityDbRegistry | null, warm: vi.fn() }))vi.mock("@/lib/community-db/projections", () => ({ useOptionalCommunityDbRegistry: () => owner.registry }))-vi.mock("next/link", async () => ({ default: (await import("@/test/community-link-mock")).CommunityLinkMock }))+vi.mock("@/lib/observability/context", () => ({ beginNavigationPrefetch: owner.warm }))+vi.mock("@/lib/community/navigation-metadata", () => ({ prepareNavigationMetadata: vi.fn() }))-beforeEach(() => { owner.registry = null })+beforeEach(() => { owner.registry = null; owner.warm.mockClear() })describe("community public Link bridge", () => {- it("requests full prefetch only on intent and resets it when href changes, retaining the anchor", async () => {+ it.each(["", "saved.html", true])("preserves native download activation for download=%s", download => {+ const onActivate = vi.fn()+ const view = render(<CommunityNavigationLink href="/c/me/friends" download={download} onActivate={onActivate}>Download</CommunityNavigationLink>)+ const anchor = view.getByRole("link")+ expect(anchor).toHaveAttribute("download")+ const click = new MouseEvent("click", { bubbles: true, cancelable: true })+ fireEvent(anchor, click)+ expect(onActivate).not.toHaveBeenCalled()+ expect(click.defaultPrevented).toBe(false)+ })+ it("warms only client metadata on intent while retaining the anchor", async () => {const onActivate = vi.fn()const props = { href: "/c/channels/a/one", onActivate }const view = render(<CommunityNavigationLink {...props}>A</CommunityNavigationLink>)const anchor = view.getByRole("link")- expect(anchor).toHaveAttribute("data-prefetch", "false")+ expect(owner.warm).not.toHaveBeenCalled()fireEvent.pointerEnter(anchor)- expect(anchor).toHaveAttribute("data-prefetch", "true")+ expect(owner.warm).toHaveBeenLastCalledWith(props.href)expect(onActivate).not.toHaveBeenCalled()view.rerender(<CommunityNavigationLink {...props} href="/c/channels/a/two">A</CommunityNavigationLink>)expect(view.getByRole("link")).toBe(anchor)- expect(anchor).toHaveAttribute("data-prefetch", "false")+ expect(owner.warm).toHaveBeenCalledTimes(1)view.rerender(<CommunityNavigationLink {...props}>A</CommunityNavigationLink>)- expect(anchor).toHaveAttribute("data-prefetch", "false")+ expect(owner.warm).toHaveBeenCalledTimes(1)fireEvent.focus(anchor)- expect(anchor).toHaveAttribute("data-prefetch", "true")+ expect(owner.warm).toHaveBeenCalledTimes(1)await setupUser().click(anchor)expect(onActivate).toHaveBeenCalledTimes(1)})@@ -37,7 +48,7 @@ describe("community public Link bridge", () => {const event = new Event("pointerdown", { bubbles: true })Object.defineProperty(event, "pointerType", { value: "touch" })fireEvent(view.getByRole("link"), event)- expect(view.getByRole("link")).toHaveAttribute("data-prefetch", "true")+ expect(owner.warm).toHaveBeenCalledWith("/c/me/dm")expect(onActivate).not.toHaveBeenCalled()})@@ -46,9 +57,9 @@ describe("community public Link bridge", () => {const props = { href: "/c/me/bots", onActivate, prefetchMode: "visible" as const }const view = render(<CommunityNavigationLink {...props}>Bots</CommunityNavigationLink>)const anchor = view.getByRole("link")- expect(anchor).toHaveAttribute("data-prefetch", "true")+ expect(owner.warm).toHaveBeenCalledWith(props.href)view.rerender(<CommunityNavigationLink {...props} active>Bots</CommunityNavigationLink>)- expect(anchor).toHaveAttribute("data-prefetch", "false")+ expect(owner.warm).toHaveBeenCalledTimes(1)const user = setupUser()await user.click(anchor)anchor.focus()@@ -70,7 +81,7 @@ describe("community public Link bridge", () => {expect(onActivate).toHaveBeenCalledTimes(1)})- it("blocks navigation and warming during dragging, then retires intent on account generation changes", () => {+ it("blocks navigation and warming during dragging, then blocks a retired account generation", () => {const lifecycle = createStore({ active: true, generation: 0 })owner.registry = { runtime: { lifecycle } } as unknown as CommunityDbRegistryconst onActivate = vi.fn()@@ -79,17 +90,17 @@ describe("community public Link bridge", () => {const anchor = view.getByRole("link")fireEvent.pointerEnter(anchor)fireEvent.click(anchor)- expect(anchor).toHaveAttribute("data-prefetch", "false")+ expect(owner.warm).not.toHaveBeenCalled()expect(onActivate).not.toHaveBeenCalled()view.rerender(<CommunityNavigationLink {...props}>A</CommunityNavigationLink>)fireEvent.focus(anchor)- expect(anchor).toHaveAttribute("data-prefetch", "true")+ expect(owner.warm).toHaveBeenCalledOnce()act(() => lifecycle.setState(() => ({ active: false, generation: 1 })))fireEvent.click(anchor)- expect(anchor).toHaveAttribute("data-prefetch", "false")+ expect(owner.warm).toHaveBeenCalledOnce()expect(onActivate).not.toHaveBeenCalled()act(() => lifecycle.setState(() => ({ active: true, generation: 2 })))- expect(anchor).toHaveAttribute("data-prefetch", "false")+ expect(owner.warm).toHaveBeenCalledOnce()})})@@ -104,7 +115,7 @@ it("keeps preview links local without prefetching real account routes", async ()expect(anchor).toHaveAttribute("href", "#product")fireEvent.pointerEnter(anchor)fireEvent.focus(anchor)- expect(anchor).not.toHaveAttribute("data-prefetch")+ expect(owner.warm).not.toHaveBeenCalled()await setupUser().click(anchor)expect(onActivate).toHaveBeenCalledOnce()})diff --git a/src/web/src/components/community/shell/community-navigation-link.tsx b/src/web/src/components/community/shell/community-navigation-link.tsxindex e52e89bfc..8feda1185 100644--- a/src/web/src/components/community/shell/community-navigation-link.tsx+++ b/src/web/src/components/community/shell/community-navigation-link.tsx@@ -1,16 +1,14 @@"use client"-import Link from "next/link"import { useCommunityPreviewNavigation } from "./community-preview-navigation"-import { useLayoutEffect, type ComponentProps } from "react"-import { createStore, useAtom, useCreateAtom, useSelector } from "@tanstack/react-store"+import { useCallback, useEffect, useRef, type ComponentProps } from "react"+import { createStore, useSelector } from "@tanstack/react-store"import { useOptionalCommunityDbRegistry } from "@/lib/community-db/projections"import { prepareNavigationMetadata } from "@/lib/community/navigation-metadata"import { beginNavigationPrefetch } from "@/lib/observability/context"const absentLifecycle = createStore({ active: true, generation: 0 })--type Props = Omit<ComponentProps<typeof Link>, "href" | "prefetch" | "onNavigate"> & {+type Props = ComponentProps<"a"> & {href: stringonActivate: () => voidprefetchMode?: "intent" | "visible"@@ -24,52 +22,31 @@ export function CommunityNavigationLink({}: Props) {const preview = useCommunityPreviewNavigation()const registry = useOptionalCommunityDbRegistry()- const lifecycle = useSelector(registry?.runtime.lifecycle ?? absentLifecycle, (state) => state)- const [intent, setIntent] = useAtom(useCreateAtom<{- href: string- registry: typeof registry- generation: number- } | null>(null))- useLayoutEffect(() => { setIntent(null) }, [href, registry, lifecycle.generation, setIntent])+ const lifecycle = useSelector(registry?.runtime.lifecycle ?? absentLifecycle, state => state)+ const warmed = useRef<{ href: string; registry: typeof registry; generation: number } | null>(null)const enabled = lifecycle.active && !navigationDisabled- const warm = () => {- if (enabled && !active) {- beginNavigationPrefetch(href)- if (registry) void prepareNavigationMetadata(registry.queryClient, href, "prefetch")- setIntent({ href, registry, generation: lifecycle.generation })- }- }- const prefetched = enabled && !active && (prefetchMode === "visible"- || (intent?.href === href && intent.registry === registry && intent.generation === lifecycle.generation))- if (preview) return (- <a {...props} href="#product" aria-current={active ? "page" : props["aria-current"]}- onClick={(event) => {- event.preventDefault()- if (enabled) onActivate()- }} />- )- return (- <Link- {...props}- href={href}- prefetch={prefetched}- aria-current={active ? "page" : props["aria-current"]}- onPointerEnter={(event) => { onPointerEnter?.(event); if (!event.defaultPrevented) warm() }}- onFocus={(event) => { onFocus?.(event); if (!event.defaultPrevented) warm() }}- onPointerDown={(event) => {- onPointerDown?.(event)- if (!event.defaultPrevented && event.pointerType === "touch") warm()- }}- onClick={(event) => {- onClick?.(event)- if (navigationDisabled || !lifecycle.active) {- event.preventDefault()- }- }}- onNavigate={(event) => {- event.preventDefault()- if (enabled) onActivate()- }}- />- )+ const warm = useCallback(() => {+ if (preview || !enabled || active || warmed.current?.href === href+ && warmed.current.registry === registry && warmed.current.generation === lifecycle.generation) return+ warmed.current = { href, registry, generation: lifecycle.generation }+ beginNavigationPrefetch(href)+ if (registry) void prepareNavigationMetadata(registry.queryClient, href, "prefetch")+ }, [active, enabled, href, lifecycle.generation, preview, registry])+ useEffect(() => { if (prefetchMode === "visible") warm() }, [prefetchMode, warm])++ if (preview) return <a {...props} href="#product" aria-current={active ? "page" : props["aria-current"]}+ onClick={event => { event.preventDefault(); if (enabled) onActivate() }} />++ return <a {...props} href={href} aria-current={active ? "page" : props["aria-current"]}+ onPointerEnter={event => { onPointerEnter?.(event); if (!event.defaultPrevented) warm() }}+ onFocus={event => { onFocus?.(event); if (!event.defaultPrevented) warm() }}+ onPointerDown={event => { onPointerDown?.(event); if (!event.defaultPrevented && event.pointerType === "touch") warm() }}+ onClick={event => {+ onClick?.(event)+ if (!enabled) { event.preventDefault(); return }+ if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey+ || props.target && props.target !== "_self" || event.currentTarget.hasAttribute("download")) return+ event.preventDefault()+ onActivate()+ }} />}diff --git a/src/web/src/components/community/shell/community-route-frame.dom.test.tsx b/src/web/src/components/community/shell/community-route-frame.dom.test.tsxindex 48fbb8d4b..0d4533d8d 100644--- a/src/web/src/components/community/shell/community-route-frame.dom.test.tsx+++ b/src/web/src/components/community/shell/community-route-frame.dom.test.tsx@@ -6,7 +6,6 @@ import { CommunityTestProvider } from "@/test/community-owner-fixture"import { createCommunityQueryOwner } from "@/test/community-query-owner"import { CommunityRouteFrame } from "./community-route-frame"import { useCommunityRouteFrame } from "./community-route-context"-import ServerContent from "@/app/c/channels/layout"import { CommunitySessionPendingFrame } from "./community-session-pending-frame"import { tid } from "@/lib/community/testids"@@ -137,17 +136,17 @@ describe("common committed community frame", () => {expect(view.getByTestId("rail")).toBe(rail)})- it("ignores ahead-of-commit pathname and gates mismatched sidebar scope", async () => {+ it("commits the URL without a layout-segment handshake and still gates a mismatched sidebar", async () => {const view = render(tree())await act(async () => {})mocks.pathname = "/c/channels/b/two"view.rerender(tree("b"))- expect(view.queryByTestId("sidebar")).toBeNull()- expect(owner.registry.runtime.ui.get().currentServerId).toBeNull()- expect(view.getByTestId("main")).toHaveTextContent("me/friends")- mocks.segments = ["channels", "b", "two"]- view.rerender(tree("b"))expect(view.getByTestId("sidebar")).toHaveAttribute("data-server-id", "b")+ expect(owner.registry.runtime.ui.get().currentServerId).toBe("b")+ expect(view.queryByText("me/friends")).toBeNull()+ view.rerender(tree("a"))+ expect(view.queryByTestId("sidebar")).toBeNull()+ expect(owner.registry.runtime.ui.get().currentServerId).toBe("b")})it.each(["url-first", "segments-first"])("gates DM query effects on exact publication in %s order", async order => {@@ -163,7 +162,7 @@ describe("common committed community frame", () => {else mocks.segments = ["me", "dm-b"]view.rerender(tree())expect(view.container.querySelector('[data-dm-target="dm-b"]')).toBe(body)- expect(body).toHaveAttribute("data-committed", "false")+ expect(body).toHaveAttribute("data-committed", order === "url-first" ? "true" : "false")mocks.segments = ["me", "dm-b"]mocks.pathname = "/c/me/dm-b"mocks.search = "seq=7"@@ -195,30 +194,23 @@ describe("common committed community frame", () => {expect(view.getByTestId("userbar")).not.toBe(userbar)})- it("takes server content identity from its own segments despite merged slot params", () => {- mocks.segments = ["a", "channel-a"]- mocks.search = "msg=other-slot&threadView=full"- const view = render(<CommunityTestProvider client={owner.client} registry={owner.registry} retainOwner>- <CommunityRouteFrame sidebar={null}><ServerContent><span>static child</span></ServerContent></CommunityRouteFrame>- </CommunityTestProvider>)- expect(mocks.channel).toHaveBeenLastCalledWith({- serverParam: "a", channelId: "channel-a",- targetHref: "/c/channels/a/channel-a", routeCommitted: false,- })+ it("takes server and channel identity from the URL despite stale segment or slot params", () => {+ mocks.segments = ["wrong-server", "wrong-channel"]mocks.pathname = "/c/channels/a/channel-a"mocks.search = "msg=own-anchor&threadView=full"- view.rerender(<CommunityTestProvider client={owner.client} registry={owner.registry} retainOwner>- <CommunityRouteFrame sidebar={null}><ServerContent><span>static child</span></ServerContent></CommunityRouteFrame>- </CommunityTestProvider>)+ const node = () => <CommunityTestProvider client={owner.client} registry={owner.registry} retainOwner>+ <CommunityRouteFrame sidebar={null}>{null}</CommunityRouteFrame>+ </CommunityTestProvider>+ const view = render(node())expect(mocks.channel).toHaveBeenLastCalledWith({serverParam: "a", channelId: "channel-a",targetHref: "/c/channels/a/channel-a?msg=own-anchor&threadView=full", routeCommitted: true,})- mocks.segments = ["a", "settings"]- view.rerender(<CommunityTestProvider client={owner.client} registry={owner.registry} retainOwner>- <CommunityRouteFrame sidebar={null}><ServerContent><span>static child</span></ServerContent></CommunityRouteFrame>- </CommunityTestProvider>)- expect(view.getByText("static child")).toBeInTheDocument()- expect(view.queryByTestId("channel")).toBeNull()+ mocks.pathname = "/c/channels/b/channel-b"+ mocks.search = "seq=9"+ view.rerender(node())+ expect(mocks.channel).toHaveBeenLastCalledWith({+ serverParam: "b", channelId: "channel-b", targetHref: "/c/channels/b/channel-b?seq=9", routeCommitted: true,+ })})})diff --git a/src/web/src/components/community/shell/community-route-frame.tsx b/src/web/src/components/community/shell/community-route-frame.tsxindex 9b9277720..390a2e1ce 100644--- a/src/web/src/components/community/shell/community-route-frame.tsx+++ b/src/web/src/components/community/shell/community-route-frame.tsx@@ -1,7 +1,7 @@"use client"import { useCallback, useLayoutEffect, useMemo, type ReactNode } from "react"-import { useSelectedLayoutSegments } from "next/navigation"+import { usePathname, useSearchParams } from "next/navigation"import { useQueryClient } from "@tanstack/react-query"import { useCurrentUser } from "@/contexts/community/current-user"import { getCommunityRuntime } from "@/stores/community/runtime"@@ -13,8 +13,9 @@ export function CommunityRouteFrame({ sidebar, children }: {sidebar: ReactNodechildren: ReactNode}) {- const segments = useSelectedLayoutSegments()- const frameHref = segments.length ? `/c/${segments.join("/")}` : "/c"+ const pathname = usePathname()+ const search = useSearchParams().toString()+ const frameHref = `${pathname}${search ? `?${search}` : ""}`const serverId = communityServerId(frameHref)const queryClient = useQueryClient()const currentUser = useCurrentUser()diff --git a/src/web/src/components/community/shell/community-session-pending-frame.dom.test.ts b/src/web/src/components/community/shell/community-session-pending-frame.dom.test.tsindex b06cd5ccb..b2ce81974 100644--- a/src/web/src/components/community/shell/community-session-pending-frame.dom.test.ts+++ b/src/web/src/components/community/shell/community-session-pending-frame.dom.test.ts@@ -1,6 +1,6 @@import { createElement } from "react"-import { describe, expect, it, vi } from "vitest"-import { render, screen } from "@/test/react-dom-harness"+import { beforeEach, describe, expect, it, vi } from "vitest"+import { fireEvent, render, screen } from "@/test/react-dom-harness"vi.mock("@/components/ui/skeleton", () => ({Skeleton: () => createElement("div", { "data-testid": "skeleton" }),@@ -16,7 +16,9 @@ vi.mock("@/components/ui/resizable", () => ({ResizablePanel: ({ children }: React.PropsWithChildren) => createElement("div", null, children),ResizableHandle: () => createElement("div"),}))-vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "unknown" }))+const viewport = vi.hoisted(() => ({ value: "unknown" }))+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => viewport.value }))+beforeEach(() => { viewport.value = "unknown" })vi.mock("@/components/community/channels/channel-sidebar", () => ({ChannelSidebarSkeleton: () => createElement("div", { "data-testid": "server-sidebar" }),}))@@ -52,6 +54,16 @@ function renderFrame(pathname: string) {}describe("CommunitySessionPendingFrame", () => {+ it.each(["mobile", "desktop"].flatMap(viewport => ["/c", "/c/me/machines", "/c/channels/s1/c1"].map(pathname => ({ viewport, pathname }))))("shows an actionable account error at $pathname on $viewport", ({ viewport: breakpoint, pathname }) => {+ viewport.value = breakpoint+ const retry = vi.fn()+ render(createElement(CommunitySessionPendingFrame, { pathname }, createElement("div", { role: "alert" },+ "Could not check account", createElement("button", { onClick: retry }, "Retry"))))+ expect(screen.getByRole("alert")).toHaveTextContent("Could not check account")+ expect(screen.queryByTestId("pending-main")).not.toBeInTheDocument()+ fireEvent.click(screen.getByRole("button", { name: "Retry" }))+ expect(retry).toHaveBeenCalledOnce()+ })it.each([["/c/me", "me-root", "me-sidebar", "me-root"],["/c/me/dm_1", "dm-detail", "me-sidebar", "dm"],diff --git a/src/web/src/components/community/shell/community-session-pending-frame.tsx b/src/web/src/components/community/shell/community-session-pending-frame.tsxindex a88e4c69e..de56da85a 100644--- a/src/web/src/components/community/shell/community-session-pending-frame.tsx+++ b/src/web/src/components/community/shell/community-session-pending-frame.tsx@@ -45,7 +45,7 @@ export function CommunitySessionPendingFrame({ pathname, children }: { pathname:sidebar={plan.sidebar.kind === "server"? <ChannelSidebarSkeleton targetServerId={plan.sidebar.serverId} />: <DmSidebarSkeleton />}- main={<CommunityPendingFrame+ main={children ?? <CommunityPendingFramehref={pathname}plan={plan}reserveBackSlot={plan.surface === "detail"}diff --git a/src/web/src/components/community/shell/explicit-navigation-entries.dom.test.tsx b/src/web/src/components/community/shell/explicit-navigation-entries.dom.test.tsxindex b84476231..a7c0ce7ae 100644--- a/src/web/src/components/community/shell/explicit-navigation-entries.dom.test.tsx+++ b/src/web/src/components/community/shell/explicit-navigation-entries.dom.test.tsx@@ -12,7 +12,7 @@ import type { BotSummary } from "@/hooks/community/use-bots"import { CommunityInviteCard } from "../social/community-invite-card"import { useCommunityNavigationController } from "./use-community-navigation-controller"import { CurrentUserProvider } from "@/contexts/community/current-user"-import MeFriendsPage from "@/app/c/me/friends/page"+import MeFriendsPage from "@/components/community/social/friends-route"const mocks = vi.hoisted(() => ({push: vi.fn(),diff --git a/src/web/src/components/community/shell/owner-server-delete-route-guard.tsx b/src/web/src/components/community/shell/owner-server-delete-route-guard.tsxindex ceae3d321..c9d2215f6 100644--- a/src/web/src/components/community/shell/owner-server-delete-route-guard.tsx+++ b/src/web/src/components/community/shell/owner-server-delete-route-guard.tsx@@ -4,7 +4,8 @@ import { useEffect } from "react"import { useQueryClient } from "@tanstack/react-query"import { useSelector } from "@tanstack/react-store"import { getCommunityRuntime } from "@/stores/community/runtime"-import { usePathname, useRouter } from "next/navigation"+import { usePathname } from "next/navigation"+import { useCommunityHistoryRouter as useRouter } from "@/lib/community/navigation"import { toast } from "sonner"import { useCurrentUser } from "@/contexts/community/current-user"import { useServers } from "@/hooks/community/use-servers"diff --git a/src/web/src/components/community/shell/server-sidebar-slot.tsx b/src/web/src/components/community/shell/server-sidebar-slot.tsxindex 1eef72d5d..b06e79370 100644--- a/src/web/src/components/community/shell/server-sidebar-slot.tsx+++ b/src/web/src/components/community/shell/server-sidebar-slot.tsx@@ -5,7 +5,8 @@ import { getCommunityRuntime } from "@/stores/community/runtime"import { useCallback, useEffect, useMemo, useRef } from "react"-import { usePathname, useRouter, useSearchParams } from "next/navigation"+import { usePathname, useSearchParams } from "next/navigation"+import { useCommunityHistoryRouter as useRouter } from "@/lib/community/navigation"import { useQueryClient } from "@tanstack/react-query"import { toast } from "sonner"import { toastApiError } from "@/lib/api/client"diff --git a/src/web/src/components/community/shell/shell-frame-contract.test.ts b/src/web/src/components/community/shell/shell-frame-contract.test.tsindex c554b6246..b9251d02b 100644--- a/src/web/src/components/community/shell/shell-frame-contract.test.ts+++ b/src/web/src/components/community/shell/shell-frame-contract.test.ts@@ -1,4 +1,4 @@-import { readFileSync } from "node:fs"+import { existsSync, readFileSync } from "node:fs"import { dirname, resolve } from "node:path"import { fileURLToPath } from "node:url"import type { ComponentProps } from "react"@@ -17,17 +17,17 @@ describe("ShellFrame public contract", () => {it("keeps the one frame above both native slots and content layouts", () => {const frame = readWeb("src/components/community/shell/community-route-frame.tsx")- expect(frame).toContain("useSelectedLayoutSegments()")+ expect(frame).toContain("usePathname()")expect(frame).toContain("<ShellFrame")expect(readWeb("src/app/c/community-layout-client.tsx")).toContain("<CommunityRouteFrame")for (const path of ["src/app/c/channels/layout.tsx", "src/app/c/me/layout.tsx"]) {- expect(readWeb(path)).not.toContain("<ShellFrame")+ expect(existsSync(resolve(webRoot, path))).toBe(false)}const shellView = readWeb("src/components/community/shell/shell-frame-view.tsx")expect(shellView.match(/<DmSidebarSlot\b/g)).toHaveLength(1)- expect(readWeb("src/app/c/@sidebar/me/layout.tsx")).not.toContain("DmSidebarSlot")+ expect(existsSync(resolve(webRoot, "src/app/c/@sidebar"))).toBe(false)expect(shellView.match(/<ServerSidebarSlot\b/g)).toHaveLength(1)- expect(readWeb("src/app/c/@sidebar/channels/[serverId]/layout.tsx")).not.toContain("ServerSidebarSlot")+ expect(frame).not.toContain("useSelectedLayoutSegments")})it("keeps shell-frame as orchestration with one public component", () => {diff --git a/src/web/src/components/community/shell/shell-frame.dom.test.ts b/src/web/src/components/community/shell/shell-frame.dom.test.tsindex 99d4b2068..e14ddcfbf 100644--- a/src/web/src/components/community/shell/shell-frame.dom.test.ts+++ b/src/web/src/components/community/shell/shell-frame.dom.test.ts@@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { act, fireEvent, render as renderDom, screen, waitFor } from "@/test/react-dom-harness"import { ShellFrame } from "./shell-frame"import { MobilePage } from "./mobile-page"-import ServerLayout from "@/app/c/channels/layout"+import { CommunityServerModuleHost as ServerLayout } from "@/test/community-module-host"import { useCommunityRuntime } from "@/stores/community/runtime"import { communityKeys } from "@/lib/query-keys"import { useInboxAutoCollapse } from "@/hooks/community/use-inbox-auto-collapse"@@ -885,7 +885,7 @@ describe("ShellFrame orchestration", () => {expect(task.context.navigation.pendingHref).toBe(returnRoot)expect(task.context.navigation.navigationPending).toBe(true)expect(screen.queryByTestId(`return-leaf-${child}`)).toBeNull()- expect(screen.getByTestId(`return-leaf-${parent}`)).not.toBeVisible()+ expect(screen.queryByTestId(`return-leaf-${parent}`)).toBeNull()task.commit(returnRoot)await waitFor(() => expect(task.context.navigation.navigationPending).toBe(false))expect(task.context.frame.href).toBe(returnRoot)diff --git a/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts b/src/web/src/components/community/shell/shell.navigation-intent.dom.test.tsindex bfc5e65dd..348df91b0 100644--- a/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts+++ b/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts@@ -12,7 +12,7 @@ import {import { ShellFrameView } from "./shell-frame-view"import { useCommunityNavigationController } from "./use-community-navigation-controller"import { CommunityRouteContext } from "./community-route-context"-import ServerLayout from "@/app/c/channels/layout"+import { CommunityServerModuleHost as ServerLayout } from "@/test/community-module-host"const mocks = vi.hoisted(() => ({pathname: "/c/channels/s1/a",diff --git a/src/web/src/components/community/shell/use-community-navigation-controller.ts b/src/web/src/components/community/shell/use-community-navigation-controller.tsindex 070631c0e..b8279a9d0 100644--- a/src/web/src/components/community/shell/use-community-navigation-controller.ts+++ b/src/web/src/components/community/shell/use-community-navigation-controller.ts@@ -6,7 +6,8 @@ import { prepareNavigationMetadata } from "@/lib/community/navigation-metadata"import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useCallback, useEffect, useLayoutEffect, useRef } from "react"import { flushSync } from "react-dom"-import { usePathname, useRouter, useSearchParams } from "next/navigation"+import { usePathname, useSearchParams } from "next/navigation"+import { useCommunityHistoryRouter as useRouter } from "@/lib/community/navigation"import { useQueryClient } from "@tanstack/react-query"import {commitLatestNavigationIntent,diff --git a/src/web/src/components/home/landing-content.test.ts b/src/web/src/components/home/landing-content.test.tsindex 78f1a03d4..6b4e52c86 100644--- a/src/web/src/components/home/landing-content.test.ts+++ b/src/web/src/components/home/landing-content.test.ts@@ -267,7 +267,7 @@ describe("landing content contract", () => {expect(signInClient).toContain('label: "Bring your own agents"')expect(signInClient).toContain('description: "Use your own computer and existing agent subscriptions."')expect(signInClient).not.toContain("Bring your own workspaces")- expect(communityLayout).toContain("await getSession()")+ expect(communityLayout).toContain('data-community-shell="public"')expect(communityLayoutClient).toContain('<SignupTracker redirectTo="/c/me/machines" />')expect(ogRoute).toContain("SITE_OG_IMAGE_URL")expect(ogRoute).toContain("Response.redirect")diff --git a/src/web/src/contexts/community/application-navigation.tsx b/src/web/src/contexts/community/application-navigation.tsxnew file mode 100644index 000000000..abfb30882--- /dev/null+++ b/src/web/src/contexts/community/application-navigation.tsx@@ -0,0 +1,5 @@+"use client"++import { createContext } from "react"++export const CommunityApplicationNavigation = createContext(false)diff --git a/src/web/src/contexts/community/module-route.tsx b/src/web/src/contexts/community/module-route.tsxindex e9642e10f..013bb1603 100644--- a/src/web/src/contexts/community/module-route.tsx+++ b/src/web/src/contexts/community/module-route.tsx@@ -2,7 +2,8 @@import { createContext, useContext, useMemo } from "react"import { CommunityRouteContext } from "@/contexts/community/route-frame"-import { useRouter, useSearchParams } from "next/navigation"+import { useSearchParams } from "next/navigation"+import { useCommunityHistoryRouter as useRouter } from "@/lib/community/navigation"export const CommunityModuleRouteContext = createContext<{ href: string; routeCommitted: boolean } | null>(null)diff --git a/src/web/src/hooks/community/thread-opener-read-handoff.ts b/src/web/src/hooks/community/thread-opener-read-handoff.tsindex 06e57ad8f..8d5089be8 100644--- a/src/web/src/hooks/community/thread-opener-read-handoff.ts+++ b/src/web/src/hooks/community/thread-opener-read-handoff.ts@@ -1,7 +1,8 @@"use client"import { useCallback, useLayoutEffect, useRef } from "react"-import { usePathname, useRouter, useSearchParams } from "next/navigation"+import { usePathname, useSearchParams } from "next/navigation"+import { useCommunityHistoryRouter as useRouter } from "@/lib/community/navigation"import { useQueryClient } from "@tanstack/react-query"import { useConversationActivity } from "@/contexts/community/conversation-activity"import { useCurrentUser } from "@/contexts/community/current-user"diff --git a/src/web/src/hooks/community/use-channel-route-model.ts b/src/web/src/hooks/community/use-channel-route-model.tsindex b9c2187a7..b16222908 100644--- a/src/web/src/hooks/community/use-channel-route-model.ts+++ b/src/web/src/hooks/community/use-channel-route-model.ts@@ -5,7 +5,8 @@ import { useCommunityRuntime } from "@/stores/community/runtime"import { useEffect, useLayoutEffect, useMemo, useRef } from "react"-import { usePathname, useRouter } from "next/navigation"+import { usePathname } from "next/navigation"+import { useCommunityHistoryRouter as useRouter } from "@/lib/community/navigation"import { useQueryClient } from "@tanstack/react-query"import { isForum as isForumType, type CommunityChannelResource } from "@alook/shared"import type { Channel } from "@/lib/community/models/navigation"diff --git a/src/web/src/lib/application-owner.anonymous.dom.test.tsx b/src/web/src/lib/application-owner.anonymous.dom.test.tsxindex 1854b7e10..36e317cf1 100644--- a/src/web/src/lib/application-owner.anonymous.dom.test.tsx+++ b/src/web/src/lib/application-owner.anonymous.dom.test.tsx@@ -2,7 +2,7 @@ import "fake-indexeddb/auto"import { createContext, useContext, useLayoutEffect } from "react"import { afterEach, beforeEach, expect, it, vi } from "vitest"import { act, render, waitFor } from "@/test/react-dom-harness"-import { InviteAcceptClient } from "@/app/c/invite/[token]/invite-accept-client"+import { InviteAcceptClient } from "@/app/(public-community)/c/invite/[token]/invite-accept-client"import { PublicQueryProvider, useApplicationOwner, type ApplicationOwner } from "./application-owner"import { CACHE_INVALIDATION_STORAGE_KEY, clearAllPersistedCaches, createIdbPersister } from "./query-persister"import { tid } from "@/lib/community/testids"diff --git a/src/web/src/lib/community/application-route.ts b/src/web/src/lib/community/application-route.tsnew file mode 100644index 000000000..388da38b2--- /dev/null+++ b/src/web/src/lib/community/application-route.ts@@ -0,0 +1,6 @@+import { resolveCommunityModulePlan } from "./community-route"++export function isCommunityApplicationPath(pathname: string): boolean {+ const route = resolveCommunityModulePlan(pathname).route+ return route !== "unknown" && route !== "public-invite"+}diff --git a/src/web/src/lib/community/bots.ts b/src/web/src/lib/community/bots.tsindex 5e5b70d8a..3113d662a 100644--- a/src/web/src/lib/community/bots.ts+++ b/src/web/src/lib/community/bots.ts@@ -66,7 +66,7 @@ export function botProfilePatch(bot: Pick<BotSummary, "id" | "name" | "image" |return { id: bot.id, identityAbout: { name: bot.name, kind: "bot", ...("discriminator" in bot && typeof bot.discriminator === "string" ? { discriminator: bot.discriminator } : {}), ...(bot.description === undefined ? {} : { aboutMe: bot.description }) }, avatar: { avatar: bot.image, avatarVersion: bot.avatarVersion } }}-export function botsResource(data: BotsResponse): BotsResourceResponse {+function botsResource(data: BotsResponse): BotsResourceResponse {return { ...data, bots: data.bots.map(({ name: _name, description: _description, image: _image, avatarVersion: _avatarVersion, presence: _presence, ...resource }) => resource) }}diff --git a/src/web/src/lib/community/document-route.test.ts b/src/web/src/lib/community/document-route.test.tsdeleted file mode 100644index dce2997cf..000000000--- a/src/web/src/lib/community/document-route.test.ts+++ /dev/null@@ -1,20 +0,0 @@-import { describe, expect, it } from "vitest"-import { communityDocumentRoute, readCommunityDocumentRoute } from "./document-route"--describe("community document selection input", () => {- it.each(["/c/me/bots", "/c/me/machines", "/c/me/dm", "/c/channels/server", "/c/channels/server/channel"])("selects only the current %s route", path => {- expect(communityDocumentRoute(new URL(path, "https://alook.test"))).toBe(path)- expect(readCommunityDocumentRoute(path)).toBe(path)- })- it("keeps only bounded message/tag selection and drops unrelated search input", () => {- expect(communityDocumentRoute(new URL("https://alook.test/c/channels/server/channel?msg=message&tag=中文&settings=private&threadView=full")))- .toBe("/c/channels/server/channel?msg=message&tag=%E4%B8%AD%E6%96%87")- })- it.each(["/c", "/c/me", "/c/me/friends", "/c/invite/token", "/sign-in", "https://elsewhere.test/c/me/bots", "/c/me/bots?settings=private", "/c/me/bots?msg=bad/slash"])("rejects an unsupported or unnormalized header %s", value => {- expect(readCommunityDocumentRoute(value)).toBeNull()- })- it.each([null, "", "/c/me/with space", "/c/me/%", "/c/me/\u0000", "/c/me/\ud800", "/c/../../sign-in", "/c/me/bots?tag=" + "x".repeat(101), "/c/me/" + "x".repeat(2048)])("rejects a noncanonical bounded header without replacing native URL: %j", value => {- expect(readCommunityDocumentRoute(value)).toBeNull()- })--})diff --git a/src/web/src/lib/community/document-route.ts b/src/web/src/lib/community/document-route.tsdeleted file mode 100644index 0e832f254..000000000--- a/src/web/src/lib/community/document-route.ts+++ /dev/null@@ -1,28 +0,0 @@-import { resolveCommunityModulePlan } from "./community-route"--export const COMMUNITY_DOCUMENT_ROUTE_HEADER = "x-alook-community-document-route"-const RESOURCE_ID = /^[A-Za-z0-9_-]{1,128}$/--export function communityDocumentRoute(url: URL): string | null {- const main = resolveCommunityModulePlan(url.pathname).main- if (!["bots", "machines", "dm", "server-landing", "server-conversation"].includes(main.kind)) return null- const params = new URLSearchParams()- const anchor = url.searchParams.get("msg")- if (anchor !== null) {- if (!RESOURCE_ID.test(anchor)) return null- params.set("msg", anchor)- }- const tag = url.searchParams.get("tag")- if (tag !== null) {- if (tag.length > 100 || /[\u0000-\u001f\u007f]/.test(tag)) return null- params.set("tag", tag)- }- const result = `${url.pathname}${params.size ? `?${params}` : ""}`- return result.length <= 2048 ? result : null-}--export function readCommunityDocumentRoute(value: string | null): string | null {- if (!value || !value.startsWith("/c/") || value.length > 2048) return null- const canonical = communityDocumentRoute(new URL(value, "https://alook.invalid"))- return canonical === value ? canonical : null-}diff --git a/src/web/src/lib/community/document-seed.rsc.test.ts b/src/web/src/lib/community/document-seed.rsc.test.tsdeleted file mode 100644index 04c8f5d57..000000000--- a/src/web/src/lib/community/document-seed.rsc.test.ts+++ /dev/null@@ -1,122 +0,0 @@-import { execFileSync } from "node:child_process"-import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"-import { createRequire } from "node:module"-import { tmpdir } from "node:os"-import path from "node:path"-import { build, transform } from "esbuild"-import ts from "typescript"-import { describe, expect, it } from "vitest"--const webRoot = path.resolve(import.meta.dirname, "../../..")-const require = createRequire(import.meta.url)-const clientProxy = require.resolve("next/dist/compiled/react-server-dom-turbopack/server.node")--async function runServerSeed(mode: "development" | "production") {- const directory = await mkdtemp(path.join(tmpdir(), "alook-document-rsc-"))- const output = path.join(directory, "seed.cjs")- const clients = new Set<string>()- try {- const result = await build({- absWorkingDir: webRoot,- stdin: {- resolveDir: webRoot,- contents: `- import assert from "node:assert/strict"- import { readCommunityDocumentSeed } from "@/lib/community/document-seed.server"- import { getCommunityRuntime } from "@/stores/community/runtime"- import { getCommunityRuntime as getOwner } from "@/stores/community/runtime-owner"- import { createCommunityDbRegistry } from "@/lib/community-db/collections"- import { QueryClient } from "@tanstack/react-query"- const profile = { id: "viewer", name: "Viewer", discriminator: "0042", avatar: null, avatarVersion: 0, aboutMe: "", bannerColor: null, statusEmoji: null, statusText: null }- async function main() {- assert.throws(() => getCommunityRuntime({}), /getCommunityRuntime.*from the server/)- for (const [href, kind] of [["/c/me", "me"], ["/c/channels/s1/c1", "text"], ["/c/channels/s1/c1", "forum"], ["/c/me/c1", "dm"], ["/c/channels/s1", "server"], ["/c/me/bots", "bots"], ["/c/me/machines", "machines"]]) {- const seed = await readCommunityDocumentSeed({ kind }, "viewer", href, profile)- assert.equal(seed.viewerId, "viewer")- assert.equal(seed.selfProfile.name, "Viewer")- assert.deepEqual(seed.db.collections, [])- assert.ok(seed.db.liveQueries.length >= 3)- assert.ok(seed.db.liveQueries.some(query => query.snapshot.rows.some(row => row.value.name === "Viewer")))- if (href.endsWith("/c1")) {- assert.equal(seed.entries.length, 1, href)- assert.equal(seed.entries[0].data.channel.type, kind)- assert.ok(JSON.stringify(seed.db.liveQueries).includes("Body"), href)- }- if (href.endsWith("/bots")) assert.deepEqual(seed.bots.bots, [])- if (href.endsWith("/machines")) assert.deepEqual(seed.machines.machines, [])- assert.deepEqual(JSON.parse(JSON.stringify(seed)), seed)- }- const isolated = await Promise.all(["alice", "bob"].map(id => readCommunityDocumentSeed({}, id, "/c/me", { ...profile, id, name: id })))- for (const [index, seed] of isolated.entries()) {- const other = isolated[1 - index].viewerId- assert.ok(!seed.db.liveQueries.some(query => query.snapshot.rows.some(row => row.value.id === other)))- }- const client = new QueryClient()- const registry = createCommunityDbRegistry(client, "viewer")- try {- assert.equal(getOwner(client), registry.runtime)- assert.throws(() => getOwner(new QueryClient()), error => error.name === "AbortError")- } finally { await registry.cleanup(); client.clear() }- assert.throws(() => getOwner(client), error => error.name === "AbortError")- process.stdout.write("server-seed-ok")- }- main().catch(error => { console.error(error); process.exitCode = 1 })- `,- },- bundle: true,- platform: "node",- format: "cjs",- write: false,- treeShaking: true,- external: ["react", clientProxy],- logLevel: "silent",- plugins: [{- name: "rsc-client-boundary",- setup(builder) {- builder.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, async ({ path: filename }) => {- const source = await readFile(filename, "utf8")- const directives = ts.createSourceFile(filename, source, ts.ScriptTarget.Latest, true).statements- let client = false- for (const statement of directives) {- if (!ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression)) break- if (statement.expression.text === "use client") client = true- }- if (client) {- clients.add(filename)- const compiled = await transform(source, { loader: filename.endsWith(".tsx") ? "tsx" : filename.endsWith(".ts") ? "ts" : "js", format: "esm" })- const parsed = ts.createSourceFile(filename, compiled.code, ts.ScriptTarget.Latest, true)- const names = parsed.statements.flatMap(statement => ts.isExportDeclaration(statement) && statement.exportClause && ts.isNamedExports(statement.exportClause) ? statement.exportClause.elements.map(element => element.name.text) : [])- return { contents: `import { createClientModuleProxy } from ${JSON.stringify(clientProxy)}; const proxy = createClientModuleProxy(${JSON.stringify(filename)}); ${names.map(name => name === "default" ? "export default proxy.default;" : `export const ${name} = proxy[${JSON.stringify(name)}];`).join("\n")}`, loader: "js" }- }- if (filename.endsWith("/community/message-door.ts")) return { contents: "export async function resolveMessageTarget(db, viewer, target) { return { ok: true, value: { access: { channel: { serverId: db.kind === 'dm' ? null : 's1' } } } } }", loader: "js" }- if (filename.endsWith("/community/conversation-entry.server.ts")) return {- contents: `import { conversationEntryFixture, dmConversationEntryFixture, forumConversationEntryFixture } from "@/test/conversation-entry-fixtures"; export async function readCommunityConversationEntry(db) { return { ok: true, entry: db.kind === "dm" ? dmConversationEntryFixture() : db.kind === "forum" ? forumConversationEntryFixture() : conversationEntryFixture() } }`, loader: "js",- }- if (filename.endsWith("/community/bots.server.ts")) return { contents: "export async function readCommunityBots() { return { bots: [], plan: { id: 'free', displayName: 'Free' }, isFounder: false, limit: 1, ownedCount: 0, activeCount: 0 } }", loader: "js" }- if (filename.endsWith("/community/machines.server.ts")) return { contents: "export async function readCommunityMachineList() { return { machines: [] } }", loader: "js" }- if (filename.endsWith("/community/server-directory.server.ts")) return { contents: "export async function readCommunityServerDirectory() { return { id: 's1', name: 'Server', discriminator: '0042', description: '', ownerId: 'viewer', icon: null, categories: [] } }", loader: "js" }- })- },- }],- })- await writeFile(output, result.outputFiles[0].contents)- const stdout = execFileSync(process.execPath, ["--conditions=react-server", output], {- cwd: webRoot,- env: { ...process.env, NODE_ENV: mode, NODE_PATH: path.join(webRoot, "node_modules") },- encoding: "utf8",- timeout: 20_000,- stdio: ["ignore", "pipe", "pipe"],- })- return { stdout, clients }- } finally {- await rm(directory, { recursive: true, force: true })- }-}--describe("document seed with native Next client references", () => {- it.each(["development", "production"] as const)("executes the server installer with %s client references and preserves its boundary", async mode => {- const result = await runServerSeed(mode)- expect(result.stdout).toBe("server-seed-ok")- expect(result.clients.has(path.join(webRoot, "src/stores/community/runtime.tsx"))).toBe(true)- })-})diff --git a/src/web/src/lib/community/document-seed.server.test.ts b/src/web/src/lib/community/document-seed.server.test.tsdeleted file mode 100644index 55f5e9c66..000000000--- a/src/web/src/lib/community/document-seed.server.test.ts+++ /dev/null@@ -1,240 +0,0 @@-import { useMessage } from "@/hooks/community/use-message"-import { useBots } from "@/hooks/community/use-bots"-import { createElement } from "react"-import { renderToString } from "react-dom/server"-import { QueryClient, QueryClientProvider } from "@tanstack/react-query"-import { beforeEach, describe, expect, it, vi } from "vitest"-import type { Database } from "@alook/shared"-import { conversationEntryFixture, conversationEntryTarget, forumConversationEntryFixture } from "@/test/conversation-entry-fixtures"-import { createCommunityDbRegistry } from "@/lib/community-db/collections"-import { CommunityDbProvider, useCanonicalCommunityProfile, useMessageWindowProjection, useRouteChannelProjection } from "@/lib/community-db/projections"-import { communityKeys } from "@/lib/query-keys"-import { installCommunityDocumentSeed } from "./document-seed"-import { conversationEntryOptions } from "./conversation-entry"-import { eq, getLiveQueryHash } from "@tanstack/react-db"-import { communityProjection } from "@/lib/community-db/live-query"-import { communityCollectionQuery } from "@/lib/community-db/queries"-import { useForumFeed } from "@/hooks/community/use-forum-feed"-import { useServerTreeProjection } from "@/lib/community-db/projections"--const mocks = vi.hoisted(() => ({ door: vi.fn(), entry: vi.fn(), bots: vi.fn(), machines: vi.fn(), server: vi.fn() }))-vi.mock("./message-door", () => ({ resolveMessageTarget: mocks.door }))-vi.mock("./conversation-entry.server", () => ({ readCommunityConversationEntry: mocks.entry }))-vi.mock("./bots.server", () => ({ readCommunityBots: mocks.bots }))-vi.mock("./machines.server", () => ({ readCommunityMachineList: mocks.machines }))-vi.mock("./server-directory.server", () => ({ readCommunityServerDirectory: mocks.server }))-vi.mock("@/hooks/community/use-channel-panels", () => ({ useForumTags: () => ({ data: { tags: [] }, isSuccess: true }) }))-import { readCommunityDocumentSeed } from "./document-seed.server"--export const selfProfile = { id: "viewer", name: "Viewer", discriminator: "0042", avatar: "/avatar", avatarVersion: 7, aboutMe: "About", bannerColor: null, statusEmoji: null, statusText: "Available" }-const db = {} as Database--beforeEach(() => {- mocks.door.mockReset().mockResolvedValue({ ok: true, value: { access: { channel: { serverId: "s1" } } } })- mocks.entry.mockReset().mockResolvedValue({ ok: true, entry: conversationEntryFixture() })- mocks.bots.mockReset().mockResolvedValue({ bots: [], plan: { id: "free", displayName: "Free" }, isFounder: false, limit: 1, ownedCount: 0, activeCount: 0 })- mocks.machines.mockReset().mockResolvedValue({ machines: [] })- mocks.server.mockReset().mockResolvedValue({ id: "s1", name: "Server", discriminator: "0042", description: "", ownerId: "viewer", icon: null, categories: [{ id: "cat", name: "Category", private: false, channels: [{ id: "c1", type: "text", name: "Channel", active: false, unread: false }] }] })-})--function Probe() {- const self = useCanonicalCommunityProfile("viewer")- const channel = useRouteChannelProjection("c1")- const messages = useMessageWindowProjection("c1", ["m1"], [])- return createElement("span", null, `${self?.name}:${channel?.name}:${messages.canonicalMessages?.[0]?.content}`)-}--describe("document resource handoff", () => {- it("leaves an unresolved Forum selection to the client instead of seeding All", async () => {- mocks.door.mockResolvedValue({ ok: true, value: { access: { channel: { serverId: "s1", type: "forum" } } } })- const seed = await readCommunityDocumentSeed(db, "viewer", "/c/channels/s1/c1", selfProfile)- expect(seed.entries).toEqual([])- expect(mocks.entry).not.toHaveBeenCalled()- })-- it.each([["", undefined], ["BUG", "bug"]])("uses explicit Forum tag=%s for its seed window", async (tag, expected) => {- mocks.door.mockResolvedValue({ ok: true, value: { access: { channel: { serverId: "s1", type: "forum" } } } })- mocks.entry.mockResolvedValue({ ok: true, entry: forumConversationEntryFixture() })- const seed = await readCommunityDocumentSeed(db, "viewer", `/c/channels/s1/c1?tag=${tag}`, selfProfile)- expect(mocks.entry).toHaveBeenCalledWith(db, expect.objectContaining({ tag: expected }))- expect(seed.entries[0].target.tag).toBe(expected ?? null)- })-- it.each(["forum", "server"])("renders the actual %s projection from its document snapshot while source restore is pending", async kind => {- if (kind === "forum") mocks.entry.mockResolvedValue({ ok: true, entry: forumConversationEntryFixture() })- const seed = await readCommunityDocumentSeed(db, "viewer", kind === "forum" ? "/c/channels/s1/c1?tag=" : "/c/channels/s1", selfProfile)- const client = new QueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })- let release!: () => void- const registry = createCommunityDbRegistry(client, "viewer", { waitForRestore: new Promise<void>(resolve => { release = resolve }) })- installCommunityDocumentSeed(client, registry, seed, "viewer")- function Forum() { const feed = useForumFeed("s1", "c1", { routeTag: "" }); return createElement("span", null, feed.posts.map(post => post.name).join("|")) }- function Server() { const tree = useServerTreeProjection("s1"); return createElement("span", null, `${tree?.name}:${tree?.categories[0]?.channels[0]?.name}`) }- try {- const html = renderToString(createElement(QueryClientProvider, { client }, createElement(CommunityDbProvider, { registry }, createElement(kind === "forum" ? Forum : Server))))- expect(html).toBe(kind === "forum" ? "<span>Body</span>" : "<span>Server:Channel</span>")- if (kind === "server") expect(mocks.server).toHaveBeenCalledWith(db, "viewer", "s1")- } finally { release(); await registry.preload(); await registry.cleanup(); client.clear() }- })- it.each(["bots", "machines"])("loads the opened %s list and its view dependencies through shared loaders", async kind => {- const seed = await readCommunityDocumentSeed(db, "viewer", `/c/me/${kind}`, selfProfile)- expect(mocks[kind]).toHaveBeenCalledWith(db, "viewer")- if (kind === "bots") expect(mocks.machines).toHaveBeenCalledWith(db, "viewer")- else expect(mocks.bots).not.toHaveBeenCalled()- expect(mocks.door).not.toHaveBeenCalled()- const client = new QueryClient()- const registry = createCommunityDbRegistry(client, "viewer")- installCommunityDocumentSeed(client, registry, seed, "viewer")- expect(client.getQueryData(kind === "bots" ? communityKeys.bots() : communityKeys.machines())).toMatchObject({ [kind]: [] })- await registry.cleanup()- client.clear()- })- it.each(["matching", "missing", "mismatched"])("isolates %s native live-query snapshots with empty client sources and no canonical installer", async mode => {- const seed = await readCommunityDocumentSeed(db, "viewer", "/c/channels/s1/c1", selfProfile)- const state = { collections: [], liveQueries: mode === "missing" ? [] : seed.db.liveQueries?.map(query => ({ ...query, queryHash: mode === "mismatched" ? `wrong:${query.queryHash}` : query.queryHash })) }- const client = new QueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })- let release!: () => void- const registry = createCommunityDbRegistry(client, "viewer", { waitForRestore: new Promise<void>(resolve => { release = resolve }) })- registry.dbClient.hydrate(state)- try {- expect(client.getQueryData(communityKeys.communityDbCollection("viewer", "profiles"))).toBeUndefined()- expect(client.getQueryData(communityKeys.communityDbCollection("viewer", "channels"))).toBeUndefined()- expect(client.getQueryData(communityKeys.communityDbCollection("viewer", "messages"))).toBeUndefined()- expect(registry.collections.profiles.size).toBe(0)- expect(registry.collections.channels.size).toBe(0)- expect(registry.collections.messages.size).toBe(0)- const html = renderToString(createElement(QueryClientProvider, { client }, createElement(CommunityDbProvider, { registry }, createElement(Probe))))- expect(html).toBe(mode === "matching" ? "<span>Viewer:Channel:Body</span>" : "<span>undefined:undefined:undefined</span>")- expect(registry.collections.profiles.size).toBe(0)- expect(registry.collections.channels.size).toBe(0)- expect(registry.collections.messages.size).toBe(0)- } finally {- release()- await registry.preload()- await registry.cleanup()- client.clear()- }- })- it("serializes resolved native snapshots before server cleanup and renders real canonical hooks before disk restore", async () => {- const errors = vi.spyOn(console, "error").mockImplementation(() => undefined)- const seed = await readCommunityDocumentSeed(db, "viewer", "/c/channels/s1/c1", selfProfile)- expect(seed.db.collections).toEqual([])- expect(seed.db.liveQueries?.length).toBeGreaterThan(0)- expect(mocks.door).toHaveBeenCalledWith(db, "viewer", { id: "c1" }, "human", "read")- let release!: () => void- const client = new QueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })- const registry = createCommunityDbRegistry(client, "viewer", { waitForRestore: new Promise<void>(resolve => { release = resolve }) })- try {- expect(installCommunityDocumentSeed(client, registry, JSON.parse(JSON.stringify(seed)), "viewer")).toBe(true)- const view = communityProjection(registry, communityCollectionQuery(registry, "profiles", ({ row }) => eq(row.id, "viewer")))!- expect(seed.db.liveQueries?.find(query => query.queryHash === getLiveQueryHash(view.collection))?.snapshot?.rows).toEqual([expect.objectContaining({ value: expect.objectContaining({ name: "Viewer" }) })])- const resource = client.getQueryData(conversationEntryOptions(client, conversationEntryTarget).queryKey)- expect(resource).toBeDefined()- expect(client.getQueryData(communityKeys.selfProfile())).toEqual({ id: "viewer" })- const html = renderToString(createElement(QueryClientProvider, { client }, createElement(CommunityDbProvider, { registry }, createElement(Probe))))- expect(html).toBe("<span>Viewer:Channel:Body</span>")- } finally {- release()- await registry.preload()- await registry.cleanup()- client.clear()- const captured = errors.mock.calls- errors.mockRestore()- expect(captured).toEqual([])- }- })-- it.each(["other", null])("rejects a seed before native hydrate for current session %s", async viewer => {- const seed = await readCommunityDocumentSeed(db, "viewer", null, selfProfile)- const client = new QueryClient()- const registry = createCommunityDbRegistry(client, "viewer")- const hydrate = vi.spyOn(registry.dbClient, "hydrate")- expect(installCommunityDocumentSeed(client, registry, seed, viewer)).toBe(false)- expect(hydrate).not.toHaveBeenCalled()- expect(client.getQueryData(communityKeys.selfProfile())).toBeUndefined()- await registry.cleanup()- client.clear()- })-- it.each([403, 404])("does not serialize denied conversation data (%s)", async status => {- mocks.door.mockResolvedValue({ ok: false, status, error: "denied" })- const seed = await readCommunityDocumentSeed(db, "viewer", "/c/channels/s1/c1", selfProfile)- expect(seed.entries).toEqual([])- expect(mocks.entry).not.toHaveBeenCalled()- expect(JSON.stringify(seed)).not.toContain("Body")- })-- it("preserves the authenticated self seed when only the target prefetch fails", async () => {- mocks.entry.mockRejectedValue(new Error("temporary read failure"))- const warn = vi.spyOn(console, "warn").mockImplementation(() => {})- try {- const seed = await readCommunityDocumentSeed(db, "viewer", "/c/channels/s1/c1", selfProfile)- expect(seed.selfProfile).toEqual(selfProfile)- expect(seed.entries).toEqual([])- expect(JSON.stringify(seed)).not.toContain("Body")- expect(warn).toHaveBeenCalledWith("[community] document resource prefetch unavailable", { kind: "server-conversation", phase: "read-entry", channelId: "c1", generatedAt: seed.generatedAt })- } finally { warn.mockRestore() }- })-- it.each(["resolve-target", "read-entry", "read-module"] as const)("correlates %s failures without logging private error material", async phase => {- const privateError = new Error("session=private-credential; query=private-body")- const warn = vi.spyOn(console, "warn").mockImplementation(() => {})- mocks.door.mockResolvedValue({ ok: true, value: { access: { channel: { serverId: null } } } })- if (phase === "resolve-target") mocks.door.mockRejectedValue(privateError)- if (phase === "read-entry") mocks.entry.mockRejectedValue(privateError)- if (phase === "read-module") mocks.machines.mockRejectedValue(privateError)- try {- const seed = await readCommunityDocumentSeed(db, "viewer", phase === "read-module" ? "/c/me/machines" : "/c/me/dm?msg=private-anchor", selfProfile)- expect(seed.selfProfile).toEqual(selfProfile)- expect(seed.entries).toEqual([])- expect(warn).toHaveBeenCalledExactlyOnceWith("[community] document resource prefetch unavailable", {- kind: phase === "read-module" ? "machines" : "dm", phase,- channelId: phase === "read-module" ? null : "dm", generatedAt: seed.generatedAt,- })- expect(JSON.stringify(warn.mock.calls)).not.toMatch(/private-|session=|query=/)- if (phase === "resolve-target") expect(mocks.entry).not.toHaveBeenCalled()- } finally { warn.mockRestore() }- })-- it("seeds the child identity and opener without waiting for the independent parent window", async () => {- const entry = conversationEntryFixture()- entry.channel = { ...entry.channel, type: "thread", parentChannelId: "parent", parentMessageId: "opener" }- entry.surfaceReceipt.surfaceKind = "thread"- entry.parent = { ...entry.channel, id: "parent", type: "text", parentChannelId: null, parentMessageId: null }- entry.opener = { ...entry.messages[0], id: "opener", channelId: "parent" }- mocks.entry.mockResolvedValue({ ok: true, entry })- const seed = await readCommunityDocumentSeed(db, "viewer", "/c/channels/s1/c1", selfProfile)- expect(seed.entries).toHaveLength(1)- expect(seed.entries[0].data.opener?.id).toBe("opener")- expect(mocks.entry).toHaveBeenCalledOnce()- const client = new QueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })- let release!: () => void- const registry = createCommunityDbRegistry(client, "viewer", { waitForRestore: new Promise<void>(resolve => { release = resolve }) })- installCommunityDocumentSeed(client, registry, seed, "viewer")- function ChildContext() {- const parent = useRouteChannelProjection("parent"), opener = useMessage("opener", { serverId: "s1" })- return createElement("span", null, `${parent?.name}:${opener.message?.content}`)- }- try {- expect(renderToString(createElement(QueryClientProvider, { client }, createElement(CommunityDbProvider, { registry }, createElement(ChildContext))))).toContain("Channel:Body")- } finally { release(); await registry.ready; await registry.cleanup(); client.clear() }- })-- it("renders a populated bots list through the actual hook before source restore", async () => {- mocks.bots.mockResolvedValue({ bots: [{ id: "bot", name: "Canonical bot", description: "About", image: null, avatarVersion: 3, machineId: "machine", runtime: "codex", modelName: null, reasoningEffort: null, runtimeConfigRevision: 1, isActive: true, presence: "online" }], plan: { id: "free", displayName: "Free" }, isFounder: false, limit: 1, ownedCount: 1, activeCount: 1 })- const seed = await readCommunityDocumentSeed(db, "viewer", "/c/me/bots", selfProfile)- const client = new QueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })- let release!: () => void- const registry = createCommunityDbRegistry(client, "viewer", { waitForRestore: new Promise<void>(resolve => { release = resolve }) })- installCommunityDocumentSeed(client, registry, seed, "viewer")- function Bots() { const view = useBots(); return createElement("span", null, `${view.bots[0]?.name}:${view.profilesPending}:${view.data?.source}`) }- try {- expect(renderToString(createElement(QueryClientProvider, { client }, createElement(CommunityDbProvider, { registry }, createElement(Bots))))).toContain("Canonical bot:false:rsc")- } finally { release(); await registry.ready; await registry.cleanup(); client.clear() }- })-- it("uses the authorized server scope rather than trusting the route selector", async () => {- const seed = await readCommunityDocumentSeed(db, "viewer", "/c/channels/foreign/c1", selfProfile)- expect(seed.entries).toEqual([])- expect(mocks.entry).not.toHaveBeenCalled()- })-})diff --git a/src/web/src/lib/community/document-seed.server.ts b/src/web/src/lib/community/document-seed.server.tsdeleted file mode 100644index ddc54d67e..000000000--- a/src/web/src/lib/community/document-seed.server.ts+++ /dev/null@@ -1,119 +0,0 @@-import { QueryClient } from "@tanstack/react-query"-import { and, eq, inArray } from "@tanstack/react-db"-import type { Database } from "@alook/shared"-import { createCommunityDbRegistry } from "@/lib/community-db/collections"-import { communityCollectionQuery, communityJoinedMessagesQuery } from "@/lib/community-db/queries"-import { dehydrateCommunityProjections, preloadCommunityProjection } from "@/lib/community-db/live-query"-import { communityKeys } from "@/lib/query-keys"-import { resolveCommunityModulePlan } from "./community-route"-import { readCommunityDocumentRoute } from "./document-route"-import { installCommunityDocumentSeed, type CommunityDocumentSeed } from "./document-seed"-import { resolveMessageTarget } from "./message-door"-import { readCommunityConversationEntry } from "./conversation-entry.server"-import { parseCommunityMessageWindow } from "./messages"-import type { CommunitySelfProfile } from "./self-profile.server"-import { readCommunityBots } from "./bots.server"-import { readCommunityMachineList } from "./machines.server"-import { readCommunityServerDirectory } from "./server-directory.server"-import { forumTagFromUrl } from "./forum-tag-selection"--export async function readCommunityDocumentSeed(db: Database, viewerId: string, href: string | null, selfProfile: CommunitySelfProfile): Promise<CommunityDocumentSeed> {- const seed: CommunityDocumentSeed = { viewerId, href: readCommunityDocumentRoute(href), generatedAt: Date.now(), selfProfile, entries: [], db: { collections: [] } }- const main = seed.href ? resolveCommunityModulePlan(seed.href).main : { kind: "none" as const }- const channelId = main.kind === "dm" ? main.dmId : main.kind === "server-conversation" ? main.leafId : null- const serverId = main.kind === "server-conversation" ? main.serverId : null- let phase: "read-module" | "resolve-target" | "read-entry" = "read-module"- try {- if (main.kind === "bots") {- const [bots, machines] = await Promise.allSettled([- readCommunityBots(db, viewerId),- readCommunityMachineList(db, viewerId),- ])- if (bots.status === "fulfilled") seed.bots = bots.value- if (machines.status === "fulfilled") seed.machines = machines.value- if (bots.status === "rejected") throw bots.reason- if (machines.status === "rejected") throw machines.reason- }- if (main.kind === "machines") seed.machines = await readCommunityMachineList(db, viewerId)- if (main.kind === "server-landing") seed.server = await readCommunityServerDirectory(db, viewerId, main.serverId)- if (channelId && seed.href) {- const url = new URL(seed.href, "https://alook.invalid")- const anchorMessageId = url.searchParams.get("msg")- const tag = url.searchParams.get("tag")?.trim().toLowerCase() || undefined- const read = async (id: string, anchor?: string | null, filter?: string) => {- phase = "resolve-target"- const resolved = await resolveMessageTarget(db, viewerId, { id }, "human", "read")- if (!resolved.ok || resolved.value.access.channel.serverId !== serverId) return- if (resolved.value.access.channel.type === "forum") {- const selected = forumTagFromUrl(url.searchParams.get("tag"))- if (selected === null) return- filter = selected === "All" ? undefined : selected- }- const params = new URLSearchParams(anchor ? { anchor } : undefined)- phase = "read-entry"- const result = await readCommunityConversationEntry(db, { viewerId, target: resolved.value, window: parseCommunityMessageWindow(params), tag: filter, preferTail: false })- if (result.ok) seed.entries.push({ target: { channelId: id, serverId, anchorMessageId: anchor ?? null, tag: filter ?? null }, data: result.entry })- return result.ok ? result.entry : undefined- }- await read(channelId, anchorMessageId, tag)- }- } catch {- console.warn("[community] document resource prefetch unavailable", { kind: main.kind, phase, channelId, generatedAt: seed.generatedAt })- }- const client = new QueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })- const registry = createCommunityDbRegistry(client, viewerId)- try {- installCommunityDocumentSeed(client, registry, seed, viewerId)- await registry.preload()- const descriptors: unknown[] = [- communityCollectionQuery(registry, "profiles", ({ row }) => eq(row.id, viewerId)),- communityCollectionQuery(registry, "profiles", () => eq(1, 1)),- communityCollectionQuery(registry, "channels"),- ]- const authorIds = new Set(Array.from(registry.collections.messages.values()).flatMap(message => message.authorId ? [message.authorId] : []))- for (const authorId of authorIds) descriptors.push(communityCollectionQuery(registry, "profiles", ({ row }) => eq(row.id, authorId)))- for (const { target, data } of seed.entries) {- const channelId = target.channelId- descriptors.push(communityCollectionQuery(registry, "channels", ({ row }) => eq(row.id, channelId)))- if (data.parent) descriptors.push(communityCollectionQuery(registry, "channels", ({ row }) => eq(row.id, data.parent!.id)))- if (data.forumFeed) continue- const resource = client.getQueryCache().findAll({ queryKey: communityKeys.conversationEntries(channelId) })[0]?.state.data as { windowKey: readonly unknown[] } | undefined- const window = resource ? client.getQueryData<{ pages: Array<{ messages: Array<{ id: string }> }> }>(resource.windowKey) : undefined- const ids = window?.pages.flatMap(page => page.messages.map(message => message.id)) ?? []- descriptors.push(communityJoinedMessagesQuery(registry, channelId, ids))- }- for (const { data } of seed.entries) if (data.forumFeed) {- const ids = data.forumFeed.threads.flatMap(thread => thread.parentMessageId ? [thread.parentMessageId] : [])- descriptors.push(communityJoinedMessagesQuery(registry, undefined, ids))- }- for (const { data } of seed.entries) if (data.opener) {- descriptors.push(communityJoinedMessagesQuery(registry, undefined, [data.opener.id]))- if (data.opener.authorId) descriptors.push(communityCollectionQuery(registry, "profiles", ({ row }) => eq(row.id, data.opener!.authorId)))- }- const dmIds = seed.entries.filter(entry => entry.data.channel.type === "dm").map(entry => entry.data.channelId)- if (seed.bots) descriptors.push(communityCollectionQuery(registry, "profiles", ({ row }) => inArray(row.id, seed.bots!.bots.map(bot => bot.id))))- if (seed.server) {- const serverId = seed.server.id- descriptors.push(- communityCollectionQuery(registry, "servers", ({ row }) => eq(row.id, serverId)),- communityCollectionQuery(registry, "categories", ({ row }) => eq(row.serverId, serverId)),- communityCollectionQuery(registry, "channels", ({ row }) => and(eq(row.serverId, serverId), eq(1, 1))),- )- }- if (dmIds.length) {- const peers = seed.entries.flatMap(entry => entry.data.peer ? [entry.data.peer.id] : [])- descriptors.push(- communityCollectionQuery(registry, "channels", ({ row }) => and(eq(1, 1), eq(row.type, "dm"))),- communityCollectionQuery(registry, "channelMemberships", ({ row }) => inArray(row.channelId, dmIds)),- communityCollectionQuery(registry, "profiles", ({ row }) => inArray(row.id, peers)),- communityCollectionQuery(registry, "readStates", ({ row }) => inArray(row.channelId, dmIds)),- )- }- const bindings = await Promise.all(descriptors.map(descriptor => preloadCommunityProjection(registry, descriptor)))- const state = dehydrateCommunityProjections(registry, bindings)- return JSON.parse(JSON.stringify({ ...seed, db: { ...state, collections: [] } })) as CommunityDocumentSeed- } finally {- await registry.cleanup()- client.clear()- }-}diff --git a/src/web/src/lib/community/document-seed.ts b/src/web/src/lib/community/document-seed.tsdeleted file mode 100644index 93f11f4f6..000000000--- a/src/web/src/lib/community/document-seed.ts+++ /dev/null@@ -1,69 +0,0 @@-import type { QueryClient, QueryKey } from "@tanstack/react-query"-import type { CommunityConversationEntryRead } from "@alook/shared"-import type { CommunityDbRegistry } from "@/lib/community-db/collections"-import { assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken, publishCommunityLiveSnapshot } from "@/lib/community-db/sync"-import { communityKeys } from "@/lib/query-keys"-import { writeCommunityProfilePatches } from "./profile-seed"-import { publishConversationEntry, type ConversationEntryTarget } from "./conversation-entry"-import type { CommunitySelfProfile } from "./self-profile.server"-import { readCommunityDocumentRoute } from "./document-route"-import { botProfilePatch, botsResource, type BotsResponse } from "./bots"-import type { MachinesResponse } from "@/hooks/community/use-machines"-import type { ServerDetail } from "@/hooks/community/use-servers"--export type CommunityDocumentSeed = {- viewerId: string- href: string | null- generatedAt: number- selfProfile: CommunitySelfProfile- entries: Array<{ target: ConversationEntryTarget; data: CommunityConversationEntryRead }>- bots?: BotsResponse- machines?: MachinesResponse- server?: ServerDetail- db: Parameters<CommunityDbRegistry["dbClient"]["hydrate"]>[0]-}--export type CommunityDocumentSeedInput = CommunityDocumentSeed | Promise<CommunityDocumentSeed | null>--export function installCommunityDocumentSeed(client: QueryClient, registry: CommunityDbRegistry, seed: CommunityDocumentSeed, sessionViewer: string | null | undefined, delivery?: {- token: ReturnType<typeof captureCommunityLiveSnapshotToken>- presence: ReturnType<CommunityDbRegistry["runtime"]["ws"]["actions"]["beginPresenceSnapshot"]>-}) {- if (seed.viewerId !== registry.accountId || seed.selfProfile.id !== registry.accountId || sessionViewer !== undefined && sessionViewer !== registry.accountId- || seed.href !== null && readCommunityDocumentRoute(seed.href) !== seed.href) return false- const original = delivery?.token ?? captureCommunityLiveSnapshotToken(client)- assertCommunityLiveSnapshotTokenCurrent(client, original, undefined)- const seedResource = (key: QueryKey, data: unknown) => {- if (!delivery || client.getQueryData(key) === undefined) client.setQueryData(key, data, { updatedAt: seed.generatedAt })- }- const profile = seed.selfProfile- writeCommunityProfilePatches([{- id: profile.id,- identityAbout: { name: profile.name, discriminator: profile.discriminator, aboutMe: profile.aboutMe, bannerColor: profile.bannerColor },- avatar: { avatar: profile.avatar, avatarVersion: profile.avatarVersion },- status: { statusEmoji: profile.statusEmoji, statusText: profile.statusText },- }], registry, { snapshot: original.profileSnapshot })- seedResource(communityKeys.selfProfile(), { id: profile.id })- if (seed.bots) {- writeCommunityProfilePatches(seed.bots.bots.map(botProfilePatch), registry, { snapshot: original.profileSnapshot })- registry.runtime.ws.actions.seedPresence(delivery?.presence ?? registry.runtime.ws.actions.beginPresenceSnapshot(), seed.bots.bots.flatMap(bot => bot.presence ? [[bot.id, bot.presence] as const] : []))- seedResource(communityKeys.bots(), { ...botsResource(seed.bots), source: "rsc" })- }- if (seed.machines) seedResource(communityKeys.machines(), { ...seed.machines, source: "rsc" })- if (seed.server) {- publishCommunityLiveSnapshot(client, { snapshot: { kind: "server-detail", data: seed.server }, proof: { kind: "structural", token: original, signal: undefined } })- seedResource(communityKeys.server(seed.server.id), seed.server.id)- }- for (const { target, data } of seed.entries) {- const token = { ...original, channelId: target.channelId }- const resource = publishConversationEntry(client, target, data, { token }, "rsc")- seedResource(communityKeys.conversationEntry(target.channelId, target, {- accountEpoch: original.accountEpoch, accessEpoch: original.accessEpoch,- channelGeneration: original.channelScopes.get(target.channelId)?.generation ?? 0,- }), resource)- }- assertCommunityLiveSnapshotTokenCurrent(client, original, undefined)- if (!delivery) registry.dbClient.hydrate(seed.db)- return true-}-diff --git a/src/web/src/lib/community/navigation.dom.test.tsx b/src/web/src/lib/community/navigation.dom.test.tsxnew file mode 100644index 000000000..a249ae0ce--- /dev/null+++ b/src/web/src/lib/community/navigation.dom.test.tsx@@ -0,0 +1,37 @@+import { useLayoutEffect } from "react"+import { beforeEach, describe, expect, it, vi } from "vitest"+import { act, render } from "@/test/react-dom-harness"+import { CommunityApplicationNavigation } from "@/contexts/community/application-navigation"+import { useCommunityHistoryRouter } from "./navigation"+const mocks = vi.hoisted(() => ({ router: { push: vi.fn(), replace: vi.fn(), refresh: vi.fn(), back: vi.fn(), forward: vi.fn(), prefetch: vi.fn() } }))+vi.mock("next/navigation", () => ({ useRouter: () => mocks.router }))+let current: ReturnType<typeof useCommunityHistoryRouter>+function Probe() { const router = useCommunityHistoryRouter(); useLayoutEffect(() => { current = router }, [router]); return null }+beforeEach(() => { vi.clearAllMocks(); window.history.replaceState(null, "", "/c/me/friends") })+describe("documented History router host", () => {+ it("preserves the framework router at providerless and preview boundaries", () => {+ render(<Probe />)+ expect(current).toBe(mocks.router)+ current.push("/c/me/bots")+ expect(mocks.router.push).toHaveBeenCalledExactlyOnceWith("/c/me/bots")+ })+ it("publishes complete app URLs without waiting for or requesting a framework route", () => {+ render(<CommunityApplicationNavigation value={true}><Probe /></CommunityApplicationNavigation>)+ const length = window.history.length+ act(() => current.push("/c/channels/server/forum?seq=42#message-42", { scroll: false }))+ expect(window.location.pathname + window.location.search + window.location.hash).toBe("/c/channels/server/forum?seq=42#message-42")+ expect(window.history.length).toBe(length + 1)+ act(() => current.replace("/c/channels/server"))+ expect(window.location.pathname).toBe("/c/channels/server")+ expect(window.history.length).toBe(length + 1)+ expect(mocks.router.push).not.toHaveBeenCalled()+ expect(mocks.router.replace).not.toHaveBeenCalled()+ expect(mocks.router.prefetch).not.toHaveBeenCalled()+ })+ it.each(["/c/invite/token", "/sign-in", "/auth/native/return", "https://other.test/c/me", "/c/invalid/extra"])("leaves %s to normal document routing", href => {+ render(<CommunityApplicationNavigation value={true}><Probe /></CommunityApplicationNavigation>)+ current.replace(href)+ expect(mocks.router.replace).toHaveBeenCalledExactlyOnceWith(href)+ expect(window.location.pathname).toBe("/c/me/friends")+ })+})diff --git a/src/web/src/lib/community/navigation.ts b/src/web/src/lib/community/navigation.tsnew file mode 100644index 000000000..0cce9c633--- /dev/null+++ b/src/web/src/lib/community/navigation.ts@@ -0,0 +1,27 @@+"use client"++import { useContext, useMemo } from "react"+import { useRouter } from "next/navigation"+import { CommunityApplicationNavigation } from "@/contexts/community/application-navigation"+import { isCommunityApplicationPath } from "./application-route"++export function useCommunityHistoryRouter() {+ const router = useRouter()+ const application = useContext(CommunityApplicationNavigation)+ const local = useMemo(() => {+ const navigate = (method: "push" | "replace", href: string, options?: { scroll?: boolean }) => {+ const url = new URL(href, window.location.href)+ if (url.origin !== window.location.origin || !isCommunityApplicationPath(url.pathname)) {+ if (options) router[method](href, options)+ else router[method](href)+ return+ }+ window.history[method === "push" ? "pushState" : "replaceState"](null, "", `${url.pathname}${url.search}${url.hash}`)+ }+ return { ...router,+ push: (href: string, options?: { scroll?: boolean }) => navigate("push", href, options),+ replace: (href: string, options?: { scroll?: boolean }) => navigate("replace", href, options),+ }+ }, [router])+ return application ? local : router+}diff --git a/src/web/src/lib/community/self-profile.server.ts b/src/web/src/lib/community/self-profile.server.tsindex 978728e29..fb359c7c8 100644--- a/src/web/src/lib/community/self-profile.server.ts+++ b/src/web/src/lib/community/self-profile.server.ts@@ -19,5 +19,3 @@ export async function readCommunitySelfProfile(db: Database, userId: string) {statusText: profile?.statusText ?? "",} }}--export type CommunitySelfProfile = Awaited<ReturnType<typeof readCommunitySelfProfile>>["profile"]diff --git a/src/web/src/lib/native-oauth-authenticated-cleanup.test.ts b/src/web/src/lib/native-oauth-authenticated-cleanup.test.tsindex ef45a4d30..7ee3e23d8 100644--- a/src/web/src/lib/native-oauth-authenticated-cleanup.test.ts+++ b/src/web/src/lib/native-oauth-authenticated-cleanup.test.ts@@ -190,7 +190,8 @@ describe("cleanupAuthenticatedNativeOauthResidue", () => {const communityLayout = readFileSync(new URL("../app/c/layout.tsx", import.meta.url), "utf8")const communityClient = readFileSync(new URL("../app/c/community-layout-client.tsx", import.meta.url), "utf8")- expect(communityLayout).toContain("await getSession()")+ expect(communityLayout).not.toContain("getSession")+ expect(communityClient).toContain("const session = useSession()")expect(communityClient.indexOf("if (!currentUser)")).toBeLessThan(communityClient.indexOf("<AuthenticatedNativeOauthCleanup />"),)diff --git a/src/web/src/lib/observability/coverage.test.ts b/src/web/src/lib/observability/coverage.test.tsindex e7246279c..37e67ef27 100644--- a/src/web/src/lib/observability/coverage.test.ts+++ b/src/web/src/lib/observability/coverage.test.ts@@ -4,6 +4,7 @@ import ts from "typescript"import { expect, it } from "vitest"import { actionNames, apiRoutes, pageRoutes, routeTemplate } from "./coverage"import { actionVariants } from "./actions"+import { resolveCommunityModulePlan } from "../community/community-route"const web = resolve(import.meta.dirname, "../../..")const files = (root: string) => readdirSync(root, { recursive: true }).filter((file): file is string => typeof file === "string" && /\.tsx?$/.test(file)).map(file => resolve(root, file))@@ -12,7 +13,13 @@ it("normalizes the ordinary message route without retaining a message ID or quer})it("keeps the route whitelist aligned with both builds and parallel route slots", () => {const routes = new Set(["src/app", "blog/src/app"].flatMap(root => files(resolve(web, root)).filter(file => file.endsWith("/page.tsx")).map(file => "/" + relative(resolve(web, root), file).split("/").slice(0, -1).filter(segment => !segment.startsWith("(") && !segment.startsWith("@")).join("/"))))- expect([...routes].sort()).toEqual([...pageRoutes].sort())+ expect([...routes].filter(route => !/^\/c(?:\/|$)/.test(route)).sort()).toEqual(pageRoutes.filter(route => !/^\/c(?:\/|$)/.test(route)).sort())+ expect([...routes].filter(route => route === "/c" || route.startsWith("/c/")).sort()).toEqual(["/c", "/c/[...path]", "/c/invite/[token]"])+ for (const route of pageRoutes.filter(route => route === "/c" || route.startsWith("/c/"))) {+ const concrete = route.replace(/\[[^\]]+\]/g, "fixture-id")+ expect(resolveCommunityModulePlan(concrete).route, concrete).not.toBe("unknown")+ expect(routeTemplate(concrete), concrete).toBe(route)+ }})it("keeps the API whitelist aligned with the current route files", () => {const root = resolve(web, "src/app/api")@@ -38,7 +45,7 @@ it("keeps existing mutation owners inventoried and semantic variants on the whitconst mutationCoverage = [{ "file": "src/web/src/hooks/community/mutations/bot-creation.ts", "owner": "useBotCreationDecision", "action": "bot.creation.decision" },{- "file": "src/web/src/app/c/invite/[token]/invite-accept-client.tsx",+ "file": "src/web/src/app/(public-community)/c/invite/[token]/invite-accept-client.tsx","owner": "InviteAcceptInner","action": "server.invite.accept"},diff --git a/src/web/src/lib/service-worker/community-shell.test.ts b/src/web/src/lib/service-worker/community-shell.test.tsnew file mode 100644index 000000000..ae32ececf--- /dev/null+++ b/src/web/src/lib/service-worker/community-shell.test.ts@@ -0,0 +1,45 @@+import { createHash } from "node:crypto"+import { describe, expect, it } from "vitest"+import { communityShellHash, isCommunityShellAssetRequest, isCommunityShellNavigation, isCommunityShellResponse } from "./community-shell"++const origin = "https://alook.test"+const html = '<html><main data-community-shell="public">Loading</main></html>'+const hash = createHash("sha256").update(html).digest("hex")+const shell = `/community-shell/${hash}`+const request = (pathname: string, headers?: HeadersInit) => new Request(`${origin}${pathname}`, { headers })+function navigation(pathname: string, headers?: HeadersInit) {+ const req = request(pathname, headers)+ Object.defineProperty(req, "mode", { value: "navigate" })+ return req+}+const response = (headers: HeadersInit = {}, body = html) => new Response(body, { headers: { "Cache-Control": "public, max-age=31536000, immutable", "Content-Type": "text/html; charset=utf-8", ...headers } })++describe("immutable anonymous community shell", () => {+ it("uses an exact content hash URL rather than admitting arbitrary HTML", () => {+ expect(communityShellHash(shell)).toBe(hash)+ for (const path of ["/c", "/app.html", `${shell}.html`, `${shell}/`, "/community-shell/../c", `/community-shell/${hash.toUpperCase()}`]) expect(communityShellHash(path), path).toBeUndefined()+ expect(isCommunityShellAssetRequest(request(shell), origin, shell)).toBe(true)+ for (const req of [request(`${shell}?user=a`), request(shell, { Cookie: "session=fixture" }), request(shell, { RSC: "1" }), request(shell, { Authorization: "fixture" }), navigation(shell), new Request(`https://other.test${shell}`)]) expect(isCommunityShellAssetRequest(req, origin, shell)).toBe(false)+ })+ it.each(["/c", "/c/me", "/c/me/machines", "/c/me/bots", "/c/me/friends", "/c/me/dm-a?seq=3", "/c/channels/s", "/c/channels/s/forum-a", "/c/channels/s/settings", "/c/messages/message-a"])("serves the same public shell for a known navigation %s", path => {+ expect(isCommunityShellNavigation(navigation(path, { Cookie: "session=fixture" }), origin)).toBe(true)+ })+ it.each(["/", "/sign-in", "/auth/native/return", "/api/auth/get-session", "/api/community/users/me/profile", "/c/invite/token", "/c/invite/token/extra", "/c/unknown/extra"])("leaves non-app path %s outside navigation routing", path => {+ expect(isCommunityShellNavigation(navigation(path), origin)).toBe(false)+ })+ it("never handles RSC, ordinary fetches, writes or cross-origin documents", () => {+ expect(isCommunityShellNavigation(request("/c"), origin)).toBe(false)+ for (const headers of [{ RSC: "1" }, { "Next-Router-State-Tree": "tree" }, { "Next-Router-Prefetch": "1" }, { Accept: "text/x-component" }]) expect(isCommunityShellNavigation(navigation("/c", headers), origin)).toBe(false)+ expect(isCommunityShellNavigation(new Request(`${origin}/c`, { method: "POST" }), origin)).toBe(false)+ expect(isCommunityShellNavigation(navigation("/c"), "https://other.test")).toBe(false)+ })+ it("admits only exact public HTML bytes for the current build", async () => {+ expect(await isCommunityShellResponse(request(shell), response(), shell)).toBe(true)+ expect(await isCommunityShellResponse(request(shell), response({}, `${html}changed`), shell)).toBe(false)+ expect(await isCommunityShellResponse(request("/app.html"), response(), shell)).toBe(false)+ for (const headers of [{ "Cache-Control": "private, no-store" }, { "Cache-Control": "public, no-cache" }, { "Cache-Control": "max-age=3600" }, { "Set-Cookie": "fixture=x" }, { Vary: "Cookie" }, { Vary: "RSC" }, { Vary: "Next-Router-State-Tree" }, { "Content-Type": "application/json" }]) expect(await isCommunityShellResponse(request(shell), response(headers), shell)).toBe(false)+ expect(await isCommunityShellResponse(request(shell), new Response(html, { status: 500 }), shell)).toBe(false)+ const redirected = response(); Object.defineProperty(redirected, "redirected", { value: true })+ expect(await isCommunityShellResponse(request(shell), redirected, shell)).toBe(false)+ })+})diff --git a/src/web/src/lib/service-worker/community-shell.ts b/src/web/src/lib/service-worker/community-shell.tsnew file mode 100644index 000000000..9610d4282--- /dev/null+++ b/src/web/src/lib/service-worker/community-shell.ts@@ -0,0 +1,40 @@+import { isCommunityApplicationPath } from "../community/application-route"++export const communityShellDirectory = "/community-shell/"+const shellPath = /^\/community-shell\/([a-f0-9]{64})$/++export function communityShellHash(pathname: string): string | undefined {+ return shellPath.exec(pathname)?.[1]+}++export function isCommunityShellAssetRequest(request: Request, origin: string, shellUrl: string): boolean {+ const url = new URL(request.url)+ return request.method === "GET" && url.origin === origin && url.pathname === shellUrl+ && !!communityShellHash(url.pathname) && !url.search && request.mode !== "navigate"+ && !request.headers.has("Authorization") && !request.headers.has("Cookie")+ && !request.headers.has("RSC") && !request.headers.has("Next-Router-State-Tree")+ && !request.headers.has("Next-Router-Prefetch") && !request.headers.get("Accept")?.includes("text/x-component")+}++export function isCommunityShellNavigation(request: Request, origin: string): boolean {+ const url = new URL(request.url)+ return request.method === "GET" && request.mode === "navigate" && url.origin === origin+ && isCommunityApplicationPath(url.pathname) && !request.headers.has("RSC")+ && !request.headers.has("Next-Router-State-Tree") && !request.headers.has("Next-Router-Prefetch")+ && !request.headers.get("Accept")?.includes("text/x-component")+}++export async function isCommunityShellResponse(request: Request, response: Response, shellUrl: string): Promise<boolean> {+ const url = new URL(request.url)+ const hash = communityShellHash(url.pathname)+ const cacheControl = response.headers.get("Cache-Control") ?? ""+ const vary = response.headers.get("Vary") ?? ""+ if (!hash || url.pathname !== shellUrl || response.status !== 200 || response.redirected+ || response.headers.get("Content-Type")?.split(";", 1)[0].trim().toLowerCase() !== "text/html"+ || !/(?:^|,)\s*public\s*(?:,|$)/i.test(cacheControl)+ || /(?:^|,)\s*(?:private|no-store|no-cache)\b/i.test(cacheControl)+ || response.headers.has("Set-Cookie")+ || /(?:^|,)\s*(?:\*|cookie|authorization|rsc|next-router[^,]*)\s*(?:,|$)/i.test(vary)) return false+ const digest = await crypto.subtle.digest("SHA-256", await response.clone().arrayBuffer())+ return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, "0")).join("") === hash+}diff --git a/src/web/src/middleware.test.ts b/src/web/src/middleware.test.tsindex 27389d773..5d721f7de 100644--- a/src/web/src/middleware.test.ts+++ b/src/web/src/middleware.test.ts@@ -22,10 +22,13 @@ function makeReq(url: string, headers: Record<string, string> = {}) {describe("middleware", () => {beforeEach(() => vi.clearAllMocks());- it("strips a supplied internal document route from a public request", async () => {- const res = await middleware(makeReq("https://app.com/about", { "x-alook-community-document-route": "/c/me/bots" }))- expect(res.headers.get("x-middleware-request-x-alook-community-document-route")).toBeNull()- expect(res.headers.get("x-middleware-override-headers") ?? "").not.toContain("x-alook-community-document-route")+ it.each(["/c", "/c/me", "/c/me/machines", "/c/channels/server/channel", "/c/invite/token"])("serves public community document %s without session work or cookie changes", async path => {+ mockGetSession.mockImplementation(() => { throw new Error("Session must not gate the public shell") })+ const res = await middleware(makeReq(`https://app.com${path}`, { Cookie: "session=fixture" }))+ expect(res.headers.get("x-middleware-next")).toBe("1")+ expect(res.headers.get("location")).toBeNull()+ expect(res.headers.get("set-cookie")).toBeNull()+ expect(mockGetSession).not.toHaveBeenCalled()})describe("HTTPS enforcement", () => {@@ -41,7 +44,7 @@ describe("middleware", () => {const req = makeReq("http://localhost/c/me", { "x-forwarded-proto": "http" });const res = await middleware(req);// localhost is exempt → falls through to auth handling (sign-in redirect), not a 301 https redirect- expect(res.headers.get("location")).not.toContain("https://localhost")+ expect(res.status).not.toBe(301)});it("does NOT force https for 127.x", async () => {@@ -63,31 +66,6 @@ describe("middleware", () => {expect(mockGetSession).not.toHaveBeenCalled();}});- it("redirects to /sign-in with redirect param when unauthenticated", async () => {- mockGetSession.mockResolvedValue({ headers: new Headers(), response: null });- const req = makeReq("https://app.com/c/me?tab=x", { "x-forwarded-proto": "https" });- const res = await middleware(req);- const loc = new URL(res.headers.get("location")!);- expect(loc.pathname).toBe("/sign-in");- expect(loc.searchParams.get("redirect")).toBe("/c/me?tab=x");- });-- it("passes through authenticated requests and forwards refreshed cookies", async () => {- const setHeaders = new Headers();- setHeaders.append("set-cookie", "session=abc; Path=/");- mockGetSession.mockResolvedValue({- headers: setHeaders,- response: { user: { id: "u1" } },- });- const req = makeReq("https://app.com/c/me", { "x-forwarded-proto": "https" });- const res = await middleware(req);- // NextResponse.next() — no redirect location- expect(res.headers.get("location")).toBeNull();- expect(res.headers.get("set-cookie")).toContain("session=abc");- expect(res.headers.get("x-middleware-request-cookie")).toBe("session=abc");- expect(res.headers.get("cache-control")).toBe("private, no-store");- });-it("does not require auth for unlisted public paths", async () => {const req = makeReq("https://app.com/about", { "x-forwarded-proto": "https" });const res = await middleware(req);@@ -104,14 +82,7 @@ describe("middleware", () => {expect(mockGetSession).not.toHaveBeenCalled();});- it("still gates the rest of /c/ (the public exemption is scoped to /c/invite/)", async () => {- mockGetSession.mockResolvedValue({ headers: new Headers(), response: null });- const req = makeReq("https://app.com/c/channels/s1", { "x-forwarded-proto": "https" });- const res = await middleware(req);- const loc = new URL(res.headers.get("location")!);- expect(loc.pathname).toBe("/sign-in");- expect(loc.searchParams.get("redirect")).toBe("/c/channels/s1");- });+});describe("Next route matcher", () => {diff --git a/src/web/src/middleware.ts b/src/web/src/middleware.tsindex 5d33811aa..3a7cefa1c 100644--- a/src/web/src/middleware.ts+++ b/src/web/src/middleware.ts@@ -1,18 +1,5 @@import { NextRequest, NextResponse } from "next/server"import { safeRedirectPath } from "@/lib/safe-redirect"-import { COMMUNITY_DOCUMENT_ROUTE_HEADER, communityDocumentRoute } from "@/lib/community/document-route"-import { authResponseCookies } from "@/lib/auth-response-cookies"--const AUTH_REQUIRED_PREFIXES = ["/c/"]--// Paths that stay public even though they'd otherwise match an auth-required-// prefix. The invite landing page is preview-first: a logged-out user must be-// able to SEE the invite (server name/icon/description/members) and only hit-// the login wall when they click Join. Its `info` API is `withOptionalAuth`-// and the invite token is the capability, so serving the page anonymously-// leaks nothing gated. Scoped to exactly this path — the rest of `/c/` stays-// gated.-const PUBLIC_PREFIXES = ["/c/invite/"]export async function middleware(request: NextRequest) {if (@@ -26,35 +13,6 @@ export async function middleware(request: NextRequest) {}const { pathname } = request.nextUrl- const isPublic = PUBLIC_PREFIXES.some((p) => pathname.startsWith(p))- 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({- headers: request.headers,- returnHeaders: true,- })) as { headers: Headers; response: unknown } | null-- if (!result?.response) {- const signInUrl = new URL("/sign-in", request.url)- signInUrl.searchParams.set("redirect", pathname + request.nextUrl.search)- return NextResponse.redirect(signInUrl)- }-- const forwarded = new Headers(request.headers)- forwarded.delete(COMMUNITY_DOCUMENT_ROUTE_HEADER)- const documentRoute = request.method === "GET" ? communityDocumentRoute(request.nextUrl) : null- if (documentRoute) forwarded.set(COMMUNITY_DOCUMENT_ROUTE_HEADER, documentRoute)- const response = authResponseCookies(request, result.headers, forwarded)- response.headers.set("Cache-Control", "private, no-store")- return response- }-if (pathname === "/sign-in" || pathname === "/sign-up") {const [{ getCloudflareContext }, { getAuth, observeAuthSession }] = await Promise.all([import("@opennextjs/cloudflare"), import("@/lib/auth"),@@ -77,11 +35,6 @@ export async function middleware(request: NextRequest) {}}- if (request.headers.has(COMMUNITY_DOCUMENT_ROUTE_HEADER)) {- const forwarded = new Headers(request.headers)- forwarded.delete(COMMUNITY_DOCUMENT_ROUTE_HEADER)- return NextResponse.next({ request: { headers: forwarded } })- }return NextResponse.next()}diff --git a/src/web/src/test/community-document-flight.test.ts b/src/web/src/test/community-document-flight.test.tsdeleted file mode 100644index c4f74f509..000000000--- a/src/web/src/test/community-document-flight.test.ts+++ /dev/null@@ -1,40 +0,0 @@-import { describe, expect, it } from "vitest"-import { readCommunityDocumentSeedFromHtml } from "./e2e-ui/_fixtures/community-ssr-frame"--const profile = { id: "viewer", name: "Viewer", discriminator: "0042", avatar: null, avatarVersion: 2 }-const seed = { viewerId: "viewer", href: "/c/me/dm", generatedAt: 123, selfProfile: profile, entries: [], db: { collections: [] } }-const html = (flight: string) => `<script>self.__next_f.push([1,${JSON.stringify(flight)}])</script>`--describe("document seed from actual Flight data framing", () => {- it("reads the prior inline document seed", async () => {- expect(await readCommunityDocumentSeedFromHtml(html(`0:${JSON.stringify({ child: { initialSeed: seed } })}\n`))).toEqual(seed)- })-- it("resolves a deferred seed and shared records without loading Client Component modules", async () => {- const value = { ...seed, selfProfile: "$c", entries: [{ target: { channelId: "dm", serverId: null }, data: { peer: "$c" } }] }- const wire = `:HL["/static/style.css","style"]\n0:{"initialSeed":"$@a"}\n5:I["unused",["never-load.js"],"default"]\na:${JSON.stringify(value)}\nc:${JSON.stringify(profile)}\n`- const decoded = await readCommunityDocumentSeedFromHtml(html(wire))- expect(decoded.viewerId).toBe("viewer")- expect(decoded.selfProfile).toEqual(profile)- expect(decoded.entries[0].data.peer).toBe(decoded.selfProfile)- })-- it("keeps UTF-8 length-framed text intact across script chunks and adjacent data rows", async () => {- const body = `${"正文🙂".repeat(400)}\na:I["text, not an import"]\n0:{"initialSeed":"wrong"}`- const value = { ...seed, entries: [{ target: { channelId: "dm", serverId: null }, data: { messages: [{ content: "$b" }] } }], db: { collections: [], label: "$$column" } }- const wire = `0:{"initialSeed":"$@a"}\na:${JSON.stringify(value)}\nb:T${new TextEncoder().encode(body).length.toString(16)},${body}c:{"unused":true}\n`- const split = Math.floor(wire.length / 2)- const decoded = await readCommunityDocumentSeedFromHtml(html(wire.slice(0, split)) + html(wire.slice(split)))- expect(decoded.entries[0].data.messages[0].content).toBe(body)- expect(decoded.db).toMatchObject({ label: "$column" })- })-- it("rejects a failed deferred seed instead of returning a partial receipt", async () => {- await expect(readCommunityDocumentSeedFromHtml(html('0:{"initialSeed":"$@a"}\na:E{"digest":"seed-error"}\n'))).rejects.toThrow()- })-- it("rejects missing and truncated document data", async () => {- await expect(readCommunityDocumentSeedFromHtml(html('0:{"other":true}\n'))).rejects.toThrow()- await expect(readCommunityDocumentSeedFromHtml(html('0:{"initialSeed":"$@a"}\na:Tff,short'))).rejects.toThrow()- })-})diff --git a/src/web/src/test/community-loading-geometry-lanes.test.ts b/src/web/src/test/community-loading-geometry-lanes.test.tsindex 02bc09458..0cadb05e7 100644--- a/src/web/src/test/community-loading-geometry-lanes.test.ts+++ b/src/web/src/test/community-loading-geometry-lanes.test.ts@@ -79,7 +79,7 @@ function fixtureRun(failure?: "navigation" | "overflow" | "empty" | "ssr-duplica}const locator = (count = 1) => ({fixtureLocator: true, visible: true, count,- attributes: { "aria-busy": "true", "aria-label": "Loading community" },+ attributes: { "aria-busy": "true", "aria-label": "Loading community", "data-community-route-kind": "community-root-redirect" },locator: () => locator(),})const page = {@@ -97,7 +97,7 @@ function fixtureRun(failure?: "navigation" | "overflow" | "empty" | "ssr-duplicaif (failure === "navigation" && visits[0] === visit) throw originalFailure},getByTestId: () => locator(),- locator: (selector: string) => locator(selector.includes("restore-bootstrap") ? 0 : 1),+ locator: (selector: string) => locator(selector.includes("restore-bootstrap") || selector.includes("user-bar-base") ? 0 : 1),waitForTimeout: async (time: number) => { visit.waits.push(time); visit.events.push("sample.wait") },evaluate: async (callback: () => unknown, input?: unknown) => {if (input && typeof input === "object" && "initialId" in input && input.initialId === tid.initialFrame) {diff --git a/src/web/src/test/community-module-host.tsx b/src/web/src/test/community-module-host.tsxnew file mode 100644index 000000000..83bdb9d56--- /dev/null+++ b/src/web/src/test/community-module-host.tsx@@ -0,0 +1,19 @@+import { type ReactNode } from "react"+import { usePathname, useSearchParams } from "next/navigation"+import { useCommunityRouteFrame } from "@/components/community/shell/community-route-context"+import { CommunityModuleRoute } from "@/components/community/shell/community-module-route"+import { useMeRouteMemory } from "@/hooks/community/use-me-route-memory"++export function CommunityServerModuleHost(_props: { children?: ReactNode }) {+ const pathname = usePathname()+ const search = useSearchParams().toString()+ const published = `${pathname}${search ? `?${search}` : ""}`+ const { navigation } = useCommunityRouteFrame()+ const target = navigation?.navigationPending && navigation.pendingHref ? navigation.pendingHref : published+ return <CommunityModuleRoute href={target} routeCommitted={target === published} />+}++export function CommunityMeMemoryHost({ children }: { children?: ReactNode }) {+ useMeRouteMemory(usePathname(), true)+ return children+}diff --git a/src/web/src/test/e2e-fixture-isolation.test.ts b/src/web/src/test/e2e-fixture-isolation.test.tsindex bb9392549..fff20dc50 100644--- a/src/web/src/test/e2e-fixture-isolation.test.ts+++ b/src/web/src/test/e2e-fixture-isolation.test.ts@@ -156,7 +156,7 @@ describe("test-scoped case actors and cleanup", () => {const browser = (): Browser => ({newContext: vi.fn(async () => {let isClosed = false- const page = { isClosed: () => isClosed, context: () => context, url: () => "http://fixture.test/sign-in" } as Page+ const page = { isClosed: () => isClosed, context: () => context, url: () => "http://fixture.test/sign-in?redirect=%2Fc" } as Pageconst context = {cookies: vi.fn(async () => []),newPage: async () => page,@@ -179,10 +179,14 @@ describe("test-scoped case actors and cleanup", () => {}, testInfo)}- const protectedRedirect = (): APIResponse => ({+ const publicDocument = (): APIResponse => ({url: () => "http://fixture.test/c",- status: () => 307,- headers: () => ({ location: "/sign-in?redirect=%2Fc" }),+ status: () => 200,+ text: async () => '<main data-community-shell="public"></main>',+ }) as unknown as APIResponse+ const protectedDenial = (): APIResponse => ({+ url: () => "http://fixture.test/api/community/servers",+ status: () => 401,}) as unknown as APIResponseconst serverDeleteResponse = (page: Page, serverId: string, cookie: string, options: {@@ -502,20 +506,28 @@ describe("test-scoped case actors and cleanup", () => {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")+ await expect(users.confirmSignedOut("logout", { ...alice, publicDocumentResponse: publicDocument(), protectedResponse: protectedDenial() })).rejects.toThrow("different case")+ await expect(users.confirmSignedOut("alice", { ...alice, publicDocumentResponse: publicDocument(), protectedResponse: protectedDenial() })).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 () => {+ it("requires cleared original cookies, the public document and protected API denial", 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")+ await expect(users.confirmSignedOut("logout", { ...logout, publicDocumentResponse: publicDocument(), protectedResponse: protectedDenial() })).rejects.toThrow("incomplete")vi.mocked(logout.context.cookies).mockResolvedValue([])- await expect(users.confirmSignedOut("logout", { ...logout, protectedResponse: { ...protectedRedirect(), status: () => 401 } as APIResponse })).rejects.toThrow("incomplete")+ await expect(users.confirmSignedOut("logout", { ...logout, publicDocumentResponse: publicDocument(), protectedResponse: { ...protectedDenial(), status: () => 200 } as APIResponse })).rejects.toThrow("incomplete")+ for (const invalid of [+ { ...publicDocument(), status: () => 503 },+ { ...publicDocument(), url: () => "https://foreign.test/c" },+ { ...publicDocument(), text: async () => "private document" },+ ]) await expect(users.confirmSignedOut("logout", { ...logout, publicDocumentResponse: invalid as APIResponse, protectedResponse: protectedDenial() })).rejects.toThrow("incomplete")+ await expect(users.confirmSignedOut("logout", { ...logout, publicDocumentResponse: publicDocument(), protectedResponse: { ...protectedDenial(), url: () => "http://fixture.test/api/other" } as APIResponse })).rejects.toThrow("incomplete")+ vi.spyOn(logout.page, "url").mockReturnValue("http://fixture.test/sign-in?redirect=%2Fc%2Fprivate")+ await expect(users.confirmSignedOut("logout", { ...logout, publicDocumentResponse: publicDocument(), protectedResponse: protectedDenial() })).rejects.toThrow("incomplete")})expect(vi.mocked(fetch).mock.calls.filter(([url]) => new URL(String(url)).pathname === "/api/ws/token")).toHaveLength(0)})@@ -530,7 +542,7 @@ describe("test-scoped case actors and cleanup", () => {const dispose = vi.fn(async () => undefined)resources.own("gate", dispose)const logout = await users.asUser("logout")- await users.confirmSignedOut("logout", { ...logout, protectedResponse: protectedRedirect() })+ await users.confirmSignedOut("logout", { ...logout, publicDocumentResponse: publicDocument(), protectedResponse: protectedDenial() })expect(dispose).toHaveBeenCalledTimes(1)expect(servers.size).toBe(0)expect(closed.every((page) => page.isClosed())).toBe(true)@@ -554,7 +566,7 @@ describe("test-scoped case actors and cleanup", () => {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() })+ await users.confirmSignedOut("logout", { ...logout, publicDocumentResponse: publicDocument(), protectedResponse: protectedDenial() })})).rejects.toThrow("Case cleanup failed")const record = JSON.parse(readFileSync(resolve(fixture.directory, "case-cleanup-failure.json"), "utf8"))expect(record.pendingSessionRetirement).toBe(true)@@ -567,7 +579,7 @@ describe("test-scoped case actors and cleanup", () => {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() })+ await users.confirmSignedOut("logout", { ...logout, publicDocumentResponse: publicDocument(), protectedResponse: protectedDenial() })}).catch((error: AggregateError) => error)expect(failure).toBeInstanceOf(AggregateError)expect(servers.size).toBe(1)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 d77032e66..0af62c6b1 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,3 +1,4 @@+import type { Request } from "@playwright/test"import { test, expect } from "./_fixtures/case-fixture"import { tid } from "./_fixtures/testids"import { composerEditable, createServer, sendMessage, expectMessageVisible } from "./_fixtures/actions"@@ -165,21 +166,42 @@ test("server → channel → message", async ({ caseActors, caseResources }) =>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()- return- }- await messagesGate- await route.continue()+ const messageContinuations: Promise<void>[] = []+ const pendingMessageRequests = new Set<Request>()+ const settleMessageRequest = (request: Request) => { pendingMessageRequests.delete(request) }+ page.on("requestfinished", settleMessageRequest)+ page.on("requestfailed", settleMessageRequest)+ caseResources.own(releaseMessages, async (captured) => { captured(); await Promise.all(messageContinuations) })+ let heldMessageReads = 0+ await page.route("**/api/community/channels/*/messages*", route => {+ const request = route.request()+ const continuation = (async () => {+ if (request.method() === "GET") {+ pendingMessageRequests.add(request)+ heldMessageReads += 1+ await messagesGate+ if (!pendingMessageRequests.has(request)) return+ }+ try { await route.continue() } catch (error) {+ if (request.method() !== "GET" || pendingMessageRequests.has(request)) throw error+ }+ })()+ messageContinuations.push(continuation)+ return continuation})await page.reload({ waitUntil: "commit" })+ await expect.poll(() => heldMessageReads).toBeGreaterThan(0)+ await expect(composerEditable(page)).toHaveCount(0)+ await expect(page.getByTestId(tid.message(firstPayload.message.id))).toHaveCount(0)+ await expect(page.getByTestId(tid.message(imePayload.message.id))).toHaveCount(0)+ releaseMessages()await expect(composerEditable(page)).toContainText(draft)await expect(page.getByTestId(tid.message(firstPayload.message.id))).toHaveCount(1)await expect(page.getByTestId(tid.message(imePayload.message.id))).toHaveCount(1)- releaseMessages()+ await Promise.all(messageContinuations)await page.unroute("**/api/community/channels/*/messages*")+ page.off("requestfinished", settleMessageRequest)+ page.off("requestfailed", settleMessageRequest)const restored = composerEditable(page)await restored.click()diff --git a/src/web/src/test/e2e-ui/08-mobile.spec.ts b/src/web/src/test/e2e-ui/08-mobile.spec.tsindex a68d1f86c..62b6b4b8f 100644--- a/src/web/src/test/e2e-ui/08-mobile.spec.ts+++ b/src/web/src/test/e2e-ui/08-mobile.spec.ts@@ -1,6 +1,7 @@import { expectInertBackground } from "./_fixtures/inert-background"import type { Page } from "@playwright/test"import { test, expect } from "./_fixtures/case-fixture"+import { expectPublicCommunityDocument } from "./_fixtures/community-ssr-frame"import { tid } from "./_fixtures/testids"import type { CaseActors } from "./_fixtures/case-fixture"@@ -266,7 +267,10 @@ test.describe("mobile layout", () => {const response = await page.goto(`/c/channels/${serverId}/${channelId}/${childChannelId}`,)- expect(response?.status()).toBe(404)+ expect(response?.status()).toBe(200)+ expectPublicCommunityDocument(await response!.text())+ await expect(page.getByText("Undeliverable — page not found", { exact: false })).toBeVisible()+ await expect(page.getByTestId(tid.composerInput)).toHaveCount(0)await page.goto("/c/me")await page.evaluate(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 c6ce31e4d..a40b7602c 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,3 +1,4 @@+import { expectPublicCommunityDocument } from "./_fixtures/community-ssr-frame"import { test, expect } from "./_fixtures/case-fixture"import type { CaseActors } from "./_fixtures/case-fixture"@@ -49,17 +50,15 @@ test.describe("eject, navigation & logout", () => {await page.getByRole("button", { name: "Log Out" }).click()await page.waitForURL(/\/sign-in/, { timeout: 20_000 , waitUntil: "commit" })- // Session is actually cleared: a protected route returns a sign-in redirect.await expect.poll(async () => (await page.context().cookies()).some((cookie) => cookie.name.startsWith("better-auth"))).toBe(false)- const protectedResponse = await page.request.get("/c", { maxRedirects: 0 })- expect(protectedResponse.status()).toBe(307)- const redirectLocation = protectedResponse.headers().location- expect(redirectLocation).toBeTruthy()- const redirectUrl = new URL(redirectLocation!, page.url())- 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 })+ const publicDocumentResponse = await page.request.get("/c", { maxRedirects: 0 })+ expect(publicDocumentResponse.status()).toBe(200)+ expectPublicCommunityDocument(await publicDocumentResponse.text())+ const protectedResponse = await page.request.get("/api/community/servers", { maxRedirects: 0 })+ expect(protectedResponse.status()).toBe(401)+ await page.goto("/c")+ await expect(page).toHaveURL(/\/sign-in\?redirect=%2Fc$/)+ await actors.confirmSignedOut("logout", { context: page.context(), page, publicDocumentResponse, protectedResponse })})})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 c1c47e033..9e85a8422 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,5 +1,6 @@import type { Page } from "@playwright/test"import { test, expect } from "./_fixtures/case-fixture"+import { holdRoute } from "./_fixtures/held-route"import { sendMessage } from "./_fixtures/actions"import { tid } from "./_fixtures/testids"@@ -142,7 +143,7 @@ test.describe("forum sidebar Stage B request shape", () => {return { participantUserIds, serverId, forumId, threadId, textAId, textBId, forumTitle, ordinaryThreadId }}- test("a cold direct child and hard refresh use their RSC window without duplicate target reads", async ({ caseActors, caseResources }) => {+ test("a cold direct child and hard refresh verify entry once without duplicate target reads", async ({ caseActors, caseResources }) => {const actors = await caseActors(["alice", "bob", "carol"])const { asUser } = actorsconst { serverId, threadId, forumTitle } = await prepareCase1(actors)@@ -150,38 +151,32 @@ test.describe("forum sidebar Stage B request shape", () => {const { page } = await asUser("alice")const requests: string[] = []const successfulResponses: string[] = []- let releaseTargetReads!: () => void- const targetGate = new Promise<void>(resolve => { releaseTargetReads = resolve })- caseResources.own(releaseTargetReads, async captured => { captured() })- const targetRead = (url: URL) => url.pathname === `/api/community/channels/${threadId}`- || url.pathname === `/api/community/channels/${threadId}/read-state`- || url.pathname === `/api/community/channels/${threadId}/messages`- await page.route(targetRead, async route => { await targetGate; await route.continue() })page.on("request", request => { if (request.method() === "GET") requests.push(request.url()) })page.on("response", response => { if (response.request().method() === "GET" && response.ok()) successfulResponses.push(response.url()) })- try {- for (const refresh of [false, true]) {- requests.length = 0- successfulResponses.length = 0- const combined = page.waitForResponse(response => response.ok() && isSidebarRequest(response.url(), serverId))- if (refresh) await page.reload({ waitUntil: "commit" })- else await page.goto(`/c/channels/${serverId}/${threadId}`)- await combined- await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${serverId}/${threadId}`)- await expect(childPanel(page).getByRole("heading", { name: forumTitle })).toBeVisible({ timeout: 20_000 })- await expect(childPanel(page).getByText("post body", { exact: true })).toBeVisible({ timeout: 20_000 })- await expect(childPanel(page).getByTestId(tid.composerInput)).toBeVisible()- await expect(page.locator('[data-slot="skeleton"]')).toHaveCount(0)- await page.waitForTimeout(refresh ? 2_000 : 500)- expect(requests.filter(url => targetRead(new URL(url)))).toEqual([])- const sidebar = requests.filter(url => isSidebarRequest(url, serverId))- expect(sidebar.length).toBeGreaterThanOrEqual(1)- expect(sidebar.length).toBeLessThanOrEqual(2)- expect(sidebar.every(url => { const retain = new URL(url).searchParams.get("retainId"); return retain === null || retain === threadId })).toBe(true)- }- } finally {- releaseTargetReads()- await page.unroute(targetRead)+ for (const refresh of [false, true]) {+ const entryGate = await holdRoute(page, url => isConversationEntryRequest(url.href, threadId), caseResources)+ requests.length = 0+ successfulResponses.length = 0+ const combined = page.waitForResponse(response => response.ok() && isSidebarRequest(response.url(), serverId))+ if (refresh) await page.reload({ waitUntil: "commit" })+ else await page.goto(`/c/channels/${serverId}/${threadId}`)+ await combined+ await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${serverId}/${threadId}`)+ await expect.poll(entryGate.held).toBe(1)+ await expect(childPanel(page).getByText("post body", { exact: true })).toHaveCount(0)+ await expect(childPanel(page).getByTestId(tid.composerInput)).toHaveCount(0)+ await entryGate.release()+ await expect(childPanel(page).getByRole("heading", { name: forumTitle })).toBeVisible({ timeout: 20_000 })+ await expect(childPanel(page).getByText("post body", { exact: true })).toBeVisible({ timeout: 20_000 })+ await expect(childPanel(page).getByTestId(tid.composerInput)).toBeVisible()+ await expect(page.locator('[data-slot="skeleton"]')).toHaveCount(0)+ await page.waitForTimeout(refresh ? 2_000 : 500)+ expect(requests.filter(url => isChannelMessagesRequest(url, threadId))).toHaveLength(1)+ expect(successfulResponses.filter(url => isConversationEntryRequest(url, threadId))).toHaveLength(1)+ const sidebar = requests.filter(url => isSidebarRequest(url, serverId))+ expect(sidebar.length).toBeGreaterThanOrEqual(1)+ expect(sidebar.length).toBeLessThanOrEqual(2)+ expect(sidebar.every(url => { const retain = new URL(url).searchParams.get("retainId"); return retain === null || retain === threadId })).toBe(true)}})@@ -210,7 +205,8 @@ test.describe("forum sidebar Stage B request shape", () => {const messageResponses = successfulResponses.filter((url) =>isChannelMessagesRequest(url, threadId),)- expect(messageResponses).toEqual([])+ expect(messageResponses).toHaveLength(1)+ expect(messageResponses.every(url => isConversationEntryRequest(url, threadId))).toBe(true)})test("a non-participant keeps a grouped forum route after retained null arrives", async ({ caseActors }) => {@@ -252,7 +248,7 @@ test.describe("forum sidebar Stage B request shape", () => {)expect(retainedResponses).toHaveLength(1)expect(retainedResponses[0]?.retainedChannel).toBeNull()- expect(successfulResponses.filter((url) => isConversationEntryRequest(url, threadId))).toHaveLength(0)+ expect(successfulResponses.filter((url) => isConversationEntryRequest(url, threadId))).toHaveLength(1)expect(await routeStability(page)).toEqual({ mounts: 1, losses: 0, present: true })expect(await participantUserIds(page, threadId)).not.toContain(userId("bob"))@@ -332,7 +328,7 @@ test.describe("forum sidebar Stage B request shape", () => {await page.waitForTimeout(2_000)expect(successfulResponses.filter((url) => isConversationEntryRequest(url, ordinaryThreadId)))- .toHaveLength(0)+ .toHaveLength(1)expect(requests.filter((url) =>isSidebarRequest(url, serverId)&& new URL(url).searchParams.get("retainId") === ordinaryThreadIddiff --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 29c4691c6..9b8699985 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,11 +1,12 @@-import type { Page, Request, Response, Route } from "@playwright/test"+import type { Page } from "@playwright/test"import { test, expect } from "./_fixtures/case-fixture"import { tid } from "./_fixtures/testids"import type { CaseResources } from "./_fixtures/case-fixture"+import { holdRoute } from "./_fixtures/held-route"type HeldServer = {- heldNavigation: () => number+ heldReads: () => numberrelease: () => Promise<void>}@@ -24,6 +25,7 @@ type SidebarFrame = {type HistoryEvent = {kind: "pushState" | "replaceState" | "popstate"pathname: string+ internal: boolean}async function installSidebarFrameProbe(page: Page) {@@ -38,21 +40,22 @@ async function installSidebarFrameProbe(page: Page) {const recordHistory = (kind: HistoryEvent["kind"],href: string | URL | null | undefined,+ data: unknown,) => {const url = href == null ? new URL(location.href) : new URL(String(href), location.href)- state.__communityHistoryEvents!.push({ kind, pathname: url.pathname })+ state.__communityHistoryEvents!.push({ kind, pathname: url.pathname, internal: typeof data === "object" && data !== null && "__NA" in data && data.__NA === true && "__PRIVATE_NEXTJS_INTERNALS_TREE" in data })}const pushState = history.pushState.bind(history)history.pushState = (...args) => {- recordHistory("pushState", args[2])+ recordHistory("pushState", args[2], args[0])return pushState(...args)}const replaceState = history.replaceState.bind(history)history.replaceState = (...args) => {- recordHistory("replaceState", args[2])+ recordHistory("replaceState", args[2], args[0])return replaceState(...args)}- addEventListener("popstate", () => recordHistory("popstate", location.href))+ addEventListener("popstate", () => recordHistory("popstate", location.href, history.state))const ownerIds = new WeakMap<Element, number>()let nextOwnerId = 0const sample = () => {@@ -156,156 +159,12 @@ async function holdServerTransition(page: Page,serverId: string, caseResources: CaseResources): Promise<HeldServer> {- let releaseGate!: () => void- const gate = new Promise<void>((resolve) => { releaseGate = resolve })- caseResources.own(releaseGate, async (captured) => { captured() })- let heldNavigation = 0- const patterns: Array<{ pattern: string; navigation: boolean }> = [- { pattern: `**/c/channels/${serverId}**`, navigation: true },- { pattern: `**/api/community/servers/${serverId}/categories**`, navigation: false },- { pattern: `**/api/community/servers/${serverId}/channels**`, navigation: false },- { pattern: `**/api/community/servers/${serverId}/unreads**`, navigation: false },- ]- const handlers = new Map<string, (route: Route) => Promise<void>>()- for (const { pattern, navigation } of patterns) {- const handler = async (route: Route) => {- if (navigation) heldNavigation += 1- await gate- await route.continue()- }- handlers.set(pattern, handler)- await page.route(pattern, handler)- }- return {- heldNavigation: () => heldNavigation,- release: async () => {- releaseGate()- await page.waitForTimeout(100)- await Promise.all([...handlers].map(([pattern, handler]) => page.unroute(pattern, handler)))- },- }-}--function isTargetRsc(request: Request, serverId: string): boolean {- return request.resourceType() === "fetch"- && request.headers().rsc === "1"- && new URL(request.url()).pathname.startsWith(`/c/channels/${serverId}/`)-}--type TargetRscBody = { bytes: number; done: boolean; error: boolean; restore: () => void }-type TargetRscWindow = typeof window & { __communityTargetRscBody: TargetRscBody }--async function observeTargetRsc(- page: Page,- serverId: string,- timeoutMs: number, caseResources: CaseResources-) {- await page.evaluate((serverId) => {- const originalFetch = window.fetch- const state = { bytes: 0, done: false, error: false, readers: 0, restore: () => { window.fetch = originalFetch } }- Object.assign(window, { __communityTargetRscBody: state })- window.fetch = function (input, init) {- const pending = originalFetch.call(this, input, init)- const url = new URL(input instanceof Request ? input.url : String(input), location.href)- if (!url.pathname.startsWith(`/c/channels/${serverId}/`) || new Headers(init?.headers).get("rsc") !== "1") return pending- return pending.then((response) => {- if (!response.body) { state.error = true; return response }- response.body.getReader = new Proxy(response.body.getReader, {- apply(target, receiver, args) {- if (++state.readers !== 1) state.error = true- const reader = Reflect.apply(target, receiver, args)- reader.cancel = new Proxy(reader.cancel, {- apply(cancel, owner, cancelArgs) {- if (!state.done) state.error = true- return Reflect.apply(cancel, owner, cancelArgs)- },- })- reader.read = new Proxy(reader.read, {- apply(read, owner, readArgs) {- const reading = Reflect.apply(read, owner, readArgs) as Promise<ReadableStreamReadResult<Uint8Array>>- return reading.then((result) => {- state.bytes += result.value?.byteLength ?? 0- state.done = result.done- return result- }, (error: unknown) => { state.error = true; throw error })- },- })- return reader- },- })- return response- }, (error: unknown) => { state.error = true; throw error })- }- }, serverId)- const deadline = Date.now() + timeoutMs- const polling = new AbortController()- const responded = new Set<Request>()- const requests: string[] = []- let settled = false- let resolveFinished!: (error: Error | null) => void- const finished = new Promise<Error | null>((resolve) => {- resolveFinished = resolve- })- const settle = (error?: Error) => {- if (settled) return- settled = true- clearTimeout(timeout)- resolveFinished(error ?? null)- }- const onRequest = (request: Request) => {- if (isTargetRsc(request, serverId)) requests.push(request.url())- }- const onRequestFailed = (request: Request) => {- if (!isTargetRsc(request, serverId) || responded.has(request)) return- settle(new Error(- `Target RSC request failed: ${request.failure()?.errorText ?? "unknown failure"}`,- ))- }- const onResponse = (response: Response) => {- if (!isTargetRsc(response.request(), serverId)) return- responded.add(response.request())- if (response.status() !== 200) {- settle(new Error(`Target RSC responded ${response.status()}: ${response.url()}`))- return- }- void page.waitForFunction(() => {- const body = (window as TargetRscWindow).__communityTargetRscBody- return body.error || body.done- }, undefined, { timeout: Math.max(1, deadline - Date.now()), signal: polling.signal }).then(async (handle) => {- await handle.dispose()- const body = await page.evaluate(() => {- const { bytes, done, error } = (window as TargetRscWindow).__communityTargetRscBody- return { bytes, done, error }- })- settle(body.error || !body.done || body.bytes === 0 ? new Error("Target RSC body did not reach a nonempty native EOF") : undefined)- }).catch((error: unknown) => { settle(new Error(`Target RSC body completion rejected: ${String(error)}`)) })- }- const timeout = setTimeout(() => {- settle(new Error(`Target RSC did not finish within ${timeoutMs}ms for server ${serverId}`))- }, timeoutMs)- let stopped = false- const stop = async () => {- if (stopped) return- stopped = true- polling.abort()- clearTimeout(timeout)- page.off("request", onRequest)- page.off("requestfailed", onRequestFailed)- page.off("response", onResponse)- if (!page.isClosed()) await page.evaluate(() => (window as Partial<TargetRscWindow>).__communityTargetRscBody?.restore())- }- caseResources.own(stop, async (captured) => {- await captured()- settle()- })- page.on("request", onRequest)- page.on("requestfailed", onRequestFailed)- page.on("response", onResponse)- return {- finished,- requests: () => [...requests],- stop,- }+ const held = await holdRoute(page, url => [+ `/api/community/servers/${serverId}/categories`,+ `/api/community/servers/${serverId}/channels`,+ `/api/community/servers/${serverId}/unreads`,+ ].includes(url.pathname), caseResources)+ return { heldReads: held.held, release: held.release }}async function activateServerIcon(page: Page, serverId: string) {@@ -362,6 +221,10 @@ test("server switching exposes one target-scoped cold checkpoint and skips it whconst channelF = await seedChannel("alice", serverF, `checkpoint-f-${stamp}`)const { page } = await asUser("alice")+ const rscRequests: string[] = []+ page.on("request", request => {+ if (request.headers().rsc === "1" && new URL(request.url()).pathname.startsWith("/c/")) rscRequests.push(request.url())+ })await page.setViewportSize({ width: 1280, height: 900 })await installSidebarFrameProbe(page)await page.goto(`/c/channels/${serverA}/${channelA}`)@@ -424,7 +287,7 @@ test("server switching exposes one target-scoped cold checkpoint and skips it whawait clearSidebarFrames(page)await clickServer(page, serverC)- await expect.poll(coldC.heldNavigation).toBeGreaterThan(0)+ await expect.poll(coldC.heldReads).toBeGreaterThan(0)await expect(page.getByTestId(tid.channelSidebarPending(serverC))).toBeVisible()await expect(page.getByTestId(tid.pendingMain("server-landing"))).toBeVisible()await expect(page.getByRole("link", { name: channelAName, exact: true })).toHaveCount(0)@@ -468,16 +331,13 @@ test("server switching exposes one target-scoped cold checkpoint and skips it whawait page.reload()await expect(page.getByRole("heading", { name: channelAName })).toBeVisible({ timeout: 30_000 })const structuralC = await holdServerTransition(page, serverC, caseResources)- const targetRsc = await observeTargetRsc(page, serverC, 30_000, caseResources)await clearSidebarFrames(page)await clearHistoryEvents(page)- try {+ const historyLength = await page.evaluate(() => history.length)+ {await clickServer(page, serverC)- await expect.poll(structuralC.heldNavigation).toBeGreaterThan(0)+ await expect.poll(structuralC.heldReads).toBeGreaterThan(0)await structuralC.release()- const rscFailure = await targetRsc.finished- if (rscFailure) throw rscFailure- expect(targetRsc.requests()).toHaveLength(1)await expectDesktopServerDetail(page, serverC)await expect(page.getByTestId(tid.channelRow(channelC))).toBeVisible({ timeout: 30_000 })await expect.poll(() => new URL(page.url()).pathname).toBe(rememberedCHref)@@ -494,14 +354,20 @@ test("server switching exposes one target-scoped cold checkpoint and skips it wh[channelA, channelB],)const navigationEvents = await historyEvents(page)- expect(navigationEvents).toHaveLength(1)- expect(navigationEvents[0]).toEqual({+ expect(navigationEvents.filter(event => event.kind === "pushState")).toEqual([{kind: "pushState",pathname: rememberedCHref,- })- } finally {- await targetRsc.stop()+ internal: true,+ }])+ expect(navigationEvents.every(event => event.pathname === rememberedCHref+ && (event.kind === "pushState" || event.kind === "replaceState" && event.internal))).toBe(true)+ expect(await page.evaluate(() => history.length)).toBe(historyLength + 1)}+ await page.goBack()+ await expect(page.getByRole("heading", { name: channelAName })).toBeVisible()+ await page.goForward()+ await expect.poll(() => new URL(page.url()).pathname).toBe(rememberedCHref)+ await expect(page.getByRole("heading", { name: rememberedCHeading, exact: true })).toBeVisible()await clickServer(page, serverA)await expectDesktopServerDetail(page, serverA)@@ -515,7 +381,7 @@ test("server switching exposes one target-scoped cold checkpoint and skips it whawait clearSidebarFrames(page)await clickServer(page, serverD)- await expect.poll(coldD.heldNavigation).toBeGreaterThan(0)+ await expect.poll(coldD.heldReads).toBeGreaterThan(0)const mobileCheckpoint = page.getByTestId(tid.channelSidebarPending(serverD))await expect(mobileCheckpoint).toBeVisible()await expect(page.getByRole("link", { name: channelAName, exact: true })).toHaveCount(0)@@ -545,7 +411,7 @@ test("server switching exposes one target-scoped cold checkpoint and skips it wh// button so this remains one immediate E→F intent window; awaiting F's// focus-driven prefetch would serialize the two intents.await page.getByTestId(tid.serverIcon(serverF)).dispatchEvent("click")- await expect.poll(coldF.heldNavigation).toBeGreaterThan(0)+ await expect.poll(coldF.heldReads).toBeGreaterThan(0)await expect(page.getByTestId(tid.channelSidebarPending(serverE))).toHaveCount(0)await expect(page.getByTestId(tid.channelSidebarPending(serverF))).toBeVisible()await expectActiveServer(page, serverF, serverD)@@ -563,4 +429,5 @@ test("server switching exposes one target-scoped cold checkpoint and skips it whchannelF,[channelA, channelB, channelC, channelD, channelE],)+ expect(rscRequests).toEqual([])})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 52ed1fa78..86a2e42c8 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,30 +1,8 @@-import type { Page, Route } from "@playwright/test"+import type { Page } from "@playwright/test"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, caseResources: CaseResources) {- let releaseGate!: () => void- const gate = new Promise<void>((resolve) => { releaseGate = resolve })- caseResources.own(releaseGate, async (captured) => { captured() })- let held = 0- const pattern = `**${pathname}**`- const handler = async (route: Route) => {- held += 1- await gate- await route.continue()- }- await page.route(pattern, handler)- return {- held: () => held,- release: async () => {- releaseGate()- await page.waitForTimeout(100)- await page.unroute(pattern, handler)- },- }-}+import { holdRoute } from "./_fixtures/held-route"function channelHeader(page: Page, name: string) {return page.getByRole("banner").getByText(name, { exact: true })@@ -141,8 +119,7 @@ test("community checkpoint shows target pending for detail and keeps list surfacconst channelA = await seedChannel("alice", serverId, channelAName)const channelB = await seedChannel("alice", serverId, channelBName)const { page } = await asUser("alice")- const machineDataGate = await holdRoute(page, "/api/community/machines", caseResources)- const machinesGate = await holdRoute(page, "/c/me/machines", caseResources)+ const machineDataGate = await holdRoute(page, "**/api/community/machines**", caseResources)await page.setViewportSize({ width: 1280, height: 900 })await page.goto(`/c/channels/${serverId}/${channelA}`)await expect(channelHeader(page, channelAName)).toBeVisible({ timeout: 30_000 })@@ -162,7 +139,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}`, caseResources)+ const leafGate = await holdRoute(page, `**/api/community/channels/${channelB}/messages*`, caseResources)await page.getByTestId(tid.channelRow(channelB)).click({ noWaitAfter: true })await expect.poll(leafGate.held).toBeGreaterThan(0)const pendingMain = page.locator(@@ -191,46 +168,39 @@ 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}`, caseResources)await page.getByRole("banner").getByRole("button", { name: "Back" }).click({ noWaitAfter: true })- await expect.poll(rootGate.held).toBeGreaterThan(0)+ await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${serverId}`)await page.setViewportSize({ width: 1280, height: 900 })await expect(page.getByLabel("Resolving conversation")).toHaveCount(0)await expect(channelHeader(page, channelBName)).toBeVisible()await page.waitForTimeout(150)await expect(page.getByLabel("Resolving conversation")).toHaveCount(0)- await expect(channelHeader(page, channelBName)).toBeVisible()- await rootGate.release()await expect(channelHeader(page, channelBName)).toBeVisible({ timeout: 30_000 })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 })- await expect.poll(machinesGate.held).toBeGreaterThan(0)await expect.poll(machineDataGate.held).toBeGreaterThan(0)await expect(page.getByPlaceholder("Search friends")).toHaveCount(0)await expect(page.getByLabel("Resolving conversation")).toHaveCount(0)await expect(page.locator('[data-slot="community-machines-heading"] [data-slot="skeleton"]').first()).toBeVisible()await expect(page.getByText("No machines yet", {exact: true})).toHaveCount(0)await expect(page.getByTestId(tid.machinePairOpen)).toHaveCount(0)- expect(new URL(page.url()).pathname).toBe("/c/me/friends")+ expect(new URL(page.url()).pathname).toBe("/c/me/machines")await machineDataGate.release()await expect(page.getByText("No machines yet", {exact: true})).toBeVisible()await expect(page.getByTestId(tid.machinePairOpen)).toBeEnabled()- expect(new URL(page.url()).pathname).toBe("/c/me/friends")+ expect(new URL(page.url()).pathname).toBe("/c/me/machines")const cachedMachineContent = page.getByText("No machines yet", {exact: true})await cachedMachineContent.evaluate(element => { element.setAttribute("data-e2e-cached-identity", "retained") })- await machinesGate.release()await expect.poll(() => new URL(page.url()).pathname).toBe("/c/me/machines")await expect(cachedMachineContent).toHaveAttribute("data-e2e-cached-identity", "retained")await page.getByRole("link", {name: "Friends", exact: true}).click()await expect(page.getByPlaceholder("Search friends")).toBeVisible()- const warmMachinesGate = await holdRoute(page, "/c/me/machines", caseResources)await page.getByRole("link", {name: "Machines", exact: true}).click({noWaitAfter: true})await expect(cachedMachineContent).toBeVisible()await expect(page.getByTestId(tid.machinePairOpen)).toBeEnabled()await expect(page.getByPlaceholder("Search friends")).toHaveCount(0)- await warmMachinesGate.release()await expect.poll(() => new URL(page.url()).pathname).toBe("/c/me/machines")expect(mutations).toEqual([])@@ -292,7 +262,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, caseResources)+ const pendingGate = await holdRoute(page, `**/api/community/channels/${pendingChannel}/messages*`, 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/41-community-initial-load-module-skeletons.spec.ts b/src/web/src/test/e2e-ui/41-community-initial-load-module-skeletons.spec.tsindex 60a2a26c0..8f80f38e2 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,6 +1,7 @@import type { BrowserContext, Page, Route, TestInfo } from "@playwright/test"import { test, expect } from "./_fixtures/case-fixture"+import { expectPublicCommunityDocument } from "./_fixtures/community-ssr-frame"import { tid } from "./_fixtures/testids"import type { CaseActors, CaseResources } from "./_fixtures/case-fixture"@@ -150,129 +151,39 @@ function captureCommunityTraffic(page: Page) {return { requests, responses, failures, sockets: () => sockets }}-async function expectHeldMessage(page: Page, originalHtml: Promise<string>, conversationId: string, messageId: string, body: string, authorName: string) {- const original = await page.evaluate(({ html, messageTestId }) => {- const document = new DOMParser().parseFromString(html, "text/html")- const rows = Array.from(document.querySelectorAll(`[data-testid="${messageTestId}"]`)).map(row => {- const transportAncestors: Array<{ id: string; tag: string }> = []- for (let parent = row.parentElement; parent; parent = parent.parentElement) {- if (parent.hasAttribute("hidden") && parent.id.startsWith("S:")) transportAncestors.push({ id: parent.id, tag: parent.tagName })- }- return { text: row.textContent ?? "", transportAncestors }- })- return { primary: rows.filter(row => row.transportAncestors.length === 0), transport: rows.filter(row => row.transportAncestors.length > 0) }- }, { html: await originalHtml, messageTestId: tid.message(messageId) })- expect(original.primary.length + original.transport.length, JSON.stringify(original)).toBeGreaterThan(0)- expect(original.primary.length, JSON.stringify(original)).toBeLessThanOrEqual(1)- for (const row of [...original.primary, ...original.transport]) {- expect(row.text).toContain(body)- expect(row.text).toContain(authorName)- }+async function expectClientMessage(page: Page, gate: { release: () => void }, conversationId: string, messageId: string, body: string, authorName: string, traffic: ReturnType<typeof captureCommunityTraffic>, testInfo: TestInfo, label: string) {+ const entry = page.waitForResponse(response => {+ const url = new URL(response.url())+ return url.pathname === `/api/community/channels/${conversationId}/messages` && url.searchParams.get("entry") === "1"+ })+ gate.release()+ expect((await entry).status()).toBe(200)const root = page.getByTestId(tid.messageScroller)const content = root.locator("[data-message-list-content]")const row = root.getByTestId(tid.message(messageId))await expect(root).toHaveCount(1)- await expect(root).toBeVisible()- await expect(root).toHaveAttribute("aria-busy", "true")- await expect(content).toHaveAttribute("data-initial-position-phase", "positioning")- await expect(content).toHaveAttribute("data-read-position-ready", "false")- await expect(content).toHaveAttribute("aria-hidden", "true")- await expect(content).toHaveAttribute("inert", "")- await expect(content).toHaveCSS("visibility", "hidden")- await expect(row).toHaveCount(1)- await expect(row.getByText(body, { exact: true })).toHaveCount(1)- await expect(row.getByText(authorName, { exact: true })).toHaveCount(1)+ await expect(row).toBeVisible()+ await expect(row.getByText(body, { exact: true })).toBeVisible()+ await expect(row.getByText(authorName, { exact: true })).toBeVisible()+ await expect(content).toHaveAttribute("data-initial-position-phase", "revealed")+ await expect(content).toHaveAttribute("data-read-position-ready", "true")const geometry = await row.evaluate((node, scrollerId) => {const root = node.closest<HTMLElement>(`[data-testid="${scrollerId}"]`)!- const content = root.querySelector<HTMLElement>("[data-message-list-content]")!- const main = root.closest<HTMLElement>('[data-slot="community-main-panel-content"]')- const surface = root.closest<HTMLElement>('[data-slot="community-conversation-surface"]')- const rects = [root, content, node, main].map(element => element?.getBoundingClientRect())- const skeleton = root.parentElement?.querySelector("[data-message-positioning-skeleton]")- return {- positiveLayout: rects.every(rect => !!rect && rect.width > 0 && rect.height > 0),- positiveScroll: root.scrollHeight > 0 && root.clientHeight > 0,- conversationId: surface?.dataset.channelId,- inStreamContainer: !!node.closest('[hidden][id^="S:"]'),- skeletonOutsideScroller: !!skeleton && !root.contains(skeleton),- }+ const row = node.getBoundingClientRect()+ const viewport = root.getBoundingClientRect()+ return { positiveLayout: row.width > 0 && row.height > 0 && viewport.width > 0 && viewport.height > 0,+ targetInView: row.top >= viewport.top && row.bottom <= viewport.bottom,+ distanceToEnd: Math.max(0, root.scrollHeight - root.clientHeight - root.scrollTop) }}, tid.messageScroller)- expect(geometry).toEqual({ positiveLayout: true, positiveScroll: true, conversationId, inStreamContainer: false, skeletonOutsideScroller: true })- await expect(page.locator("[data-message-positioning-skeleton]")).toBeVisible()- const refs = await root.evaluateHandle((node, messageTestId) => ({- root: node,- content: node.querySelector<HTMLElement>("[data-message-list-content]")!,- row: node.querySelector<HTMLElement>(`[data-testid="${messageTestId}"]`)!,- }), tid.message(messageId))- return { root, content, row, refs, conversationId, messageId, authorName, original }-}--async function expectReleasedMessage(page: Page, gate: { release: () => void }, held: Awaited<ReturnType<typeof expectHeldMessage>>, traffic: ReturnType<typeof captureCommunityTraffic>, testInfo: TestInfo, label: string) {- const probe = await held.refs.evaluateHandle(saved => {- type Sample = { phase: string | null; firstVisibleId: string | null; targetInView: boolean; distanceToEnd: number; sameRoot: boolean; sameContent: boolean; sameRow: boolean; positioningSkeleton: boolean; readReady: string | null }- const state = { first: null as Sample | null, frames: 0, expired: false }- const deadline = performance.now() + 30_000- let raf = 0- const sample = () => {- if (performance.now() >= deadline) { state.expired = true; return }- state.frames += 1- const root = document.querySelector<HTMLElement>(`[data-testid="${saved.root.getAttribute("data-testid")}"]`)- const content = root?.querySelector<HTMLElement>("[data-message-list-content]")- const viewport = root?.getBoundingClientRect()- const visibleRows = root && viewport && viewport.width > 0 && viewport.height > 0 && getComputedStyle(root).visibility === "visible" ? Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]")).filter(row => {- const rect = row.getBoundingClientRect()- return getComputedStyle(row).visibility === "visible" && rect.width > 0 && rect.height > 0 && rect.bottom > viewport.top && rect.top < viewport.bottom- }) : []- if (root && content && viewport && visibleRows.length > 0) {- const row = root.querySelector<HTMLElement>(`[data-testid="${saved.row.getAttribute("data-testid")}"]`)- const rect = row?.getBoundingClientRect()- state.first = {- phase: content.getAttribute("data-initial-position-phase"),- firstVisibleId: visibleRows[0].dataset.msgId ?? null,- targetInView: !!rect && rect.width > 0 && rect.height > 0 && rect.top >= viewport.top && rect.bottom <= viewport.bottom,- distanceToEnd: Math.max(0, root.scrollHeight - root.clientHeight - root.scrollTop),- sameRoot: root === saved.root, sameContent: content === saved.content, sameRow: row === saved.row,- positioningSkeleton: !!root.parentElement?.querySelector("[data-message-positioning-skeleton]"),- readReady: content.getAttribute("data-read-position-ready"),- }- return- }- raf = requestAnimationFrame(sample)- }- raf = requestAnimationFrame(sample)- return { state, stop: () => cancelAnimationFrame(raf) }- })- try {- gate.release()- await expect.poll(() => probe.evaluate(probe => probe.state.first)).toMatchObject({- phase: "revealed", firstVisibleId: held.messageId, targetInView: true,- sameRoot: true, sameContent: true, sameRow: true, positioningSkeleton: false,- })- const observation = await probe.evaluate(probe => probe.state)- expect(observation.expired).toBe(false)- expect(observation.first!.distanceToEnd).toBeLessThanOrEqual(1)- await expect(held.row).toBeVisible()- await expect(held.row.getByText(held.authorName, { exact: true })).toBeVisible()- await expect(held.content).toHaveAttribute("data-initial-position-phase", "revealed")- await expect(held.content).toHaveAttribute("data-read-position-ready", "true")- expect(await held.refs.evaluate(saved => saved.root.isConnected && saved.content.parentElement === saved.root && saved.row.isConnected && saved.root.contains(saved.row))).toBe(true)- await expect.poll(traffic.sockets).toBe(1)- const targetPaths = new Set([- `/api/community/channels/${held.conversationId}`,- `/api/community/channels/${held.conversationId}/read-state`,- `/api/community/channels/${held.conversationId}/messages`,- ])- expect(traffic.requests.filter(({ method, pathname }) => method === "GET" && targetPaths.has(pathname))).toEqual([])- expect(traffic.failures.filter(({ pathname }) => targetPaths.has(pathname))).toEqual([])- } finally {- const observation = await probe.evaluate(probe => { probe.stop(); return probe.state })- try {- await testInfo.attach(label, { body: JSON.stringify({ evidence: "bounded DOM RAF sample, not compositor proof", conversationId: held.conversationId, messageId: held.messageId, authorName: held.authorName, originalSsr: held.original, observation, requests: traffic.requests, sockets: traffic.sockets(), url: page.url() }), contentType: "application/json" })- } finally {- await probe.dispose()- await held.refs.dispose()- }- }+ expect(geometry.positiveLayout).toBe(true)+ expect(geometry.targetInView).toBe(true)+ expect(geometry.distanceToEnd).toBeLessThanOrEqual(1)+ await expect.poll(traffic.sockets).toBe(1)+ const entries = traffic.requests.filter(request => request.method === "GET" && request.pathname === `/api/community/channels/${conversationId}/messages` && new URLSearchParams(request.search).get("entry") === "1")+ expect(entries).toHaveLength(1)+ expect(traffic.failures.filter(request => request.pathname.startsWith(`/api/community/channels/${conversationId}`))).toEqual([])+ await testInfo.attach(label, { body: JSON.stringify({ conversationId, messageId, geometry, requests: traffic.requests, sockets: traffic.sockets(), url: page.url() }), contentType: "application/json" })+ return { root, content, row, conversationId, messageId }}async function expectDocumentRouteFallback(@@ -281,6 +192,7 @@ async function expectDocumentRouteFallback(distinctiveStrings: string[],originalHtml: Promise<string>,) {+ expectPublicCommunityDocument(await originalHtml)const fallback = await page.evaluate(({ html, initialId, mainId, railId, userBarId, meId, serverId }) => {const document = new DOMParser().parseFromString(html, "text/html")const frames = Array.from(document.querySelectorAll(`[data-testid="${initialId}"]`))@@ -299,23 +211,23 @@ async function expectDocumentRouteFallback(text: frame.textContent ?? "",customBootstrap: document.querySelectorAll('[data-slot="community-restore-bootstrap"]').length,}- }, { html: await originalHtml, initialId: tid.initialFrame, mainId: tid.pendingMain(expected.main),+ }, { html: await originalHtml, initialId: tid.initialFrame, mainId: tid.pendingMain("route-resolution"),railId: tid.initialRailPending, userBarId: tid.initialUserBarPending, meId: tid.dmSidebarPending,serverId: expected.serverId ? tid.channelSidebarPending(expected.serverId) : tid.channelSidebarPending("") })expect(fallback).not.toBeNull()- expect(fallback!.route).toBe(expected.route)+ expect(fallback!.route, JSON.stringify(expected)).toBe("community-root-redirect")expect(fallback!.primaryCount).toBe(1)expect(fallback!.unexplainedExtras).toBe(0)expect(fallback!.customBootstrap).toBe(0)- expect(fallback!.rail).toBe(expected.sidebar !== "none" ? 1 : 0)- expect(fallback!.userBar).toBe(expected.sidebar !== "none" ? 1 : 0)- expect(fallback!.me).toBe(expected.sidebar === "me" ? 1 : 0)- expect(fallback!.server).toBe(expected.sidebar === "server" ? 1 : 0)+ expect(fallback!.rail).toBe(0)+ expect(fallback!.userBar).toBe(0)+ expect(fallback!.me).toBe(0)+ expect(fallback!.server).toBe(0)expect(fallback!.main).toBe(1)expect(fallback!.placeholders).toBeGreaterThan(0)expect(fallback!.buttons).toBe(0)expect(fallback!.links).toBe(0)- for (const value of distinctiveStrings) expect(fallback!.text).not.toContain(value)+ for (const value of distinctiveStrings) { expect(fallback!.text).not.toContain(value); expect(await originalHtml).not.toContain(value) }}test.describe("community initial-load module skeletons", () => {@@ -335,7 +247,7 @@ test.describe("community initial-load module skeletons", () => {return { coldRootStorageKey, installColdRootProbe, closeHeldContext, serverId, channelId, dmId, serverName, channelName, channelMessageId, dmMessageId, privateMessage }}- test("cold mobile documents retain URL-owned fallbacks and authorized RSC content", async ({ caseActors, caseResources }, testInfo) => {+ test("cold mobile documents stay public before client identity and entry reads", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(240_000)const actors = await caseActors(["alice", "bob"])@@ -364,9 +276,6 @@ test.describe("community initial-load module skeletons", () => {await expect.poll(gate.hits).toBeGreaterThan(0)expect(gate.sessionRequests()).toBe(0)await expectDocumentRouteFallback(page, expected, [serverName, channelName, privateMessage], gate.documentHtml())- const held = expected.main === "dm" || expected.main === "server-conversation"- ? await expectHeldMessage(page, gate.documentHtml(), expected.main === "dm" ? dmId : channelId, expected.main === "dm" ? dmMessageId : channelMessageId, privateMessage, actors.userName("alice"))- : nullif (pathname === "/c") {await testInfo.attach("community-root-neutral-390x844", {body: await page.screenshot(),@@ -375,12 +284,14 @@ test.describe("community initial-load module skeletons", () => {}expect(traffic.requests).toEqual([])expect(traffic.sockets()).toBe(0)- if (held) await expectReleasedMessage(page, gate, held, traffic, testInfo, `first-visible-dom-${expected.main}-${page.viewportSize()!.width}`)+ if (expected.main === "dm" || expected.main === "server-conversation") {+ await expectClientMessage(page, gate, expected.main === "dm" ? dmId : channelId, expected.main === "dm" ? dmMessageId : channelMessageId, privateMessage, actors.userName("alice"), traffic, testInfo, `client-entry-${expected.main}-${page.viewportSize()!.width}`)+ }await closeHeldContext(context, gate)}})- test("desktop cold documents retain route-owned fallback columns and RSC content", async ({ caseActors, caseResources }, testInfo) => {+ test("desktop cold documents stay public before client identity and entry reads", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(120_000)const actors = await caseActors(["alice", "bob"])@@ -401,9 +312,6 @@ test.describe("community initial-load module skeletons", () => {await expect.poll(gate.hits).toBeGreaterThan(0)expect(gate.sessionRequests()).toBe(0)await expectDocumentRouteFallback(page, expected, [serverName, channelName, privateMessage], gate.documentHtml())- const held = expected.main === "dm" || expected.main === "server-conversation"- ? await expectHeldMessage(page, gate.documentHtml(), expected.main === "dm" ? dmId : channelId, expected.main === "dm" ? dmMessageId : channelMessageId, privateMessage, actors.userName("alice"))- : nullif (pathname === "/c") {await testInfo.attach("community-root-neutral-1280x900", {body: await page.screenshot(),@@ -412,7 +320,9 @@ test.describe("community initial-load module skeletons", () => {}expect(traffic.requests).toEqual([])expect(traffic.sockets()).toBe(0)- if (held) await expectReleasedMessage(page, gate, held, traffic, testInfo, `first-visible-dom-${expected.main}-${page.viewportSize()!.width}`)+ if (expected.main === "dm" || expected.main === "server-conversation") {+ await expectClientMessage(page, gate, expected.main === "dm" ? dmId : channelId, expected.main === "dm" ? dmMessageId : channelMessageId, privateMessage, actors.userName("alice"), traffic, testInfo, `client-entry-${expected.main}-${page.viewportSize()!.width}`)+ }await closeHeldContext(context, gate)}})@@ -520,53 +430,44 @@ test.describe("community initial-load module skeletons", () => {.toBe("/c/me/machines")})- test("639↔640 preserves one RSC main node with zero request or socket delta", async ({ caseActors, caseResources }, testInfo) => {+ test("639↔640 preserves one authenticated main node without new route work", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(120_000)-const actors = await caseActors(["alice", "bob"])- const { asUser } = actors- const { closeHeldContext, serverId, channelId, dmId, channelMessageId, dmMessageId, privateMessage } = await prepareCase1(actors, caseResources)-- for (const pathname of [- `/c/me/${dmId}`,- `/c/channels/${serverId}/${channelId}`,- ] as const) {- const { context, page } = await asUser("alice")+ const { serverId, channelId, dmId, channelMessageId, dmMessageId, privateMessage } = await prepareCase1(actors, caseResources)+ for (const [pathname, conversationId, messageId] of [[`/c/me/${dmId}`, dmId, dmMessageId], [`/c/channels/${serverId}/${channelId}`, channelId, channelMessageId]]) {+ const { context, page } = await actors.asUser("alice")await page.setViewportSize({ width: 639, height: 844 })const gate = await holdApplicationScripts(page, caseResources)+ const traffic = captureCommunityTraffic(page)await page.goto(pathname, { waitUntil: "commit" })await expect.poll(gate.hits).toBeGreaterThan(0)expect(gate.sessionRequests()).toBe(0)- const isDm = pathname === `/c/me/${dmId}`- const held = await expectHeldMessage(page, gate.documentHtml(), isDm ? dmId : channelId, isDm ? dmMessageId : channelMessageId, privateMessage, actors.userName("alice"))+ expectPublicCommunityDocument(await gate.documentHtml())+ await expect(page.getByTestId(tid.message(messageId))).toHaveCount(0)+ const loaded = await expectClientMessage(page, gate, conversationId, messageId, privateMessage, actors.userName("alice"), traffic, testInfo, "client-entry-resize")const main = page.locator('[data-slot="community-main-panel-content"]').filter({ visible: true })await expect(main).toBeVisible()- await main.evaluate((node) => { Reflect.set(window, "__communityInitialMain", node) })-- const traffic = captureCommunityTraffic(page)- await page.setViewportSize({ width: 640, height: 844 })- await expect(main).toBeVisible()- const wide = await expectHeldMessage(page, gate.documentHtml(), held.conversationId, held.messageId, privateMessage, actors.userName("alice"))- await wide.refs.dispose()- expect(await main.evaluate((node) => (- Reflect.get(window, "__communityInitialMain") === node- ))).toBe(true)- await page.setViewportSize({ width: 639, height: 844 })- await expect(main).toBeVisible()- expect(await main.evaluate((node) => (- Reflect.get(window, "__communityInitialMain") === node- ))).toBe(true)- expect(traffic.requests).toEqual([])- expect(traffic.sockets()).toBe(0)- const narrow = await expectHeldMessage(page, gate.documentHtml(), held.conversationId, held.messageId, privateMessage, actors.userName("alice"))- await narrow.refs.dispose()- await expectReleasedMessage(page, gate, held, traffic, testInfo, `first-visible-dom-resize-${isDm ? "dm" : "channel"}`)- expect(await main.evaluate(node => Reflect.get(window, "__communityInitialMain") === node)).toBe(true)- await closeHeldContext(context, gate)+ const originalMain = await main.elementHandle()+ const originalRow = await loaded.row.elementHandle()+ await page.waitForLoadState("networkidle")+ const resizeTraffic = captureCommunityTraffic(page)+ for (const width of [640, 639]) {+ await page.setViewportSize({ width, height: 844 })+ await expect(main).toBeVisible()+ await expect(loaded.row).toBeVisible()+ expect(await main.evaluate((node, original) => node === original, originalMain)).toBe(true)+ expect(await loaded.row.evaluate((node, original) => node === original, originalRow)).toBe(true)+ }+ expect(resizeTraffic.requests).toEqual([])+ expect(resizeTraffic.sockets()).toBe(0)+ await originalMain?.dispose()+ await originalRow?.dispose()+ gate.abort()+ await caseResources.closeContext(context)}})- test("releasing scripts mounts one server-seeded user shell without duplicate route work", async ({ caseActors, caseResources }, testInfo) => {+ test("releasing scripts mounts one verified user shell with one protected entry read", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(120_000)const actors = await caseActors(["alice", "bob"])@@ -590,8 +491,7 @@ test.describe("community initial-load module skeletons", () => {expect(traffic.requests).toEqual([])expect(traffic.sockets()).toBe(0)- const held = await expectHeldMessage(page, gate.documentHtml(), channelId, channelMessageId, privateMessage, actors.userName("alice"))- await expectReleasedMessage(page, gate, held, traffic, testInfo, "first-visible-dom-server-release")+ await expectClientMessage(page, gate, channelId, channelMessageId, privateMessage, actors.userName("alice"), traffic, testInfo, "client-entry-server-release")await expect(page.getByTestId(tid.initialFrame)).toHaveCount(0, { timeout: 30_000 })await expect(page.getByTestId(tid.composerInput)).toBeVisible({ timeout: 30_000 })await expect.poll(traffic.sockets).toBe(1)@@ -603,7 +503,7 @@ test.describe("community initial-load module skeletons", () => {`/api/community/channels/${channelId}/read-state`,`/api/community/channels/${channelId}/messages`,])- expect(traffic.requests.filter(({ method, pathname }) => method === "GET" && targetReadPaths.has(pathname))).toEqual([])+ expect(traffic.requests.filter(({ method, pathname, search }) => method === "GET" && pathname === `/api/community/channels/${channelId}/messages` && new URLSearchParams(search).get("entry") === "1")).toHaveLength(1)expect(traffic.failures.filter(({ pathname }) => targetReadPaths.has(pathname))).toEqual([])const readOnlyPostPaths = new Set(["/api/community/messages/batch",diff --git a/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts b/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.tsindex 84000305e..f7298a4ea 100644--- a/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts+++ b/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts@@ -1,5 +1,5 @@import { expectInertBackground } from "./_fixtures/inert-background"-import type { Page, Request, Route } from "@playwright/test"+import type { Page, Request } from "@playwright/test"import { expect, test, type CaseActors } from "./_fixtures/case-fixture"import { GEOMETRY_EPSILON, composerEditable, gotoAfterUserWsAuth, ignoreNextDevToolsPointerCapture, waitForElementMotion } from "./_fixtures/actions"import { communityFrameEvents, proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"@@ -159,7 +159,7 @@ test.describe("mobile Inbox interactive user-bar base", () => {test.setTimeout(180_000)for (const cancelBeforeCommit of [false, true]) {- test(`keeps the first pending list Inbox command, cancel before commit=${cancelBeforeCommit}`, async ({ caseActors, caseResources }) => {+ test(`handles the first Inbox command after immediate parent return, close immediately=${cancelBeforeCommit}`, async ({ caseActors }) => {const actors = await caseActors(["alice", "bob"])const stamp = Date.now()const serverId = await actors.seed.seedServer("alice", `Pending Inbox ${stamp}`)@@ -172,50 +172,22 @@ test.describe("mobile Inbox interactive user-bar base", () => {await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)await ignoreNextDevToolsPointerCapture(page)await expect(page.getByRole("banner").getByText(channelName, { exact: true })).toBeVisible()- let release!: () => void- const gate = new Promise<void>((resolve) => { release = resolve })- caseResources.own(release, async (captured) => { captured() })- let held = 0const root = `/c/channels/${serverId}`- const pattern = (url: URL) => url.pathname === root- const handler = async (route: Route) => {- held += 1- await gate- await route.continue()- }- await page.route(pattern, handler)- try {- await page.getByRole("banner").getByRole("button", { name: "Back" }).tap({ noWaitAfter: true })- await expect.poll(() => held).toBeGreaterThan(0)- const trigger = page.getByTestId(tid.inboxTrigger)- await expect(trigger).toBeVisible()- await trigger.tap()- await expect(trigger).toHaveAttribute("aria-busy", "true")- await expect(trigger).toHaveAttribute("aria-expanded", "false")- await expect(page.getByRole("dialog", { name: "Inbox", exact: true })).toHaveCount(0)- if (cancelBeforeCommit) {- await trigger.tap()- await expect(trigger).not.toHaveAttribute("aria-busy")- }- release()- await expect(page).toHaveURL(new RegExp(`${root}$`))- await expect(page.getByRole("banner").getByText(channelName, { exact: true })).toHaveCount(0)- await expect(trigger).not.toHaveAttribute("aria-busy")- if (cancelBeforeCommit) {- await expect(trigger).toHaveAttribute("aria-expanded", "false")- await expect(page.getByRole("dialog", { name: "Inbox", exact: true })).toHaveCount(0)- } else {- await expect(trigger).toHaveAttribute("aria-expanded", "true")- await expect(page.getByRole("dialog", { name: "Inbox", exact: true })).toBeVisible()- await expect(page.getByTestId(tid.userBarExtension)).toHaveCount(1)- await trigger.tap()- await expect(trigger).toHaveAttribute("aria-expanded", "false")- await expect(page.getByRole("dialog", { name: "Inbox", exact: true })).toHaveCount(0)- }- } finally {- release()- await page.unroute(pattern, handler)+ await page.getByRole("banner").getByRole("button", { name: "Back" }).tap({ noWaitAfter: true })+ await expect(page).toHaveURL(new RegExp(`${root}$`))+ await expect(page.getByRole("banner").getByText(channelName, { exact: true })).toHaveCount(0)+ const trigger = page.getByTestId(tid.inboxTrigger)+ await expect(trigger).toBeVisible()+ await trigger.tap()+ await expect(trigger).not.toHaveAttribute("aria-busy")+ await expect(trigger).toHaveAttribute("aria-expanded", "true")+ if (!cancelBeforeCommit) {+ await expect(page.getByRole("dialog", { name: "Inbox", exact: true })).toBeVisible()+ await expect(page.getByTestId(tid.userBarExtension)).toHaveCount(1)}+ await trigger.tap()+ await expect(trigger).toHaveAttribute("aria-expanded", "false")+ await expect(page.getByRole("dialog", { name: "Inbox", exact: true })).toHaveCount(0)})}diff --git a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.tsindex ab698e7b2..60316fa2b 100644--- a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts+++ b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts@@ -1,3 +1,4 @@+import type { CommunityConversationEntryRead } from "@alook/shared"import type { Locator, Page, Route, TestInfo } from "@playwright/test"import { test, expect, type CaseActors } from "./_fixtures/case-fixture"import { composerEditable, gotoAfterUserWsAuth, sendMessage } from "./_fixtures/actions"@@ -22,7 +23,7 @@ import {} from "./_fixtures/scroll-trace"import { tid } from "./_fixtures/testids"import { WEB_URL } from "./_setup/paths"-import { expectUniqueSsrCommunityFrame, readCommunityDocumentSeedFromHtml } from "./_fixtures/community-ssr-frame"+import { expectUniqueSsrCommunityFrame, expectPublicCommunityDocument } from "./_fixtures/community-ssr-frame"const VIEWPORT = { width: 1280, height: 800 }@@ -829,16 +830,21 @@ test.describe("message scroll characterization", () => {alice.page.on("request", request => {if (request.method() === "POST" && new URL(request.url()).pathname === `/api/community/channels/${channelId}/messages`) composerPosts += 1})- const anchorResponse = alice.page.waitForResponse(response => response.request().isNavigationRequest()+ const documentResponse = alice.page.waitForResponse(response => response.request().isNavigationRequest()&& new URL(response.url()).pathname === `/c/channels/${serverId}/${channelId}`)+ const anchorResponse = alice.page.waitForResponse(response => {+ const url = new URL(response.url())+ return response.request().method() === "GET" && url.pathname === `/api/community/channels/${channelId}/messages` && url.searchParams.get("entry") === "1"+ })await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}`)const scroller = alice.page.getByTestId(tid.messageScroller)await expect(scroller.locator('[data-message-list-content]')).toHaveAttribute("data-read-position-ready", "true")const anchored = await anchorResponseexpect(anchored.status()).toBe(200)- const anchorPage = (await readCommunityDocumentSeedFromHtml(await anchored.text())).entries.find(entry => entry.target.channelId === channelId)- expect(anchorPage?.data.selection.reason).toBe("read_pointer")- expect(anchorPage?.data.page.hasMoreNewer).toBe(true)+ expectPublicCommunityDocument(await (await documentResponse).text())+ const anchorPage = await anchored.json() as CommunityConversationEntryRead+ expect(anchorPage.selection.reason).toBe("read_pointer")+ expect(anchorPage.page.hasMoreNewer).toBe(true)let newestGets = 0alice.page.on("request", request => {const url = new URL(request.url())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 114201132..b39021442 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@@ -2,6 +2,7 @@ import type { Page, WebSocket } from "@playwright/test"import { expect, test } from "./_fixtures/case-fixture"import { gotoAfterUserWsAuth, openServer } from "./_fixtures/actions"+import { holdRoute } from "./_fixtures/held-route"import { tid } from "./_fixtures/testids"import { WEB_URL } from "./_setup/paths"import type { UserKey } from "./_setup/users"@@ -131,29 +132,9 @@ async function delayDelete(page: Page, serverId: string, caseResources: CaseReso}}-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())- const targetsServer = url.pathname === `/c/channels/${serverId}`- || url.pathname.startsWith(`/c/channels/${serverId}/`)- if (!targetsServer || !url.searchParams.has("_rsc")) {- await route.continue()- return- }- intercepted.resolve()- await release.promise- await route.continue()- })- return {- intercepted: intercepted.promise,- release: () => release.resolve(),- cleanup: () => page.unroute(pattern),- }+async function delayServerEntry(page: Page, channelId: string, resources: CaseResources) {+ return holdRoute(page, url => url.pathname === `/api/community/channels/${channelId}/messages`+ && url.searchParams.get("entry") === "1", resources)}async function installHistoryRecorder(page: Page): Promise<void> {@@ -292,7 +273,7 @@ for (const testCase of [})}-test("slow target RSC survives delete/list/WS convergence and lands on its remembered Channel", async ({ caseActors, caseResources }) => {+test("a held target entry survives delete/list/WS convergence on its remembered Channel", async ({ caseActors, caseResources }) => {const actors = await caseActors(["carol"])const { asUser } = actorsconst { serverIds, seedServerRoute } = await prepareCase(actors)@@ -315,7 +296,10 @@ 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!, caseResources)+ const targetChannelId = targetPathname.split("/").at(-1)!+ await page.reload()+ await expect(page.getByTestId(tid.composerInput)).toBeVisible()+ const targetEntry = await delayServerEntry(page, targetChannelId, caseResources)const response = page.waitForResponse((candidate) => (candidate.request().method() === "DELETE"&& new URL(candidate.url()).pathname === `/api/community/servers/${deleted.serverId}`@@ -326,15 +310,14 @@ test("slow target RSC survives delete/list/WS convergence and lands on its rememexpect((await response).status()).toBe(204)const deleteResponse = await responseawait actors.recordServerDeletion("carol", deleted.serverId, { page, response: deleteResponse })- await targetRsc.intercepted+ await expect.poll(targetEntry.held).toBeGreaterThan(0)expect(new URL(page.url()).pathname).not.toBe("/c/me")- targetRsc.release()+ await targetEntry.release()expect(await expectServerLeaf(page, targetServerId!)).toBe(targetPathname)await expect(page.getByTestId(tid.serverIcon(deleted.serverId))).toHaveCount(0)- await targetRsc.cleanup()})-test("a newer user navigation wins while the delete target RSC is pending", async ({ caseActors, caseResources }) => {+test("a newer user navigation wins while the delete target entry is pending", async ({ caseActors, caseResources }) => {const actors = await caseActors(["dave"])const { asUser } = actorsconst { serverIds, seedServerRoute } = await prepareCase(actors)@@ -355,9 +338,11 @@ test("a newer user navigation wins while the delete target RSC is pending", asyn))expect(userRoute).toBeTruthy()await openServer(page, targetServerId!)- await expectServerLeaf(page, targetServerId!)+ const targetPathname = await expectServerLeaf(page, targetServerId!)await openServer(page, deleted.serverId)- const targetRsc = await delayServerRsc(page, targetServerId!, caseResources)+ await page.reload()+ await expect(page.getByTestId(tid.composerInput)).toBeVisible()+ const targetEntry = await delayServerEntry(page, targetPathname.split("/").at(-1)!, caseResources)const response = page.waitForResponse((candidate) => (candidate.request().method() === "DELETE"&& new URL(candidate.url()).pathname === `/api/community/servers/${deleted.serverId}`@@ -368,14 +353,13 @@ test("a newer user navigation wins while the delete target RSC is pending", asynexpect((await response).status()).toBe(204)const deleteResponse = await responseawait actors.recordServerDeletion("dave", deleted.serverId, { page, response: deleteResponse })- await targetRsc.intercepted+ await expect.poll(targetEntry.held).toBeGreaterThan(0)await page.getByTestId(tid.serverIcon(userRoute!.serverId)).click()- targetRsc.release()+ await targetEntry.release()await expectServerLeaf(page, userRoute!.serverId)await expect(page).not.toHaveURL(new RegExp(`/c/channels/${targetServerId}(?:/|$)`), {timeout: 2_000,})- await targetRsc.cleanup()})test("a Back visit after terminal cleanup is an ordinary missing route", async ({ caseActors, caseResources }) => {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 221f136b0..ed68a68c5 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@@ -400,7 +400,7 @@ test.describe("desktop default User Bar width", () => {return { serverId, channelId }}- test("prepaints saved SSR shell widths and preserves the interactive handoff", async ({ caseActors, caseResources }, testInfo) => {+ test("prepaints a public frame and preserves saved widths from the first authenticated shell", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(240_000)const actors = await caseActors(["alice"])@@ -432,11 +432,9 @@ test.describe("desktop default User Bar width", () => {await expect.poll(scripts.hits).toBeGreaterThan(0)const ssrFrame = await expectUniqueSsrCommunityFrame(page)await expect(ssrFrame).toBeVisible()- await expect.poll(async () => (- (await page.evaluate(() => (- Reflect.get(window, "__desktopWidthSamples") as LayoutSample[]- ))).some(({ scriptsHeld }) => scriptsHeld)- )).toBe(true)+ await expect(ssrFrame).toHaveAttribute("data-community-route-kind", "community-root-redirect")+ await expect(page.locator('[data-slot="community-user-bar-base"]')).toHaveCount(0)+ expect(await page.evaluate(() => Reflect.get(window, "__desktopWidthSamples"))).toEqual([])await scripts.release()communityReads.release()await expect(page.getByTestId(tid.channelComposerShell)).toBeVisible()@@ -456,7 +454,8 @@ test.describe("desktop default User Bar width", () => {Math.abs(sidebar - targetWidth) <= geometryEpsilon&& Math.abs(overlay - (targetWidth + 58)) <= geometryEpsilon))).toBe(true)- expect(sequence.some(({ scriptsHeld }) => scriptsHeld)).toBe(true)+ expect(sequence.length).toBeGreaterThan(0)+ expect(sequence.some(({ scriptsHeld }) => scriptsHeld)).toBe(false)expect(sequence.at(-1)?.scriptsHeld).toBe(false)}})@@ -1084,8 +1083,8 @@ test.describe("desktop default User Bar width", () => {const ssrPhase = await ssrFrame.evaluate(root => ({ initial: root.getAttribute("data-testid"), busy: root.getAttribute("aria-busy"), route: root.getAttribute("data-community-route-kind"), slot: root.getAttribute("data-slot"), placeholders: root.querySelectorAll('[data-slot="skeleton"]').length }))if (ssrPhase.initial === tid.initialFrame) {expect(ssrPhase.busy).toBe("true")- expect(ssrPhase.route).toBe("server-root")- expect(ssrPhase.placeholders).toBeGreaterThan(0)+ expect(ssrPhase.route).toBe("community-root-redirect")+ await expect(pending.page.locator('[data-slot="community-user-bar-base"]')).toHaveCount(0)} else expect(ssrPhase.slot).toBe("community-shell-root")await expect(pending.page.locator('[data-slot="community-restore-bootstrap"]')).toHaveCount(0)await scripts.release()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 33c719c45..f3525d30d 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@@ -2,7 +2,7 @@ import { devices, type Page } from "@playwright/test"import { COMMUNITY_CONTRACT_HEADER, DEFAULT_MESSAGE_PAGE_SIZE, type CommunityConversationEntryRead } from "@alook/shared"import { expect, test } from "./_fixtures/case-fixture"import { composerEditable } from "./_fixtures/actions"-import { readCommunityDocumentSeedFromHtml } from "./_fixtures/community-ssr-frame"+import { expectPublicCommunityDocument } from "./_fixtures/community-ssr-frame"import { tid } from "./_fixtures/testids"import { WEB_URL } from "./_setup/paths"@@ -315,17 +315,22 @@ test.describe("mobile notification chat routes (native bridge simulation)", () =expect(readPointer).not.toBe(laterIds.at(-1))const { page } = await asUser("bob", devices["iPhone 13"])+ const entryResponse = page.waitForResponse(response => {+ const url = new URL(response.url())+ return response.request().method() === "GET" && url.pathname === `/api/community/channels/${channelId}/messages`+ && url.searchParams.get("entry") === "1" && url.searchParams.get("anchor") === channelMessageId+ })const response = await page.goto(`/c/channels/${serverId}/${channelId}?msg=${channelMessageId}`)expect(response?.ok()).toBe(true)const html = await response!.text()- const initialSeed = await readCommunityDocumentSeedFromHtml(html)- expect(initialSeed.viewerId).toBe(actors.userId("bob"))- const seeded = initialSeed.entries.find(entry => entry.target.channelId === channelId)- expect(seeded?.target).toEqual({ channelId, serverId, anchorMessageId: channelMessageId, tag: null })- expect(seeded?.data.selection).toEqual({ reason: "explicit_anchor", anchorMessageId: channelMessageId })- expect(seeded?.data.surfaceReceipt).toEqual({ channelId, surfaceKind: "channel" })- expect(seeded?.data.messages).toEqual(expect.arrayContaining([expect.objectContaining({ id: channelMessageId })]))- expect(seeded?.data.messages.some(message => message.id === readPointer)).toBe(false)+ expectPublicCommunityDocument(html)+ const explicitResponse = await entryResponse+ expect(explicitResponse.ok()).toBe(true)+ const explicitEntry = await explicitResponse.json() as CommunityConversationEntryRead+ expect(explicitEntry.selection).toEqual({ reason: "explicit_anchor", anchorMessageId: channelMessageId })+ expect(explicitEntry.surfaceReceipt).toEqual({ channelId, surfaceKind: "channel" })+ expect(explicitEntry.messages).toEqual(expect.arrayContaining([expect.objectContaining({ id: channelMessageId })]))+ expect(explicitEntry.messages.some(message => message.id === readPointer)).toBe(false)const target = page.getByTestId(tid.message(channelMessageId))await expect(target).toBeVisible()await expect(target.locator(".group").first()).toHaveClass(/bg-primary\/10/)@@ -338,7 +343,7 @@ test.describe("mobile notification chat routes (native bridge simulation)", () =await expect.poll(position).toMatchObject({ inView: true, ready: "true" })await expect(page).toHaveURL(`${WEB_URL}/c/channels/${serverId}/${channelId}`)await expect(composerEditable(page)).toBeVisible({ timeout: 30_000 })- await testInfo.attach("msg-anchor-evidence", { body: JSON.stringify({ status: response!.status(), htmlBytes: Buffer.byteLength(html), selection: seeded?.data.selection, surfaceReceipt: seeded?.data.surfaceReceipt, anchorId: channelMessageId, readPointer, latestId: laterIds.at(-1), defaultWindowIds: defaultEntry.messages.map(message => message.id), explicitWindowIds: seeded?.data.messages.map(message => message.id), position: await position(), url: page.url() }), contentType: "application/json" })+ await testInfo.attach("msg-anchor-evidence", { body: JSON.stringify({ status: response!.status(), htmlBytes: Buffer.byteLength(html), selection: explicitEntry.selection, surfaceReceipt: explicitEntry.surfaceReceipt, anchorId: channelMessageId, readPointer, latestId: laterIds.at(-1), defaultWindowIds: defaultEntry.messages.map(message => message.id), explicitWindowIds: explicitEntry.messages.map(message => message.id), position: await position(), url: page.url() }), contentType: "application/json" })})})diff --git a/src/web/src/test/e2e-ui/64-mobile-parent-return.spec.ts b/src/web/src/test/e2e-ui/64-mobile-parent-return.spec.tsindex de06b61bd..89f68604f 100644--- a/src/web/src/test/e2e-ui/64-mobile-parent-return.spec.ts+++ b/src/web/src/test/e2e-ui/64-mobile-parent-return.spec.ts@@ -3,10 +3,10 @@ import { test, expect } from "./_fixtures/case-fixture"import type { CaseResources } from "./_fixtures/case-fixture"import { tid } from "./_fixtures/testids"-async function holdParentRoute(page: Page, pathname: string, resources: CaseResources) {+async function holdReturnDocumentRoutes(page: Page, pathnames: string[], resources: CaseResources) {let release!: () => voidconst gate = new Promise<void>(resolve => { release = resolve })- const pattern = (url: URL) => url.pathname === pathname+ const pattern = (url: URL) => pathnames.includes(url.pathname)let held = 0const pending = new Set<Request>()const continuations: Promise<void>[] = []@@ -40,7 +40,7 @@ async function holdParentRoute(page: Page, pathname: string, resources: CaseResofor (const parentType of ["forum", "text"] as const) {for (const input of ["button", "system"] as const) {- test(`mobile ${parentType} parent accepts ${input} Back before the previous return commits`, async ({ caseActors, caseResources }, testInfo) => {+ test(`mobile ${parentType} parent accepts consecutive ${input} Back without framework route reads`, async ({ caseActors, caseResources }, testInfo) => {const actors = await caseActors(["alice"])const { seedServer, seedChannel, seedMessage, seedThread, seedForumThread } = actors.seedconst serverId = await seedServer("alice", `Parent return ${parentType} ${input}`)@@ -76,11 +76,10 @@ for (const parentType of ["forum", "text"] as const) {expect(channel).toMatchObject({ id: childId, serverId, parentChannelId: parentId })expect(parent).toMatchObject({ id: parentId, type: parentType })- const parentRoute = await holdParentRoute(page, parentPath, caseResources)+ const parentRoute = await holdReturnDocumentRoutes(page, [parentPath, rootPath], caseResources)await back.click({ noWaitAfter: true })- await expect.poll(parentRoute.held).toBeGreaterThan(0)await expect(foreground.locator(`[data-community-target-href="${parentPath}"]`)).toBeVisible()- expect(new URL(page.url()).pathname).toBe(childPath)+ expect(new URL(page.url()).pathname).toBe(parentPath)if (input === "button") await back.click({ noWaitAfter: true })else await page.evaluate(() => window.dispatchEvent(new Event("alook:native-back", { cancelable: true })))@@ -91,6 +90,7 @@ for (const parentType of ["forum", "text"] as const) {const screenshot = testInfo.outputPath("list-before-parent-release.png")await page.screenshot({ path: screenshot })await testInfo.attach("list-before-parent-release", { path: screenshot, contentType: "image/png" })+ expect(parentRoute.held()).toBe(0)await parentRoute.release()await expect.poll(() => new URL(page.url()).pathname).toBe(rootPath)await expect(parentRow).toBeVisible()diff --git a/src/web/src/test/e2e-ui/66-public-static-resource-cache.spec.ts b/src/web/src/test/e2e-ui/66-public-static-resource-cache.spec.tsindex 1c73b5bf1..2f01307fd 100644--- a/src/web/src/test/e2e-ui/66-public-static-resource-cache.spec.ts+++ b/src/web/src/test/e2e-ui/66-public-static-resource-cache.spec.ts@@ -1,3 +1,4 @@+import { createHash } from "node:crypto"import { mkdtempSync } from "node:fs"import { rm } from "node:fs/promises"import { tmpdir } from "node:os"@@ -6,6 +7,8 @@ import { chromium, type BrowserContext, type Page, type TestInfo } from "@playwrimport { publicWorkerCacheNames, publicWorkerRuntimeCacheNames } from "../../lib/service-worker/cache-identity"import { publicRuntimeAssetKind } from "../../lib/service-worker/public-cache"import { expect, test } from "./_fixtures/case-fixture"+import { expectPublicCommunityDocument } from "./_fixtures/community-ssr-frame"+import { tid } from "./_fixtures/testids"import { blogBuildIdFromScripts } from "./_fixtures/public-static-qa"type Asset = { url: string; cacheName: string }@@ -143,6 +146,59 @@ async function attachReceipt(page: Page, testInfo: TestInfo, name: string, resou}test.describe("production public static resource cache", () => {+ test("a closed community page reopens from the public shell while identity and entry remain online", async ({ caseActors }, testInfo) => {+ const actors = await caseActors(["alice", "bob"])+ const dmId = await actors.seed.seedDm("alice", actors.userId("bob"))+ const body = `Public shell private message ${Date.now()}`+ const messageId = await actors.seed.seedDmMessage("bob", dmId, body)+ const { page, context } = await actors.asUser("alice")+ await page.goto(`/c/me/${dmId}`)+ await expect(page.getByTestId(tid.message(messageId))).toBeVisible()+ await expectRootWorker(page)+ const keys = await publicCacheKeys(page)+ const shellKeys = (keys[publicWorkerCacheNames().precache] ?? []).filter(url => /^\/community-shell\/[a-f0-9]{64}$/.test(new URL(url).pathname))+ expect(shellKeys).toHaveLength(1)+ const cachedHtml = await page.evaluate(async ({ name, url }) => {+ const response = await (await caches.open(name)).match(url)+ if (!response) throw new Error("Installed shell is missing")+ return response.text()+ }, { name: publicWorkerCacheNames().precache, url: shellKeys[0] })+ expectPublicCommunityDocument(cachedHtml)+ const hash = createHash("sha256").update(cachedHtml).digest("hex")+ expect(new URL(shellKeys[0]).pathname).toBe(`/community-shell/${hash}`)+ for (const privateValue of [actors.userId("alice"), messageId, body]) expect(cachedHtml).not.toContain(privateValue)+ await page.close()+ const reopened = await context.newPage()+ const target = `/c/me/${dmId}?qa=warm-shell#frame`+ let deniedNetworkRequests = 0+ const denyDocumentNetwork = async (route: import("@playwright/test").Route) => { deniedNetworkRequests += 1; await route.abort("failed") }+ const documentPath = (url: URL) => url.pathname === `/c/me/${dmId}`+ await context.route(documentPath, denyDocumentNetwork)+ await runWithCleanup(async () => {+ await reopened.goto("/robots.txt")+ await expectRootWorker(reopened)+ expect(await reopened.evaluate(async target => { try { await fetch(target, { cache: "no-store" }); return false } catch { return true } }, target)).toBe(true)+ expect(deniedNetworkRequests).toBeGreaterThan(0)+ const sessionResponse = reopened.waitForResponse(response => new URL(response.url()).pathname === "/api/auth/get-session")+ const entryResponse = reopened.waitForResponse(response => {+ const url = new URL(response.url())+ return url.pathname === `/api/community/channels/${dmId}/messages` && url.searchParams.get("entry") === "1"+ })+ const started = Date.now()+ const response = await reopened.goto(target)+ expect(response?.status()).toBe(200)+ expect(response?.fromServiceWorker()).toBe(true)+ expect(await response!.text()).toBe(cachedHtml)+ expect((await sessionResponse).ok()).toBe(true)+ expect((await entryResponse).ok()).toBe(true)+ await expect(reopened.getByTestId(tid.message(messageId))).toBeVisible()+ await expect(reopened.getByTestId(tid.composerInput)).toBeVisible()+ expect(new URL(reopened.url()).pathname + new URL(reopened.url()).search + new URL(reopened.url()).hash).toBe(target)+ await testInfo.attach("public-shell-warm-reopen", { body: JSON.stringify({ shellHash: hash, documentFromServiceWorker: true, deniedNetworkRequests, observedHistoryReadyMs: Date.now() - started }), contentType: "application/json" })+ await testInfo.attach("public-shell-warm-reopen-ui", { body: await reopened.screenshot(), contentType: "image/png" })+ }, async () => { await context.unroute(documentPath, denyDocumentNetwork) })+ })+test("a first Blog visit registers the root worker and installs the added Main public resources", async ({ page }, testInfo) => {await page.goto("/blog")await expect(page.getByRole("heading", { name: "Blog", exact: true })).toBeVisible()diff --git a/src/web/src/test/e2e-ui/_fixtures/case-fixture.ts b/src/web/src/test/e2e-ui/_fixtures/case-fixture.tsindex 06b7c0a8e..a95036e5a 100644--- a/src/web/src/test/e2e-ui/_fixtures/case-fixture.ts+++ b/src/web/src/test/e2e-ui/_fixtures/case-fixture.ts@@ -25,7 +25,7 @@ export type CaseActors = {recordServerDeletion: (role: UserKey, serverId: string, evidence: ServerDeletionEvidence) => Promise<void>}-export type SignedOutEvidence = { context: BrowserContext; page: Page; protectedResponse: APIResponse }+export type SignedOutEvidence = { context: BrowserContext; page: Page; publicDocumentResponse: APIResponse; protectedResponse: APIResponse }export type ServerDeletionEvidence = { page: Page; response: PlaywrightResponse }export type OwnedCaseResource<T> = { readonly value: T; close: () => Promise<void> }export type CaseResources = {@@ -284,10 +284,13 @@ export const test = base.extend<{ caseActors: CaseExitOwner["allocate"]; caseResif (!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 documentUrl = new URL(evidence.publicDocumentResponse.url())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 (responseUrl.origin !== WEB_URL || responseUrl.pathname !== "/api/community/servers" || evidence.protectedResponse.status() !== 401+ || documentUrl.origin !== WEB_URL || documentUrl.pathname !== "/c" || evidence.publicDocumentResponse.status() !== 200+ || !(await evidence.publicDocumentResponse.text()).includes('data-community-shell="public"')+ || pageUrl.origin !== WEB_URL || pageUrl.pathname !== "/sign-in" || pageUrl.searchParams.get("redirect") !== "/c"+ || (await evidence.context.cookies()).some((value) => value.name.startsWith("better-auth"))) throw new Error("Original cookie, public document and protected API 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 = trueexiting = truediff --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 df22a985d..60024c417 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@@ -93,7 +93,7 @@ async function holdCommunityReads(page: Page, resources?: CaseResources) {return { hits: () => hits, release }}-async function expectServerSeededRouteFrame(+async function expectPublicRouteFrame(page: Page,width: number,height: number,@@ -136,7 +136,8 @@ async function expectServerSeededRouteFrame(if (visibleFrames[0].initial) {expect(visibleFrames[0].busy).toBe("true")expect(visibleFrames[0].label).toBe("Loading community")- expect(visibleFrames[0].placeholders).toBeGreaterThan(0)+ await expect(frame).toHaveAttribute("data-community-route-kind", "community-root-redirect")+ await expect(page.locator('[data-slot="community-user-bar-base"]')).toHaveCount(0)} else expect(visibleFrames[0].slot).toBe("community-shell-root")expect(geometry.overflow).toBe(0)expect(visibleFrames[0]).toMatchObject({ x: 0, y: 0, width, height })@@ -563,9 +564,8 @@ export async function seedGeometryRoutes(main(page).getByText(content, { exact: true }).first()const threadMessageReady = (content: string) => (page: Page) => page.getByTestId(tid.threadSplitPanel).getByText(content, { exact: true }).first()- const threadComposerReady = (page: Page) => page- .getByTestId(tid.threadSplitPanel)- .getByTestId(tid.composerInput)+ const threadEntryPending = (page: Page) => page+ .getByTestId(tid.conversationResolutionPending).filter({ visible: true }).first()return [{ name: "me-list", pathname: "/c/me", mobileRail: true, ready: (page) => page.getByRole("link", { name: "Friends", exact: true }) },{ name: "friends", pathname: "/c/me/friends", ready: (page) => page.getByPlaceholder("Search friends") },@@ -578,8 +578,8 @@ export async function seedGeometryRoutes(pathname: `/c/channels/${serverId}/${forumId}`,ready: messageReady(forumTitle),intermediate: {- requestPattern: `**/api/community/channels/${forumId}/threads?**`,- ready: (page) => page.getByTestId(tid.forumFilterBar),+ requestPattern: `**/api/community/channels/${forumId}/messages**`,+ ready: (page) => page.getByLabel("Loading forum", { exact: true }).filter({ visible: true }).first(),},},{@@ -588,7 +588,7 @@ export async function seedGeometryRoutes(ready: threadMessageReady(threadMessage),intermediate: {requestPattern: `**/api/community/channels/${threadId}/messages**`,- ready: threadComposerReady,+ ready: threadEntryPending,},},{@@ -597,7 +597,7 @@ export async function seedGeometryRoutes(ready: threadMessageReady(forumMessage),intermediate: {requestPattern: `**/api/community/channels/${forumPostId}/messages**`,- ready: threadComposerReady,+ ready: threadEntryPending,},},]@@ -624,7 +624,7 @@ export async function runAndroidLoadingGeometry(actors: CaseActors, resources: Cawait 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 expectPublicRouteFrame(page, width, width === 320 ? 720 : 900)await page.waitForTimeout(250)ssrEvidence = {blockedScripts: [...scripts.blocked],@@ -634,7 +634,7 @@ export async function runAndroidLoadingGeometry(actors: CaseActors, resources: Cexpect(scripts.received, "application JS must remain blocked during SSR measurement").toEqual([])expect(scripts.sessionRequests(),- "server-seeded identity must not issue a browser session request",+ "blocked application scripts must not issue a browser session request",).toBe(0)await page.evaluate(() => Reflect.set(window, "__communityApplicationScriptsReleased", true))scripts.release()@@ -710,7 +710,7 @@ export async function runDesktopPersistedPendingGeometry(await expect.poll(() => scriptGate.blocked.length).toBeGreaterThan(0)expect(scriptGate.received).toEqual([])expect(scriptGate.sessionRequests()).toBe(0)- await expectServerSeededRouteFrame(page, viewportWidth, 900)+ await expectPublicRouteFrame(page, viewportWidth, 900)scriptGate.release()await expect.poll(communityReads.hits).toBeGreaterThan(0)await expect(page.locator('[data-slot="community-shell-root"]')).toBeVisible()@@ -773,7 +773,7 @@ export async function runSkeletonLoadingMotion(actors: CaseActors, resources: Caawait expect.poll(() => scripts.blocked.length).toBeGreaterThan(0)expect(scripts.received).toEqual([])expect(scripts.sessionRequests()).toBe(0)- await expectServerSeededRouteFrame(page, 320, 720)+ await expectPublicRouteFrame(page, 320, 720)scripts.release()await expect.poll(communityReads.hits).toBeGreaterThan(0)await page.getByRole("link", { name: "Machines", exact: true }).click()@@ -809,7 +809,7 @@ export async function runNeutralRootGeometry(expect(scripts.received).toEqual([])expect(scripts.sessionRequests()).toBe(0)- const frame = await expectServerSeededRouteFrame(page, width, width === 390 ? 844 : 900)+ const frame = await expectPublicRouteFrame(page, width, width === 390 ? 844 : 900)await expect(page.locator('[data-slot="community-shell-root"]')).toHaveCount(0)await expect(page.getByTestId(tid.initialRailPending)).toHaveCount(0)await expect(page.getByTestId(tid.dmSidebarPending)).toHaveCount(0)@@ -873,13 +873,11 @@ export async function runRouteLoadingGeometry(await expect.poll(() => scripts.blocked.length).toBeGreaterThan(0)expect(scripts.received).toEqual([])expect(scripts.sessionRequests()).toBe(0)- await expectServerSeededRouteFrame(+ await expectPublicRouteFrame(page,entry.width,entry.width === 390 ? 844 : 900,)- const ssrGeometry = await visibleGeometry(page)- await resetCls(page)scripts.release()await expect.poll(communityReads.hits).toBeGreaterThan(0)await expect(page.locator('[data-slot="community-shell-root"]')).toHaveCount(1)@@ -895,10 +893,18 @@ export async function runRouteLoadingGeometry(contentType: "image/png",})- expectSameGeometry(ssrGeometry, pendingGeometry)+ await resetCls(page)communityReads.release()if (entry.intermediate && intermediate) {+ await expect.poll(intermediate.hits).toBeGreaterThan(0)+ await expect(entry.ready(page)).toHaveCount(0)+ if (entry.name === "thread" || entry.name === "forum-post") {+ await expect(page.getByTestId(tid.threadSplitPanel).getByTestId(tid.composerInput)).toHaveCount(0)+ }await expect(entry.intermediate.ready(page)).toBeVisible({ timeout: 30_000 })+ if (entry.name === "thread" || entry.name === "forum-post") {+ await expect(entry.intermediate.ready(page)).toHaveAttribute("aria-busy", "true")+ }const intermediatePath = testInfo.outputPath(`${theme}-${entry.width}-${entry.name}-intermediate.png`,)@@ -910,6 +916,7 @@ export async function runRouteLoadingGeometry(intermediate.release()}await expect(entry.ready(page)).toBeVisible({ timeout: 30_000 })+ if (entry.name === "forum") await expect(page.getByTestId(tid.forumFilterBar)).toBeVisible()await expect(page.locator('[data-slot="community-shell-root"]')).toHaveCount(1)const loadedAdd = page.getByTestId(tid.serverAdd)if (entry.width === 1280 || entry.mobileRail) {diff --git a/src/web/src/test/e2e-ui/_fixtures/community-ssr-frame.ts b/src/web/src/test/e2e-ui/_fixtures/community-ssr-frame.tsindex 78cbbc1fe..2dae7e4c0 100644--- a/src/web/src/test/e2e-ui/_fixtures/community-ssr-frame.ts+++ b/src/web/src/test/e2e-ui/_fixtures/community-ssr-frame.ts@@ -1,73 +1,9 @@-import { createRequire } from "node:module"-import { resolve } from "node:path"import { expect, type Page } from "@playwright/test"-import type { CommunityDocumentSeed } from "@/lib/community/document-seed"import { tid } from "./testids"-const nodeRequire = createRequire(resolve(__dirname, "community-ssr-frame.ts"))--export async function readCommunityDocumentSeedFromHtml(html: string): Promise<CommunityDocumentSeed> {- const flight = [...html.matchAll(/self\.__next_f\.push\(\[1,("(?:\\.|[^"\\])*")\]\)/g)]- .map(match => JSON.parse(match[1]) as string).join("")- const bytes = new TextEncoder().encode(flight)- const decoder = new TextDecoder()- const data: Uint8Array[] = []- let seed: unknown- const findSeed = (value: unknown): unknown => {- if (!value || typeof value !== "object") return undefined- if (Object.hasOwn(value, "initialSeed")) return (value as { initialSeed: unknown }).initialSeed- for (const child of Object.values(value)) {- const result = findSeed(child)- if (result !== undefined) return result- }- }- for (let offset = 0; offset < bytes.length;) {- const start = offset- const colon = bytes.indexOf(58, offset)- expect(colon, "Flight record must have a separator").toBeGreaterThanOrEqual(offset)- const id = decoder.decode(bytes.subarray(offset, colon))- const payload = colon + 1- const tag = String.fromCharCode(bytes[payload])- expect(id).toMatch(tag === "H" ? /^[0-9a-f]*$/ : /^[0-9a-f]+$/)- const sized = "TAOobUSsLlGgMmV".includes(tag)- let end: number- if (sized) {- const comma = bytes.indexOf(44, payload + 1)- expect(comma, "Flight length must end with a comma").toBeGreaterThan(payload + 1)- const length = decoder.decode(bytes.subarray(payload + 1, comma))- expect(length).toMatch(/^[0-9a-f]+$/)- end = comma + 1 + Number.parseInt(length, 16)- expect(end).toBeLessThanOrEqual(bytes.length)- } else {- const newline = bytes.indexOf(10, payload)- expect(newline, "Flight line must be complete").toBeGreaterThanOrEqual(payload)- end = newline + 1- }- const model = !sized && !/^[A-Z#rx]$/.test(tag)- if (model) {- const value: unknown = JSON.parse(decoder.decode(bytes.subarray(payload, end - 1)))- if (seed === undefined) seed = findSeed(value)- }- if (id !== "0" && (sized || model || tag === "E")) data.push(bytes.subarray(start, end))- offset = end- }- expect(seed, "Document must contain initialSeed").not.toBeUndefined()- const { createFromReadableStream } = nodeRequire("next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.edge.production.js") as {- createFromReadableStream<T>(stream: ReadableStream<Uint8Array>, options: { serverConsumerManifest: { moduleMap: object; serverModuleMap: object; moduleLoading: null } }): Promise<T>- }- const decoded = await createFromReadableStream<CommunityDocumentSeed>(new ReadableStream<Uint8Array>({- start(controller) {- const root = new TextEncoder().encode(`0:${JSON.stringify(seed)}\n`)- const projected = new Uint8Array(root.length + data.reduce((size, record) => size + record.length, 0))- projected.set(root)- let offset = root.length- for (const record of data) { projected.set(record, offset); offset += record.length }- controller.enqueue(projected)- controller.close()- },- }), { serverConsumerManifest: { moduleMap: {}, serverModuleMap: {}, moduleLoading: null } })- expect(decoded, "Document seed must be resolved").toMatchObject({ viewerId: expect.any(String), entries: expect.any(Array) })- return decoded+export function expectPublicCommunityDocument(html: string) {+ expect(html).toContain('data-community-shell="public"')+ expect(html).not.toMatch(/initialSeed|viewerId|sessionToken/)}export async function expectUniqueSsrInitialFrame(page: Page) {diff --git a/src/web/src/test/e2e-ui/_fixtures/held-route.ts b/src/web/src/test/e2e-ui/_fixtures/held-route.tsnew file mode 100644index 000000000..7b5716f0f--- /dev/null+++ b/src/web/src/test/e2e-ui/_fixtures/held-route.ts@@ -0,0 +1,40 @@+import type { Page, Request, Route } from "@playwright/test"+import type { CaseResources } from "./case-fixture"++export async function holdRoute(page: Page, pattern: string | ((url: URL) => boolean), resources: CaseResources) {+ let releaseGate!: () => void+ const gate = new Promise<void>(resolve => { releaseGate = resolve })+ const pending = new Set<Request>()+ const continuations: Promise<void>[] = []+ let held = 0+ const settle = (request: Request) => { pending.delete(request) }+ page.on("requestfinished", settle)+ page.on("requestfailed", settle)+ const handler = (route: Route) => {+ const request = route.request()+ pending.add(request)+ held += 1+ const continuation = (async () => {+ await gate+ if (!pending.has(request)) return+ try { await route.continue() } catch (error) {+ if (pending.has(request)) throw error+ }+ })()+ continuations.push(continuation)+ return continuation+ }+ await page.route(pattern, handler)+ let closed = false+ const release = async () => {+ if (closed) return+ closed = true+ releaseGate()+ await Promise.all(continuations)+ await page.unroute(pattern, handler)+ page.off("requestfinished", settle)+ page.off("requestfailed", settle)+ }+ resources.own(release, async captured => { await captured() })+ return { held: () => held, release }+}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 2e5e0678c..092e1851c 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@@ -6,7 +6,7 @@ import { HostCommandSchema } from "@alook/shared/community-cli-contract"import { MACHINE_WS_URL, REPO_ROOT, WEB_URL } from "./_setup/paths"import type { APIResponse, Page, Request, TestInfo } from "@playwright/test"import { proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"-import { expectUniqueSsrCommunityFrame } from "./_fixtures/community-ssr-frame"+import { expectPublicCommunityDocument, expectUniqueSsrCommunityFrame } from "./_fixtures/community-ssr-frame"import { PERSIST_CACHE_PREFIX } from "@/lib/query-persister"import { expect, test } from "./_fixtures/case-fixture"@@ -148,7 +148,7 @@ async function clearQueryPersistence(page: Page) {async function expectCacheFirstReload(page: Page,- assertRscContent: () => Promise<void>,+ assertEntryContent: () => Promise<void>,assertCachedContent: () => Promise<void>,assertReconciledContent: () => Promise<void>, caseResources: CaseResources, independentParentEntry?: string): Promise<ReloadCapture> {@@ -201,6 +201,11 @@ async function expectCacheFirstReload(const url = new URL(route.request().url())const path = url.pathnameconst parentEntry = independentParentEntry && path === `/api/community/channels/${independentParentEntry}/messages` && url.searchParams.get("entry") === "1"+ const childEntry = url.searchParams.get("entry") === "1" && path.endsWith("/messages") && !parentEntry+ if (childEntry) {+ await route.continue()+ return+ }if (parentEntry) {heldReads += 1await readsGate@@ -222,7 +227,7 @@ async function expectCacheFirstReload(try {await page.reload({ waitUntil: "commit" })- await assertRscContent()+ await assertEntryContent()await expect.poll(() => heldReads).toBeGreaterThan(0)await expect.poll(() => wsAttempts).toBeGreaterThan(0)const readCapture = () => page.evaluate((): ReloadCapture | null => {@@ -272,7 +277,7 @@ async function expectCacheFirstReload(}}-test("a warm channel reload shows qualified RSC content while browser reads remain held", async ({ caseActors, caseResources }) => {+test("a warm channel reload shows entry-qualified cached content while browser reads remain held", async ({ caseActors, caseResources }) => {test.setTimeout(120_000)const actors = await caseActors(["alice"])@@ -309,7 +314,7 @@ test("a warm channel reload shows qualified RSC content while browser reads rema}, caseResources)})-test("a warm DM reload shows qualified RSC identity and history before browser reads", async ({ caseActors, caseResources }) => {+test("a warm DM reload shows entry-qualified identity and history before browser reads", async ({ caseActors, caseResources }) => {test.setTimeout(120_000)const actors = await caseActors(["alice", "bob"])@@ -352,7 +357,7 @@ test("a warm DM reload shows qualified RSC identity and history before browser r}, caseResources)})-test("a warm desktop thread reload keeps RSC child and independently reconciles its parent entry", async ({ caseActors, caseResources }) => {+test("a warm desktop thread reload qualifies its child and independently reconciles its parent entry", async ({ caseActors, caseResources }) => {test.setTimeout(120_000)const actors = await caseActors(["alice"])@@ -496,13 +501,14 @@ test("a true-cold channel load reuses localized skeletons without a custom bootsexpect(await page.evaluate(() => (performance.getEntriesByName("alook:restore:first-cached-paint", "mark").length))).toBe(0)- await expect(page.getByText(body, { exact: false }).first()).toBeVisible({ timeout: 20_000 })- await expect(page.getByTestId(tid.composerInput)).toBeVisible()+ await expect(page.getByText(body, { exact: false })).toHaveCount(0)+ await expect(page.getByTestId(tid.composerInput)).toHaveCount(0)} finally {releaseReads()await page.unroute("**/api/community/**")}await expect(page.getByText(body, { exact: false }).first()).toBeVisible({ timeout: 20_000 })+ await expect(page.getByTestId(tid.composerInput)).toBeVisible()})async function holdOriginalPersistedRead(page: Page, viewerId: string, oldId: string, newId: string) {@@ -686,7 +692,7 @@ async function retiredAccountDiskState(page: Page, viewerId: string, channelId:}), { prefix: PERSIST_CACHE_PREFIX, viewerId, channelId })}-test("late original IDB cannot replace RSC messages or revive a DM after a real WS block", async ({ caseActors, caseResources }, testInfo) => {+test("late original IDB cannot revive a DM after a real WS block", async ({ caseActors, caseResources }, testInfo) => {test.setTimeout(120_000)const actors = await caseActors(["alice", "bob"])const { asUser, userId } = actors@@ -701,7 +707,7 @@ test("late original IDB cannot replace RSC messages or revive a DM after a real{ key: ["community", "db", userId("alice"), "messages"], containsId: oldId },])await alice.page.goto("/")- const newBody = `new RSC DM ${Date.now()}`+ const newBody = `new private DM ${Date.now()}`const newId = await seedDmMessage("bob", dmId, newBody)await holdOriginalPersistedRead(alice.page, userId("alice"), oldId, newId)caseResources.own(alice.page, releaseOriginalPersistedRead)@@ -717,14 +723,15 @@ test("late original IDB cannot replace RSC messages or revive a DM after a realconst response = await alice.page.goto(`/c/me/${dmId}`, { waitUntil: "commit" })expect(response?.status()).toBe(200)const originalHtml = await response!.text()- expect(originalHtml).toContain(newId)+ expectPublicCommunityDocument(originalHtml)+ expect(originalHtml).not.toContain(newId)await expect.poll(() => alice.page.evaluate(() => {const state = Reflect.get(window, "__217DiskRead") as { held: number; oldPresent: boolean; newPresent: boolean }return { held: state.held, oldPresent: state.oldPresent, newPresent: state.newPresent }})).toEqual({ held: 1, oldPresent: true, newPresent: false })- await expect(alice.page.getByTestId(tid.message(newId))).toBeVisible()- await expect(alice.page.getByTestId(tid.message(newId)).getByText(newBody, { exact: true })).toBeVisible()- await expect(alice.page.getByTestId(tid.composerInput)).toBeVisible()+ await expect(alice.page.getByTestId(tid.message(oldId))).toHaveCount(0)+ await expect(alice.page.getByTestId(tid.message(newId))).toHaveCount(0)+ await expect(alice.page.getByTestId(tid.composerInput)).toHaveCount(0)expect(targetGets).toEqual([])await expect.poll(() => proxy.connectionFrames.some(frame => frame.type === "auth.ok")).toBe(true)const blocked = await bob.page.request.post(`/api/community/users/${userId("alice")}/block`)@@ -736,13 +743,14 @@ test("late original IDB cannot replace RSC messages or revive a DM after a realawait expect(alice.page.getByTestId(tid.message(newId))).toHaveCount(0)await expect(alice.page.getByTestId(tid.composerInput)).toHaveCount(0)await releaseOriginalPersistedRead(alice.page)+ releaseNetwork()await expect.poll(() => alice.page.evaluate(() => performance.getEntriesByName("alook:restore:complete", "mark").length)).toBe(1)await expect(alice.page.getByRole("alert").filter({ hasText: "You can no longer read this conversation." })).toBeVisible()await expect(alice.page).toHaveURL(new RegExp(`/c/me/${dmId}$`))await expect(alice.page.getByTestId(tid.message(oldId))).toHaveCount(0)await expect(alice.page.getByTestId(tid.message(newId))).toHaveCount(0)await expect(alice.page.getByTestId(tid.composerInput)).toHaveCount(0)- await testInfo.attach("late-idb-rsc-ws-boundaries", { body: JSON.stringify({ dmId, oldId, newId, originalHtmlContainsNewId: originalHtml.includes(newId), denied: denied.status(), wsBlock: proxy.frames.filter(frame => frame.type === "community:friend.block").map(frame => ({ type: frame.type, userId: frame.userId })) }), contentType: "application/json" })+ await testInfo.attach("late-idb-public-shell-ws-boundaries", { body: JSON.stringify({ dmId, oldId, newId, originalHtmlContainsNewId: originalHtml.includes(newId), denied: denied.status(), wsBlock: proxy.frames.filter(frame => frame.type === "community:friend.block").map(frame => ({ type: frame.type, userId: frame.userId })) }), contentType: "application/json" })} finally {await releaseOriginalPersistedRead(alice.page)releaseNetwork()@@ -1010,7 +1018,8 @@ for (const lateSource of ["query", "idb"] as const) {})return id})- await expect(page.getByTestId(tid.message(aliceMessage))).toBeVisible()+ if (held) await expect(page.getByTestId(tid.message(aliceMessage))).toBeVisible()+ else await expect(page.getByTestId(tid.message(aliceMessage))).toHaveCount(0)if (held) {await expect.poll(() => held.captured() !== undefined).toBe(true)expect(held.captured()?.status).toBe(200)