Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
perf(web): show cached product targets before route delivery
Generee84b580ccd6
diff --git a/src/web/src/app/c/@sidebar/channels/[serverId]/layout.tsx b/src/web/src/app/c/@sidebar/channels/[serverId]/layout.tsxindex 8f16389e7..ecc572698 100644--- a/src/web/src/app/c/@sidebar/channels/[serverId]/layout.tsx+++ b/src/web/src/app/c/@sidebar/channels/[serverId]/layout.tsx@@ -1,10 +1,5 @@import type { ReactNode } from "react"-import { ServerSidebarSlot } from "@/components/community/shell/server-sidebar-slot"-export default async function ServerSidebarLayout({ children, params }: {- children: ReactNode- params: Promise<{ serverId: string }>-}) {- const { serverId } = await params- return <><ServerSidebarSlot serverId={serverId} />{children}</>+export default function ServerSidebarLayout({ children }: { children: ReactNode }) {+ return children}diff --git a/src/web/src/app/c/channels/[serverId]/page.dom.test.ts b/src/web/src/app/c/channels/[serverId]/page.dom.test.tsindex ea6b0b4b5..5875fb839 100644--- a/src/web/src/app/c/channels/[serverId]/page.dom.test.ts+++ b/src/web/src/app/c/channels/[serverId]/page.dom.test.ts@@ -2,8 +2,12 @@ import { createElement } from "react"import { beforeEach, describe, expect, it, vi } from "vitest"import { render, screen } from "@/test/react-dom-harness"import ServerDefaultPage from "./page"+import { tid } from "@/lib/community/testids"import { CommunityServerRouteContext } from "@/components/community/shell/community-route-context"+import { CommunityModuleRouteContext } from "@/contexts/community/module-route"+import { CommunityRouteContext } from "@/contexts/community/route-frame"+const mocks = vi.hoisted(() => ({breakpoint: { current: "mobile" as "mobile" | "desktop" | "unknown" },lastChannel: { current: null as string | null },@@ -64,6 +68,7 @@ describe("ServerDefaultPage checkpoint route contract", () => {const rendered = render(createElement(CommunityServerRouteContext, { value: { serverId: "server_1", serverParam: "server_1" } }, createElement(ServerDefaultPage)))expect(mocks.replace).not.toHaveBeenCalled()+ expect(screen.getByTestId(tid.pendingMain("server-landing"))).toHaveAttribute("data-community-target-href", "/c/channels/server_1")expect(screen.getByRole("main", { name: "Loading server" })).toHaveAttribute("aria-busy", "true")expect(screen.getByRole("main", { name: "Loading server" })).not.toHaveAttribute("data-community-mobile-transition")@@ -130,3 +135,15 @@ describe("ServerDefaultPage checkpoint route contract", () => {expect(screen.getByText("Create a channel from the sidebar to get started.")).toBeInTheDocument()})})+++it("submits the pending target root destination through its intent owner with target search", () => {+ mocks.breakpoint.current = "desktop"+ mocks.search.current = "wrong=old"+ const replace = vi.fn()+ render(createElement(CommunityRouteContext, { value: { navigation: { replace } } as never },+ createElement(CommunityModuleRouteContext, { value: { href: "/c/channels/server_1?invite=1", routeCommitted: false } },+ createElement(CommunityServerRouteContext, { value: { serverId: "server_1", serverParam: "server_1" } }, createElement(ServerDefaultPage)))))+ expect(replace).toHaveBeenCalledExactlyOnceWith("/c/channels/server_1/channel_1?invite=1")+ expect(mocks.replace).not.toHaveBeenCalled()+})diff --git a/src/web/src/app/c/channels/[serverId]/page.tsx b/src/web/src/app/c/channels/[serverId]/page.tsxindex f6d7b917f..eb67a69b0 100644--- a/src/web/src/app/c/channels/[serverId]/page.tsx+++ b/src/web/src/app/c/channels/[serverId]/page.tsx@@ -1,52 +1,3 @@"use client"-import { useCommunityServerRoute } from "@/components/community/shell/community-route-context"-import { useEffect, useRef } from "react"-import { useRouter, useSearchParams } from "next/navigation"-import { ServerLandingPendingFrame } from "@/components/community/shell/server-landing-pending-frame"-import { useServer } from "@/hooks/community/use-servers"-import { useBreakpoint } from "@/hooks/use-mobile"-import { getLastChannel, resolveCommunityLandingHref } from "@/lib/community/last-channel"--export default function ServerDefaultPage() {- const { serverId } = useCommunityServerRoute()- const router = useRouter()- const searchParams = useSearchParams()- const { server: currentServer } = useServer(serverId)- const breakpoint = useBreakpoint()- const replacingHrefRef = useRef<string | null>(null)-- useEffect(() => {- if (breakpoint !== "desktop" || !currentServer) return- const allChannels = currentServer.categories.flatMap((cat) => cat.channels)- // Restore one remembered channel id, or use the first top-level channel- // when there is no valid memory.- const target = resolveCommunityLandingHref({- serverId,- channelIds: allChannels.filter((channel) => !channel.pending).map((channel) => channel.id),- last: getLastChannel(serverId),- breakpoint,- })- if (target !== `/c/channels/${encodeURIComponent(serverId)}`) {- const search = searchParams.toString()- const href = `${target}${search ? `?${search}` : ""}`- if (replacingHrefRef.current === href) return- replacingHrefRef.current = href- router.replace(href)- }- }, [breakpoint, currentServer, serverId, router, searchParams])-- if (breakpoint !== "desktop") return null-- const allChannels = currentServer?.categories.flatMap((cat) => cat.channels) ?? []- if (currentServer && allChannels.length === 0) {- return (- <div className="flex flex-1 flex-col items-center justify-center gap-2 text-muted-foreground">- <span className="text-sm">No channels yet</span>- <span className="text-xs">Create a channel from the sidebar to get started.</span>- </div>- )- }-- return <ServerLandingPendingFrame />-}+export { default } from "@/components/community/shell/server-landing-route"diff --git a/src/web/src/app/c/channels/[serverId]/settings/page.tsx b/src/web/src/app/c/channels/[serverId]/settings/page.tsxindex d98e334e6..c87b55a8a 100644--- a/src/web/src/app/c/channels/[serverId]/settings/page.tsx+++ b/src/web/src/app/c/channels/[serverId]/settings/page.tsx@@ -1,17 +1,3 @@"use client"-import { useCommunityServerRoute } from "@/components/community/shell/community-route-context"-import { useEffect } from "react"-import { useRouter, useSearchParams } from "next/navigation"--export default function ServerSettingsRedirect() {- const { serverId } = useCommunityServerRoute()- const router = useRouter()- const searchParams = useSearchParams()- useEffect(() => {- const nextSearchParams = new URLSearchParams(searchParams.toString())- nextSearchParams.set("settings", "1")- router.replace(`/c/channels/${encodeURIComponent(serverId)}?${nextSearchParams.toString()}`)- }, [serverId, router, searchParams])- return null-}+export { default } from "@/components/community/shell/server-settings-route"diff --git a/src/web/src/app/c/channels/layout.route-memory.dom.test.ts b/src/web/src/app/c/channels/layout.route-memory.dom.test.tsindex f3baad142..76b262d6b 100644--- a/src/web/src/app/c/channels/layout.route-memory.dom.test.ts+++ b/src/web/src/app/c/channels/layout.route-memory.dom.test.ts@@ -129,7 +129,6 @@ vi.mock("@/stores/community", async (importOriginal) => {...actual,useCommunityStore: { getState: () => state },useCurrentChannelId: () => null,- useCurrentChannelMeta: () => null,}})vi.mock("@/contexts/community/current-user", () => ({@@ -362,7 +361,7 @@ describe("ServerLayout deletion routing", () => {const actual = await vi.importActual<typeof import("@/lib/community/eject-server")>("@/lib/community/eject-server")actual.beginOwnerServerDelete(mocks.queryClient, "missing-server", mocks.routeToken)const renderer = render(createElement(ServerLayout))- expect(renderer.getByTestId("owner-delete-pending-frame")).toHaveAttribute("data-href", "/c/channels/missing-server/missing-channel")+ expect(renderer.getByTestId("owner-delete-pending-frame")).toHaveAttribute("data-href", mocks.pendingHref.current)expect(mocks.channelRoute).not.toHaveBeenCalled()renderer.unmount()})diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsxindex 41cbe7f93..1480b9a04 100644--- a/src/web/src/app/c/channels/layout.tsx+++ b/src/web/src/app/c/channels/layout.tsx@@ -2,23 +2,16 @@import type { ReactNode } from "react"import { useSelectedLayoutSegments, usePathname, useSearchParams } from "next/navigation"-import { useQueryClient } from "@tanstack/react-query"-import { useSelector } from "@tanstack/react-store"-import { useCurrentUser } from "@/contexts/community/current-user"-import { getCommunityRuntime } from "@/stores/community/runtime"import { CommunityServerRouteContext, useCommunityRouteFrame } from "@/components/community/shell/community-route-context"-import { ChannelRoute } from "@/components/community/channels/channel-route"+import { ServerConversationRoute } from "@/components/community/channels/server-conversation-route"import { normalizeCommunityHref, resolveCommunityModulePlan } from "@/lib/community/community-route"-import { CommunityPendingFrame } from "@/components/community/shell/community-pending-frame"export default function ServerLayout({ children }: { children: ReactNode }) {const segments = useSelectedLayoutSegments()const serverParam = segments[0]const pathname = usePathname()const searchParams = useSearchParams()- const queryClient = useQueryClient()- const currentUser = useCurrentUser()- const { navigation, ownerDeleteRouteScope } = useCommunityRouteFrame()+ const { navigation } = useCommunityRouteFrame()const serverId = serverParam ? decodeURIComponent(serverParam) : ""const publishedHref = normalizeCommunityHref(`${pathname}${searchParams.size ? `?${searchParams}` : ""}`)const framePathname = segments.length ? `/c/channels/${segments.join("/")}` : "/c/channels"@@ -31,17 +24,10 @@ export default function ServerLayout({ children }: { children: ReactNode }) {const modulePlan = resolveCommunityModulePlan(targetHref.href)const routeChannelId = modulePlan.main.kind === "server-conversation" && modulePlan.main.serverId === serverId? modulePlan.main.leafId : null- const protectedRoute = useSelector(getCommunityRuntime(queryClient).serverEject, (state) =>- state.transactions.has(serverId) || Boolean(ownerDeleteRouteScope?.serverId === serverId- && state.tombstones.get(ownerDeleteRouteScope.token) === serverId))- const content = protectedRoute- ? <CommunityPendingFrame href={pathname} />- : routeChannelId- ? <ChannelRoute key={JSON.stringify([currentUser.id, serverId])}- serverParam={serverParam!} channelId={routeChannelId}- targetHref={targetHref.href} routeCommitted={publishedHref.href === targetHref.href} />- : childrenreturn <CommunityServerRouteContext value={{ serverId, serverParam: serverParam ?? "" }}>- {content}+ <ServerConversationRoute serverId={serverId} serverParam={serverParam ?? ""}+ channelId={routeChannelId} href={targetHref.href} routeCommitted={publishedHref.href === targetHref.href}>+ {children}+ </ServerConversationRoute></CommunityServerRouteContext>}diff --git a/src/web/src/app/c/me/bots/page.tsx b/src/web/src/app/c/me/bots/page.tsxindex 9f1414ba6..5c025428d 100644--- a/src/web/src/app/c/me/bots/page.tsx+++ b/src/web/src/app/c/me/bots/page.tsx@@ -1,13 +1,3 @@"use client"-import { BotList } from "@/components/community/bots/bot-list"-import { useUiHandlers } from "@/stores/community"--export default function MeBotsPage() {- const uiHandlers = useUiHandlers()- return (- <BotList- onBack={() => uiHandlers.goBackMobile?.()}- />- )-}+export { default } from "@/components/community/bots/me-bots-route"diff --git a/src/web/src/app/c/me/friends/page.dom.test.tsx b/src/web/src/app/c/me/friends/page.dom.test.tsxindex c13a05145..27ebd0534 100644--- a/src/web/src/app/c/me/friends/page.dom.test.tsx+++ b/src/web/src/app/c/me/friends/page.dom.test.tsx@@ -1,26 +1,92 @@import React from "react"import { renderToString } from "react-dom/server"-import { render } from "@/test/react-dom-harness"+import { act, fireEvent, render } from "@/test/react-dom-harness"import { beforeEach, describe, expect, it, vi } from "vitest"import MeFriendsPage from "./page"+import { CommunityTestProvider } from "@/test/community-owner-fixture"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { useCommunityNavigationController } from "@/components/community/shell/use-community-navigation-controller"+import { CommunityRouteContext } from "@/contexts/community/route-frame"+import { normalizeCommunityHref, resolveCommunityCheckpointPlan, type CommunityCommittedFrame } from "@/lib/community/community-route"+import { CommunityModuleRouteContext } from "@/contexts/community/module-route"-const mocks = vi.hoisted(() => ({ breakpoint: "unknown", props: vi.fn(), back: vi.fn() }))+const mocks = vi.hoisted(() => ({ breakpoint: "unknown", props: vi.fn(), back: vi.fn(), realPage: false, pathname: "/c/channels/source/channel", search: "", push: vi.fn(), replace: vi.fn() }))vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mocks.breakpoint }))-vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn() }), useSearchParams: () => new URLSearchParams() }))-vi.mock("@/hooks/community/use-friends", () => ({ useFriends: () => ({ friends: [], pending: [], blocked: [], isLoading: true }) }))+vi.mock("next/navigation", () => ({ useRouter: () => ({push: mocks.push, replace: mocks.replace}), usePathname: () => mocks.pathname, useSearchParams: () => new URLSearchParams(mocks.search) }))+vi.mock("@/hooks/community/use-friends", () => ({ useFriends: () => ({ friends: [], pending: [], blocked: [], isPending: !mocks.realPage }) }))vi.mock("@/stores/community", () => ({ useUiHandlers: () => ({ goBackMobile: mocks.back }) }))-vi.mock("@/lib/community-db/projections", () => ({ useCanonicalProfilesByUserId: () => new Map() }))+vi.mock("@/lib/community-db/projections", async original => ({...await original<typeof import("@/lib/community-db/projections")>(), useCanonicalProfilesByUserId: () => new Map()}))vi.mock("@/hooks/community/mutations", () => {const mutation = () => ({ mutateAsync: vi.fn(), mutate: vi.fn() })return { useSendFriendRequest: mutation, useAcceptFriendRequest: mutation, useRejectFriendRequest: mutation,useCancelBotFriendRequest: mutation, useRemoveFriend: mutation, useBlockUser: mutation,useUnblockUser: mutation, useCreateOrGetDm: mutation }})-vi.mock("@/components/community/social/friends-page", () => ({ FriendsPage: (props: Record<string, unknown>) => { mocks.props(props); return null } }))+vi.mock("@/components/community/social/friends-page", async original => {+ const actual = await original<typeof import("@/components/community/social/friends-page")>()+ return {...actual, FriendsPage: (props: React.ComponentProps<typeof actual.FriendsPage>) => { mocks.props(props); return mocks.realPage ? <actual.FriendsPage {...props} /> : null }}+})++beforeEach(() => { mocks.props.mockClear(); mocks.back.mockClear(); mocks.realPage = false; mocks.push.mockClear(); mocks.replace.mockClear(); mocks.pathname = "/c/channels/source/channel"; mocks.search = "" })-beforeEach(() => { mocks.props.mockClear(); mocks.back.mockClear() })+async function pendingFriends() {+ mocks.realPage = true+ const owner = await createCommunityQueryOwner()+ let committedFrame: CommunityCommittedFrame = {...normalizeCommunityHref(mocks.pathname), revision: 0}+ let navigation!: ReturnType<typeof useCommunityNavigationController>+ function Scenario() {+ const currentNavigation = useCommunityNavigationController(committedFrame)+ React.useLayoutEffect(() => { navigation = currentNavigation }, [currentNavigation])+ const checkpoint = resolveCommunityCheckpointPlan({committedFrame, targetHref: currentNavigation.pendingHref ?? currentNavigation.publishedHref, pending: currentNavigation.navigationPending, targetReady: true})+ return <CommunityRouteContext value={{frame: committedFrame, navigation: currentNavigation, breakpoint: "desktop", ownerDeleteRouteScope: undefined}}>+ {checkpoint.main.kind === "module-route" ? <CommunityModuleRouteContext value={{href: checkpoint.main.href, routeCommitted: !currentNavigation.navigationPending}}><MeFriendsPage /></CommunityModuleRouteContext> : null}+ </CommunityRouteContext>+ }+ const node = () => <CommunityTestProvider client={owner.client} registry={owner.registry} retainOwner><Scenario /></CommunityTestProvider>+ const view = render(node())+ act(() => navigation.pushImmediate("/c/me/friends?tab=new"))+ return {view, get navigation() { return navigation }, publish(href: string) {+ const url = new URL(href, "https://alook.test")+ mocks.pathname = url.pathname; mocks.search = url.search.slice(1)+ committedFrame = {...normalizeCommunityHref(url.pathname), revision: 1}+ view.rerender(node())+ }}+}describe("friends route initial mobile back ownership", () => {+ it("changes the real New tab to All before route delivery through the latest navigation owner", async () => {+ const page = await pendingFriends()+ expect(page.view.getByRole("tab", {name: "New"})).toHaveAttribute("aria-selected", "true")+ const original = page.navigation.captureIntent()+ fireEvent.click(page.view.getByRole("tab", {name: "All"}))+ expect(page.navigation.pendingHref).toBe("/c/me/friends")+ expect(original()).toBe(false)+ expect(page.view.getByRole("tab", {name: "All"})).toHaveAttribute("aria-selected", "true")+ expect(mocks.pathname).toBe("/c/channels/source/channel")+ })++ it("keeps a newer All intent when the old New-tab response publishes first", async () => {+ const page = await pendingFriends()+ act(() => page.navigation.replace("/c/me/friends"))+ page.publish("/c/me/friends?tab=new")+ expect(page.navigation.navigationPending).toBe(true)+ expect(page.navigation.pendingHref).toBe("/c/me/friends")+ expect(page.view.getByRole("tab", {name: "All"})).toHaveAttribute("aria-selected", "true")+ page.publish("/c/me/friends")+ expect(page.navigation.navigationPending).toBe(false)+ expect(page.view.getByRole("tab", {name: "All"})).toHaveAttribute("aria-selected", "true")+ })++ it("uses pending target tab parameters while Next still publishes the old search", () => {+ const node = (href: string, routeCommitted: boolean) => <CommunityModuleRouteContext value={{href, routeCommitted}}><MeFriendsPage /></CommunityModuleRouteContext>+ const view = render(node("/c/me/friends?tab=new", false))+ expect(mocks.props.mock.calls.at(-1)![0]).toMatchObject({activeTab: "new"})+ view.rerender(node("/c/me/friends?tab=all", false))+ expect(mocks.props.mock.calls.at(-1)![0]).toMatchObject({activeTab: "all"})+ view.rerender(node("/c/me/friends?tab=all", true))+ expect(mocks.props.mock.calls.at(-1)![0]).toMatchObject({activeTab: "all"})+ })+it.each(["unknown", "mobile", "desktop"])("supplies the same viewport-owned Back action at %s", (breakpoint) => {mocks.breakpoint = breakpointrenderToString(<MeFriendsPage />)diff --git a/src/web/src/app/c/me/friends/page.tsx b/src/web/src/app/c/me/friends/page.tsxindex 487061f63..5bf0197f3 100644--- a/src/web/src/app/c/me/friends/page.tsx+++ b/src/web/src/app/c/me/friends/page.tsx@@ -1,146 +1,3 @@"use client"-import { FriendsPage } from "@/components/community/social/friends-page"-import { useMemo } from "react"-import { useRouter, useSearchParams } from "next/navigation"-import { useFriends } from "@/hooks/community/use-friends"-import { useUiHandlers } from "@/stores/community"-import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"-import { readCommunityProfile } from "@/lib/community/profile-read"-import {- useSendFriendRequest,- useAcceptFriendRequest,- useRejectFriendRequest,- useCancelBotFriendRequest,- useRemoveFriend,- useBlockUser,- useUnblockUser,- useCreateOrGetDm,-} from "@/hooks/community/mutations"-import { toast } from "sonner"-import { toastApiError } from "@/lib/api/client"--export default function MeFriendsPage() {- const router = useRouter()- const searchParams = useSearchParams()- const activeTab = searchParams.get("tab") === "new" ? "new" : "all"- const { friends: rawFriends, pending, blocked, isLoading } = useFriends()- const uiHandlers = useUiHandlers()- const profilesByUserId = useCanonicalProfilesByUserId()- const friends = useMemo(- () =>- rawFriends.map((f) => {- const userId = f.userId ?? f.id- const canonical = profilesByUserId.get(userId)- const profile = canonical- ? readCommunityProfile(canonical, userId)- : { ...f, presence: f.status }- return {- ...f,- name: profile.name,- discriminator: profile.discriminator,- avatar: profile.avatar,- avatarVersion: profile.avatarVersion,- status: profile.presence,- statusEmoji: profile.statusEmoji,- statusText: profile.statusText,- }- }),- [profilesByUserId, rawFriends],- )-- const sendFriendRequest = useSendFriendRequest()- const acceptFriendRequest = useAcceptFriendRequest()- const rejectFriendRequest = useRejectFriendRequest()- const cancelBotFriendRequest = useCancelBotFriendRequest()- const removeFriend = useRemoveFriend()- const blockUser = useBlockUser()- const unblockUser = useUnblockUser()- const createOrGetDm = useCreateOrGetDm()-- return (- <FriendsPage- friends={friends}- pending={pending}- blocked={blocked}- loading={isLoading}- activeTab={activeTab}- onActiveTabChange={(tab) => {- router.replace(tab === "new" ? "/c/me/friends?tab=new" : "/c/me/friends")- }}- onOpenProfile={(name, event, discriminator, userId) => {- uiHandlers.openProfile?.(name, event, discriminator, userId)- }}- onBack={() => uiHandlers.goBackMobile?.()}- onAccept={async (id) => {- try {- await acceptFriendRequest.mutateAsync({ friendshipId: id })- toast("Friend request accepted")- } catch (error) {- toastApiError(error, "Failed to accept request")- throw error- }- }}- onReject={async (id) => {- try {- await rejectFriendRequest.mutateAsync({ friendshipId: id })- } catch (error) {- toastApiError(error, "Failed to reject request")- throw error- }- }}- onCancelRequest={({ id }) =>- // Unified after migration 0065 — outgoing pendings (own or the owner's- // bots') are real community_friendship rows cancelled via DELETE.- cancelBotFriendRequest.mutate(- { requestId: id },- { onError: (e) => toastApiError(e, "Failed to cancel request") },- )- }- onUnblock={(id) =>- unblockUser.mutate(- { userId: id },- {- onSuccess: () => toast("User unblocked"),- onError: (e) => toastApiError(e, "Failed to unblock user"),- },- )- }- onSendRequest={async ({ userId, username }) => {- try {- await sendFriendRequest.mutateAsync({ userId, username })- toast("Friend request sent")- } catch (e) {- toastApiError(e, "Failed to send friend request")- }- }}- onRemoveFriend={(id) =>- removeFriend.mutate(- { friendshipId: id },- {- onSuccess: () => toast("Friend removed"),- onError: (e) => toastApiError(e, "Failed to remove friend"),- },- )- }- onBlock={(id) =>- blockUser.mutate(- { userId: id },- {- onSuccess: () => toast("User blocked"),- onError: (e) => toastApiError(e, "Failed to block user"),- },- )- }- onDm={async (userId) => {- uiHandlers.cancelPendingNavigation?.()- try {- const data = await createOrGetDm.mutateAsync({ userId })- if (data.conversation.id) uiHandlers.navigatePath?.(`/c/me/${data.conversation.id}`)- } catch (e) {- toastApiError(e, "Failed to open DM")- }- }}- />- )-}+export { default } from "@/components/community/social/friends-route"diff --git a/src/web/src/app/c/me/layout.tsx b/src/web/src/app/c/me/layout.tsxindex 8d2aa424c..c1fc563ba 100644--- a/src/web/src/app/c/me/layout.tsx+++ b/src/web/src/app/c/me/layout.tsx@@ -1,23 +1,15 @@"use client"-import { useEffect, type ReactNode } from "react"+import type { ReactNode } from "react"import { useSelectedLayoutSegments, usePathname } from "next/navigation"-import { useCurrentUser } from "@/contexts/community/current-user"-import { isRememberableMeLocation, setLastMeLocation } from "@/lib/community/last-me-location"-import { commitLastCommunityRoute } from "@/lib/community/last-community-route"+import { useMeRouteMemory } from "@/hooks/community/use-me-route-memory"import { resolveCommunityModulePlan } from "@/lib/community/community-route"export default function MeLayout({ children }: { children: ReactNode }) {const pathname = usePathname()- const currentUser = useCurrentUser()const segments = useSelectedLayoutSegments()const modulePlan = resolveCommunityModulePlan(segments.length ? `/c/me/${segments.join("/")}` : "/c/me")const dmId = modulePlan.main.kind === "dm" ? modulePlan.main.dmId : undefined- useEffect(() => {- const staticModuleActive = ["/c/me/friends", "/c/me/machines", "/c/me/bots"].includes(pathname)- if (dmId || !staticModuleActive || !isRememberableMeLocation(pathname)) return- setLastMeLocation(pathname)- commitLastCommunityRoute(currentUser.id, pathname)- }, [currentUser.id, dmId, pathname])+ useMeRouteMemory(pathname, !dmId)return children}diff --git a/src/web/src/app/c/me/machines/page.tsx b/src/web/src/app/c/me/machines/page.tsxindex 2e90ab49c..458d63b4f 100644--- a/src/web/src/app/c/me/machines/page.tsx+++ b/src/web/src/app/c/me/machines/page.tsx@@ -1,32 +1,3 @@"use client"-import { MachineList } from "@/components/community/machines/machine-list"-import { OnboardingSelectDialogPreview } from "@/components/community/onboarding/onboarding-select-dialog.preview"-import { useUiHandlers } from "@/stores/community"-import { useSearchParams } from "next/navigation"--export default function MeMachinesPage() {- const uiHandlers = useUiHandlers()- const searchParams = useSearchParams()- const onboardingPreview = searchParams.get("onboarding-preview")- const showOnboardingPreview =- process.env.NODE_ENV !== "production"- && (- onboardingPreview === "1"- || onboardingPreview === "online"- || onboardingPreview === "setting-up"- )- return (- <>- <MachineList- onBack={() => uiHandlers.goBackMobile?.()}- />- {showOnboardingPreview ? (- <OnboardingSelectDialogPreview- simulateOnlineMachine={onboardingPreview === "online"}- showSettingUp={onboardingPreview === "setting-up"}- />- ) : null}- </>- )-}+export { default } from "@/components/community/machines/me-machines-route"diff --git a/src/web/src/app/c/me/page.dom.test.ts b/src/web/src/app/c/me/page.dom.test.tsindex c85345303..9f415c17d 100644--- a/src/web/src/app/c/me/page.dom.test.ts+++ b/src/web/src/app/c/me/page.dom.test.ts@@ -14,7 +14,7 @@ const mocks = vi.hoisted(() => ({replace: vi.fn(),}))-vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: mocks.replace }) }))+vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: mocks.replace }), useSearchParams: () => new URLSearchParams() }))vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mocks.breakpoint }))vi.mock("@/lib/community-onboarding", () => ({useCommunityOnboarding: () => mocks.onboarding,diff --git a/src/web/src/app/c/me/page.tsx b/src/web/src/app/c/me/page.tsxindex c840da2dd..750012b8c 100644--- a/src/web/src/app/c/me/page.tsx+++ b/src/web/src/app/c/me/page.tsx@@ -1,33 +1,3 @@"use client"-import { useEffect } from "react"-import { useRouter } from "next/navigation"-import { useBreakpoint } from "@/hooks/use-mobile"-import { CommunityPendingFrame } from "@/components/community/shell/community-pending-frame"-import { useCommunityOnboarding } from "@/lib/community-onboarding"-import { getLastMeLeaf, pickMeLandingLocation } from "@/lib/community/last-me-location"-import { useSelector } from "@tanstack/react-store"-import { useQueryClient } from "@tanstack/react-query"-import { getCommunityRuntime } from "@/stores/community/runtime"--export default function MeListPage() {- const router = useRouter()- const breakpoint = useBreakpoint()- const onboarding = useCommunityOnboarding()- const queryClient = useQueryClient()- const runtime = getCommunityRuntime(queryClient)- const ownerDeleteRootLanding = useSelector(runtime.serverEject, (state) => state.meRootLanding)- const destination = breakpoint === "desktop"- && !onboarding- && !ownerDeleteRootLanding- ? pickMeLandingLocation(getLastMeLeaf())- : null-- useEffect(() => {- if (!destination) return- if (runtime.ui.get().onboardingState || runtime.serverEject.get().meRootLanding) return- router.replace(destination)- }, [destination, router, runtime])-- return destination ? <CommunityPendingFrame href={destination} /> : null-}+export { default } from "@/components/community/shell/me-root-route"diff --git a/src/web/src/app/c/page.dom.test.ts b/src/web/src/app/c/page.dom.test.tsindex 90487079c..f8725f7c2 100644--- a/src/web/src/app/c/page.dom.test.ts+++ b/src/web/src/app/c/page.dom.test.ts@@ -14,11 +14,11 @@ vi.mock("next/navigation", () => ({vi.mock("@/contexts/community/current-user", () => ({useCurrentUser: () => ({ id: mocks.userId }),}))-vi.mock("@/components/community/shell/community-session-pending-frame", () => ({- CommunitySessionPendingFrame: (props: Record<string, unknown>) => (+vi.mock("@/components/community/shell/community-pending-frame", () => ({+ CommunityPendingFrame: (props: Record<string, unknown>) => (createElement("div", {"data-testid": "community-session-pending-frame",- "data-pathname": props.pathname,+ "data-pathname": props.href,})),}))diff --git a/src/web/src/app/c/page.tsx b/src/web/src/app/c/page.tsxindex be32f4d49..d21a30dfc 100644--- a/src/web/src/app/c/page.tsx+++ b/src/web/src/app/c/page.tsx@@ -1,22 +1,3 @@"use client"-import { useRouter } from "next/navigation"-import { useEffect } from "react"-import { CommunitySessionPendingFrame } from "@/components/community/shell/community-session-pending-frame"-import { useCurrentUser } from "@/contexts/community/current-user"-import { resolveCommunityColdEntryDestination } from "@/lib/community/last-community-route"--export default function CommunityIndex() {- const router = useRouter()- const currentUser = useCurrentUser()- useEffect(() => {- const destination = resolveCommunityColdEntryDestination({- accountId: currentUser.id,- pathname: window.location.pathname,- search: window.location.search,- hash: window.location.hash,- })- router.replace(destination)- }, [currentUser.id, router])- return <CommunitySessionPendingFrame pathname="/c" />-}+export { default } from "@/components/community/shell/community-root-route"diff --git a/src/web/src/components/community/bots/bot-list-controller.dom.test.ts b/src/web/src/components/community/bots/bot-list-controller.dom.test.tsindex 08f730fd7..ed7a142c6 100644--- a/src/web/src/components/community/bots/bot-list-controller.dom.test.ts+++ b/src/web/src/components/community/bots/bot-list-controller.dom.test.ts@@ -1,4 +1,8 @@import React from "react"+import { useCommunityNavigationController } from "@/components/community/shell/use-community-navigation-controller"+import { CommunityRouteContext } from "@/contexts/community/route-frame"+import { normalizeCommunityHref } from "@/lib/community/community-route"+import { CommunityModuleRouteContext } from "@/contexts/community/module-route"import { useQueryClient } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"import { readFileSync } from "node:fs"@@ -16,6 +20,7 @@ const readWebSource = (path: string) => readFileSync(resolve(webRoot, path), "utconst mocks = vi.hoisted(() => ({hookOrder: [] as string[],+ pathname: "/c/me/bots",target: "mac1" as string | null,audit: null as string | null,bots: [] as BotSummary[],@@ -53,6 +58,7 @@ const mocks = vi.hoisted(() => ({}))vi.mock("next/navigation", () => ({+ usePathname: () => mocks.pathname,useRouter: () => {mocks.hookOrder.push("router")return { push: mocks.push, replace: mocks.replace }@@ -81,7 +87,7 @@ vi.mock("@/hooks/community/use-bots", async (importOriginal) => {return {bots: mocks.bots,data: mocks.botsDataReady ? { bots: mocks.bots, ...mocks.planSummary, isFounder: mocks.isFounder } : undefined,- isLoading: mocks.botsLoading,+ isPending: mocks.botsLoading,}},useDeleteBot: () => {@@ -105,7 +111,7 @@ vi.mock("@/hooks/community/use-bots", async (importOriginal) => {vi.mock("@/hooks/community/use-machines", () => ({useMachines: () => {mocks.hookOrder.push("machines")- return { machines: mocks.machines, isLoading: mocks.machinesLoading }+ return { machines: mocks.machines, isPending: mocks.machinesLoading }},}))vi.mock("@/lib/community-db/projections", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/community-db/projections")>(),@@ -179,9 +185,51 @@ const bot = (id: string, machineId: string): BotSummary => ({})describe("useBotListController", () => {+ it("publishes pending billing through the real navigation owner instead of leaving the old target selected", () => {+ mocks.pathname = "/c/channels/source/channel"+ const frame = {...normalizeCommunityHref(mocks.pathname), revision: 0}+ let navigation!: ReturnType<typeof useCommunityNavigationController>+ function Scenario() {+ const currentNavigation = useCommunityNavigationController(frame)+ React.useLayoutEffect(() => { navigation = currentNavigation }, [currentNavigation])+ return React.createElement(CommunityRouteContext, {value: {frame, navigation: currentNavigation, breakpoint: "desktop", ownerDeleteRouteScope: undefined}},+ React.createElement(CommunityModuleRouteContext, {value: {href: currentNavigation.pendingHref ?? "/c/me/bots?keep=1", routeCommitted: false}}, React.createElement(Probe)))+ }+ rtlRender(React.createElement(Scenario))+ act(() => navigation.pushImmediate("/c/me/bots?keep=1"))+ const oldIntent = navigation.captureIntent()+ act(() => latest.viewPlan())+ expect(navigation.pendingHref).toBe("/c/me/bots?keep=1&settings=billing")+ expect(oldIntent()).toBe(false)+ })++ it("opens billing from the pending target URL rather than the still-published module", () => {+ window.history.replaceState(null, "", "/c/me/friends?tab=new")+ rtlRender(React.createElement(CommunityModuleRouteContext, {value: {href: "/c/me/bots?keep=1", routeCommitted: false}}, React.createElement(Probe)))+ act(() => latest.viewPlan())+ expect(mocks.push).toHaveBeenCalledWith("/c/me/bots?keep=1&settings=billing")+ expect(window.location.pathname).toBe("/c/me/friends")+ })++ it("renders cached target data without consuming audit or machine URL actions before commit", () => {+ const node = (routeCommitted: boolean) => React.createElement(CommunityModuleRouteContext, {value: {href: "/c/me/bots?audit=b1&machineId=mac1&keep=1", routeCommitted}}, React.createElement(Probe))+ const view = rtlRender(node(false))+ expect(latest.isLoading).toBe(false)+ expect(latest.bots.map(item => item.id)).toEqual(["b1"])+ expect(latest.activityOpen).toBe(false)+ expect(mocks.replace).not.toHaveBeenCalled()+ expect(scrollIntoView).not.toHaveBeenCalled()+ view.rerender(node(true))+ expect(latest.activityOpen).toBe(true)+ expect(latest.activityBot?.id).toBe("b1")+ expect(mocks.replace).not.toHaveBeenCalled()+ expect(scrollIntoView).toHaveBeenCalledOnce()+ })+beforeEach(() => {vi.clearAllMocks()vi.useFakeTimers()+ mocks.pathname = "/c/me/bots"mocks.isFounder = truemocks.billingReturn = nullmocks.hookOrder.length = 0diff --git a/src/web/src/components/community/bots/bot-list-controller.ts b/src/web/src/components/community/bots/bot-list-controller.tsindex 72a5de34b..96bef3edc 100644--- a/src/web/src/components/community/bots/bot-list-controller.ts+++ b/src/web/src/components/community/bots/bot-list-controller.ts@@ -7,7 +7,7 @@ import { useMutationState, useQueryClient } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"import { useCommunityViewSource } from "@/hooks/community/use-community-view-source"import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react"-import { useRouter, useSearchParams } from "next/navigation"+import { useCommunityModuleLocation } from "@/contexts/community/module-route"import { isPresenceOnline } from "@alook/shared"import { toast } from "sonner"import { toastApiError } from "@/lib/api/client"@@ -40,23 +40,24 @@ export function useBotListController(): BotListController {const client = useQueryClient()const protocol = useMemo(() => createStore({ scrolledFor: null as string | null, suppressedAudit: null as string | null, targetAudit: null as string | null, activityOpen: false, activityGeneration: 0 }), [])const patchProtocol = useCallback((patch: Partial<ReturnType<typeof protocol.get>>) => protocol.setState((state) => ({ ...state, ...patch })), [protocol])- const router = useRouter()const source = useCommunityViewSource("bot-list")const uiHandlers = useUiHandlers()- const searchParams = useSearchParams()+ const { router, searchParams, routeCommitted } = useCommunityModuleLocation()const botsQuery = useBots()const { bots } = botsQuery- const isLoading = botsQuery.isLoading || botsQuery.profilesPending === true+ const isLoading = botsQuery.isPending || botsQuery.profilesPending === trueconst botsResolved = botsQuery.data !== undefined && botsQuery.profilesPending !== trueconst [billingOpen, setBillingOpen] = useAtom(useCreateAtom(false))const viewPlan = () => {- const next = new URL(window.location.href)+ const next = new URL(routeCommitted ? window.location.href : `/c/me/bots?${searchParams.toString()}`, window.location.origin)next.searchParams.delete("billing")next.searchParams.set("settings", "billing")- window.history.pushState(null, "", `${next.pathname}${next.search}${next.hash}`)+ const href = `${next.pathname}${next.search}${next.hash}`+ if (routeCommitted) window.history.pushState(null, "", href)+ else router.push(href)}const machinesQuery = useMachines()- const { machines, isLoading: machinesLoading } = machinesQuery+ const { machines, isPending: machinesLoading } = machinesQueryconst machinesUnknown = machinesQuery.data?.observed === falseuseObservedRegion("bots", botsResolved, bots.length, { snapshot_source: botsQuery.data?.source ?? "unknown", target_coverage: botsResolved ? "covered" : "uncovered", wait_reason: botsQuery.profilesPending ? "identity" : botsResolved ? "none" : "entry" })const profilesByUserId = useCanonicalProfilesByUserId(bots.map((bot) => bot.id))@@ -226,7 +227,7 @@ export function useBotListController(): BotListController {patchProtocol({ targetAudit: targetAuditBotId })}, [patchProtocol, protocol, targetAuditBotId])useEffect(() => {- if (!targetMachineId || bots.length === 0) return+ if (!routeCommitted || !targetMachineId || bots.length === 0) returnsetCollapsedMachines((current) => {if (!current.has(targetMachineId)) return currentconst next = new Set(current)@@ -240,10 +241,10 @@ export function useBotListController(): BotListController {setHighlightId(targetMachineId)const timer = setTimeout(() => { try { assert(); setHighlightId(null) } catch {} }, 2000)return () => clearTimeout(timer)- }, [targetMachineId, bots.length, setCollapsedMachines, protocol, source, patchProtocol, setHighlightId])+ }, [routeCommitted, targetMachineId, bots.length, setCollapsedMachines, protocol, source, patchProtocol, setHighlightId])useEffect(() => {- if (!botsResolved) return+ if (!routeCommitted || !botsResolved) returnif (!targetAuditBotId) {patchProtocol({ suppressedAudit: null })if (activityOpen) {@@ -274,7 +275,7 @@ export function useBotListController(): BotListController {if (!activityOpen) {setActivityOpen(true)}- }, [activityBot, activityOpen, bots, botsResolved, patchProtocol, protocol, router, searchParams, setActivityBot, setActivityGeneration, setActivityOpen, targetAuditBotId])+ }, [routeCommitted, activityBot, activityOpen, bots, botsResolved, patchProtocol, protocol, router, searchParams, setActivityBot, setActivityGeneration, setActivityOpen, targetAuditBotId])const openActivity = (bot: BotSummary) => {uiHandlers.cancelPendingNavigation?.()diff --git a/src/web/src/components/community/bots/bot-list-facade.contract.dom.test.ts b/src/web/src/components/community/bots/bot-list-facade.contract.dom.test.tsindex 884a829a8..9fd6d6588 100644--- a/src/web/src/components/community/bots/bot-list-facade.contract.dom.test.ts+++ b/src/web/src/components/community/bots/bot-list-facade.contract.dom.test.ts@@ -66,7 +66,9 @@ describe("BotList facade contract", () => {it("keeps the production page and existing regression on the original path", () => {const page = source("src/app/c/me/bots/page.tsx")const existingTest = source("src/components/community/bots/bot-list-card.dom.test.ts")- expect(page).toContain('from "@/components/community/bots/bot-list"')+ const consumer = source("src/components/community/bots/me-bots-route.tsx")+ expect(page).toContain('export { default } from "@/components/community/bots/me-bots-route"')+ expect(consumer).toContain('from "@/components/community/bots/bot-list"')expect(existingTest).toContain('from "./bot-list"')expect(`${page}\n${existingTest}`).not.toMatch(/bot-list-(types|controller|view|machine-group|overlays)/,diff --git a/src/web/src/components/community/bots/me-bots-route.tsx b/src/web/src/components/community/bots/me-bots-route.tsxnew file mode 100644index 000000000..9f1414ba6--- /dev/null+++ b/src/web/src/components/community/bots/me-bots-route.tsx@@ -0,0 +1,13 @@+"use client"++import { BotList } from "@/components/community/bots/bot-list"+import { useUiHandlers } from "@/stores/community"++export default function MeBotsPage() {+ const uiHandlers = useUiHandlers()+ return (+ <BotList+ onBack={() => uiHandlers.goBackMobile?.()}+ />+ )+}diff --git a/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.ts b/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.tsindex 3d87ea3f8..5dba36d29 100644--- a/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.ts+++ b/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.ts@@ -20,7 +20,7 @@ describe("adaptive navigation cutover contracts", () => {expect(sidebar).toContain("onSelectForumThread?.(parentId, thread.id)")})- it("keeps the layout as the one channel subtree owner and removes the nested leaf", () => {+ it("shares one channel subtree consumer across the layout and shell and removes the nested leaf", () => {const layout = readSource("../../../app/c/channels/layout.tsx")const flatPage = readSource("../../../app/c/channels/[serverId]/[channelId]/page.tsx")const nestedPage = new URL(@@ -28,10 +28,11 @@ describe("adaptive navigation cutover contracts", () => {import.meta.url,)- expect(layout).toContain(- 'import { ChannelRoute } from "@/components/community/channels/channel-route"',- )- expect(layout).toContain("key={JSON.stringify([currentUser.id, serverId])}")+ const consumer = readSource("./server-conversation-route.tsx")+ const shell = readSource("../shell/community-module-route.tsx")+ expect(layout).toContain("<ServerConversationRoute")+ expect(shell).toContain("<ServerConversationRoute")+ expect(consumer).toContain("key={JSON.stringify([viewer.id, serverId])}")expect(layout).not.toContain("parentChannelId={routeParent" + "ChannelId}")expect(flatPage).toContain("return null")expect(flatPage).not.toContain("<ChannelRoute")diff --git a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.tsindex 931639304..d5380ea08 100644--- a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts+++ b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts@@ -597,8 +597,9 @@ describe("ChannelRoute message surface ownership", () => {mockRouteModel.currentChannelMeta!.id = "channel_3"Object.assign(mockRouteModel, { routeHydrated: true, routeLifecycle: "ready" })renderer.rerender(node())- expect(mockOpenerGate).not.toHaveBeenCalled()- expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()+ expect(mockOpenerGate).toHaveBeenLastCalledWith(expect.objectContaining({ childChannelId: "channel_3", lifecycle: "pending" }))+ expect(mockedUseChannelMessageFeed).toHaveBeenLastCalledWith(expect.objectContaining({channelId: "channel_3", anchorMessageId: "mC"}))+ mockOpenerGate.mockClear()mockPathname.value = "/c/channels/server_1/channel_3"mockSearchParams.value = "msg=mC&inboxThreadOpener=nonceC"renderer.rerender(node())@@ -635,8 +636,10 @@ describe("ChannelRoute message surface ownership", () => {mockedUseChannelMessageFeed.mockClear()mockOpenerGate.mockClear()renderer.rerender(node())- expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()- expect(mockOpenerGate).not.toHaveBeenCalled()+ expect(mockedUseChannelMessageFeed).toHaveBeenLastCalledWith(expect.objectContaining({channelId: "channel_2", anchorMessageId: "cancelled"}))+ expect(mockOpenerGate).toHaveBeenLastCalledWith(expect.objectContaining({childChannelId: "channel_2", lifecycle: "pending"}))+ expect(mockRouter.replace).not.toHaveBeenCalledWith(expect.stringContaining("cancelled"), expect.anything())+ mockedUseChannelMessageFeed.mockClear()mockNavigation.navigationPending = falsemockNavigation.pendingHref = nullmockCurrentChannelId.value = "channel_1"@@ -700,14 +703,31 @@ describe("ChannelRoute message surface ownership", () => {routeCommitted: false,}))expect(mockUseThreadSplitMode).toHaveBeenLastCalledWith({ breakpoint: "desktop", enabled: true, forceFullscreen: true })- expect(mockOpenerGate).not.toHaveBeenCalled()- expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()+ expect(mockOpenerGate).toHaveBeenLastCalledWith(expect.objectContaining({lifecycle: "pending"}))+ expect(mockedUseChannelMessageFeed).toHaveBeenLastCalledWith(expect.objectContaining({channelId: "channel_1", anchorMessageId: "new"}))expect(mockCommitLastCommunityRoute).not.toHaveBeenCalled()expect(mockRouter.replace).not.toHaveBeenCalled()expect(screen.getByTestId("community-thread-split")).toHaveAttribute("data-layout", "full")renderer.unmount()})+ it("shows the cached split parent without admitting member/subscription effects before commit", async () => {+ await observeSecondary()+ const { ThreadSplitParentSurface } = await vi.importActual<typeof import("./thread-split-parent-surface")>("./thread-split-parent-surface")+ configureThreadRoute()+ mockSplitMode.value = "split"+ mockedUseChannelMessageFeed.mockReturnValue(feed())+ mockSplitParentSurface.mockImplementation(props => React.createElement(ThreadSplitParentSurface, props as never))+ const node = (routeCommitted: boolean) => React.createElement(ChannelRoute, {serverParam: "server_1", channelId: "channel_1", routeCommitted})+ const renderer = render(node(false))+ expect(mockedUseChannelMessageFeed).toHaveBeenCalledWith(expect.objectContaining({channelId: "parent_1"}))+ expect(mockClaimSecondary).not.toHaveBeenCalled()+ expect(mockedUseChannelMemberViewModel).toHaveBeenCalledWith(expect.objectContaining({channelId: "parent_1", accessAllowed: false}))+ renderer.rerender(node(true))+ expect(mockClaimSecondary).toHaveBeenLastCalledWith(expect.anything(), expect.any(Symbol), "parent_1")+ expect(mockedUseChannelMemberViewModel).toHaveBeenCalledWith(expect.objectContaining({channelId: "parent_1", accessAllowed: true}))+ })+it("lets the real parent surface read independently and retires it when its own proof is lost", async () => {await observeSecondary()const { ThreadSplitParentSurface } = await vi.importActual<typeof import("./thread-split-parent-surface")>("./thread-split-parent-surface")@@ -1539,12 +1559,14 @@ describe("ChannelRoute message surface ownership", () => {fireEvent.click(screen.getByTestId("community-thread-split-fullscreen"))expect(mockUiHandlers.cancelPendingNavigation).toHaveBeenCalledOnce()expect(mockUiHandlers.cancelPendingNavigation.mock.invocationCallOrder[0])- .toBeLessThan(mockRouter.push.mock.invocationCallOrder[0]!)- expect(mockRouter.push).toHaveBeenCalledWith(+ .toBeLessThan(mockNavigation.push.mock.invocationCallOrder[0]!)+ expect(mockNavigation.push).toHaveBeenCalledWith("/c/channels/server_1/channel_1?keep=1&threadView=full",{ scroll: false },)+ expect(mockRouter.push).not.toHaveBeenCalled()+fireEvent.click(screen.getByTestId("community-thread-split-close"))expect(mockUiHandlers.goBackMobile).toHaveBeenCalledWith("/c/channels/server_1/parent_1")})diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsxindex 4b5e5118d..38d15a213 100644--- a/src/web/src/components/community/channels/channel-route.tsx+++ b/src/web/src/components/community/channels/channel-route.tsx@@ -80,7 +80,7 @@ function MobileChannelRoutes(props: ChannelRouteProps) {const previous = retained.current !== props.channelId ? retained.current : retained.previousconst backgroundId = mobileSeen || breakpoint === "mobile" ? parentId ?? (identity === undefined ? previous : null) : nullconst ids = backgroundId && backgroundId !== props.channelId ? [backgroundId, props.channelId] : [props.channelId]- return <>{ids.map(id => <ConversationActivityContext key={!mobileSeen && breakpoint !== "mobile" || id === initialId ? "initial" : id} value={id === props.channelId && (!mobileSeen && breakpoint !== "mobile" || props.routeCommitted !== false)}>+ return <>{ids.map(id => <ConversationActivityContext key={!mobileSeen && breakpoint !== "mobile" || id === initialId ? "initial" : id} value={id === props.channelId && props.routeCommitted !== false}><ChannelRouteLayer {...props} channelId={id} foreground={id === props.channelId} backgroundVisible={id === parentId} routeCommitted={id === props.channelId ? props.routeCommitted : true} targetHref={id === props.channelId ? props.targetHref : channelHref(props.serverParam, id)} /></ConversationActivityContext>)}</>}@@ -199,6 +199,7 @@ function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, rouonOpenChild: (id: string) => void}) {const active = useConversationActivity()+ const { navigation } = useCommunityRouteFrame()const router = useRouter()const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)const currentAnchorMessageId = anchorMessageId@@ -308,8 +309,8 @@ function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, rouuiHandlers.cancelPendingNavigation?.()const params = new URLSearchParams(searchParams.toString())params.set(THREAD_VIEW_PARAM, "full")- router.push(`${channelHref(serverParam, channelId)}?${params.toString()}`, { scroll: false })- }, [channelId, router, searchParams, serverParam, uiHandlers])+ navigation.push(`${channelHref(serverParam, channelId)}?${params.toString()}`, { scroll: false })+ }, [channelId, navigation, searchParams, serverParam, uiHandlers])const openProfile = useCallback<OpenProfile>((name, e, discriminator, userId) => {uiHandlers.openProfile?.(name, e, discriminator, userId)@@ -318,8 +319,8 @@ function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, rouconst channelReadReady =routeModel.routeLifecycle === "ready" &&routeModel.routeHydrated- const channelHydrated = !resolvingParent && (routeCommitted || resume) && channelReadReady &&- (!isForumPostChild || (!forumPostOpener.isLoading && !openerError))+ const channelHydrated = !resolvingParent && channelReadReady &&+ (!isForumPostChild || (Boolean(forumPostOpener.data) && !openerError))const clientReady = active && routeCommitted && channelHydrated && currentChannelId === channelIduseNativeSystemNotificationConversationDismissal(currentUser.id, {kind: "server",@@ -367,7 +368,7 @@ function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, rouparentChannelId={currentChannelMeta?.parentChannelId ?? null}parentMessageId={currentChannelMeta?.parentMessageId ?? null}parentIsForum={isForumPostChild}- routeLifecycle={routeModel.routeLifecycle}+ routeLifecycle={routeCommitted ? routeModel.routeLifecycle : "pending"}childCreatorId={currentChannelMeta?.creatorId}canRenameThread={canManageServer(myRole)}onNavigateParent={navigateParent}diff --git a/src/web/src/components/community/channels/channel-sidebar.navigation.dom.test.tsx b/src/web/src/components/community/channels/channel-sidebar.navigation.dom.test.tsxindex 9f9c3a072..f4ca678a7 100644--- a/src/web/src/components/community/channels/channel-sidebar.navigation.dom.test.tsx+++ b/src/web/src/components/community/channels/channel-sidebar.navigation.dom.test.tsx@@ -1,5 +1,5 @@import { describe, expect, it, vi } from "vitest"-import { act, fireEvent, render, setupUser } from "@/test/react-dom-harness"+import { act, fireEvent, render, setupUser, waitFor } from "@/test/react-dom-harness"import { tid } from "@/lib/community/testids"import { ChannelSidebar } from "./channel-sidebar"import { useChannelTree } from "./use-channel-tree"@@ -86,5 +86,30 @@ describe("real sortable channel navigation surface", () => {await user.keyboard("{Enter}")expect(onPick.mock.calls).toEqual([["two"], ["two"]])expect(onReorder).not.toHaveBeenCalled()+ for (const element of [view.getByTestId(tid.channelSidebarScroll), anchor, ...(grouped ? [view.getByText("Group")] : [])]) {+ fireEvent.contextMenu(element, { button: 2 })+ expect(view.queryByRole("menu")).toBeNull()+ }})})++it.each(["list", "row", "category"] as const)("retires an open %s menu when actions become unavailable without reviving it or replacing content", async kind => {+ const onPick = vi.fn()+ const view = render(<Sidebar onPick={onPick} grouped />)+ const scroll = view.getByTestId(tid.channelSidebarScroll)+ const row = view.getByTestId(tid.channelRow("two"))+ const category = view.getByText("Group")+ const trigger = kind === "list" ? scroll : kind === "row" ? row : category.closest('[data-slot="context-menu-trigger"]')!+ fireEvent.contextMenu(trigger, { button: 2 })+ expect(await view.findByRole("menu")).toBeVisible()+ view.rerender(<Sidebar onPick={onPick} isAdmin={false} grouped />)+ expect(view.queryByRole("menu")).toBeNull()+ view.rerender(<Sidebar onPick={onPick} grouped />)+ const closing = view.queryByRole("menu")+ if (closing) expect(closing).toHaveAttribute("data-closed")+ await waitFor(() => expect(view.queryByRole("menu")).toBeNull())+ expect(view.getByTestId(tid.channelSidebarScroll)).toBe(scroll)+ expect(view.getByTestId(tid.channelRow("two"))).toBe(row)+ expect(view.getByText("Group")).toBe(category)+ expect(onPick).not.toHaveBeenCalled()+})diff --git a/src/web/src/components/community/channels/channel-sidebar.tsx b/src/web/src/components/community/channels/channel-sidebar.tsxindex 58db7f5ba..a9d843980 100644--- a/src/web/src/components/community/channels/channel-sidebar.tsx+++ b/src/web/src/components/community/channels/channel-sidebar.tsx@@ -1,10 +1,11 @@"use client"+import type { ContextMenu as ContextMenuPrimitive } from "@base-ui/react/context-menu"import { useAtom, useCreateAtom } from "@tanstack/react-store";import { OfficialServerBadge } from "../official-server-badge"import { CommunityNavigationLink } from "../shell/community-navigation-link"import { channelHref } from "@/lib/community/community-route"-import { Fragment, memo, useRef, type MouseEvent } from "react"+import { Fragment, memo, useEffect, useRef, type MouseEvent } from "react"import { Settings, Users, Link2, Bell, ChevronDown, UserPlus } from "lucide-react"import {DndContext, KeyboardSensor, MouseSensor, TouchSensor, closestCenter, useSensor, useSensors, useDndContext,@@ -97,6 +98,13 @@ export const ChannelSidebar = memo(function ChannelSidebar({forumThreadsByParent = {}, activeThreadId, onSelectForumThread,}: ChannelSidebarProps) {const { collapsed, catOrder, order, catNames, catPrivate, catPending, toggleCat, onDragOver, onDragEnd: treeDragEnd } = tree+ const menuActionsRef = useRef<ContextMenuPrimitive.Root.Actions | null>(null)+ useEffect(() => {+ if (!isAdmin) {+ menuActionsRef.current?.close()+ menuActionsRef.current?.unmount()+ }+ }, [isAdmin])// Category the dragged channel started in — captured at drag start, because// `onDragOver` mutates `order` mid-drag so by drop time it already reflects// the destination.@@ -351,10 +359,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({)}</header>)}- {/* right-click anywhere in the list (incl. empty space) → create channel / category.- Non-admins have no actions, so the menu is skipped entirely (no empty popover). */}- {isAdmin ? (- <ContextMenu>+ <ContextMenu disabled={!isAdmin} actionsRef={menuActionsRef}><ContextMenuTriggerrender={(<div@@ -365,19 +370,13 @@ export const ChannelSidebar = memo(function ChannelSidebar({>{channelTree}</ContextMenuTrigger>- <ContextMenuContent className="w-48">- <ContextMenuItem onClick={() => requestCreateChannel(noneCatId)}>Create channel</ContextMenuItem>- <ContextMenuItem onClick={() => setDialog({ kind: "create-category" })}>Create category</ContextMenuItem>- </ContextMenuContent>+ {isAdmin && (+ <ContextMenuContent className="w-48">+ <ContextMenuItem onClick={() => requestCreateChannel(noneCatId)}>Create channel</ContextMenuItem>+ <ContextMenuItem onClick={() => setDialog({ kind: "create-category" })}>Create category</ContextMenuItem>+ </ContextMenuContent>+ )}</ContextMenu>- ) : (- <div- data-testid={tid.channelSidebarScroll}- className="min-h-0 flex-1 overflow-y-auto px-2 py-4 thin-scrollbar scrollbar-none"- >- {channelTree}- </div>- )}{dialog?.kind === "create-channel" && (<CreateChannelDialogdiff --git a/src/web/src/components/community/channels/conversation-resolution-error-frame.tsx b/src/web/src/components/community/channels/conversation-resolution-error-frame.tsxindex 05d6022ab..35bd899d5 100644--- a/src/web/src/components/community/channels/conversation-resolution-error-frame.tsx+++ b/src/web/src/components/community/channels/conversation-resolution-error-frame.tsx@@ -7,16 +7,18 @@ export function ConversationResolutionErrorFrame({retrying,onRetry,as: Element = "main",+ title = "Couldn't verify this conversation",}: {retrying: booleanonRetry: () => voidas?: "main" | "div"+ title?: string}) {return (<Element className="flex min-h-0 min-w-0 flex-1 flex-col items-center justify-center gap-4 p-4 text-center"><div role="alert" className="flex flex-col items-center gap-2"><AlertCircle className="size-5 text-muted-foreground" aria-hidden />- <p className="text-sm font-medium">Couldn't verify this conversation</p>+ <p className="text-sm font-medium">{title}</p><p className="text-xs text-muted-foreground">Check your connection and try again.</p></div><Button variant="outline" className="h-11 px-4 sm:h-9" onClick={onRetry} disabled={retrying}>diff --git a/src/web/src/components/community/channels/dm-sidebar.tsx b/src/web/src/components/community/channels/dm-sidebar.tsxindex 241cdf16e..24edfd5aa 100644--- a/src/web/src/components/community/channels/dm-sidebar.tsx+++ b/src/web/src/components/community/channels/dm-sidebar.tsx@@ -4,6 +4,7 @@ import { CommunityNavigationLink } from "../shell/community-navigation-link"import { dmHref } from "@/lib/community/community-route"import { memo } from "react"import { Users, Ban, Monitor, Bot } from "lucide-react"+import { ConversationResolutionErrorFrame } from "./conversation-resolution-error-frame"import { Avatar } from "../avatar"import { Skeleton } from "@/components/ui/skeleton"import { tid } from "@/lib/community/testids"@@ -15,11 +16,13 @@ export const DmSidebar = memo(function DmSidebar({dms, activeDm, blockedUserIds, loading, onPickDm, onShowFriends, onShowMachines, onShowBots,friendsActive, machinesActive, botsActive,friendRequestCount = 0,+ loadError,}: {dms: DM[]activeDm: string | nullblockedUserIds?: Set<string>loading?: boolean+ loadError?: { retrying: boolean; onRetry: () => void }onPickDm: (id: string) => voidonShowFriends: () => voidonShowMachines?: () => void@@ -93,7 +96,9 @@ export const DmSidebar = memo(function DmSidebar({<div className="mb-2 truncate px-2 text-xs font-semibold text-muted-foreground">Direct Messages</div>- {loading && dms.length === 0 ? (+ {loadError ? (+ <ConversationResolutionErrorFrame as="div" title="Couldn't load direct messages" {...loadError} />+ ) : loading && dms.length === 0 ? (<DmRowsSkeleton />) : dms.length === 0 ? (<p className="px-2 py-4 text-center text-xs text-muted-foreground">Your direct messages will appear here.</p>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.tsindex 4a9506ea5..0e2957a86 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@@ -156,3 +156,14 @@ describe("ForumSurface generic read-row adapter", () => {rendered.unmount()})})+++it("passes native pending state to the forum view while restore has not started fetching", () => {+ mocks.feed.isPending = true+ mocks.feed.isLoading = false+ mocks.feed.posts = []+ mocks.feed.isError = false+ mocks.feed.error = null+ render(React.createElement(ForumSurface, { serverId: "server", forumChannelId: "forum", members: [], onOpenPost: () => {} }))+ expect(ForumView).toHaveBeenLastCalledWith(expect.objectContaining({ loading: true }), undefined)+})diff --git a/src/web/src/components/community/channels/forum-surface.readiness.dom.test.tsx b/src/web/src/components/community/channels/forum-surface.readiness.dom.test.tsxnew file mode 100644index 000000000..00c492fb3--- /dev/null+++ b/src/web/src/components/community/channels/forum-surface.readiness.dom.test.tsx@@ -0,0 +1,24 @@+import { IsRestoringProvider } from "@tanstack/react-query"+import { beforeEach, expect, it, vi } from "vitest"+import { render } 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 { ForumSurface } from "./forum-surface"++const load = vi.hoisted(() => vi.fn())+vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: load }))+vi.mock("@/hooks/community/use-channel-panels", () => ({ useForumTags: () => ({ data: { tags: [] }, isSuccess: true }) }))+vi.mock("@/hooks/community/use-read-observer", () => ({ useTimelineReadObserver: () => {} }))+vi.mock("./forum-view", () => ({ ForumView: ({ loading, posts }: { loading: boolean; posts: Array<{ name: string }> }) => <main>{loading ? "Loading posts" : posts.length ? posts.map(post => post.name).join(",") : "No posts"}</main> }))+beforeEach(() => { load.mockReset(); load.mockImplementation(() => new Promise(() => {})) })+it.each([false, true])("keeps absent forum data loading and renders qualified cached empty (cached=%s)", async cached => {+ const { client, registry } = await createCommunityQueryOwner()+ if (cached) await seedConversationEntry(client, forumConversationEntryFixture("c1", "s1", true))+ const view = render(<CommunityTestProvider client={client} registry={registry}>+ <IsRestoringProvider value><ForumSurface serverId="s1" forumChannelId="c1" members={[]} onOpenPost={() => {}} /></IsRestoringProvider>+ </CommunityTestProvider>)+ expect(view.getByText(cached ? "No posts" : "Loading posts")).toBeVisible()+ expect(view.queryByText(cached ? "Loading posts" : "No posts")).toBeNull()+ expect(load).not.toHaveBeenCalled()+})diff --git a/src/web/src/components/community/channels/forum-surface.tsx b/src/web/src/components/community/channels/forum-surface.tsxindex c40e454c2..d7b144837 100644--- a/src/web/src/components/community/channels/forum-surface.tsx+++ b/src/web/src/components/community/channels/forum-surface.tsx@@ -85,7 +85,7 @@ export function ForumSurface({ serverId, forumChannelId, ...props }: {{...props}posts={feed.posts}observation={feed.observation}- loading={feed.isLoading}+ loading={feed.isPending}tag={feed.tag}availableTags={feed.availableTags}onTagChange={feed.selectTag}diff --git a/src/web/src/components/community/channels/server-conversation-route.tsx b/src/web/src/components/community/channels/server-conversation-route.tsxnew file mode 100644index 000000000..b47838d1e--- /dev/null+++ b/src/web/src/components/community/channels/server-conversation-route.tsx@@ -0,0 +1,29 @@+"use client"++import type { ReactNode } from "react"+import { useQueryClient } from "@tanstack/react-query"+import { useSelector } from "@tanstack/react-store"+import { useCurrentUser } from "@/contexts/community/current-user"+import { getCommunityRuntime } from "@/stores/community/runtime"+import { useCommunityRouteFrame } from "@/components/community/shell/community-route-context"+import { CommunityPendingFrame } from "@/components/community/shell/community-pending-frame"+import { ChannelRoute } from "./channel-route"++export function ServerConversationRoute({ serverId, serverParam, channelId, href, routeCommitted, children }: {+ serverId: string+ serverParam: string+ channelId: string | null+ href: string+ routeCommitted: boolean+ children?: ReactNode+}) {+ const client = useQueryClient()+ const viewer = useCurrentUser()+ const { ownerDeleteRouteScope } = useCommunityRouteFrame()+ const protectedRoute = useSelector(getCommunityRuntime(client).serverEject, state =>+ state.transactions.has(serverId) || Boolean(ownerDeleteRouteScope?.serverId === serverId+ && state.tombstones.get(ownerDeleteRouteScope.token) === serverId))+ if (protectedRoute) return <CommunityPendingFrame href={href} />+ return channelId ? <ChannelRoute key={JSON.stringify([viewer.id, serverId])}+ serverParam={serverParam} channelId={channelId} targetHref={href} routeCommitted={routeCommitted} /> : children+}diff --git a/src/web/src/components/community/channels/sortable-category.tsx b/src/web/src/components/community/channels/sortable-category.tsxindex d4d3bf76b..fdc68a7c2 100644--- a/src/web/src/components/community/channels/sortable-category.tsx+++ b/src/web/src/components/community/channels/sortable-category.tsx@@ -1,5 +1,7 @@"use client"+import type { ContextMenu as ContextMenuPrimitive } from "@base-ui/react/context-menu"+import { useEffect, useRef } from "react"import { useAtom, useCreateAtom } from "@tanstack/react-store";import type React from "react"@@ -10,8 +12,6 @@ import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, Cimport { ConfirmDialog } from "@/components/ui/confirm-dialog"import { DropLine } from "../drop-line"-// True when the category header has at least one right-click action. With none, we skip-// the ContextMenu wrapper so a non-admin doesn't get an empty popover strip.export function hasCategoryMenu(h: { onAddChannel?: () => void; onSettings?: () => void; onDelete?: () => void }) {return !!(h.onAddChannel || h.onSettings || h.onDelete)}@@ -38,8 +38,6 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChanconst style = { transform: CSS.Transform.toString(transform), transition, opacity: isDragging ? 0.4 : 1, zIndex: isDragging ? 10 : undefined }const showLine = isOver && !isDraggingconst lineSide: "top" | "bottom" = activeIndex !== -1 && activeIndex < index ? "bottom" : "top"- // The header div is the drag surface; it renders bare (no ContextMenu) when there are no- // actions, so share its props/children across both branches to avoid drift.const headerProps = {ref: setActivatorNodeRef,...(canReorder ? attributes : { role: "button", tabIndex: 0 }),@@ -80,15 +78,22 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChan<ChevronDown className={`size-3 shrink-0 transition-transform ${open ? "" : "-rotate-90"}`} /></>)+ const hasMenu = hasCategoryMenu({ onAddChannel, onSettings, onDelete })+ const menuActionsRef = useRef<ContextMenuPrimitive.Root.Actions | null>(null)+ useEffect(() => {+ if (!hasMenu) {+ menuActionsRef.current?.close()+ menuActionsRef.current?.unmount()+ }+ }, [hasMenu])return (<div ref={setNodeRef} style={style} className={`relative mb-4 ${pending ? "opacity-60" : ""}`}>{showLine && <DropLine side={lineSide} />}- {hasCategoryMenu({ onAddChannel, onSettings, onDelete }) ? (- <ContextMenu>+ <ContextMenu disabled={!hasMenu} actionsRef={menuActionsRef}><ContextMenuTrigger render={<div {...headerProps} />}>{headerInner}</ContextMenuTrigger>- <ContextMenuContent className="w-48">+ {hasMenu && <ContextMenuContent className="w-48"><div className="truncate px-2 py-2 text-xs font-semibold text-muted-foreground">{name}</div>{onAddChannel && <ContextMenuItem onClick={onAddChannel}><Plus className="size-4" /> Create channel</ContextMenuItem>}{onSettings && <ContextMenuItem onClick={onSettings}><Settings className="size-4" /> Category settings</ContextMenuItem>}@@ -101,11 +106,8 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChan><Trash2 className="size-4" /> Delete category</ContextMenuItem></>)}- </ContextMenuContent>+ </ContextMenuContent>}</ContextMenu>- ) : (- <div {...headerProps}>{headerInner}</div>- )}{open && (<div className={`rounded-md transition-colors ${isOver ? "bg-accent/40" : ""}`}>{children}diff --git a/src/web/src/components/community/channels/sortable-channel.tsx b/src/web/src/components/community/channels/sortable-channel.tsxindex c30668f8b..9f9e174ea 100644--- a/src/web/src/components/community/channels/sortable-channel.tsx+++ b/src/web/src/components/community/channels/sortable-channel.tsx@@ -1,6 +1,8 @@"use client"+import type { ContextMenu as ContextMenuPrimitive } from "@base-ui/react/context-menu"import { CommunityNavigationLink } from "../shell/community-navigation-link"+import { useEffect, useRef } from "react"import { useAtom, useCreateAtom } from "@tanstack/react-store";import { BellOff, Loader2, Pencil, Trash2, Users } from "lucide-react"@@ -14,8 +16,6 @@ import { tid } from "@/lib/community/testids"import type { Channel } from "@/lib/community/models/navigation"import { selectUnreadPresentation } from "@/hooks/community/unread-presentation"-// True when the row has at least one right-click action. With none, we skip the-// ContextMenu wrapper entirely so a non-manager doesn't get an empty popover strip.export function hasChannelMenu(h: { onEdit?: () => void; onManageMembers?: () => void; onDelete?: () => void }) {return !!(h.onEdit || h.onManageMembers || h.onDelete)}@@ -100,12 +100,19 @@ export function SortableChannel({ ch, href, active, onClick, onEdit, onDelete, o) : (<div {...rowProps} onClick={onClick}>{content}</div>)- if (!hasChannelMenu({ onEdit, onManageMembers, onDelete })) return row+ const hasMenu = hasChannelMenu({ onEdit, onManageMembers, onDelete })+ const menuActionsRef = useRef<ContextMenuPrimitive.Root.Actions | null>(null)+ useEffect(() => {+ if (!hasMenu) {+ menuActionsRef.current?.close()+ menuActionsRef.current?.unmount()+ }+ }, [hasMenu])return (<>- <ContextMenu>+ <ContextMenu disabled={!hasMenu} actionsRef={menuActionsRef}><ContextMenuTrigger render={row} />- <ContextMenuContent className="w-48">+ {hasMenu && <ContextMenuContent className="w-48"><div className="truncate px-2 py-2 text-xs font-semibold text-muted-foreground">/{ch.name}</div>{onEdit && <ContextMenuItem onClick={onEdit}><Pencil className="size-4" /> Edit channel</ContextMenuItem>}{onManageMembers && <ContextMenuItem onClick={onManageMembers}><Users className="size-4" /> Manage members</ContextMenuItem>}@@ -118,7 +125,7 @@ export function SortableChannel({ ch, href, active, onClick, onEdit, onDelete, o><Trash2 className="size-4" /> Delete channel</ContextMenuItem></>)}- </ContextMenuContent>+ </ContextMenuContent>}</ContextMenu>{onDelete && (<ConfirmDialogdiff --git a/src/web/src/components/community/channels/text-channel-surface.tsx b/src/web/src/components/community/channels/text-channel-surface.tsxindex 8a1be8af9..55236feb1 100644--- a/src/web/src/components/community/channels/text-channel-surface.tsx+++ b/src/web/src/components/community/channels/text-channel-surface.tsx@@ -219,6 +219,7 @@ export function TextChannelSurface({open={controller.contextTarget !== null}onOpenChange={(open) => { if (!open) controller.setContextTarget(null) }}channelId={controller.contextTarget?.channelId ?? channelId}+ serverId={controller.contextTarget?.serverId ?? serverId}channelLabel={controller.contextTarget?.label}targetSeq={controller.contextTarget?.seq ?? null}pinnedIds={controller.pinnedIds}diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsxindex 12c4acdc7..1d19a1878 100644--- a/src/web/src/components/community/channels/thread-channel-surface.tsx+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx@@ -3,7 +3,7 @@import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useCallback, useEffect, type ComponentProps, type ReactNode } from "react"-import { useRouter } from "next/navigation"+import { useCommunityRouter } from "@/contexts/community/module-route"import { toastApiError, apiFetch } from "@/lib/api/client"import { useBreakpoint } from "@/hooks/use-mobile"import { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"@@ -99,7 +99,7 @@ export function ThreadChannelSurface({splitActions?: { onFullscreen: () => void; onClose: () => void }layoutPending?: boolean}) {- const router = useRouter()+ const router = useCommunityRouter()const breakpoint = useBreakpoint()const [rightPanel, setRightPanel] = useAtom(useCreateAtom<RightPanel>(null))const [localName, setLocalName] = useAtom(useCreateAtom<string | null>(null))@@ -331,6 +331,7 @@ export function ThreadChannelSurface({open={controller.contextTarget !== null}onOpenChange={(open) => { if (!open) controller.setContextTarget(null) }}channelId={controller.contextTarget?.channelId ?? channelId}+ serverId={controller.contextTarget?.serverId ?? serverId}channelLabel={controller.contextTarget?.label}targetSeq={controller.contextTarget?.seq ?? null}pinnedIds={controller.pinnedIds}diff --git a/src/web/src/components/community/channels/thread-split-parent-surface.tsx b/src/web/src/components/community/channels/thread-split-parent-surface.tsxindex d64772f54..7d480937c 100644--- a/src/web/src/components/community/channels/thread-split-parent-surface.tsx+++ b/src/web/src/components/community/channels/thread-split-parent-surface.tsx@@ -1,5 +1,6 @@"use client"+import { useConversationActivity } from "@/contexts/community/conversation-activity"import { useLayoutEffect, useState, type ComponentProps } from "react"import { canManageServer, isForum, USE_SERVER_DEFAULT } from "@alook/shared"import { toastApiError } from "@/lib/api/client"@@ -46,6 +47,7 @@ export function ThreadSplitParentSurface({onOpenProfile: OpenProfileonIdentity: (parentId: string, confirmed: boolean) => void}) {+ const active = useConversationActivity()const metadata = useChannelMetadata(serverId, hint.id)const channel = metadata.data ? { ...hint, ...metadata.data } : hintconst runtime = useCommunityRuntime()@@ -55,12 +57,12 @@ export function ThreadSplitParentSurface({return () => onIdentity(channel.id, false)}, [channel.id, metadata.identityKnown, onIdentity])useLayoutEffect(() => {- if (metadata.canRead) communityWsClaimSecondaryChannel(runtime, subscriptionOwner, channel.id)+ if (active && metadata.canRead) communityWsClaimSecondaryChannel(runtime, subscriptionOwner, channel.id)else communityWsReleaseSecondaryChannel(runtime, subscriptionOwner)return () => {communityWsReleaseSecondaryChannel(runtime, subscriptionOwner)}- }, [channel.id, metadata.canRead, runtime, subscriptionOwner])+ }, [active, channel.id, metadata.canRead, runtime, subscriptionOwner])const members = useChannelMemberViewModel({serverId,channelId: channel.id,@@ -71,7 +73,7 @@ export function ThreadSplitParentSurface({isChildChannel: false,isNotifyUnit: false,currentUser: viewer,- accessAllowed: metadata.canRead,+ accessAllowed: active && metadata.canRead,})const notifs = useNotificationSettings()const { mutate: setChannelNotif } = useSetChannelNotif()diff --git a/src/web/src/components/community/machines/machine-list.dom.test.ts b/src/web/src/components/community/machines/machine-list.dom.test.tsindex 1198ad578..411a780d4 100644--- a/src/web/src/components/community/machines/machine-list.dom.test.ts+++ b/src/web/src/components/community/machines/machine-list.dom.test.ts@@ -1,8 +1,12 @@import React from "react"+import { useCommunityNavigationController } from "@/components/community/shell/use-community-navigation-controller"+import { CommunityRouteContext } from "@/contexts/community/route-frame"+import { normalizeCommunityHref } from "@/lib/community/community-route"import { renderToString } from "react-dom/server"import { render as renderNative } from "@/test/react-dom-harness"import { CommunityTestProvider } from "@/test/community-owner-fixture"import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { CommunityModuleRouteContext } from "@/contexts/community/module-route"import MeMachinesPage from "@/app/c/me/machines/page"import { beforeEach, describe, expect, it, vi } from "vitest"import { act, fireEvent, waitFor } from "@/test/react-dom-harness"@@ -10,6 +14,9 @@ import { renderCommunity as render } from "@/test/community-owner-harness"const mocks = vi.hoisted(() => ({apiFetch: vi.fn(),+ replace: vi.fn(),+ push: vi.fn(),+ pathname: "/c/me/machines",goBackMobile: vi.fn(),query: vi.fn(),toastSuccess: vi.fn(),@@ -59,7 +66,8 @@ vi.mock("@/components/ui/alert-dialog", () => ({}))vi.mock("next/navigation", () => ({- useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),+ useRouter: () => ({ push: mocks.push, replace: mocks.replace }),+ usePathname: () => mocks.pathname,useSearchParams: () => new URLSearchParams(),}))@@ -91,7 +99,7 @@ vi.mock("./pair-machine-sheet", () => ({ PairMachineSheet: ({ open, onLimitReachvi.mock("@/components/community/onboarding-tiles/connect-tile", () => ({ ConnectTile: () => null }))vi.mock("@/hooks/community/use-machines", async (importOriginal) => ({ ...await importOriginal<typeof import("@/hooks/community/use-machines")>(),machinesQueryFn: mocks.query,- useMachines: () => ({ machines: mocks.machines.current, isLoading: mocks.machinesLoading.current, isError: mocks.machinesError.current, isFetching: false, capacityPending: mocks.capacityPending.current, refetch: mocks.retryMachines, data: mocks.machinesError.current ? undefined : { machineCapacity: mocks.capacityPending.current ? undefined : mocks.capacity.current } }),+ useMachines: () => ({ machines: mocks.machines.current, isLoading: mocks.machinesLoading.current, isPending: mocks.machinesLoading.current, isError: mocks.machinesError.current, isFetching: false, capacityPending: mocks.capacityPending.current, refetch: mocks.retryMachines, data: mocks.machinesError.current ? undefined : { machineCapacity: mocks.capacityPending.current ? undefined : mocks.capacity.current } }),}))vi.mock("@/hooks/community/use-bots", () => ({ useBots: () => ({ bots: [] }) }))vi.mock("@/stores/community", async (importOriginal) => ({ ...await importOriginal<typeof import("@/stores/community")>(),@@ -138,6 +146,21 @@ function withExactClass(container: HTMLElement, className: string): HTMLElement[}describe("SSR mobile Back footprint", () => {+ it("keeps reconnect and URL cleanup dormant until the target is committed", () => {+ mocks.machines.current = [machine()]+ mocks.machinesLoading.current = false+ mocks.machinesError.current = false+ mocks.capacityPending.current = false+ mocks.replace.mockClear()+ const node = (routeCommitted: boolean) => React.createElement(CommunityModuleRouteContext, {value: {href: "/c/me/machines?reconnect=machine-1&keep=1", routeCommitted}}, React.createElement(MeMachinesPage))+ const view = render(node(false))+ expect(view.queryByTestId("test-pair-sheet")).toBeNull()+ expect(mocks.replace).not.toHaveBeenCalled()+ view.rerender(node(true))+ expect(view.getByTestId("test-pair-sheet")).toBeVisible()+ expect(mocks.replace).toHaveBeenCalledExactlyOnceWith("/c/me/machines?keep=1")+ })+it.each([false, true])("keeps the existing mobile header through hydrate with loading=%s", async loading => {mocks.machines.current = []mocks.machinesLoading.current = loading@@ -188,6 +211,27 @@ describe("machine daemon update UI", () => {mocks.onboardingState.current = "done"})+ it("publishes a pending View plan click through the latest navigation owner", () => {+ mocks.pathname = "/c/channels/source/channel"+ mocks.machines.current = [machine({status: "offline"})]+ mocks.capacity.current = {plan: {id: "free", displayName: "Free"}, isFounder: false, limit: 1, ownedCount: 1, onlineCount: 0}+ const frame = {...normalizeCommunityHref(mocks.pathname), revision: 0}+ let navigation!: ReturnType<typeof useCommunityNavigationController>+ function Scenario() {+ const currentNavigation = useCommunityNavigationController(frame)+ React.useLayoutEffect(() => { navigation = currentNavigation }, [currentNavigation])+ return React.createElement(CommunityRouteContext, {value: {frame, navigation: currentNavigation, breakpoint: "desktop", ownerDeleteRouteScope: undefined}},+ React.createElement(CommunityModuleRouteContext, {value: {href: currentNavigation.pendingHref ?? "/c/me/machines?keep=1", routeCommitted: false}}, React.createElement(MachineList)))+ }+ const view = render(React.createElement(Scenario))+ act(() => navigation.pushImmediate("/c/me/machines?keep=1"))+ const oldIntent = navigation.captureIntent()+ fireEvent.click(view.getByRole("button", {name: "Connect a machine"}))+ fireEvent.click(view.getByRole("button", {name: "View plan"}))+ expect(navigation.pendingHref).toBe("/c/me/machines?keep=1&settings=billing")+ expect(oldIntent()).toBe(false)+ })+it("shows Retry when the list is unknown rather than claiming no machines exist", () => {mocks.machinesError.current = trueconst view = render(React.createElement(MachineList))diff --git a/src/web/src/components/community/machines/machine-list.readiness.dom.test.tsx b/src/web/src/components/community/machines/machine-list.readiness.dom.test.tsxnew file mode 100644index 000000000..d7b2d8f4f--- /dev/null+++ b/src/web/src/components/community/machines/machine-list.readiness.dom.test.tsx@@ -0,0 +1,74 @@+import React from "react"+import { IsRestoringProvider } from "@tanstack/react-query"+import { beforeEach, expect, it, vi } from "vitest"+import { act, render, waitFor } from "@/test/react-dom-harness"+import { CommunityTestProvider } from "@/test/community-owner-fixture"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { CommunityModuleRouteContext } from "@/contexts/community/module-route"+import { communityKeys } from "@/lib/query-keys"+import { MachineList } from "./machine-list"++const load = vi.hoisted(() => vi.fn())+vi.mock("@/lib/api/client", () => ({ apiFetch: load, getErrorMessage: () => "Unavailable" }))+vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn(), replace: vi.fn() }), useSearchParams: () => new URLSearchParams() }))+vi.mock("@/hooks/community/use-bots", () => ({ useBots: () => ({ bots: [] }) }))+vi.mock("./pair-machine-sheet", () => ({ PairMachineSheet: () => null }))+vi.mock("./guide-me-avatar-motion", () => ({ GuideMeAvatarMotion: () => null }))+vi.mock("@/lib/community-onboarding", () => ({ useCommunityOnboarding: () => "done", startCommunityOnboarding: vi.fn() }))+vi.mock("@/lib/utils", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/utils")>(), getAppMode: () => "dev" }))++beforeEach(() => { load.mockReset() })++function deferred<T>() {+ let resolve!: (value: T) => void+ const promise = new Promise<T>(done => { resolve = done })+ return { promise, resolve }+}++it.each([false, true])("keeps the real empty target unknown until its list is available (restoring=%s)", async restoring => {+ const { client } = await createCommunityQueryOwner()+ const primary = deferred<{ machines: [] }>()+ const observations = deferred<{ quotas: []; machineCapacity: { plan: { id: string; displayName: string }; isFounder: boolean; limit: number; ownedCount: number; onlineCount: number } }>()+ load.mockImplementation((url: string) => url.endsWith("view=list") ? primary.promise : observations.promise)+ const node = (restore: boolean) => <CommunityTestProvider client={client}>+ <IsRestoringProvider value={restore}>+ <CommunityModuleRouteContext value={{ href: "/c/me/machines", routeCommitted: false }}><MachineList /></CommunityModuleRouteContext>+ </IsRestoringProvider>+ </CommunityTestProvider>+ const view = render(node(restoring))+ expect(view.queryByText("No machines yet")).toBeNull()+ expect(view.queryByRole("button", { name: "Connect a machine" })).toBeNull()+ expect(view.container.querySelector('[data-slot="community-machines-heading"] [data-slot="skeleton"]')).not.toBeNull()+ view.rerender(node(false))+ await waitFor(() => expect(load).toHaveBeenCalledWith("/api/community/machines?view=list", expect.anything()))+ expect(client.getQueryState(communityKeys.machines())).toMatchObject({ status: "pending", fetchStatus: "fetching", data: undefined })+ expect(view.queryByText("No machines yet")).toBeNull()+ await act(async () => { primary.resolve({ machines: [] }) })+ expect(await view.findByText("No machines yet")).toBeVisible()+ expect(view.getByRole("button", { name: "Connect a machine" })).toBeDisabled()+ await act(async () => { observations.resolve({ quotas: [], machineCapacity: { plan: { id: "free", displayName: "Free" }, isFounder: false, limit: 1, ownedCount: 0, onlineCount: 0 } }) })+ await waitFor(() => expect(view.getByRole("button", { name: "Connect a machine" })).toBeEnabled())+})++it.each([false, true])("shows a complete cached empty list while its capacity remains unknown (restoring=%s)", async restoring => {+ const { client } = await createCommunityQueryOwner()+ const primary = deferred<{ machines: [] }>()+ const observations = deferred<{ quotas: [] }>()+ client.setQueryData(communityKeys.machines(), { machines: [], complete: true, observed: false, source: "restored_idb" })+ load.mockImplementation((url: string) => url.endsWith("view=list") ? primary.promise : observations.promise)+ const node = (restore: boolean) => <CommunityTestProvider client={client}>+ <IsRestoringProvider value={restore}>+ <CommunityModuleRouteContext value={{ href: "/c/me/machines", routeCommitted: false }}><MachineList /></CommunityModuleRouteContext>+ </IsRestoringProvider>+ </CommunityTestProvider>+ const view = render(node(restoring))+ const empty = view.getByText("No machines yet")+ expect(empty).toBeVisible()+ expect(view.getByRole("button", { name: "Connect a machine" })).toBeDisabled()+ expect(view.getByRole("button", { name: "Machine usage loading" })).toBeDisabled()+ view.rerender(node(false))+ await waitFor(() => expect(load).toHaveBeenCalledWith("/api/community/machines?view=list", expect.anything()))+ expect(view.getByText("No machines yet")).toBe(empty)+ await act(async () => { primary.resolve({ machines: [] }); observations.resolve({ quotas: [] }) })+ expect(view.getByText("No machines yet")).toBe(empty)+})diff --git a/src/web/src/components/community/machines/machine-list.tsx b/src/web/src/components/community/machines/machine-list.tsxindex 60ce22d02..e1e6d1cb7 100644--- a/src/web/src/components/community/machines/machine-list.tsx+++ b/src/web/src/components/community/machines/machine-list.tsx@@ -5,7 +5,7 @@ import { getCommunityRuntime, useCommunityRuntime } from "@/stores/community/runimport { useCallback, useEffect, useRef, type ReactNode } from "react"-import { useRouter, useSearchParams } from "next/navigation"+import { useCommunityModuleLocation } from "@/contexts/community/module-route"import { toast } from "sonner"import { ChevronLeft } from "lucide-react"import { useQueryClient, useQuery, useMutation } from "@tanstack/react-query"@@ -211,23 +211,24 @@ export function MachineUpdateDialog({}export function MachineList({ onBack }: { onBack?: () => void } = {}) {- const router = useRouter()- const searchParams = useSearchParams()+ const { router, searchParams, routeCommitted } = useCommunityModuleLocation()const communityRuntime = useCommunityRuntime()const queryClient = useQueryClient()const origin = useCommunityMutationOrigin()const source = useCommunityViewSource("machine-list")- const { machines, capacityPending, data: machinesData, isLoading: queryLoading, isError: queryError, isFetching: retryingMachines, refetch: retryMachines } = useMachines()+ const { machines, capacityPending, data: machinesData, isPending: queryLoading, isError: queryError, isFetching: retryingMachines, refetch: retryMachines } = useMachines()const machinesLoading = queryLoading || machinesData?.complete === false && machines.length === 0useObservedRegion("machines", machinesData !== undefined && machinesData.complete !== false, machines.length, { snapshot_source: machinesData?.source ?? "unknown", target_coverage: machinesData ? "covered" : "uncovered", wait_reason: machinesLoading ? "entry" : "none" })const capacity = machinesData?.machineCapacity ?? nullconst [limitOpen, setLimitOpen] = useAtom(useCreateAtom(false))const viewPlan = useCallback(() => {- const next = new URL(window.location.href)+ const next = new URL(routeCommitted ? window.location.href : `/c/me/machines?${searchParams.toString()}`, window.location.origin)next.searchParams.delete("billing")next.searchParams.set("settings", "billing")- window.history.pushState(null, "", `${next.pathname}${next.search}${next.hash}`)- }, [])+ const href = `${next.pathname}${next.search}${next.hash}`+ if (routeCommitted) window.history.pushState(null, "", href)+ else router.push(href)+ }, [routeCommitted, router, searchParams])const { bots } = useBots()const pendingMachineTokenId = usePendingMachineTokenId()const [pairOpen, setPairOpen] = useAtom(useCreateAtom(false))@@ -319,14 +320,14 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {const handledReconnectRef = useRef<string | null>(null)useEffect(() => {const reconnectId = searchParams.get("reconnect")- if (!reconnectId || handledReconnectRef.current === reconnectId || machinesLoading) return+ if (!routeCommitted || !reconnectId || handledReconnectRef.current === reconnectId || machinesLoading) returnhandledReconnectRef.current = reconnectIdconst machine = machines.find((m) => m.id === reconnectId)if (machine) openReconnect(machine)const search = searchParams.toString()const href = `/c/me/machines${search ? `?${search}` : ""}`router.replace(removeCommunityParam(href, "reconnect"))- }, [searchParams, machines, machinesLoading, openReconnect, router])+ }, [routeCommitted, searchParams, machines, machinesLoading, openReconnect, router])const closePair = useCallback((open: boolean) => {setPairOpen(open)diff --git a/src/web/src/components/community/machines/me-machines-route.tsx b/src/web/src/components/community/machines/me-machines-route.tsxnew file mode 100644index 000000000..d999b788e--- /dev/null+++ b/src/web/src/components/community/machines/me-machines-route.tsx@@ -0,0 +1,32 @@+"use client"++import { MachineList } from "@/components/community/machines/machine-list"+import { OnboardingSelectDialogPreview } from "@/components/community/onboarding/onboarding-select-dialog.preview"+import { useUiHandlers } from "@/stores/community"+import { useCommunityModuleLocation } from "@/contexts/community/module-route"++export default function MeMachinesPage() {+ const uiHandlers = useUiHandlers()+ const { searchParams, routeCommitted } = useCommunityModuleLocation()+ const onboardingPreview = searchParams.get("onboarding-preview")+ const showOnboardingPreview =+ routeCommitted && process.env.NODE_ENV !== "production"+ && (+ onboardingPreview === "1"+ || onboardingPreview === "online"+ || onboardingPreview === "setting-up"+ )+ return (+ <>+ <MachineList+ onBack={() => uiHandlers.goBackMobile?.()}+ />+ {showOnboardingPreview ? (+ <OnboardingSelectDialogPreview+ simulateOnlineMachine={onboardingPreview === "online"}+ showSettingUp={onboardingPreview === "setting-up"}+ />+ ) : null}+ </>+ )+}diff --git a/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts b/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.tsindex 62d9cae60..4ad346470 100644--- a/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts+++ b/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts@@ -27,7 +27,7 @@ const mocks = vi.hoisted(() => ({}))vi.mock("next/navigation", () => ({- useParams: () => ({ serverId: "server_1" }),+ useParams: () => ({ serverId: "wrong_published_server" }),useRouter: () => ({ push: mocks.push }),}))vi.mock("@tanstack/react-query", async (importOriginal) => ({ ...await importOriginal<typeof import("@tanstack/react-query")>(),@@ -246,13 +246,14 @@ describe("MessageContextSheet thread navigation", () => {open: false,onOpenChange: mocks.close,channelId: "parent_1",+ serverId: "target_server",targetSeq: 1,}))act(() => mocks.openThread?.("child_1"))expect(mocks.cancel).toHaveBeenCalledOnce()expect(mocks.cancel.mock.invocationCallOrder[0]).toBeLessThan(mocks.push.mock.invocationCallOrder[0]!)- expect(mocks.push).toHaveBeenCalledWith("/c/channels/server_1/child_1")+ expect(mocks.push).toHaveBeenCalledWith("/c/channels/target_server/child_1")expect(mocks.close).toHaveBeenCalledWith(false)})diff --git a/src/web/src/components/community/messages/message-context-sheet.tsx b/src/web/src/components/community/messages/message-context-sheet.tsxindex 14515580e..d6d1d8306 100644--- a/src/web/src/components/community/messages/message-context-sheet.tsx+++ b/src/web/src/components/community/messages/message-context-sheet.tsx@@ -3,7 +3,7 @@ import { useAtom, useCreateAtom } from "@tanstack/react-store"import { useCallback, useEffect, useMemo, useRef } from "react"-import { useRouter, useParams } from "next/navigation"+import { useCommunityRouter } from "@/contexts/community/module-route"import { toast } from "sonner"import { useQuery, useQueryClient } from "@tanstack/react-query"import { deriveThreadName } from "@alook/shared"@@ -158,6 +158,7 @@ export function MessageContextSheet({open,onOpenChange,channelId,+ serverId,channelLabel,targetSeq,pinnedIds,@@ -171,6 +172,7 @@ export function MessageContextSheet({open: booleanonOpenChange: (v: boolean) => voidchannelId: string+ serverId?: string// Source channel's display name for the header — a message ref opens this// sheet to preview a (possibly other) channel's message in place, so the// header names which channel's context this is (Gus #417/#423, Alli #420).@@ -190,8 +192,7 @@ export function MessageContextSheet({const currentUser = useCurrentUser()const uiHandlers = useUiHandlers()const queryClient = useQueryClient()- const router = useRouter()- const routeParams = useParams<{ serverId?: string }>()+ const router = useCommunityRouter()const pinMessageMut = usePinMessage()const unpinMessageMut = useUnpinMessage()const createThreadMut = useCreateThread()@@ -327,7 +328,6 @@ export function MessageContextSheet({const onCreateThreadId = useCallback(async (id: string) => {if (type === "dm") return- const serverId = routeParams?.serverIdif (!serverId) returnconst m = findMessage(id)const content = m ? (m.content ?? "") : undefined@@ -337,7 +337,7 @@ export function MessageContextSheet({} catch (e) {if (!isAbortError(e)) toastApiError(e, "Failed to create thread")}- }, [type, routeParams, channelId, findMessage, createThreadMut])+ }, [type, serverId, channelId, findMessage, createThreadMut])const onOpenThreadId = useCallback((threadId: string) => {@@ -346,7 +346,7 @@ export function MessageContextSheet({// case (threads live inside channels, not DMs).openMessageContextThread({type,- serverId: routeParams?.serverId,+ serverId,threadId,push: (href) => {uiHandlers.cancelPendingNavigation?.()@@ -354,7 +354,7 @@ export function MessageContextSheet({},close: () => onOpenChange(false),})- }, [type, router, routeParams, onOpenChange, uiHandlers])+ }, [type, router, serverId, onOpenChange, uiHandlers])const onPreviewImage = useCallback((image: ImagePreview) => {uiHandlers.previewImage?.(image)diff --git a/src/web/src/components/community/onboarding/onboarding-preview-flow.test.ts b/src/web/src/components/community/onboarding/onboarding-preview-flow.test.tsindex 36f4961a6..955fa2182 100644--- a/src/web/src/components/community/onboarding/onboarding-preview-flow.test.ts+++ b/src/web/src/components/community/onboarding/onboarding-preview-flow.test.ts@@ -17,7 +17,7 @@ const machineDialogSource = readFileSync("utf8",)const machinesPageSource = readFileSync(- resolve(directory, "../../../app/c/me/machines/page.tsx"),+ resolve(directory, "../machines/me-machines-route.tsx"),"utf8",)diff --git a/src/web/src/components/community/shell/cached-conversation-route.dom.test.tsx b/src/web/src/components/community/shell/cached-conversation-route.dom.test.tsxnew file mode 100644index 000000000..c7fb014c3--- /dev/null+++ b/src/web/src/components/community/shell/cached-conversation-route.dom.test.tsx@@ -0,0 +1,187 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { useLayoutEffect } from "react"+import { IsRestoringProvider, QueryClientProvider } from "@tanstack/react-query"+import { CurrentUserProvider } from "@/contexts/community/current-user"+import { CommunityDbProvider } from "@/lib/community-db/projections"+import { CommunityRouteContext } from "./community-route-context"+import { CommunityModuleRoute } from "./community-module-route"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { conversationEntryFixture, seedConversationEntry } from "@/test/conversation-entry-fixtures"+import { act, render } from "@/test/react-dom-harness"+import { installMessageScrollFixture, restoreMessageScrollFixture, resize } from "@/test/message-scroll-fixture"+import { disposeReadCoordinator, getLocalReadingPosition } from "@/hooks/community/read-coordinator"+import { disposeAccountReadStateReconciliation } from "@/hooks/community/community-ws/read-state-reconciliation"++const mocks = vi.hoisted(() => ({ load: vi.fn(), replace: vi.fn(), memory: vi.fn(), dismiss: vi.fn(), snapshots: [] as unknown[], observedRows: new Set<Element>(), href: "/c/channels/old/old" }))+vi.mock("next/navigation", () => ({+ useRouter: () => ({ replace: mocks.replace, push: vi.fn() }),+ usePathname: () => mocks.href.split("?")[0],+ useSearchParams: () => new URLSearchParams(mocks.href.split("?")[1]),+}))+vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: (...args: unknown[]) => mocks.load(...args) }))+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop", useIsMobile: () => false }))+vi.mock("@/hooks/community/use-servers", () => ({ useServer: () => ({ server: null }) }))+vi.mock("@/components/community/members/channel-member-view-model", () => ({ useChannelMemberViewModel: () => ({ composerMembers: [], composerMentionCandidates: [], memberPanelProps: {}, manageMembersDialog: null, resolveUserName: (id: string) => id, myRole: "member" }) }))+vi.mock("@/hooks/community/use-notification-settings", () => ({ useNotificationSettings: () => ({ channel: {} }) }))+vi.mock("@/hooks/community/use-native-system-notifications", () => ({ useNativeSystemNotificationConversationDismissal: (...args: unknown[]) => mocks.dismiss(...args) }))+vi.mock("@/lib/community/last-community-route", async original => ({ ...await original<typeof import("@/lib/community/last-community-route")>(), commitCommunityChannelRoute: (...args: unknown[]) => mocks.memory(...args) }))+vi.mock("@/hooks/community/use-channel-message-feed", async original => {+ const actual = await original<typeof import("@/hooks/community/use-channel-message-feed")>()+ return {...actual, useChannelMessageFeed: (options: Parameters<typeof actual.useChannelMessageFeed>[0]) => {+ const result = actual.useChannelMessageFeed(options)+ useLayoutEffect(() => { mocks.snapshots.push(result.readSnapshot) }, [result.readSnapshot])+ return result+ }}+})+vi.mock("@/hooks/community/use-channel-panels", () => ({ usePins: () => ({pins: [], isLoading: false}), useThreads: () => ({threads: [], isLoading: false}) }))+vi.mock("@/hooks/community/mutations", () => ({+ useSendMessage: () => ({mutateAsync: vi.fn()}), useSetChannelNotif: () => ({mutate: vi.fn()}),+ useToggleReactionApi: () => vi.fn(), useAddReactionApi: () => vi.fn(),+ usePinMessage: () => ({mutate: vi.fn()}), useUnpinMessage: () => ({mutate: vi.fn()}),+ useToggleMark: () => vi.fn(), useEditMessage: () => ({mutate: vi.fn()}),+ useCreateThread: () => ({mutateAsync: vi.fn()}), useUploadFile: () => ({mutateAsync: vi.fn()}),+}))+vi.mock("@/components/community/messages/composer", () => ({ Composer: () => <div data-testid="qualified-composer" />, ComposerSkeleton: () => null }))+vi.mock("@/components/community/messages/message-context-sheet", () => ({ MessageContextSheet: () => null }))+vi.mock("@/components/community/channels/channel-header", () => ({ ChannelHeader: ({channel}: {channel: string}) => <header>{channel}</header>, ChannelHeaderSkeleton: () => null }))++let owner: Awaited<ReturnType<typeof createCommunityQueryOwner>>+let view: ReturnType<typeof render> | undefined+beforeEach(async () => {+ installMessageScrollFixture()+ vi.stubGlobal("matchMedia", vi.fn(() => ({matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn()})))+ vi.stubGlobal("IntersectionObserver", class { observe(node: Element) { if (node.matches("[data-msg-id]")) mocks.observedRows.add(node) } unobserve() {} disconnect() {} takeRecords() { return [] } })+ owner = await createCommunityQueryOwner()+ view = undefined+ mocks.load.mockReset()+ mocks.observedRows.clear()+ mocks.snapshots.length = 0+ mocks.memory.mockClear()+ mocks.dismiss.mockClear()+ mocks.replace.mockClear()+ mocks.href = "/c/channels/old/old"+ mocks.load.mockImplementation((url: string) => {+ if (url === "/api/community/users/me/attention") return Promise.resolve({scopes: [], items: [], limit: 100, truncated: false})+ throw new Error(`Unexpected cached-route request: ${url}`)+ })+})+afterEach(() => {+ view?.unmount()+ disposeReadCoordinator(owner.client)+ disposeAccountReadStateReconciliation(owner.client)+ restoreMessageScrollFixture()+})++const href = "/c/channels/s1/c1"+const entryIntent = {href}+function node(routeCommitted: boolean, restoring = false, target = href) {+ return <QueryClientProvider client={owner.client}><CommunityDbProvider registry={owner.registry}>+ <CurrentUserProvider initialUser={{id: "viewer", name: "Viewer", avatar: "V", email: "[email protected]"}}>+ <CommunityRouteContext value={{breakpoint: "desktop", frame: {revision: 1}, navigation: {entryIntent, pendingHref: routeCommitted ? null : href, publishedHref: mocks.href}} as never}>+ <IsRestoringProvider value={restoring}><CommunityModuleRoute href={target} routeCommitted={routeCommitted} /></IsRestoringProvider>+ </CommunityRouteContext>+ </CurrentUserProvider>+ </CommunityDbProvider></QueryClientProvider>+}+async function mount(restoring = false, target = href) {+ await act(async () => {+ view = render(node(false, restoring, target))+ await import("../channels/server-conversation-route")+ })+ resize()+ await act(async () => {})+ return view!+}++describe("cached target through the real route, entry and message consumers", () => {+ it("keeps a cold forum opener unknown through restore instead of mounting then removing the composer", async () => {+ const entry = conversationEntryFixture()+ entry.channel = { ...entry.channel, type: "thread", parentChannelId: "parent", parentMessageId: "opener" }+ entry.surfaceReceipt = { channelId: entry.channelId, surfaceKind: "thread" }+ entry.parent = { ...conversationEntryFixture().channel, id: "parent", type: "forum", name: "Forum" }+ entry.selection = { reason: "tail", anchorMessageId: null }+ entry.page = { ...entry.page, olderCursor: null, hasMoreOlder: false }+ await seedConversationEntry(owner.client, entry)+ mocks.load.mockImplementation((url: string) => {+ if (url === "/api/community/messages/opener") return new Promise(() => {})+ if (url === "/api/community/users/me/attention") return Promise.resolve({ scopes: [], items: [], limit: 100, truncated: false })+ throw new Error(`Unexpected cold-opener request: ${url}`)+ })+ const target = `${href}?threadView=full`+ const mounted = await mount(true, target)+ expect(mounted.queryByTestId("qualified-composer")).toBeNull()+ mounted.rerender(node(false, false, target))+ await act(async () => {})+ expect(mounted.queryByTestId("qualified-composer")).toBeNull()+ })++ it("keeps a canonical cached forum opener and composer through restore and route commit", async () => {+ const entry = conversationEntryFixture()+ entry.channel = { ...entry.channel, type: "thread", parentChannelId: "parent", parentMessageId: "opener" }+ entry.surfaceReceipt = { channelId: entry.channelId, surfaceKind: "thread" }+ entry.parent = { ...conversationEntryFixture().channel, id: "parent", type: "forum", name: "Forum" }+ entry.opener = { ...entry.messages[0], id: "opener", channelId: "parent", content: "Cached post title" }+ entry.selection = { reason: "tail", anchorMessageId: null }+ entry.page = { ...entry.page, olderCursor: null, hasMoreOlder: false }+ await seedConversationEntry(owner.client, entry)+ mocks.load.mockImplementation((url: string) => {+ if (url === "/api/community/messages/opener") return Promise.resolve(entry.opener)+ if (url === "/api/community/users/me/attention") return Promise.resolve({ scopes: [], items: [], limit: 100, truncated: false })+ throw new Error(`Unexpected cached-opener request: ${url}`)+ })+ const target = `${href}?threadView=full`+ const mounted = await mount(true, target)+ const composer = mounted.getByTestId("qualified-composer")+ expect(composer).toBeVisible()+ mounted.rerender(node(false, false, target))+ await act(async () => {})+ expect(mounted.getByTestId("qualified-composer")).toBe(composer)+ mocks.href = target+ mounted.rerender(node(true, false, target))+ expect(mounted.getByTestId("qualified-composer")).toBe(composer)+ })++ it("shows qualified messages before publication and keeps the same scroller through commit", async () => {+ const entry = conversationEntryFixture()+ entry.messages[0].content = "Cached target body"+ entry.readState = {...entry.readState, lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0}+ entry.selection = {reason: "tail", anchorMessageId: null}+ entry.page = {...entry.page, olderCursor: null, hasMoreOlder: false}+ await seedConversationEntry(owner.client, entry)+ const mounted = await mount()+ const root = mounted.getByTestId("community-message-scroller")+ expect(mounted.getByText("Cached target body")).toBeVisible()+ const row = root.querySelector('[data-msg-id="m1"]')+ expect(row).not.toBeNull()+ const snapshot = mocks.snapshots.at(-1)+ expect(snapshot).toMatchObject({lastReadSeq: 0})+ expect(mocks.observedRows.size).toBe(0)+ expect(mocks.href).toBe("/c/channels/old/old")+ expect(owner.runtime.ui.get().currentChannelId).toBeNull()+ expect(mocks.memory).not.toHaveBeenCalled()+ expect(mocks.dismiss.mock.calls.every(([, , ready]) => ready === false)).toBe(true)+ expect(getLocalReadingPosition(owner.client, "c1")).toBeNull()+ expect(mocks.load.mock.calls.filter(([url]) => String(url).endsWith("/read"))).toEqual([])+ mocks.href = href+ mounted.rerender(node(true))+ resize()+ await act(async () => {})+ expect(mounted.getByTestId("community-message-scroller")).toBe(root)+ expect(root.querySelector('[data-msg-id="m1"]')).toBe(row)+ expect(owner.runtime.ui.get().currentChannelId).toBe("c1")+ expect(mocks.snapshots.at(-1)).toBe(snapshot)+ expect(mocks.observedRows.has(row!)).toBe(true)+ expect(mocks.memory).toHaveBeenCalledWith("viewer", "s1", "c1")+ expect(mocks.dismiss).toHaveBeenLastCalledWith("viewer", {kind: "server", serverId: "s1", channelId: "c1"}, true)+ })++ it("does not admit cached messages after the target channel is revoked", async () => {+ await seedConversationEntry(owner.client, conversationEntryFixture())+ act(() => owner.runtime.ws.actions.revokeChannelAccess("s1", "c1"))+ const mounted = await mount()+ expect(mounted.queryByText("Body")).toBeNull()+ expect(mounted.container.querySelector("[data-msg-id]")).toBeNull()+ expect(mocks.memory).not.toHaveBeenCalled()+ expect(mocks.replace).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/components/community/shell/community-list-errors.dom.test.tsx b/src/web/src/components/community/shell/community-list-errors.dom.test.tsxnew file mode 100644index 000000000..ce563dc16--- /dev/null+++ b/src/web/src/components/community/shell/community-list-errors.dom.test.tsx@@ -0,0 +1,103 @@+import { beforeEach, expect, it, vi } from "vitest"+import { act, fireEvent, render, waitFor } from "@/test/react-dom-harness"+import { CommunityTestProvider } from "@/test/community-owner-fixture"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { CurrentUserProvider } from "@/contexts/community/current-user"+import { CommunityRouteContext } from "@/contexts/community/route-frame"+import { CommunityModuleRouteContext } from "@/contexts/community/module-route"+import { normalizeCommunityHref } from "@/lib/community/community-route"+import { communityKeys } from "@/lib/query-keys"+import { friendsQueryFn } from "@/hooks/community/use-friends"+import { dmsProjectedQueryFn } from "@/hooks/community/use-dms"+import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"+import FriendsRoute from "../social/friends-route"+import { DmSidebarSlot } from "./dm-sidebar-slot"++const load = vi.hoisted(() => vi.fn())+vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: load }))+vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn(), replace: vi.fn() }), useSearchParams: () => new URLSearchParams() }))+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop", useIsMobile: () => false }))+vi.mock("@/hooks/community/use-friends", async original => ({ ...await original<typeof import("@/hooks/community/use-friends")>(), useFriendsPresence: () => {} }))+vi.mock("@/hooks/community/use-inbox", () => ({ useInboxUnreads: () => ({ friendRequests: [] }) }))+beforeEach(() => { load.mockReset() })++type Kind = "friends" | "dms"+const friend = { id: "friendship", userId: "peer", name: "Cached person", discriminator: "0001", avatar: "P", status: "offline", sub: "" }+const dm = { id: "dm", userId: "peer", name: "Cached person", discriminator: "0001", avatar: "P", status: "offline", preview: "Cached conversation" }+const primaryPath = (kind: Kind) => kind === "friends" ? "/api/community/friends/accepted" : "/api/community/users/me/dms"+const key = (kind: Kind) => kind === "friends" ? communityKeys.friends() : communityKeys.dms()+const emptyText = (kind: Kind) => kind === "friends" ? "No friends yet. Add someone from the New tab." : "Your direct messages will appear here."+function response(path: string, populated = false) {+ if (path.endsWith("/accepted")) return { friends: populated ? [friend] : [] }+ if (path.endsWith("/blocked")) return { blocked: [] }+ if (path.endsWith("/pending")) return { pending: [] }+ if (path.endsWith("/dms")) return { conversations: populated ? [dm] : [] }+ throw new Error(`Unexpected list request: ${path}`)+}+function node(owner: Awaited<ReturnType<typeof createCommunityQueryOwner>>, kind: Kind) {+ const href = kind === "friends" ? "/c/me/friends" : "/c/me"+ return <CommunityTestProvider client={owner.client} registry={owner.registry}>+ <CurrentUserProvider initialUser={{ id: "viewer", name: "Viewer", avatar: "V", email: "[email protected]" }}>+ <CommunityRouteContext value={{ frame: { ...normalizeCommunityHref(href), revision: 1 } } as never}>+ <CommunityModuleRouteContext value={{ href, routeCommitted: false }}>+ {kind === "friends" ? <FriendsRoute /> : <DmSidebarSlot href={href} routeCommitted={false} />}+ </CommunityModuleRouteContext>+ </CommunityRouteContext>+ </CurrentUserProvider>+ </CommunityTestProvider>+}++it.each(["friends", "dms"] as const)("shows the real %s initial error and retries its native Query through loading to confirmed empty", async kind => {+ const owner = await createCommunityQueryOwner()+ let calls = 0+ let resolve!: () => void+ const held = new Promise<void>(done => { resolve = done })+ load.mockImplementation(async (path: string) => {+ if (path === primaryPath(kind)) {+ calls+++ if (calls === 1) throw new Error("Initial list unavailable")+ await held+ }+ return response(path)+ })+ const view = render(node(owner, kind))+ const alert = await view.findByRole("alert")+ expect(alert).toHaveTextContent(kind === "friends" ? "Couldn't load friends" : "Couldn't load direct messages")+ expect(owner.client.getQueryState(key(kind))).toMatchObject({ status: "error", fetchStatus: "idle", data: undefined })+ expect(view.queryByText(emptyText(kind))).toBeNull()+ if (kind === "dms") expect(view.getByRole("link", { name: "Friends" })).toBeVisible()+ fireEvent.click(view.getByRole("button", { name: "Retry" }))+ await waitFor(() => expect(calls).toBe(2))+ expect(owner.client.getQueryState(key(kind))).toMatchObject({ status: "pending", fetchStatus: "fetching", data: undefined })+ expect(view.queryByText(emptyText(kind))).toBeNull()+ expect(view.container.querySelector('[data-slot="skeleton"]')).not.toBeNull()+ await act(async () => { resolve() })+ expect(await view.findByText(emptyText(kind))).toBeVisible()+ expect(view.queryByRole("alert")).toBeNull()+ expect(owner.client.getQueryState(key(kind))).toMatchObject({ status: "success", data: { ids: [] } })+ expect(load.mock.calls.every(([, options]) => !options?.method || options.method === "GET")).toBe(true)+})++it.each([+ ["friends", false], ["friends", true], ["dms", false], ["dms", true],+] as const)("keeps the same qualified %s content through background failure (populated=%s)", async (kind, populated) => {+ const owner = await createCommunityQueryOwner()+ load.mockImplementation(async (path: string) => response(path, populated))+ const queryKey = key(kind)+ await owner.client.query({ queryKey, queryFn: kind === "friends" ? friendsQueryFn : dmsProjectedQueryFn(getActiveAccountUnreadProjection(owner.client), owner.client) })+ let reject!: (error: Error) => void+ const held = new Promise<never>((_, fail) => { reject = fail })+ load.mockImplementation((path: string) => path === primaryPath(kind) ? held : Promise.resolve(response(path, populated)))+ await owner.client.invalidateQueries({ queryKey, exact: true, refetchType: "none" })+ const view = render(node(owner, kind))+ const text = populated ? "Cached person" : emptyText(kind)+ const content = view.getByText(text)+ expect(content).toBeVisible()+ await waitFor(() => expect(owner.client.getQueryState(queryKey)?.fetchStatus).toBe("fetching"))+ await act(async () => { reject(new Error("Background list unavailable")) })+ await waitFor(() => expect(owner.client.getQueryState(queryKey)?.status).toBe("error"))+ expect(owner.client.getQueryData(queryKey)).toEqual({ ids: populated ? [kind === "friends" ? "friendship" : "dm"] : [] })+ expect(view.getByText(text)).toBe(content)+ expect(content).toBeVisible()+ expect(view.queryByRole("alert")).toBeNull()+})diff --git a/src/web/src/components/community/shell/community-list-readiness.dom.test.tsx b/src/web/src/components/community/shell/community-list-readiness.dom.test.tsxnew file mode 100644index 000000000..d6f1fdc0f--- /dev/null+++ b/src/web/src/components/community/shell/community-list-readiness.dom.test.tsx@@ -0,0 +1,39 @@+import { IsRestoringProvider } from "@tanstack/react-query"+import { beforeEach, expect, it, vi } from "vitest"+import { render } from "@/test/react-dom-harness"+import { CommunityTestProvider } from "@/test/community-owner-fixture"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { CurrentUserProvider } from "@/contexts/community/current-user"+import { CommunityModuleRouteContext } from "@/contexts/community/module-route"+import { communityKeys } from "@/lib/query-keys"+import FriendsRoute from "../social/friends-route"+import BotsRoute from "../bots/me-bots-route"++const load = vi.hoisted(() => vi.fn())+vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: load }))+vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn(), replace: vi.fn() }), useSearchParams: () => new URLSearchParams() }))+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop", useIsMobile: () => false }))+vi.mock("@/lib/community-onboarding", async original => ({ ...await original<typeof import("@/lib/community-onboarding")>(), useCommunityOnboarding: () => null }))+vi.mock("../machines/pair-machine-sheet", () => ({ PairMachineSheet: () => null }))+beforeEach(() => { load.mockReset(); load.mockImplementation(() => new Promise(() => {})) })++it.each(["friends", "bots"] as const)("uses native pending versus cached empty for the real %s consumer during restore", async module => {+ const { client, registry } = await createCommunityQueryOwner()+ const Route = module === "friends" ? FriendsRoute : BotsRoute+ const node = () => <CommunityTestProvider client={client} registry={registry}>+ <CurrentUserProvider initialUser={{ id: "viewer", name: "Viewer", avatar: "V", email: "[email protected]" }}>+ <IsRestoringProvider value>+ <CommunityModuleRouteContext value={{ href: `/c/me/${module}`, routeCommitted: false }}><Route /></CommunityModuleRouteContext>+ </IsRestoringProvider>+ </CurrentUserProvider>+ </CommunityTestProvider>+ const view = render(node())+ expect(view.queryByText("No friends yet. Add someone from the New tab.")).toBeNull()+ expect(view.queryByText("No bots yet")).toBeNull()+ expect(view.container.querySelector('[data-slot="skeleton"]')).not.toBeNull()+ expect(load).not.toHaveBeenCalled()+ client.setQueryData(module === "friends" ? communityKeys.friends() : communityKeys.bots(), module === "friends" ? { ids: [] } : { bots: [], observed: false, source: "restored_idb" })+ view.rerender(node())+ expect(view.getByText(module === "friends" ? "No friends yet. Add someone from the New tab." : "No bots yet")).toBeVisible()+ expect(load).not.toHaveBeenCalled()+})diff --git a/src/web/src/components/community/shell/community-module-route.dom.test.tsx b/src/web/src/components/community/shell/community-module-route.dom.test.tsxnew file mode 100644index 000000000..1ef738a73--- /dev/null+++ b/src/web/src/components/community/shell/community-module-route.dom.test.tsx@@ -0,0 +1,45 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { act, render } from "@/test/react-dom-harness"+import { useCommunityModuleLocation } from "@/contexts/community/module-route"+import { CommunityModuleRoute } from "./community-module-route"++const mocks = vi.hoisted(() => ({ rememberMe: vi.fn(), rememberCommunity: vi.fn() }))+vi.mock("next/navigation", () => ({ useRouter: () => ({push: vi.fn(), replace: vi.fn()}), useSearchParams: () => new URLSearchParams("old=1") }))+vi.mock("@/contexts/community/current-user", () => ({ useCurrentUser: () => ({id: "viewer"}) }))+vi.mock("@/lib/community/last-me-location", () => ({isRememberableMeLocation: () => true, setLastMeLocation: (...args: unknown[]) => mocks.rememberMe(...args)}))+vi.mock("@/lib/community/last-community-route", () => ({commitLastCommunityRoute: (...args: unknown[]) => mocks.rememberCommunity(...args)}))+vi.mock("./community-pending-frame", () => ({CommunityPendingFrame: () => <div>Loading module</div>}))+function Module() {+ const {searchParams, routeCommitted} = useCommunityModuleLocation()+ return <main data-search={searchParams.toString()} data-committed={String(routeCommitted)}><input aria-label="Module state" /></main>+}+vi.mock("../social/friends-route", () => ({default: Module}))+vi.mock("../bots/me-bots-route", () => ({default: Module}))+vi.mock("../machines/me-machines-route", () => ({default: Module}))+beforeEach(() => { vi.clearAllMocks() })++describe("shared module delivery and committed route memory", () => {+ it.each(["friends", "bots", "machines"] as const)("keeps %s target parameters and body through commit without early route memory", async module => {+ const href = `/c/me/${module}?target=one`+ let view!: ReturnType<typeof render>+ await act(async () => {+ view = render(<CommunityModuleRoute href={href} routeCommitted={false} />)+ await Promise.all([import("../social/friends-route"), import("../bots/me-bots-route"), import("../machines/me-machines-route")])+ })+ const body = view.getByRole("main")+ const input = view.getByLabelText("Module state") as HTMLInputElement+ input.value = "Retained"+ expect(body).toHaveAttribute("data-search", "target=one")+ expect(body).toHaveAttribute("data-committed", "false")+ expect(mocks.rememberMe).not.toHaveBeenCalled()+ expect(mocks.rememberCommunity).not.toHaveBeenCalled()+ view.rerender(<CommunityModuleRoute href={href} routeCommitted />)+ expect(view.getByRole("main")).toBe(body)+ expect(view.getByLabelText("Module state")).toBe(input)+ expect(input).toHaveValue("Retained")+ expect(body).toHaveAttribute("data-search", "target=one")+ expect(body).toHaveAttribute("data-committed", "true")+ expect(mocks.rememberMe).toHaveBeenCalledExactlyOnceWith(`/c/me/${module}`)+ expect(mocks.rememberCommunity).toHaveBeenCalledExactlyOnceWith("viewer", `/c/me/${module}`)+ })+})diff --git a/src/web/src/components/community/shell/community-module-route.hydration.dom.test.tsx b/src/web/src/components/community/shell/community-module-route.hydration.dom.test.tsxnew file mode 100644index 000000000..4cc159080--- /dev/null+++ b/src/web/src/components/community/shell/community-module-route.hydration.dom.test.tsx@@ -0,0 +1,91 @@+import * as React from "react"+import { renderToReadableStream } from "react-dom/server.browser"+import { hydrateRoot, type Root } from "react-dom/client"+import { act } from "@/test/react-dom-harness"+import { afterEach, expect, it, vi } from "vitest"++vi.mock("@/hooks/community/use-me-route-memory", () => ({ useMeRouteMemory: () => {} }))+vi.mock("../social/friends-route", () => ({ default: () => null }))+vi.mock("../bots/me-bots-route", () => ({ default: () => null }))+vi.mock("../machines/me-machines-route", () => ({ default: () => null }))+vi.mock("./community-pending-frame", () => ({ CommunityPendingFrame: () => <div>Loading target</div> }))++function conversationConsumer(useFrame: typeof import("./community-route-context").useCommunityRouteFrame) {+ return function ServerConversationRoute({ channelId }: { channelId: string }) {+ const { breakpoint } = useFrame()+ return <main data-channel={channelId} data-breakpoint={breakpoint}><input aria-label="Composer" defaultValue="SSR draft" /></main>+ }+}++function Application({ Route, Frame, href }: { Route: React.ComponentType<{ href: string; routeCommitted: boolean }>; Frame: typeof import("./community-route-context").CommunityRouteContext; href: string }) {+ const [breakpoint, setBreakpoint] = React.useState("unknown")+ React.useEffect(() => { setBreakpoint("desktop") }, [])+ return <Frame value={{ breakpoint } as never}><Route href={href} routeCommitted /></Frame>+}++let root: Root | undefined+let container: HTMLDivElement | undefined+let releaseLoading = () => {}+let clientRead: Promise<void> | undefined+afterEach(async () => {+ releaseLoading()+ await clientRead+ await act(async () => { root?.unmount() })+ container?.remove()+ root = undefined+ container = undefined+ clientRead = undefined+ for (const path of ["../channels/server-conversation-route", "../social/friends-route", "../bots/me-bots-route", "../machines/me-machines-route"]) vi.doUnmock(path)+ vi.resetModules()+})++it.each([+ ["ordinary-thread", "/c/channels/server/ordinary-thread", "../channels/server-conversation-route", "ServerConversationRoute"],+ ["forum-child", "/c/channels/server/forum-child", "../channels/server-conversation-route", "ServerConversationRoute"],+ ["friends", "/c/me/friends", "../social/friends-route", "default"],+ ["bots", "/c/me/bots", "../bots/me-bots-route", "default"],+ ["machines", "/c/me/machines", "../machines/me-machines-route", "default"],+])("keeps the original %s SSR input while the client consumer module loads", async (_shape, href, path, exportName) => {+ vi.resetModules()+ const serverFrame = await import("./community-route-context")+ vi.doMock(path, () => ({ [exportName]: conversationConsumer(serverFrame.useCommunityRouteFrame) }))+ const server = await import("./community-module-route")+ const stream = await renderToReadableStream(<Application Route={server.CommunityModuleRoute} Frame={serverFrame.CommunityRouteContext} href={href} />)+ await stream.allReady+ const html = await new Response(stream).text()+ container = document.createElement("div")+ container.innerHTML = html+ document.body.appendChild(container)+ const composer = container.querySelector("input")!+ expect(composer).not.toBeNull()+ composer.value = "Early user draft"+ let release!: () => void+ const gate = new Promise<void>(resolve => { release = resolve })+ releaseLoading = release+ let started!: () => void+ const loading = new Promise<void>(resolve => { started = resolve })+ vi.resetModules()+ const clientFrame = await import("./community-route-context")+ vi.doUnmock(path)+ vi.doMock(path, async () => {+ started()+ await gate+ return { [exportName]: conversationConsumer(clientFrame.useCommunityRouteFrame) }+ })+ const recoveries: unknown[] = []+ clientRead = import("./community-module-route").then(module => {+ act(() => {+ root = hydrateRoot(container!, <Application Route={module.CommunityModuleRoute} Frame={clientFrame.CommunityRouteContext} href={href} />, {+ onRecoverableError: error => { recoveries.push(error) },+ })+ })+ })+ await loading+ await act(async () => {})+ expect(container.querySelector("input")).toBe(composer)+ expect(composer.value).toBe("Early user draft")+ await act(async () => { release(); await clientRead })+ expect(container.querySelector("input")).toBe(composer)+ expect(composer.value).toBe("Early user draft")+ expect(recoveries).toEqual([])+})diff --git a/src/web/src/components/community/shell/community-module-route.tsx b/src/web/src/components/community/shell/community-module-route.tsxnew file mode 100644index 000000000..1447b947a--- /dev/null+++ b/src/web/src/components/community/shell/community-module-route.tsx@@ -0,0 +1,52 @@+"use client"++import { useMeRouteMemory } from "@/hooks/community/use-me-route-memory"+import { Suspense, useEffect } from "react"+import { CommunityModuleRouteContext, useCommunityRouter } from "@/contexts/community/module-route"+import { normalizeCommunityHref, resolveCommunityModulePlan } from "@/lib/community/community-route"+import { CommunityPendingFrame } from "./community-pending-frame"+import { ServerConversationRoute } from "../channels/server-conversation-route"++import FriendsRoute from "../social/friends-route"+import BotsRoute from "../bots/me-bots-route"+import MachinesRoute from "../machines/me-machines-route"+import CommunityRootRoute from "./community-root-route"+import MeRootRoute from "./me-root-route"+import ServerLandingRoute from "./server-landing-route"+import ServerSettingsRoute from "./server-settings-route"+import { CommunityServerRouteContext } from "@/contexts/community/route-frame"+import { MessageRoute } from "../messages/message-route"++export function CommunityModuleRoute({ href, routeCommitted }: { href: string; routeCommitted: boolean }) {+ const target = normalizeCommunityHref(href)+ const plan = resolveCommunityModulePlan(target.href)+ useMeRouteMemory(target.pathname, routeCommitted)+ const content = plan.route === "community-root-redirect" ? <CommunityRootRoute />+ : plan.route === "onboarding-preview" ? <CommunityRouteRedirect href={plan.canonicalHref!} />+ : plan.main.kind === "server-conversation" ? (+ <ServerConversationRoute serverId={plan.main.serverId} serverParam={encodeURIComponent(plan.main.serverId)}+ channelId={plan.main.leafId} href={target.href} routeCommitted={routeCommitted} />+ ) : plan.main.kind === "friends" ? <FriendsRoute />+ : plan.main.kind === "bots" ? <BotsRoute />+ : plan.main.kind === "machines" ? <MachinesRoute />+ : plan.main.kind === "me-root" ? <MeRootRoute />+ : plan.main.kind === "server-landing" ? (+ <CommunityServerRouteContext value={{ serverId: plan.main.serverId, serverParam: encodeURIComponent(plan.main.serverId) }}>+ <ServerConversationRoute serverId={plan.main.serverId} serverParam={encodeURIComponent(plan.main.serverId)}+ channelId={null} href={target.href} routeCommitted={routeCommitted}>+ {plan.route === "server-settings-redirect" ? <ServerSettingsRoute /> : <ServerLandingRoute />}+ </ServerConversationRoute>+ </CommunityServerRouteContext>+ ) : plan.route === "message-resolution" ? <MessageRoute messageId={decodeURIComponent(target.pathname.split("/")[3]!)} /> : null+ return <CommunityModuleRouteContext value={{ href: target.href, routeCommitted }}>+ <Suspense fallback={<CommunityPendingFrame href={target.href} reserveBackSlot={target.surface === "detail"} />}>+ {content}+ </Suspense>+ </CommunityModuleRouteContext>+}++function CommunityRouteRedirect({ href }: { href: string }) {+ const router = useCommunityRouter()+ useEffect(() => { router.replace(href) }, [href, router])+ return <CommunityPendingFrame href={href} />+}diff --git a/src/web/src/components/community/shell/community-root-route.tsx b/src/web/src/components/community/shell/community-root-route.tsxnew file mode 100644index 000000000..0d61a90d4--- /dev/null+++ b/src/web/src/components/community/shell/community-root-route.tsx@@ -0,0 +1,25 @@+"use client"++import { CommunityModuleRouteContext, useCommunityRouter } from "@/contexts/community/module-route"+import { useContext, useEffect } from "react"+import { CommunityPendingFrame } from "@/components/community/shell/community-pending-frame"+import { useCurrentUser } from "@/contexts/community/current-user"+import { resolveCommunityColdEntryDestination } from "@/lib/community/last-community-route"++export default function CommunityIndex() {+ const router = useCommunityRouter()+ const currentUser = useCurrentUser()+ const target = useContext(CommunityModuleRouteContext)+ const targetHref = target?.href+ useEffect(() => {+ const entry = targetHref ? new URL(targetHref, window.location.origin) : window.location+ const destination = resolveCommunityColdEntryDestination({+ accountId: currentUser.id,+ pathname: entry.pathname,+ search: entry.search,+ hash: entry.hash,+ })+ router.replace(destination)+ }, [currentUser.id, router, targetHref])+ return <CommunityPendingFrame href="/c" />+}diff --git a/src/web/src/components/community/shell/community-route-frame.dom.test.tsx b/src/web/src/components/community/shell/community-route-frame.dom.test.tsxindex 22a860a06..48fbb8d4b 100644--- a/src/web/src/components/community/shell/community-route-frame.dom.test.tsx+++ b/src/web/src/components/community/shell/community-route-frame.dom.test.tsx@@ -60,6 +60,8 @@ vi.mock("@/components/ui/resizable", () => {})vi.mock("./server-rail", () => ({ ServerRail: () => <div data-testid="rail"><button data-testid="home">Home</button><input data-testid="rail-state" /></div> }))vi.mock("./user-bar", () => ({ UserBar: () => <div data-testid="userbar">{mocks.userId}</div> }))+vi.mock("@/components/community/social/friends-route", () => ({ default: () => <div data-testid="main">me/friends</div> }))+vi.mock("@/components/brand/alook-loading/AlookLoading", () => ({ AlookLoading: () => null }))vi.mock("./community-inbox-popover", () => ({ InboxPopover: () => null }))vi.mock("./shell-frame-overlays", () => ({ ShellFrameOverlays: () => null }))vi.mock("@/components/community/channels/dm-route", () => ({ DmRoute: ({ dmId, routeCommitted }: { dmId: string; routeCommitted: boolean }) => createElement("main", { "data-dm-target": dmId, "data-committed": String(routeCommitted) }) }))@@ -99,7 +101,7 @@ function tree(serverId: string | null = null) {}describe("common committed community frame", () => {- it("lets the neutral root own its only actual SSR frame before destination resolution", () => {+ it("keeps the unresolved root neutral inside the common route frame", () => {mocks.segments = []mocks.pathname = "/c"const html = renderToString(<CommunityTestProvider client={owner.client} registry={owner.registry} retainOwner>@@ -111,8 +113,9 @@ describe("common committed community frame", () => {expect(html).not.toContain('data-testid="userbar"')})- it("retains global nodes and state across me/server and preserves same-server sidebar", () => {+ it("retains global nodes and state across me/server and preserves same-server sidebar", async () => {const view = render(tree())+ await act(async () => {})const rail = view.getByTestId("rail")const home = view.getByTestId("home")const userbar = view.getByTestId("userbar")@@ -134,8 +137,9 @@ describe("common committed community frame", () => {expect(view.getByTestId("rail")).toBe(rail)})- it("ignores ahead-of-commit pathname and gates mismatched sidebar scope", () => {+ it("ignores ahead-of-commit pathname and gates mismatched sidebar scope", async () => {const view = render(tree())+ await act(async () => {})mocks.pathname = "/c/channels/b/two"view.rerender(tree("b"))expect(view.queryByTestId("sidebar")).toBeNull()@@ -146,10 +150,11 @@ describe("common committed community frame", () => {expect(view.getByTestId("sidebar")).toHaveAttribute("data-server-id", "b")})- it.each(["url-first", "segments-first"])("gates DM query effects on exact publication in %s order", order => {+ it.each(["url-first", "segments-first"])("gates DM query effects on exact publication in %s order", async order => {mocks.segments = ["me", "dm-a"]mocks.pathname = "/c/me/dm-a"const view = render(tree())+ await act(async () => {})expect(view.container.querySelector('[data-dm-target="dm-a"]')).toHaveAttribute("data-committed", "true")act(() => owner.runtime.ui.get().uiHandlers.navigatePath?.("/c/me/dm-b?seq=7"))const body = view.container.querySelector('[data-dm-target="dm-b"]')!@@ -172,6 +177,7 @@ describe("common committed community frame", () => {mocks.breakpoint = "mobile"mocks.segments = ["me"]const view = render(tree())+ await act(async () => {})const home = view.getByTestId("home")const userbar = view.getByTestId("userbar")mocks.segments = ["me", "dm-a"]diff --git a/src/web/src/components/community/shell/community-route-frame.tsx b/src/web/src/components/community/shell/community-route-frame.tsxindex 5772049d0..9b9277720 100644--- a/src/web/src/components/community/shell/community-route-frame.tsx+++ b/src/web/src/components/community/shell/community-route-frame.tsx@@ -28,8 +28,6 @@ export function CommunityRouteFrame({ sidebar, children }: {getCommunityRuntime(queryClient).ui.actions.setCurrentServerId(serverId)}, [queryClient, serverId])- if (frameHref === "/c") return children-return (<ShellFramekey={currentUser.id}diff --git a/src/web/src/components/community/shell/community-session-pending-frame.tsx b/src/web/src/components/community/shell/community-session-pending-frame.tsxindex 262867d70..a88e4c69e 100644--- a/src/web/src/components/community/shell/community-session-pending-frame.tsx+++ b/src/web/src/components/community/shell/community-session-pending-frame.tsx@@ -1,5 +1,6 @@"use client"+import type { ReactNode } from "react"import { ChannelSidebarSkeleton } from "@/components/community/channels/channel-sidebar"import { DmSidebarSkeleton } from "@/components/community/channels/dm-sidebar"import { AppSurface } from "@/components/ui/app-surface"@@ -13,7 +14,7 @@ import { Shell } from "./shell"import { UserBarSkeleton } from "./user-bar"/** Stable, inert viewport shown before authenticated community providers exist. */-export function CommunitySessionPendingFrame({ pathname }: { pathname: string }) {+export function CommunitySessionPendingFrame({ pathname, children }: { pathname: string; children?: ReactNode }) {const breakpoint = useBreakpoint()const plan = resolveCommunityModulePlan(pathname)const showCommunityShell = plan.rail === "community"@@ -27,9 +28,9 @@ export function CommunitySessionPendingFrame({ pathname }: { pathname: string })><div className="relative flex min-h-0 min-w-0 flex-1 flex-col"><AppSurface className="rounded-none border-0 bg-background">- {plan.main.kind !== "none" && (+ {children ?? (plan.main.kind !== "none" && (<CommunityPendingFrame href={pathname} plan={plan} />- )}+ ))}</AppSurface></div></Shell>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.tsxindex fc1c72f7e..0afc5370f 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@@ -16,6 +16,7 @@ const mocks = vi.hoisted(() => ({vi.mock("./community-route-context", () => ({useCommunityRouteFrame: () => ({ frame: {scope: { kind: mocks.scope },+ href: mocks.scope === "me" ? "/c/me/friends" : "/c/channels/server",pathname: mocks.scope === "me" ? "/c/me/friends" : "/c/channels/server",} }),}))@@ -33,7 +34,7 @@ vi.mock("@/hooks/community/use-dms", () => ({mocks.subscribe()return () => { mocks.unsubscribe() }}, [])- return { dms: [{ userId: mocks.peer, avatar: mocks.avatar }], isLoading: false }+ return { dms: [{ userId: mocks.peer, avatar: mocks.avatar }], isPending: false }},}))vi.mock("@/hooks/community/use-friends", () => ({@@ -123,3 +124,15 @@ describe("account-scoped DM sidebar Activity", () => {expect(rendered.container.querySelectorAll("img")).toHaveLength(1)})})+++it("shows the selected Me sidebar before the committed server frame moves and keeps its original node", () => {+ mocks.scope = "server"+ const view = render(<DmSidebarSlot href="/c/me/friends" routeCommitted={false} />)+ const input = view.getByRole("textbox") as HTMLInputElement+ input.value = "Target sidebar state"+ mocks.scope = "me"+ view.rerender(<DmSidebarSlot href="/c/me/friends" routeCommitted />)+ expect(view.getByRole("textbox")).toBe(input)+ expect(input).toHaveValue("Target sidebar state")+})diff --git a/src/web/src/components/community/shell/dm-sidebar-slot.tsx b/src/web/src/components/community/shell/dm-sidebar-slot.tsxindex b6e49da20..613668660 100644--- a/src/web/src/components/community/shell/dm-sidebar-slot.tsx+++ b/src/web/src/components/community/shell/dm-sidebar-slot.tsx@@ -3,7 +3,7 @@ import { useObservedRegion } from "@/lib/observability/regions"import { useCommunityRuntime } from "@/stores/community/runtime"-import { dmHref } from "@/lib/community/community-route"+import { dmHref, normalizeCommunityHref } 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"@@ -13,33 +13,37 @@ import { useFriends, useFriendsPresence } from "@/hooks/community/use-friends"import { useInboxUnreads } from "@/hooks/community/use-inbox"// DM-side layout. The DM subtree has no server settings, no channel sidebar,// and no `[serverId]` param — everything is scoped to the current user.-export function DmSidebarSlot({ visible = true }: { visible?: boolean }) {+export function DmSidebarSlot({ visible = true, href, routeCommitted = true }: { visible?: boolean; href?: string; routeCommitted?: boolean }) {const { frame } = useCommunityRouteFrame()- const inMe = frame.scope.kind === "me"+ const target = normalizeCommunityHref(href ?? frame.href)+ const inMe = target.scope.kind === "me"const [visitedMe, setVisitedMe] = useState(inMe)useLayoutEffect(() => {if (inMe) setVisitedMe(true)}, [inMe])if (!inMe && !visitedMe) return null- return <Activity mode={inMe && visible ? "visible" : "hidden"}><MeSidebar /></Activity>+ return <Activity mode={inMe && visible ? "visible" : "hidden"}><MeSidebar pathname={target.pathname} routeCommitted={routeCommitted} /></Activity>}-function MeSidebar() {+function MeSidebar({ pathname, routeCommitted }: { pathname: string; routeCommitted: boolean }) {const communityRuntime = useCommunityRuntime()- const { frame } = useCommunityRouteFrame()- const pathname = frame.pathnameconst {dms,- isLoading: dmsLoading,+ isPending: dmsLoading,+ data,+ isError,+ isFetching,+ refetch,} = useDms()const { blocked } = useFriends()- useObservedRegion("sidebar", !dmsLoading, dms.length)+ const initialError = isError && data === undefined+ useObservedRegion("sidebar", !dmsLoading && !initialError, dms.length)const friendRequestCount = useInboxUnreads().friendRequests.lengthconst currentChannelId = useCurrentChannelId()// 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.- useFriendsPresence()+ useFriendsPresence(routeCommitted)const machinesActive = pathname === "/c/me/machines"const botsActive = pathname === "/c/me/bots"@@ -71,12 +75,15 @@ function MeSidebar() {[blocked],)+ const retryDms = useCallback(() => { void refetch({ cancelRefetch: false }) }, [refetch])+const sidebar = useCallback(() => (<DmSidebardms={dms}activeDm={currentChannelId}blockedUserIds={blockedUserIds}loading={dmsLoading}+ loadError={initialError ? { retrying: isFetching, onRetry: retryDms } : undefined}onPickDm={enterDm}onShowFriends={onShowFriends}friendRequestCount={friendRequestCount}@@ -86,7 +93,7 @@ function MeSidebar() {machinesActive={machinesActive}botsActive={botsActive}/>- ), [dms, currentChannelId, dmsLoading, blockedUserIds, enterDm, onShowFriends, friendRequestCount, onShowMachines, onShowBots, friendsActive, machinesActive, botsActive])+ ), [dms, currentChannelId, dmsLoading, initialError, isFetching, retryDms, blockedUserIds, enterDm, onShowFriends, friendRequestCount, onShowMachines, onShowBots, friendsActive, machinesActive, botsActive])return sidebar()}diff --git a/src/web/src/components/community/shell/me-root-route.tsx b/src/web/src/components/community/shell/me-root-route.tsxnew file mode 100644index 000000000..3ff14b3ff--- /dev/null+++ b/src/web/src/components/community/shell/me-root-route.tsx@@ -0,0 +1,33 @@+"use client"++import { useEffect } from "react"+import { useCommunityModuleLocation } from "@/contexts/community/module-route"+import { useBreakpoint } from "@/hooks/use-mobile"+import { CommunityPendingFrame } from "@/components/community/shell/community-pending-frame"+import { useCommunityOnboarding } from "@/lib/community-onboarding"+import { getLastMeLeaf, pickMeLandingLocation } from "@/lib/community/last-me-location"+import { useSelector } from "@tanstack/react-store"+import { useQueryClient } from "@tanstack/react-query"+import { getCommunityRuntime } from "@/stores/community/runtime"++export default function MeListPage() {+ const { router } = useCommunityModuleLocation()+ const breakpoint = useBreakpoint()+ const onboarding = useCommunityOnboarding()+ const queryClient = useQueryClient()+ const runtime = getCommunityRuntime(queryClient)+ const ownerDeleteRootLanding = useSelector(runtime.serverEject, (state) => state.meRootLanding)+ const destination = breakpoint === "desktop"+ && !onboarding+ && !ownerDeleteRootLanding+ ? pickMeLandingLocation(getLastMeLeaf())+ : null++ useEffect(() => {+ if (!destination) return+ if (runtime.ui.get().onboardingState || runtime.serverEject.get().meRootLanding) return+ router.replace(destination)+ }, [destination, router, runtime])++ return destination ? <CommunityPendingFrame href={destination} /> : null+}diff --git a/src/web/src/components/community/shell/server-landing-route.intent.dom.test.tsx b/src/web/src/components/community/shell/server-landing-route.intent.dom.test.tsxnew file mode 100644index 000000000..61dc2c23a--- /dev/null+++ b/src/web/src/components/community/shell/server-landing-route.intent.dom.test.tsx@@ -0,0 +1,140 @@+import { beforeEach, expect, it, vi } from "vitest"+import { useLayoutEffect } from "react"+import { act, fireEvent, render, waitFor } from "@/test/react-dom-harness"+import { CommunityTestProvider } from "@/test/community-owner-fixture"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { CurrentUserProvider } from "@/contexts/community/current-user"+import { CommunityModuleRouteContext } from "@/contexts/community/module-route"+import { CommunityRouteContext, CommunityServerRouteContext } from "@/contexts/community/route-frame"+import { normalizeCommunityHref } from "@/lib/community/community-route"+import { communityKeys } from "@/lib/query-keys"+import { captureCommunityLiveSnapshotToken, publishCommunityLiveSnapshot } from "@/lib/community-db/sync"+import { serversProjectedQueryFn, useServer } from "@/hooks/community/use-servers"+import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"+import { beginOwnerServerDelete, commitOwnerServerDelete, createOwnerServerDeleteRouteToken, observeOwnerServerDeleteRouteCommit } from "@/lib/community/eject-server"+import { flushOwnerServerDeleteRouteCommit } from "@/hooks/community/community-ws/scope-eviction"+import { useCommunityNavigationController } from "./use-community-navigation-controller"+import ServerLandingRoute from "./server-landing-route"++const mocks = vi.hoisted(() => ({ push: vi.fn(), replace: vi.fn(), prefetch: vi.fn(), load: vi.fn(), breakpoint: "desktop" }))+vi.mock("next/navigation", () => ({ useRouter: () => ({ push: mocks.push, replace: mocks.replace, prefetch: mocks.prefetch }), usePathname: () => "/c/me", useSearchParams: () => new URLSearchParams() }))+vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: mocks.load }))+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mocks.breakpoint }))+vi.mock("@/components/brand/alook-loading/AlookLoading", () => ({ AlookLoading: () => null }))+beforeEach(() => { vi.clearAllMocks(); mocks.breakpoint = "desktop"; mocks.load.mockImplementation(() => new Promise(() => {})) })++function ServerRead({ enabled }: { enabled: boolean }) {+ useServer(enabled ? "target" : null)+ return null+}++async function setup(method: "push" | "pushImmediate", { cold = false, empty = false, mobile = false } = {}) {+ const { client, registry } = await createCommunityQueryOwner()+ const server = { id: "target", name: "Target", discriminator: "0001", description: "", icon: null, ownerId: "viewer" }+ mocks.breakpoint = mobile ? "mobile" : "desktop"+ mocks.load.mockResolvedValueOnce({ servers: [{ ...server, role: "owner", memberId: "membership" }] })+ await client.query({ queryKey: communityKeys.servers(), queryFn: serversProjectedQueryFn(getActiveAccountUnreadProjection(client), client) })+ const channels = empty ? [] : [{ id: "channel", name: "Channel", active: false, unread: false, muted: false, type: "text" as const }]+ if (!cold) {+ publishCommunityLiveSnapshot(client, {+ snapshot: { kind: "server-detail", data: { ...server, categories: [{ id: "category", name: "", private: 0, channels }] } },+ proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined },+ })+ client.setQueryData(communityKeys.server(server.id), server.id)+ }+ let release!: () => void+ const response = new Promise<void>(resolve => { release = resolve })+ mocks.load.mockImplementation(async (path: string) => {+ await response+ if (path.endsWith("/categories")) return { categories: [{ id: "category", name: "", private: 0 }] }+ if (path.endsWith("/channels")) return { channels: channels.map(channel => ({ ...channel, categoryId: "category" })) }+ throw new Error(`Unexpected request ${path}`)+ })+ const calls: string[] = []+ mocks.push.mockImplementation((href: string) => { calls.push(href) })+ mocks.replace.mockImplementation((href: string) => { calls.push(href) })+ const frame = { ...normalizeCommunityHref("/c/me"), revision: 0 }+ let navigation!: ReturnType<typeof useCommunityNavigationController>+ function Harness() {+ const current = useCommunityNavigationController(frame)+ useLayoutEffect(() => { navigation = current }, [current])+ const href = current.pendingHref ?? frame.href+ return <CommunityRouteContext value={{ breakpoint: "desktop", frame, navigation: current, ownerDeleteRouteScope: undefined }}>+ <button onClick={() => current[method]("/c/channels/target")}>Open server</button>+ <output data-testid="pending">{href}</output>+ <ServerRead enabled={href.startsWith("/c/channels/target")} />+ {href === "/c/channels/target" && <CommunityModuleRouteContext value={{ href, routeCommitted: false }}>+ <CommunityServerRouteContext value={{ serverId: server.id, serverParam: server.id }}><ServerLandingRoute /></CommunityServerRouteContext>+ </CommunityModuleRouteContext>}+ </CommunityRouteContext>+ }+ const view = render(<CommunityTestProvider client={client} registry={registry}>+ <CurrentUserProvider initialUser={{ id: "viewer", name: "Viewer", avatar: "V", email: "[email protected]" }}><Harness /></CurrentUserProvider>+ </CommunityTestProvider>)+ return { view, calls, release, client, registry, get navigation() { return navigation } }+}++it.each(["push", "pushImmediate"] as const)("keeps the actual landing consumer's leaf as the final native dispatch during %s", async method => {+ const test = await setup(method)+ const { view, calls } = test+ let releaseOlder!: (href: string) => void+ let older!: Promise<boolean>+ await act(async () => { older = test.navigation.resolveAndPush(() => new Promise(resolve => { releaseOlder = resolve })) })+ const oldIntent = test.navigation.captureIntent()+ fireEvent.click(view.getByRole("button", { name: "Open server" }))+ await waitFor(() => expect(mocks.replace).toHaveBeenCalledWith("/c/channels/target/channel"))+ expect(view.getByTestId("pending")).toHaveTextContent("/c/channels/target/channel")+ expect(calls).toEqual(["/c/channels/target/channel"])+ expect(oldIntent()).toBe(false)+ await act(async () => { releaseOlder("/c/channels/old/channel"); expect(await older).toBe(false) })+ expect(calls).toEqual(["/c/channels/target/channel"])+})++it.each(["push", "pushImmediate"] as const)("submits the root then the native leaf when cold server data arrives after %s", async method => {+ const { view, calls, release } = await setup(method, { cold: true })+ fireEvent.click(view.getByRole("button", { name: "Open server" }))+ expect(calls).toEqual(["/c/channels/target"])+ await act(async () => { release() })+ await waitFor(() => expect(calls).toEqual(["/c/channels/target", "/c/channels/target/channel"]))+})++it.each([{ empty: true }, { mobile: true }])("retains the root when the real landing consumer has no desktop leaf redirect: %j", async options => {+ const { view, calls } = await setup("push", options)+ fireEvent.click(view.getByRole("button", { name: "Open server" }))+ await act(async () => {})+ expect(calls).toEqual(["/c/channels/target"])+ expect(mocks.replace).not.toHaveBeenCalled()+ if (options.empty) expect(view.getByText("No channels yet")).toBeVisible()+})++it("finishes the current root after an older server deletion retires its in-flight detail proof", async () => {+ const { view, calls, release, client, registry } = await setup("push", { cold: true })+ const token = createOwnerServerDeleteRouteToken(client)+ act(() => {+ publishCommunityLiveSnapshot(client, {+ snapshot: { kind: "server-detail", data: { id: "deleted", name: "Deleted", discriminator: "0002", description: "", icon: null, ownerId: "viewer", categories: [{ id: "old-category", name: "", private: 0, channels: [{ id: "old-channel", name: "Old", active: false, unread: false }] }] } },+ proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined },+ })+ beginOwnerServerDelete(client, "deleted", token)+ expect(commitOwnerServerDelete(client, "deleted", token)).toBe(false)+ })+ fireEvent.click(view.getByRole("button", { name: "Open server" }))+ await waitFor(() => expect(mocks.load.mock.calls.some(([path]) => String(path).endsWith("/target/channels"))).toBe(true))+ const original = client.getQueryCache().find({ queryKey: communityKeys.server("target"), exact: true })!+ expect(original.state.fetchStatus).toBe("fetching")+ await act(async () => {+ observeOwnerServerDeleteRouteCommit(client, "/c/channels/target")+ expect(flushOwnerServerDeleteRouteCommit(client)).toEqual(["deleted"])+ release()+ })+ await waitFor(() => expect(calls.at(-1)).toBe("/c/channels/target/channel"))+ await waitFor(() => {+ expect(original.state.fetchStatus).toBe("idle")+ expect(original.state.error).toBeNull()+ })+ expect(client.getQueryCache().find({ queryKey: communityKeys.server("target"), exact: true })).toBe(original)+ expect(registry.collections.servers.get("deleted")).toBeUndefined()+ expect(registry.collections.servers.get("target")?.detailComplete).toBe(true)+ expect(original.state.error).toBeNull()+ expect(mocks.load.mock.calls.filter(([path]) => String(path).endsWith("/target/categories"))).toHaveLength(2)+})diff --git a/src/web/src/components/community/shell/server-landing-route.tsx b/src/web/src/components/community/shell/server-landing-route.tsxnew file mode 100644index 000000000..e4ec7ebfa--- /dev/null+++ b/src/web/src/components/community/shell/server-landing-route.tsx@@ -0,0 +1,54 @@+"use client"++import { useCommunityServerRoute } from "@/components/community/shell/community-route-context"+import { useEffect, useRef } from "react"+import { useCommunityModuleLocation } from "@/contexts/community/module-route"+import { CommunityPendingFrame } from "./community-pending-frame"+import { serverRootHref } from "@/lib/community/community-route"+import { useServer } from "@/hooks/community/use-servers"+import { useBreakpoint } from "@/hooks/use-mobile"+import { getLastChannel, resolveCommunityLandingHref } from "@/lib/community/last-channel"++export default function ServerDefaultPage() {+ const { serverId } = useCommunityServerRoute()+ const { router, searchParams } = useCommunityModuleLocation()+ const { server: currentServer } = useServer(serverId)+ const breakpoint = useBreakpoint()+ const replacingHrefRef = useRef<string | null>(null)++ useEffect(() => {+ if (breakpoint !== "desktop" || !currentServer) return+ const allChannels = currentServer.categories.flatMap((cat) => cat.channels)+ // Restore one remembered channel id, or use the first top-level channel+ // when there is no valid memory.+ const target = resolveCommunityLandingHref({+ serverId,+ channelIds: allChannels.filter((channel) => !channel.pending).map((channel) => channel.id),+ last: getLastChannel(serverId),+ breakpoint,+ })+ if (target !== `/c/channels/${encodeURIComponent(serverId)}`) {+ const search = searchParams.toString()+ const href = `${target}${search ? `?${search}` : ""}`+ if (replacingHrefRef.current === href) return+ replacingHrefRef.current = href+ router.replace(href)+ }+ }, [breakpoint, currentServer, serverId, router, searchParams])++ if (breakpoint !== "desktop") return null++ const allChannels = currentServer?.categories.flatMap((cat) => cat.channels) ?? []+ if (currentServer && allChannels.length === 0) {+ return (+ <div className="flex flex-1 flex-col items-center justify-center gap-2 text-muted-foreground">+ <span className="text-sm">No channels yet</span>+ <span className="text-xs">Create a channel from the sidebar to get started.</span>+ </div>+ )+ }++ const root = serverRootHref(serverId)+ const search = searchParams.toString()+ return <CommunityPendingFrame href={`${root}${search ? `?${search}` : ""}`} />+}diff --git a/src/web/src/components/community/shell/server-settings-route.tsx b/src/web/src/components/community/shell/server-settings-route.tsxnew file mode 100644index 000000000..b93192991--- /dev/null+++ b/src/web/src/components/community/shell/server-settings-route.tsx@@ -0,0 +1,16 @@+"use client"++import { useCommunityServerRoute } from "@/components/community/shell/community-route-context"+import { useEffect } from "react"+import { useCommunityModuleLocation } from "@/contexts/community/module-route"++export default function ServerSettingsRedirect() {+ const { serverId } = useCommunityServerRoute()+ const { router, searchParams } = useCommunityModuleLocation()+ useEffect(() => {+ const nextSearchParams = new URLSearchParams(searchParams.toString())+ nextSearchParams.set("settings", "1")+ router.replace(`/c/channels/${encodeURIComponent(serverId)}?${nextSearchParams.toString()}`)+ }, [serverId, router, searchParams])+ return null+}diff --git a/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx b/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsxnew file mode 100644index 000000000..ea370b7a1--- /dev/null+++ b/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx@@ -0,0 +1,111 @@+import { IsRestoringProvider } from "@tanstack/react-query"+import { useLayoutEffect } from "react"+import { beforeEach, expect, it, vi } from "vitest"+import { act, fireEvent, render, setupUser, waitFor } from "@/test/react-dom-harness"+import { CommunityTestProvider } from "@/test/community-owner-fixture"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { CurrentUserProvider } from "@/contexts/community/current-user"+import { CommunityRouteContext } from "@/contexts/community/route-frame"+import { normalizeCommunityHref, type CommunityCommittedFrame } from "@/lib/community/community-route"+import { communityKeys } from "@/lib/query-keys"+import { tid } from "@/lib/community/testids"+import { captureCommunityLiveSnapshotToken, publishCommunityLiveSnapshot } from "@/lib/community-db/sync"+import { createOwnerServerDeleteRouteToken } from "@/lib/community/eject-server"+import { serversProjectedQueryFn } from "@/hooks/community/use-servers"+import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"+import { useCommunityRuntime } from "@/stores/community/runtime"+import { ServerSidebarSlot } from "./server-sidebar-slot"+import { useCommunityNavigationController } from "./use-community-navigation-controller"++const mocks = vi.hoisted(() => ({ pathname: "/c/channels/target", push: vi.fn(), replace: vi.fn(), prefetch: vi.fn(), load: vi.fn() }))+vi.mock("next/link", async () => ({ default: (await import("@/test/community-link-mock")).CommunityLinkMock }))+vi.mock("next/navigation", () => ({ useRouter: () => ({ push: mocks.push, replace: mocks.replace, prefetch: mocks.prefetch }), usePathname: () => mocks.pathname, useSearchParams: () => new URLSearchParams() }))+vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: mocks.load }))+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "mobile", useIsMobile: () => true }))+vi.mock("@/hooks/community/use-server-members", () => ({ useServerMembers: () => ({ members: [] }) }))+vi.mock("@/hooks/community/use-server-panels", async original => ({ ...await original<typeof import("@/hooks/community/use-server-panels")>(), usePresence: () => {} }))+vi.mock("@/components/community/settings/server-settings", () => ({ ServerSettings: () => null }))+beforeEach(() => { vi.clearAllMocks(); mocks.pathname = "/c/channels/target"; mocks.load.mockImplementation(() => new Promise(() => {})) })++it.each([false, true])("keeps real same-server list, row and category nodes through native pending/commit and return, grouped=%s", async grouped => {+ const { client, registry } = await createCommunityQueryOwner()+ const server = { id: "target", name: "Target server", discriminator: "0001", description: "", icon: null, ownerId: "viewer" }+ const proof = { kind: "structural" as const, token: captureCommunityLiveSnapshotToken(client), signal: undefined }+ mocks.load.mockResolvedValueOnce({ servers: [{ ...server, role: "owner", memberId: "membership" }] })+ await client.query({ queryKey: communityKeys.servers(), queryFn: serversProjectedQueryFn(getActiveAccountUnreadProjection(client), client) })+ mocks.load.mockClear()+ publishCommunityLiveSnapshot(client, { snapshot: { kind: "server-detail", data: { ...server, categories: [{ id: "category", name: grouped ? "Group" : "", private: 0, channels: [{ id: "channel", name: "Target channel", active: false, unread: false, muted: false, type: "text" }] }] } }, proof })+ client.setQueryData(communityKeys.server(server.id), server.id)+ client.setQueryData(communityKeys.forumSidebarThreads(server.id), { threads: [], verifiedEpoch: 0, serverNow: new Date().toISOString(), serverClockOffsetMs: 0 })+ const token = createOwnerServerDeleteRouteToken(client)+ function Harness({ frame }: { frame: CommunityCommittedFrame }) {+ const navigation = useCommunityNavigationController(frame)+ const runtime = useCommunityRuntime()+ useLayoutEffect(() => {+ runtime.ui.actions.registerUiHandlers({ navigatePath: navigation.push, cancelPendingNavigation: navigation.cancelPendingNavigation })+ }, [navigation.push, navigation.cancelPendingNavigation, runtime.ui])+ return <CommunityRouteContext value={{ breakpoint: "mobile", frame, navigation, ownerDeleteRouteScope: { serverId: server.id, token } }}>+ <output data-testid="pending">{String(navigation.navigationPending)}</output>+ <button onClick={() => navigation.replace("/c/channels/target", { resume: true })}>Return</button>+ <ServerSidebarSlot serverId={server.id} href={navigation.pendingHref ?? frame.href} routeCommitted={!navigation.navigationPending} />+ </CommunityRouteContext>+ }+ const node = (href: string, revision: number) => <CommunityTestProvider client={client} registry={registry}>+ <CurrentUserProvider initialUser={{ id: "viewer", name: "Viewer", avatar: "V", email: "[email protected]" }}>+ <IsRestoringProvider value><Harness frame={{ ...normalizeCommunityHref(href), revision }} /></IsRestoringProvider>+ </CurrentUserProvider>+ </CommunityTestProvider>+ const view = render(node("/c/channels/target", 0))+ const scroll = await view.findByTestId(tid.channelSidebarScroll)+ const row = view.getByTestId(tid.channelRow("channel"))+ expect(row).toHaveAttribute("aria-roledescription", "sortable")+ const header = grouped ? view.getByText("Group") : null+ scroll.scrollTop = 37+ row.setAttribute("data-retained-row", "original")+ const assertNodes = () => {+ expect.soft(view.getByTestId(tid.channelSidebarScroll)).toBe(scroll)+ expect.soft(view.getByTestId(tid.channelSidebarScroll).scrollTop).toBe(37)+ expect.soft(view.getByTestId(tid.channelRow("channel"))).toBe(row)+ expect.soft(view.getByTestId(tid.channelRow("channel"))).toHaveAttribute("data-retained-row", "original")+ if (header) expect.soft(view.getByText("Group")).toBe(header)+ }+ fireEvent.click(row)+ expect(mocks.push).toHaveBeenCalledExactlyOnceWith("/c/channels/target/channel")+ expect(view.getByTestId("pending")).toHaveTextContent("true")+ assertNodes()+ expect(row).not.toHaveAttribute("aria-roledescription")+ fireEvent.contextMenu(view.getByTestId(tid.channelSidebarScroll), { button: 2 })+ expect(view.queryByRole("menu")).toBeNull()+ mocks.pathname = "/c/channels/target/channel"+ view.rerender(node(mocks.pathname, 1))+ await waitFor(() => expect(view.getByTestId("pending")).toHaveTextContent("false"))+ assertNodes()+ fireEvent.click(view.getByRole("button", { name: "Return" }))+ expect(mocks.replace).toHaveBeenCalledExactlyOnceWith("/c/channels/target")+ expect(view.getByTestId("pending")).toHaveTextContent("true")+ assertNodes()+ mocks.pathname = "/c/channels/target"+ await act(async () => { view.rerender(node(mocks.pathname, 2)) })+ await waitFor(() => expect(view.getByTestId("pending")).toHaveTextContent("false"))+ assertNodes()+ expect(row).toHaveAttribute("aria-roledescription", "sortable")+ const user = setupUser()+ act(() => row.focus())+ await user.keyboard(" ")+ expect(row).toHaveAttribute("aria-pressed", "true")+ await user.keyboard("{Escape}")+ assertNodes()+ if (header) {+ fireEvent.click(header)+ expect(view.queryByTestId(tid.channelRow("channel"))).toBeNull()+ fireEvent.click(header)+ expect(view.getByTestId(tid.channelRow("channel"))).toBeVisible()+ expect(view.getByText("Group")).toBe(header)+ expect(view.getByTestId(tid.channelSidebarScroll)).toBe(scroll)+ }+ fireEvent.contextMenu(scroll, { button: 2 })+ expect(await view.findByRole("menuitem", { name: "Create category" })).toBeVisible()+ await user.keyboard("{Escape}")+ expect(mocks.load.mock.calls.map(([path]) => path)).toEqual(["/api/community/channels/channel/messages?entry=1"])+ expect(mocks.load.mock.calls.every(([, options]) => !options?.method || options.method === "GET")).toBe(true)+})diff --git a/src/web/src/components/community/shell/server-sidebar-slot.target.dom.test.tsx b/src/web/src/components/community/shell/server-sidebar-slot.target.dom.test.tsxnew file mode 100644index 000000000..396056e3a--- /dev/null+++ b/src/web/src/components/community/shell/server-sidebar-slot.target.dom.test.tsx@@ -0,0 +1,63 @@+import { IsRestoringProvider } from "@tanstack/react-query"+import { beforeEach, expect, it, vi } from "vitest"+import { render } from "@/test/react-dom-harness"+import { CommunityTestProvider } from "@/test/community-owner-fixture"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { CurrentUserProvider } from "@/contexts/community/current-user"+import { CommunityRouteContext } from "@/contexts/community/route-frame"+import { normalizeCommunityHref } from "@/lib/community/community-route"+import { communityKeys } from "@/lib/query-keys"+import { captureCommunityLiveSnapshotToken, publishCommunityLiveSnapshot } from "@/lib/community-db/sync"+import { createOwnerServerDeleteRouteToken } from "@/lib/community/eject-server"+import { ServerSidebarSlot } from "./server-sidebar-slot"++const mocks = vi.hoisted(() => ({ pathname: "/c/channels/source/channel", replace: vi.fn(), members: vi.fn(), presence: vi.fn(), props: vi.fn(), load: vi.fn() }))+vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: mocks.replace }), usePathname: () => mocks.pathname, useSearchParams: () => new URLSearchParams("settings=1") }))+vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: mocks.load }))+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop", useIsMobile: () => false }))+vi.mock("@/hooks/community/use-server-members", () => ({ useServerMembers: (id: string | null) => { mocks.members(id); return { members: [] } } }))+vi.mock("@/hooks/community/use-server-panels", () => ({ usePresence: mocks.presence }))+vi.mock("@/components/community/channels/channel-sidebar-tree-owner", () => ({ ChannelSidebarRevealBoundary: (props: { serverName: string; categories: Array<{ channels: Array<{ id: string; name: string }> }> }) => {+ mocks.props(props)+ return <aside><h1>{props.serverName}</h1><input aria-label="Sidebar state" />{props.categories.flatMap(category => category.channels).map(channel => <span key={channel.id}>{channel.name}</span>)}</aside>+} }))+vi.mock("@/components/community/settings/server-settings", () => ({ ServerSettings: () => <div>Server settings</div> }))+beforeEach(() => { vi.clearAllMocks(); mocks.pathname = "/c/channels/source/channel"; mocks.load.mockImplementation(() => new Promise(() => {})) })++it("uses the canonical target sidebar before commit, retaining its node while deferred side effects gain the real route", async () => {+ const { client, registry } = await createCommunityQueryOwner()+ const server = { id: "target", name: "Target server", discriminator: "0001", description: "", icon: null, ownerId: "viewer" }+ const proof = { kind: "structural" as const, token: captureCommunityLiveSnapshotToken(client), signal: undefined }+ publishCommunityLiveSnapshot(client, { snapshot: { kind: "servers", data: { servers: [{ ...server, initial: "T", active: false, unread: false, mentions: 0, isOwner: true, role: "owner", memberId: "membership" }] } }, proof })+ publishCommunityLiveSnapshot(client, { snapshot: { kind: "server-detail", data: { ...server, categories: [{ id: "category", name: "Main", private: 0, channels: [{ id: "channel", name: "Target channel", active: false, unread: false, muted: false, type: "text" }] }] } }, proof })+ client.setQueryData(communityKeys.servers(), [server.id])+ client.setQueryData(communityKeys.server(server.id), server.id)+ const sourceToken = createOwnerServerDeleteRouteToken(client)+ const targetToken = createOwnerServerDeleteRouteToken(client)+ const node = (committed: boolean) => <CommunityTestProvider client={client} registry={registry}>+ <CurrentUserProvider initialUser={{ id: "viewer", name: "Viewer", avatar: "V", email: "[email protected]" }}>+ <IsRestoringProvider value>+ <CommunityRouteContext value={{ frame: { ...normalizeCommunityHref(mocks.pathname), revision: committed ? 2 : 1 }, navigation: { captureIntent: () => () => true, navigationPending: !committed, pendingHref: committed ? null : "/c/channels/target?settings=1" }, ownerDeleteRouteScope: { serverId: committed ? "target" : "source", token: committed ? targetToken : sourceToken } } as never}>+ <ServerSidebarSlot serverId="target" href="/c/channels/target?settings=1" routeCommitted={committed} />+ </CommunityRouteContext>+ </IsRestoringProvider>+ </CurrentUserProvider>+ </CommunityTestProvider>+ const view = render(node(false))+ expect(view.getByText("Target server")).toBeVisible()+ expect(view.getByText("Target channel")).toBeVisible()+ const input = view.getByRole("textbox") as HTMLInputElement+ input.value = "Target state"+ expect(mocks.members).toHaveBeenLastCalledWith(null)+ expect(mocks.presence).toHaveBeenLastCalledWith(null)+ expect(mocks.props).toHaveBeenLastCalledWith(expect.objectContaining({ onCreateChannel: undefined, onOpenSettings: undefined }))+ expect(view.queryByText("Server settings")).toBeNull()+ expect(mocks.replace).not.toHaveBeenCalled()+ expect(mocks.load).not.toHaveBeenCalled()+ mocks.pathname = "/c/channels/target"+ view.rerender(node(true))+ expect(view.getByRole("textbox")).toBe(input)+ expect(input).toHaveValue("Target state")+ expect(mocks.members).toHaveBeenLastCalledWith("target")+ expect(mocks.presence).toHaveBeenLastCalledWith("target")+})diff --git a/src/web/src/components/community/shell/server-sidebar-slot.tsx b/src/web/src/components/community/shell/server-sidebar-slot.tsxindex 152b3e329..cd14ede34 100644--- a/src/web/src/components/community/shell/server-sidebar-slot.tsx+++ b/src/web/src/components/community/shell/server-sidebar-slot.tsx@@ -16,6 +16,7 @@ import {communityServerId,serverModalMarkerCleanupHref,resolveCommunityModulePlan,+ normalizeCommunityHref,} from "@/lib/community/community-route"import { useBreakpoint } from "@/hooks/use-mobile"import { ChannelSidebarRevealBoundary } from "@/components/community/channels/channel-sidebar-tree-owner"@@ -25,7 +26,6 @@ import { validateIconSourceFile } from "@/lib/community/image-crop"import type { SettingsSection } from "@/components/community/settings/settings-types"import { canManageServer, isForum, notifLevelDisplay, type ChannelType } from "@alook/shared"import { readCommunityProfile } from "@/lib/community/profile-read"-import { useCurrentChannelId, useCurrentChannelMeta } from "@/stores/community"import { useCurrentUser } from "@/contexts/community/current-user"import {useServer,@@ -80,24 +80,26 @@ import {useCanonicalProfilesByUserId,useOptionalCommunityDbRegistry,useTrustedRestoredPrimary,+ useRouteChannelProjection,} from "@/lib/community-db/projections"-export function ServerSidebarSlot({ serverId }: { serverId: string }) {+export function ServerSidebarSlot({ serverId, href, routeCommitted = true }: { serverId: string; href?: string; routeCommitted?: boolean }) {const { frame, ownerDeleteRouteScope } = useCommunityRouteFrame()- if (frame.scope.kind !== "server" || frame.scope.serverId !== serverId- || ownerDeleteRouteScope?.serverId !== serverId) return null- return <ServerSidebar key={serverId} serverId={serverId} />+ const target = normalizeCommunityHref(href ?? frame.href)+ if (target.scope.kind !== "server" || target.scope.serverId !== serverId) return null+ return <ServerSidebar key={serverId} serverId={serverId} href={target.href} routeCommitted={routeCommitted+ && frame.scope.kind === "server" && frame.scope.serverId === serverId && ownerDeleteRouteScope?.serverId === serverId} />}-function ServerSidebar({ serverId }: { serverId: string }) {- const { frame, navigation, ownerDeleteRouteScope } = useCommunityRouteFrame()+function ServerSidebar({ serverId, href, routeCommitted }: { serverId: string; href: string; routeCommitted: boolean }) {+ const { navigation, ownerDeleteRouteScope } = useCommunityRouteFrame()const searchParams = useSearchParams()const pathname = usePathname()- const modulePlan = resolveCommunityModulePlan(frame.pathname)+ const modulePlan = resolveCommunityModulePlan(href)const routeChannelId = modulePlan.main.kind === "server-conversation" ? modulePlan.main.leafId : nullconst queryClient = useQueryClient()- const ownerDeleteRouteToken = ownerDeleteRouteScope!.token- const ownerDeleteRouteProtected = useSelector(getCommunityRuntime(queryClient).serverEject, (state) => state.transactions.has(serverId) || state.tombstones.get(ownerDeleteRouteToken) === serverId)+ const ownerDeleteRouteToken = routeCommitted && ownerDeleteRouteScope?.serverId === serverId ? ownerDeleteRouteScope.token : undefined+ const ownerDeleteRouteProtected = useSelector(getCommunityRuntime(queryClient).serverEject, (state) => state.transactions.has(serverId) || Boolean(ownerDeleteRouteToken && state.tombstones.get(ownerDeleteRouteToken) === serverId))const hasChannel = !!routeChannelIdconst breakpoint = useBreakpoint()@@ -114,13 +116,13 @@ function ServerSidebar({ serverId }: { serverId: string }) {const {server: currentServer,data: authoritativeServer,- } = useServer(ownerDeleteRouteProtected ? null : serverId)+ } = useServer(ownerDeleteRouteProtected || serverAccessRevoked ? null : serverId)const sidebarCategories = useMemo(() => currentServer?.categories ?? [],[currentServer],)- const sidebarHintOnly = Boolean(currentServer && !authoritativeServer)- const membersHook = useServerMembers(currentServer ? serverId : null)+ const sidebarHintOnly = !routeCommitted || Boolean(currentServer && !authoritativeServer)+ const membersHook = useServerMembers(routeCommitted && currentServer ? serverId : null)const profilesByUserId = useCanonicalProfilesByUserId()const enrichedMembers = useMemo(() =>@@ -142,13 +144,14 @@ function ServerSidebar({ serverId }: { serverId: string }) {}),[currentUser.id, membersHook.members, profilesByUserId],)- const isAdmin = canManageServer(useViewerServerRole(serverId, currentUser.id))- usePresence(currentServer ? serverId : null)+ const role = useViewerServerRole(serverId, currentUser.id)+ const isAdmin = routeCommitted && canManageServer(role)+ usePresence(routeCommitted && currentServer ? serverId : null)const notifs = useNotificationSettings()const notifLevel = resolveServerNotificationDisplayLevel(notifs.server[serverId])const channelNotif = notifs.channel- const currentChannelId = useCurrentChannelId()- const currentChannelMeta = useCurrentChannelMeta()+ const currentChannelId = routeChannelId+ const currentChannelMeta = useRouteChannelProjection(routeChannelId)const activeForumThreadId = useMemo(() => {if (!currentChannelId || !currentChannelMeta?.parentChannelId) return nullconst parent = sidebarCategories@@ -212,7 +215,7 @@ function ServerSidebar({ serverId }: { serverId: string }) {onSuccess: ({ serverId: deletedServerId, isUiCurrent }, { needsNavigation }) => {if (isUiCurrent?.()) toast("Server deleted")clearLastChannel(deletedServerId)- if (!needsNavigation) return+ if (!needsNavigation || !ownerDeleteRouteToken) returnvoid (async () => {const allowed = new Set([...communityDb!.collections.serverMemberships.values()].filter((row) => row.viewer && row.userId === currentUser.id).map((row) => row.serverId))const survivor = [...communityDb!.collections.servers.values()].filter((server) => allowed.has(server.id)).sort((a, b) => (a.position ?? 0) - (b.position ?? 0)).find((server) => server.id !== deletedServerId)@@ -254,7 +257,7 @@ function ServerSidebar({ serverId }: { serverId: string }) {// transient read failure. The ref prevents a re-fire during navigation.const ejectedRef = useRef(false)useEffect(() => {- if (ejectedRef.current) return+ if (!routeCommitted || ejectedRef.current) returnif (navigation.navigationPending&& communityServerId(navigation.pendingHref ?? "") !== serverId) returnif (typeof window !== "undefined"@@ -281,7 +284,7 @@ function ServerSidebar({ serverId }: { serverId: string }) {router.replace(destination)},})- }, [cancelPendingNavigation, currentUser.id, navigation.navigationPending, navigation.pendingHref, pathname, serverAccessRevoked, serverId, serversList.isLiveAuthoritative, serversList.isSuccess, serversList.isFetching, serversList.servers, router, searchParams, queryClient])+ }, [routeCommitted, cancelPendingNavigation, currentUser.id, navigation.navigationPending, navigation.pendingHref, pathname, serverAccessRevoked, serverId, serversList.isLiveAuthoritative, serversList.isSuccess, serversList.isFetching, serversList.servers, router, searchParams, queryClient])// Reset the guard when the URL changes to a NEW server id — otherwise// navigating server → dangling-server → server would leave the ref// latched and skip the eject.@@ -290,7 +293,7 @@ function ServerSidebar({ serverId }: { serverId: string }) {}, [serverId])const [serverSettingsOpen, setServerSettingsOpen] = useAtom(useCreateAtom(false))- const settingsView = useCommunityViewSource("server-settings:" + serverId, serverSettingsOpen)+ const settingsView = useCommunityViewSource("server-settings:" + serverId, routeCommitted && serverSettingsOpen)const [settingsSection, setSettingsSection] = useAtom(useCreateAtom<SettingsSection>("overview"))const [invitePopoverOpen, setInvitePopoverOpen] = useAtom(useCreateAtom(false))const [pendingIconCrop, setPendingIconCrop] = useAtom(useCreateAtom<{ src: string; fileName: string } | null>(null))@@ -311,10 +314,10 @@ function ServerSidebar({ serverId }: { serverId: string }) {// and the URL query string carrying it — was already gone by then, so the// dialog silently never opened.)useEffect(() => {- if (communityServerId(pathname) !== serverId) return+ if (!routeCommitted || communityServerId(pathname) !== serverId) returnif (searchParams.get("settings") === "1") setServerSettingsOpen(true)if (searchParams.get("invite") === "1") setInvitePopoverOpen(true)- }, [pathname, serverId, searchParams, setInvitePopoverOpen, setServerSettingsOpen])+ }, [routeCommitted, pathname, serverId, searchParams, setInvitePopoverOpen, setServerSettingsOpen])useEffect(() => {// These flags land on the bare `/c/channels/:serverId` URL@@ -326,7 +329,7 @@ function ServerSidebar({ serverId }: { serverId: string }) {// wins. Mobile intentionally remains on the server root and must consume// the one-shot marker there instead of waiting for a redirect that never// runs.- if (ownerDeleteRouteProtected || communityServerId(pathname) !== serverId) return+ if (!routeCommitted || ownerDeleteRouteProtected || communityServerId(pathname) !== serverId) returnconst search = searchParams.toString()const currentHref = `${pathname}${search ? `?${search}` : ""}`const cleanupHref = serverModalMarkerCleanupHref(currentHref, {@@ -350,6 +353,7 @@ function ServerSidebar({ serverId }: { serverId: string }) {hasChannel,currentServer,ownerDeleteRouteProtected,+ routeCommitted,])const categories = useMemo(() => sidebarCategories.map((category) => ({diff --git a/src/web/src/components/community/shell/shell-frame-contract.test.ts b/src/web/src/components/community/shell/shell-frame-contract.test.tsindex 50e36c112..c554b6246 100644--- a/src/web/src/components/community/shell/shell-frame-contract.test.ts+++ b/src/web/src/components/community/shell/shell-frame-contract.test.ts@@ -26,7 +26,8 @@ describe("ShellFrame public contract", () => {const shellView = readWeb("src/components/community/shell/shell-frame-view.tsx")expect(shellView.match(/<DmSidebarSlot\b/g)).toHaveLength(1)expect(readWeb("src/app/c/@sidebar/me/layout.tsx")).not.toContain("DmSidebarSlot")- expect(readWeb("src/app/c/@sidebar/channels/[serverId]/layout.tsx")).toContain("serverId={serverId}")+ expect(shellView.match(/<ServerSidebarSlot\b/g)).toHaveLength(1)+ expect(readWeb("src/app/c/@sidebar/channels/[serverId]/layout.tsx")).not.toContain("ServerSidebarSlot")})it("keeps shell-frame as orchestration with one public component", () => {diff --git a/src/web/src/components/community/shell/shell-frame-view.dom.test.ts b/src/web/src/components/community/shell/shell-frame-view.dom.test.tsindex 133c2a5fa..14591eab2 100644--- a/src/web/src/components/community/shell/shell-frame-view.dom.test.ts+++ b/src/web/src/components/community/shell/shell-frame-view.dom.test.ts@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { act, render } from "@/test/react-dom-harness"import { ShellFrameView } from "./shell-frame-view"import { CommunitySessionPendingFrame } from "./community-session-pending-frame"-import type { CommunityCheckpointPlan, CommunitySurface } from "@/lib/community/community-route"+import { normalizeCommunityHref, resolveCommunityCheckpointPlan, type CommunityCheckpointPlan, type CommunitySurface } from "@/lib/community/community-route"import {COMMUNITY_LAYOUT_PREPAINT_ATTRIBUTE,desktopUserBarInitialOverlayCssWidth,@@ -50,6 +50,9 @@ vi.mock("@/components/community/channels/dm-route", () => ({return createElement("main", { "data-dm-target": dmId, "data-committed": String(routeCommitted) }, "Cached DM")},}))+vi.mock("./community-module-route", () => ({+ CommunityModuleRoute: ({href, routeCommitted}: {href: string; routeCommitted: boolean}) => createElement("main", {"data-module-target": href, "data-committed": String(routeCommitted)}, createElement("input", {"aria-label": "Retained module state"})),+}))vi.mock("react-resizable-panels", () => ({useDefaultLayout: (options: Record<string, unknown>) => {mocks.defaultLayoutOptions(options)@@ -124,6 +127,7 @@ vi.mock("@/components/ui/app-surface", () => ({vi.mock("./shell", () => ({Shell: ({ children, ...props }: Record<string, unknown>) => createElement("div", { ...props, "data-shell-root": "" }, children as ReactNode),}))+vi.mock("./server-sidebar-slot", () => ({ ServerSidebarSlot: () => null }))vi.mock("./dm-sidebar-slot", () => ({ DmSidebarSlot: () => null }))vi.mock("./server-rail", () => ({ServerRail: (props: Record<string, unknown>) => {@@ -230,6 +234,24 @@ const extensionProps = {let animateDescriptor: PropertyDescriptor | undefineddescribe("ShellFrameView", () => {+ it("keeps neutral root presentation under the same host before a target consumer takes over", () => {+ const common = { ...extensionProps, breakpoint: "unknown" as const, sidebar: () => null, rail, profile, inbox }+ const root: CommunityCheckpointPlan = { ...committedCheckpoint("/c", "list"), main: { kind: "module-route", href: "/c", module: "route-resolution" } }+ const target: CommunityCheckpointPlan = { ...committedCheckpoint("/c/me/friends", "list"), main: { kind: "module-route", href: "/c/me/friends", module: "friends" } }+ const view = render(createElement(ShellFrameView, { ...common, checkpoint: root }))+ expect(view.container.querySelector('[data-slot="community-shell-root"]')).toBeNull()+ expect(view.container.querySelector('[aria-label="Loading community"][aria-busy="true"]')).not.toBeNull()+ expect(view.container.querySelector('[data-server-rail], [data-user-bar], [data-shell-overlays]')).toBeNull()+ expect(view.container.querySelector('[data-module-target="/c"]')).not.toBeNull()+ view.rerender(createElement(ShellFrameView, { ...common, breakpoint: "desktop", checkpoint: target, routeCommitted: false }))+ const input = view.getByRole("textbox") as HTMLInputElement+ input.value = "Target draft"+ expect(view.container.querySelector('[data-slot="community-shell-root"]')).not.toBeNull()+ view.rerender(createElement(ShellFrameView, { ...common, breakpoint: "desktop", checkpoint: target, routeCommitted: true }))+ expect(view.getByRole("textbox")).toBe(input)+ expect(input).toHaveValue("Target draft")+ })+beforeEach(() => {vi.unstubAllGlobals()mocks.onLayoutChanged.mockClear()@@ -268,6 +290,26 @@ describe("ShellFrameView", () => {vi.unstubAllGlobals()})+ it.each(["/c/channels/s2/c2?threadView=full", "/c/me/friends?tab=new", "/c/me/bots?audit=b1", "/c/me/machines?reconnect=m1"])("retains the selected real-consumer slot through commit for %s", href => {+ const source = {...normalizeCommunityHref("/c/channels/s1/c1"), revision: 1}+ const target = {...normalizeCommunityHref(href.split("?")[0]!), revision: 2}+ const props = (committed: boolean) => ({...extensionProps, breakpoint: "desktop" as const, routeCommitted: committed, rail, profile, inbox,+ sidebar: () => createElement("sidebar-content"), checkpoint: resolveCommunityCheckpointPlan({committedFrame: committed ? target : source, targetHref: href, pending: !committed, targetReady: true})})+ const view = render(createElement(ShellFrameView, props(false), createElement("old-next-page")))+ const body = view.container.querySelector("[data-module-target]")!+ const input = view.getByLabelText("Retained module state") as HTMLInputElement+ input.value = "Retained"+ expect(body).toHaveAttribute("data-module-target", href)+ expect(body).toHaveAttribute("data-committed", "false")+ expect(view.container.querySelector("old-next-page")).toBeNull()+ view.rerender(createElement(ShellFrameView, props(true), createElement("new-next-page")))+ expect(view.container.querySelector("[data-module-target]")).toBe(body)+ expect(view.getByLabelText("Retained module state")).toBe(input)+ expect(input).toHaveValue("Retained")+ expect(body).toHaveAttribute("data-committed", "true")+ expect(view.container.querySelector("new-next-page")).toBeNull()+ })+it("mounts the selected DM before Next publication and retains the same body at commit", () => {const props = (dmId: string, routeCommitted = false) => ({...extensionProps, breakpoint: "desktop" as const, routeCommitted, rail, profile, inbox,@@ -890,7 +932,6 @@ describe("ShellFrameView", () => {expect(renderer.container.querySelector("[data-channel-loading-frame]")).not.toBeNull()expect(mocks.pendingProps).toHaveBeenLastCalledWith(expect.objectContaining({href: "/c/channels/s1/c2",- conversationSubtype: undefined,}))expect(renderer.container.querySelector("[data-community-mobile-transition]")).toBeNull()@@ -914,7 +955,6 @@ describe("ShellFrameView", () => {main: {kind: "target-skeleton",href: "/c/channels/s1/c3",- conversationSubtype: "thread",},},},@@ -922,7 +962,6 @@ describe("ShellFrameView", () => {))expect(mocks.pendingProps).toHaveBeenLastCalledWith(expect.objectContaining({href: "/c/channels/s1/c3",- conversationSubtype: "thread",}))renderer.rerender(createElement(ShellFrameView,diff --git a/src/web/src/components/community/shell/shell-frame-view.tsx b/src/web/src/components/community/shell/shell-frame-view.tsxindex 368ba9cc4..4270f1134 100644--- a/src/web/src/components/community/shell/shell-frame-view.tsx+++ b/src/web/src/components/community/shell/shell-frame-view.tsx@@ -4,13 +4,17 @@ import { MobilePage } from "./mobile-page"import { DmRoute } from "@/components/community/channels/dm-route"import { ChannelSidebarSkeleton } from "@/components/community/channels/channel-sidebar"import { DmSidebarSkeleton } from "@/components/community/channels/dm-sidebar"+import { CommunitySessionPendingFrame } from "./community-session-pending-frame"import { CommunityPendingFrame } from "./community-pending-frame"+import { CommunityModuleRoute } from "./community-module-route"+import { communityServerId, resolveCommunityModulePlan } from "@/lib/community/community-route"import { ServerRail } from "./server-rail"import { UserBar } from "./user-bar"import { InboxPopover } from "./community-inbox-popover"import { ShellFrameOverlays } from "./shell-frame-overlays"import { CommunityShellLayout } from "./community-shell-layout"import { DmSidebarSlot } from "./dm-sidebar-slot"+import { ServerSidebarSlot } from "./server-sidebar-slot"import { ProfileCard } from "../social/profile-card"import type { Breakpoint } from "@/hooks/use-mobile"import type { CommunityCheckpointPlan } from "@/lib/community/community-route"@@ -60,6 +64,9 @@ export function ShellFrameView({dismissUserBarExtension,}: Props) {const { surface } = checkpoint+ const contentHref = checkpoint.main.kind === "keep" ? checkpoint.targetHref : checkpoint.main.href+ const modulePlan = resolveCommunityModulePlan(contentHref)+ const targetSidebar = modulePlan.sidebarconst { runningBots } = useRunningOwnedBots()const inboxElement = (<InboxPopover@@ -101,10 +108,16 @@ export function ShellFrameView({const main = checkpoint.main.kind === "dm-route" ? (<DmRoute key={`${profile.currentUser.id}/${checkpoint.main.dmId}`} dmId={checkpoint.main.dmId}routeCommitted={routeCommitted} />- ) : checkpoint.main.kind === "keep" || checkpoint.main.kind === "server-route" ? children : (- <CommunityPendingFrame href={checkpoint.targetHref} reserveBackSlot={surface === "detail"}- conversationSubtype={checkpoint.main.conversationSubtype} />+ ) : checkpoint.main.kind === "server-route" || checkpoint.main.kind === "module-route" ? (+ <CommunityModuleRoute key={`${profile.currentUser.id}/${checkpoint.main.kind === "server-route"+ ? `server:${communityServerId(checkpoint.main.href)}`+ : checkpoint.main.module}`} href={checkpoint.main.href} routeCommitted={routeCommitted} />+ ) : checkpoint.main.kind === "keep" ? children : (+ <CommunityPendingFrame href={checkpoint.targetHref} reserveBackSlot={surface === "detail"} />)+ if (modulePlan.route === "community-root-redirect") {+ return <CommunitySessionPendingFrame pathname={contentHref}>{main}</CommunitySessionPendingFrame>+ }const meDetail = surface === "detail" && checkpoint.targetHref.startsWith("/c/me/")return (<CommunityShellLayout@@ -119,7 +132,9 @@ export function ShellFrameView({aria-hidden={checkpoint.sidebar.kind !== "keep" || undefined}className="flex min-h-0 flex-1 flex-col">- <DmSidebarSlot visible={checkpoint.sidebar.kind === "keep"} />+ <DmSidebarSlot visible={checkpoint.sidebar.kind === "keep"} href={contentHref} routeCommitted={routeCommitted} />+ {targetSidebar.kind === "server" && <ServerSidebarSlot key={`${profile.currentUser.id}/${targetSidebar.serverId}`}+ serverId={targetSidebar.serverId} href={contentHref} routeCommitted={routeCommitted} />}{breakpoint === "desktop" ? sidebar() : sidebar({ noHeader: false })}</div>{checkpoint.sidebar.kind === "server-skeleton"diff --git a/src/web/src/components/community/shell/shell-frame.dom.test.ts b/src/web/src/components/community/shell/shell-frame.dom.test.tsindex ac4cdca83..e2e2c478a 100644--- a/src/web/src/components/community/shell/shell-frame.dom.test.ts+++ b/src/web/src/components/community/shell/shell-frame.dom.test.ts@@ -413,7 +413,7 @@ describe("ShellFrame orchestration", () => {expect(checkpoint()).toMatchObject({surface: "list",targetHref: "/c/channels/s1",- main: { kind: "keep" },+ main: { kind: "module-route", module: "server-landing" },})expect(mocks.inboxOptions).toHaveBeenLastCalledWith(expect.objectContaining({publishedHref: "/c/channels/s1/c1",@@ -442,7 +442,7 @@ describe("ShellFrame orchestration", () => {mode: "cold-scope",surface: "list",targetHref: "/c/channels/s2",- sidebar: { kind: "server-skeleton", serverId: "s2" },+ sidebar: { kind: "keep" },})expect(mocks.railOptions).toHaveBeenLastCalledWith(expect.objectContaining({activeServerId: "s1",@@ -467,7 +467,7 @@ describe("ShellFrame orchestration", () => {expect(checkpoint()).toMatchObject({mode: "warm-scope",- main: { kind: "keep" },+ main: { kind: "module-route", module: "server-landing" },})})@@ -505,12 +505,12 @@ describe("ShellFrame orchestration", () => {mode: "warm-scope",surface: "list",targetHref: "/c/channels/s2",- main: { kind: "keep" },+ main: { kind: "module-route", module: "server-landing" },})expect(mocks.railOptions).toHaveBeenLastCalledWith(expect.objectContaining({activeServerId: "s1",projectedView: "server",- projectedActiveServerId: "s1",+ projectedActiveServerId: "s2",}))})@@ -781,7 +781,7 @@ describe("ShellFrame orchestration", () => {const shell = renderInboxLifecycle()fireEvent.click(screen.getByRole("button", { name: "Open Inbox" }))shell.update({ frameHref: "/c/me" })- expect(shell.context.navigation.navigationPending).toBe(false)+ expect(shell.context.navigation.navigationPending).toBe(true)expect(mocks.openChanges).not.toHaveBeenCalled()shell.update({ publishedHref: "/c/me" })expectVisibleInbox()@@ -949,4 +949,19 @@ describe("ShellFrame orchestration", () => {})})+it.each(["header", "native"])("cancels an ordinary pending cross-scope target through the same %s Back handler", mode => {+ mocks.breakpoint.current = "mobile"+ mocks.currentHref.current = "/c/channels/s1/c1"+ mocks.pendingHref.current = "/c/me/friends?tab=new"+ mocks.navigationPending.current = true+ const view = render(createElement(ShellFrame, { ...baseProps, frameHref: "/c/channels/s1/c1" }))+ act(() => {+ if (mode === "native") window.dispatchEvent(new Event("alook:native-back", { cancelable: true }))+ else mocks.registerUiHandlers.mock.calls.at(-1)?.[0].goBackMobile()+ })+ expect(mocks.replace).toHaveBeenCalledExactlyOnceWith("/c/channels/s1/c1")+ view.unmount()+})++})diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsxindex 95c4e0b53..7d5675b32 100644--- a/src/web/src/components/community/shell/shell-frame.tsx+++ b/src/web/src/components/community/shell/shell-frame.tsx@@ -102,12 +102,6 @@ const [committedFrame, setCommittedFrame] = useAtom(useCreateAtom(initialCommittconst committedChannelId = committedModule.main.kind === "server-conversation"? committedModule.main.leafId : nullconst committedChannel = useRouteChannelProjection(committedChannelId)- const mobileParentPath = committedModule.sidebar.kind === "server"- && committedChannel?.id === committedChannelId- && committedChannel.serverId === committedModule.sidebar.serverId- && committedChannel.parentChannelId- ? channelHref(committedModule.sidebar.serverId, committedChannel.parentChannelId)- : route.parentPathconst target = navigation.pendingHref? normalizeCommunityHref(navigation.pendingHref): null@@ -120,15 +114,16 @@ const [committedFrame, setCommittedFrame] = useAtom(useCreateAtom(initialCommitt: nullconst targetServer = useServerTreeProjection(targetServerId)const targetRouteChannel = useRouteChannelProjection(targetChannelId)- const targetChannel = targetServer?.categories- ?.flatMap((category) => category.channels)- .find((channel) => channel.id === targetChannelId)- ?? targetRouteChannel- const targetConversationSubtype = targetChannel?.type === "text"- || targetChannel?.type === "forum"- || targetChannel?.type === "thread"- ? targetChannel.type- : undefined+ const displayedModule = targetModulePlan ?? committedModule+ const displayedChannelId = targetModulePlan ? targetChannelId : committedChannelId+ const displayedChannel = targetModulePlan ? targetRouteChannel : committedChannel+ const displayedRoute = target ? resolveCommunityRoute(target.href) : route+ const mobileParentPath = displayedModule.sidebar.kind === "server"+ && displayedChannel?.id === displayedChannelId+ && displayedChannel.serverId === displayedModule.sidebar.serverId+ && displayedChannel.parentChannelId+ ? channelHref(displayedModule.sidebar.serverId, displayedChannel.parentChannelId)+ : displayedRoute.parentPathconst targetReady = targetServerId? queryClient.getQueryData(communityKeys.server(targetServerId)) !== undefined|| targetServer !== undefined@@ -137,10 +132,10 @@ const [committedFrame, setCommittedFrame] = useAtom(useCreateAtom(initialCommitt: falseconst checkpoint = resolveCommunityCheckpointPlan({committedFrame,- targetHref: navigation.pendingHref,+ targetHref: navigation.pendingHref ?? (normalizeCommunityHref(navigation.publishedHref).leafKey !== committedFrame.leafKey+ ? navigation.entryIntent?.href ?? navigation.publishedHref : navigation.publishedHref),pending: navigation.navigationPending,targetReady,- targetConversationSubtype,})const projectedView = checkpoint.rail.kind === "target"? checkpoint.rail.viewdiff --git a/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts b/src/web/src/components/community/shell/shell.navigation-intent.dom.test.tsindex 829815427..bfc5e65dd 100644--- a/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts+++ b/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts@@ -4,6 +4,7 @@ import { CommunityTestProvider as QueryClientProvider } from "@/test/community-oimport { beforeEach, describe, expect, it, vi } from "vitest"import { act, fireEvent, render, screen } from "@/test/react-dom-harness"import {+ isPublishedNonStructuralCommit,normalizeCommunityHref,resolveCommunityCheckpointPlan,type CommunityCommittedFrame,@@ -37,6 +38,8 @@ vi.mock("./use-hydrated-client", () => ({ useHydratedClient: () => true }))vi.mock("@/hooks/community/use-running-owned-bots", () => ({useRunningOwnedBots: () => ({ runningBots: [] }),}))+vi.mock("@/components/brand/alook-loading/AlookLoading", () => ({ AlookLoading: () => null }))+vi.mock("./server-sidebar-slot", () => ({ ServerSidebarSlot: () => null }))vi.mock("./server-rail", () => ({ServerRail: ({ onHome }: { onHome: () => void }) => createElement("button", {onClick: onHome,@@ -101,7 +104,8 @@ function renderShell(breakpoint: "mobile" | "desktop" = "mobile", queryClient =navigation = useCommunityNavigationController(committedFrame)const checkpoint = resolveCommunityCheckpointPlan({committedFrame,- targetHref: navigation.pendingHref,+ targetHref: navigation.pendingHref ?? (normalizeCommunityHref(navigation.publishedHref).leafKey !== committedFrame.leafKey+ ? navigation.entryIntent?.href ?? navigation.publishedHref : navigation.publishedHref),pending: navigation.navigationPending,targetReady: false,})@@ -109,6 +113,7 @@ function renderShell(breakpoint: "mobile" | "desktop" = "mobile", queryClient =breakpoint,inboxOpening: false,checkpoint,+ routeCommitted: isPublishedNonStructuralCommit(committedFrame, navigation.publishedHref, navigation.pendingHref ?? navigation.publishedHref),sidebar: () => createElement("span", null, "Sidebar"),rail: { railProps: { onHome: () => navigation.push(nextTarget) } } as never,profile: { currentUser: { id: "viewer", name: "Viewer", avatar: "V" } } as never,@@ -146,8 +151,8 @@ function renderShell(breakpoint: "mobile" | "desktop" = "mobile", queryClient =}}-function beginInboxNavigation(shell: ReturnType<typeof renderShell>) {- act(() => shell.navigation.pushImmediate(target))+async function beginInboxNavigation(shell: ReturnType<typeof renderShell>) {+ await act(async () => shell.navigation.pushImmediate(target))}function expectPendingTarget(shell: ReturnType<typeof renderShell>) {@@ -170,25 +175,25 @@ beforeEach(() => {describe("Shell input and explicit navigation ownership", () => {it.each(["Target skeleton", "Blank area", "Draft input"])("keeps the target checkpoint after clicking %s",- (label) => {+ async (label) => {const shell = renderShell()- beginInboxNavigation(shell)+ await beginInboxNavigation(shell)fireEvent.click(label === "Draft input" ? screen.getByLabelText(label) : screen.getByText(label))expectPendingTarget(shell)expect(mocks.push).toHaveBeenCalledTimes(1)},)- it.each(["Enter", " ", "ArrowDown"])("keeps pending target while typing %s", (key) => {+ it.each(["Enter", " ", "ArrowDown"])("keeps pending target while typing %s", async (key) => {const shell = renderShell()- beginInboxNavigation(shell)+ await beginInboxNavigation(shell)fireEvent.keyDown(screen.getByLabelText("Draft input"), { key })expectPendingTarget(shell)})- it("keeps pending target while opening and closing Inbox", () => {+ it("keeps pending target while opening and closing Inbox", async () => {const shell = renderShell("desktop")- beginInboxNavigation(shell)+ await beginInboxNavigation(shell)fireEvent.click(screen.getByRole("button", { name: "Inbox" }))expect(screen.getByRole("button", { name: "Inbox" }).getAttribute("aria-expanded")).toBe("true")expectPendingTarget(shell)@@ -197,9 +202,9 @@ describe("Shell input and explicit navigation ownership", () => {expectPendingTarget(shell)})- it("supersedes a previous target at a real new navigation entry", () => {+ it("supersedes a previous target at a real new navigation entry", async () => {const shell = renderShell("desktop")- beginInboxNavigation(shell)+ await beginInboxNavigation(shell)fireEvent.click(screen.getByRole("button", { name: "New destination" }))expect(shell.navigation.pendingHref).toBe(nextTarget)expect(mocks.push.mock.calls.map(([href]) => href)).toEqual([target, nextTarget])@@ -250,9 +255,9 @@ describe("Shell input and explicit navigation ownership", () => {expect(shell.navigation.navigationPending).toBe(true)})- it("settles an exact frame without an extra click", () => {+ it("settles an exact frame without an extra click", async () => {const shell = renderShell()- beginInboxNavigation(shell)+ await beginInboxNavigation(shell)shell.commit(target, 1)expect(shell.navigation.pendingHref).toBeNull()expect(shell.navigation.navigationPending).toBe(false)@@ -260,9 +265,9 @@ describe("Shell input and explicit navigation ownership", () => {expect(screen.getByText("Committed content")).toBeTruthy()})- it("still clears pending target on popstate", () => {+ it("still clears pending target on popstate", async () => {const shell = renderShell()- beginInboxNavigation(shell)+ await beginInboxNavigation(shell)act(() => window.dispatchEvent(new Event("popstate")))expect(shell.navigation.pendingHref).toBeNull()expect(mocks.push).toHaveBeenCalledTimes(1)@@ -270,6 +275,20 @@ describe("Shell input and explicit navigation ownership", () => {})describe("current pending-commit qualification", () => {+ it.each(["friends", "bots", "machines"])("keeps the latest %s query selected when an older response publishes its shared pathname", module => {+ const shell = renderShell("desktop")+ const previous = `/c/me/${module}?target=old`+ const target = `/c/me/${module}?target=new`+ act(() => shell.navigation.push(previous))+ act(() => shell.navigation.replace(target))+ shell.commit(previous, 1)+ expect(shell.navigation.pendingHref).toBe(target)+ expect(shell.navigation.navigationPending).toBe(true)+ shell.publish(target)+ expect(shell.navigation.pendingHref).toBeNull()+ expect(shell.navigation.navigationPending).toBe(false)+ })+it.each(["frame-first", "publication-first"])("retains the structural target with a complete query URL, %s", (order) => {const shell = renderShell("desktop")const href = "/c/channels/s1?from=inbox"@@ -367,7 +386,7 @@ describe("Shell input and explicit navigation ownership", () => {const ownCommit = shell.navigation.captureIntent({ nextCommitHref: target })act(() => shell.navigation.push(target))shell.commit(target, 1, false)- expect(shell.navigation.navigationPending).toBe(false)+ expect(shell.navigation.navigationPending).toBe(true)expect(shell.navigation.publishedHref).not.toBe(target)expect(ownCommit()).toBe(true)shell.publish(target)diff --git a/src/web/src/components/community/shell/use-community-navigation-controller.dom.test.ts b/src/web/src/components/community/shell/use-community-navigation-controller.dom.test.tsindex ec4bdf496..6adc381a1 100644--- a/src/web/src/components/community/shell/use-community-navigation-controller.dom.test.ts+++ b/src/web/src/components/community/shell/use-community-navigation-controller.dom.test.ts@@ -72,6 +72,24 @@ describe("useCommunityNavigationController", () => {afterEach(() => vi.unstubAllGlobals())+ it.each(["/c/channels/s2/c2", "/c/channels/s2", "/c/me/dm2", "/c/messages/message2", "/c/me/friends"])("keeps a newer complete target when an older query for %s publishes first", async pathname => {+ const hook = await renderController()+ const previous = `${pathname}?target=old`+ const target = `${pathname}?target=new`+ await act(async () => hook.current.push(previous))+ await act(async () => hook.current.replace(target))+ mocks.pathname.current = pathname+ mocks.search.current = new URLSearchParams("target=old")+ mocks.frame.current = { ...normalizeCommunityHref(pathname), revision: 1 }+ await hook.rerender()+ expect(hook.current.pendingHref).toBe(target)+ expect(hook.current.navigationPending).toBe(true)+ mocks.search.current = new URLSearchParams("target=new")+ await hook.rerender()+ expect(hook.current.pendingHref).toBeNull()+ expect(hook.current.navigationPending).toBe(false)+ })+it("does not treat published pathname as commit and clears after frame evidence", async () => {const hook = await renderController()expect(hook.current.navigationPending).toBe(false)@@ -114,6 +132,11 @@ describe("useCommunityNavigationController", () => {mocks.pathname.current = "/c/channels/s2/c2"mocks.frame.current = { ...normalizeCommunityHref("/c/channels/s2"), revision: 2 }await hook.rerender()+ expect(hook.current.navigationPending).toBe(true)+ expect(hook.current.pendingHref).toBe("/c/channels/s2")+ await act(async () => hook.current.replace("/c/channels/s2/c2"))+ mocks.frame.current = { ...normalizeCommunityHref("/c/channels/s2/c2"), revision: 3 }+ await hook.rerender()expect(hook.current.navigationPending).toBe(false)expect(hook.current.pendingHref).toBeNull()})diff --git a/src/web/src/components/community/shell/use-community-navigation-controller.ts b/src/web/src/components/community/shell/use-community-navigation-controller.tsindex 1824fea1d..070631c0e 100644--- a/src/web/src/components/community/shell/use-community-navigation-controller.ts+++ b/src/web/src/components/community/shell/use-community-navigation-controller.ts@@ -60,7 +60,9 @@ export function useCommunityNavigationController(&& target.leafKey !== committedFrameRef.current.leafKey ? 1 : 0)return () => {if (!mountedRef.current) return false- if (revision === gateRef.current.revision && frameRevision === committedFrameRef.current.revision) return true+ if (revision === gateRef.current.revision && (frameRevision === committedFrameRef.current.revision+ || target !== null && targetRevision === committedFrameRef.current.revision+ && target?.leafKey === committedFrameRef.current.leafKey)) return trueconst settled = settledIntentRef.currentreturn targetHref !== null && settled !== null&& settled.revision === revision && gateRef.current.revision === revision + 1@@ -77,7 +79,6 @@ export function useCommunityNavigationController(const [navigationPending, setNavigationPending] = useAtom(useCreateAtom(false))const [pendingHref, setPendingHref] = useAtom(useCreateAtom<string | null>(null))const [entryIntent, setEntryIntent] = useAtom(useCreateAtom<{ href: string; resume?: boolean } | null>(null))- const parentReturnPending = hasPendingParentReturn({ entryIntent, navigationPending, pendingHref })const cancelPendingNavigation = useCallback(() => {supersedeNavigationIntent(gateRef.current)@@ -96,7 +97,7 @@ export function useCommunityNavigationController(targetHref: pendingHref,baselineRevision: pendingBaselineRevisionRef.current,})- if (!settled || parentReturnPending && !isPublishedNonStructuralCommit(committedFrame, publishedHref, pendingHref)) return+ if (!settled || !isPublishedNonStructuralCommit(committedFrame, publishedHref, pendingHref)) returnsettledIntentRef.current = {revision: gateRef.current.revision,frameRevision: committedFrame.revision,@@ -105,7 +106,7 @@ export function useCommunityNavigationController(supersedeNavigationIntent(gateRef.current)setNavigationPending(false)setPendingHref(null)- }, [committedFrame, parentReturnPending, pendingHref, publishedHref, setNavigationPending, setPendingHref])+ }, [committedFrame, pendingHref, publishedHref, setNavigationPending, setPendingHref])useEffect(() => {if (typeof window === "undefined") return@@ -116,7 +117,8 @@ export function useCommunityNavigationController(}}, [cancelPendingNavigation])- const submitNavigation = useCallback((submit: () => void) => {+ const submitNavigation = useCallback((submit: () => void, isCurrent?: () => boolean) => {+ if (isCurrent && !isCurrent()) returnconst revision = gateRef.current.revisiontry {submit()@@ -133,6 +135,7 @@ export function useCommunityNavigationController(beginNavigation(href)void prepareNavigationMetadata(queryClient, href, "foreground")supersedeNavigationIntent(gateRef.current)+ const isCurrent = captureIntent({ pendingCommitHref: href })pendingBaselineRevisionRef.current = committedFrame.revisionpendingBaselineLeafRef.current = committedFrame.leafKey// Publish the target checkpoint before Next starts the RSC transition.@@ -142,8 +145,8 @@ export function useCommunityNavigationController(setNavigationPending(true)setPendingHref(href)})- submitNavigation(() => router.push(...args))- }, [committedFrame.leafKey, committedFrame.revision, navigationPending, publishedHref, queryClient, router, setEntryIntent, setNavigationPending, setPendingHref, submitNavigation])+ submitNavigation(() => router.push(...args), isCurrent)+ }, [captureIntent, committedFrame.leafKey, committedFrame.revision, navigationPending, publishedHref, queryClient, router, setEntryIntent, setNavigationPending, setPendingHref, submitNavigation])const pushImmediate = useCallback((href: string, prepare?: (action?: Action) => void) => {setEntryIntent({ href })@@ -152,6 +155,7 @@ export function useCommunityNavigationController(prepare?.(action)void prepareNavigationMetadata(queryClient, href, "foreground")supersedeNavigationIntent(gateRef.current)+ const isCurrent = captureIntent({ pendingCommitHref: href })pendingBaselineRevisionRef.current = committedFrame.revisionpendingBaselineLeafRef.current = committedFrame.leafKey// Inbox promises a target checkpoint on the next paint. Publish it before@@ -160,8 +164,8 @@ export function useCommunityNavigationController(setNavigationPending(true)setPendingHref(href)})- submitNavigation(() => router.push(href))- }, [committedFrame.leafKey, committedFrame.revision, navigationPending, publishedHref, queryClient, router, setEntryIntent, setNavigationPending, setPendingHref, submitNavigation])+ submitNavigation(() => router.push(href), isCurrent)+ }, [captureIntent, committedFrame.leafKey, committedFrame.revision, navigationPending, publishedHref, queryClient, router, setEntryIntent, setNavigationPending, setPendingHref, submitNavigation])const replace = useCallback((href: string, options?: { resume?: boolean }) => {setEntryIntent({ href, ...(options?.resume ? { resume: true } : {}) })diff --git a/src/web/src/components/community/social/community-invite-card.tsx b/src/web/src/components/community/social/community-invite-card.tsxindex 5f68570ea..7fa246ed7 100644--- a/src/web/src/components/community/social/community-invite-card.tsx+++ b/src/web/src/components/community/social/community-invite-card.tsx@@ -1,6 +1,6 @@"use client"-import { useRouter } from "next/navigation"+import { useCommunityRouter } from "@/contexts/community/module-route"import { useUiHandlers } from "@/stores/community"import { useQuery } from "@tanstack/react-query"import { toast } from "sonner"@@ -47,7 +47,7 @@ export function CommunityInviteCard({token: stringperspective: MessagePerspective}) {- const router = useRouter()+ const router = useCommunityRouter()const uiHandlers = useUiHandlers()const { servers } = useServers()const joinServer = useJoinServer()diff --git a/src/web/src/components/community/social/friends-route.tsx b/src/web/src/components/community/social/friends-route.tsxnew file mode 100644index 000000000..b97ded4e6--- /dev/null+++ b/src/web/src/components/community/social/friends-route.tsx@@ -0,0 +1,150 @@+"use client"++import { ConversationResolutionErrorFrame } from "@/components/community/channels/conversation-resolution-error-frame"+import { FriendsPage } from "@/components/community/social/friends-page"+import { useMemo } from "react"+import { useCommunityModuleLocation } from "@/contexts/community/module-route"+import { useFriends } from "@/hooks/community/use-friends"+import { useUiHandlers } from "@/stores/community"+import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"+import { readCommunityProfile } from "@/lib/community/profile-read"+import {+ useSendFriendRequest,+ useAcceptFriendRequest,+ useRejectFriendRequest,+ useCancelBotFriendRequest,+ useRemoveFriend,+ useBlockUser,+ useUnblockUser,+ useCreateOrGetDm,+} from "@/hooks/community/mutations"+import { toast } from "sonner"+import { toastApiError } from "@/lib/api/client"++export default function MeFriendsPage() {+ const { router, searchParams } = useCommunityModuleLocation()+ const activeTab = searchParams.get("tab") === "new" ? "new" : "all"+ const { friends: rawFriends, pending, blocked, isPending: isLoading, data, isError, isFetching, refetch } = useFriends()+ const uiHandlers = useUiHandlers()+ const profilesByUserId = useCanonicalProfilesByUserId()+ const friends = useMemo(+ () =>+ rawFriends.map((f) => {+ const userId = f.userId ?? f.id+ const canonical = profilesByUserId.get(userId)+ const profile = canonical+ ? readCommunityProfile(canonical, userId)+ : { ...f, presence: f.status }+ return {+ ...f,+ name: profile.name,+ discriminator: profile.discriminator,+ avatar: profile.avatar,+ avatarVersion: profile.avatarVersion,+ status: profile.presence,+ statusEmoji: profile.statusEmoji,+ statusText: profile.statusText,+ }+ }),+ [profilesByUserId, rawFriends],+ )++ const sendFriendRequest = useSendFriendRequest()+ const acceptFriendRequest = useAcceptFriendRequest()+ const rejectFriendRequest = useRejectFriendRequest()+ const cancelBotFriendRequest = useCancelBotFriendRequest()+ const removeFriend = useRemoveFriend()+ const blockUser = useBlockUser()+ const unblockUser = useUnblockUser()+ const createOrGetDm = useCreateOrGetDm()++ if (isError && data === undefined) {+ return <ConversationResolutionErrorFrame title="Couldn't load friends" retrying={isFetching} onRetry={() => { void refetch({ cancelRefetch: false }) }} />+ }++ return (+ <FriendsPage+ friends={friends}+ pending={pending}+ blocked={blocked}+ loading={isLoading}+ activeTab={activeTab}+ onActiveTabChange={(tab) => {+ router.replace(tab === "new" ? "/c/me/friends?tab=new" : "/c/me/friends")+ }}+ onOpenProfile={(name, event, discriminator, userId) => {+ uiHandlers.openProfile?.(name, event, discriminator, userId)+ }}+ onBack={() => uiHandlers.goBackMobile?.()}+ onAccept={async (id) => {+ try {+ await acceptFriendRequest.mutateAsync({ friendshipId: id })+ toast("Friend request accepted")+ } catch (error) {+ toastApiError(error, "Failed to accept request")+ throw error+ }+ }}+ onReject={async (id) => {+ try {+ await rejectFriendRequest.mutateAsync({ friendshipId: id })+ } catch (error) {+ toastApiError(error, "Failed to reject request")+ throw error+ }+ }}+ onCancelRequest={({ id }) =>+ // Unified after migration 0065 — outgoing pendings (own or the owner's+ // bots') are real community_friendship rows cancelled via DELETE.+ cancelBotFriendRequest.mutate(+ { requestId: id },+ { onError: (e) => toastApiError(e, "Failed to cancel request") },+ )+ }+ onUnblock={(id) =>+ unblockUser.mutate(+ { userId: id },+ {+ onSuccess: () => toast("User unblocked"),+ onError: (e) => toastApiError(e, "Failed to unblock user"),+ },+ )+ }+ onSendRequest={async ({ userId, username }) => {+ try {+ await sendFriendRequest.mutateAsync({ userId, username })+ toast("Friend request sent")+ } catch (e) {+ toastApiError(e, "Failed to send friend request")+ }+ }}+ onRemoveFriend={(id) =>+ removeFriend.mutate(+ { friendshipId: id },+ {+ onSuccess: () => toast("Friend removed"),+ onError: (e) => toastApiError(e, "Failed to remove friend"),+ },+ )+ }+ onBlock={(id) =>+ blockUser.mutate(+ { userId: id },+ {+ onSuccess: () => toast("User blocked"),+ onError: (e) => toastApiError(e, "Failed to block user"),+ },+ )+ }+ onDm={async (userId) => {+ uiHandlers.cancelPendingNavigation?.()+ try {+ const data = await createOrGetDm.mutateAsync({ userId })+ if (data.conversation.id) uiHandlers.navigatePath?.(`/c/me/${data.conversation.id}`)+ } catch (e) {+ toastApiError(e, "Failed to open DM")+ }+ }}+ />+ )+}diff --git a/src/web/src/contexts/community/module-route.dom.test.tsx b/src/web/src/contexts/community/module-route.dom.test.tsxnew file mode 100644index 000000000..541096c4f--- /dev/null+++ b/src/web/src/contexts/community/module-route.dom.test.tsx@@ -0,0 +1,34 @@+import { expect, it, vi } from "vitest"+import { fireEvent, render } from "@/test/react-dom-harness"+import { CommunityRouteContext } from "./route-frame"+import { CommunityModuleRouteContext, useCommunityModuleLocation, useCommunityRouter } from "./module-route"++const next = vi.hoisted(() => ({ push: vi.fn(), replace: vi.fn() }))+vi.mock("next/navigation", () => ({ useRouter: () => next, useSearchParams: () => new URLSearchParams("published=old") }))+function Entry() {+ const router = useCommunityRouter()+ const location = useCommunityModuleLocation()+ return <><button onClick={() => router.push("/c/channels/target/thread?msg=opener")}>Open target</button>+ <button onClick={() => location.router.replace("/c/me/friends?tab=new")}>Select tab</button>+ <span>{location.searchParams.toString()}</span></>+}+it.each([false, true])("uses the existing intent owner for all module and nested entry callbacks (committed=%s)", routeCommitted => {+ const navigation = { push: vi.fn(), replace: vi.fn() }+ const view = render(<CommunityRouteContext value={{ navigation } as never}>+ <CommunityModuleRouteContext value={{ href: "/c/me/bots?audit=target", routeCommitted }}><Entry /></CommunityModuleRouteContext>+ </CommunityRouteContext>)+ fireEvent.click(view.getByRole("button", { name: "Open target" }))+ fireEvent.click(view.getByRole("button", { name: "Select tab" }))+ expect(navigation.push).toHaveBeenCalledExactlyOnceWith("/c/channels/target/thread?msg=opener")+ expect(navigation.replace).toHaveBeenCalledExactlyOnceWith("/c/me/friends?tab=new")+ expect(next.push).not.toHaveBeenCalled()+ expect(next.replace).not.toHaveBeenCalled()+ expect(view.getByText("audit=target")).toBeVisible()+})+it("keeps the native router at a providerless public or isolated page boundary", () => {+ next.push.mockClear(); next.replace.mockClear()+ const view = render(<Entry />)+ fireEvent.click(view.getByRole("button", { name: "Open target" }))+ expect(next.push).toHaveBeenCalledExactlyOnceWith("/c/channels/target/thread?msg=opener")+ expect(view.getByText("published=old")).toBeVisible()+})diff --git a/src/web/src/contexts/community/module-route.tsx b/src/web/src/contexts/community/module-route.tsxnew file mode 100644index 000000000..e9642e10f--- /dev/null+++ b/src/web/src/contexts/community/module-route.tsx@@ -0,0 +1,24 @@+"use client"++import { createContext, useContext, useMemo } from "react"+import { CommunityRouteContext } from "@/contexts/community/route-frame"+import { useRouter, useSearchParams } from "next/navigation"++export const CommunityModuleRouteContext = createContext<{ href: string; routeCommitted: boolean } | null>(null)++export function useCommunityRouter() {+ const publishedRouter = useRouter()+ const navigation = useContext(CommunityRouteContext)?.navigation+ const push = navigation?.push ?? publishedRouter.push+ const replace = navigation?.replace ?? publishedRouter.replace+ return useMemo(() => ({ push, replace }), [push, replace])+}++export function useCommunityModuleLocation() {+ const target = useContext(CommunityModuleRouteContext)+ const router = useCommunityRouter()+ const published = useSearchParams()+ const search = target ? target.href.split("?")[1] ?? "" : published.toString()+ const searchParams = useMemo(() => new URLSearchParams(search), [search])+ return { router, searchParams, routeCommitted: target?.routeCommitted ?? true }+}diff --git a/src/web/src/hooks/community/mutations/servers.dom.test.tsx b/src/web/src/hooks/community/mutations/servers.dom.test.tsxindex 8b6331f8b..aaef4fa5f 100644--- a/src/web/src/hooks/community/mutations/servers.dom.test.tsx+++ b/src/web/src/hooks/community/mutations/servers.dom.test.tsx@@ -8,7 +8,7 @@ import { clearAllPersistedCaches } from "@/lib/query-persister"import { communityKeys } from "@/lib/query-keys"import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { captureCommunityLiveSnapshotToken, publishCommunityLiveSnapshot } from "@/lib/community-db/sync"-import { cancelOwnerServerDelete, claimOwnerServerDeleteNavigation, claimOwnerServerDeleteScopeFlush, completeOwnerServerDeleteScopeFlush, createOwnerServerDeleteRouteToken, isOwnerServerDeleteMeRootLanding, isOwnerServerDeleteRouteProtected, observeOwnerServerDeleteRouteCommit } from "@/lib/community/eject-server"+import { beginOwnerServerDelete, cancelOwnerServerDelete, claimOwnerServerDeleteNavigation, claimOwnerServerDeleteScopeFlush, completeOwnerServerDeleteScopeFlush, createOwnerServerDeleteRouteToken, isOwnerServerDeleteMeRootLanding, isOwnerServerDeleteRouteProtected, observeOwnerServerDeleteRouteCommit } from "@/lib/community/eject-server"import { useDeleteServer } from "./servers"const mocks = vi.hoisted(() => ({ api: vi.fn(), flushOwnerServerDeleteAfterSuccess: vi.fn() }))vi.mock("@/lib/api/client", () => ({ apiFetch: mocks.api }))@@ -18,7 +18,7 @@ vi.mock("@tanstack/react-query-devtools", () => ({ ReactQueryDevtools: () => nulvi.mock("@/hooks/community/community-ws/scope-eviction", async (original) => ({ ...await original<typeof import("@/hooks/community/community-ws/scope-eviction")>(), flushOwnerServerDeleteAfterSuccess: mocks.flushOwnerServerDeleteAfterSuccess }))type Callbacks = Parameters<typeof useDeleteServer>[0]async function setup(serverId: string, callbacks: Omit<Callbacks, "routeToken">) {- let client!: QueryClient, current!: ReturnType<typeof useDeleteServer>, originalToken!: Callbacks["routeToken"]+ let client!: QueryClient, current!: ReturnType<typeof useDeleteServer>, originalToken!: NonNullable<Callbacks["routeToken"]>function Probe({ activeCallbacks }: { activeCallbacks: Omit<Callbacks, "routeToken"> & Partial<Pick<Callbacks, "routeToken">> }) {client = useQueryClient()const token = useMemo(() => createOwnerServerDeleteRouteToken(client), [])@@ -101,3 +101,15 @@ describe("useDeleteServer — unmounted caller with original account provider recancelOwnerServerDelete(view.client, serverId, view.routeToken)})})+++it.each([false, true])("rejects a delete without the committed route token without changing membership or another transaction (existing=%s)", async existing => {+ const serverId = "target-not-committed"+ const view = await setup(serverId, {})+ if (existing) beginOwnerServerDelete(view.client, serverId, view.routeToken)+ act(() => view.rerender({ activeCallbacks: { routeToken: undefined } }))+ await expect(view.result.current.mutateAsync({ serverId })).rejects.toThrow("Missing committed server route")+ expect(mocks.api).not.toHaveBeenCalled()+ expect(isOwnerServerDeleteRouteProtected(view.client, serverId)).toBe(existing)+ expect([...getCommunityDbRegistry(view.client)!.collections.serverMemberships.values()].some(row => row.serverId === serverId && row.viewer)).toBe(true)+})diff --git a/src/web/src/hooks/community/mutations/servers.ts b/src/web/src/hooks/community/mutations/servers.tsindex 62a0416b9..a9e994142 100644--- a/src/web/src/hooks/community/mutations/servers.ts+++ b/src/web/src/hooks/community/mutations/servers.ts@@ -85,7 +85,7 @@ export function useJoinServer() {export type LeaveServerArgs = { serverId: string }type DeleteServerArgs = LeaveServerArgs & { isUiCurrent?: () => boolean }type DeleteServerCallbacks = {- routeToken: OwnerServerDeleteRouteToken+ routeToken?: OwnerServerDeleteRouteTokenonSuccess?: (args: DeleteServerArgs,result: { needsNavigation: boolean },@@ -142,14 +142,16 @@ export function useLeaveServer() {export function useDeleteServer(callbacks: DeleteServerCallbacks) {const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()const unreadProjection = getActiveAccountUnreadProjection(queryClient)- return useCommunityCommandMutation<void, Error, DeleteServerArgs, { token: AccountUnreadScopeToken; proof: CommunityLiveSnapshotToken } & DeleteServerCallbacks>(origin, { meta: { observabilityAction: "server.delete" },+ return useCommunityCommandMutation<void, Error, DeleteServerArgs, { token: AccountUnreadScopeToken; proof: CommunityLiveSnapshotToken } & DeleteServerCallbacks & { routeToken: OwnerServerDeleteRouteToken }>(origin, { meta: { observabilityAction: "server.delete" },scope: { id: "community-server-membership" },onMutate: async (args) => {const token = args.originalawait origin.registry?.readyorigin.assert(token)- beginOwnerServerDelete(queryClient, args.serverId, callbacks.routeToken)- return { ...callbacks, proof: token, token: unreadProjection.beginScopeRetirement({ kind: "server", serverId: args.serverId }) }+ const routeToken = callbacks.routeToken+ if (!routeToken) throw new DOMException("Missing committed server route", "AbortError")+ beginOwnerServerDelete(queryClient, args.serverId, routeToken)+ return { ...callbacks, routeToken, proof: token, token: unreadProjection.beginScopeRetirement({ kind: "server", serverId: args.serverId }) }},mutationFn: async (args) => {const original = args.original, registry = origin.registry!@@ -168,8 +170,8 @@ export function useDeleteServer(callbacks: DeleteServerCallbacks) {try { await transaction.when("settled") } catch (error) { origin.assert(token); throw error }},onError: (error, args, context) => {- cancelOwnerServerDelete(queryClient, args.serverId, context?.routeToken)if (!context) return+ cancelOwnerServerDelete(queryClient, args.serverId, context.routeToken)try { origin.assert(context.proof) } catch { return }unreadProjection.rollbackScopeRetirement(context.token)context.onError?.(error, communityCommandInput(args))diff --git a/src/web/src/hooks/community/thread-opener-read-handoff.dom.test.ts b/src/web/src/hooks/community/thread-opener-read-handoff.dom.test.tsindex b69dc5bb1..e32925e33 100644--- a/src/web/src/hooks/community/thread-opener-read-handoff.dom.test.ts+++ b/src/web/src/hooks/community/thread-opener-read-handoff.dom.test.ts@@ -1,4 +1,5 @@import React from "react"+import { ConversationActivityContext } from "@/contexts/community/conversation-activity"import type { QueryClient } from "@tanstack/react-query"import { CommunityTestProvider } from "@/test/community-owner-fixture"import { createCommunityQueryOwner } from "@/test/community-query-owner"@@ -279,6 +280,34 @@ describe("thread opener read handoff", () => {expect(second).not.toBe(first)})+ it("does not clean a stale published nonce while an inactive target owns a new handoff", () => {+ const next = {...target, nonce: "nonce-2"}+ armThreadOpenerReservationHandoff(state.queryClient!, next)+ const node = (active: boolean) => React.createElement(ConversationActivityContext, {value: active}, React.createElement(Harness, {lifecycle: active ? "ready" : "pending"}))+ const renderer = rtlRender(node(false))+ expect(mocks.replace).not.toHaveBeenCalled()+ expect(mocks.register).not.toHaveBeenCalled()+ expect(mocks.submit).not.toHaveBeenCalled()+ expect(getThreadOpenerReservationHandoff(state.queryClient!, "nonce-2")).toMatchObject({phase: "armed", openerSeq: 7})+ state.params = "inboxThreadOpener=nonce-2&msg=new-target&tab=all"+ renderer.rerender(node(true))+ expect(mocks.submit).toHaveBeenCalledExactlyOnceWith({lease: "parent"}, {kind: "timeline", channelId: "parent-1", messageId: "opener-7", seq: 7})+ expect(mocks.replace).toHaveBeenCalledExactlyOnceWith("/c/channels/server-1/child-1?msg=new-target&tab=all", {scroll: false})+ })++ it("keeps a matching readable handoff unclaimed while its target remains inactive", () => {+ armThreadOpenerReservationHandoff(state.queryClient!, target)+ const node = (active: boolean) => React.createElement(ConversationActivityContext, {value: active}, React.createElement(Harness, {lifecycle: "ready"}))+ const renderer = rtlRender(node(false))+ expect(mocks.register).not.toHaveBeenCalled()+ expect(mocks.submit).not.toHaveBeenCalled()+ expect(mocks.replace).not.toHaveBeenCalled()+ expect(getThreadOpenerReservationHandoff(state.queryClient!, "nonce-1")).toMatchObject({phase: "armed"})+ renderer.rerender(node(true))+ expect(mocks.submit).toHaveBeenCalledExactlyOnceWith({lease: "parent"}, {kind: "timeline", channelId: "parent-1", messageId: "opener-7", seq: 7})+ expect(mocks.replace).toHaveBeenCalledExactlyOnceWith("/c/channels/server-1/child-1?msg=message-9&tab=all", {scroll: false})+ })+it("cleans an aligned nonce URL when no matching handoff exists", async () => {const renderer = await render("ready")expect(mocks.submit).not.toHaveBeenCalled()diff --git a/src/web/src/hooks/community/thread-opener-read-handoff.ts b/src/web/src/hooks/community/thread-opener-read-handoff.tsindex bc7ffafb5..06e57ad8f 100644--- a/src/web/src/hooks/community/thread-opener-read-handoff.ts+++ b/src/web/src/hooks/community/thread-opener-read-handoff.ts@@ -3,6 +3,7 @@import { useCallback, useLayoutEffect, useRef } from "react"import { usePathname, useRouter, useSearchParams } from "next/navigation"import { useQueryClient } from "@tanstack/react-query"+import { useConversationActivity } from "@/contexts/community/conversation-activity"import { useCurrentUser } from "@/contexts/community/current-user"import { channelHref, removeCommunityParam } from "@/lib/community/community-route"import {@@ -68,6 +69,7 @@ export function useThreadOpenerRouteGate({openerMessageId: string | nulllifecycle: RouteLifecycle}) {+ const active = useConversationActivity()const queryClient = useQueryClient()const router = useRouter()const pathname = usePathname()@@ -95,7 +97,7 @@ export function useThreadOpenerRouteGate({&& handoff.openerMessageId === openerMessageIduseLayoutEffect(() => {- if (!nonce || !routeAligned) return+ if (!active || !nonce || !routeAligned) returnconst lease = registerThreadOpenerRouteLease(queryClient,nonce,@@ -103,10 +105,10 @@ export function useThreadOpenerRouteGate({childChannelId,)return () => releaseThreadOpenerRouteLease(lease)- }, [childChannelId, nonce, queryClient, routeAligned, serverId])+ }, [active, childChannelId, nonce, queryClient, routeAligned, serverId])useLayoutEffect(() => {- if (!nonce || !routeAligned) return+ if (!active || !nonce || !routeAligned) returnif (!routeMatches || lifecycle === "terminal-error") {terminateThreadOpenerReservationHandoff(queryClient, nonce)cleanUrl()@@ -117,9 +119,9 @@ export function useThreadOpenerRouteGate({cleanUrl()return}- }, [canonicalMatches, cleanUrl, lifecycle, nonce, queryClient, routeAligned, routeMatches])+ }, [active, canonicalMatches, cleanUrl, lifecycle, nonce, queryClient, routeAligned, routeMatches])- return routeAligned && canonicalMatches && handoff ? handoff : null+ return active && routeAligned && canonicalMatches && handoff ? handoff : null}export function useClaimThreadOpenerReadHandoff(diff --git a/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx b/src/web/src/hooks/community/use-conversation-entry.dom.test.tsxindex 1a7b062b3..779b21857 100644--- a/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx+++ b/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx@@ -6,7 +6,7 @@ import { createCommunityQueryOwner } from "@/test/community-query-owner"import { conversationEntryFixture as fixture, dmConversationEntryFixture, conversationEntryTarget as target } from "@/test/conversation-entry-fixtures"import { CommunityDbProvider } from "@/lib/community-db/projections"import { registerCommunityDbRegistry } from "@/lib/community-db/collections"-import { captureCommunityLiveSnapshotToken, ingestMessages, ingestReadStateSnapshot } from "@/lib/community-db/sync"+import { captureCommunityLiveSnapshotToken, ingestMessages, ingestReadStateSnapshot, publishAccountAttentionSnapshot } from "@/lib/community-db/sync"import { conversationEntryOptions, currentConversationReadState, publishConversationEntry } from "@/lib/community/conversation-entry"import { communityKeys } from "@/lib/query-keys"import { ConversationReadTimeoutError } from "@/lib/community/conversation-read"@@ -765,3 +765,46 @@ describe("conversation entry return during accepted reading", () => {}})})+++describe("native entry freshness with authoritative newer attention", () => {+ it.each([["channel", false, false], ["channel", true, false], ["dm", false, false], ["dm", true, false], ["channel", true, true], ["dm", true, true]] as const)("keeps cached %s content while respecting newer=%s, explicit anchor=%s", async (kind, newer, explicitAnchor) => {+ const { client, registry, wrapper } = await setup()+ const packet = kind === "dm" ? dmConversationEntryFixture() : fixture()+ const selectedTarget = { channelId: packet.channelId, serverId: packet.channel.serverId, ...(explicitAnchor ? { anchorMessageId: "m1" } : {}) }+ if (explicitAnchor) packet.selection = { reason: "explicit_anchor", anchorMessageId: "m1" }+ load.mockResolvedValueOnce(packet)+ const original = await client.query(conversationEntryOptions(client, selectedTarget))+ load.mockClear()+ publishAccountAttentionSnapshot(client, {+ snapshot: { scopes: [{ scopeId: packet.channelId, channelId: packet.channelId, serverId: packet.channel.serverId,+ ordinaryUnread: newer, lastUnreadSeq: newer ? 2 : 1, lastAttentionSeq: null, attentionCount: 0 }], items: [], limit: 100, truncated: false,+ included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } },+ proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined },+ })+ const held = deferred<ReturnType<typeof fixture>>()+ load.mockReturnValue(held.promise)+ const hook = renderHook(() => useConversationEntry(selectedTarget), { wrapper })+ const selected = hook.result.current.window+ expect(selected).not.toBeNull()+ expect(hook.result.current.isPending).toBe(false)+ expect(hook.result.current.snapshot?.lastReadMessageId).toBe("m1")+ expect(client.getQueryData<{ pages: Array<{ messages: Array<{ id: string }> }> }>(original.windowKey)?.pages[0].messages.map(row => row.id)).toEqual(["m1"])+ if (!newer || explicitAnchor) {+ await act(async () => { await Promise.resolve() })+ expect(load).not.toHaveBeenCalled()+ } else {+ await waitFor(() => expect(load).toHaveBeenCalledOnce())+ expect(load.mock.calls[0][0]).toBe("/api/community/channels/c1/messages?entry=1")+ expect(hook.result.current.window).toBe(selected)+ const fresh = { ...packet, channel: { ...packet.channel, messageCount: 2 }, messages: [...packet.messages, { ...packet.messages[0], id: "m2", seq: 2, content: "New message" }], page: { ...packet.page, latestSeq: 2 } }+ await act(async () => { held.resolve(fresh) })+ await waitFor(() => expect(client.getQueryData<{ pages: Array<{ messages: Array<{ id: string }> }> }>(original.windowKey)?.pages.flatMap(page => page.messages.map(row => row.id))).toContain("m2"))+ expect(hook.result.current.window).toBe(selected)+ expect(hook.result.current.snapshot?.lastReadMessageId).toBe("m1")+ expect(load.mock.calls.every(([, options]) => !options?.method || options.method === "GET")).toBe(true)+ }+ expect(registry.collections.readStates.get(packet.channelId)?.lastReadSeq).toBe(1)+ hook.unmount()+ })+})diff --git a/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx b/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsxindex 21fef152c..cd9279844 100644--- a/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx+++ b/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx@@ -13,10 +13,10 @@ import { conversationEntryFixture } from "@/test/conversation-entry-fixtures"import { seedConversationEntry } from "@/test/conversation-entry-fixtures"import { act, fireEvent, render } from "@/test/react-dom-harness"import { installMessageScrollFixture, restoreMessageScrollFixture, resize } from "@/test/message-scroll-fixture"-import { ingestReadStateSnapshot } from "@/lib/community-db/sync"+import { captureCommunityLiveSnapshotToken, ingestReadStateSnapshot, publishAccountAttentionSnapshot } from "@/lib/community-db/sync"import { currentConversationReadState } from "@/lib/community/conversation-entry"import { disposeReadCoordinator, getLocalReadingPosition, getReadCoordinator } from "./read-coordinator"-import { disposeAccountReadStateReconciliation } from "./community-ws/read-state-reconciliation"+import { disposeAccountReadStateReconciliation, type AccountReadStateSnapshot } from "./community-ws/read-state-reconciliation"const navigationMock = vi.hoisted(() => ({ href: "/c/channels/s1/c1", replace: vi.fn() }))const load = vi.hoisted(() => vi.fn())@@ -96,16 +96,37 @@ function entry(kind: Kind, channelId = "c1", ownTail = false) {return value}-async function setup(kind: Kind, ownTail = false, strict = false) {+async function setup(kind: Kind, ownTail = false, strict = false, options: {+ cached?: ReturnType<typeof entry>+ latestAttentionSeq?: number+ refresh?: Promise<ReturnType<typeof entry>>+ refreshWindow?: Promise<ReturnType<typeof entry>>+ readPointer?: AccountReadStateSnapshot["readStates"][number]+} = {}) {owner = await createCommunityQueryOwner()- await seedConversationEntry(owner.client, entry(kind, "c1", ownTail))+ await seedConversationEntry(owner.client, options.cached ?? entry(kind, "c1", ownTail))await seedConversationEntry(owner.client, entry("channel", "c2"))+ if (options.readPointer) ingestReadStateSnapshot(owner.registry, { revision: 2, readStates: [options.readPointer] })+ if (options.latestAttentionSeq) publishAccountAttentionSnapshot(owner.client, {+ snapshot: { scopes: [{ scopeId: "c1", channelId: "c1", serverId: "s1", ordinaryUnread: true,+ lastUnreadSeq: options.latestAttentionSeq, lastAttentionSeq: null, attentionCount: 0 }],+ items: [], limit: 100, truncated: false,+ included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } },+ proof: { token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined },+ })let finishPut!: (value: unknown) => voidlet finishCanonical!: (value: unknown) => voidconst put = new Promise(resolve => { finishPut = resolve })const canonicalTransport = new Promise(resolve => { finishCanonical = resolve })releaseTransport = () => { finishPut({ changed: true, revision: 6, targetSeq: 42 }); finishCanonical({ revision: 6, readStates: [] }) }load.mockImplementation((url: string) => {+ if (url === "/api/community/channels/c1/messages?entry=1" && options.refresh) return options.refresh+ if (url === "/api/community/channels/c1/messages" && options.refreshWindow) return options.refreshWindow.then(value => ({+ ...value.page, messages: value.messages,+ }))+ if (url.startsWith("/api/community/channels/c1/messages?since=") && options.refresh) return options.refresh.then(value => ({+ ...value.page, messages: value.messages.filter(message => message.seq > 1),+ }))if (url.endsWith("/read")) return putif (url === "/api/community/users/me/read-state") return canonicalTransportif (url === "/api/community/users/me/attention") return Promise.resolve({ scopes: [], items: [], limit: 100, truncated: false })@@ -196,6 +217,74 @@ afterEach(async () => {})describe("conversation entry positioning through real reading owners", () => {+ it.each([{ delayCanonical: false, previousTail: false }, { delayCanonical: true, previousTail: false }, { delayCanonical: false, previousTail: true }])("keeps a cached read tail visible until native data is complete, delayed canonical=$delayCanonical, previous tail=$previousTail", async ({ delayCanonical, previousTail }) => {+ const fresh = entry("channel")+ fresh.messages = fresh.messages.slice(0, 13)+ fresh.channel.messageCount = 13+ const readPointer = { channelId: "c1", lastReadMessageId: "m1", lastReadSeq: 1, lastReadAt: fresh.messages[0].createdAt }+ fresh.readState = readPointer+ fresh.selection = { reason: "read_pointer", anchorMessageId: "m1" }+ fresh.readStateRevision = 2+ fresh.page.latestSeq = 13+ const cached = { ...fresh, channel: { ...fresh.channel, messageCount: 1 }, messages: fresh.messages.slice(0, 1), page: { ...fresh.page, latestSeq: 1 } }+ if (previousTail) {+ cached.readState = { channelId: "c1", lastReadMessageId: null, lastReadSeq: 0, lastReadAt: null }+ cached.readStateRevision = 1+ cached.selection = { reason: "tail", anchorMessageId: null }+ }+ let finishRefresh!: (value: typeof fresh) => void+ const refresh = new Promise<typeof fresh>(resolve => { finishRefresh = resolve })+ let finishWindow!: (value: typeof fresh) => void+ const refreshWindow = new Promise<typeof fresh>(resolve => { finishWindow = resolve })+ const view = await setup("channel", false, false, { cached, latestAttentionSeq: 13, refresh,+ ...(previousTail ? { readPointer, refreshWindow } : {}),+ })+ const nativeWrite = owner.registry.collections.messages.utils.writeBatch.bind(owner.registry.collections.messages.utils)+ const publications: Array<() => Promise<void>> = []+ const delayed = delayCanonical ? vi.spyOn(owner.registry.collections.messages.utils, "writeBatch").mockImplementation(callback => (+ new Promise<void>((resolve, reject) => { publications.push(() => nativeWrite(callback).then(resolve, reject)) })+ )) : null+ const publish = async () => {+ delayed?.mockRestore()+ await Promise.all(publications.splice(0).map(commit => commit()))+ }+ try {+ expect(latest.feed.messages.map(message => message.id)).toEqual(["m1"])+ expect(view.visible("m1")).toBe(true)+ expect(latest.feed.isFetching).toBe(true)+ const initialReadReady = view.root().querySelector("[data-message-list-content]")!.getAttribute("data-read-position-ready")+ await act(async () => { finishRefresh(fresh); await vi.advanceTimersByTimeAsync(0) })+ resize()+ if (delayCanonical) {+ expect({ latestSeq: latest.feed.latestSeq, messages: latest.feed.messages.map(message => message.id),+ fetching: latest.feed.isFetching, readSnapshotFetching: latest.feed.readSnapshotFetching,+ readReady: view.root().querySelector("[data-message-list-content]")!.getAttribute("data-read-position-ready"),+ }).toEqual({ latestSeq: 13, messages: ["m1"], fetching: false, readSnapshotFetching: true, readReady: "false" })+ await act(async () => { await publish(); await vi.advanceTimersByTimeAsync(0) })+ resize()+ }+ if (previousTail) {+ expect({ latestSeq: latest.feed.latestSeq, messages: latest.feed.messages.map(message => message.id),+ fetching: latest.feed.isFetching, readSnapshotFetching: latest.feed.readSnapshotFetching,+ readReady: view.root().querySelector("[data-message-list-content]")!.getAttribute("data-read-position-ready"),+ }).toEqual({ latestSeq: 1, messages: ["m1"], fetching: false, readSnapshotFetching: true, readReady: "false" })+ await act(async () => { finishWindow(fresh); await vi.advanceTimersByTimeAsync(0) })+ resize()+ }+ expect(latest.feed.error).toBeNull()+ expect(latest.feed.messages).toHaveLength(13)+ const marker = view.root().querySelector("[data-new-divider]")!.getBoundingClientRect()+ const viewport = view.root().getBoundingClientRect()+ expect({ initialReadReady, newInViewport: marker.bottom > viewport.top && marker.top < viewport.bottom,+ lastInViewport: view.visible("m13"), readReadyAfter: view.root().querySelector("[data-message-list-content]")!.getAttribute("data-read-position-ready"),+ }).toEqual({ initialReadReady: "false", newInViewport: true, lastInViewport: false, readReadyAfter: "true" })+ expect(latest.feed.readSnapshot?.lastReadSeq).toBe(1)+ expect(load.mock.calls.some(([, options]) => options?.method === "PUT")).toBe(false)+ } finally {+ await act(async () => { finishRefresh(fresh); finishWindow(fresh); await publish(); await vi.advanceTimersByTimeAsync(0) })+ }+ })+it.each([{ kind: "channel", strict: false }, { kind: "post", strict: false },{ kind: "thread", strict: false }, { kind: "channel", strict: true },diff --git a/src/web/src/hooks/community/use-me-route-memory.ts b/src/web/src/hooks/community/use-me-route-memory.tsnew file mode 100644index 000000000..d28c5a869--- /dev/null+++ b/src/web/src/hooks/community/use-me-route-memory.ts@@ -0,0 +1,16 @@+"use client"++import { useEffect } from "react"+import { useCurrentUser } from "@/contexts/community/current-user"+import { isRememberableMeLocation, setLastMeLocation } from "@/lib/community/last-me-location"+import { commitLastCommunityRoute } from "@/lib/community/last-community-route"++export function useMeRouteMemory(pathname: string, active: boolean) {+ const currentUser = useCurrentUser()+ useEffect(() => {+ if (!active || !["/c/me/friends", "/c/me/machines", "/c/me/bots"].includes(pathname)+ || !isRememberableMeLocation(pathname)) return+ setLastMeLocation(pathname)+ commitLastCommunityRoute(currentUser.id, pathname)+ }, [active, currentUser.id, pathname])+}diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.tsindex 3bb1bdc61..1167e0b0c 100644--- a/src/web/src/hooks/community/use-messages.ts+++ b/src/web/src/hooks/community/use-messages.ts@@ -12,8 +12,8 @@ import { useMessageWindowProjection } from "@/lib/community-db/projections"import { getCommunityRuntime } from "@/stores/community/runtime"import { useMessageOverlayIds } from "@/stores/community/message-stream"import { materializeMessageStream, type MessageScope } from "@/lib/community/message-stream"-import { messageWindowOptions, type InitialMessageWindow } from "@/lib/community/message-window"-import type { findConversationEntryWindow } from "@/lib/community/conversation-entry"+import { messageWindowOptions, type InitialMessageWindow, type MessageWindowData } from "@/lib/community/message-window"+import { knownConversationLatestSeq, type findConversationEntryWindow } from "@/lib/community/conversation-entry"import type { Msg } from "@/lib/community/models/message"import { messageReconcileOptions } from "./community-ws/reconnect-messages"@@ -87,7 +87,9 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undeficonst proof = entry.resource?.proofconst viewKey = hashKey([channelId, serverId, anchorMessageId, tag, proof?.accountEpoch ?? -1, proof?.accessEpoch ?? -1,channelId ? proof?.channelScopes.get(channelId)?.generation ?? 0 : 0])- const present = useMemo(() => createStore<PresentSelection>({ attempt: 0, pending: false, window: null, version: 0, error: null }), [viewKey, entry.intent])+ const present = useMemo(() => ({ viewKey, intent: entry.intent,+ state: createStore<PresentSelection>({ attempt: 0, pending: false, window: null, version: 0, error: null }),+ }), [viewKey, entry.intent]).stateconst selection = useSelector(present, (state) => state)const selectedWindow = entry.canRead ? selection.window ?? entry.window : nullconst enabled = !!channelId && !!selectedWindow && entry.canRead@@ -102,7 +104,7 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undeficonst options = messageWindowOptions(client, enabled ? channelId : "__none__", initial, tag, { observation })const queryKey = selectedWindow?.key ?? options.queryKeyconst query = useInfiniteQuery({ ...options, queryKey, enabled, subscribed: enabled })- useQuery({ ...messageReconcileOptions(client, { kind: serverId === null ? "dm" : "channel", scopeId: channelId ?? "__none__", serverId: serverId ?? undefined }, queryKey), enabled: false, subscribed: enabled })+ const reconciliation = useQuery({ ...messageReconcileOptions(client, { kind: serverId === null ? "dm" : "channel", scopeId: channelId ?? "__none__", serverId: serverId ?? undefined }, queryKey), enabled: false, subscribed: enabled })const originalQuery = client.getQueryCache().find({ queryKey, exact: true })const owner = useMemo(() => ({ present, query: originalQuery, enabled }), [present, originalQuery, enabled])const committed = useRef<typeof owner | null>(null)@@ -128,6 +130,11 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undeficonst messages = useMemo(() => entry.canRead ? materializeMessageStream(canonicalBase, overlay, canonicalById).filter((message) => messageMatchesTag(message, tag)) : [],[canonicalBase, canonicalById, overlay, entry.canRead, tag])const latestSeq = Math.max(0, ...(query.data?.pages.map((page) => page.latestSeq ?? 0) ?? []))+ const landingWindow = entry.resource ? client.getQueryData<MessageWindowData>(entry.resource.windowKey) : undefined+ const landingLatestSeq = Math.max(0, ...(landingWindow?.pages.map(page => page.latestSeq ?? 0) ?? []))+ const readSnapshotFetching = entry.isPending || ids.some(id => !canonicalById.has(id))+ || !anchorMessageId && !tag && (landingLatestSeq > latestSeq && (!reconciliation.isError || reconciliation.isFetching)+ || entry.isFetching && !!channelId && knownConversationLatestSeq(client, channelId) > latestSeq)const pages = query.data?.pages ?? []const oldest = pages.at(-1)const newest = pages[0]@@ -191,8 +198,8 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefifetchOlder, fetchNewer, jumpToPresent, presentVersion: selection.version,anchorReconciled: !!selectedWindow,navigationBlocked: !entry.canRead,- readSnapshot: entry.snapshot, readSnapshotFetching: entry.isPending,- initialPositionKnown: !!selectedWindow && entry.snapshot !== null && !loading,+ readSnapshot: entry.snapshot, readSnapshotFetching,+ initialPositionKnown: !!selectedWindow && entry.snapshot !== null && !loading && !readSnapshotFetching,initialPositionMessageId: entry.initialPositionMessageId, positionEntry: entry.intent,retryInitialLoad, retryingInitialLoad: entry.isFetching || query.isFetching,entryCanRead: entry.canRead, entryDenied: entry.denied, entryAnchorMissing: entry.anchorMissing,diff --git a/src/web/src/hooks/community/use-servers.dom.test.ts b/src/web/src/hooks/community/use-servers.dom.test.tsindex f9ab50aea..4ae9c37da 100644--- a/src/web/src/hooks/community/use-servers.dom.test.ts+++ b/src/web/src/hooks/community/use-servers.dom.test.ts@@ -2,7 +2,7 @@ import { createElement, type PropsWithChildren } from "react"import { QueryClient, QueryClientProvider, CancelledError } from "@tanstack/react-query"import { beforeEach, describe, expect, it, vi } from "vitest"import { act, renderHook, waitFor } from "@/test/react-dom-harness"-import { createCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections"+import { createCommunityDbRegistry, registerCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections"import { CommunityDbProvider } from "@/lib/community-db/projections"import { captureCommunityLiveSnapshotToken, publishAccountAttentionSnapshot, publishCommunityLiveSnapshot, projectCommunityWsEventToDb, publishCommunityChannelDirectory } from "@/lib/community-db/sync"import { communityKeys } from "@/lib/query-keys"@@ -234,6 +234,54 @@ describe("useServers / serversQueryFn", () => {})describe("useServer / projected canonical detail", () => {+ it.each(["account", "owner"])("rechecks %s ownership after structural retirement rejects and before the hook restarts", async retirement => {+ seedList()+ let release!: () => void+ const response = new Promise<void>(resolve => { release = resolve })+ apiFetchMock.mockImplementation(async (url: string) => { await response; return detailApi(url) })+ const retireOwner = registerCommunityDbRegistry(registry)+ const unsubscribe = client.getQueryCache().subscribe(event => {+ if (event.type !== "updated" || event.action.type !== "error" || event.query.queryKey !== client.getQueryCache().find({ queryKey: communityKeys.server(identity.id), exact: true })?.queryKey) return+ if (retirement === "account") registry.runtime.ws.actions.activateProfileAccount("replacement")+ else retireOwner()+ })+ try {+ const view = renderHook(() => useServer(identity.id), { wrapper: Owner })+ await waitFor(() => expect(apiFetchMock.mock.calls.filter(([url]) => String(url).endsWith("/channels"))).toHaveLength(1))+ await act(async () => { registry.runtime.ws.actions.revokeServerAccess("other"); release() })+ await waitFor(() => expect(retirement === "owner" ? !registry.runtime.lifecycle.get().active : registry.runtime.ws.get().profileViewerId === "replacement").toBe(true))+ await waitFor(() => expect(view.result.current.fetchStatus).toBe("idle"))+ expect(view.result.current.server).toBeNull()+ expect(registry.collections.servers.get(identity.id)?.detailComplete).toBe(false)+ expect(apiFetchMock.mock.calls.filter(([url]) => String(url).endsWith("/categories"))).toHaveLength(1)+ } finally {+ unsubscribe()+ }+ })++ it.each(["target", "account", "signal", "generic-abort"])("does not restart a current detail read after %s retirement", async retirement => {+ seedList()+ let release!: () => void+ const response = new Promise<void>(resolve => { release = resolve })+ apiFetchMock.mockImplementation(async (url: string) => {+ await response+ if (retirement === "generic-abort") throw new DOMException("Transport aborted", "AbortError")+ return detailApi(url)+ })+ const view = renderHook(() => useServer(identity.id), { wrapper: Owner })+ await waitFor(() => expect(apiFetchMock.mock.calls.filter(([url]) => String(url).endsWith("/channels"))).toHaveLength(1))+ await act(async () => {+ if (retirement === "target") registry.runtime.ws.actions.revokeServerAccess(identity.id)+ if (retirement === "account") registry.runtime.ws.actions.activateProfileAccount("replacement")+ if (retirement === "signal") await client.cancelQueries({ queryKey: communityKeys.server(identity.id), exact: true })+ release()+ })+ await waitFor(() => expect(view.result.current.fetchStatus).toBe("idle"))+ expect(view.result.current.server).toBeNull()+ expect(apiFetchMock.mock.calls.filter(([url]) => String(url).endsWith("/categories"))).toHaveLength(1)+ if (retirement !== "signal") expect(view.result.current.error?.name).toBe("AbortError")+ })+it("retains a current server deadline failure across another native consumer and recovers on explicit retry", async () => {seedList()const key = communityKeys.server(identity.id)diff --git a/src/web/src/hooks/community/use-servers.ts b/src/web/src/hooks/community/use-servers.tsindex 44ec04112..0e1a6b4b8 100644--- a/src/web/src/hooks/community/use-servers.ts+++ b/src/web/src/hooks/community/use-servers.ts@@ -13,7 +13,7 @@ type QueryClient,type QueryFunctionContext,type UseQueryResult,} from "@tanstack/react-query"-import { useMemo } from "react"+import { useEffect, useMemo } from "react"import { createStore } from "@tanstack/store"import type { ServerRow } from "@/lib/community-db/schema"import { apiFetch } from "@/lib/api/client"@@ -30,7 +30,8 @@ type AccountUnreadSource,} from "./account-unread-projection"import { useCommunityWsStore } from "@/stores/community/ws"import { useCommunityRuntime } from "@/stores/community/runtime"-import { ApiError } from "@/lib/errors"+import { getCommunityDbRegistry } from "@/lib/community-db/collections"+import { ApiError, isAbortError } from "@/lib/errors"import { evictServerChannelScopes } from "./community-ws/scope-eviction"import {useAttentionScopes,@@ -323,6 +324,22 @@ const serverQueryFn = (}}+function serverDetailReadSuperseded(queryClient: QueryClient, serverId: string, token: CommunityLiveSnapshotToken, signal?: AbortSignal) {+ const registry = getCommunityDbRegistry(queryClient)+ if (!registry || registry !== token.registry) return false+ const state = registry.runtime.ws.get()+ const lifecycle = registry.runtime.lifecycle.get()+ return !signal?.aborted && lifecycle.active && lifecycle.generation === token.ownerGeneration+ && state.profileViewerId === token.viewerId && state.profileAccountEpoch === token.accountEpoch+ && state.accessEpoch !== token.accessEpoch && !state.revokedServerIds.has(serverId)+}++class SupersededServerDetailRead extends DOMException {+ constructor(readonly token: CommunityLiveSnapshotToken, readonly signal: AbortSignal | undefined) {+ super("Superseded server detail read", "AbortError")+ }+}+export const serverProjectedQueryFn = (queryClient: QueryClient,serverId: string,@@ -367,6 +384,9 @@ export const serverProjectedQueryFn = (if (error instanceof ApiError && (error.status === 403 || error.status === 404)) {evictServerChannelScopes(queryClient, serverId)}+ if (isAbortError(error) && serverDetailReadSuperseded(queryClient, serverId, structuralToken, signal)) {+ throw new SupersededServerDetailRead(structuralToken, signal)+ }throw error}}@@ -399,6 +419,13 @@ export function useServer(retry: conversationReadRetryPolicy(queryClient.defaultQueryOptions({ queryKey: communityKeys.server(serverId ?? "__none__") }).retry),networkMode: "always",})+ const restart = query.refetch+ useEffect(() => {+ const error = query.error+ if (serverId && error instanceof SupersededServerDetailRead && serverDetailReadSuperseded(queryClient, serverId, error.token, error.signal)) {+ void restart({ cancelRefetch: false })+ }+ }, [query.error, queryClient, serverId, restart])const projectedServer = useMemo(() => {const source = dbServerif (!source || !serverId) return nulldiff --git a/src/web/src/lib/community/community-route.test.ts b/src/web/src/lib/community/community-route.test.tsindex d5f94a8ec..151387a81 100644--- a/src/web/src/lib/community/community-route.test.ts+++ b/src/web/src/lib/community/community-route.test.ts@@ -150,7 +150,7 @@ describe("community route", () => {targetHref: "/malformed",rail: { kind: "keep" },sidebar: { kind: "keep" },- main: { kind: "keep" },+ main: { kind: "server-route", href: "/c/channels/s1/c1" },})})@@ -176,6 +176,22 @@ describe("community route", () => {}).mode).toBe(mode)})+ it("uses the real cross-server consumer and target-scoped canonical sidebar", () => {+ expect(resolveCommunityCheckpointPlan({+ committedFrame: { ...normalizeCommunityHref("/c/channels/s1/c1"), revision: 2 },+ targetHref: "/c/channels/s2/c2?msg=m2", pending: true, targetReady: true,+ })).toMatchObject({ mode: "warm-scope", rail: {kind: "target", view: "server", activeServerId: "s2"},+ sidebar: {kind: "keep"}, main: {kind: "server-route", href: "/c/channels/s2/c2?msg=m2"} })+ })++ it.each(["friends", "bots", "machines"] as const)("selects the %s consumer with target parameters before and after commit", module => {+ const href = `/c/me/${module}?target=one`+ const pending = resolveCommunityCheckpointPlan({committedFrame: {...normalizeCommunityHref("/c/channels/s1/c1"), revision: 1}, targetHref: href, pending: true, targetReady: true})+ const committed = resolveCommunityCheckpointPlan({committedFrame: {...normalizeCommunityHref(href.split("?")[0]!), revision: 2}, targetHref: href, pending: false, targetReady: true})+ expect(pending.main).toEqual({kind: "module-route", module, href})+ expect(committed.main).toEqual(pending.main)+ })+it("keeps the committed surface and child alive during same-scope navigation", () => {const committedFrame = {...normalizeCommunityHref("/c/channels/s1"),@@ -206,7 +222,6 @@ describe("community route", () => {targetHref: "/c/channels/s1/c2?msg=m2&threadView=full",pending: true,targetReady: true,- targetConversationSubtype: "forum",}).main).toEqual({kind: "server-route",href: "/c/channels/s1/c2?msg=m2&threadView=full",@@ -220,6 +235,17 @@ describe("community route", () => {}).main).toEqual({ kind: "dm-route", href: "/c/me/dm2", dmId: "dm2" })})+ it("keeps a public invite outside the authenticated target consumers", () => {+ expect(resolveCommunityCheckpointPlan({+ committedFrame: { ...normalizeCommunityHref("/c/me/friends"), revision: 2 },+ targetHref: "/c/invite/token?from=server", pending: true, targetReady: false,+ })).toEqual({+ mode: "cold-scope", surface: "detail", targetHref: "/c/invite/token?from=server",+ rail: { kind: "keep" }, sidebar: { kind: "keep" },+ main: { kind: "target-skeleton", href: "/c/invite/token?from=server" },+ })+ })+it("keeps committed A as the source after the router publishes B", () => {const committedFrame = {...normalizeCommunityHref("/c/channels/s1/c1"),@@ -235,8 +261,8 @@ describe("community route", () => {surface: "detail",targetHref: "/c/channels/s2/c2",rail: { kind: "target", view: "server", activeServerId: "s2" },- sidebar: { kind: "server-skeleton", serverId: "s2" },- main: { kind: "target-skeleton", href: "/c/channels/s2/c2" },+ sidebar: { kind: "keep" },+ main: { kind: "server-route", href: "/c/channels/s2/c2" },})})@@ -327,7 +353,30 @@ describe("ordinary message resolution route", () => {})it("publishes a target checkpoint before a message leaf commits", () => {const committedFrame={...normalizeCommunityHref("/c/me/friends"),revision:1}- expect(resolveCommunityCheckpointPlan({committedFrame,targetHref:"/c/messages/message_1",pending:true,targetReady:false})).toMatchObject({main:{kind:"target-skeleton",href:"/c/messages/message_1"}})- expect(resolveCommunityCheckpointPlan({committedFrame,targetHref:"/c/unknown",pending:true,targetReady:false}).main.kind).toBe("keep")+ expect(resolveCommunityCheckpointPlan({committedFrame,targetHref:"/c/messages/message_1",pending:true,targetReady:false})).toMatchObject({main:{kind:"module-route",module:"route-resolution",href:"/c/messages/message_1"}})+ expect(resolveCommunityCheckpointPlan({committedFrame,targetHref:"/c/unknown",pending:true,targetReady:false}).main).toEqual({kind:"module-route",module:"friends",href:"/c/me/friends"})+ })+})+++describe("complete authenticated route consumer selection", () => {+ it.each([+ ["/c", "module-route", "route-resolution"],+ ["/c/me", "module-route", "me-root"],+ ["/c/me/friends?tab=new", "module-route", "friends"],+ ["/c/me/bots?audit=bot", "module-route", "bots"],+ ["/c/me/machines?reconnect=machine", "module-route", "machines"],+ ["/c/me/dm", "dm-route", undefined],+ ["/c/channels/target", "module-route", "server-landing"],+ ["/c/channels/target/channel?msg=message", "server-route", undefined],+ ["/c/channels/target/settings", "module-route", "server-landing"],+ ["/c/messages/message", "module-route", "route-resolution"],+ ["/c/onboarding-preview", "module-route", "route-resolution"],+ ])("selects the same actual %s consumer without a directory-ready prerequisite", (href, kind, module) => {+ const pending = resolveCommunityCheckpointPlan({ committedFrame: { ...normalizeCommunityHref("/c/channels/source/channel"), revision: 1 }, targetHref: href, pending: true, targetReady: false })+ const committed = resolveCommunityCheckpointPlan({ committedFrame: { ...normalizeCommunityHref(href), revision: 2 }, targetHref: href, pending: false, targetReady: false })+ expect(pending.main).toEqual({ kind, href, ...(module ? { module } : kind === "dm-route" ? { dmId: "dm" } : {}) })+ expect(committed.main).toEqual(pending.main)+ expect(pending.sidebar).toEqual({ kind: "keep" })})})diff --git a/src/web/src/lib/community/community-route.ts b/src/web/src/lib/community/community-route.tsindex bd089d75d..c26bfb09c 100644--- a/src/web/src/lib/community/community-route.ts+++ b/src/web/src/lib/community/community-route.ts@@ -2,6 +2,7 @@ export type CommunitySurface = "list" | "detail"type CommunityModuleRoute =| "community-root-redirect"+ | "onboarding-preview"| "me-root"| "me-friends"| "me-machines"@@ -71,10 +72,9 @@ export type CommunityCheckpointPlan = {| { kind: "keep" }| { kind: "server-skeleton"; serverId: string }| { kind: "me-skeleton" }- main: { kind: "keep" } | { kind: "server-route"; href: string } | { kind: "dm-route"; href: string; dmId: string } | {+ main: { kind: "keep" } | { kind: "server-route"; href: string } | { kind: "module-route"; href: string; module: "friends" | "bots" | "machines" | "me-root" | "server-landing" | "route-resolution" } | { kind: "dm-route"; href: string; dmId: string } | {kind: "target-skeleton"href: string- conversationSubtype?: "text" | "forum" | "thread"}}@@ -125,6 +125,11 @@ export function resolveCommunityModulePlan(href: string): CommunityModulePlan {}}+ if (segments[1] === "onboarding-preview" && segments.length === 2) {+ return { route: "onboarding-preview", canonicalHref: "/c/me/machines?onboarding-preview=1", surface: "detail",+ rail: "community", sidebar: { kind: "me" }, main: { kind: "route-resolution" } }+ }+if (segments[1] === "invite" && segments.length === 3) {return {route: "public-invite",@@ -293,93 +298,31 @@ export function resolveCommunityCheckpointPlan({targetHref,pending,targetReady,- targetConversationSubtype,}: {committedFrame: CommunityCommittedFrametargetHref: string | nullpending: booleantargetReady: boolean- targetConversationSubtype?: "text" | "forum" | "thread"}): CommunityCheckpointPlan {if (!pending || !targetHref) {- return committedPlan(committedFrame)+ return committedPlan(committedFrame, targetHref && normalizeCommunityHref(targetHref).leafKey === committedFrame.leafKey ? targetHref : committedFrame.href)}const target = normalizeCommunityHref(targetHref)- const targetModule = resolveCommunityModulePlan(target.href)- if (targetModule.route === "message-resolution" && target.leafKey !== committedFrame.leafKey) {- return { mode: "cold-scope", surface: target.surface, targetHref: target.href,- rail: { kind: "keep" }, sidebar: { kind: "keep" },- main: { kind: "target-skeleton", href: target.href } }- }- if (targetModule.main.kind === "dm") {- const plan = committedPlan(committedFrame, target.href)- return {- ...plan,- mode: communityScopeEqual(committedFrame.scope, target.scope) ? "same-scope-leaf" : targetReady ? "warm-scope" : "cold-scope",- surface: target.surface,- rail: target.scope.kind === "me" && committedFrame.scope.kind !== "me" ? { kind: "target", view: "dm" } : plan.rail,- sidebar: committedFrame.scope.kind !== "me" ? { kind: "me-skeleton" } : plan.sidebar,- main: { kind: "dm-route", href: target.href, dmId: targetModule.main.dmId },- }- }- const targetMainKind = targetModule.main.kind- const isConversationTarget = targetMainKind === "server-conversation"- if (target.scope.kind === "unknown" || target.leafKey === committedFrame.leafKey) {- return committedPlan(committedFrame, target.href)- }-- if (communityScopeEqual(committedFrame.scope, target.scope)) {- return {- mode: "same-scope-leaf",- surface: target.surface,- targetHref: target.href,- rail: { kind: "keep" },- sidebar: { kind: "keep" },- main: targetMainKind === "server-conversation"- ? { kind: "server-route", href: target.href }- : isConversationTarget- ? {- kind: "target-skeleton",- href: target.href,- ...(targetConversationSubtype ? { conversationSubtype: targetConversationSubtype } : {}),- }- : { kind: "keep" },- }- }-- if (targetReady) {- return {- ...committedPlan(committedFrame, target.href),- mode: "warm-scope",- surface: target.surface,- main: isConversationTarget- ? {- kind: "target-skeleton",- href: target.href,- ...(targetConversationSubtype ? { conversationSubtype: targetConversationSubtype } : {}),- }- : { kind: "keep" },- }+ if (resolveCommunityModulePlan(target.href).route === "unknown" || target.leafKey === committedFrame.leafKey) return committedPlan(committedFrame, target.href)+ const sameScope = communityScopeEqual(committedFrame.scope, target.scope)+ const plan = committedPlan({ ...target, revision: committedFrame.revision })+ if (plan.main.kind === "keep") return {+ ...plan,+ mode: "cold-scope",+ main: { kind: "target-skeleton", href: target.href },}-- const rail = target.scope.kind === "server"- ? { kind: "target" as const, view: "server" as const, activeServerId: target.scope.serverId }- : { kind: "target" as const, view: "dm" as const }- const sidebar = target.scope.kind === "server"- ? { kind: "server-skeleton" as const, serverId: target.scope.serverId }- : { kind: "me-skeleton" as const }return {- mode: "cold-scope",- surface: target.surface,- targetHref: target.href,- rail,- sidebar,- main: {- kind: "target-skeleton",- href: target.href,- ...(targetConversationSubtype ? { conversationSubtype: targetConversationSubtype } : {}),- },+ ...plan,+ mode: sameScope ? "same-scope-leaf" : targetReady ? "warm-scope" : "cold-scope",+ rail: sameScope ? { kind: "keep" } : target.scope.kind === "server"+ ? { kind: "target", view: "server", activeServerId: target.scope.serverId }+ : target.scope.kind === "me" ? { kind: "target", view: "dm" } : { kind: "keep" },}}@@ -387,14 +330,19 @@ function committedPlan(frame: CommunityCommittedFrame,targetHref = frame.href,): CommunityCheckpointPlan {- const main = resolveCommunityModulePlan(frame.href).main+ const modulePlan = resolveCommunityModulePlan(frame.href)+ const main = modulePlan.main+ const href = normalizeCommunityHref(targetHref).leafKey === frame.leafKey ? targetHref : frame.hrefreturn {mode: "committed",surface: frame.surface,targetHref,rail: { kind: "keep" },sidebar: { kind: "keep" },- main: main.kind === "dm" ? { kind: "dm-route", href: targetHref, dmId: main.dmId } : { kind: "keep" },+ main: main.kind === "dm" ? { kind: "dm-route", href, dmId: main.dmId }+ : main.kind === "server-conversation" ? { kind: "server-route", href }+ : modulePlan.route !== "unknown" && main.kind !== "none"+ ? { kind: "module-route", href, module: main.kind } : { kind: "keep" },}}diff --git a/src/web/src/lib/community/conversation-entry.ts b/src/web/src/lib/community/conversation-entry.tsindex 36742d7c5..76e9ac60c 100644--- a/src/web/src/lib/community/conversation-entry.ts+++ b/src/web/src/lib/community/conversation-entry.ts@@ -14,7 +14,7 @@ import {assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken,publishCommunityChannelMetadata, publishCommunityChannelMembersSnapshot, publishCommunityConversationReadState, confirmCommunityConversationPresence,publishCommunityMessages, retireCommunityChannelReading, type CommunityFreshQueryProof,- publishCommunityForumFeed,+ publishCommunityForumFeed, getCanonicalCommunityAttentionScopes,} from "@/lib/community-db/sync"import { messageWindowPage, type MessagesPageParam } from "./models/message"import { messageWindowIdentity, type InitialMessageWindow, type MessageWindowData } from "./message-window"@@ -145,6 +145,12 @@ export function findConversationEntryWindow(client: QueryClient, target: Convers}}+export function knownConversationLatestSeq(client: QueryClient, channelId: string) {+ return Math.max(0, ...getCanonicalCommunityAttentionScopes(client)+ .filter(scope => scope.channelId === channelId)+ .map(scope => Math.max(scope.lastUnreadSeq, scope.lastAttentionSeq ?? 0)))+}+export function conversationEntryOptions(client: QueryClient, target: ConversationEntryTarget, observation?: ApiRequestOptions["observation"]) {const qualification = captureCommunityLiveSnapshotToken(client, target.channelId)const queryKey = communityKeys.conversationEntry(target.channelId, target, {@@ -201,7 +207,14 @@ export function conversationEntryOptions(client: QueryClient, target: Conversaticonst resource = query.state.dataif (!resource) return 0const pointer = knownPointer && resource.readStateRevision <= (knownPointer.observedRevision ?? -1) ? knownPointer : resource.readStateAtEntry- return findConversationEntryWindow(client, target, resource, pointer) ? 5_000 : 0+ const window = findConversationEntryWindow(client, target, resource, pointer)+ if (!window) return 0+ if (!target.anchorMessageId && !target.tag && messageWindowIdentity(window.key)) {+ const cachedWindow = client.getQueryData<MessageWindowData>(window.key)!+ const observedLatest = Math.max(0, ...cachedWindow.pages.map(page => page.latestSeq ?? 0))+ if (knownConversationLatestSeq(client, target.channelId) > observedLatest) return 0+ }+ return 5_000},gcTime: typeof window === "undefined" ? Infinity : 5 * 60 * 1000,retry: target.serverId === null ? false : retryConversationRead,diff --git a/src/web/src/stores/community/index.ts b/src/web/src/stores/community/index.tsindex 1dad4f32e..d123e2b90 100644--- a/src/web/src/stores/community/index.ts+++ b/src/web/src/stores/community/index.ts@@ -4,7 +4,6 @@ import { useSelector, shallow } from "@tanstack/react-store"import { useMemo } from "react"import type React from "react"import type { FileAttachment, ImagePreview } from "@/lib/community/models/message"-import { useRouteChannelProjection } from "@/lib/community-db/projections"import { useCommunityRuntime } from "./runtime"import { createCommunityStore, type CommunityUiHandlers } from "./ui-store"@@ -19,8 +18,6 @@ export function useCommunityStore<T>(selector: (state: ReturnType<ReturnType<typexport const useCurrentChannelId = () =>useCommunityStore((s) => s.currentChannelId)-export const useCurrentChannelMeta = () => useRouteChannelProjection(useCurrentChannelId()) ?? null-export function useUiHandlers() {const { ui } = useCommunityRuntime()return useMemo(() => ({diff --git a/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts b/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.tsindex 4a8cd60c7..52ed1fa78 100644--- a/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts+++ b/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts@@ -141,6 +141,8 @@ test("community checkpoint shows target pending for detail and keeps list surfacconst channelA = await seedChannel("alice", serverId, channelAName)const channelB = await seedChannel("alice", serverId, channelBName)const { page } = await asUser("alice")+ const machineDataGate = await holdRoute(page, "/api/community/machines", caseResources)+ const machinesGate = await holdRoute(page, "/c/me/machines", caseResources)await page.setViewportSize({ width: 1280, height: 900 })await page.goto(`/c/channels/${serverId}/${channelA}`)await expect(channelHeader(page, channelAName)).toBeVisible({ timeout: 30_000 })@@ -201,18 +203,35 @@ test("community checkpoint shows target pending for detail and keeps list surfacawait rootGate.release()await expect(channelHeader(page, channelBName)).toBeVisible({ timeout: 30_000 })- const machinesGate = await holdRoute(page, "/c/me/machines", caseResources)await page.goto("/c/me/friends")await expect(page.getByPlaceholder("Search friends")).toBeVisible({ timeout: 30_000 })await page.getByRole("link", { name: "Machines", exact: true }).click({ noWaitAfter: true })await expect.poll(machinesGate.held).toBeGreaterThan(0)+ await expect.poll(machineDataGate.held).toBeGreaterThan(0)+ await expect(page.getByPlaceholder("Search friends")).toHaveCount(0)await expect(page.getByLabel("Resolving conversation")).toHaveCount(0)- await expect(page.getByPlaceholder("Search friends")).toBeVisible()- await page.waitForTimeout(150)- await expect(page.getByPlaceholder("Search friends")).toBeVisible()+ await expect(page.locator('[data-slot="community-machines-heading"] [data-slot="skeleton"]').first()).toBeVisible()+ await expect(page.getByText("No machines yet", {exact: true})).toHaveCount(0)+ await expect(page.getByTestId(tid.machinePairOpen)).toHaveCount(0)+ expect(new URL(page.url()).pathname).toBe("/c/me/friends")+ await machineDataGate.release()+ await expect(page.getByText("No machines yet", {exact: true})).toBeVisible()+ await expect(page.getByTestId(tid.machinePairOpen)).toBeEnabled()+ expect(new URL(page.url()).pathname).toBe("/c/me/friends")+ const cachedMachineContent = page.getByText("No machines yet", {exact: true})+ await cachedMachineContent.evaluate(element => { element.setAttribute("data-e2e-cached-identity", "retained") })await machinesGate.release()- await expect(page.getByTestId(tid.machinePairOpen))- .toBeVisible({ timeout: 30_000 })+ await expect.poll(() => new URL(page.url()).pathname).toBe("/c/me/machines")+ await expect(cachedMachineContent).toHaveAttribute("data-e2e-cached-identity", "retained")+ await page.getByRole("link", {name: "Friends", exact: true}).click()+ await expect(page.getByPlaceholder("Search friends")).toBeVisible()+ const warmMachinesGate = await holdRoute(page, "/c/me/machines", caseResources)+ await page.getByRole("link", {name: "Machines", exact: true}).click({noWaitAfter: true})+ await expect(cachedMachineContent).toBeVisible()+ await expect(page.getByTestId(tid.machinePairOpen)).toBeEnabled()+ await expect(page.getByPlaceholder("Search friends")).toHaveCount(0)+ await warmMachinesGate.release()+ await expect.poll(() => new URL(page.url()).pathname).toBe("/c/me/machines")expect(mutations).toEqual([])})