Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(web): stabilize /c/me routing and loading boundaries (#574)
Generd609b49616c8
diff --git a/src/web/src/app/c/layout.test.ts b/src/web/src/app/c/layout.test.tsnew file mode 100644index 000000000..7a521144b--- /dev/null+++ b/src/web/src/app/c/layout.test.ts@@ -0,0 +1,84 @@+import { createElement } from "react"+import { readFileSync } from "node:fs"+// @ts-expect-error react-test-renderer intentionally has no local declaration package.+import TestRenderer, { act } from "react-test-renderer"+import { beforeEach, describe, expect, it, vi } from "vitest"++const mocks = vi.hoisted(() => ({+ pathname: "/c/me",+ replace: vi.fn(),+ session: { data: null as null | { user: { id: string; name: string; email: string; image: string | null } }, isPending: true },+}))++vi.mock("next/navigation", () => ({+ usePathname: () => mocks.pathname,+ useRouter: () => ({ replace: mocks.replace }),+}))+vi.mock("@/lib/auth-client", () => ({ useSession: () => mocks.session }))+vi.mock("./community-shell", () => ({+ CommunityShell: (props: Record<string, unknown>) => createElement("community-shell", props),+}))+vi.mock("@/components/community/shell/community-session-pending-frame", () => ({+ CommunitySessionPendingFrame: () => createElement("session-pending"),+}))+vi.mock("@/components/signup-tracker", () => ({+ SignupTracker: (props: Record<string, unknown>) => createElement("signup-tracker", props),+}))++import CommunityLayout from "./layout"++function render() {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(createElement(CommunityLayout, null, createElement("child")))+ })+ return renderer+}++describe("CommunityLayout session boundary", () => {+ beforeEach(() => {+ mocks.pathname = "/c/me"+ mocks.session = { data: null, isPending: true }+ mocks.replace.mockClear()+ })++ it("keeps a stable frame while identity is pending", () => {+ const renderer = render()+ expect(renderer.root.findAllByType("session-pending")).toHaveLength(1)+ expect(renderer.root.findAllByType("community-shell")).toHaveLength(0)+ })++ it("keeps the frame mounted while a signed-out redirect commits", () => {+ mocks.session = { data: null, isPending: false }+ const renderer = render()+ expect(mocks.replace).toHaveBeenCalledWith("/sign-in")+ expect(renderer.root.findAllByType("session-pending")).toHaveLength(1)+ })++ it("constructs the shell only after identity is available", () => {+ mocks.session = {+ data: { user: { id: "u1", name: "Ada", email: "[email protected]", image: null } },+ isPending: false,+ }+ const renderer = render()+ const shell = renderer.root.findByType("community-shell")+ expect(shell.props.currentUser).toMatchObject({ id: "u1", name: "Ada", email: "[email protected]" })+ expect(renderer.root.findAllByType("session-pending")).toHaveLength(0)+ })++ it("preserves the public invite bypass", () => {+ mocks.pathname = "/c/invite/token"+ const renderer = render()+ expect(renderer.root.findAllByType("child")).toHaveLength(1)+ expect(renderer.root.findAllByType("session-pending")).toHaveLength(0)+ expect(mocks.replace).not.toHaveBeenCalled()+ })++ it("wires the Me verifier to canonical fetch-in-flight state", () => {+ const source = readFileSync(new URL("./me/layout.tsx", import.meta.url), "utf8")+ expect(source).toMatch(/isPending:\s*dmsPending/)+ expect(source).toMatch(/isFetching:\s*dmsFetching/)+ expect(source).toContain("const canonicalDmsUnsettled = dmsPending || dmsFetching")+ expect(source).toContain("useDmRouteVerification(params.dmId, rawDms, canonicalDmsUnsettled)")+ })+})diff --git a/src/web/src/app/c/layout.tsx b/src/web/src/app/c/layout.tsxindex ee0a003f8..39bd2d5a1 100644--- a/src/web/src/app/c/layout.tsx+++ b/src/web/src/app/c/layout.tsx@@ -6,6 +6,7 @@ import { useSession } from "@/lib/auth-client"import { CommunityShell } from "./community-shell"import { avatarInitial } from "@/lib/community/avatar"import { SignupTracker } from "@/components/signup-tracker"+import { CommunitySessionPendingFrame } from "@/components/community/shell/community-session-pending-frame"// The invite landing page is preview-first: a logged-out visitor must be able// to see it (and only hit the login wall on Join). It's a standalone@@ -37,7 +38,7 @@ export default function CommunityLayout({// gate, no CommunityShell (a logged-out visitor has no currentUser).if (isPublic) return <><SignupTracker />{children}</>- if (isPending || !session) return null+ if (isPending || !session) return <CommunitySessionPendingFrame />const currentUser = {id: session.user.id,diff --git a/src/web/src/app/c/me/[dmId]/loading.tsx b/src/web/src/app/c/me/[dmId]/loading.tsxnew file mode 100644index 000000000..bd89a5b9b--- /dev/null+++ b/src/web/src/app/c/me/[dmId]/loading.tsx@@ -0,0 +1,5 @@+import { DmLoadingFrame } from "@/components/community/channels/dm-loading-frame"++export default function DmLoading() {+ return <DmLoadingFrame />+}diff --git a/src/web/src/app/c/me/[dmId]/page.test.ts b/src/web/src/app/c/me/[dmId]/page.test.tsnew file mode 100644index 000000000..227f28736--- /dev/null+++ b/src/web/src/app/c/me/[dmId]/page.test.ts@@ -0,0 +1,18 @@+import { readFileSync } from "node:fs"+import { describe, expect, it } from "vitest"++describe("DM page loading ownership", () => {+ it("keeps full-frame and message-body ownership separate", () => {+ const source = readFileSync(new URL("./page.tsx", import.meta.url), "utf8")+ expect(source).toContain("fullFramePending: !hasDm && dmsLoading")+ expect(source).toContain("notFound: !hasDm && !dmsLoading")+ expect(source).toContain("messageBodyLoading: hasDm && (")+ expect(source).toContain("readSnapshotFetching ||\n messagesLoading")+ expect(source).toContain("if (loadingOwnership.fullFramePending)")+ expect(source).toContain("<DmHeader\n")+ expect(source).toContain("<Composer\n")+ expect(source).toContain("loading={loadingOwnership.messageBodyLoading}")+ expect(source).not.toContain("<ComposerSkeleton")+ expect(source).not.toContain("<DmHeaderSkeleton")+ })+})diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsxindex 3768df03b..24ff968e3 100644--- a/src/web/src/app/c/me/[dmId]/page.tsx+++ b/src/web/src/app/c/me/[dmId]/page.tsx@@ -2,13 +2,15 @@import { useCallback, useEffect, useMemo, useState } from "react"import { useParams, useSearchParams } from "next/navigation"+import { useQuery } from "@tanstack/react-query"import { toast } from "sonner"import { useBreakpoint } from "@/hooks/use-mobile"-import { DmHeader, DmHeaderSkeleton } from "@/components/community/channels/dm-header"+import { DmHeader } from "@/components/community/channels/dm-header"+import { DmLoadingFrame } from "@/components/community/channels/dm-loading-frame"import { Avatar } from "@/components/community/avatar"import { MessageList } from "@/components/community/messages/message-list"import { MessageContextSheet } from "@/components/community/messages/message-context-sheet"-import { Composer, ComposerSkeleton, type SendAttachment } from "@/components/community/messages/composer"+import { Composer, type SendAttachment } from "@/components/community/messages/composer"import type { FileAttachment, ImagePreview } from "@/lib/community/models/message"import type { OpenProfile } from "@/components/community/social/profile-types"import {@@ -22,7 +24,7 @@ import { useOnlineUserIds, useCommunityWsStore } from "@/stores/community/ws"import { tid } from "@/lib/community/testids"import { resolveRowPresence } from "@/lib/community/presence"import { makeUserNameResolver } from "@/lib/community/display-name"-import { useDms } from "@/hooks/community/use-dms"+import { dmsQueryFn, type DmsResponse } from "@/hooks/community/use-dms"import { useFriends } from "@/hooks/community/use-friends"import { useDmMessages } from "@/hooks/community/use-messages"import { useDmReadStateSnapshot } from "@/hooks/community/use-dm-read-state"@@ -50,6 +52,9 @@ import { notifLevelDisplay, type NotifLevel } from "@alook/shared"import { useNotificationSettings } from "@/hooks/community/use-notification-settings"import { useSetChannelNotif } from "@/hooks/community/mutations"import { toastApiError } from "@/lib/api/client"+import { communityKeys } from "@/lib/query-keys"++const EMPTY_DMS: DmsResponse["conversations"] = []// Thin re-mount wrapper — same reason as the server-side channel view: the// dynamic segment reuses the same component instance across DM switches, so@@ -59,6 +64,30 @@ export default function DmPage() {return <DmView key={params.dmId} />}+function resolveDmLoadingOwnership({+ hasDm,+ dmsLoading,+ currentChannelMatches,+ readSnapshotFetching,+ messagesLoading,+}: {+ hasDm: boolean+ dmsLoading: boolean+ currentChannelMatches: boolean+ readSnapshotFetching: boolean+ messagesLoading: boolean+}) {+ return {+ fullFramePending: !hasDm && dmsLoading,+ notFound: !hasDm && !dmsLoading,+ messageBodyLoading: hasDm && (+ !currentChannelMatches ||+ readSnapshotFetching ||+ messagesLoading+ ),+ }+}+function DmView() {const params = useParams<{ dmId: string }>()const dmId = params.dmId@@ -69,7 +98,16 @@ function DmView() {const notifications = useNotificationSettings()const setNotification = useSetChannelNotif()- const { dms, isLoading: dmsLoading } = useDms()+ // MeLayout owns the canonical cold DMs fetch. This second observer consumes+ // that result without treating it as stale on mount; explicit WS/query+ // invalidation still refetches the active canonical key.+ const dmsQuery = useQuery<DmsResponse>({+ queryKey: communityKeys.dms(),+ queryFn: dmsQueryFn,+ staleTime: Infinity,+ })+ const dms = dmsQuery.data?.conversations ?? EMPTY_DMS+ const dmsLoading = dmsQuery.isLoadingconst { friends: rawFriends, blocked } = useFriends()const onlineUserIds = useOnlineUserIds()const userStatuses = useCommunityWsStore((s) => s.userStatuses)@@ -340,31 +378,22 @@ function DmView() {const handleTyping = () => { communityWsSendTyping({ channelId: dmId }) }- // Wait for query to catch up to the URL and for messages to load. See- // the server-side channel page for the same rationale — the store's- // channelId sync runs after this render commits, so gate on the two- // lining up before showing real content.- const channelHydrated =- currentChannelId === dmId &&- !messagesLoading &&- !dmsLoading- if (!channelHydrated) {- return (- <>- <DmHeaderSkeleton onBack={bp === "mobile" ? goBack : undefined} />- <main className="flex min-h-0 min-w-0 flex-1 flex-col">- {/* `key={dmId}` matches the real-content branch below — same- reconciliation fix as the channel page (see its equivalent- comment). `variant="dm"` now drives the skeleton shape- explicitly instead of the removed `dm={!!hero}` inference. */}- <MessageList key={dmId} channel="" messages={[]} loading={true} onOpenThread={() => { }} variant="dm" />- <ComposerSkeleton />- </main>- </>- )+ // The DM row owns header/composer identity. Until it is known, keep the+ // complete DM frame pending; once known, read-state and message fetching+ // are allowed to affect only MessageList below.+ const loadingOwnership = resolveDmLoadingOwnership({+ hasDm: !!dm,+ dmsLoading,+ currentChannelMatches: currentChannelId === dmId,+ readSnapshotFetching,+ messagesLoading,+ })++ if (loadingOwnership.fullFramePending) {+ return <DmLoadingFrame reserveBackSlot={bp === "mobile"} />}- if (!dm) {+ if (loadingOwnership.notFound || !dm) {return (<div className="flex flex-1 items-center justify-center text-muted-foreground"><span className="text-sm">Conversation not found</span>@@ -390,7 +419,7 @@ function DmView() {variant="dm"channel={dm.name}messages={messages}- loading={messagesLoading}+ loading={loadingOwnership.messageBodyLoading}newDividerBefore={newDividerBefore}typingUsers={typingUsers.map((id) => typingNames[id] ?? resolveUserName(id))}onOpenThread={() => { }}diff --git a/src/web/src/app/c/me/bots/loading.tsx b/src/web/src/app/c/me/bots/loading.tsxnew file mode 100644index 000000000..d8e76aac8--- /dev/null+++ b/src/web/src/app/c/me/bots/loading.tsx@@ -0,0 +1,5 @@+import { CommunityPendingFrame } from "@/components/community/shell/community-pending-frame"++export default function BotsLoading() {+ return <CommunityPendingFrame href="/c/me/bots" />+}diff --git a/src/web/src/app/c/me/friends/loading.tsx b/src/web/src/app/c/me/friends/loading.tsxnew file mode 100644index 000000000..797c0f809--- /dev/null+++ b/src/web/src/app/c/me/friends/loading.tsx@@ -0,0 +1,5 @@+import { CommunityPendingFrame } from "@/components/community/shell/community-pending-frame"++export default function FriendsLoading() {+ return <CommunityPendingFrame href="/c/me/friends" />+}diff --git a/src/web/src/app/c/me/layout.tsx b/src/web/src/app/c/me/layout.tsxindex 5e308805a..22234580c 100644--- a/src/web/src/app/c/me/layout.tsx+++ b/src/web/src/app/c/me/layout.tsx@@ -5,6 +5,7 @@ import { useQueryClient } from "@tanstack/react-query"import { usePathname, useRouter, useParams } from "next/navigation"import { ShellFrame } from "@/components/community/shell/shell-frame"import { CommunityPendingFrame } from "@/components/community/shell/community-pending-frame"+import { DmRouteErrorFrame } from "@/components/community/channels/dm-route-error-frame"import { DmSidebar } from "@/components/community/channels/dm-sidebar"import { useCommunityStore, useCurrentChannelId } from "@/stores/community"import { useDms } from "@/hooks/community/use-dms"@@ -28,8 +29,14 @@ export default function MeLayout({ children }: { children: ReactNode }) {const router = useRouter()const pathname = usePathname()const params = useParams<{ dmId?: string }>()- const { dms: rawDms, isLoading: dmsLoading } = useDms()- const dmRouteStatus = useDmRouteVerification(params.dmId, rawDms)+ const {+ dms: rawDms,+ isLoading: dmsLoading,+ isPending: dmsPending,+ isFetching: dmsFetching,+ } = useDms()+ const canonicalDmsUnsettled = dmsPending || dmsFetching+ const dmRouteVerification = useDmRouteVerification(params.dmId, rawDms, canonicalDmsUnsettled)const onlineUserIds = useOnlineUserIds()const dms = useMemo(() =>@@ -72,7 +79,7 @@ export default function MeLayout({ children }: { children: ReactNode }) {const meLocationStatus = resolveMeLocationStatus({pathname,dmId: params.dmId,- dmRouteStatus,+ dmRouteStatus: dmRouteVerification.status,})useEffect(() => {@@ -161,7 +168,12 @@ export default function MeLayout({ children }: { children: ReactNode }) {activeServerId={undefined}sidebar={sidebar}>- {params.dmId && meLocationStatus !== "remember"+ {params.dmId && dmRouteVerification.status === "error"+ ? <DmRouteErrorFrame+ onRetry={dmRouteVerification.retry}+ retrying={dmRouteVerification.retrying}+ />+ : params.dmId && meLocationStatus !== "remember"? <CommunityPendingFrame href={pathname} />: children}</ShellFrame>diff --git a/src/web/src/app/c/me/loading.test.ts b/src/web/src/app/c/me/loading.test.tsnew file mode 100644index 000000000..e2db82153--- /dev/null+++ b/src/web/src/app/c/me/loading.test.ts@@ -0,0 +1,43 @@+import { createElement } from "react"+// @ts-expect-error react-test-renderer intentionally has no local declaration package.+import TestRenderer, { act } from "react-test-renderer"+import { describe, expect, it, vi } from "vitest"++vi.mock("@/components/community/shell/community-pending-frame", () => ({+ CommunityPendingFrame: (props: Record<string, unknown>) => createElement("pending-frame", props),+}))+vi.mock("@/components/community/channels/dm-loading-frame", () => ({+ DmLoadingFrame: (props: Record<string, unknown>) => createElement("dm-loading-frame", props),+}))++import MeLoading from "./loading"+import FriendsLoading from "./friends/loading"+import MachinesLoading from "./machines/loading"+import BotsLoading from "./bots/loading"+import DmLoading from "./[dmId]/loading"++function hrefFor(Component: () => React.ReactNode) {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(createElement(Component))+ })+ return renderer.root.findByType("pending-frame").props.href+}++describe("Me route loading boundaries", () => {+ it("assigns the root and static leaves their own pending href", () => {+ expect(hrefFor(MeLoading)).toBe("/c/me")+ expect(hrefFor(FriendsLoading)).toBe("/c/me/friends")+ expect(hrefFor(MachinesLoading)).toBe("/c/me/machines")+ expect(hrefFor(BotsLoading)).toBe("/c/me/bots")+ })++ it("uses the dedicated DM loading frame for a dynamic leaf", () => {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(createElement(DmLoading))+ })+ expect(renderer.root.findAllByType("dm-loading-frame")).toHaveLength(1)+ expect(renderer.root.findAllByType("pending-frame")).toHaveLength(0)+ })+})diff --git a/src/web/src/app/c/me/loading.tsx b/src/web/src/app/c/me/loading.tsxindex 6125f5c95..793021814 100644--- a/src/web/src/app/c/me/loading.tsx+++ b/src/web/src/app/c/me/loading.tsx@@ -1,5 +1,5 @@-import { ChannelLoadingFrame } from "@/components/community/channels/channel-loading-frame"+import { CommunityPendingFrame } from "@/components/community/shell/community-pending-frame"export default function MeRouteLoading() {- return <ChannelLoadingFrame />+ return <CommunityPendingFrame href="/c/me" />}diff --git a/src/web/src/app/c/me/machines/loading.tsx b/src/web/src/app/c/me/machines/loading.tsxnew file mode 100644index 000000000..b3a6fc765--- /dev/null+++ b/src/web/src/app/c/me/machines/loading.tsx@@ -0,0 +1,5 @@+import { CommunityPendingFrame } from "@/components/community/shell/community-pending-frame"++export default function MachinesLoading() {+ return <CommunityPendingFrame href="/c/me/machines" />+}diff --git a/src/web/src/app/c/me/page.test.ts b/src/web/src/app/c/me/page.test.tsnew file mode 100644index 000000000..bae74059f--- /dev/null+++ b/src/web/src/app/c/me/page.test.ts@@ -0,0 +1,62 @@+import { createElement } from "react"+// @ts-expect-error react-test-renderer intentionally has no local declaration package.+import TestRenderer, { act } from "react-test-renderer"+import { beforeEach, describe, expect, it, vi } from "vitest"++const mocks = vi.hoisted(() => ({+ breakpoint: "unknown" as "unknown" | "desktop" | "mobile",+ lastLeaf: null as string | null,+ replace: vi.fn(),+}))++vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: mocks.replace }) }))+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mocks.breakpoint }))+vi.mock("@/lib/community/last-me-location", () => ({+ getLastMeLeaf: () => mocks.lastLeaf,+ pickMeLandingLocation: (leaf: string | null) => `/c/me/${leaf ?? "friends"}`,+}))+vi.mock("@/components/community/shell/community-pending-frame", () => ({+ CommunityPendingFrame: (props: Record<string, unknown>) => createElement("pending-frame", props),+}))++import MeListPage from "./page"++describe("MeListPage", () => {+ beforeEach(() => {+ mocks.breakpoint = "unknown"+ mocks.lastLeaf = null+ mocks.replace.mockClear()+ })++ it.each(["unknown", "mobile"] as const)("keeps %s on the canonical list root", (breakpoint) => {+ mocks.breakpoint = breakpoint+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(createElement(MeListPage))+ })+ expect(mocks.replace).not.toHaveBeenCalled()+ expect(renderer.toJSON()).toBeNull()+ })++ it("replaces desktop with remembered leaf while keeping its pending module mounted", () => {+ mocks.breakpoint = "desktop"+ mocks.lastLeaf = "dm-last"+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(createElement(MeListPage))+ })+ expect(mocks.replace).toHaveBeenCalledTimes(1)+ expect(mocks.replace).toHaveBeenCalledWith("/c/me/dm-last")+ expect(renderer.root.findByType("pending-frame").props.href).toBe("/c/me/dm-last")+ })++ it("defaults desktop to Friends", () => {+ mocks.breakpoint = "desktop"+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(createElement(MeListPage))+ })+ expect(mocks.replace).toHaveBeenCalledWith("/c/me/friends")+ expect(renderer.root.findByType("pending-frame").props.href).toBe("/c/me/friends")+ })+})diff --git a/src/web/src/app/c/me/page.tsx b/src/web/src/app/c/me/page.tsxindex 714f0b86e..c4b96fbd4 100644--- a/src/web/src/app/c/me/page.tsx+++ b/src/web/src/app/c/me/page.tsx@@ -3,16 +3,20 @@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 { getLastMeLeaf, pickMeLandingLocation } from "@/lib/community/last-me-location"export default function MeListPage() {const router = useRouter()const breakpoint = useBreakpoint()+ const destination = breakpoint === "desktop"+ ? pickMeLandingLocation(getLastMeLeaf())+ : nulluseEffect(() => {- if (breakpoint !== "desktop") return- router.replace(pickMeLandingLocation(getLastMeLeaf()))- }, [breakpoint, router])+ if (!destination) return+ router.replace(destination)+ }, [destination, router])- return null+ return destination ? <CommunityPendingFrame href={destination} /> : null}diff --git a/src/web/src/components/community/channels/dm-loading-frame.test.ts b/src/web/src/components/community/channels/dm-loading-frame.test.tsnew file mode 100644index 000000000..0aa7889c7--- /dev/null+++ b/src/web/src/components/community/channels/dm-loading-frame.test.ts@@ -0,0 +1,29 @@+import { createElement } from "react"+// @ts-expect-error react-test-renderer intentionally has no local declaration package.+import TestRenderer, { act } from "react-test-renderer"+import { describe, expect, it, vi } from "vitest"++vi.mock("./dm-header", () => ({+ DmHeaderSkeleton: (props: Record<string, unknown>) => createElement("dm-header-skeleton", props),+}))+vi.mock("@/components/community/messages/message-list", () => ({+ MessageList: (props: Record<string, unknown>) => createElement("message-list", props),+}))+vi.mock("@/components/community/messages/composer", () => ({+ ComposerSkeleton: () => createElement("composer-skeleton"),+}))++import { DmLoadingFrame } from "./dm-loading-frame"++describe("DmLoadingFrame", () => {+ it("uses DM header, message, and composer skeletons", () => {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(createElement(DmLoadingFrame, { reserveBackSlot: true }))+ })+ expect(renderer.root.findByType("dm-header-skeleton").props.onBack).toBeTypeOf("function")+ expect(renderer.root.findByType("message-list").props).toMatchObject({ loading: true, variant: "dm" })+ expect(renderer.root.findAllByType("composer-skeleton")).toHaveLength(1)+ expect(renderer.root.findByProps({ "aria-label": "Loading direct message" }).props["aria-busy"]).toBe("true")+ })+})diff --git a/src/web/src/components/community/channels/dm-loading-frame.tsx b/src/web/src/components/community/channels/dm-loading-frame.tsxnew file mode 100644index 000000000..dc9a242e0--- /dev/null+++ b/src/web/src/components/community/channels/dm-loading-frame.tsx@@ -0,0 +1,17 @@+"use client"++import { DmHeaderSkeleton } from "./dm-header"+import { MessageList } from "@/components/community/messages/message-list"+import { ComposerSkeleton } from "@/components/community/messages/composer"++export function DmLoadingFrame({ reserveBackSlot = false }: { reserveBackSlot?: boolean }) {+ return (+ <>+ <DmHeaderSkeleton onBack={reserveBackSlot ? () => {} : undefined} />+ <main className="flex min-h-0 min-w-0 flex-1 flex-col" aria-busy="true" aria-label="Loading direct message">+ <MessageList channel="" messages={[]} loading onOpenThread={() => {}} variant="dm" />+ <ComposerSkeleton />+ </main>+ </>+ )+}diff --git a/src/web/src/components/community/channels/dm-route-error-frame.test.ts b/src/web/src/components/community/channels/dm-route-error-frame.test.tsnew file mode 100644index 000000000..3540781d4--- /dev/null+++ b/src/web/src/components/community/channels/dm-route-error-frame.test.ts@@ -0,0 +1,37 @@+import { createElement } from "react"+// @ts-expect-error react-test-renderer intentionally has no local declaration package.+import TestRenderer, { act } from "react-test-renderer"+import { describe, expect, it, vi } from "vitest"++vi.mock("lucide-react", () => ({ AlertCircle: () => createElement("alert-icon") }))+vi.mock("@/components/ui/button", () => ({+ Button: ({ children, ...props }: { children: React.ReactNode } & Record<string, unknown>) =>+ createElement("button", props, children),+}))+vi.mock("./dm-header", () => ({+ DmHeaderSkeleton: (props: Record<string, unknown>) => createElement("dm-header-skeleton", props),+}))+vi.mock("@/components/community/messages/composer", () => ({+ ComposerSkeleton: () => createElement("composer-skeleton"),+}))++import { DmRouteErrorFrame } from "./dm-route-error-frame"++describe("DmRouteErrorFrame", () => {+ it("retries locally and disables the action while retrying", () => {+ const retry = vi.fn()+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(createElement(DmRouteErrorFrame, { onRetry: retry, retrying: false }))+ })+ const button = renderer.root.findByType("button")+ act(() => button.props.onClick())+ expect(retry).toHaveBeenCalledTimes(1)++ act(() => {+ renderer.update(createElement(DmRouteErrorFrame, { onRetry: retry, retrying: true }))+ })+ expect(renderer.root.findByType("button").props.disabled).toBe(true)+ expect(renderer.root.findByProps({ role: "alert" })).toBeDefined()+ })+})diff --git a/src/web/src/components/community/channels/dm-route-error-frame.tsx b/src/web/src/components/community/channels/dm-route-error-frame.tsxnew file mode 100644index 000000000..7ad9bd820--- /dev/null+++ b/src/web/src/components/community/channels/dm-route-error-frame.tsx@@ -0,0 +1,35 @@+"use client"++import { AlertCircle } from "lucide-react"+import { Button } from "@/components/ui/button"+import { DmHeaderSkeleton } from "./dm-header"+import { ComposerSkeleton } from "@/components/community/messages/composer"++export function DmRouteErrorFrame({+ onRetry,+ retrying,+ reserveBackSlot = false,+}: {+ onRetry: () => void+ retrying: boolean+ reserveBackSlot?: boolean+}) {+ return (+ <>+ <DmHeaderSkeleton onBack={reserveBackSlot ? () => {} : undefined} />+ <main className="flex min-h-0 min-w-0 flex-1 flex-col">+ <div role="alert" className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 px-6 text-center">+ <AlertCircle className="size-5 text-muted-foreground" aria-hidden />+ <div>+ <p className="text-sm font-medium">Couldn't verify this conversation</p>+ <p className="mt-1 text-xs text-muted-foreground">Check your connection and try again.</p>+ </div>+ <Button size="sm" variant="outline" onClick={onRetry} disabled={retrying}>+ {retrying ? "Retrying…" : "Retry"}+ </Button>+ </div>+ <ComposerSkeleton />+ </main>+ </>+ )+}diff --git a/src/web/src/components/community/shell/community-pending-frame.test.ts b/src/web/src/components/community/shell/community-pending-frame.test.tsindex b80ccb6e9..fe4749856 100644--- a/src/web/src/components/community/shell/community-pending-frame.test.ts+++ b/src/web/src/components/community/shell/community-pending-frame.test.ts@@ -14,6 +14,12 @@ vi.mock("@/components/community/social/friends-page", () => ({vi.mock("@/components/community/channels/channel-loading-frame", () => ({ChannelLoadingFrame: (props: Record<string, unknown>) => createElement("channel-skeleton", props),}))+vi.mock("@/components/community/channels/dm-loading-frame", () => ({+ DmLoadingFrame: (props: Record<string, unknown>) => createElement("dm-skeleton", props),+}))+vi.mock("@/components/ui/skeleton", () => ({+ Skeleton: (props: Record<string, unknown>) => createElement("skeleton", props),+}))import { CommunityPendingFrame } from "./community-pending-frame"@@ -48,11 +54,15 @@ describe("CommunityPendingFrame", () => {expect(friends.root.findByType("friends-skeleton").props.onBack).toBeUndefined()})- it("uses the canonical conversation skeleton for DM and channel details", () => {- for (const href of ["/c/me/dm_1", "/c/channels/s1/c1"] ) {- const result = render(href)- expect(result.root.findByType("channel-skeleton").props.reserveBackSlot).toBe(true)- expect(result.root.findByType("channel-skeleton").props.onBack).toBeUndefined()- }+ it("separates the neutral Me root, DM, and channel fallbacks", () => {+ const root = render("/c/me")+ expect(root.root.findByProps({ "aria-label": "Loading your space" }).props["aria-busy"]).toBe("true")++ const dm = render("/c/me/dm_1")+ expect(dm.root.findByType("dm-skeleton").props.reserveBackSlot).toBe(true)++ const channel = render("/c/channels/s1/c1")+ expect(channel.root.findByType("channel-skeleton").props.reserveBackSlot).toBe(true)+ expect(channel.root.findByType("channel-skeleton").props.onBack).toBeUndefined()})})diff --git a/src/web/src/components/community/shell/community-pending-frame.tsx b/src/web/src/components/community/shell/community-pending-frame.tsxindex fb3ddf9aa..dbf5d0be0 100644--- a/src/web/src/components/community/shell/community-pending-frame.tsx+++ b/src/web/src/components/community/shell/community-pending-frame.tsx@@ -2,8 +2,20 @@import { BotListSkeleton } from "@/components/community/bots/bot-list-view"import { ChannelLoadingFrame } from "@/components/community/channels/channel-loading-frame"+import { DmLoadingFrame } from "@/components/community/channels/dm-loading-frame"import { MachineListSkeleton } from "@/components/community/machines/machine-list"import { FriendsPage } from "@/components/community/social/friends-page"+import { Skeleton } from "@/components/ui/skeleton"++function MeRootPendingFrame() {+ return (+ <main aria-busy="true" aria-label="Loading your space" className="flex min-h-0 flex-1 flex-col gap-3 p-4">+ <Skeleton className="h-6 w-32" />+ <Skeleton className="h-14 w-full" />+ <Skeleton className="h-14 w-5/6" />+ </main>+ )+}export function CommunityPendingFrame({href,@@ -13,6 +25,7 @@ export function CommunityPendingFrame({reserveBackSlot?: boolean}) {const pathname = href.split(/[?#]/, 1)[0]+ if (pathname === "/c/me") return <MeRootPendingFrame />if (pathname === "/c/me/machines") return <MachineListSkeleton reserveBackSlot={reserveBackSlot} />if (pathname === "/c/me/bots") return <BotListSkeleton reserveBackSlot={reserveBackSlot} />if (pathname === "/c/me/friends") {@@ -26,5 +39,8 @@ export function CommunityPendingFrame({/>)}+ if (/^\/c\/me\/[^/]+$/.test(pathname)) {+ return <DmLoadingFrame reserveBackSlot={reserveBackSlot} />+ }return <ChannelLoadingFrame reserveBackSlot={reserveBackSlot} />}diff --git a/src/web/src/components/community/shell/community-session-pending-frame.test.ts b/src/web/src/components/community/shell/community-session-pending-frame.test.tsnew file mode 100644index 000000000..85199a9c4--- /dev/null+++ b/src/web/src/components/community/shell/community-session-pending-frame.test.ts@@ -0,0 +1,24 @@+import { createElement } from "react"+// @ts-expect-error react-test-renderer intentionally has no local declaration package.+import TestRenderer, { act } from "react-test-renderer"+import { describe, expect, it, vi } from "vitest"++vi.mock("@/components/ui/skeleton", () => ({+ Skeleton: (props: Record<string, unknown>) => createElement("skeleton", props),+}))++import { CommunitySessionPendingFrame } from "./community-session-pending-frame"++describe("CommunitySessionPendingFrame", () => {+ it("renders a stable inert viewport without community controls", () => {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(createElement(CommunitySessionPendingFrame))+ })+ const frame = renderer.root.findByProps({ "aria-label": "Loading community" })+ expect(frame.props["aria-busy"]).toBe("true")+ expect(renderer.root.findAllByType("skeleton").length).toBeGreaterThan(5)+ expect(renderer.root.findAllByType("button")).toEqual([])+ expect(renderer.root.findAllByType("a")).toEqual([])+ })+})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.tsxnew file mode 100644index 000000000..bdd91088b--- /dev/null+++ b/src/web/src/components/community/shell/community-session-pending-frame.tsx@@ -0,0 +1,37 @@+import { Skeleton } from "@/components/ui/skeleton"++/** Stable, inert viewport shown before authenticated community providers exist. */+export function CommunitySessionPendingFrame() {+ return (+ <main+ aria-busy="true"+ aria-label="Loading community"+ className="flex h-dvh min-h-0 overflow-hidden bg-muted/40 p-2 pl-0"+ >+ <div aria-hidden className="flex w-14 shrink-0 flex-col items-center gap-3 py-2">+ <Skeleton className="size-10 rounded-xl" />+ <Skeleton className="size-10 rounded-full" />+ <Skeleton className="size-10 rounded-full" />+ </div>+ <div aria-hidden className="flex min-w-0 flex-1 overflow-hidden rounded-tl-xl border-l border-t border-border/40 bg-background">+ <div className="hidden w-60 shrink-0 flex-col gap-3 border-r border-border/40 bg-sidebar p-3 sm:flex">+ <Skeleton className="h-6 w-28" />+ <Skeleton className="h-9 w-full" />+ <Skeleton className="h-9 w-4/5" />+ <Skeleton className="mt-auto h-11 w-full" />+ </div>+ <div className="flex min-w-0 flex-1 flex-col">+ <div className="flex h-12 items-center gap-2 border-b border-border/40 px-3">+ <Skeleton className="size-6 rounded-full" />+ <Skeleton className="h-4 w-36" />+ </div>+ <div className="flex flex-1 flex-col gap-4 p-4">+ <Skeleton className="h-16 w-2/3 max-w-md" />+ <Skeleton className="h-16 w-3/4 max-w-lg" />+ <Skeleton className="h-16 w-1/2 max-w-sm" />+ </div>+ </div>+ </div>+ </main>+ )+}diff --git a/src/web/src/components/community/shell/shell-frame.test.ts b/src/web/src/components/community/shell/shell-frame.test.tsindex aa5eeb6f8..605412adc 100644--- a/src/web/src/components/community/shell/shell-frame.test.ts+++ b/src/web/src/components/community/shell/shell-frame.test.ts@@ -25,6 +25,7 @@ const mocks = vi.hoisted(() => {navigate: handlers.navigate,cancelPendingNavigation: handlers.cancelPendingNavigation,},+ railOptions: vi.fn(),profile: {previewImage: handlers.previewImage,previewAttachment: handlers.previewAttachment,@@ -57,7 +58,10 @@ vi.mock("@/stores/community", () => ({}),}))vi.mock("./use-shell-rail-controller", () => ({- useShellRailController: () => mocks.rail,+ useShellRailController: (options: unknown) => {+ mocks.railOptions(options)+ return mocks.rail+ },}))vi.mock("./use-shell-profile-controller", () => ({useShellProfileController: () => mocks.profile,@@ -84,6 +88,7 @@ describe("ShellFrame orchestration", () => {mocks.registerUiHandlers.mockClear()mocks.replace.mockClear()mocks.push.mockClear()+ mocks.railOptions.mockClear()})afterEach(() => vi.unstubAllGlobals())@@ -190,4 +195,19 @@ describe("ShellFrame orchestration", () => {expect(second.navigatePath).toBe(withMessage.navigatePath)expect(second.replacePath).toBe(withMessage.replacePath)})++ it("passes the single resolved breakpoint to the rail controller", async () => {+ mocks.breakpoint.current = "unknown"+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(ShellFrame, baseProps))+ })+ expect(mocks.railOptions).toHaveBeenLastCalledWith(expect.objectContaining({ breakpoint: "unknown" }))++ mocks.breakpoint.current = "mobile"+ await act(async () => {+ renderer.update(createElement(ShellFrame, baseProps, "mobile"))+ })+ expect(mocks.railOptions).toHaveBeenLastCalledWith(expect.objectContaining({ breakpoint: "mobile" }))+ })})diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsxindex 2e21ed830..e7a2a01d6 100644--- a/src/web/src/components/community/shell/shell-frame.tsx+++ b/src/web/src/components/community/shell/shell-frame.tsx@@ -37,6 +37,7 @@ export function ShellFrame(props: ShellFrameProps) {const rail = useShellRailController({navigation,queryClient,+ breakpoint,view,activeServerId,onOpenActiveServerSettings,diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.test.ts b/src/web/src/components/community/shell/use-shell-rail-controller.test.tsindex 0032c3a68..6c89fa078 100644--- a/src/web/src/components/community/shell/use-shell-rail-controller.test.ts+++ b/src/web/src/components/community/shell/use-shell-rail-controller.test.ts@@ -18,6 +18,7 @@ const mocks = vi.hoisted(() => ({markSwitch: vi.fn(),toast: vi.fn(),toastApiError: vi.fn(),+ lastMeLeaf: { current: null as string | null },}))vi.mock("sonner", () => ({ toast: mocks.toast }))@@ -55,8 +56,9 @@ vi.mock("@/lib/community/last-channel", () => ({channelIds[0] ? `/c/channels/${id}/${channelIds[0]}` : `/c/channels/${id}`,}))vi.mock("@/lib/community/last-me-location", () => ({- getLastMeLeaf: () => null,- pickMeLandingLocation: () => "/c/me",+ ME_ROOT: "/c/me",+ getLastMeLeaf: () => mocks.lastMeLeaf.current,+ pickMeLandingLocation: (leaf: string | null) => `/c/me/${leaf ?? "friends"}`,}))type Result = ReturnType<typeof useShellRailController>@@ -95,6 +97,7 @@ async function renderController(overrides: Record<string, unknown> = {}) {const options = {navigation,queryClient,+ breakpoint: "desktop",view: "server",activeServerId: "s1",...overrides,@@ -132,6 +135,7 @@ describe("useShellRailController", () => {for (const mock of Object.values(mocks)) {if (typeof mock === "function" && "mockReset" in mock) mock.mockReset()}+ mocks.lastMeLeaf.current = null})it("commits cold server navigation synchronously without waiting for detail", async () => {@@ -198,7 +202,7 @@ describe("useShellRailController", () => {hook.current.railProps.onServerNavigate("s2")hook.current.railProps.onHome()})- expect(hook.pushed).toEqual(["/c/channels/s2", "/c/me"])+ expect(hook.pushed).toEqual(["/c/channels/s2", "/c/me/friends"])expect(hook.queryClient.fetchQuery).not.toHaveBeenCalled()})@@ -222,7 +226,7 @@ describe("useShellRailController", () => {await act(async () => hook.current.railProps.onServerPrefetch("s1"))await act(async () => hook.current.railProps.onHomePrefetch())expect(hook.pushed).toEqual(["/c/channels/s1"])- expect(hook.prefetched).toEqual(["/c/channels/s1/cached", "/c/me"])+ expect(hook.prefetched).toEqual(["/c/channels/s1/cached", "/c/me/friends"])expect(hook.queryClient.fetchQuery).not.toHaveBeenCalled()hook.queryClient.fetchQuery.mockImplementationOnce(async ({ queryKey }: { queryKey: unknown[] }) => {@@ -245,6 +249,27 @@ describe("useShellRailController", () => {expect(hook.prefetched).toContain("/c/channels/s3")})+ it("uses one breakpoint-canonical Home destination for click and prefetch", async () => {+ mocks.lastMeLeaf.current = "dm-last"+ const desktop = await renderController({ breakpoint: "desktop" })+ await act(async () => {+ desktop.current.railProps.onHomePrefetch()+ desktop.current.railProps.onHome()+ })+ expect(desktop.prefetched).toEqual(["/c/me/dm-last"])+ expect(desktop.pushed).toEqual(["/c/me/dm-last"])++ for (const breakpoint of ["mobile", "unknown"] as const) {+ const safeRoot = await renderController({ breakpoint })+ await act(async () => {+ safeRoot.current.railProps.onHomePrefetch()+ safeRoot.current.railProps.onHome()+ })+ expect(safeRoot.prefetched).toEqual(["/c/me"])+ expect(safeRoot.pushed).toEqual(["/c/me"])+ }+ })+it("keeps callback fields stable without stabilizing the railProps aggregate", async () => {const hook = await renderController()const firstProps = hook.current.railPropsdiff --git a/src/web/src/components/community/shell/use-shell-rail-controller.ts b/src/web/src/components/community/shell/use-shell-rail-controller.tsindex 33946c695..fc40e9675 100644--- a/src/web/src/components/community/shell/use-shell-rail-controller.ts+++ b/src/web/src/components/community/shell/use-shell-rail-controller.ts@@ -19,7 +19,8 @@ import {useCreateServerFolderWith,} from "@/hooks/community/mutations"import { getLastChannel, pickServerLandingHref } from "@/lib/community/last-channel"-import { getLastMeLeaf, pickMeLandingLocation } from "@/lib/community/last-me-location"+import { getLastMeLeaf, ME_ROOT, pickMeLandingLocation } from "@/lib/community/last-me-location"+import type { Breakpoint } from "@/hooks/use-mobile"import { useCommunityStore } from "@/stores/community"import { resolveServerRailOverlayAction } from "./server-rail-actions"import type { ShellFrameProps } from "./shell-frame-types"@@ -35,11 +36,13 @@ type Options = Pick<> & {navigation: CommunityNavigationControllerqueryClient: QueryClient+ breakpoint: Breakpoint}export function useShellRailController({navigation,queryClient,+ breakpoint,view,activeServerId,onOpenActiveServerSettings,@@ -97,15 +100,21 @@ export function useShellRailController({markSwitch("server", id)navigation.push(`/c/channels/${id}`)}, [navigation])+ const homeDestination = useCallback(+ () => breakpoint === "desktop"+ ? pickMeLandingLocation(getLastMeLeaf())+ : ME_ROOT,+ [breakpoint],+ )const onHome = useCallback(() => {- navigation.push("/c/me")- }, [navigation])+ navigation.push(homeDestination())+ }, [homeDestination, navigation])const onServerPrefetch = useCallback((id: string) => {void resolveServerDestination(id).then((destination) => navigation.prefetch(destination))}, [navigation, resolveServerDestination])const onHomePrefetch = useCallback(- () => navigation.prefetch(pickMeLandingLocation(getLastMeLeaf())),- [navigation],+ () => navigation.prefetch(homeDestination()),+ [homeDestination, navigation],)const onCreateServer = useCallback(async (name: string, icon?: File) => {try {diff --git a/src/web/src/hooks/community/use-dm-route-verification.test.ts b/src/web/src/hooks/community/use-dm-route-verification.test.tsindex 6ea29e4d3..8d6e603ed 100644--- a/src/web/src/hooks/community/use-dm-route-verification.test.ts+++ b/src/web/src/hooks/community/use-dm-route-verification.test.ts@@ -5,9 +5,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { communityKeys } from "@/lib/query-keys"import type { DM } from "@/lib/community/models/people"import {+ classifyDmRouteAuthorityError,startDmRouteVerification,useDmRouteVerification,- verifyDmRoute,+ type DmRouteVerificationResult,type DmRouteVerificationStatus,} from "./use-dm-route-verification"@@ -36,13 +37,19 @@ function deferred<T>() {function Capture({dmId,dms,+ canonicalUnsettled = false,onRender,+ onResult,}: {dmId: string | undefineddms: readonly DM[]+ canonicalUnsettled?: booleanonRender: (status: DmRouteVerificationStatus) => void+ onResult?: (result: DmRouteVerificationResult) => void}) {- onRender(useDmRouteVerification(dmId, dms))+ const result = useDmRouteVerification(dmId, dms, canonicalUnsettled)+ onRender(result.status)+ onResult?.(result)return null}@@ -118,18 +125,30 @@ describe("DM route verification", () => {expect(apiFetchMock).toHaveBeenCalledTimes(1)})+ it("trusts a provisional canonical cache row without starting authority", async () => {+ const queryClient = client()+ const provisional: DM = {+ id: "dm-provisional",+ userId: "u-provisional",+ name: "Provisional peer",+ discriminator: "4444",+ avatar: "P",+ status: "offline",+ preview: "",+ }+ queryClient.setQueryData(communityKeys.dms(), { conversations: [provisional] })++ await expect(startDmRouteVerification(queryClient, provisional.id)).resolves.toBe("present")+ expect(apiFetchMock).not.toHaveBeenCalled()+ })+it.each([403, 404])("classifies explicit %s as denied", async (status) => {- const queryClient = {- fetchQuery: vi.fn().mockRejectedValue(Object.assign(new Error("unavailable"), { status })),- } as unknown as QueryClient- await expect(verifyDmRoute(queryClient, "dm-denied")).resolves.toBe("denied")+ expect(classifyDmRouteAuthorityError({ status })).toBe("denied")})- it("does not convert a transient failure into a missing result", async () => {- const queryClient = {- fetchQuery: vi.fn().mockRejectedValue(Object.assign(new Error("offline"), { status: 0 })),- } as unknown as QueryClient- await expect(verifyDmRoute(queryClient, "dm-offline")).rejects.toMatchObject({ status: 0 })+ it("does not classify a transient failure as denied", () => {+ expect(classifyDmRouteAuthorityError({ status: 0 })).toBe("error")+ expect(classifyDmRouteAuthorityError(new Error("offline"))).toBe("error")})it("fetches and settles a cold missing route under Strict Mode", async () => {@@ -152,6 +171,119 @@ describe("DM route verification", () => {renderer.unmount()})+ it("waits for the canonical DMs query before verifying an absent route", async () => {+ const queryClient = client()+ apiFetchMock.mockResolvedValue({ conversations: [] })+ const statuses: DmRouteVerificationStatus[] = []+ const props = {+ dmId: "dm-missing",+ dms: [],+ canonicalUnsettled: true,+ onRender: (status: DmRouteVerificationStatus) => statuses.push(status),+ }+ const renderer = await renderHook(queryClient, props)++ expect(statuses.at(-1)).toBe("pending")+ expect(apiFetchMock).not.toHaveBeenCalled()++ await act(async () => {+ renderer.update(+ React.createElement(+ React.StrictMode,+ null,+ React.createElement(+ QueryClientProvider,+ { client: queryClient },+ React.createElement(Capture, { ...props, canonicalUnsettled: false }),+ ),+ ),+ )+ })+ await waitFor(() => statuses.at(-1) === "missing")+ expect(apiFetchMock).toHaveBeenCalledTimes(1)+ renderer.unmount()+ })++ it("waits for a stale canonical refetch that eventually contains the route", async () => {+ const queryClient = client()+ const canonical: DM = {+ id: "dm-refetched",+ userId: "u-refetched",+ name: "Refetched peer",+ discriminator: "3333",+ avatar: "R",+ status: "offline",+ preview: "",+ }+ const statuses: DmRouteVerificationStatus[] = []+ const props = {+ dmId: canonical.id,+ dms: [],+ canonicalUnsettled: true,+ onRender: (status: DmRouteVerificationStatus) => statuses.push(status),+ }+ const renderer = await renderHook(queryClient, props)++ expect(statuses.at(-1)).toBe("pending")+ expect(apiFetchMock).not.toHaveBeenCalled()++ await act(async () => {+ renderer.update(+ React.createElement(+ React.StrictMode,+ null,+ React.createElement(+ QueryClientProvider,+ { client: queryClient },+ React.createElement(Capture, {+ ...props,+ dms: [canonical],+ canonicalUnsettled: false,+ }),+ ),+ ),+ )+ })++ expect(statuses.at(-1)).toBe("present")+ expect(apiFetchMock).not.toHaveBeenCalled()+ renderer.unmount()+ })++ it("starts one authority request after a stale canonical refetch remains absent", async () => {+ const queryClient = client()+ apiFetchMock.mockResolvedValue({ conversations: [] })+ const statuses: DmRouteVerificationStatus[] = []+ const props = {+ dmId: "dm-still-missing",+ dms: [],+ canonicalUnsettled: true,+ onRender: (status: DmRouteVerificationStatus) => statuses.push(status),+ }+ const renderer = await renderHook(queryClient, props)++ expect(statuses.at(-1)).toBe("pending")+ expect(apiFetchMock).not.toHaveBeenCalled()++ await act(async () => {+ renderer.update(+ React.createElement(+ React.StrictMode,+ null,+ React.createElement(+ QueryClientProvider,+ { client: queryClient },+ React.createElement(Capture, { ...props, canonicalUnsettled: false }),+ ),+ ),+ )+ })+ await waitFor(() => statuses.at(-1) === "missing")++ expect(apiFetchMock).toHaveBeenCalledTimes(1)+ renderer.unmount()+ })+it("shares a click-started request with the route observer", async () => {const queryClient = client()const request = deferred<{ conversations: DM[] }>()@@ -183,26 +315,26 @@ describe("DM route verification", () => {renderer.unmount()})- it("keeps a transient route verification failure pending", async () => {+ it("surfaces a transient failure and retries only the current verification", async () => {const queryClient = client()const statuses: DmRouteVerificationStatus[] = []- const queryKey = communityKeys.dmRouteVerification("dm-offline")- await queryClient.fetchQuery({- queryKey,- queryFn: () => Promise.reject(Object.assign(new Error("offline"), { status: 0 })),- retry: false,- }).catch(() => undefined)- onlineManager.setOnline(false)+ let latest!: DmRouteVerificationResult+ apiFetchMock.mockRejectedValueOnce(Object.assign(new Error("offline"), { status: 0 }))const renderer = await renderHook(queryClient, {dmId: "dm-offline",dms: [],onRender: (status) => statuses.push(status),+ onResult: (result) => { latest = result },})- expect(statuses.at(-1)).toBe("pending")+ await waitFor(() => statuses.at(-1) === "error")expect(statuses).not.toContain("missing")- expect(queryClient.getQueryState(queryKey)?.fetchStatus).toBe("paused")- expect(apiFetchMock).not.toHaveBeenCalled()+ expect(apiFetchMock).toHaveBeenCalledTimes(1)++ apiFetchMock.mockResolvedValueOnce({ conversations: [] })+ await act(async () => latest.retry())+ await waitFor(() => statuses.at(-1) === "missing")+ expect(apiFetchMock).toHaveBeenCalledTimes(2)renderer.unmount()})diff --git a/src/web/src/hooks/community/use-dm-route-verification.ts b/src/web/src/hooks/community/use-dm-route-verification.tsindex 7a8c44827..fae8e4cff 100644--- a/src/web/src/hooks/community/use-dm-route-verification.ts+++ b/src/web/src/hooks/community/use-dm-route-verification.ts@@ -1,34 +1,45 @@"use client"-import { useEffect } from "react"+import { useCallback, useEffect } from "react"import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query"+import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import type { DM } from "@/lib/community/models/people"-import { dmsQueryFn, type DmsResponse } from "./use-dms"+import type { DmsResponse } from "./use-dms"++const dmRouteAuthorityQueryFn = () => apiFetch<DmsResponse>(+ "/api/community/users/me/dms",+)export type DmRouteVerification = "present" | "missing" | "denied"-export type DmRouteVerificationStatus = "idle" | "pending" | "present" | "missing"+export type DmRouteVerificationStatus = "idle" | "pending" | "present" | "missing" | "error"+export type DmRouteVerificationResult = {+ status: DmRouteVerificationStatus+ retry: () => void+ retrying: boolean+}-export async function verifyDmRoute(+export function classifyDmRouteAuthorityError(error: unknown): "denied" | "error" {+ const status = typeof error === "object" && error !== null && "status" in error+ ? error.status+ : undefined+ return status === 403 || status === 404 ? "denied" : "error"+}++function verifyDmRoute(queryClient: QueryClient,dmId: string,): Promise<DmRouteVerification> {- try {- const response = await queryClient.fetchQuery<DmsResponse>({- queryKey: communityKeys.dms(),- queryFn: dmsQueryFn,- staleTime: 0,- })- return response.conversations.some((dm) => dm.id === dmId) ? "present" : "missing"- } catch (error) {- const status = typeof error === "object" && error !== null && "status" in error- ? error.status- : undefined- if (status === 403 || status === 404) {- return "denied"- }- throw error- }+ return dmRouteAuthorityQueryFn().then(+ (response) => {+ queryClient.setQueryData(communityKeys.dms(), response)+ return response.conversations.some((dm) => dm.id === dmId) ? "present" : "missing"+ },+ (error: unknown) => {+ if (classifyDmRouteAuthorityError(error) === "denied") return "denied"+ throw error+ },+ )}function verificationOptions(queryClient: QueryClient, dmId: string) {@@ -43,6 +54,10 @@ export function startDmRouteVerification(queryClient: QueryClient,dmId: string,): Promise<DmRouteVerification> {+ const canonical = queryClient.getQueryData<DmsResponse>(communityKeys.dms())+ if (canonical?.conversations.some((dm) => dm.id === dmId)) {+ return Promise.resolve("present")+ }return queryClient.fetchQuery({...verificationOptions(queryClient, dmId),staleTime: 0,@@ -52,14 +67,19 @@ export function startDmRouteVerification(export function useDmRouteVerification(dmId: string | undefined,dms: readonly DM[],-): DmRouteVerificationStatus {+ canonicalUnsettled: boolean,+): DmRouteVerificationResult {const queryClient = useQueryClient()const present = !!dmId && dms.some((dm) => dm.id === dmId)const verification = useQuery({...verificationOptions(queryClient, dmId ?? "__none__"),- enabled: !!dmId && !present,+ enabled: !!dmId && !canonicalUnsettled && !present,staleTime: Infinity,})+ const retry = useCallback(() => {+ if (!dmId || verification.fetchStatus === "fetching") return+ void verification.refetch()+ }, [dmId, verification])useEffect(() => {if (!dmId) returnreturn () => {@@ -72,9 +92,15 @@ export function useDmRouteVerification(}}, [dmId, queryClient])- if (!dmId) return "idle"- if (verification.data === "missing" || verification.data === "denied") return "missing"- if (present || verification.data === "present") return "present"- if (verification.fetchStatus === "fetching") return "pending"- return "pending"+ let status: DmRouteVerificationStatus = "pending"+ if (!dmId) status = "idle"+ else if (present || verification.data === "present") status = "present"+ else if (verification.data === "missing" || verification.data === "denied") status = "missing"+ else if (verification.isError) status = "error"++ return {+ status,+ retry,+ retrying: verification.fetchStatus === "fetching",+ }}diff --git a/src/web/src/lib/community/last-me-location.test.ts b/src/web/src/lib/community/last-me-location.test.tsindex dcff6656e..b35a89507 100644--- a/src/web/src/lib/community/last-me-location.test.ts+++ b/src/web/src/lib/community/last-me-location.test.ts@@ -81,6 +81,11 @@ describe("resolveMeLocationStatus", () => {dmId: "dm_1",dmRouteStatus: "pending",})).toBe("wait")+ expect(resolveMeLocationStatus({+ pathname: "/c/me/dm_1",+ dmId: "dm_1",+ dmRouteStatus: "error",+ })).toBe("wait")})it("remembers a confirmed DM and marks a missing DM stale", () => {diff --git a/src/web/src/lib/community/last-me-location.ts b/src/web/src/lib/community/last-me-location.tsindex 27f40d537..c983c4c0c 100644--- a/src/web/src/lib/community/last-me-location.ts+++ b/src/web/src/lib/community/last-me-location.ts@@ -58,7 +58,7 @@ export function resolveMeLocationStatus({}: {pathname: stringdmId: string | undefined- dmRouteStatus: "idle" | "pending" | "present" | "missing"+ dmRouteStatus: "idle" | "pending" | "present" | "missing" | "error"}): MeLocationStatus {if (!isRememberableMeLocation(pathname)) return "ignore"if (!dmId) return "remember"diff --git a/src/web/src/test/e2e-ui/04-dm.spec.ts b/src/web/src/test/e2e-ui/04-dm.spec.tsindex 5e4813321..f216b81f4 100644--- a/src/web/src/test/e2e-ui/04-dm.spec.ts+++ b/src/web/src/test/e2e-ui/04-dm.spec.ts@@ -2,6 +2,7 @@ import type { Frame } from "@playwright/test"import { test, expect, userId, userName } from "./_fixtures/community-fixture"import { tid } from "./_fixtures/testids"import { sendMessage } from "./_fixtures/actions"+import { proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"import { seedDm, seedBlock, seedDmMessage } from "./_fixtures/seed"// Journey 4 — DMs. human↔human needs only not-blocked (no friendship). Covers@@ -16,34 +17,32 @@ test.describe.serial("direct messages", () => {await bob.page.goto("/c/me")expect((await initialDms).status()).toBe(200)- let releaseAuthority!: () => void- let authorityStarted!: () => void- let authorityFinished!: () => void- const authorityGate = new Promise<void>((resolve) => { releaseAuthority = resolve })- const authorityRequest = new Promise<void>((resolve) => { authorityStarted = resolve })- const authoritySettled = new Promise<void>((resolve) => { authorityFinished = resolve })- let held = false+ let releaseCanonical!: () => void+ let canonicalFinished!: () => void+ const canonicalGate = new Promise<void>((resolve) => { releaseCanonical = resolve })+ const canonicalSettled = new Promise<void>((resolve) => { canonicalFinished = resolve })+ let dmsGets = 0const dmsPattern = "**/api/community/users/me/dms"await bob.page.route(dmsPattern, async (route) => {- if (held || route.request().method() !== "GET") {+ if (route.request().method() !== "GET") {await route.continue()return}- held = true- authorityStarted()+ dmsGets += 1try {- await authorityGate+ await canonicalGateawait route.continue()} catch (error) {if (!(error instanceof Error && error.message.includes("already handled"))) throw error} finally {- authorityFinished()+ canonicalFinished()}})const dmId = await seedDm("alice", userId("bob"))const body = `first inbox DM ${Date.now()}`const messageId = await seedDmMessage("alice", dmId, body)+ await expect.poll(() => dmsGets).toBe(1)const routeHistory: string[] = []const recordRoute = (frame: Frame) => {if (frame === bob.page.mainFrame()) routeHistory.push(new URL(frame.url()).pathname)@@ -54,8 +53,8 @@ test.describe.serial("direct messages", () => {await bob.page.getByRole("button", { name: "Inbox" }).click()const inboxRow = bob.page.getByTestId(tid.inboxUnreadDm(dmId))await expect(inboxRow).toBeVisible({ timeout: 20_000 })+ const dmsGetsBeforeClick = dmsGetsawait inboxRow.click()- await authorityRequestawait bob.page.waitForURL(new RegExp(`/c/me/${dmId}$`), {timeout: 20_000,@@ -67,24 +66,158 @@ test.describe.serial("direct messages", () => {})).toBeVisible()expect(routeHistory).not.toContain("/c/me")- const authorityResponse = bob.page.waitForResponse((response) =>- response.request().method() === "GET"- && new URL(response.url()).pathname === "/api/community/users/me/dms",- )- releaseAuthority()- expect((await authorityResponse).status()).toBe(200)await expect(bob.page.getByTestId(tid.message(messageId))).toHaveCount(1)await expect(bob.page.getByText(body, { exact: false }).first()).toBeVisible({ timeout: 20_000 })await expect(bob.page).toHaveURL(new RegExp(`/c/me/${dmId}$`))expect(routeHistory).not.toContain("/c/me")+ expect(dmsGets - dmsGetsBeforeClick).toBe(0)} finally {- releaseAuthority()- await authoritySettled+ releaseCanonical()+ await canonicalSettledbob.page.off("framenavigated", recordRoute)await bob.page.unroute(dmsPattern)}})+ test("a canonical DM skips authority and keeps known chrome while read-state and messages load", async ({ asUser }) => {+ const dmId = await seedDm("alice", userId("bob"))+ const body = `held DM message ${Date.now()}`+ const messageId = await seedDmMessage("bob", dmId, body)+ const alice = await asUser("alice")+ const wsProxy = await proxyCommunityWebSockets(alice.context, {+ decideConnectionFrame: (frame) => frame.type === "auth.ok" ? "hold" : "forward",+ })+ let dmsGets = 0+ const interactiveMutations: string[] = []+ alice.page.on("request", (request) => {+ const pathname = new URL(request.url()).pathname+ if (request.method() === "GET" && pathname === "/api/community/users/me/dms") {+ dmsGets += 1+ }+ if (request.method() !== "GET" && pathname.startsWith(`/api/community/channels/${dmId}`)) {+ interactiveMutations.push(`${request.method()} ${pathname}`)+ }+ })++ let releaseRead!: () => void+ let readFinished!: () => void+ const readGate = new Promise<void>((resolve) => { releaseRead = resolve })+ const readSettled = new Promise<void>((resolve) => { readFinished = resolve })+ const readPattern = `**/api/community/channels/${dmId}/read-state`+ await alice.page.route(readPattern, async (route) => {+ try {+ await readGate+ await route.continue()+ } catch (error) {+ if (!(error instanceof Error && error.message.includes("already handled"))) throw error+ } finally {+ readFinished()+ }+ })++ let releaseMessages!: () => void+ let messagesStarted!: () => void+ let messagesFinished!: () => void+ const messagesGate = new Promise<void>((resolve) => { releaseMessages = resolve })+ const messagesRequest = new Promise<void>((resolve) => { messagesStarted = resolve })+ const messagesSettled = new Promise<void>((resolve) => { messagesFinished = resolve })+ let heldMessages = false+ const messagesPattern = `**/api/community/channels/${dmId}/messages*`+ await alice.page.route(messagesPattern, async (route) => {+ if (route.request().method() !== "GET" || heldMessages) {+ await route.continue()+ return+ }+ heldMessages = true+ messagesStarted()+ try {+ await messagesGate+ await route.continue()+ } catch (error) {+ if (!(error instanceof Error && error.message.includes("already handled"))) throw error+ } finally {+ messagesFinished()+ }+ })++ try {+ await alice.page.goto(`/c/me/${dmId}`)+ await expect(alice.page.getByRole("heading", {+ level: 1,+ name: new RegExp(userName("bob")),+ })).toBeVisible({ timeout: 20_000 })+ await expect(alice.page.getByTestId(tid.composerInput)).toBeVisible()+ await expect(alice.page.getByTestId(tid.messageScroller).locator('[data-slot="skeleton"]')).not.toHaveCount(0)++ releaseRead()+ await readSettled+ await messagesRequest+ await expect(alice.page.getByRole("heading", {+ level: 1,+ name: new RegExp(userName("bob")),+ })).toBeVisible()+ await expect(alice.page.getByTestId(tid.composerInput)).toBeVisible()+ await expect(alice.page.getByTestId(tid.messageScroller).locator('[data-slot="skeleton"]')).not.toHaveCount(0)+ await expect.poll(() => wsProxy.heldConnectionCount()).toBe(1)+ expect(dmsGets).toBe(1)+ expect(interactiveMutations).toEqual([])++ releaseMessages()+ await messagesSettled+ await expect(alice.page.getByTestId(tid.message(messageId))).toHaveCount(1)+ await expect(alice.page.getByText(body, { exact: false }).first()).toBeVisible({ timeout: 20_000 })+ } finally {+ releaseRead()+ releaseMessages()+ await readSettled+ await messagesSettled+ await alice.page.unroute(readPattern)+ await alice.page.unroute(messagesPattern)+ }+ })++ test("an absent DM verifies once per attempt and exposes transient Retry locally", async ({ asUser }) => {+ const alice = await asUser("alice")+ const wsProxy = await proxyCommunityWebSockets(alice.context, {+ decideConnectionFrame: (frame) => frame.type === "auth.ok" ? "hold" : "forward",+ })+ const missingDmId = `dm-missing-${Date.now()}`+ let dmsGets = 0+ const dmsPattern = "**/api/community/users/me/dms"+ await alice.page.route(dmsPattern, async (route) => {+ if (route.request().method() !== "GET") {+ await route.continue()+ return+ }+ dmsGets += 1+ if (dmsGets === 1) {+ await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ conversations: [] }) })+ return+ }+ if (dmsGets === 2) {+ await route.fulfill({ status: 503, contentType: "application/json", body: JSON.stringify({ error: "temporary" }) })+ return+ }+ await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ conversations: [] }) })+ })++ try {+ await alice.page.goto(`/c/me/${missingDmId}`)+ await expect(alice.page.getByRole("alert").filter({+ hasText: "Couldn\'t verify this conversation",+ })).toBeVisible()+ await expect(alice.page).toHaveURL(new RegExp(`/c/me/${missingDmId}$`))+ await expect.poll(() => wsProxy.heldConnectionCount()).toBe(1)+ expect(dmsGets).toBe(2)++ await alice.page.getByRole("button", { name: "Retry" }).click()+ await expect.poll(() => dmsGets).toBe(3)+ await expect.poll(() => new URL(alice.page.url()).pathname).toBe("/c/me/friends")+ } finally {+ await alice.page.unroute(dmsPattern)+ }+ })+test("a DM message reaches the peer live and the conversation appears without reload", async ({ asUser }) => {// Alice opens a DM to Bob via API (precondition), then both drive the UI.const dmId = await seedDm("alice", userId("bob"))diff --git a/src/web/src/test/e2e-ui/08-mobile.spec.ts b/src/web/src/test/e2e-ui/08-mobile.spec.tsindex 60dbc4bc5..f1ed08996 100644--- a/src/web/src/test/e2e-ui/08-mobile.spec.ts+++ b/src/web/src/test/e2e-ui/08-mobile.spec.ts@@ -30,6 +30,26 @@ async function expectPanelToFillGroup(page: Page, id: "sidebar" | "main"): Promiexpect(Math.abs(panelRect!.width - groupRect!.width)).toBeLessThanOrEqual(1)}+async function installMeLoadingProbe(page: Page): Promise<void> {+ await page.addInitScript(() => {+ const state = window as typeof window & { __wrongMeConversationLoadingSeen?: boolean }+ state.__wrongMeConversationLoadingSeen = false+ const inspect = () => {+ if (location.pathname.startsWith("/c/me/") && document.querySelector('[aria-label="Loading conversation"]')) {+ state.__wrongMeConversationLoadingSeen = true+ }+ }+ new MutationObserver(inspect).observe(document.documentElement, { childList: true, subtree: true })+ inspect()+ })+}++async function expectNoWrongMeConversationLoading(page: Page): Promise<void> {+ expect(await page.evaluate(() => (+ window as typeof window & { __wrongMeConversationLoadingSeen?: boolean }+ ).__wrongMeConversationLoadingSeen)).toBe(false)+}+test.describe.serial("mobile layout", () => {let serverId: stringlet channelId: string@@ -136,12 +156,14 @@ test.describe.serial("mobile layout", () => {test("Friends, Machines, and Bots deep links all default to content", async ({ asUser }) => {const { page } = await asUser("alice")+ await installMeLoadingProbe(page)for (const pathname of ["/c/me/friends", "/c/me/machines", "/c/me/bots"]) {await page.goto(pathname)const back = page.getByRole("button", { name: "Back" })await expect(back).toBeVisible()await expect(page.getByTestId(tid.homeButton)).toBeHidden()+ await expectNoWrongMeConversationLoading(page)await back.click()await expect.poll(() => new URL(page.url()).pathname).toBe("/c/me")@@ -267,8 +289,10 @@ test.describe.serial("mobile layout", () => {test("a direct DM opens detail and Header Back replaces it with Me root", async ({ asUser }) => {const { page } = await asUser("alice")+ await installMeLoadingProbe(page)await page.goto(`/c/me/${dmId}`)await expect(page.getByTestId(tid.composerInput)).toBeVisible()+ await expectNoWrongMeConversationLoading(page)await page.getByRole("button", { name: "Back" }).click()await expect.poll(() => new URL(page.url()).pathname).toBe("/c/me")diff --git a/src/web/src/test/e2e-ui/12-friends.spec.ts b/src/web/src/test/e2e-ui/12-friends.spec.tsindex 0c4737421..fefbc069f 100644--- a/src/web/src/test/e2e-ui/12-friends.spec.ts+++ b/src/web/src/test/e2e-ui/12-friends.spec.ts@@ -1,18 +1,25 @@import { test, expect, userId, userName } from "./_fixtures/community-fixture"-import { seedFriendship } from "./_fixtures/seed"+import { seedChannel, seedFriendship, seedServer } from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"// Journey 12 — friends. A seeded friendship (Alice↔Bob) shows on the friends// page; the row opens a DM on click. Friendship handshake uses the two-cookie// helper (accept is addressee-only).test.describe.serial("friends", () => {+ let serverId: string+ let channelId: string+test.beforeAll(async () => {await seedFriendship("alice", "bob", userId("bob"))+ serverId = await seedServer("alice", `Friends Home ${Date.now()}`)+ channelId = await seedChannel("alice", serverId, "friends-home")})test("a friend shows in the friends list and opens a DM", async ({ asUser }) => {const { page } = await asUser("alice")await page.goto("/c/me")- await page.waitForURL(/\/c\/me/, { timeout: 20_000 , waitUntil: "commit" })+ await page.waitForURL(/\/c\/me\/friends$/, { timeout: 20_000 , waitUntil: "commit" })+ await expect(page.getByLabel("Loading conversation")).toHaveCount(0)// Bob appears in the friends list (his dev display name = email local-part).const bobRow = page.getByText(userName("bob"), { exact: false }).first()@@ -20,7 +27,34 @@ test.describe.serial("friends", () => {// Left-click opens the DM with Bob.await bobRow.click()- await page.waitForURL(/\/c\/me\/[^/]+/, { timeout: 20_000 , waitUntil: "commit" })- expect(page.url()).toMatch(/\/c\/me\/[^/]+/)+ await expect.poll(() => new URL(page.url()).pathname).not.toBe("/c/me/friends")+ await expect(page.getByTestId(tid.composerInput)).toBeVisible({ timeout: 20_000 })+ expect(new URL(page.url()).pathname).toMatch(/^\/c\/me\/[^/]+$/)++ const rememberedDmPath = new URL(page.url()).pathname+ await page.goto(`/c/channels/${serverId}/${channelId}`)+ await expect(page.getByTestId(tid.composerInput)).toBeVisible()+ await page.evaluate(() => {+ const state = window as typeof window & { __meRouteCommits?: string[] }+ state.__meRouteCommits = []+ const push = history.pushState.bind(history)+ const replace = history.replaceState.bind(history)+ history.pushState = (...args) => {+ push(...args)+ state.__meRouteCommits!.push(location.pathname)+ }+ history.replaceState = (...args) => {+ replace(...args)+ state.__meRouteCommits!.push(location.pathname)+ }+ })++ await page.getByTestId(tid.homeButton).click()+ await expect.poll(() => new URL(page.url()).pathname).toBe(rememberedDmPath)+ const commits = await page.evaluate(() => (+ window as typeof window & { __meRouteCommits?: string[] }+ ).__meRouteCommits ?? [])+ expect(commits).not.toContain("/c/me")+ expect(commits.at(-1)).toBe(rememberedDmPath)})})