Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

perf(web): decouple community seeds and forum navigation (#1044)

Gener882842781d31
diff --git a/src/web/src/app/c/QueryProvider.document.dom.test.tsx b/src/web/src/app/c/QueryProvider.document.dom.test.tsx
index 62ecf98fd..9f4453d50 100644
--- a/src/web/src/app/c/QueryProvider.document.dom.test.tsx
+++ b/src/web/src/app/c/QueryProvider.document.dom.test.tsx
@@ -1,14 +1,17 @@
import "fake-indexeddb/auto"
-import React from "react"
+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 } from "@/test/conversation-entry-fixtures"
+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 { useMessages } from "@/hooks/community/use-messages"
+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"
@@ -32,9 +35,28 @@ vi.mock("@/lib/community/conversation-entry.server", () => ({ readCommunityConve
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() {
@@ -55,6 +77,217 @@ beforeEach(() => {
})
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()
@@ -195,11 +428,13 @@ describe("initial document seed in the actual native account provider", () => {
view.unmount()
})
- it("rejects another viewer's document before the native DB hydrate call", async () => {
+ 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={seed}><AccountProbe /></QueryProvider>)
+ 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()
diff --git a/src/web/src/app/c/QueryProvider.tsx b/src/web/src/app/c/QueryProvider.tsx
index f1150d716..c33e4b646 100644
--- a/src/web/src/app/c/QueryProvider.tsx
+++ b/src/web/src/app/c/QueryProvider.tsx
@@ -1,6 +1,6 @@
"use client"
-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"
+import { Suspense, use, 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,18 +30,64 @@ 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 { discardCommunityRestoreReplacements, installCommunityDbSync, restoreCommunityCollections } from "@/lib/community-db/sync"
+import { captureCommunityLiveSnapshotToken, 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 } from "@/lib/community/document-seed"
+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
@@ -108,7 +154,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?: CommunityDocumentSeed }) {
+export function QueryProvider(props: { children: ReactNode; userId: string | null; initialUser?: CurrentUser; initialSeed?: CommunityDocumentSeedInput }) {
const session = useSession()
return <ScopedQueryProvider key={props.userId ?? "anon"} {...props} session={session} sessionViewer={currentSessionViewer} />
}
@@ -124,7 +170,7 @@ function ScopedQueryProvider({
children: ReactNode
userId: string | null
initialUser?: CurrentUser
- initialSeed?: CommunityDocumentSeed
+ initialSeed?: CommunityDocumentSeedInput
session: ReturnType<typeof useSession>
sessionViewer: () => string | null | undefined
}) {
@@ -145,9 +191,29 @@ function ScopedQueryProvider({
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) installCommunityDocumentSeed(queryClient, registry, initialSeed, viewer)
+ 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 unreadProjection = useMemo(
() => userId ? getAccountUnreadProjection(queryClient, userId) : null,
[queryClient, userId],
@@ -254,7 +320,7 @@ function ScopedQueryProvider({
queryClient={queryClient}
registry={communityDb}
>
- {children}
+ {deferredSeed ? <DocumentSeedContent delivery={deferredSeed} client={queryClient} registry={communityDb}>{children}</DocumentSeedContent> : children}
{isDev ? <ReactQueryDevtools initialIsOpen={false} /> : null}
</CommunityDbRuntime> : null}
</PersistQueryClientProvider>
diff --git a/src/web/src/app/c/community-layout-client.tsx b/src/web/src/app/c/community-layout-client.tsx
index ae63a2064..a8c45de68 100644
--- a/src/web/src/app/c/community-layout-client.tsx
+++ b/src/web/src/app/c/community-layout-client.tsx
@@ -14,7 +14,7 @@ import {
retireCommunityColdEntryAttempt,
} from "@/lib/community/last-community-route"
import type { CurrentUser } from "@/contexts/community/current-user"
-import type { CommunityDocumentSeed } from "@/lib/community/document-seed"
+import type { CommunityDocumentSeedInput } from "@/lib/community/document-seed"
function isPublicCommunityPath(pathname: string): boolean {
return resolveCommunityModulePlan(pathname).route === "public-invite"
@@ -29,7 +29,7 @@ export function CommunityLayoutClient({
children: ReactNode
sidebar: ReactNode
currentUser: CurrentUser | null
- initialSeed?: CommunityDocumentSeed
+ initialSeed?: CommunityDocumentSeedInput
}) {
const router = useRouter()
const pathname = usePathname()
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.ts
index b33ae0fd4..2dfb89323 100644
--- a/src/web/src/app/c/community-shell.document.server.test.ts
+++ b/src/web/src/app/c/community-shell.document.server.test.ts
@@ -1,14 +1,14 @@
import { createElement, type ReactNode } from "react"
-import { renderToString } from "react-dom/server"
+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 { useOptionalCommunityDbRegistry } from "@/lib/community-db/projections"
+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 }))
+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() }) }))
@@ -21,13 +21,65 @@ vi.mock("@/components/community/onboarding/community-onboarding-form", () => ({
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 () => ({ ok: true, entry: documentTarget.dm ? dmConversationEntryFixture() : conversationEntryFixture() }) }))
+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 actual %s message rows through the real message list 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: "" }
diff --git a/src/web/src/app/c/community-shell.tsx b/src/web/src/app/c/community-shell.tsx
index ab3216abd..dfd75afc3 100644
--- a/src/web/src/app/c/community-shell.tsx
+++ b/src/web/src/app/c/community-shell.tsx
@@ -25,7 +25,7 @@ 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 { CommunityDocumentSeed } from "@/lib/community/document-seed"
+import type { CommunityDocumentSeedInput } from "@/lib/community/document-seed"
/**
* Client wrapper that provides the QueryClient, CurrentUser, and the
@@ -47,7 +47,7 @@ export function CommunityShell({
}: {
currentUser: CurrentUser
children: ReactNode
- initialSeed?: CommunityDocumentSeed
+ initialSeed?: CommunityDocumentSeedInput
}) {
return (
<QueryProvider userId={currentUser.id} initialUser={currentUser} initialSeed={initialSeed}>
diff --git a/src/web/src/app/c/layout.server.test.ts b/src/web/src/app/c/layout.server.test.ts
index 76ed85ec7..1b7d80a7c 100644
--- a/src/web/src/app/c/layout.server.test.ts
+++ b/src/web/src/app/c/layout.server.test.ts
@@ -139,7 +139,7 @@ describe("CommunityLayout server session streaming", () => {
expect(mocks.client).toHaveBeenCalledTimes(1)
expect(mocks.client).toHaveBeenCalledWith({
currentUser,
- initialSeed: seed,
+ initialSeed: expect.any(Promise),
children,
sidebar,
})
@@ -159,7 +159,7 @@ describe("CommunityLayout server session streaming", () => {
await rendering.finished
expect(mocks.client).toHaveBeenCalledWith({
currentUser,
- initialSeed: seed,
+ initialSeed: expect.any(Promise),
children,
sidebar,
})
@@ -174,20 +174,22 @@ describe("CommunityLayout server session streaming", () => {
expect(rendering.errors).toEqual([])
})
- it("keeps streaming the public skeleton while authenticated document data is held", async () => {
+ 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 first = await rendering.publicFrame
- expect(first).toContain("community-initial-frame")
- expect(first).not.toContain("Canonical Ada")
- expect(first).not.toContain("private-child")
- expect(mocks.client).not.toHaveBeenCalled()
+ 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 rendering.finished
- expect(mocks.client).toHaveBeenCalledWith(expect.objectContaining({ currentUser, initialSeed: seed }))
+ await expect(pending).resolves.toBe(seed)
expect(rendering.errors).toEqual([])
} finally { rendering.abort() }
})
@@ -228,7 +230,7 @@ describe("Bots document Machine-list primary connection", () => {
expect(mocks.self).toHaveBeenCalledWith(selected, "account-a")
expect(mocks.bots).toHaveBeenCalledWith(selected, "account-a")
expect(mocks.machines).toHaveBeenCalledWith(selected, "account-a")
- expect(mocks.client.mock.calls[0]![0].initialSeed).toMatchObject({ viewerId: "account-a", machines: { machines: [] }, bots: { bots: [] } })
+ 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"
@@ -283,7 +285,7 @@ describe("document session eligibility before profile and seed reads", () => {
expect(mocks.cloudflareContext).toHaveBeenCalledOnce()
expect(mocks.self).toHaveBeenCalledOnce()
expect(mocks.seed).toHaveBeenCalledOnce()
- expect(mocks.client).toHaveBeenCalledExactlyOnceWith({ currentUser, initialSeed: seed, children, sidebar })
+ expect(mocks.client).toHaveBeenCalledExactlyOnceWith({ currentUser, initialSeed: expect.any(Promise), children, sidebar })
expect(rendering.errors).toEqual([])
})
})
diff --git a/src/web/src/app/c/layout.tsx b/src/web/src/app/c/layout.tsx
index 2e2004f42..87a3ae461 100644
--- a/src/web/src/app/c/layout.tsx
+++ b/src/web/src/app/c/layout.tsx
@@ -27,9 +27,9 @@ async function CommunitySessionLayout({ children, sidebar }: CommunityLayoutProp
const authenticated = session && session.user.isBot !== true && (session.user.deletedAt ?? null) === null
? await loadDocument(session.user.id) : null
const currentUser = authenticated?.viewer ? {
- ...authenticated.seed.selfProfile,
+ ...authenticated.profile,
email: authenticated.viewer.email,
- avatar: authenticated.seed.selfProfile.avatar || avatarInitial(authenticated.seed.selfProfile.name),
+ avatar: authenticated.profile.avatar || avatarInitial(authenticated.profile.name),
} : null
return (
@@ -46,5 +46,9 @@ async function loadDocument(viewerId: string) {
const db = kind === "machines" || kind === "bots" ? getPrimaryDb(env.DB) : getDb(env.DB)
const { viewer, profile } = await readCommunitySelfProfile(db, viewerId)
if (!viewer) return null
- return { viewer, seed: await readCommunityDocumentSeed(db, viewerId, href, profile) }
+ const seed = readCommunityDocumentSeed(db, viewerId, href, profile).catch((error: unknown) => {
+ console.error("Community document prefetch failed", error)
+ return null
+ })
+ return { viewer, profile, seed }
}
diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsx
index 38d15a213..500f2ad90 100644
--- a/src/web/src/components/community/channels/channel-route.tsx
+++ b/src/web/src/components/community/channels/channel-route.tsx
@@ -410,6 +410,12 @@ function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, rou
serverId={serverId}
channelId={channelId}
channelName={channelName}
+ routeTag={searchParams.get("tag")}
+ onSelectTag={(tag) => {
+ const next = new URLSearchParams(searchParams)
+ next.set("tag", tag === "All" ? "" : tag)
+ navigation.replace(`${channelHref(serverParam, channelId)}?${next}`)
+ }}
viewer={currentUser}
viewerRole={myRole}
onNavigateParent={navigateServerRoot}
diff --git a/src/web/src/components/community/channels/forum-channel-surface.tsx b/src/web/src/components/community/channels/forum-channel-surface.tsx
index 4786106cb..e06eb191e 100644
--- a/src/web/src/components/community/channels/forum-channel-surface.tsx
+++ b/src/web/src/components/community/channels/forum-channel-surface.tsx
@@ -38,6 +38,8 @@ export function ForumChannelSurface({
onOpenPost,
onOpenProfile,
embedded = false,
+ routeTag,
+ onSelectTag,
}: {
serverId: string
channelId: string
@@ -54,6 +56,8 @@ export function ForumChannelSurface({
onOpenPost: (postId: string) => void
onOpenProfile: OpenProfile
embedded?: boolean
+ routeTag?: string | null
+ onSelectTag?: (tag: string) => void
}) {
const source = useCommunityViewSource(`forum-surface:${serverId}:${channelId}`)
const [panelState, setPanelState] = useAtom(useCreateAtom<{ channelId: string; panel: RightPanel }>({
@@ -115,6 +119,8 @@ export function ForumChannelSurface({
<ForumSurface
serverId={serverId}
forumChannelId={channelId}
+ routeTag={routeTag}
+ onSelectTag={onSelectTag}
members={composerMembers}
mentionCandidates={composerMentionCandidates}
onOpenPost={onOpenPost}
diff --git a/src/web/src/components/community/channels/forum-surface.dom.test.ts b/src/web/src/components/community/channels/forum-surface.dom.test.ts
index 0e2957a86..34be45a2c 100644
--- a/src/web/src/components/community/channels/forum-surface.dom.test.ts
+++ b/src/web/src/components/community/channels/forum-surface.dom.test.ts
@@ -48,6 +48,10 @@ const mocks = vi.hoisted(() => ({
isError: false,
refetch: vi.fn(() => Promise.resolve()),
tag: "All",
+ selectionReady: true,
+ tagsKnown: true,
+ tagsError: false,
+ retryTags: vi.fn(),
availableTags: [],
selectTag: vi.fn(),
hasMoreOlder: false,
diff --git a/src/web/src/components/community/channels/forum-surface.pagination.dom.test.ts b/src/web/src/components/community/channels/forum-surface.pagination.dom.test.ts
index 7bf540a69..7d0538024 100644
--- a/src/web/src/components/community/channels/forum-surface.pagination.dom.test.ts
+++ b/src/web/src/components/community/channels/forum-surface.pagination.dom.test.ts
@@ -26,7 +26,7 @@ vi.mock("@/hooks/community/use-forum-feed", async () => {
staleTime: Infinity, retry: 1, retryDelay: 0,
})
return {
- ...query, posts: query.data.pages.flatMap(value => value.posts), tag: "All",
+ ...query, posts: query.data.pages.flatMap(value => value.posts), tag: "All", selectionReady: true,
availableTags: [], selectTag: vi.fn(), hasMoreOlder: query.hasNextPage,
isFetchingOlder: query.isFetchingNextPage, fetchOlder: () => { void query.fetchNextPage() },
}
diff --git a/src/web/src/components/community/channels/forum-surface.tsx b/src/web/src/components/community/channels/forum-surface.tsx
index d7b144837..393b97bb5 100644
--- a/src/web/src/components/community/channels/forum-surface.tsx
+++ b/src/web/src/components/community/channels/forum-surface.tsx
@@ -14,9 +14,11 @@ import { useTimelineReadObserver } from "@/hooks/community/use-read-observer"
import { isConversationAccessError } from "@/lib/community/conversation-read"
import { ConversationResolutionErrorFrame } from "./conversation-resolution-error-frame"
-export function ForumSurface({ serverId, forumChannelId, ...props }: {
+export function ForumSurface({ serverId, forumChannelId, routeTag, onSelectTag, ...props }: {
serverId: string
forumChannelId: string
+ routeTag?: string | null
+ onSelectTag?: (tag: string) => void
members: Member[]
mentionCandidates?: ComposerProps["mentionCandidates"]
onOpenPost: (id: string) => void
@@ -28,8 +30,8 @@ export function ForumSurface({ serverId, forumChannelId, ...props }: {
canDeletePost?: (post: ForumThread) => boolean
deletingPost?: string | null
}) {
- const feed = useForumFeed(serverId, forumChannelId)
- const readState = useConversationEntry({ channelId: forumChannelId, serverId })
+ const feed = useForumFeed(serverId, forumChannelId, { routeTag, onSelectTag })
+ const readState = useConversationEntry(feed.selectionReady ? { channelId: forumChannelId, serverId, tag: feed.tag === "All" ? null : feed.tag } : null)
const [scrollRootEl, setScrollRootEl] = useAtom(useCreateAtom<HTMLDivElement | null>(null))
const retryScope = JSON.stringify([forumChannelId, feed.tag])
const [retryAttempt, setRetryAttempt] = useAtom(useCreateAtom<{ scope: string } | null>(null))
@@ -85,9 +87,12 @@ export function ForumSurface({ serverId, forumChannelId, ...props }: {
{...props}
posts={feed.posts}
observation={feed.observation}
- loading={feed.isPending}
- tag={feed.tag}
+ loading={!feed.selectionReady || feed.isPending}
+ tag={feed.selectionReady ? feed.tag : ""}
availableTags={feed.availableTags}
+ tagsKnown={feed.tagsKnown}
+ tagsError={feed.tagsError}
+ onRetryTags={() => { void feed.retryTags() }}
onTagChange={feed.selectTag}
hasMore={feed.hasMoreOlder}
loadingMore={feed.isFetchingOlder}
diff --git a/src/web/src/components/community/channels/forum-view.categories.dom.test.tsx b/src/web/src/components/community/channels/forum-view.categories.dom.test.tsx
new file mode 100644
index 000000000..a4323dcb3
--- /dev/null
+++ b/src/web/src/components/community/channels/forum-view.categories.dom.test.tsx
@@ -0,0 +1,50 @@
+import { expect, it, vi } from "vitest"
+import { fireEvent, mockElementGeometry, render } from "@/test/react-dom-harness"
+import type { ForumThread } from "@/lib/community/models/message"
+import { tid } from "@/lib/community/testids"
+import { ForumView } from "./forum-view"
+
+vi.mock("@/lib/community-db/projections", () => ({ useCanonicalProfilesByUserId: () => new Map() }))
+
+const post: ForumThread = {
+ id: "post", name: "Post", messageCount: 1, lastMessageAt: "2026-10-22T10:00:00Z",
+ parent: { authorName: "Author", text: "Root" }, authorId: "author", authorAvatar: "A", authorAvatarVersion: 0,
+ openerMessageId: "opener", tags: ["partial"], preview: "Preview", participants: [], participantCount: 1,
+}
+const props = {
+ forumChannelId: "forum", members: [], posts: [post], tag: "All", onTagChange: () => {}, onOpenPost: () => {},
+ onScrollRoot: (node: HTMLDivElement | null) => { if (node) mockElementGeometry(node, { clientHeight: 600, clientWidth: 390 }) },
+}
+
+it("keeps posts while unknown tags settle to the complete sorted vocabulary", () => {
+ const view = render(<ForumView {...props} tagsKnown={false} availableTags={[]} />)
+ const card = view.getByTestId(tid.forumThreadCard("post"))
+ expect(view.getByRole("status", { name: "Loading tag filters" })).toBeVisible()
+ expect(view.getByRole("status", { name: "Loading tag filters" })).toHaveClass("h-7")
+ expect(view.queryByTestId(tid.forumTagChip("partial"))).toBeNull()
+ expect(view.queryByTestId(tid.forumTagAll)).toBeNull()
+ view.rerender(<ForumView {...props} tagsKnown availableTags={["apple", "archived", "zebra"]} />)
+ const rail = view.getByTestId(tid.forumTagScroller)
+ expect([...rail.querySelectorAll("button")].map(button => button.textContent)).toEqual(["All", "#apple", "#zebra", "Archived"])
+ expect(view.getByTestId(tid.forumThreadCard("post"))).toBe(card)
+})
+
+it("renders a confirmed empty catalog without deriving categories from current posts", () => {
+ const view = render(<ForumView {...props} tagsKnown availableTags={[]} />)
+ expect(view.getByTestId(tid.forumTagAll)).toBeVisible()
+ expect(view.queryByTestId(tid.forumTagChip("partial"))).toBeNull()
+ expect(view.queryByRole("status", { name: "Loading tag filters" })).toBeNull()
+ expect(view.getByTestId(tid.forumThreadCard("post"))).toBeVisible()
+})
+
+it("retries only unavailable tags and retains a complete cached catalog through errors", () => {
+ const retry = vi.fn()
+ const view = render(<ForumView {...props} tagsKnown={false} tagsError onRetryTags={retry} />)
+ expect(view.getByRole("button", { name: "Retry tags" })).toHaveClass("h-7", "leading-5")
+ fireEvent.click(view.getByRole("button", { name: "Retry tags" }))
+ expect(retry).toHaveBeenCalledOnce()
+ expect(view.getByTestId(tid.forumThreadCard("post"))).toBeVisible()
+ view.rerender(<ForumView {...props} tagsKnown tagsError availableTags={["cached"]} onRetryTags={retry} />)
+ expect(view.getByTestId(tid.forumTagChip("cached"))).toBeVisible()
+ expect(view.queryByRole("button", { name: "Retry tags" })).toBeNull()
+})
diff --git a/src/web/src/components/community/channels/forum-view.native-layout.dom.test.tsx b/src/web/src/components/community/channels/forum-view.native-layout.dom.test.tsx
index 523ecee50..a68c16fb1 100644
--- a/src/web/src/components/community/channels/forum-view.native-layout.dom.test.tsx
+++ b/src/web/src/components/community/channels/forum-view.native-layout.dom.test.tsx
@@ -166,3 +166,71 @@ it("keeps the original paging boundary while rendering a larger reserve", () =>
view.rerender(createElement(ForumView, props))
expect(onLoadMore).toHaveBeenCalledTimes(1)
})
+
+it("keeps a new Forum instance at the start through hidden mounting and positive-size delivery", () => {
+ let visible = false
+ rowHeight = () => visible ? 160 : 0
+ const writes: number[] = []
+ const frames = new Map<number, FrameRequestCallback>()
+ let frameId = 0
+ vi.spyOn(window, "requestAnimationFrame").mockImplementation(callback => { frames.set(++frameId, callback); return frameId })
+ vi.spyOn(window, "cancelAnimationFrame").mockImplementation(id => { frames.delete(id) })
+ const props = {
+ forumChannelId: "forum-hidden-return", members: [], posts: posts.slice(0, 15), tag: "All",
+ onTagChange: () => {}, onOpenPost: () => {},
+ onScrollRoot: (node: HTMLDivElement | null) => {
+ if (!node) return
+ Object.defineProperties(node, {
+ clientWidth: { configurable: true, get: () => visible ? 390 : 0 },
+ clientHeight: { configurable: true, get: () => visible ? 751 : 0 },
+ scrollHeight: { configurable: true, get: () => visible ? Math.max(node.clientHeight, (Number.parseFloat((node.firstElementChild as HTMLElement)?.style.height ?? "0") || 0) + 16) : 0 },
+ scrollTo: { configurable: true, value: ({ top = 0 }: ScrollToOptions) => {
+ node.scrollTop = Math.max(0, Math.min(top, node.scrollHeight - node.clientHeight))
+ writes.push(node.scrollTop)
+ } },
+ })
+ },
+ }
+ const enter = () => {
+ const view = render(createElement(ForumView, props))
+ const root = view.getByTestId(tid.forumPostList)
+ visible = true
+ for (let pass = 0; pass < 4; pass++) act(() => {
+ for (const [callback, nodes] of [...observers]) {
+ const entries = [...nodes].map<ResizeObserverEntry>(node => {
+ const height = node.hasAttribute("data-index") ? rowHeight(Number((node as HTMLElement).dataset.index)) : 751
+ return { target: node, borderBoxSize: [{ blockSize: height, inlineSize: 390 }], contentBoxSize: [{ blockSize: height, inlineSize: 390 }], devicePixelContentBoxSize: [], contentRect: new DOMRect(0, 0, 390, height) }
+ })
+ if (entries.length) callback(entries, {} as ResizeObserver)
+ }
+ root.dispatchEvent(new Event("scroll"))
+ const pending = [...frames.values()]
+ frames.clear()
+ for (const callback of pending) callback(performance.now())
+ })
+ expect(root.scrollHeight).toBeGreaterThan(root.clientHeight)
+ expect(root.scrollTop).toBe(0)
+ expect(root.querySelector("[data-index]")).toHaveAttribute("data-index", "0")
+ expect(writes.every(offset => offset === 0)).toBe(true)
+ return { view, root }
+ }
+ const first = enter()
+ act(() => { first.root.scrollTop = 700; first.root.dispatchEvent(new Event("scroll")) })
+ const measuredHeight = first.root.scrollHeight
+ act(() => {
+ for (const [callback, nodes] of [...observers]) {
+ const entries = [...nodes].filter(node => node.hasAttribute("data-index")).map<ResizeObserverEntry>(node => ({
+ target: node, borderBoxSize: [{ blockSize: 0, inlineSize: 0 }], contentBoxSize: [{ blockSize: 0, inlineSize: 0 }], devicePixelContentBoxSize: [], contentRect: new DOMRect(),
+ }))
+ if (entries.length) callback(entries, {} as ResizeObserver)
+ }
+ })
+ expect(first.root.scrollHeight).toBe(measuredHeight)
+ expect(first.root.scrollTop).toBe(700)
+ first.view.unmount()
+ visible = false
+ writes.length = 0
+ const returned = enter()
+ expect(returned.root).not.toBe(first.root)
+ returned.view.unmount()
+})
diff --git a/src/web/src/components/community/channels/forum-view.test.ts b/src/web/src/components/community/channels/forum-view.test.ts
index ad52edcf6..1589ae7ba 100644
--- a/src/web/src/components/community/channels/forum-view.test.ts
+++ b/src/web/src/components/community/channels/forum-view.test.ts
@@ -286,9 +286,10 @@ describe("ForumView responsive post actions", () => {
for (const button of [tagButton, archiveButton, deleteButton]) {
expect(button).toContain("size-8")
expect(button).toContain("opacity-100")
- expect(button).toContain("sm:size-6")
+ expect(button).not.toContain("sm:size-")
expect(button).toContain("sm:opacity-0")
- expect(button).toContain("sm:focus-visible:opacity-100")
+ expect(button).toContain("sm:group-focus-within/card:opacity-100")
+ expect(button).not.toContain("transition-opacity")
expect(button).toContain("sm:group-hover/card:opacity-100")
}
expect(tagButton).toContain("sm:data-popup-open:opacity-100")
@@ -296,7 +297,7 @@ describe("ForumView responsive post actions", () => {
expect(archiveButton).toContain('aria-pressed="false"')
expect(archiveButton).toContain("disabled:opacity-50")
expect(deleteButton).toContain("disabled:opacity-50")
- expect(html).toContain("min-h-8 pr-28 sm:min-h-0 sm:pr-22")
+ expect(html).toContain("min-h-8 pr-28")
expect(html).toContain("w-full min-w-0 max-w-full text-[15px] font-semibold leading-tight")
expect(html).toContain(tid.forumThreadTitle("p1"))
expect(html).toContain(tid.forumThreadTitleText("p1"))
@@ -338,7 +339,7 @@ describe("ForumView responsive post actions", () => {
expect(html).not.toContain(tid.forumThreadTagBtn("p1"))
expect(html).not.toContain(tid.forumThreadArchiveBtn("p1"))
expect(html).toContain(tid.forumThreadDeleteBtn("p1"))
- expect(html).toContain("min-h-8 pr-12 sm:min-h-0 sm:pr-8")
+ expect(html).toContain("min-h-8 pr-12")
})
})
diff --git a/src/web/src/components/community/channels/forum-view.tsx b/src/web/src/components/community/channels/forum-view.tsx
index d6d44172b..3589cdb11 100644
--- a/src/web/src/components/community/channels/forum-view.tsx
+++ b/src/web/src/components/community/channels/forum-view.tsx
@@ -4,7 +4,7 @@ import { useObservedRegion } from "@/lib/observability/regions"
import { visibleVirtualItems } from "@/lib/observability/virtual-window"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
import { memo, useCallback, useLayoutEffect, useMemo, useRef } from "react"
-import { defaultRangeExtractor, useVirtualizer, type Range } from "@tanstack/react-virtual"
+import { defaultRangeExtractor, measureElement, useVirtualizer, type Range } from "@tanstack/react-virtual"
import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS } from "@/hooks/community/virtualizer-react-options"
import { Archive, ArchiveRestore, MessagesSquare, ListChevronsUpDown, Plus, Tag, Trash2 } from "lucide-react"
import { Button } from "@/components/ui/button"
@@ -39,6 +39,7 @@ const MAX_AVATARS = 5
const MAX_VISIBLE_TAGS = 2
const FORUM_VIRTUALIZER_DOM_MODE = "position"
const FORUM_VIRTUALIZER_OVERSCAN = 5
+const POST_ACTION_CLASS = "grid size-8 shrink-0 place-items-center rounded-md text-muted-foreground opacity-100 sm:opacity-0 sm:group-focus-within/card:opacity-100 sm:group-hover/card:opacity-100 sm:data-popup-open:opacity-100 disabled:cursor-not-allowed disabled:opacity-50"
const forumRangeExtractor = (range: Range) => defaultRangeExtractor({
...range,
overscan: range.overscan + range.endIndex - range.startIndex + 1,
@@ -129,16 +130,12 @@ const ForumPostTitle = memo(function ForumPostTitle({ name, postId, seq }: { nam
)
})
-// Forum channel body — rendered under the shared ChannelHeader. A feed of posts;
-// each post opens as a thread. The filter bar's tag chips are DERIVED from the
-// posts themselves (the deduped union of every post's tags) — there is no
-// forum-level tag vocabulary. Per-post tags are edited from a hover icon on each
-// card (creator + server managers), not a forum-wide manage mode.
export function ForumView({
forumChannelId,
members,
mentionCandidates,
posts, loading, observation, tag, availableTags = [], onTagChange, onOpenPost, onCreatePost, onEditPostTags, canEditPostTags, savingTagsFor,
+ tagsKnown = true, tagsError = false, onRetryTags,
hasMore, loadingMore, isFetching, isError, onLoadMore,
onDeletePost, canDeletePost, deletingPost,
onScrollRoot,
@@ -151,6 +148,9 @@ export function ForumView({
loading?: boolean
tag: string
availableTags?: string[]
+ tagsKnown?: boolean
+ tagsError?: boolean
+ onRetryTags?: () => void
onTagChange: (tag: string) => void
hasMore?: boolean
loadingMore?: boolean
@@ -197,6 +197,13 @@ export function ForumView({
count: posts.length,
getScrollElement: () => scrollRef.current,
estimateSize,
+ measureElement: (element, entry, instance) => {
+ const size = measureElement(element, entry, instance)
+ if (size > 0) return size
+ const index = instance.indexFromElement(element)
+ const cached = instance.itemSizeCache.get(instance.options.getItemKey(index))
+ return cached && cached > 0 ? cached : instance.options.estimateSize(index)
+ },
getItemKey,
overscan: FORUM_VIRTUALIZER_OVERSCAN,
rangeExtractor: forumRangeExtractor,
@@ -215,9 +222,7 @@ export function ForumView({
}, [paginationRange, posts.length, virtualItems])
const observedPosts = visibleVirtualItems(virtualizer).flatMap(item => posts[item.index] ? [posts[item.index]] : [])
useObservedRegion("forum", (!loading || posts.length > 0) && (!posts.length || observedPosts.length > 0), observedPosts.length, observation)
- const filterTags = availableTags.length > 0
- ? availableTags
- : [...new Set(posts.flatMap((post) => post.tags))]
+ const filterTags = [...new Set(availableTags)]
const hasArchivedPosts = filterTags.includes(FORUM_ARCHIVE_TAG)
const displayFilterTags = [
...filterTags.filter((candidate) => candidate !== FORUM_ARCHIVE_TAG),
@@ -291,7 +296,13 @@ export function ForumView({
onKeyDown={onTagRailKeyDown}
className="flex w-full min-w-0 flex-nowrap items-center gap-2 overflow-x-auto overscroll-x-contain thin-scrollbar scrollbar-none"
>
- {filterTags.length > 0 && (
+ {!tagsKnown ? tagsError ? (
+ <button type="button" className="h-7 shrink-0 rounded-lg px-2.75 py-1 text-[13px] leading-5 text-muted-foreground hover:text-foreground" onClick={onRetryTags}>Retry tags</button>
+ ) : (
+ <div role="status" aria-label="Loading tag filters" className="flex h-7 shrink-0 items-center gap-2">
+ <Skeleton className="h-7 w-16 rounded-lg" /><Skeleton className="h-7 w-20 rounded-lg" /><Skeleton className="h-7 w-16 rounded-lg" />
+ </div>
+ ) : (
<>
<button
ref={tag === "All" ? activeFilterRef : undefined}
@@ -341,7 +352,7 @@ export function ForumView({
ref={bindScrollRoot}
role="main"
data-testid={tid.forumPostList}
- className="flex-1 overflow-y-auto thin-scrollbar px-0 py-2 sm:px-4"
+ className="flex-1 overflow-y-auto thin-scrollbar [overflow-anchor:none] px-0 py-2 sm:px-4"
>
{loading && posts.length === 0 ? (
<ForumListSkeleton />
@@ -399,7 +410,7 @@ export function ForumView({
type="button"
data-testid={tid.forumThreadTagBtn(p.id)}
onClick={(event) => event.stopPropagation()}
- className="grid size-8 shrink-0 place-items-center rounded-md text-muted-foreground opacity-100 transition-opacity hover:bg-accent hover:text-foreground sm:size-6 sm:opacity-0 sm:focus-visible:opacity-100 sm:data-popup-open:opacity-100 sm:group-hover/card:opacity-100"
+ className={cn(POST_ACTION_CLASS, "hover:bg-accent hover:text-foreground")}
aria-label="Edit tags"
>
<Tag className="size-4" />
@@ -423,7 +434,7 @@ export function ForumView({
onEditPostTags?.(p.id, toggleForumArchivedStatus(p.tags)),
).catch(() => undefined)
}}
- className="grid size-8 shrink-0 place-items-center rounded-md text-muted-foreground opacity-100 transition-opacity hover:bg-accent hover:text-foreground sm:size-6 sm:opacity-0 sm:focus-visible:opacity-100 sm:group-hover/card:opacity-100 disabled:cursor-not-allowed disabled:opacity-50"
+ className={cn(POST_ACTION_CLASS, "hover:bg-accent hover:text-foreground")}
aria-label={archived ? "Unarchive post" : "Archive post"}
aria-pressed={archived}
>
@@ -438,7 +449,7 @@ export function ForumView({
data-testid={tid.forumThreadDeleteBtn(p.id)}
disabled={deletingPost === p.id}
onClick={(e) => { e.stopPropagation(); setDeletingFor(p) }}
- className="grid size-8 shrink-0 place-items-center rounded-md text-muted-foreground opacity-100 transition-opacity hover:bg-accent hover:text-destructive sm:size-6 sm:opacity-0 sm:focus-visible:opacity-100 sm:group-hover/card:opacity-100 disabled:cursor-not-allowed disabled:opacity-50"
+ className={cn(POST_ACTION_CLASS, "hover:bg-accent hover:text-destructive")}
aria-label="Delete post"
>
<Trash2 className="size-4" />
@@ -448,9 +459,9 @@ export function ForumView({
)}
<div className={cn(
- actionCount === 3 && "min-h-8 pr-28 sm:min-h-0 sm:pr-22",
- actionCount === 2 && "min-h-8 pr-20 sm:min-h-0 sm:pr-16",
- actionCount === 1 && "min-h-8 pr-12 sm:min-h-0 sm:pr-8",
+ actionCount === 3 && "min-h-8 pr-28",
+ actionCount === 2 && "min-h-8 pr-20",
+ actionCount === 1 && "min-h-8 pr-12",
actionCount === 0 && "pr-0",
)}>
<ForumPostTitle name={p.name} postId={p.id} seq={p.parentSeq} />
@@ -460,7 +471,7 @@ export function ForumView({
<Avatar label={author.avatar} seed={p.authorId} size={20} />
<span className="shrink-0 font-medium text-foreground" suppressHydrationWarning>{author.name}</span>
<span className="shrink-0" aria-hidden>·</span>
- <span className="shrink-0" suppressHydrationWarning>{formatRelativeTime(p.lastMessageAt)}</span>
+ <span className="shrink-0" suppressHydrationWarning>Active {formatRelativeTime(p.lastMessageAt)}</span>
{hasOrdinaryTags && <span className="shrink-0 max-sm:hidden" aria-hidden>·</span>}
<ForumTagSummary tags={p.tags} />
<span className="ml-auto flex shrink-0 items-center gap-2">
diff --git a/src/web/src/components/community/shell/dm-sidebar-slot.dom.test.tsx b/src/web/src/components/community/shell/dm-sidebar-slot.dom.test.tsx
index 0afc5370f..b1a2e5da5 100644
--- a/src/web/src/components/community/shell/dm-sidebar-slot.dom.test.tsx
+++ b/src/web/src/components/community/shell/dm-sidebar-slot.dom.test.tsx
@@ -1,6 +1,8 @@
import { createElement, useEffect } from "react"
+import { renderToString } from "react-dom/server"
+import { hydrateRoot } from "react-dom/client"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { render } from "@/test/react-dom-harness"
+import { act, render } from "@/test/react-dom-harness"
import { RemoteIdentityImage } from "@/components/remote-image/remote-image"
import { DmSidebarSlot } from "./dm-sidebar-slot"
@@ -46,7 +48,7 @@ vi.mock("@/hooks/community/use-inbox", () => ({
}))
vi.mock("@/lib/observability/regions", () => ({ useObservedRegion: vi.fn() }))
vi.mock("@/components/community/channels/dm-sidebar", () => ({
- DmSidebar: ({ dms }: { dms: Array<{ userId: string; avatar: string }> }) => <aside>
+ DmSidebar: ({ dms, activeDm }: { dms: Array<{ userId: string; avatar: string }>; activeDm?: string | null }) => <aside data-active-dm={activeDm ?? ""}>
<input aria-label="Sidebar state" defaultValue="retained" />
<RemoteIdentityImage src={dms[0].avatar} identityKey={dms[0].userId} alt="Peer" />
</aside>,
@@ -64,6 +66,30 @@ beforeEach(() => {
afterEach(() => { vi.restoreAllMocks() })
describe("account-scoped DM sidebar Activity", () => {
+ it("hydrates the direct target DM and switches activation without waiting for the old UI store", async () => {
+ mocks.scope = "me"
+ const tree = <DmSidebarSlot href="/c/me/dm-a" />
+ const container = document.createElement("div")
+ container.innerHTML = renderToString(tree)
+ document.body.appendChild(container)
+ const sidebar = container.querySelector("aside")!
+ expect(sidebar).toHaveAttribute("data-active-dm", "dm-a")
+ const recoveries: unknown[] = []
+ let root!: ReturnType<typeof hydrateRoot>
+ try {
+ await act(async () => { root = hydrateRoot(container, tree, { onRecoverableError: error => { recoveries.push(error) } }) })
+ expect(container.querySelector("aside")).toBe(sidebar)
+ expect(sidebar).toHaveAttribute("data-active-dm", "dm-a")
+ await act(async () => { root.render(<DmSidebarSlot href="/c/me/dm-b" routeCommitted={false} />) })
+ expect(sidebar).toHaveAttribute("data-active-dm", "dm-b")
+ await act(async () => { root.render(<DmSidebarSlot href="/c/me/friends" />) })
+ expect(sidebar).toHaveAttribute("data-active-dm", "")
+ await act(async () => { root.render(<DmSidebarSlot href="/c/me/dm-a" />) })
+ expect(sidebar).toHaveAttribute("data-active-dm", "dm-a")
+ expect(recoveries).toEqual([])
+ } finally { await act(async () => { root?.unmount() }); container.remove() }
+ })
+
it("starts at the first Me visit, preserves real DOM and releases Effects while away", () => {
const rendered = render(<DmSidebarSlot />)
expect(mocks.reads).not.toHaveBeenCalled()
diff --git a/src/web/src/components/community/shell/dm-sidebar-slot.tsx b/src/web/src/components/community/shell/dm-sidebar-slot.tsx
index 613668660..8148b5e5a 100644
--- a/src/web/src/components/community/shell/dm-sidebar-slot.tsx
+++ b/src/web/src/components/community/shell/dm-sidebar-slot.tsx
@@ -3,11 +3,10 @@ import { useObservedRegion } from "@/lib/observability/regions"
import { useCommunityRuntime } from "@/stores/community/runtime"
-import { dmHref, normalizeCommunityHref } from "@/lib/community/community-route"
+import { dmHref, normalizeCommunityHref, resolveCommunityModulePlan } from "@/lib/community/community-route"
import { Activity, useCallback, useLayoutEffect, useMemo, useState } from "react"
import { useCommunityRouteFrame } from "./community-route-context"
import { DmSidebar } from "@/components/community/channels/dm-sidebar"
-import { useCurrentChannelId } from "@/stores/community"
import { useDms } from "@/hooks/community/use-dms"
import { useFriends, useFriendsPresence } from "@/hooks/community/use-friends"
import { useInboxUnreads } from "@/hooks/community/use-inbox"
@@ -39,7 +38,8 @@ function MeSidebar({ pathname, routeCommitted }: { pathname: string; routeCommit
const initialError = isError && data === undefined
useObservedRegion("sidebar", !dmsLoading && !initialError, dms.length)
const friendRequestCount = useInboxUnreads().friendRequests.length
- const currentChannelId = useCurrentChannelId()
+ const main = resolveCommunityModulePlan(pathname).main
+ const currentChannelId = main.kind === "dm" ? main.dmId : null
// Seed online friends into the global profile map. The endpoint is a subset
// of the full WS audience, so it only patches the ids it explicitly returns.
diff --git a/src/web/src/hooks/community/mutations/dm.dom.test.tsx b/src/web/src/hooks/community/mutations/dm.dom.test.tsx
new file mode 100644
index 000000000..b368f622c
--- /dev/null
+++ b/src/web/src/hooks/community/mutations/dm.dom.test.tsx
@@ -0,0 +1,50 @@
+import { createElement, type PropsWithChildren } from "react"
+import { useQuery } from "@tanstack/react-query"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { act, renderHook, waitFor } from "@/test/react-dom-harness"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { communityKeys } from "@/lib/query-keys"
+import { useCreateOrGetDm } from "./dm"
+
+const api = vi.fn()
+vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => api(...args), toastApiError: vi.fn() }))
+
+beforeEach(() => { api.mockReset() })
+
+describe("DM open completion", () => {
+ it("returns the authorized target while its active sidebar refresh is held", async () => {
+ const { client, registry } = await createCommunityQueryOwner()
+ const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client, registry }, children)
+ const initial = { conversations: [] }
+ client.setQueryData(communityKeys.dms(), initial)
+ let release!: (value: typeof initial) => void
+ const refresh = vi.fn(() => new Promise<typeof initial>(resolve => { release = resolve }))
+ api.mockResolvedValue({ conversation: { id: "dm-a" } })
+ const view = renderHook(() => {
+ const sidebar = useQuery({ queryKey: communityKeys.dms(), queryFn: refresh, staleTime: Infinity })
+ return { sidebar, open: useCreateOrGetDm() }
+ }, { wrapper })
+ try {
+ let target: unknown
+ await act(async () => { target = await view.result.current.open.mutateAsync({ userId: "peer-a" }) })
+ expect(target).toEqual({ conversation: { id: "dm-a" } })
+ expect(refresh).toHaveBeenCalledOnce()
+ expect(client.getQueryState(communityKeys.dms())?.fetchStatus).toBe("fetching")
+ expect(view.result.current.sidebar.data).toBe(initial)
+ await act(async () => { release(initial) })
+ await waitFor(() => expect(view.result.current.sidebar.isFetching).toBe(false))
+ } finally { release?.(initial); view.unmount() }
+ })
+
+ it("keeps a failed command from reporting a target or refreshing the sidebar", async () => {
+ const { client, registry } = await createCommunityQueryOwner()
+ const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client, registry }, children)
+ const invalidate = vi.spyOn(client, "invalidateQueries")
+ api.mockRejectedValue(new Error("not allowed"))
+ const view = renderHook(() => useCreateOrGetDm(), { wrapper })
+ await act(async () => { await expect(view.result.current.mutateAsync({ userId: "peer-a" })).rejects.toThrow("not allowed") })
+ expect(invalidate).not.toHaveBeenCalled()
+ view.unmount()
+ })
+})
diff --git a/src/web/src/hooks/community/mutations/dm.ts b/src/web/src/hooks/community/mutations/dm.ts
index 981d2f2cb..37d0726a7 100644
--- a/src/web/src/hooks/community/mutations/dm.ts
+++ b/src/web/src/hooks/community/mutations/dm.ts
@@ -34,7 +34,7 @@ export function useCreateOrGetDm() {
assertActive,
})
origin.assert(original)
- for (const resource of resources) if (queryClient.getQueryCache().find({ queryKey: resource.queryKey, exact: true }) === resource) await queryClient.invalidateQueries({ queryKey: resource.queryKey, exact: true }, { cancelRefetch: false })
+ for (const resource of resources) if (queryClient.getQueryCache().find({ queryKey: resource.queryKey, exact: true }) === resource) void queryClient.invalidateQueries({ queryKey: resource.queryKey, exact: true }, { cancelRefetch: false })
origin.assert(original)
assertActive?.()
return result
diff --git a/src/web/src/hooks/community/use-forum-feed.pending-tags.dom.test.ts b/src/web/src/hooks/community/use-forum-feed.pending-tags.dom.test.ts
index ad3ff1354..66a2614fe 100644
--- a/src/web/src/hooks/community/use-forum-feed.pending-tags.dom.test.ts
+++ b/src/web/src/hooks/community/use-forum-feed.pending-tags.dom.test.ts
@@ -24,7 +24,17 @@ async function setup(selected = "archived") {
included: { parentMessages: [{ id: "opener", channelId: "forum_1", seq: 1, content: "Post", authorId: "author", authorName: "Author", authorImage: null, authorAvatarVersion: 0 }], firstMessages: [], participants: [], tags: backendTags.map((tag) => ({ messageId: "opener", tag })) },
})
api.mockImplementation((path: string, options?: { method?: string }) => {
- if (path.includes("/messages?entry=1")) return Promise.resolve(forumConversationEntryFixture("forum_1", "server_1", true))
+ if (path.includes("/messages?entry=1")) {
+ const filter = new URL(path, "https://local").searchParams.get("tag")
+ const empty = filter === "archived" ? !backendTags.includes("archived") : backendTags.includes("archived") || !!filter && !backendTags.includes(filter)
+ const entry = forumConversationEntryFixture("forum_1", "server_1", empty)
+ if (!empty && entry.forumFeed) {
+ entry.forumFeed.threads[0] = { ...entry.forumFeed.threads[0], id: "post", parentMessageId: "opener" }
+ entry.forumFeed.included.messages[0] = { ...entry.forumFeed.included.messages[0], id: "opener" }
+ entry.forumFeed.included.tags = backendTags.map(tag => ({ messageId: "opener", tag }))
+ }
+ return Promise.resolve(entry)
+ }
if (options?.method === "PUT") return held
if (path.endsWith("/messages/tags")) return Promise.resolve({ tags: [...backendTags] })
if (path.includes("/threads?")) return Promise.resolve(page())
diff --git a/src/web/src/hooks/community/use-forum-feed.selection.dom.test.tsx b/src/web/src/hooks/community/use-forum-feed.selection.dom.test.tsx
new file mode 100644
index 000000000..32a972e71
--- /dev/null
+++ b/src/web/src/hooks/community/use-forum-feed.selection.dom.test.tsx
@@ -0,0 +1,94 @@
+import { createElement, type PropsWithChildren } from "react"
+import { renderToString } from "react-dom/server"
+import { hydrateRoot } from "react-dom/client"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { act, renderHook, waitFor } from "@/test/react-dom-harness"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { forumConversationEntryFixture, seedConversationEntry } from "@/test/conversation-entry-fixtures"
+import { useForumFeed } from "./use-forum-feed"
+
+const api = vi.hoisted(() => vi.fn())
+vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: api }))
+
+function entryFor(tag: string | null) {
+ const entry = forumConversationEntryFixture("forum", "server")
+ const id = tag ?? "all"
+ entry.forumFeed!.threads[0] = { ...entry.forumFeed!.threads[0], id: `post-${id}`, parentMessageId: `opener-${id}` }
+ entry.forumFeed!.included.messages[0] = { ...entry.forumFeed!.included.messages[0], id: `opener-${id}`, content: `${id} body` }
+ entry.forumFeed!.included.tags = tag ? [{ messageId: `opener-${id}`, tag }] : []
+ return entry
+}
+
+beforeEach(() => {
+ localStorage.clear()
+ api.mockReset().mockImplementation(async (path: string) => {
+ if (path.endsWith("/messages/tags")) return { tags: ["archived", "bug"] }
+ if (path.includes("/messages?entry=1")) return entryFor(new URL(path, "https://local").searchParams.get("tag"))
+ throw new Error(`Unexpected request: ${path}`)
+ })
+})
+
+describe("Forum initial selection authority", () => {
+ it.each([
+ { routeTag: "bug", stored: "archived", expected: "bug", requestTag: "bug" },
+ { routeTag: "", stored: "archived", expected: "All", requestTag: null },
+ { routeTag: null, stored: "archived", expected: "archived", requestTag: "archived" },
+ { routeTag: null, stored: null, expected: "All", requestTag: null },
+ ])("resolves URL=$routeTag and storage=$stored as $expected before requesting its entry", async ({ routeTag, stored, expected, requestTag }) => {
+ const owner = await createCommunityQueryOwner()
+ if (stored) localStorage.setItem("alook:forum-tag:forum", stored)
+ const wrapper = ({ children }: PropsWithChildren) => <CommunityTestProvider {...owner}>{children}</CommunityTestProvider>
+ const view = renderHook(() => useForumFeed("server", "forum", { routeTag }), { wrapper })
+ await waitFor(() => expect(view.result.current.posts.map(post => post.id)).toEqual([`post-${requestTag ?? "all"}`]))
+ expect(view.result.current.tag).toBe(expected)
+ const entries = api.mock.calls.map(([path]) => path as string).filter(path => path.includes("/messages?entry=1"))
+ expect(entries).toHaveLength(1)
+ expect(new URL(entries[0], "https://local").searchParams.get("tag")).toBe(requestTag)
+ view.unmount()
+ })
+
+ it("restores the URL category after selecting another category and navigating back", async () => {
+ const owner = await createCommunityQueryOwner()
+ const onSelectTag = vi.fn()
+ const wrapper = ({ children }: PropsWithChildren) => <CommunityTestProvider {...owner}>{children}</CommunityTestProvider>
+ const view = renderHook(({ routeTag }) => useForumFeed("server", "forum", { routeTag, onSelectTag }), {
+ wrapper, initialProps: { routeTag: "bug" },
+ })
+ await waitFor(() => expect(view.result.current.posts.map(post => post.id)).toEqual(["post-bug"]))
+ act(() => view.result.current.selectTag("archived"))
+ expect(onSelectTag).toHaveBeenCalledWith("archived")
+ view.rerender({ routeTag: "archived" })
+ await waitFor(() => expect(view.result.current.posts.map(post => post.id)).toEqual(["post-archived"]))
+ view.rerender({ routeTag: "bug" })
+ expect(view.result.current.tag).toBe("bug")
+ await waitFor(() => expect(view.result.current.posts.map(post => post.id)).toEqual(["post-bug"]))
+ expect(localStorage.getItem("alook:forum-tag:forum")).toBe("archived")
+ view.unmount()
+ })
+
+ it("hydrates an unknown stored selection without first displaying a qualified All window", async () => {
+ const owner = await createCommunityQueryOwner()
+ await seedConversationEntry(owner.client, entryFor(null))
+ localStorage.setItem("alook:forum-tag:forum", "archived")
+ const displayed: string[] = []
+ function Probe() {
+ const feed = useForumFeed("server", "forum")
+ if (feed.posts.length) displayed.push(...feed.posts.map(post => post.id))
+ return <span>{feed.selectionReady ? feed.posts.map(post => post.id).join("|") : "selection pending"}</span>
+ }
+ const tree = createElement(CommunityTestProvider, { ...owner }, createElement(Probe))
+ const container = document.createElement("div")
+ container.innerHTML = renderToString(tree)
+ expect(container.textContent).toBe("selection pending")
+ expect(displayed).toEqual([])
+ document.body.appendChild(container)
+ let root!: ReturnType<typeof hydrateRoot>
+ try {
+ await act(async () => { root = hydrateRoot(container, tree) })
+ await waitFor(() => expect(container.textContent).toBe("post-archived"))
+ expect(displayed.length).toBeGreaterThan(0)
+ expect(displayed.every(id => id === "post-archived")).toBe(true)
+ } finally { act(() => root.unmount()); container.remove() }
+ })
+})
diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.ts
index aebab3caf..219e204e1 100644
--- a/src/web/src/hooks/community/use-forum-feed.ts
+++ b/src/web/src/hooks/community/use-forum-feed.ts
@@ -11,7 +11,7 @@ import { avatarInitial } from "@/lib/community/avatar"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { useCanonicalChannelsById, useCanonicalMessagesById, useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
import { assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken, publishCommunityForumFeed } from "@/lib/community-db/sync"
-import { readForumTagSelection, validateForumTagSelection, writeForumTagSelection } from "@/lib/community/forum-tag-selection"
+import { forumTagFromUrl, readForumTagSelection, validateForumTagSelection, writeForumTagSelection } from "@/lib/community/forum-tag-selection"
import type { ForumThread, Msg } from "@/lib/community/models/message"
import type { ChannelRow } from "@/lib/community-db/schema"
import { readCommunityProfile } from "@/lib/community/profile-read"
@@ -87,30 +87,38 @@ export function mapForumFeedPages(pages: ForumFeedPage[], messages: ReadonlyMap<
return [...byId.values()].sort((a, b) => compareAsciiSqliteBinary(channels.get(b.id)?.createdAt ?? "", channels.get(a.id)?.createdAt ?? "") || compareAsciiSqliteBinary(b.id, a.id))
}
-export function useForumFeed(serverId: string, channelId: string) {
+export function useForumFeed(serverId: string, channelId: string, options?: { routeTag?: string | null; onSelectTag?: (tag: string) => void }) {
const queryClient = useQueryClient(), channels = useCanonicalChannelsById(), profiles = useCanonicalProfilesByUserId()
const readTag = () => { try { return readForumTagSelection(window.localStorage, channelId) } catch { return "All" } }
const subscribeTag = useCallback((notify: () => void) => { window.addEventListener("storage", notify); return () => window.removeEventListener("storage", notify) }, [])
- const persistedTag = useSyncExternalStore(subscribeTag, readTag, () => "All")
+ const persistedTag = useSyncExternalStore(subscribeTag, readTag, (): string | null => null)
+ const routeTag = forumTagFromUrl(options?.routeTag)
const [selection, setSelection] = useAtom(useCreateAtom({ channelId: null as string | null, tag: "All" }))
- const tag = selection.channelId === channelId ? selection.tag : persistedTag
- const selectTag = useCallback((next: string) => { setSelection({ channelId, tag: next }); try { writeForumTagSelection(window.localStorage, channelId, next) } catch {} }, [channelId, setSelection])
+ const resolvedTag = routeTag ?? (selection.channelId === channelId ? selection.tag : persistedTag)
+ const selectionReady = resolvedTag !== null
+ const tag = resolvedTag ?? "All"
+ const onSelectTag = options?.onSelectTag
+ const selectTag = useCallback((next: string) => {
+ setSelection({ channelId, tag: next })
+ try { writeForumTagSelection(window.localStorage, channelId, next) } catch {}
+ onSelectTag?.(next)
+ }, [channelId, setSelection, onSelectTag])
const tagsQuery = useForumTags(channelId, true)
const pendingTagCommands = useIsMutating({ mutationKey: ["community", "forum-tag-command"], exact: true, predicate: (mutation) => {
const args = mutation.state.variables as { serverId?: string; forumChannelId?: string } | undefined
return args?.serverId === serverId && args.forumChannelId === channelId
} })
- useEffect(() => { if (!pendingTagCommands && tagsQuery.isSuccess && tag !== "All" && validateForumTagSelection(tag, tagsQuery.data.tags) === "All") selectTag("All") }, [pendingTagCommands, tag, tagsQuery.isSuccess, tagsQuery.data, selectTag])
+ useEffect(() => { if (selectionReady && !pendingTagCommands && tagsQuery.isSuccess && tag !== "All" && validateForumTagSelection(tag, tagsQuery.data.tags) === "All") selectTag("All") }, [selectionReady, pendingTagCommands, tag, tagsQuery.isSuccess, tagsQuery.data, selectTag])
const selectedTag = tag === "All" ? null : tag
- const entry = useConversationResource({ channelId, serverId })
+ const entry = useConversationResource(selectionReady ? { channelId, serverId, tag: selectedTag } : null)
const queryKey = communityKeys.forumFeed(entry.canRead ? channelId : "__none__", selectedTag)
const query = useInfiniteQuery({ queryKey, queryFn: forumFeedPageQueryFn(channelId, selectedTag, queryClient), initialPageParam: null as string | null, getNextPageParam: (lastPage) => lastPage.hasMore ? lastPage.nextCursor : undefined,
- enabled: entry.canRead, subscribed: entry.canRead, staleTime: 5_000,
+ enabled: selectionReady && entry.canRead, subscribed: selectionReady && entry.canRead, staleTime: 5_000,
retry: conversationReadRetryPolicy(queryClient.defaultQueryOptions({ queryKey }).retry), networkMode: "always" })
const messageIds = useMemo(() => [...new Set(query.data?.pages.flatMap((page) => page.threads.flatMap((thread) => thread.openerMessageId ? [thread.openerMessageId] : [])) ?? [])], [query.data?.pages])
const messages = useCanonicalMessagesById(messageIds)
- const posts = useMemo(() => mapForumFeedPages(query.data?.pages ?? [], messages ?? new Map(), channels, profiles, selectedTag), [query.data?.pages, messages, channels, profiles, selectedTag])
+ const posts = useMemo(() => selectionReady ? mapForumFeedPages(query.data?.pages ?? [], messages ?? new Map(), channels, profiles, selectedTag) : [], [selectionReady, query.data?.pages, messages, channels, profiles, selectedTag])
const fetchNextPage = query.fetchNextPage
const fetchOlder = useCallback(() => { void fetchNextPage({ cancelRefetch: false }) }, [fetchNextPage])
- return { ...query, observation: { snapshot_source: entry.resource?.source ?? "unknown" as const, target_coverage: query.data ? "covered" as const : "uncovered" as const, wait_reason: !entry.canRead ? "entry" as const : query.data ? "none" as const : "window" as const }, posts, tag, selectTag, availableTags: tagsQuery.data?.tags ?? [], hasMoreOlder: query.hasNextPage, isFetchingOlder: query.isFetchingNextPage, fetchOlder }
+ return { ...query, observation: { snapshot_source: entry.resource?.source ?? "unknown" as const, target_coverage: query.data ? "covered" as const : "uncovered" as const, wait_reason: !entry.canRead ? "entry" as const : query.data ? "none" as const : "window" as const }, posts, tag, selectionReady, selectTag, tagsKnown: tagsQuery.data !== undefined, tagsError: tagsQuery.isError, retryTags: tagsQuery.refetch, availableTags: tagsQuery.data?.tags ?? [], hasMoreOlder: query.hasNextPage, isFetchingOlder: query.isFetchingNextPage, fetchOlder }
}
diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.ts
index 560f6594a..93092c8c9 100644
--- a/src/web/src/lib/community-db/sync.ts
+++ b/src/web/src/lib/community-db/sync.ts
@@ -77,6 +77,7 @@ type ChannelRow,
type FolderItemRow,
type FolderRow,
type MessageRow,
+type ProfileRow,
type FriendshipRow,
type NotificationSettingRow,
type ReadStateClockRow,
@@ -459,7 +460,16 @@ export async function restoreCommunityCollections(registry: CommunityDbRegistry,
if (!eligible(name, row)) continue
if (current) {
const present = Object.fromEntries(Object.entries(current).filter(([, value]) => value !== undefined))
- next.set(id, schema.parse(state && state.dataUpdatedAt > 0 ? { ...row, ...present } : { ...present, ...row }))
+ const merged = state && state.dataUpdatedAt > 0 ? { ...row, ...present } : { ...present, ...row }
+ if (name === "profiles") {
+ const currentProfile = current as ProfileRow
+ const diskProfile = row as ProfileRow
+ const currentVersion = currentProfile.avatarVersion ?? -1
+ const diskVersion = diskProfile.avatarVersion ?? -1
+ const newer = currentVersion > diskVersion ? currentProfile : diskVersion > currentVersion ? diskProfile : undefined
+ if (newer) Object.assign(merged, { avatar: newer.avatar, avatarVersion: newer.avatarVersion })
+ }
+ next.set(id, schema.parse(merged))
} else if (!excluded(name, row)) {
const merged = withCanonicalWriteContext(client, { kind: "query", requestRevision: 0, profileSnapshot: token.profileSnapshot }, () => (
isProtectedFromQueryWrite(registry, name, id) ? mergePendingOperationsIntoQueryRow(registry, name, id, schema, row) : row
diff --git a/src/web/src/lib/community/document-seed.server.test.ts b/src/web/src/lib/community/document-seed.server.test.ts
index 7cce569c0..55f5e9c66 100644
--- a/src/web/src/lib/community/document-seed.server.test.ts
+++ b/src/web/src/lib/community/document-seed.server.test.ts
@@ -45,14 +45,29 @@ function Probe() {
}
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" : "/c/channels/s1", selfProfile)
+ 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"); return createElement("span", null, feed.posts.map(post => post.name).join("|")) }
+ 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))))
diff --git a/src/web/src/lib/community/document-seed.server.ts b/src/web/src/lib/community/document-seed.server.ts
index 25af8f084..ddc54d67e 100644
--- a/src/web/src/lib/community/document-seed.server.ts
+++ b/src/web/src/lib/community/document-seed.server.ts
@@ -15,6 +15,7 @@ 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: [] } }
@@ -43,6 +44,11 @@ export async function readCommunityDocumentSeed(db: Database, viewerId: 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 })
@@ -64,6 +70,8 @@ export async function readCommunityDocumentSeed(db: Database, viewerId: string,
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)))
diff --git a/src/web/src/lib/community/document-seed.ts b/src/web/src/lib/community/document-seed.ts
index 9a7df7099..93f11f4f6 100644
--- a/src/web/src/lib/community/document-seed.ts
+++ b/src/web/src/lib/community/document-seed.ts
@@ -1,4 +1,4 @@
-import type { QueryClient } from "@tanstack/react-query"
+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"
@@ -23,11 +23,19 @@ export type CommunityDocumentSeed = {
db: Parameters<CommunityDbRegistry["dbClient"]["hydrate"]>[0]
}
-export function installCommunityDocumentSeed(client: QueryClient, registry: CommunityDbRegistry, seed: CommunityDocumentSeed, sessionViewer: string | null | undefined) {
+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 = captureCommunityLiveSnapshotToken(client)
+ 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,
@@ -35,27 +43,27 @@ export function installCommunityDocumentSeed(client: QueryClient, registry: Comm
avatar: { avatar: profile.avatar, avatarVersion: profile.avatarVersion },
status: { statusEmoji: profile.statusEmoji, statusText: profile.statusText },
}], registry, { snapshot: original.profileSnapshot })
- client.setQueryData(communityKeys.selfProfile(), { id: profile.id }, { updatedAt: seed.generatedAt })
+ seedResource(communityKeys.selfProfile(), { id: profile.id })
if (seed.bots) {
writeCommunityProfilePatches(seed.bots.bots.map(botProfilePatch), registry, { snapshot: original.profileSnapshot })
- registry.runtime.ws.actions.seedPresence(registry.runtime.ws.actions.beginPresenceSnapshot(), seed.bots.bots.flatMap(bot => bot.presence ? [[bot.id, bot.presence] as const] : []))
- client.setQueryData(communityKeys.bots(), { ...botsResource(seed.bots), source: "rsc" }, { updatedAt: seed.generatedAt })
+ 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) client.setQueryData(communityKeys.machines(), { ...seed.machines, source: "rsc" }, { updatedAt: seed.generatedAt })
+ 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 } })
- client.setQueryData(communityKeys.server(seed.server.id), seed.server.id, { updatedAt: seed.generatedAt })
+ 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")
- client.setQueryData(communityKeys.conversationEntry(target.channelId, target, {
+ seedResource(communityKeys.conversationEntry(target.channelId, target, {
accountEpoch: original.accountEpoch, accessEpoch: original.accessEpoch,
channelGeneration: original.channelScopes.get(target.channelId)?.generation ?? 0,
- }), resource, { updatedAt: seed.generatedAt })
+ }), resource)
}
assertCommunityLiveSnapshotTokenCurrent(client, original, undefined)
- registry.dbClient.hydrate(seed.db)
+ if (!delivery) registry.dbClient.hydrate(seed.db)
return true
}
diff --git a/src/web/src/lib/community/forum-tag-selection.test.ts b/src/web/src/lib/community/forum-tag-selection.test.ts
index 189f61d2b..c5a179e35 100644
--- a/src/web/src/lib/community/forum-tag-selection.test.ts
+++ b/src/web/src/lib/community/forum-tag-selection.test.ts
@@ -1,7 +1,14 @@
import { describe, expect, it, vi } from "vitest"
-import { readForumTagSelection, validateForumTagSelection, writeForumTagSelection } from "./forum-tag-selection"
+import { forumTagFromUrl, readForumTagSelection, validateForumTagSelection, writeForumTagSelection } from "./forum-tag-selection"
describe("forum tag selection", () => {
+ it("distinguishes an absent URL selection from explicit All and normalizes a tag", () => {
+ expect(forumTagFromUrl(null)).toBeNull()
+ expect(forumTagFromUrl(undefined)).toBeNull()
+ expect(forumTagFromUrl("")).toBe("All")
+ expect(forumTagFromUrl(" BUG ")).toBe("bug")
+ expect(forumTagFromUrl("all")).toBe("all")
+ })
it("defaults to All and scopes persisted selections by channel", () => {
const getItem = vi.fn((key: string) => key.endsWith("forum-a") ? "bug" : null)
expect(readForumTagSelection({ getItem }, "forum-a")).toBe("bug")
diff --git a/src/web/src/lib/community/forum-tag-selection.ts b/src/web/src/lib/community/forum-tag-selection.ts
index bf5382a6d..5e2a19b48 100644
--- a/src/web/src/lib/community/forum-tag-selection.ts
+++ b/src/web/src/lib/community/forum-tag-selection.ts
@@ -1,5 +1,9 @@
const keyFor = (channelId: string) => `alook:forum-tag:${channelId}`
+export function forumTagFromUrl(value: string | null | undefined): string | null {
+ return value == null ? null : value.trim().toLowerCase() || "All"
+}
+
export function readForumTagSelection(storage: Pick<Storage, "getItem">, channelId: string): string {
return storage.getItem(keyFor(channelId)) || "All"
}
diff --git a/src/web/src/test/community-document-flight.test.ts b/src/web/src/test/community-document-flight.test.ts
new file mode 100644
index 000000000..c4f74f509
--- /dev/null
+++ b/src/web/src/test/community-document-flight.test.ts
@@ -0,0 +1,40 @@
+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/e2e-ui/17-forum-sidebar-stage-b.spec.ts b/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts
index d102df92f..c1c47e033 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
@@ -568,9 +568,11 @@ test.describe("forum sidebar archived opener projection", () => {
})
await viewer.page.reload({ waitUntil: "commit" })
for (const id of initialIds.filter((id) => id !== archivedId).concat(refillId)) {
- await expect(viewer.page.getByTestId(tid.forumSidebarThread(id))).toBeVisible({
- timeout: 20_000,
- })
+ const sidebarThread = viewer.page.getByTestId(tid.forumSidebarThread(id))
+ await expect(async () => {
+ expect(await sidebarThread.count()).toBe(1)
+ expect(await sidebarThread.isVisible()).toBe(true)
+ }).toPass({ timeout: 20_000 })
}
await expect(viewer.page.getByTestId(tid.forumSidebarThread(archivedId))).toHaveCount(0)
})
diff --git a/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts b/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts
index 41a4d619b..ac20a31bd 100644
--- a/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts
+++ b/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts
@@ -35,6 +35,7 @@ async function prepareCase(actors: CaseActors) {
const MOBILE_WIDTHS = [320, 390] as const
const FILTER_RAIL_WIDTHS = [320, 390, 1280] as const
+const ACTION_WIDTHS = [639, 640, 641, 1280] as const
const TAGS = ["alpha-long-tag", "beta-long-tag", "gamma", "delta", "epsilon"]
const DESKTOP_OVERFLOW_TAGS = [
"desktop-overflow-tag-one",
@@ -66,6 +67,24 @@ async function rect(locator: Locator): Promise<Rect | null> {
}
}
+async function postActionGeometry(card: Locator, postId: string) {
+ return card.evaluate((element, titleId) => {
+ const readRect = (target: Element | null) => {
+ if (!target) throw new Error("Missing Forum geometry target")
+ const box = target.getBoundingClientRect()
+ return { left: box.left, right: box.right, top: box.top, bottom: box.bottom, width: box.width, height: box.height }
+ }
+ const row = element.closest("[data-index]")
+ return {
+ card: readRect(element),
+ title: readRect(element.querySelector(`[data-testid="${titleId}"]`)),
+ preview: readRect(element.querySelector(":scope > p")),
+ row: readRect(row),
+ virtualHeight: readRect(row?.parentElement ?? null).height,
+ }
+ }, tid.forumThreadTitle(postId))
+}
+
async function expectNewPostGeometry(
page: Page,
width: (typeof FILTER_RAIL_WIDTHS)[number],
@@ -466,6 +485,10 @@ async function expectNoOverflowFilterRail(
await page.emulateMedia({ colorScheme: "light" })
await expect(page.locator("html")).not.toHaveClass(/dark/)
const rail = page.getByTestId(tid.forumTagScroller)
+ await expect(rail.getByTestId(tid.forumTagAll)).toBeVisible({ timeout: 20_000 })
+ await expect(rail.getByTestId(tid.forumTagChip("solo"))).toBeVisible({ timeout: 20_000 })
+ await expect(rail.getByRole("button")).toHaveText(["All", "#solo"])
+ await expect(rail.getByRole("status", { name: "Loading tag filters" })).toHaveCount(0)
const geometry = await rail.evaluate((element) => ({ clientWidth: element.clientWidth, scrollWidth: element.scrollWidth }))
expect(geometry.scrollWidth, `no-overflow rail@${width}`).toBe(geometry.clientWidth)
await expect(page.getByTestId(tid.forumTagFadeLeft)).toHaveCount(0)
@@ -629,13 +652,41 @@ test("forum post actions stay discoverable on mobile without changing permission
await manager.page.mouse.move(0, 0)
const managerTagButton = manager.page.getByTestId(tid.forumThreadTagBtn(primaryPostId))
const managerDeleteButton = manager.page.getByTestId(tid.forumThreadDeleteBtn(primaryPostId))
+ const managerArchiveButton = manager.page.getByTestId(tid.forumThreadArchiveBtn(primaryPostId))
await expect(managerTagButton).toHaveCSS("opacity", "0")
await expect(managerDeleteButton).toHaveCSS("opacity", "0")
for (const button of [managerTagButton, managerDeleteButton]) {
const buttonRect = await rect(button)
- expect(buttonRect?.width).toBe(24)
- expect(buttonRect?.height).toBe(24)
+ expect(buttonRect?.width).toBe(32)
+ expect(buttonRect?.height).toBe(32)
+ }
+ for (const width of ACTION_WIDTHS) {
+ await manager.page.setViewportSize({ width, height: 900 })
+ await managerTagButton.evaluate((button) => button.blur())
+ await manager.page.mouse.move(0, 0)
+ await managerCard.scrollIntoViewIfNeeded()
+ for (const button of [managerTagButton, managerArchiveButton, managerDeleteButton]) {
+ await expect(button).toHaveCSS("opacity", width < 640 ? "1" : "0")
+ const buttonRect = await rect(button)
+ expect(buttonRect?.width, `action width@${width}`).toBe(32)
+ expect(buttonRect?.height, `action height@${width}`).toBe(32)
+ }
+ const baseline = await postActionGeometry(managerCard, primaryPostId)
+ await managerCard.hover()
+ await expect(managerTagButton).toHaveCSS("opacity", "1")
+ const hover = await postActionGeometry(managerCard, primaryPostId)
+ expect(hover, `hover geometry@${width}`).toEqual(baseline)
+ await manager.page.mouse.move(0, 0)
+ await managerTagButton.focus()
+ await expect(managerTagButton).toHaveCSS("opacity", "1")
+ const focus = await postActionGeometry(managerCard, primaryPostId)
+ expect(focus, `focus geometry@${width}`).toEqual(baseline)
+ await testInfo.attach(`manager-actions-${width}.json`, {
+ body: JSON.stringify({ width, baseline, hover, focus }),
+ contentType: "application/json",
+ })
}
+ await managerTagButton.evaluate((button) => button.blur())
await managerCard.hover()
await expect(managerTagButton).toHaveCSS("opacity", "1")
await expect(managerDeleteButton).toHaveCSS("opacity", "1")
diff --git a/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.ts b/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.ts
index 8ee5be925..f1e0536d5 100644
--- a/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.ts
+++ b/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.ts
@@ -361,7 +361,11 @@ test("mobile foreground proof is exact, bounded, and recovers through one curren
"true",
{ timeout: 20_000 },
)
- await expect(composerEditable(alice.page)).toBeVisible({ timeout: 20_000 })
+ const reloadedComposer = composerEditable(alice.page)
+ await expect(async () => {
+ expect(await reloadedComposer.count()).toBe(1)
+ expect(await reloadedComposer.isVisible()).toBe(true)
+ }).toPass({ timeout: 20_000 })
await expect.poll(() => proxy.connectionCount()).toBe(reloadConnectionBaseline + 1)
await expect.poll(() => successfulTokenResponses).toBe(reloadSuccessfulTokenBaseline + 1)
await alice.page.waitForTimeout(500)
diff --git a/src/web/src/test/e2e-ui/39-mobile-composer-send.spec.ts b/src/web/src/test/e2e-ui/39-mobile-composer-send.spec.ts
index ef3afee89..57fac18ee 100644
--- a/src/web/src/test/e2e-ui/39-mobile-composer-send.spec.ts
+++ b/src/web/src/test/e2e-ui/39-mobile-composer-send.spec.ts
@@ -96,7 +96,11 @@ async function expectHoverKeyboardSend({
await expect.poll(() => hasMessageFrame(frames, channelId, payload.message.id)).toBe(true)
await page.reload({ waitUntil: "commit" })
- await expect(composerEditable(page)).toBeVisible({ timeout: 20_000 })
+ const reloadedComposer = composerEditable(page)
+ await expect(async () => {
+ expect(await reloadedComposer.count()).toBe(1)
+ expect(await reloadedComposer.isVisible()).toBe(true)
+ }).toPass({ timeout: 20_000 })
await expect(page.getByTestId(tid.message(payload.message.id))).toContainText(firstLine)
expect(messagePosts).toBe(1)
}
@@ -240,7 +244,11 @@ async function expectExplicitTouchSend({
await expect.poll(() => hasMessageFrame(frames, channelId, payload.message.id)).toBe(true)
await page.reload({ waitUntil: "commit" })
- await expect(composerEditable(page, root)).toBeVisible({ timeout: 20_000 })
+ const reloadedComposer = composerEditable(page, root)
+ await expect(async () => {
+ expect(await reloadedComposer.count()).toBe(1)
+ expect(await reloadedComposer.isVisible()).toBe(true)
+ }).toPass({ timeout: 20_000 })
await expect(page.getByTestId(tid.message(payload.message.id))).toContainText(firstLine)
expect(messagePosts).toBe(1)
}
diff --git a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
index 101154c7f..d82df6664 100644
--- a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
+++ b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
@@ -562,10 +562,21 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
await ignoreNextDevToolsPointerCapture(bob.page)
const aliceThread = alice.page.getByTestId(tid.threadSplitPanel)
const bobThread = bob.page.getByTestId(tid.threadSplitPanel)
- await expect(composerEditable(alice.page, aliceThread)).toBeVisible()
- await expect(composerEditable(bob.page, bobThread)).toBeVisible()
+ const aliceThreadComposer = composerEditable(alice.page, aliceThread)
+ await expect(async () => {
+ expect(await aliceThreadComposer.count()).toBe(1)
+ expect(await aliceThreadComposer.isVisible()).toBe(true)
+ }).toPass({ timeout: 10_000 })
+ const bobThreadComposer = composerEditable(bob.page, bobThread)
+ await expect(async () => {
+ expect(await bobThreadComposer.count()).toBe(1)
+ expect(await bobThreadComposer.isVisible()).toBe(true)
+ }).toPass({ timeout: 10_000 })
const threadTarget = alice.page.getByTestId(tid.message(threadBobMessageId))
- await expect(threadTarget).toBeVisible()
+ await expect(async () => {
+ expect(await threadTarget.count()).toBe(1)
+ expect(await threadTarget.isVisible()).toBe(true)
+ }).toPass({ timeout: 10_000 })
const restingThreadGap = await alice.page.evaluate(({ targetId, composerId, threadPanelTestId }) => {
const target = document.querySelector(`[data-testid="${threadPanelTestId}"]`)?.querySelector(`[data-testid="${targetId}"]`)?.getBoundingClientRect()
const composer = document.querySelector(`[data-testid="${threadPanelTestId}"]`)?.querySelector(`[data-testid="${composerId}"]`)?.getBoundingClientRect()
@@ -667,9 +678,21 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
await Promise.all([waitForCurrentCommunityAuth(aliceProxy, aliceBeforeReturn), waitForCurrentCommunityAuth(bobProxy, bobBeforeReturn)])
await ignoreNextDevToolsPointerCapture(alice.page)
await ignoreNextDevToolsPointerCapture(bob.page)
- await expect(composerEditable(alice.page)).toBeVisible()
- await expect(composerEditable(bob.page)).toBeVisible()
- await expect(alice.page.getByTestId(tid.message(replyPayload.message.id))).toBeVisible()
+ const aliceReturnedComposer = composerEditable(alice.page)
+ await expect(async () => {
+ expect(await aliceReturnedComposer.count()).toBe(1)
+ expect(await aliceReturnedComposer.isVisible()).toBe(true)
+ }).toPass({ timeout: 10_000 })
+ const bobReturnedComposer = composerEditable(bob.page)
+ await expect(async () => {
+ expect(await bobReturnedComposer.count()).toBe(1)
+ expect(await bobReturnedComposer.isVisible()).toBe(true)
+ }).toPass({ timeout: 10_000 })
+ const returnedReply = alice.page.getByTestId(tid.message(replyPayload.message.id))
+ await expect(async () => {
+ expect(await returnedReply.count()).toBe(1)
+ expect(await returnedReply.isVisible()).toBe(true)
+ }).toPass({ timeout: 10_000 })
const typingWsReadyId = await seedMessage("bob", channelId, `typing ws ready ${stamp}`)
await expect.poll(() => aliceProxy.frames.some((frame) => (
frameHasMessage(frame, channelId, typingWsReadyId)
@@ -842,7 +865,11 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
await ignoreNextDevToolsPointerCapture(alice.page)
await ignoreNextDevToolsPointerCapture(bob.page)
await expect(composerEditable(alice.page)).toBeVisible()
- await expect(composerEditable(bob.page)).toBeVisible()
+ const bobColdDmComposer = composerEditable(bob.page)
+ await expect(async () => {
+ expect(await bobColdDmComposer.count()).toBe(1)
+ expect(await bobColdDmComposer.isVisible()).toBe(true)
+ }).toPass({ timeout: 10_000 })
const dmWsReadyId = await seedMessage("bob", dmId, `dm **reply target** ${stamp}`)
await expect.poll(() => aliceProxy.frames.some((frame) => (
frameHasMessage(frame, dmId, dmWsReadyId)
@@ -973,7 +1000,11 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
const dmReloadGets = trackSurfaceGets(alice.page, dmId)
await alice.page.reload({ waitUntil: "commit" })
await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/me/${dmId}`)
- await expect(alice.page.getByTestId(tid.message(dmReloadReadState.lastReadMessageId!))).toBeVisible()
+ const reloadedDmReadMessage = alice.page.getByTestId(tid.message(dmReloadReadState.lastReadMessageId!))
+ await expect(async () => {
+ expect(await reloadedDmReadMessage.count()).toBe(1)
+ expect(await reloadedDmReadMessage.isVisible()).toBe(true)
+ }).toPass({ timeout: 10_000 })
await expectRetainedMountGets(alice.page, dmId, dmReloadReadState, dmReloadGets)
expect(Math.abs(
await dmScroller.evaluate((element) => element.scrollTop) - departedDmReloadScrollTop,
@@ -1073,7 +1104,10 @@ test("mobile thread return uses server read state instead of tab-local pixel mem
await ignoreNextDevToolsPointerCapture(alice.page)
const editable = composerEditable(alice.page)
const scroller = alice.page.getByTestId(tid.messageScroller)
- await expect(editable).toBeVisible()
+ await expect(async () => {
+ expect(await editable.count()).toBe(1)
+ expect(await editable.isVisible()).toBe(true)
+ }).toPass({ timeout: 10_000 })
await scroller.hover()
await expect.poll(async () => {
if (await alice.page.getByTestId(tid.message(longMessageId)).count()) return true
diff --git a/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts b/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts
index 31b2937b9..76b44da29 100644
--- a/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts
+++ b/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts
@@ -9,7 +9,10 @@ test.use({ viewport: { width: 390, height: 844 } })
async function expectMobileBack(page: Page) {
const control = page.getByRole("banner").getByRole("button", { name: "Back" })
- await expect(control).toBeVisible()
+ await expect(async () => {
+ expect(await control.count()).toBe(1)
+ expect(await control.isVisible()).toBe(true)
+ }).toPass({ timeout: 10_000 })
const controlBox = await control.boundingBox()
expect(controlBox).toMatchObject({ width: 44, height: 44 })
return control
@@ -243,7 +246,11 @@ test.describe("mobile server header direct hierarchy", () => {
}
await page.setViewportSize({ width: 639, height: 844 })
await page.goto(`/c/channels/${serverId}/${threadId}`, { waitUntil: "commit" })
- await expect(page.getByTestId(tid.threadSplitPanel).getByTestId(tid.composerInput)).toBeVisible({ timeout: 20_000 })
+ const threadComposer = page.getByTestId(tid.threadSplitPanel).getByTestId(tid.composerInput)
+ await expect(async () => {
+ expect(await threadComposer.count()).toBe(1)
+ expect(await threadComposer.isVisible()).toBe(true)
+ }).toPass({ timeout: 20_000 })
await expectMobileBack(page)
// RULE: Cold HTTP reads and first-auth read-state/directory reconciliation
// must finish before the all-community resize measurement begins.
diff --git a/src/web/src/test/e2e-ui/43-composer-attachment-drafts.spec.ts b/src/web/src/test/e2e-ui/43-composer-attachment-drafts.spec.ts
index 6e318cb9e..93bd253bc 100644
--- a/src/web/src/test/e2e-ui/43-composer-attachment-drafts.spec.ts
+++ b/src/web/src/test/e2e-ui/43-composer-attachment-drafts.spec.ts
@@ -60,7 +60,11 @@ test.describe("same-tab Community attachment drafts", () => {
const { page } = await asUser("alice")
const channelA = `/c/channels/${serverId}/${channelAId}`
await page.goto(channelA, { waitUntil: "commit" })
- await expect(composerEditable(page)).toBeVisible({ timeout: 20_000 })
+ const initialComposer = composerEditable(page)
+ await expect(async () => {
+ expect(await initialComposer.count()).toBe(1)
+ expect(await initialComposer.isVisible()).toBe(true)
+ }).toPass({ timeout: 20_000 })
await page.evaluate(() => {
const created: string[] = []
const revoked: string[] = []
@@ -159,7 +163,11 @@ test.describe("same-tab Community attachment drafts", () => {
const { page } = await asUser("alice")
const channelA = `/c/channels/${serverId}/${channelAId}`
await page.goto(channelA, { waitUntil: "commit" })
- await expect(composerEditable(page)).toBeVisible({ timeout: 20_000 })
+ const initialComposer = composerEditable(page)
+ await expect(async () => {
+ expect(await initialComposer.count()).toBe(1)
+ expect(await initialComposer.isVisible()).toBe(true)
+ }).toPass({ timeout: 20_000 })
const body = `retry restored file ${Date.now()}`
await composerEditable(page).fill(body)
await page.getByTestId(tid.composerFileInput).setInputFiles({
@@ -229,7 +237,11 @@ test.describe("same-tab Community attachment drafts", () => {
await page.setViewportSize({ width: 390, height: 844 })
const channelA = `/c/channels/${serverId}/${channelAId}`
await page.goto(channelA, { waitUntil: "commit" })
- await expect(composerEditable(page)).toBeVisible({ timeout: 20_000 })
+ const initialComposer = composerEditable(page)
+ await expect(async () => {
+ expect(await initialComposer.count()).toBe(1)
+ expect(await initialComposer.isVisible()).toBe(true)
+ }).toPass({ timeout: 20_000 })
const body = `mobile restored image ${Date.now()}`
await composerEditable(page).fill(body)
await page.getByTestId(tid.composerFileInput).setInputFiles({
diff --git a/src/web/src/test/e2e-ui/51-mobile-forum-tag-editor.spec.ts b/src/web/src/test/e2e-ui/51-mobile-forum-tag-editor.spec.ts
index e55821b42..4f6437f60 100644
--- a/src/web/src/test/e2e-ui/51-mobile-forum-tag-editor.spec.ts
+++ b/src/web/src/test/e2e-ui/51-mobile-forum-tag-editor.spec.ts
@@ -298,7 +298,7 @@ test.describe("forum tag editor", () => {
}).toEqual({ tags: [], threads: [threadId] })
for (const { page } of [tabA, tabB]) {
await expect(page.getByTestId(tid.forumTagChip("archived"))).toHaveCount(0)
- await expect(page.getByTestId(tid.forumTagAll)).toHaveCount(0)
+ await expect(page.getByTestId(tid.forumTagAll)).toBeVisible()
await expect.poll(() => page.evaluate((id) => localStorage.getItem(`alook:forum-tag:${id}`), forumId)).toBeNull()
const card = page.getByTestId(tid.forumThreadCard(threadId))
await expect(card).toBeVisible()
@@ -326,6 +326,7 @@ test.describe("forum tag editor", () => {
await expect(page.getByTestId(tid.forumTagChip("archived"))).toBeVisible()
await page.getByTestId(tid.forumTagChip("archived")).click()
await expect(page.getByTestId(tid.forumThreadCard(threadId))).toBeVisible()
+ await expect(page).toHaveURL((url) => url.searchParams.get("tag") === "archived")
const writes = observeTagPuts(page)
const initialUrl = page.url()
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.ts
index 8bbbff22f..fbe3d0eb8 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
@@ -692,7 +692,11 @@ test.describe("message scroll characterization", () => {
await anchored.page.setViewportSize(VIEWPORT)
await installScrollTrace(anchored.page)
await anchored.page.goto(`/c/channels/${serverId}/${loadingChannelId}`, { waitUntil: "commit" })
- await expect(anchored.page.getByTestId(tid.newDivider)).toBeVisible({ timeout: 30_000 })
+ const anchoredNewDivider = anchored.page.getByTestId(tid.newDivider)
+ await expect(async () => {
+ expect(await anchoredNewDivider.count()).toBe(1)
+ expect(await anchoredNewDivider.isVisible()).toBe(true)
+ }).toPass({ timeout: 30_000 })
await expect(anchored.page.getByTestId(tid.messageScroller)).toHaveAttribute("data-pagination-enabled", "true")
const older = await holdNextRequest(actors,
anchored.page,
@@ -832,7 +836,7 @@ test.describe("message scroll characterization", () => {
await expect(scroller.locator('[data-message-list-content]')).toHaveAttribute("data-read-position-ready", "true")
const anchored = await anchorResponse
expect(anchored.status()).toBe(200)
- const anchorPage = readCommunityDocumentSeedFromHtml(await anchored.text()).entries.find(entry => entry.target.channelId === channelId)
+ 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)
let newestGets = 0
diff --git a/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts b/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts
index 5386a2895..313b06869 100644
--- a/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts
+++ b/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts
@@ -150,7 +150,11 @@ test("older and newer pages preserve a real-message anchor and do not replay", a
}
})
await olderUser.page.goto(`/c/channels/${serverId}/${channelId}`, { waitUntil: "commit" })
- await expect(olderUser.page.getByTestId(tid.newDivider)).toBeVisible({ timeout: 30_000 })
+ const olderNewDivider = olderUser.page.getByTestId(tid.newDivider)
+ await expect(async () => {
+ expect(await olderNewDivider.count()).toBe(1)
+ expect(await olderNewDivider.isVisible()).toBe(true)
+ }).toPass({ timeout: 30_000 })
await expect(olderUser.page.getByTestId(tid.messageScroller).locator('[data-message-list-content][data-read-position-ready="true"][data-initial-position-phase="revealed"]')).toBeVisible()
const olderPage = await holdNextPage(olderUser.page, channelId, "cursor", caseResources)
await moveToEdge(olderUser.page, "start")
@@ -173,7 +177,11 @@ test("older and newer pages preserve a real-message anchor and do not replay", a
}
})
await newerUser.page.goto(`/c/channels/${serverId}/${channelId}`, { waitUntil: "commit" })
- await expect(newerUser.page.getByTestId(tid.newDivider)).toBeVisible({ timeout: 30_000 })
+ const newerNewDivider = newerUser.page.getByTestId(tid.newDivider)
+ await expect(async () => {
+ expect(await newerNewDivider.count()).toBe(1)
+ expect(await newerNewDivider.isVisible()).toBe(true)
+ }).toPass({ timeout: 30_000 })
await expect(newerUser.page.getByTestId(tid.messageScroller).locator('[data-message-list-content][data-read-position-ready="true"][data-initial-position-phase="revealed"]')).toBeVisible()
const newerPage = await holdNextPage(newerUser.page, channelId, "since", caseResources)
await moveToEdge(newerUser.page, "end")
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.ts
index 5c8ee6eee..f68b2bff3 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
@@ -219,10 +219,28 @@ async function readShellGeometry(page: Page): Promise<ShellGeometry> {
}, { sidebar: "sidebar", main: "main", userBar: tid.userBar })
}
-async function expectDesktopGeometry(page: Page, sidebarWidth: number) {
- await expect(page.getByTestId(tid.userBar)).toBeVisible()
- await expect(shellPanel(page, "sidebar")).toBeVisible()
- await expect(page.locator('[data-slot="community-user-bar-overlay"]')).toBeVisible()
+async function expectDesktopGeometry(page: Page, sidebarWidth: number, options: { coldEntry?: boolean } = {}) {
+ if (options.coldEntry) {
+ const userBar = page.getByTestId(tid.userBar)
+ await expect(async () => {
+ expect(await userBar.count()).toBe(1)
+ expect(await userBar.isVisible()).toBe(true)
+ }).toPass({ timeout: 10_000 })
+ const sidebar = shellPanel(page, "sidebar")
+ await expect(async () => {
+ expect(await sidebar.count()).toBe(1)
+ expect(await sidebar.isVisible()).toBe(true)
+ }).toPass({ timeout: 10_000 })
+ const overlay = page.locator('[data-slot="community-user-bar-overlay"]')
+ await expect(async () => {
+ expect(await overlay.count()).toBe(1)
+ expect(await overlay.isVisible()).toBe(true)
+ }).toPass({ timeout: 10_000 })
+ } else {
+ await expect(page.getByTestId(tid.userBar)).toBeVisible()
+ await expect(shellPanel(page, "sidebar")).toBeVisible()
+ await expect(page.locator('[data-slot="community-user-bar-overlay"]')).toBeVisible()
+ }
await expect.poll(async () => {
const geometry = await readShellGeometry(page)
return {
@@ -617,7 +635,7 @@ test.describe("desktop default User Bar width", () => {
main: expect.any(Number),
})
await interaction.page.reload({ waitUntil: "commit" })
- await expectDesktopGeometry(interaction.page, resizedWidth)
+ await expectDesktopGeometry(interaction.page, resizedWidth, { coldEntry: true })
const resetHandle = interaction.page.locator('[data-slot="resizable-handle"]')
await resetHandle.dblclick({ force: true })
await expectDesktopGeometry(interaction.page, expectedDefaultSidebarWidth)
@@ -630,7 +648,7 @@ test.describe("desktop default User Bar width", () => {
layoutStorageKey,
)) as Record<string, unknown>
await interaction.page.reload({ waitUntil: "commit" })
- await expectDesktopGeometry(interaction.page, expectedDefaultSidebarWidth)
+ await expectDesktopGeometry(interaction.page, expectedDefaultSidebarWidth, { coldEntry: true })
await attachJson(testInfo, "desktop-width-layout-evidence", {
hydrationSamples,
mobileGeometry,
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.ts
index 66f2f810a..33c719c45 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
@@ -318,7 +318,7 @@ test.describe("mobile notification chat routes (native bridge simulation)", () =
const response = await page.goto(`/c/channels/${serverId}/${channelId}?msg=${channelMessageId}`)
expect(response?.ok()).toBe(true)
const html = await response!.text()
- const initialSeed = readCommunityDocumentSeedFromHtml(html)
+ 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 })
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.ts
index 9ed875fa5..78cbbc1fe 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,27 +1,73 @@
+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"
-export function readCommunityDocumentSeedFromHtml(html: string): CommunityDocumentSeed {
+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 seedKey = '"initialSeed":'
- const seedKeyIndex = flight.indexOf(`${seedKey}{`)
- expect(seedKeyIndex).toBeGreaterThanOrEqual(0)
- const seedStart = seedKeyIndex + seedKey.length
- let depth = 0
- let quoted = false
- let escaped = false
- let seedEnd = seedStart
- for (; seedEnd < flight.length; seedEnd += 1) {
- const char = flight[seedEnd]
- if (escaped) { escaped = false; continue }
- if (quoted && char === "\\") { escaped = true; continue }
- if (char === '"') { quoted = !quoted; continue }
- if (!quoted && char === "{") depth += 1
- if (!quoted && char === "}" && --depth === 0) { seedEnd += 1; break }
+ 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>
}
- return JSON.parse(flight.slice(seedStart, seedEnd)) as CommunityDocumentSeed
+ 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 async function expectUniqueSsrInitialFrame(page: Page) {