Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): unify adaptive community navigation (#491)

Gustavo Ye54e928679048
diff --git a/DESIGN.md b/DESIGN.md
index 4a2f4ca06..1c20d33b8 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -108,7 +108,7 @@ Two stages, not three. The split lives at **`640px`** — Tailwind's default `sm
| Stage | Range | Layout shape |
| --- | --- | --- |
-| **Mobile** | `< 640px` | Single column with zone switching (`MobileZone = "nav" \| "messages"`). Back button in headers. Popovers may promote to sheets when they'd overflow. |
+| **Mobile** | `< 640px` | Single column with pathname-owned list/detail routing. Back button in detail headers. Popovers may promote to sheets when they'd overflow. |
| **Desktop** | `≥ 640px` | Multi-column shells — server rail + channel/DM sidebar + main (in community), or app sidebar + workspace (elsewhere). Hover surfaces reveal actions. No back button in headers. |
Rules:
diff --git a/src/web/src/app/api/community/users/me/marks/route.test.ts b/src/web/src/app/api/community/users/me/marks/route.test.ts
index 8a8cfed21..b49480b25 100644
--- a/src/web/src/app/api/community/users/me/marks/route.test.ts
+++ b/src/web/src/app/api/community/users/me/marks/route.test.ts
@@ -106,7 +106,12 @@ describe("GET /api/community/users/me/marks", () => {
author: { id: "u-alice", name: "Alice", email: "[email protected]", image: null },
},
])
- mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "general", serverId: "s1" }])
+ mockGetChannelsByIds.mockResolvedValue([{
+ id: "c1",
+ name: "general",
+ serverId: "s1",
+ parentChannelId: "parent1",
+ }])
mockGetServersByIds.mockResolvedValue([{ id: "s1", name: "Server 1" }])
const res = await GET(new NextRequest("http://localhost/api/community/users/me/marks"))
@@ -118,6 +123,7 @@ describe("GET /api/community/users/me/marks", () => {
serverId: "s1",
channel: "general",
channelId: "c1",
+ parentChannelId: "parent1",
// serverId + channelId locate the channel, m.seq jumps to the message —
// all three required for cross-channel navigation. seq lives inside `m`
// to match the frontend `Marked` type (m: Msg).
diff --git a/src/web/src/app/api/community/users/me/marks/route.ts b/src/web/src/app/api/community/users/me/marks/route.ts
index fce61f95b..48cc9a9d5 100644
--- a/src/web/src/app/api/community/users/me/marks/route.ts
+++ b/src/web/src/app/api/community/users/me/marks/route.ts
@@ -116,6 +116,7 @@ export const GET = withCommunityActor(async (req, ctx) => {
serverId: ch?.serverId,
channel: ch ? ch.name : "Unknown",
channelId: row.mark.channelId,
+ parentChannelId: ch?.parentChannelId ?? null,
m: {
id: row.message.id,
authorId: row.author.id,
diff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/[childChannelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/[childChannelId]/page.tsx
new file mode 100644
index 000000000..33e148271
--- /dev/null
+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/[childChannelId]/page.tsx
@@ -0,0 +1,21 @@
+"use client"
+
+import { useParams } from "next/navigation"
+import { ChannelRoute } from "@/components/community/channels/channel-route"
+
+export default function ChildChannelPage() {
+ const params = useParams<{
+ serverId: string
+ channelId: string
+ childChannelId: string
+ }>()
+ const key = `${params.serverId}/${params.channelId}/${params.childChannelId}`
+ return (
+ <ChannelRoute
+ key={key}
+ serverParam={params.serverId}
+ parentChannelId={params.channelId}
+ channelId={params.childChannelId}
+ />
+ )
+}
diff --git a/src/web/src/app/c/channels/[serverId]/page.tsx b/src/web/src/app/c/channels/[serverId]/page.tsx
index bb87ede02..e437af2bd 100644
--- a/src/web/src/app/c/channels/[serverId]/page.tsx
+++ b/src/web/src/app/c/channels/[serverId]/page.tsx
@@ -5,6 +5,7 @@ import { useParams, useRouter, useSearchParams } from "next/navigation"
import { MessageList } from "@/components/community/messages/message-list"
import { Skeleton } from "@/components/ui/skeleton"
import { useServer } from "@/hooks/community/use-servers"
+import { useBreakpoint } from "@/hooks/use-mobile"
import { getLastChannel, pickServerLandingChannel } from "@/lib/community/last-channel"
/**
@@ -21,12 +22,13 @@ export default function ServerDefaultPage() {
const searchParams = useSearchParams()
const serverId = decodeURIComponent(params.serverId)
const { server: currentServer } = useServer(serverId)
+ const breakpoint = useBreakpoint()
useEffect(() => {
- if (!currentServer) return
+ if (breakpoint !== "desktop" || !currentServer) return
const allChannels = currentServer.categories.flatMap((cat) => cat.channels)
- // Restore the remembered last channel when it still exists + is visible
- // here; otherwise the first channel. See `pickServerLandingChannel`.
+ // Restore the remembered route leaf, including canonical parent/child
+ // leaves, or use the first top-level channel when there is no memory.
const target = pickServerLandingChannel(
allChannels.map((c) => c.id),
getLastChannel(serverId),
@@ -35,7 +37,9 @@ export default function ServerDefaultPage() {
const search = searchParams.toString()
router.replace(`/c/channels/${serverId}/${target}${search ? `?${search}` : ""}`)
}
- }, [currentServer, serverId, router, searchParams])
+ }, [breakpoint, currentServer, serverId, router, searchParams])
+
+ if (breakpoint !== "desktop") return null
const allChannels = currentServer?.categories.flatMap((cat) => cat.channels) ?? []
if (currentServer && allChannels.length === 0) {
diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsx
index 1698d8d71..601894532 100644
--- a/src/web/src/app/c/channels/layout.tsx
+++ b/src/web/src/app/c/channels/layout.tsx
@@ -13,10 +13,10 @@ import { patchChannelUnread } from "@/hooks/community/server-detail-cache"
import type { ServerDetail } from "@/hooks/community/use-servers"
import { ShellFrame } from "@/components/community/shell/shell-frame"
import {
- removeCommunityParam,
- resolveMobileZone,
- withMobileZone,
-} from "@/components/community/shell/mobile-zone"
+ childChannelHref,
+ serverModalMarkerCleanupHref,
+} from "@/lib/community/community-route"
+import { useBreakpoint } from "@/hooks/use-mobile"
import { ChannelSidebar } from "@/components/community/channels/channel-sidebar"
import { ServerSettings } from "@/components/community/settings/server-settings"
import { ImageCropDialog } from "@/components/community/image-crop-dialog"
@@ -70,12 +70,17 @@ import {
} from "@/hooks/community/mutations"
export default function ServerLayout({ children }: { children: ReactNode }) {
- const params = useParams<{ serverId: string; channelId?: string }>()
+ const params = useParams<{ serverId: string; channelId?: string; childChannelId?: string }>()
const searchParams = useSearchParams()
const pathname = usePathname()
const serverId = decodeURIComponent(params.serverId)
- const routeChannelId = params.channelId ? decodeURIComponent(params.channelId) : null
- const hasChannel = !!params.channelId
+ const routeChannelId = params.childChannelId
+ ? decodeURIComponent(params.childChannelId)
+ : params.channelId
+ ? decodeURIComponent(params.channelId)
+ : null
+ const hasChannel = !!routeChannelId
+ const breakpoint = useBreakpoint()
const router = useRouter()
const queryClient = useQueryClient()
@@ -187,7 +192,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
toast,
replace: (destination) => {
cancelPendingNavigation()
- router.replace(withMobileZone(destination, resolveMobileZone(searchParams)))
+ router.replace(destination)
},
})
}, [cancelPendingNavigation, serverId, serversList.isSuccess, serversList.isFetching, serversList.servers, router, searchParams])
@@ -241,42 +246,37 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
}, [searchParams])
useEffect(() => {
- const wantsSettings = searchParams.get("settings") === "1"
- const wantsInvite = searchParams.get("invite") === "1"
- // The message controller is intentionally unmounted while mobile nav is
- // visible, so it cannot consume its own `seq` command in that pane. Clean
- // the one-shot command at the persistent layout boundary instead. Content
- // routes leave it alone so the mounted controller can still open the
- // requested message context before removing the parameter itself.
- const wantsNavSeq =
- resolveMobileZone(searchParams) === "nav" && searchParams.has("seq")
- if (!wantsSettings && !wantsInvite && !wantsNavSeq) return
-
// These flags land on the bare `/c/channels/:serverId` URL
// (e.g. right-click a rail server → "Server settings"/"Invite to
// Server"), which is also the URL the sibling default-channel page
- // redirects away from once it knows the server's first channel. When
- // that server's detail query is already warm in the cache, both
- // redirects fire in the very same commit — and since React runs a
- // child's effects before its parent's, our `router.replace` below would
- // run *after* the page's channel redirect and clobber it, stranding the
- // URL on the channel-less server root. Wait for that race to resolve
- // (channel present, or confirmed there are none) before stripping the
- // query so we don't fight the page's own navigation — once it lands on
- // a channel URL, that URL has no query string left to strip anyway.
- const stillRedirecting =
- !hasChannel && !!currentServer && currentServer.categories.some((c) => c.channels.length > 0)
- if (stillRedirecting) return
-
- cancelPendingNavigation()
+ // redirects away from once it knows the server's first channel on
+ // desktop. With a warm detail query, the child and parent effects can
+ // replace in the same commit, so desktop waits until the channel route
+ // 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.
const search = searchParams.toString()
const currentHref = `${pathname}${search ? `?${search}` : ""}`
- const withoutSettings = removeCommunityParam(currentHref, "settings")
- const withoutInvite = removeCommunityParam(withoutSettings, "invite")
- router.replace(
- wantsNavSeq ? removeCommunityParam(withoutInvite, "seq") : withoutInvite,
- )
- }, [cancelPendingNavigation, searchParams, pathname, router, hasChannel, currentServer])
+ const cleanupHref = serverModalMarkerCleanupHref(currentHref, {
+ breakpoint,
+ hasChannel,
+ hasServerChannels: Boolean(
+ currentServer?.categories.some((category) => category.channels.length > 0),
+ ),
+ })
+ if (!cleanupHref) return
+
+ cancelPendingNavigation()
+ router.replace(cleanupHref)
+ }, [
+ breakpoint,
+ cancelPendingNavigation,
+ searchParams,
+ pathname,
+ router,
+ hasChannel,
+ currentServer,
+ ])
const categories = useMemo(() => (currentServer?.categories ?? []).map((category) => ({
...category,
@@ -319,7 +319,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
// trusts the cache unconditionally, so both directions must write to it.
markSwitch("channel", id)
cancelPendingNavigation()
- router.push(`/c/channels/${serverId}/${id}`)
+ useCommunityStore.getState().uiHandlers.navigatePath?.(`/c/channels/${serverId}/${id}`)
channelTree.markRead(id)
const hasChildFallback = setForumSidebarParentUnreadBase(
queryClient,
@@ -333,18 +333,24 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
(cache) => patchChannelUnread(cache, id, false),
)
}
- }, [cancelPendingNavigation, channelTree, queryClient, router, serverId])
+ }, [cancelPendingNavigation, channelTree, queryClient, serverId])
- const setActiveForumThread = useCallback((id: string) => {
+ const setActiveForumThread = useCallback((parentId: string, id: string) => {
markSwitch("channel", id)
cancelPendingNavigation()
- router.push(`/c/channels/${serverId}/${id}`)
+ useCommunityStore.getState().uiHandlers.navigatePath?.(
+ childChannelHref(serverId, parentId, id),
+ )
removeForumSidebarUnreadChild(queryClient, serverId, id)
patchForumSidebarUnreadExact(queryClient, serverId, id, false)
- }, [cancelPendingNavigation, queryClient, router, serverId])
+ }, [cancelPendingNavigation, queryClient, serverId])
const prefetchChannel = useCallback(
- (id: string) => router.prefetch(`/c/channels/${serverId}/${id}`),
+ (id: string, parentId?: string) => router.prefetch(
+ parentId
+ ? childChannelHref(serverId, parentId, id)
+ : `/c/channels/${serverId}/${id}`,
+ ),
[router, serverId],
)
@@ -513,7 +519,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
toast("Server deleted")
useCommunityStore.getState().setCurrentServerId(null)
cancelPendingNavigation()
- router.push("/c/me")
+ useCommunityStore.getState().uiHandlers.navigatePath?.("/c/me")
},
onError: (e) => toastApiError(e, "Failed to delete server"),
})
diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsx
index 0478ffbca..376ec8cc7 100644
--- a/src/web/src/app/c/me/[dmId]/page.tsx
+++ b/src/web/src/app/c/me/[dmId]/page.tsx
@@ -449,7 +449,7 @@ function DmView() {
onTyping={handleTyping}
replyingTo={replyTo?.authorName}
onCancelReply={() => setReplyTo(null)}
- autoFocus={bp !== "mobile"}
+ autoFocus={bp === "desktop"}
draftKey={`dm/${dmId}`}
/>
</div>
diff --git a/src/web/src/app/c/me/friends/page.tsx b/src/web/src/app/c/me/friends/page.tsx
new file mode 100644
index 000000000..3dd3c325c
--- /dev/null
+++ b/src/web/src/app/c/me/friends/page.tsx
@@ -0,0 +1,127 @@
+"use client"
+
+import { useBreakpoint } from "@/hooks/use-mobile"
+import { FriendsPage } from "@/components/community/social/friends-page"
+import { useMemo } from "react"
+import { useFriends } from "@/hooks/community/use-friends"
+import { useUiHandlers } from "@/stores/community"
+import { useOnlineUserIds, useCommunityWsStore } from "@/stores/community/ws"
+import { resolveRowPresence } from "@/lib/community/presence"
+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 bp = useBreakpoint()
+ const { friends: rawFriends, pending, blocked, isLoading } = useFriends()
+ const uiHandlers = useUiHandlers()
+ const onlineUserIds = useOnlineUserIds()
+ const userStatuses = useCommunityWsStore((s) => s.userStatuses)
+ const friends = useMemo(
+ () =>
+ rawFriends.map((f) => {
+ const liveStatus = userStatuses.get(f.userId ?? f.id)
+ return {
+ ...f,
+ status: resolveRowPresence(f, onlineUserIds),
+ statusEmoji: liveStatus ? liveStatus.emoji : f.statusEmoji,
+ statusText: liveStatus ? liveStatus.text : f.statusText,
+ }
+ }),
+ [rawFriends, onlineUserIds, userStatuses],
+ )
+
+ 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}
+ onBack={bp === "mobile" ? () => uiHandlers.goBackMobile?.() : undefined}
+ onAccept={(id) =>
+ acceptFriendRequest.mutate(
+ { friendshipId: id },
+ {
+ onSuccess: () => toast("Friend request accepted"),
+ onError: (e) => toastApiError(e, "Failed to accept request"),
+ },
+ )
+ }
+ onReject={(id) =>
+ rejectFriendRequest.mutate(
+ { friendshipId: id },
+ { onError: (e) => toastApiError(e, "Failed to reject request") },
+ )
+ }
+ 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) => {
+ 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/app/c/me/layout.tsx b/src/web/src/app/c/me/layout.tsx
index e333b317f..7a135e839 100644
--- a/src/web/src/app/c/me/layout.tsx
+++ b/src/web/src/app/c/me/layout.tsx
@@ -2,9 +2,8 @@
import { useCallback, useEffect, useMemo, type ReactNode } from "react"
import { useQueryClient } from "@tanstack/react-query"
-import { usePathname, useRouter, useParams, useSearchParams } from "next/navigation"
+import { usePathname, useRouter, useParams } from "next/navigation"
import { ShellFrame } from "@/components/community/shell/shell-frame"
-import { resolveMobileZone, withMobileZone } from "@/components/community/shell/mobile-zone"
import { DmSidebar } from "@/components/community/channels/dm-sidebar"
import { useCommunityStore, useCurrentChannelId } from "@/stores/community"
import { useDms } from "@/hooks/community/use-dms"
@@ -26,7 +25,6 @@ import {
export default function MeLayout({ children }: { children: ReactNode }) {
const router = useRouter()
const pathname = usePathname()
- const searchParams = useSearchParams()
const params = useParams<{ dmId?: string }>()
const { dms: rawDms, isLoading: dmsLoading, isSuccess: dmsReady } = useDms()
const onlineUserIds = useOnlineUserIds()
@@ -64,10 +62,9 @@ export default function MeLayout({ children }: { children: ReactNode }) {
useCommunityWsStore.getState().mergePresence(onlineFriendIds)
}, [onlineFriendIds])
- const hasDm = !!params.dmId
const machinesActive = pathname === "/c/me/machines"
const botsActive = pathname === "/c/me/bots"
- const friendsActive = !hasDm && !machinesActive && !botsActive
+ const friendsActive = pathname === "/c/me/friends"
const meLocationStatus = resolveMeLocationStatus({
pathname,
@@ -84,8 +81,8 @@ export default function MeLayout({ children }: { children: ReactNode }) {
if (meLocationStatus !== "stale") return
if (getLastMeLeaf() === meLeafFromPathname(pathname)) clearLastMeLocation()
cancelPendingNavigation()
- router.replace(withMobileZone(ME_ROOT, resolveMobileZone(searchParams)))
- }, [cancelPendingNavigation, meLocationStatus, pathname, router, searchParams])
+ router.replace(ME_ROOT)
+ }, [cancelPendingNavigation, meLocationStatus, pathname, router])
// Mirror channel sidebar-click behavior (channels/layout.tsx:226-236): do
// NOT eagerly mark the DM read on click. That fires a bodyless
@@ -108,30 +105,26 @@ export default function MeLayout({ children }: { children: ReactNode }) {
? { ...prev, conversations: prev.conversations.map((d) => (d.id === id ? { ...d, unread: false } : d)) }
: prev,
)
- cancelPendingNavigation()
- router.push(`/c/me/${id}`)
- }, [cancelPendingNavigation, queryClient, router])
+ useCommunityStore.getState().uiHandlers.navigatePath?.(`/c/me/${id}`)
+ }, [queryClient])
const onShowFriends = useCallback(() => {
useCommunityStore.getState().setCurrentChannelId(null)
- cancelPendingNavigation()
- router.push("/c/me")
- }, [cancelPendingNavigation, router])
+ useCommunityStore.getState().uiHandlers.navigatePath?.("/c/me/friends")
+ }, [])
const onShowMachines = useCallback(() => {
useCommunityStore.getState().setCurrentChannelId(null)
- cancelPendingNavigation()
- router.push("/c/me/machines")
- }, [cancelPendingNavigation, router])
+ useCommunityStore.getState().uiHandlers.navigatePath?.("/c/me/machines")
+ }, [])
const onShowBots = useCallback(() => {
useCommunityStore.getState().setCurrentChannelId(null)
- cancelPendingNavigation()
- router.push("/c/me/bots")
- }, [cancelPendingNavigation, router])
+ useCommunityStore.getState().uiHandlers.navigatePath?.("/c/me/bots")
+ }, [])
const prefetchDm = useCallback((id: string) => router.prefetch(`/c/me/${id}`), [router])
- const prefetchFriends = useCallback(() => router.prefetch("/c/me"), [router])
+ const prefetchFriends = useCallback(() => router.prefetch("/c/me/friends"), [router])
const prefetchMachines = useCallback(() => router.prefetch("/c/me/machines"), [router])
const prefetchBots = useCallback(() => router.prefetch("/c/me/bots"), [router])
diff --git a/src/web/src/app/c/me/page.tsx b/src/web/src/app/c/me/page.tsx
index 3850e5779..714f0b86e 100644
--- a/src/web/src/app/c/me/page.tsx
+++ b/src/web/src/app/c/me/page.tsx
@@ -1,129 +1,18 @@
"use client"
+import { useEffect } from "react"
import { useRouter } from "next/navigation"
import { useBreakpoint } from "@/hooks/use-mobile"
-import { FriendsPage } from "@/components/community/social/friends-page"
-import { useMemo } from "react"
-import { useFriends } from "@/hooks/community/use-friends"
-import { useUiHandlers } from "@/stores/community"
-import { useOnlineUserIds, useCommunityWsStore } from "@/stores/community/ws"
-import { resolveRowPresence } from "@/lib/community/presence"
-import {
- useSendFriendRequest,
- useAcceptFriendRequest,
- useRejectFriendRequest,
- useCancelBotFriendRequest,
- useRemoveFriend,
- useBlockUser,
- useUnblockUser,
- useCreateOrGetDm,
-} from "@/hooks/community/mutations"
-import { toast } from "sonner"
-import { toastApiError } from "@/lib/api/client"
+import { getLastMeLeaf, pickMeLandingLocation } from "@/lib/community/last-me-location"
-export default function MeFriendsPage() {
+export default function MeListPage() {
const router = useRouter()
- const bp = useBreakpoint()
- const { friends: rawFriends, pending, blocked, isLoading } = useFriends()
- const uiHandlers = useUiHandlers()
- const onlineUserIds = useOnlineUserIds()
- const userStatuses = useCommunityWsStore((s) => s.userStatuses)
- const friends = useMemo(
- () =>
- rawFriends.map((f) => {
- const liveStatus = userStatuses.get(f.userId ?? f.id)
- return {
- ...f,
- status: resolveRowPresence(f, onlineUserIds),
- statusEmoji: liveStatus ? liveStatus.emoji : f.statusEmoji,
- statusText: liveStatus ? liveStatus.text : f.statusText,
- }
- }),
- [rawFriends, onlineUserIds, userStatuses],
- )
+ const breakpoint = useBreakpoint()
- const sendFriendRequest = useSendFriendRequest()
- const acceptFriendRequest = useAcceptFriendRequest()
- const rejectFriendRequest = useRejectFriendRequest()
- const cancelBotFriendRequest = useCancelBotFriendRequest()
- const removeFriend = useRemoveFriend()
- const blockUser = useBlockUser()
- const unblockUser = useUnblockUser()
- const createOrGetDm = useCreateOrGetDm()
+ useEffect(() => {
+ if (breakpoint !== "desktop") return
+ router.replace(pickMeLandingLocation(getLastMeLeaf()))
+ }, [breakpoint, router])
- return (
- <FriendsPage
- friends={friends}
- pending={pending}
- blocked={blocked}
- loading={isLoading}
- onBack={bp === "mobile" ? () => uiHandlers.goBackMobile?.() : undefined}
- onAccept={(id) =>
- acceptFriendRequest.mutate(
- { friendshipId: id },
- {
- onSuccess: () => toast("Friend request accepted"),
- onError: (e) => toastApiError(e, "Failed to accept request"),
- },
- )
- }
- onReject={(id) =>
- rejectFriendRequest.mutate(
- { friendshipId: id },
- { onError: (e) => toastApiError(e, "Failed to reject request") },
- )
- }
- 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) => {
- try {
- const data = await createOrGetDm.mutateAsync({ userId })
- if (data.conversation.id) router.push(`/c/me/${data.conversation.id}`)
- } catch (e) {
- toastApiError(e, "Failed to open DM")
- }
- }}
- />
- )
+ return null
}
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.ts
new file mode 100644
index 000000000..a30a4f366
--- /dev/null
+++ b/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.ts
@@ -0,0 +1,32 @@
+import { readFileSync } from "node:fs"
+import { describe, expect, it } from "vitest"
+
+const readSource = (relativePath: string) =>
+ readFileSync(new URL(relativePath, import.meta.url), "utf8")
+
+describe("adaptive navigation cutover contracts", () => {
+ it("uses canonical parent-aware routes for known child entries and prefetches", () => {
+ const contextSheet = readSource("../messages/message-context-sheet.tsx")
+ const layout = readSource("../../../app/c/channels/layout.tsx")
+ const sidebar = readSource("./channel-sidebar.tsx")
+
+ expect(contextSheet).toContain(
+ "router.push(childChannelHref(serverId, channelId, threadId))",
+ )
+ expect(contextSheet).not.toContain(
+ "router.push(`/c/channels/${serverId}/${threadId}`)",
+ )
+ expect(layout).toContain("childChannelHref(serverId, parentId, id)")
+ expect(sidebar).toContain("prefetchChannel?.(thread.id, parentId)")
+ })
+
+ it("autofocuses message composers only after desktop is known", () => {
+ const dmPage = readSource("../../../app/c/me/[dmId]/page.tsx")
+ const textSurface = readSource("./text-channel-surface.tsx")
+ const threadSurface = readSource("./thread-channel-surface.tsx")
+
+ expect(dmPage).toContain('autoFocus={bp === "desktop"}')
+ expect(textSurface).toContain('autoFocus={breakpoint === "desktop"}')
+ expect(threadSurface).toContain('autoFocus={breakpoint === "desktop"}')
+ })
+})
diff --git a/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts b/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts
index 05b1879b8..8767db9b2 100644
--- a/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts
+++ b/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts
@@ -43,7 +43,8 @@ const { mockRouteModel, mockMemberViewModel, mockRouter } = vi.hoisted(() => ({
vi.mock("next/navigation", () => ({
useRouter: () => mockRouter,
- useSearchParams: () => new URLSearchParams("msg=m_target&pane=nav&keep=1"),
+ usePathname: () => "/c/channels/server_1/channel_1",
+ useSearchParams: () => new URLSearchParams("msg=m_target&keep=1"),
}))
vi.mock("sonner", () => ({ toast: vi.fn() }))
vi.mock("@/lib/api/client", () => ({ apiFetch: vi.fn(), toastApiError: vi.fn() }))
@@ -253,7 +254,7 @@ describe("ChannelRoute message surface ownership", () => {
expect(mockedUseChannelMessageFeed).toHaveBeenCalledTimes(1)
expect(mockRouter.replace).toHaveBeenCalledWith(
- "/c/channels/server_1/channel_1?pane=nav&keep=1",
+ "/c/channels/server_1/channel_1?keep=1",
{ scroll: false },
)
expect(mockedUseChannelMessageFeed).toHaveBeenCalledWith(expect.objectContaining({ channelId: "channel_1" }))
@@ -331,6 +332,9 @@ describe("ChannelRoute message surface ownership", () => {
channelId: "channel_1",
isChildChannel: true,
}))
+ expect(mockRouter.replace).toHaveBeenLastCalledWith(
+ "/c/channels/server_1/parent_1/channel_1?msg=m_target&keep=1",
+ )
})
it("keeps a child target through warm cache and 5000ms until MessageList consumes it", () => {
diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsx
index 421fa44b1..7c0833783 100644
--- a/src/web/src/components/community/channels/channel-route.tsx
+++ b/src/web/src/components/community/channels/channel-route.tsx
@@ -18,6 +18,7 @@ import { setLastChannel } from "@/lib/community/last-channel"
import { resolveChannelDisplayName } from "@/lib/community/channel-display-name"
import { toChannelRefCandidate } from "@/lib/community/channel-ref-extension"
import {
+ useCommunityStore,
useCurrentChannelId,
useUiHandlers,
} from "@/stores/community"
@@ -26,7 +27,7 @@ import { useChannelRouteModel } from "@/hooks/community/use-channel-route-model"
import { useForumOpenerHint } from "@/hooks/community/use-forum-opener-hint"
import { useNotificationSettings } from "@/hooks/community/use-notification-settings"
import { useSetChannelNotif } from "@/hooks/community/mutations"
-import { removeCommunityParam } from "@/components/community/shell/mobile-zone"
+import { childChannelHref, removeCommunityParam } from "@/lib/community/community-route"
/**
* /c/channels/:serverId/:channelId
@@ -35,7 +36,15 @@ import { removeCommunityParam } from "@/components/community/shell/mobile-zone"
* - Text channel: MessageList + Composer + right panels
* - Child thread opened via URL: child-channel view (breadcrumb + list)
*/
-export function ChannelRoute({ serverParam, channelId }: { serverParam: string; channelId: string }) {
+export function ChannelRoute({
+ serverParam,
+ channelId,
+ parentChannelId: routeParentChannelId,
+}: {
+ serverParam: string
+ channelId: string
+ parentChannelId?: string
+}) {
const router = useRouter()
const searchParams = useSearchParams()
const serverId = decodeURIComponent(serverParam)
@@ -43,8 +52,11 @@ export function ChannelRoute({ serverParam, channelId }: { serverParam: string;
// memory) so re-entering the server restores here instead of the default.
// Pure localStorage write; failures are swallowed in the helper.
useEffect(() => {
- setLastChannel(serverId, channelId)
- }, [serverId, channelId])
+ setLastChannel(
+ serverId,
+ routeParentChannelId ? `${routeParentChannelId}/${channelId}` : channelId,
+ )
+ }, [serverId, channelId, routeParentChannelId])
// Cross-channel "jump to message" target, captured ONCE at mount from `?msg=`.
// `ChannelView` is keyed by `serverId/channelId`, so a fresh jump remounts and
// re-reads this. The param is stripped from the URL right after (below) so a
@@ -125,17 +137,38 @@ export function ChannelRoute({ serverParam, channelId }: { serverParam: string;
useEffect(() => {
if (!jumpTargetId) return
const search = searchParams.toString()
- const href = `/c/channels/${serverParam}/${channelId}${search ? `?${search}` : ""}`
+ const routePath = routeParentChannelId
+ ? childChannelHref(serverParam, routeParentChannelId, channelId)
+ : `/c/channels/${serverParam}/${channelId}`
+ const href = `${routePath}${search ? `?${search}` : ""}`
router.replace(removeCommunityParam(href, "msg"), { scroll: false })
// eslint-disable-next-line react-hooks/exhaustive-deps -- run once for this mount's jump
}, [])
+ useEffect(() => {
+ const parentChannelId = currentChannelMeta?.parentChannelId
+ if (!isChildChannel || routeParentChannelId || !parentChannelId) return
+ const search = searchParams.toString()
+ const routePath = childChannelHref(serverParam, parentChannelId, channelId)
+ router.replace(`${routePath}${search ? `?${search}` : ""}`)
+ }, [
+ channelId,
+ currentChannelMeta?.parentChannelId,
+ isChildChannel,
+ routeParentChannelId,
+ router,
+ searchParams,
+ serverParam,
+ ])
+
const enterThread = useCallback((id: string) => {
// No eager read PUT here — the thread page's `useEagerChannelRead` fires it
// on mount AFTER its read-state snapshot latches, so the "New" divider
// still anchors to the pre-open pointer. A PUT here would race the snapshot.
- router.push(`/c/channels/${serverParam}/${id}`)
- }, [router, serverParam])
+ useCommunityStore.getState().uiHandlers.navigatePath?.(
+ childChannelHref(serverParam, channelId, id),
+ )
+ }, [channelId, serverParam])
const openProfile = useCallback<OpenProfile>((name, e, discriminator, userId) => {
uiHandlers.openProfile?.(name, e, discriminator, userId)
diff --git a/src/web/src/components/community/channels/channel-sidebar.tsx b/src/web/src/components/community/channels/channel-sidebar.tsx
index 460e80ec9..2567f3cd6 100644
--- a/src/web/src/components/community/channels/channel-sidebar.tsx
+++ b/src/web/src/components/community/channels/channel-sidebar.tsx
@@ -50,7 +50,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({
serverIcon?: string | null
activeChannel: string
setActiveChannel: (id: string) => void
- prefetchChannel?: (id: string) => void
+ prefetchChannel?: (id: string, parentId?: string) => void
noHeader?: boolean
onOpenSettings?: (section?: SettingsSection) => void
isAdmin?: boolean
@@ -73,7 +73,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({
onInvitePopoverOpenChange?: (open: boolean) => void
forumThreadsByParent?: Record<string, ForumSidebarThread[]>
activeThreadId?: string | null
- onSelectForumThread?: (id: string) => void
+ onSelectForumThread?: (parentId: string, id: string) => void
}) {
const { collapsed, catOrder, order, catNames, catPrivate, catPending, toggleCat, removeChannel, renameChannel, renameCategory, onDragOver, onDragEnd: treeDragEnd } = tree
// Category the dragged channel started in — captured at drag start, because
@@ -181,8 +181,8 @@ export const ChannelSidebar = memo(function ChannelSidebar({
thread={thread}
active={thread.id === activeThreadId}
muted={!!mutedChannels?.[parentId]}
- onClick={() => onSelectForumThread?.(thread.id)}
- onPrefetch={() => prefetchChannel?.(thread.id)}
+ onClick={() => onSelectForumThread?.(parentId, thread.id)}
+ onPrefetch={() => prefetchChannel?.(thread.id, parentId)}
/>
))}
</div>
diff --git a/src/web/src/components/community/channels/text-channel-surface.test.ts b/src/web/src/components/community/channels/text-channel-surface.test.ts
index 34385ecb7..5ca1accf2 100644
--- a/src/web/src/components/community/channels/text-channel-surface.test.ts
+++ b/src/web/src/components/community/channels/text-channel-surface.test.ts
@@ -20,6 +20,7 @@ const mutationMocks = vi.hoisted(() => ({
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
+ usePathname: () => "/c/channels/server_1/channel_1",
useSearchParams: () => ({ get: () => null }),
}))
vi.mock("sonner", () => ({ toast: vi.fn() }))
diff --git a/src/web/src/components/community/channels/text-channel-surface.tsx b/src/web/src/components/community/channels/text-channel-surface.tsx
index 4ba59ed69..68334a940 100644
--- a/src/web/src/components/community/channels/text-channel-surface.tsx
+++ b/src/web/src/components/community/channels/text-channel-surface.tsx
@@ -147,7 +147,7 @@ export function TextChannelSurface({
onTyping={controller.handleTyping}
replyingTo={controller.replyTo?.authorName}
onCancelReply={() => controller.setReplyTo(null)}
- autoFocus={breakpoint !== "mobile"}
+ autoFocus={breakpoint === "desktop"}
draftKey={`${serverId}/${channelId}`}
/>
</div>
diff --git a/src/web/src/components/community/channels/thread-channel-surface.test.ts b/src/web/src/components/community/channels/thread-channel-surface.test.ts
index 2352d18f3..4979638b8 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.test.ts
+++ b/src/web/src/components/community/channels/thread-channel-surface.test.ts
@@ -319,7 +319,7 @@ describe("ThreadChannelSurface ownership", () => {
headerProps = mockedChannelHeader.mock.calls.at(-1)![0]
expect(headerProps.breadcrumb?.label).toBe("Renamed thread")
act(() => headerProps.breadcrumb?.onNavigateBack())
- expect(mocks.router.push).toHaveBeenCalledWith("/c/channels/server_1/parent_1")
+ expect(mocks.router.replace).toHaveBeenCalledWith("/c/channels/server_1/parent_1")
act(() => headerProps.onToggle("pinned"))
const panelProps = mockedCommunityPanelSheet.mock.calls.at(-1)![0]
diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsx
index 024400011..2acc23bf0 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.tsx
+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx
@@ -103,7 +103,7 @@ export function ThreadChannelSurface({
const openPinned = useCallback(() => setRightPanel("pinned"), [])
const navigateBack = useCallback(() => {
if (parentChannelId) {
- router.push(`/c/channels/${serverParam}/${parentChannelId}`)
+ router.replace(`/c/channels/${serverParam}/${parentChannelId}`)
return
}
onBack?.()
@@ -248,7 +248,7 @@ export function ThreadChannelSurface({
onTyping={controller.handleTyping}
replyingTo={controller.replyTo?.authorName}
onCancelReply={() => controller.setReplyTo(null)}
- autoFocus={breakpoint !== "mobile"}
+ autoFocus={breakpoint === "desktop"}
draftKey={`${serverId}/${channelId}`}
/>
</div>
diff --git a/src/web/src/components/community/machines/machine-list.tsx b/src/web/src/components/community/machines/machine-list.tsx
index 1a6117ec0..69d06a443 100644
--- a/src/web/src/components/community/machines/machine-list.tsx
+++ b/src/web/src/components/community/machines/machine-list.tsx
@@ -44,7 +44,7 @@ import {
updateCommunityOnboardingResources,
useCommunityOnboarding,
} from "@/lib/community-onboarding"
-import { removeCommunityParam } from "@/components/community/shell/mobile-zone"
+import { removeCommunityParam } from "@/lib/community/community-route"
// Loading placeholder shaped like a real MachineCard (size-10 rounded-xl icon +
// name row + meta lines + trailing kebab slot) so the list doesn't reflow when
@@ -192,9 +192,11 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
updateCommunityOnboardingResources({ machineRecovery: false })
continueOnboarding = true
}
- if (continueOnboarding) router.push("/c/me/bots")
+ if (continueOnboarding) {
+ useCommunityStore.getState().uiHandlers.navigatePath?.("/c/me/bots")
+ }
}
- }, [machines, pendingMachineTokenId, pendingTokenId, connectedHostname, router])
+ }, [machines, pendingMachineTokenId, pendingTokenId, connectedHostname])
const openPair = useCallback(() => {
setPairMode({ kind: "pair" })
@@ -451,7 +453,7 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
onClick={() => {
const machineId = confirmDelete?.id
setConfirmDelete(null)
- router.push(
+ useCommunityStore.getState().uiHandlers.navigatePath?.(
machineId
? `/c/me/bots?machineId=${machineId}`
: "/c/me/bots"
diff --git a/src/web/src/components/community/messages/message-channel-controller-state.test.ts b/src/web/src/components/community/messages/message-channel-controller-state.test.ts
index 8c6141246..85532faf8 100644
--- a/src/web/src/components/community/messages/message-channel-controller-state.test.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-state.test.ts
@@ -33,6 +33,7 @@ const mocks = vi.hoisted(() => {
createActions: vi.fn((_input?: unknown) => messageActions),
accept: vi.fn(() => true),
run: vi.fn(async () => {}),
+ pathname: "/c/channels/server_1/channel_1",
seq: null as string | null,
sendMutation: vi.fn(),
reactionMutation: vi.fn(),
@@ -50,8 +51,9 @@ const mocks = vi.hoisted(() => {
vi.mock("next/navigation", () => ({
useRouter: () => mocks.router,
+ usePathname: () => mocks.pathname,
useSearchParams: () => new URLSearchParams(
- mocks.seq ? `seq=${mocks.seq}&pane=nav&keep=1` : "",
+ mocks.seq ? `seq=${mocks.seq}&keep=1` : "",
),
}))
vi.mock("@/lib/api/client", () => ({
@@ -146,6 +148,7 @@ describe("useMessageChannelController", () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.order.length = 0
+ mocks.pathname = "/c/channels/server_1/channel_1"
mocks.seq = null
mocks.storeState.pendingReply = null
mocks.apiFetch.mockResolvedValue({ results: [] })
@@ -316,7 +319,7 @@ describe("useMessageChannelController", () => {
serverId: "server_1", channelId: "channel_1", label: "general", seq: 7,
})
expect(mocks.router.replace).toHaveBeenCalledWith(
- "/c/channels/server_1/channel_1?pane=nav&keep=1", { scroll: false },
+ "/c/channels/server_1/channel_1?keep=1", { scroll: false },
)
expect(mocks.storeState.registerUiHandlers).toHaveBeenCalledWith({
jumpToSeq: expect.any(Function), openMessageContext: expect.any(Function),
@@ -337,6 +340,22 @@ describe("useMessageChannelController", () => {
})
})
+ it("consumes seq on the current canonical child route and preserves other query state", () => {
+ mocks.pathname = "/c/channels/server_1/parent_1/channel_1"
+ mocks.seq = "7"
+ act(() => {
+ TestRenderer.create(React.createElement(Probe, { value: props() }))
+ })
+
+ expect(latest.contextTarget).toEqual({
+ serverId: "server_1", channelId: "channel_1", label: "general", seq: 7,
+ })
+ expect(mocks.router.replace).toHaveBeenCalledWith(
+ "/c/channels/server_1/parent_1/channel_1?keep=1",
+ { scroll: false },
+ )
+ })
+
it("clears missing anchors only on authoritative error and consumes only the matching target", () => {
const missingFeed = { ...feed, messages: [], isError: false }
let renderer: TestRenderer.ReactTestRenderer
diff --git a/src/web/src/components/community/messages/message-channel-controller-state.ts b/src/web/src/components/community/messages/message-channel-controller-state.ts
index 252ed2410..48bbe2c14 100644
--- a/src/web/src/components/community/messages/message-channel-controller-state.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-state.ts
@@ -1,7 +1,7 @@
"use client"
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"
-import { useRouter, useSearchParams } from "next/navigation"
+import { usePathname, useRouter, useSearchParams } from "next/navigation"
import type { MentionType } from "@alook/shared"
import { apiFetch, toastApiError } from "@/lib/api/client"
import { avatarInitial } from "@/lib/community/avatar"
@@ -31,7 +31,7 @@ import {
acceptChannelMessage,
runAcceptedMessageIntent,
} from "./message-channel-controller-send"
-import { removeCommunityParam } from "@/components/community/shell/mobile-zone"
+import { removeCommunityParam } from "@/lib/community/community-route"
import type {
MessageChannelControllerProps,
MessageChannelControllerValue,
@@ -42,7 +42,6 @@ import type {
export function useMessageChannelController({
channelId,
serverId,
- serverParam,
channelName,
forumParentChannelId,
viewer,
@@ -54,6 +53,7 @@ export function useMessageChannelController({
resolveUserName,
}: Omit<MessageChannelControllerProps, "children">): MessageChannelControllerValue {
const router = useRouter()
+ const pathname = usePathname()
const searchParams = useSearchParams()
const [replyTo, setReplyTo] = useState<ReplyTarget | null>(null)
const [searchQuery, setSearchQuery] = useState("")
@@ -189,9 +189,9 @@ export function useMessageChannelController({
const seq = Number(seqParam)
if (!Number.isFinite(seq)) return
setContextTarget({ serverId, channelId, label: channelName, seq })
- const href = `/c/channels/${serverParam}/${channelId}${searchParamsString ? `?${searchParamsString}` : ""}`
+ const href = `${pathname}${searchParamsString ? `?${searchParamsString}` : ""}`
router.replace(removeCommunityParam(href, "seq"), { scroll: false })
- }, [seqParam, serverId, channelId, channelName, router, searchParamsString, serverParam])
+ }, [seqParam, serverId, channelId, channelName, pathname, router, searchParamsString])
const messageScope = useMemo(
() => ({ kind: "channel" as const, id: channelId, serverId }),
diff --git a/src/web/src/components/community/messages/message-context-sheet.tsx b/src/web/src/components/community/messages/message-context-sheet.tsx
index de15c5173..c3ed098b9 100644
--- a/src/web/src/components/community/messages/message-context-sheet.tsx
+++ b/src/web/src/components/community/messages/message-context-sheet.tsx
@@ -21,6 +21,7 @@ import { usePinMessage, useUnpinMessage, useCreateThread, useToggleMark } from "
import type { FileAttachment, ImagePreview, MessagesPage, Msg, Reaction, RenderMsg } from "@/lib/community/models/message"
import type { OpenProfile } from "@/components/community/social/profile-types"
import { useHoverCapable } from "@/hooks/use-hover-capable"
+import { childChannelHref } from "@/lib/community/community-route"
export type ReplyTarget = { id: string; authorName: string; text: string }
@@ -313,9 +314,9 @@ export function MessageContextSheet({
if (type === "dm") return
const serverId = routeParams?.serverId
if (!serverId) return
- router.push(`/c/channels/${serverId}/${threadId}`)
+ router.push(childChannelHref(serverId, channelId, threadId))
onOpenChange(false)
- }, [type, router, routeParams, onOpenChange])
+ }, [type, router, routeParams, channelId, onOpenChange])
const onPreviewImage = useCallback((image: ImagePreview) => {
uiHandlers.previewImage?.(image)
diff --git a/src/web/src/components/community/shell/community-inbox-popover.test.ts b/src/web/src/components/community/shell/community-inbox-popover.test.ts
index 52e2ab6ca..ca9ca0402 100644
--- a/src/web/src/components/community/shell/community-inbox-popover.test.ts
+++ b/src/web/src/components/community/shell/community-inbox-popover.test.ts
@@ -97,7 +97,7 @@ describe("InboxPopover forum post rows", () => {
expect(row).toBeDefined()
await act(async () => row!.props.onClick())
- expect(onOpenChannel).toHaveBeenCalledWith("s1", "t1")
+ expect(onOpenChannel).toHaveBeenCalledWith("s1", "t1", "f1")
expect(onOpenForumThread).not.toHaveBeenCalled()
})
})
diff --git a/src/web/src/components/community/shell/community-inbox-popover.tsx b/src/web/src/components/community/shell/community-inbox-popover.tsx
index d5dd05f30..41324cd0f 100644
--- a/src/web/src/components/community/shell/community-inbox-popover.tsx
+++ b/src/web/src/components/community/shell/community-inbox-popover.tsx
@@ -24,7 +24,7 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenForumThread, o
servers: UnreadServer[]
dms: UnreadDm[]
loading?: boolean
- onOpenChannel?: (serverId: string, channelId: string) => void
+ onOpenChannel?: (serverId: string, channelId: string, parentChannelId?: string) => void
onOpenForumThread: (serverId: string, parentChannelId: string, childChannelId: string, openerMessageId: string) => void
onOpenDm?: (dmId: string) => void
}) {
@@ -72,7 +72,7 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenForumThread, o
if (child.openerMessageId) {
onOpenForumThread(s.serverId, c.channelId, child.channelId, child.openerMessageId)
} else {
- onOpenChannel?.(s.serverId, child.channelId)
+ onOpenChannel?.(s.serverId, child.channelId, c.channelId)
}
}}
className="flex w-full items-center gap-2 rounded-md py-1.5 pl-8 pr-2 text-left text-sm hover:bg-accent"
@@ -204,7 +204,7 @@ export function InboxPopover({
marked: Marked[]
markedLoading?: boolean
loading?: boolean
- onOpenChannel?: (serverId: string, channelId: string) => void
+ onOpenChannel?: (serverId: string, channelId: string, parentChannelId?: string) => void
onOpenForumThread: (serverId: string, parentChannelId: string, childChannelId: string, openerMessageId: string) => void
onOpenDm?: (dmId: string) => void
onOpenMention?: (m: Mention) => void
diff --git a/src/web/src/components/community/shell/mobile-zone.test.ts b/src/web/src/components/community/shell/mobile-zone.test.ts
deleted file mode 100644
index d2513d84b..000000000
--- a/src/web/src/components/community/shell/mobile-zone.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { describe, expect, it } from "vitest"
-import {
- removeCommunityParam,
- resolveMobileZone,
- withMobileZone,
- type MobileZone,
-} from "./mobile-zone"
-
-describe("resolveMobileZone", () => {
- it.each([
- ["", "messages"],
- ["pane=nav", "nav"],
- ["pane=messages", "messages"],
- ["pane=content", "messages"],
- ["pane=", "messages"],
- ["pane=NAV", "messages"],
- ["seq=12&pane=nav", "nav"],
- ] satisfies Array<[string, MobileZone]>)(
- "maps %j to %s",
- (query, expected) => {
- expect(resolveMobileZone(new URLSearchParams(query))).toBe(expected)
- },
- )
-})
-
-describe("withMobileZone", () => {
- it.each([
- ["/c/me/dm-1", "nav", "/c/me/dm-1?pane=nav"],
- ["/c/me/dm-1?seq=12#message", "nav", "/c/me/dm-1?seq=12&pane=nav#message"],
- ["/c/me/dm-1?pane=messages&seq=12", "nav", "/c/me/dm-1?pane=nav&seq=12"],
- ["/c/me/dm-1?pane=nav&seq=12#message", "messages", "/c/me/dm-1?seq=12#message"],
- ["/c/me/dm-1?seq=12#message", "messages", "/c/me/dm-1?seq=12#message"],
- ["/c/me/dm-1?pane=nav#message", "messages", "/c/me/dm-1#message"],
- ["?invite=1#dialog", "nav", "?invite=1&pane=nav#dialog"],
- ["#message", "nav", "?pane=nav#message"],
- ] satisfies Array<[string, MobileZone, string]>)(
- "updates %j to the %s zone without dropping other URL state",
- (href, zone, expected) => {
- expect(withMobileZone(href, zone)).toBe(expected)
- },
- )
-})
-
-describe("removeCommunityParam", () => {
- it.each([
- ["/c/channels/s-1/c-1?msg=m-1&pane=nav#message", "msg", "/c/channels/s-1/c-1?pane=nav#message"],
- ["/c/me/machines?pane=nav&reconnect=machine-1&invite=1", "reconnect", "/c/me/machines?pane=nav&invite=1"],
- ["/c/me/dm-1?seq=12&seq=13&pane=nav", "seq", "/c/me/dm-1?pane=nav"],
- ["/c/me/dm-1?pane=nav#message", "missing", "/c/me/dm-1?pane=nav#message"],
- ["/c/me/dm-1?msg=m-1#message", "msg", "/c/me/dm-1#message"],
- ["/c/me/dm-1#message", "msg", "/c/me/dm-1#message"],
- ])(
- "removes only %j from %j",
- (href, key, expected) => {
- expect(removeCommunityParam(href, key)).toBe(expected)
- },
- )
-})
diff --git a/src/web/src/components/community/shell/mobile-zone.ts b/src/web/src/components/community/shell/mobile-zone.ts
deleted file mode 100644
index 5c5780b55..000000000
--- a/src/web/src/components/community/shell/mobile-zone.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-export type MobileZone = "nav" | "messages"
-
-const MOBILE_ZONE_QUERY_KEY = "pane"
-
-type SearchParamsReader = {
- get: (name: string) => string | null
-}
-
-export function resolveMobileZone(searchParams: SearchParamsReader): MobileZone {
- return searchParams.get(MOBILE_ZONE_QUERY_KEY) === "nav" ? "nav" : "messages"
-}
-
-export function withMobileZone(href: string, zone: MobileZone): string {
- return updateHrefSearchParams(href, (searchParams) => {
- if (zone === "nav") searchParams.set(MOBILE_ZONE_QUERY_KEY, "nav")
- else searchParams.delete(MOBILE_ZONE_QUERY_KEY)
- })
-}
-
-export function removeCommunityParam(href: string, key: string): string {
- return updateHrefSearchParams(href, (searchParams) => {
- searchParams.delete(key)
- })
-}
-
-function updateHrefSearchParams(
- href: string,
- update: (searchParams: URLSearchParams) => void,
-): string {
- const hashIndex = href.indexOf("#")
- const hash = hashIndex === -1 ? "" : href.slice(hashIndex)
- const hrefWithoutHash = hashIndex === -1 ? href : href.slice(0, hashIndex)
- const queryIndex = hrefWithoutHash.indexOf("?")
- const pathname = queryIndex === -1
- ? hrefWithoutHash
- : hrefWithoutHash.slice(0, queryIndex)
- const query = queryIndex === -1 ? "" : hrefWithoutHash.slice(queryIndex + 1)
- const searchParams = new URLSearchParams(query)
-
- update(searchParams)
-
- const nextQuery = searchParams.toString()
- return `${pathname}${nextQuery ? `?${nextQuery}` : ""}${hash}`
-}
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.ts
index a79e1dfb2..a92b26233 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
@@ -42,7 +42,8 @@ describe("ShellFrame public contract", () => {
expect(source).toContain("useShellRailController")
expect(source).toContain("useShellProfileController")
expect(source).toContain("useShellInboxController")
- expect(source).toContain("resolveMobileZone(searchParams)")
+ expect(source).toContain("resolveCommunityRoute(pathname)")
+ expect(source).toContain("useCommunityNavigationController")
expect(source).toContain("<ShellFrameView")
expect(source).not.toContain("<ServerRail")
expect(source).not.toContain("<ProfileCard")
diff --git a/src/web/src/components/community/shell/shell-frame-view.test.ts b/src/web/src/components/community/shell/shell-frame-view.test.ts
index dc14168b1..374643079 100644
--- a/src/web/src/components/community/shell/shell-frame-view.test.ts
+++ b/src/web/src/components/community/shell/shell-frame-view.test.ts
@@ -72,13 +72,32 @@ describe("ShellFrameView", () => {
vi.stubGlobal("ResizeObserver", ResizeObserverMock)
})
+ it("shows one stable loading frame while the breakpoint is unknown", async () => {
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(ShellFrameView, {
+ breakpoint: "unknown",
+ surface: "detail",
+ navigationPending: false,
+ sidebar: () => createElement("sidebar-content"),
+ cancelPendingNavigation: vi.fn(),
+ rail,
+ profile,
+ inbox,
+ }, createElement("main-content")))
+ })
+ expect(renderer.root.findAllByType("channel-loading-frame")).toHaveLength(1)
+ expect(renderer.root.findAllByType("server-rail")).toHaveLength(0)
+ expect(renderer.root.findAllByType("main-content")).toHaveLength(0)
+ })
+
it("keeps the desktop panel geometry, order, and seeded overlay call", async () => {
const sidebar = vi.fn(() => createElement("sidebar-content"))
let renderer!: TestRenderer.ReactTestRenderer
await act(async () => {
renderer = TestRenderer.create(createElement(ShellFrameView, {
breakpoint: "desktop",
- mobileZone: "messages",
+ surface: "detail",
navigationPending: false,
sidebar,
cancelPendingNavigation: vi.fn(),
@@ -128,7 +147,7 @@ describe("ShellFrameView", () => {
await act(async () => {
renderer = TestRenderer.create(createElement(ShellFrameView, {
breakpoint: "mobile",
- mobileZone: "nav",
+ surface: "list",
navigationPending: false,
sidebar,
cancelPendingNavigation: vi.fn(),
@@ -151,7 +170,7 @@ describe("ShellFrameView", () => {
await act(async () => {
renderer.update(createElement(ShellFrameView, {
breakpoint: "mobile",
- mobileZone: "messages",
+ surface: "detail",
navigationPending: false,
sidebar,
cancelPendingNavigation: vi.fn(),
@@ -170,7 +189,7 @@ describe("ShellFrameView", () => {
it("disconnects and re-subscribes sidebar observation across breakpoint changes", async () => {
const sidebar = vi.fn(() => createElement("sidebar-content"))
const common = {
- mobileZone: "nav" as const,
+ surface: "list" as const,
navigationPending: false,
sidebar,
cancelPendingNavigation: vi.fn(),
@@ -224,7 +243,7 @@ describe("ShellFrameView", () => {
await act(async () => {
renderer = TestRenderer.create(createElement(
ShellFrameView,
- { ...common, breakpoint: "desktop", mobileZone: "messages" },
+ { ...common, breakpoint: "desktop", surface: "detail" },
createElement("main-content"),
), { createNodeMock: () => ({ offsetWidth: 240 }) })
})
@@ -234,7 +253,7 @@ describe("ShellFrameView", () => {
await act(async () => {
renderer.update(createElement(
ShellFrameView,
- { ...common, breakpoint: "mobile", mobileZone: "nav" },
+ { ...common, breakpoint: "mobile", surface: "list" },
createElement("main-content"),
))
})
@@ -243,7 +262,7 @@ describe("ShellFrameView", () => {
await act(async () => {
renderer.update(createElement(
ShellFrameView,
- { ...common, breakpoint: "mobile", mobileZone: "messages" },
+ { ...common, breakpoint: "mobile", surface: "detail" },
createElement("main-content"),
))
})
diff --git a/src/web/src/components/community/shell/shell-frame-view.tsx b/src/web/src/components/community/shell/shell-frame-view.tsx
index a77aeb11b..7d2d5d29c 100644
--- a/src/web/src/components/community/shell/shell-frame-view.tsx
+++ b/src/web/src/components/community/shell/shell-frame-view.tsx
@@ -15,7 +15,7 @@ import {
desktopUserBarOverlayWidth,
} from "./shell-frame-geometry"
import type { Breakpoint } from "@/hooks/use-mobile"
-import type { MobileZone } from "./mobile-zone"
+import type { CommunitySurface } from "@/lib/community/community-route"
import type { ShellFrameProps } from "./shell-frame-types"
import type { useShellRailController } from "./use-shell-rail-controller"
import type { useShellProfileController } from "./use-shell-profile-controller"
@@ -23,7 +23,7 @@ import type { useShellInboxController } from "./use-shell-inbox-controller"
type Props = Pick<ShellFrameProps, "sidebar" | "children" | "extraDialogs"> & {
breakpoint: Breakpoint
- mobileZone: MobileZone
+ surface: CommunitySurface
cancelPendingNavigation: () => void
navigationPending: boolean
rail: ReturnType<typeof useShellRailController>
@@ -35,7 +35,7 @@ const SHELL_SURFACE_CLASS = "rounded-tl-xl rounded-tr-none rounded-br-none round
export function ShellFrameView({
breakpoint,
- mobileZone,
+ surface,
sidebar,
children,
extraDialogs,
@@ -64,6 +64,16 @@ export function ShellFrameView({
avatar: profile.currentUser.avatar,
}
+ if (breakpoint === "unknown") {
+ return (
+ <Shell onNavigationIntent={cancelPendingNavigation}>
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background">
+ <ChannelLoadingFrame />
+ </div>
+ </Shell>
+ )
+ }
+
if (breakpoint === "desktop") {
return (
<Shell onNavigationIntent={cancelPendingNavigation}>
@@ -131,7 +141,7 @@ export function ShellFrameView({
return (
<Shell onNavigationIntent={cancelPendingNavigation}>
- {mobileZone === "nav" && (
+ {surface === "list" && (
<>
<ServerRail {...rail.railProps} bottomInset={60} />
<div className="relative flex min-h-0 min-w-0 flex-1 flex-col pt-2">
@@ -154,12 +164,12 @@ export function ShellFrameView({
</div>
</>
)}
- {mobileZone === "messages" && (
+ {surface === "detail" && (
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background">
{navigationPending ? <ChannelLoadingFrame /> : children}
</div>
)}
- {mobileZone === "nav" && navigationPending && (
+ {surface === "list" && navigationPending && (
<div className="absolute inset-0 z-20 flex bg-background">
<ChannelLoadingFrame />
</div>
diff --git a/src/web/src/components/community/shell/shell-frame.test.ts b/src/web/src/components/community/shell/shell-frame.test.ts
index eeebdfa0c..266a948f3 100644
--- a/src/web/src/components/community/shell/shell-frame.test.ts
+++ b/src/web/src/components/community/shell/shell-frame.test.ts
@@ -12,11 +12,11 @@ const mocks = vi.hoisted(() => {
cancelPendingNavigation: vi.fn(),
}
return {
- onboarding: { current: { status: "active", stage: "server" } as unknown },
- pathname: { current: "/c/channels/s1" },
- searchParams: { current: new URLSearchParams() },
+ currentHref: { current: "/c/channels/s1" },
breakpoint: { current: "desktop" },
- replaceState: vi.fn(),
+ onboardingState: { current: null as Record<string, unknown> | null },
+ replace: vi.fn(),
+ push: vi.fn(),
registerUiHandlers: vi.fn(),
handlers,
rail: {
@@ -33,15 +33,21 @@ const mocks = vi.hoisted(() => {
}
})
-vi.mock("next/navigation", () => ({
- useRouter: () => ({ push: vi.fn(), replace: vi.fn(), prefetch: vi.fn() }),
- usePathname: () => mocks.pathname.current,
- useSearchParams: () => mocks.searchParams.current,
-}))
vi.mock("@tanstack/react-query", () => ({ useQueryClient: () => ({}) }))
vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mocks.breakpoint.current }))
vi.mock("@/lib/community-onboarding", () => ({
- useCommunityOnboarding: () => mocks.onboarding.current,
+ useCommunityOnboarding: () => mocks.onboardingState.current,
+}))
+vi.mock("./use-community-navigation-controller", () => ({
+ useCommunityNavigationController: () => ({
+ currentHref: mocks.currentHref.current,
+ navigationPending: false,
+ push: mocks.push,
+ replace: mocks.replace,
+ prefetch: vi.fn(),
+ resolveAndPush: vi.fn(),
+ cancelPendingNavigation: mocks.handlers.cancelPendingNavigation,
+ }),
}))
vi.mock("@/stores/community", () => ({
useCommunityStore: Object.assign(vi.fn(), {
@@ -69,54 +75,67 @@ const baseProps = {
describe("ShellFrame orchestration", () => {
beforeEach(() => {
- mocks.onboarding.current = { status: "active", stage: "server" }
- mocks.pathname.current = "/c/channels/s1"
- mocks.searchParams.current = new URLSearchParams()
+ mocks.currentHref.current = "/c/channels/s1"
mocks.breakpoint.current = "desktop"
+ mocks.onboardingState.current = null
mocks.registerUiHandlers.mockClear()
- mocks.replaceState.mockClear()
- vi.stubGlobal("window", {
- history: { replaceState: mocks.replaceState },
- location: { hash: "" },
- })
+ mocks.replace.mockClear()
+ mocks.push.mockClear()
})
afterEach(() => vi.unstubAllGlobals())
- it("derives the pane from the current URL and tracks search-param updates", async () => {
- mocks.searchParams.current = new URLSearchParams("pane=nav")
+ it("derives list and detail surfaces from the pathname", async () => {
let renderer!: TestRenderer.ReactTestRenderer
await act(async () => {
renderer = TestRenderer.create(createElement(ShellFrame, baseProps))
})
- expect(renderer.root.findByType("shell-frame-view").props.mobileZone).toBe("nav")
+ expect(renderer.root.findByType("shell-frame-view").props.surface).toBe("list")
- mocks.searchParams.current = new URLSearchParams()
+ mocks.currentHref.current = "/c/channels/s1/c1?keep=1"
await act(async () => {
renderer.update(createElement(ShellFrame, baseProps, "next"))
})
- expect(renderer.root.findByType("shell-frame-view").props.mobileZone).toBe("messages")
+ expect(renderer.root.findByType("shell-frame-view").props.surface).toBe("detail")
})
- it("commits onboarding pane changes through native history on mobile", async () => {
+ it("replaces a mobile detail with its semantic parent", async () => {
mocks.breakpoint.current = "mobile"
+ mocks.currentHref.current = "/c/channels/s1/c1"
let renderer!: TestRenderer.ReactTestRenderer
await act(async () => {
renderer = TestRenderer.create(createElement(ShellFrame, baseProps))
})
- expect(mocks.replaceState).toHaveBeenLastCalledWith(
- null, "", "/c/channels/s1?pane=nav",
- )
+ const handlers = mocks.registerUiHandlers.mock.calls.at(-1)?.[0]
+ handlers.goBackMobile()
+ expect(mocks.replace).toHaveBeenLastCalledWith("/c/channels/s1")
+ })
+
+ it("returns mobile server onboarding to the semantic list surface", async () => {
+ mocks.breakpoint.current = "mobile"
+ mocks.currentHref.current = "/c/me/dm_1"
+ mocks.onboardingState.current = { status: "active", stage: "server" }
- mocks.searchParams.current = new URLSearchParams("pane=nav")
- mocks.onboarding.current = { status: "active", stage: "channel" }
await act(async () => {
- renderer.update(createElement(ShellFrame, baseProps, "channel"))
+ TestRenderer.create(createElement(ShellFrame, baseProps))
})
- expect(mocks.replaceState).toHaveBeenLastCalledWith(null, "", "/c/channels/s1")
+
+ expect(mocks.replace).toHaveBeenCalledWith("/c/me")
+ })
+
+ it("keeps mobile server onboarding stable on an existing list surface", async () => {
+ mocks.breakpoint.current = "mobile"
+ mocks.currentHref.current = "/c/me"
+ mocks.onboardingState.current = { status: "active", stage: "server" }
+
+ await act(async () => {
+ TestRenderer.create(createElement(ShellFrame, baseProps))
+ })
+
+ expect(mocks.replace).not.toHaveBeenCalled()
})
- it("registers exactly six stable UI handlers", async () => {
+ it("registers the shared navigation and UI handlers", async () => {
let renderer!: TestRenderer.ReactTestRenderer
await act(async () => {
renderer = TestRenderer.create(createElement(ShellFrame, baseProps))
@@ -126,26 +145,26 @@ describe("ShellFrame orchestration", () => {
"cancelPendingNavigation",
"goBackMobile",
"navigate",
+ "navigatePath",
"openProfile",
"previewAttachment",
"previewImage",
+ "replacePath",
])
- mocks.searchParams.current = new URLSearchParams("msg=m1")
- Object.assign(window.location, { hash: "#anchor" })
+ mocks.currentHref.current = "/c/channels/s1/c1?msg=m1"
await act(async () => {
renderer.update(createElement(ShellFrame, baseProps, "message"))
})
const withMessage = mocks.registerUiHandlers.mock.calls.at(-1)?.[0]
withMessage.goBackMobile()
- expect(mocks.replaceState).toHaveBeenLastCalledWith(
- null, "", "/c/channels/s1?msg=m1&pane=nav#anchor",
- )
+ expect(mocks.replace).toHaveBeenLastCalledWith("/c/channels/s1")
await act(async () => {
renderer.update(createElement(ShellFrame, baseProps, "rerender"))
})
const second = mocks.registerUiHandlers.mock.calls.at(-1)?.[0]
- for (const key of Object.keys(withMessage)) expect(second[key]).toBe(withMessage[key])
+ expect(second.navigatePath).toBe(withMessage.navigatePath)
+ expect(second.replacePath).toBe(withMessage.replacePath)
})
})
diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsx
index 97859a2f4..4defe4904 100644
--- a/src/web/src/components/community/shell/shell-frame.tsx
+++ b/src/web/src/components/community/shell/shell-frame.tsx
@@ -1,16 +1,16 @@
"use client"
import { useCallback, useEffect } from "react"
-import { usePathname, useRouter, useSearchParams } from "next/navigation"
import { useQueryClient } from "@tanstack/react-query"
import { useBreakpoint } from "@/hooks/use-mobile"
import { useCommunityOnboarding } from "@/lib/community-onboarding"
+import { resolveCommunityRoute } from "@/lib/community/community-route"
import { useCommunityStore } from "@/stores/community"
import { ShellFrameView } from "./shell-frame-view"
import { useShellRailController } from "./use-shell-rail-controller"
import { useShellProfileController } from "./use-shell-profile-controller"
import { useShellInboxController } from "./use-shell-inbox-controller"
-import { resolveMobileZone, withMobileZone } from "./mobile-zone"
+import { useCommunityNavigationController } from "./use-community-navigation-controller"
import type { ShellFrameProps } from "./shell-frame-types"
/** Shared community shell orchestration for the server and DM layouts. */
@@ -24,53 +24,48 @@ export function ShellFrame(props: ShellFrameProps) {
onOpenActiveServerSettings,
onOpenActiveServerInvite,
} = props
- const router = useRouter()
- const pathname = usePathname()
- const searchParams = useSearchParams()
const queryClient = useQueryClient()
const breakpoint = useBreakpoint()
const onboardingState = useCommunityOnboarding()
- const search = searchParams.toString()
- const currentHref = search ? `${pathname}?${search}` : pathname
- const mobileZone = resolveMobileZone(searchParams)
-
- useEffect(() => {
- if (breakpoint !== "mobile" || onboardingState?.status !== "active") return
- const browserHref = `${currentHref}${window.location.hash}`
- const nextHref = withMobileZone(
- browserHref,
- onboardingState.stage === "server" ? "nav" : "messages",
- )
- if (nextHref !== browserHref) window.history.replaceState(null, "", nextHref)
- }, [breakpoint, currentHref, onboardingState])
+ const navigation = useCommunityNavigationController()
+ const replacePath = navigation.replace
+ const pathname = navigation.currentHref.split("?")[0]!
+ const route = resolveCommunityRoute(pathname)
const rail = useShellRailController({
- router,
+ navigation,
queryClient,
- breakpoint,
- currentHref,
view,
activeServerId,
onOpenActiveServerSettings,
onOpenActiveServerInvite,
})
const profile = useShellProfileController({
- router,
+ router: navigation,
queryClient,
- cancelPendingNavigation: rail.cancelPendingNavigation,
+ cancelPendingNavigation: navigation.cancelPendingNavigation,
view,
activeServerId,
})
const inbox = useShellInboxController({
- router,
+ router: navigation,
queryClient,
- cancelPendingNavigation: rail.cancelPendingNavigation,
+ cancelPendingNavigation: navigation.cancelPendingNavigation,
})
const goBackMobile = useCallback(() => {
- const browserHref = `${currentHref}${window.location.hash}`
- const nextHref = withMobileZone(browserHref, "nav")
- if (nextHref !== browserHref) window.history.replaceState(null, "", nextHref)
- }, [currentHref])
+ if (route.parentPath) navigation.replace(route.parentPath)
+ }, [navigation, route.parentPath])
+
+ useEffect(() => {
+ if (
+ breakpoint !== "mobile" ||
+ onboardingState?.status !== "active" ||
+ onboardingState.stage !== "server" ||
+ route.surface !== "detail" ||
+ !route.parentPath
+ ) return
+ replacePath(route.parentPath)
+ }, [breakpoint, onboardingState, replacePath, route.parentPath, route.surface])
useEffect(() => {
useCommunityStore.getState().registerUiHandlers({
@@ -78,26 +73,30 @@ export function ShellFrame(props: ShellFrameProps) {
previewAttachment: profile.previewAttachment,
openProfile: profile.openProfile,
goBackMobile,
+ navigatePath: navigation.push,
+ replacePath: navigation.replace,
navigate: rail.navigate,
- cancelPendingNavigation: rail.cancelPendingNavigation,
+ cancelPendingNavigation: navigation.cancelPendingNavigation,
})
}, [
goBackMobile,
profile.openProfile,
profile.previewAttachment,
profile.previewImage,
- rail.cancelPendingNavigation,
rail.navigate,
+ navigation.cancelPendingNavigation,
+ navigation.push,
+ navigation.replace,
])
return (
<ShellFrameView
breakpoint={breakpoint}
- mobileZone={mobileZone}
+ surface={route.surface}
sidebar={sidebar}
extraDialogs={extraDialogs}
- cancelPendingNavigation={rail.cancelPendingNavigation}
- navigationPending={rail.navigationPending}
+ cancelPendingNavigation={navigation.cancelPendingNavigation}
+ navigationPending={navigation.navigationPending}
rail={rail}
profile={profile}
inbox={inbox}
diff --git a/src/web/src/components/community/shell/use-community-navigation-controller.test.ts b/src/web/src/components/community/shell/use-community-navigation-controller.test.ts
new file mode 100644
index 000000000..e70fcb603
--- /dev/null
+++ b/src/web/src/components/community/shell/use-community-navigation-controller.test.ts
@@ -0,0 +1,96 @@
+import { createElement } from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { useCommunityNavigationController } from "./use-community-navigation-controller"
+
+const mocks = vi.hoisted(() => ({
+ pathname: { current: "/c/me" },
+ search: { current: new URLSearchParams() },
+ push: vi.fn(),
+ replace: vi.fn(),
+ prefetch: vi.fn(),
+}))
+
+vi.mock("next/navigation", () => ({
+ usePathname: () => mocks.pathname.current,
+ useSearchParams: () => mocks.search.current,
+ useRouter: () => ({
+ push: mocks.push,
+ replace: mocks.replace,
+ prefetch: mocks.prefetch,
+ }),
+}))
+
+type Result = ReturnType<typeof useCommunityNavigationController>
+
+function Capture({ onResult }: { onResult: (result: Result) => void }) {
+ onResult(useCommunityNavigationController())
+ return null
+}
+
+async function renderController() {
+ let current!: Result
+ let renderer!: TestRenderer.ReactTestRenderer
+ const onResult = (result: Result) => { current = result }
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(Capture, { onResult }))
+ })
+ return {
+ get current() { return current },
+ rerender: async () => {
+ await act(async () => renderer.update(createElement(Capture, { onResult })))
+ },
+ }
+}
+
+describe("useCommunityNavigationController", () => {
+ beforeEach(() => {
+ mocks.pathname.current = "/c/me"
+ mocks.search.current = new URLSearchParams()
+ mocks.push.mockReset()
+ mocks.replace.mockReset()
+ mocks.prefetch.mockReset()
+ })
+
+ it("sets pending immediately and clears it after the committed href changes", async () => {
+ const hook = await renderController()
+ expect(hook.current.navigationPending).toBe(false)
+
+ await act(async () => hook.current.push("/c/me/friends"))
+ expect(mocks.push).toHaveBeenCalledWith("/c/me/friends")
+ expect(hook.current.navigationPending).toBe(true)
+
+ mocks.pathname.current = "/c/me/friends"
+ await hook.rerender()
+ expect(hook.current.navigationPending).toBe(false)
+ })
+
+ it("uses replace for semantic parent navigation", async () => {
+ const hook = await renderController()
+ await act(async () => hook.current.replace("/c/channels/s1"))
+ expect(mocks.replace).toHaveBeenCalledWith("/c/channels/s1")
+ expect(mocks.push).not.toHaveBeenCalled()
+ })
+
+ it("commits only the latest async destination", async () => {
+ const hook = await renderController()
+ let resolveFirst!: (href: string) => void
+ let resolveSecond!: (href: string) => void
+ const first = new Promise<string>((resolve) => { resolveFirst = resolve })
+ const second = new Promise<string>((resolve) => { resolveSecond = resolve })
+ let firstResult!: Promise<boolean>
+ let secondResult!: Promise<boolean>
+
+ await act(async () => {
+ firstResult = hook.current.resolveAndPush(() => first)
+ secondResult = hook.current.resolveAndPush(() => second)
+ })
+ resolveFirst("/c/channels/s1/c1")
+ resolveSecond("/c/channels/s2/c2")
+
+ await expect(firstResult).resolves.toBe(false)
+ await expect(secondResult).resolves.toBe(true)
+ expect(mocks.push).toHaveBeenCalledTimes(1)
+ expect(mocks.push).toHaveBeenCalledWith("/c/channels/s2/c2")
+ })
+})
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.ts
new file mode 100644
index 000000000..98bf974be
--- /dev/null
+++ b/src/web/src/components/community/shell/use-community-navigation-controller.ts
@@ -0,0 +1,80 @@
+"use client"
+
+import { useCallback, useEffect, useRef, useState } from "react"
+import { usePathname, useRouter, useSearchParams } from "next/navigation"
+import {
+ commitLatestNavigationIntent,
+ createNavigationIntentGate,
+ supersedeNavigationIntent,
+} from "@/lib/community/navigation-intent"
+import type { ShellRouter } from "./shell-frame-types"
+
+export type CommunityNavigationController = {
+ currentHref: string
+ navigationPending: boolean
+ push: (href: string) => void
+ replace: (href: string) => void
+ prefetch: (href: string) => void
+ resolveAndPush: (resolve: () => Promise<string>) => Promise<boolean>
+ cancelPendingNavigation: () => void
+}
+
+export function useCommunityNavigationController(): CommunityNavigationController {
+ const router = useRouter() as ShellRouter
+ const pathname = usePathname()
+ const searchParams = useSearchParams()
+ const search = searchParams.toString()
+ const currentHref = search ? `${pathname}?${search}` : pathname
+ const gateRef = useRef(createNavigationIntentGate())
+ const [navigationPending, setNavigationPending] = useState(false)
+
+ const cancelPendingNavigation = useCallback(() => {
+ supersedeNavigationIntent(gateRef.current)
+ setNavigationPending(false)
+ }, [])
+
+ useEffect(() => {
+ supersedeNavigationIntent(gateRef.current)
+ setNavigationPending(false)
+ }, [currentHref])
+
+ const push = useCallback((href: string) => {
+ if (href === currentHref) return
+ supersedeNavigationIntent(gateRef.current)
+ setNavigationPending(true)
+ router.push(href)
+ }, [currentHref, router])
+
+ const replace = useCallback((href: string) => {
+ if (href === currentHref) return
+ supersedeNavigationIntent(gateRef.current)
+ setNavigationPending(true)
+ router.replace(href)
+ }, [currentHref, router])
+
+ const resolveAndPush = useCallback(async (resolve: () => Promise<string>) => {
+ setNavigationPending(true)
+ try {
+ return await commitLatestNavigationIntent(gateRef.current, resolve, (href) => {
+ if (href === currentHref) {
+ setNavigationPending(false)
+ return
+ }
+ router.push(href)
+ })
+ } catch (error) {
+ setNavigationPending(false)
+ throw error
+ }
+ }, [currentHref, router])
+
+ return {
+ currentHref,
+ navigationPending,
+ push,
+ replace,
+ prefetch: router.prefetch,
+ resolveAndPush,
+ cancelPendingNavigation,
+ }
+}
diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts
index a81864f38..c3a4eb465 100644
--- a/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts
+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts
@@ -115,7 +115,7 @@ describe("useShellInboxController", () => {
expect(hook.order).toEqual(["watch", "read", "cancel", "push"])
expect(mocks.watch).toHaveBeenCalledWith("channel:child")
expect(mocks.readForum).toHaveBeenCalledWith({ parentChannelId: "forum", openerMessageId: "opener" })
- expect(hook.pushed.at(-1)).toBe("/c/channels/s1/child")
+ expect(hook.pushed.at(-1)).toBe("/c/channels/s1/forum/child")
hook.order.length = 0
await act(async () => hook.current.popoverProps.onOpenMention?.({ id: "m1" } as never))
@@ -136,6 +136,16 @@ describe("useShellInboxController", () => {
expect(mocks.watch).toHaveBeenLastCalledWith("marked:mk1")
expect(hook.pushed.at(-1)).toBe("/c/channels/s1/c1?seq=7")
+ await act(async () => hook.current.popoverProps.onOpenMarked?.({
+ id: "mk-child",
+ serverId: "s1",
+ channelId: "child1",
+ parentChannelId: "parent1",
+ m: { seq: 8 },
+ } as never))
+ expect(mocks.watch).toHaveBeenLastCalledWith("marked:mk-child")
+ expect(hook.pushed.at(-1)).toBe("/c/channels/s1/parent1/child1?seq=8")
+
await act(async () => hook.current.popoverProps.onOpenMarked?.({
id: "mk2",
serverId: null,
diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.ts
index e7afd5952..11c4cd3c1 100644
--- a/src/web/src/components/community/shell/use-shell-inbox-controller.ts
+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.ts
@@ -2,6 +2,7 @@
import { useCallback, useState, type ComponentProps } from "react"
import { communityKeys } from "@/lib/query-keys"
+import { childChannelHref } from "@/lib/community/community-route"
import type { Marked } from "@/lib/community/models/inbox"
import { useInboxUnreads, useInboxMentions, useInboxMarked } from "@/hooks/community/use-inbox"
import { useInboxAutoCollapse } from "@/hooks/community/use-inbox-auto-collapse"
@@ -44,11 +45,14 @@ export function useShellInboxController({
const openServerChannel = useCallback((
serverId: string,
channelId: string,
+ parentChannelId?: string,
watchKey: string = `channel:${channelId}`,
) => {
watchInboxItem(watchKey)
cancelPendingNavigation()
- router.push(`/c/channels/${serverId}/${channelId}`)
+ router.push(parentChannelId
+ ? childChannelHref(serverId, parentChannelId, channelId)
+ : `/c/channels/${serverId}/${channelId}`)
}, [cancelPendingNavigation, router, watchInboxItem])
const openForumThread = useCallback((
@@ -60,7 +64,7 @@ export function useShellInboxController({
watchInboxItem(`channel:${childChannelId}`)
readForumThreadFromInbox({ parentChannelId, openerMessageId })
cancelPendingNavigation()
- router.push(`/c/channels/${serverId}/${childChannelId}`)
+ router.push(childChannelHref(serverId, parentChannelId, childChannelId))
}, [cancelPendingNavigation, readForumThreadFromInbox, router, watchInboxItem])
const openMarked = useCallback((marked: Marked) => {
@@ -68,7 +72,10 @@ export function useShellInboxController({
cancelPendingNavigation()
const seqQuery = marked.m.seq != null ? `?seq=${marked.m.seq}` : ""
if (marked.serverId) {
- router.push(`/c/channels/${marked.serverId}/${marked.channelId}${seqQuery}`)
+ const channelPath = marked.parentChannelId
+ ? childChannelHref(marked.serverId, marked.parentChannelId, marked.channelId)
+ : `/c/channels/${marked.serverId}/${marked.channelId}`
+ router.push(`${channelPath}${seqQuery}`)
} else {
router.push(`/c/me/${marked.channelId}${seqQuery}`)
}
@@ -104,7 +111,7 @@ export function useShellInboxController({
onOpenDm: openDm,
onOpenMention: (mention) => {
if (mention.serverId && mention.channelId) {
- openServerChannel(mention.serverId, mention.channelId, `mention:${mention.id}`)
+ openServerChannel(mention.serverId, mention.channelId, undefined, `mention:${mention.id}`)
}
},
onOpenMarked: openMarked,
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.ts
index ed3e62ae5..0032c3a68 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
@@ -78,15 +78,22 @@ async function renderController(overrides: Record<string, unknown> = {}) {
replace: (href: string) => { replaced.push(href) },
prefetch: (href: string) => { prefetched.push(href) },
}
+ const navigation = {
+ currentHref: "/c/channels/s1",
+ navigationPending: false,
+ push: router.push,
+ replace: router.replace,
+ prefetch: router.prefetch,
+ resolveAndPush: vi.fn(),
+ cancelPendingNavigation: vi.fn(),
+ }
const cache = new Map<string, unknown>()
const queryClient = {
getQueryData: vi.fn((key: unknown[]) => cache.get(String(key.at(-1)))),
fetchQuery: vi.fn(),
}
const options = {
- router,
- currentHref: "/c/channels/s1",
- breakpoint: "desktop",
+ navigation,
queryClient,
view: "server",
activeServerId: "s1",
@@ -106,6 +113,7 @@ async function renderController(overrides: Record<string, unknown> = {}) {
renderer,
options,
router,
+ navigation,
queryClient,
cache,
pushed,
@@ -128,22 +136,16 @@ describe("useShellRailController", () => {
it("commits cold server navigation synchronously without waiting for detail", async () => {
const hook = await renderController()
- expect(hook.current.navigationPending).toBe(false)
-
await act(async () => {
hook.current.railProps.onServerNavigate("s1")
hook.current.railProps.onServerNavigate("s2")
})
- expect(hook.pushed).toEqual(["/c/channels/s2"])
- expect(hook.current.navigationPending).toBe(true)
+ expect(hook.pushed).toEqual(["/c/channels/s1", "/c/channels/s2"])
expect(hook.queryClient.fetchQuery).not.toHaveBeenCalled()
expect(mocks.markSwitch).toHaveBeenNthCalledWith(1, "server", "s1")
expect(mocks.markSwitch).toHaveBeenNthCalledWith(2, "server", "s2")
- hook.options.currentHref = "/c/channels/s2"
- await hook.rerender()
- expect(hook.current.navigationPending).toBe(false)
})
it("does not leave deferred server work that can overwrite a direct channel navigation", async () => {
@@ -200,22 +202,14 @@ describe("useShellRailController", () => {
expect(hook.queryClient.fetchQuery).not.toHaveBeenCalled()
})
- it("adds the nav pane on mobile and skips an exact current rail target", async () => {
- const hook = await renderController({
- breakpoint: "mobile",
- currentHref: "/c/channels/s1/cached?pane=nav",
- })
+ it("always sends rail selection to the semantic server root", async () => {
+ const hook = await renderController()
hook.cache.set("s1", {
categories: [{ channels: [{ id: "cached", pending: false }] }],
})
await act(async () => hook.current.railProps.onServerNavigate("s1"))
- expect(hook.pushed).toEqual([])
-
- hook.options.currentHref = "/c/channels/s2/other"
- await hook.rerender()
- await act(async () => hook.current.railProps.onServerNavigate("s1"))
- expect(hook.pushed).toEqual(["/c/channels/s1/cached?pane=nav"])
+ expect(hook.pushed).toEqual(["/c/channels/s1"])
})
it("uses cached and fetched destinations for navigation and prefetch fallbacks", async () => {
@@ -227,7 +221,7 @@ describe("useShellRailController", () => {
await act(async () => hook.current.railProps.onServerNavigate("s1"))
await act(async () => hook.current.railProps.onServerPrefetch("s1"))
await act(async () => hook.current.railProps.onHomePrefetch())
- expect(hook.pushed).toEqual(["/c/channels/s1/cached"])
+ expect(hook.pushed).toEqual(["/c/channels/s1"])
expect(hook.prefetched).toEqual(["/c/channels/s1/cached", "/c/me"])
expect(hook.queryClient.fetchQuery).not.toHaveBeenCalled()
@@ -276,7 +270,7 @@ describe("useShellRailController", () => {
})
mocks.toast.mockImplementation(() => { order.push("toast") })
const hook = await renderController()
- hook.router.push = (href: string) => { order.push(`push:${href}`) }
+ hook.navigation.push = (href: string) => { order.push(`push:${href}`) }
await act(async () => hook.current.railProps.onCreateServer("New"))
expect(order).toEqual(["create", "toast", "push:/c/channels/new"])
@@ -286,7 +280,7 @@ describe("useShellRailController", () => {
order.push("mutate")
options.onSuccess()
})
- hook.router.replace = (href: string) => { order.push(`replace:${href}`) }
+ hook.navigation.replace = (href: string) => { order.push(`replace:${href}`) }
await act(async () => hook.current.railProps.onLeaveServer("s1"))
expect(order).toEqual(["mark", "mutate", "toast", "replace:/c/me"])
})
@@ -301,7 +295,7 @@ describe("useShellRailController", () => {
mocks.toast.mockImplementation(() => { order.push("toast") })
mocks.uploadIcon.mockImplementation(() => { order.push("upload") })
const hook = await renderController()
- hook.router.push = (href: string) => { order.push(`push:${href}`) }
+ hook.navigation.push = (href: string) => { order.push(`push:${href}`) }
await act(async () => hook.current.railProps.onCreateServer("New", file))
expect(order).toEqual(["create", "toast", "upload", "push:/c/channels/new"])
diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.ts b/src/web/src/components/community/shell/use-shell-rail-controller.ts
index f29b324de..389358aec 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
@@ -1,6 +1,6 @@
"use client"
-import { useCallback, useEffect, useMemo, useRef, useState } from "react"
+import { useCallback, useMemo } from "react"
import { toast } from "sonner"
import { toastApiError } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
@@ -20,15 +20,10 @@ import {
} from "@/hooks/community/mutations"
import { getLastChannel, pickServerLandingHref } from "@/lib/community/last-channel"
import { getLastMeLeaf, pickMeLandingLocation } from "@/lib/community/last-me-location"
-import {
- createNavigationIntentGate,
- supersedeNavigationIntent,
-} from "@/lib/community/navigation-intent"
import { useCommunityStore } from "@/stores/community"
-import type { Breakpoint } from "@/hooks/use-mobile"
-import { withMobileZone, type MobileZone } from "./mobile-zone"
import { resolveServerRailOverlayAction } from "./server-rail-actions"
-import type { ShellFrameProps, ShellRouter } from "./shell-frame-types"
+import type { ShellFrameProps } from "./shell-frame-types"
+import type { CommunityNavigationController } from "./use-community-navigation-controller"
import type { QueryClient } from "@tanstack/react-query"
type Options = Pick<
@@ -38,16 +33,12 @@ type Options = Pick<
| "onOpenActiveServerSettings"
| "onOpenActiveServerInvite"
> & {
- router: ShellRouter
- currentHref: string
- breakpoint: Breakpoint
+ navigation: CommunityNavigationController
queryClient: QueryClient
}
export function useShellRailController({
- router,
- currentHref,
- breakpoint,
+ navigation,
queryClient,
view,
activeServerId,
@@ -79,16 +70,6 @@ export function useShellRailController({
[activeServerId, folderServerIds, servers],
)
- const navigationGateRef = useRef(createNavigationIntentGate())
- const [navigationPending, setNavigationPending] = useState(false)
- const cancelPendingNavigation = useCallback(() => {
- supersedeNavigationIntent(navigationGateRef.current)
- }, [])
- useEffect(() => {
- cancelPendingNavigation()
- setNavigationPending(false)
- }, [cancelPendingNavigation, currentHref])
-
const serverDestination = useCallback((id: string) => {
const detail = queryClient.getQueryData<ServerDetail>(communityKeys.server(id))
const channelIds = detail?.categories.flatMap((category) =>
@@ -112,30 +93,19 @@ export function useShellRailController({
return serverDestination(id)
}, [queryClient, serverDestination])
- const paneHref = useCallback((destination: string, mobileZone: MobileZone) =>
- withMobileZone(destination, breakpoint === "mobile" ? mobileZone : "messages"),
- [breakpoint])
- const pushIfChanged = useCallback((destination: string) => {
- if (destination === currentHref) return
- setNavigationPending(true)
- router.push(destination)
- }, [currentHref, router])
-
const onServerNavigate = useCallback((id: string) => {
markSwitch("server", id)
- cancelPendingNavigation()
- pushIfChanged(paneHref(serverDestination(id), "nav"))
- }, [cancelPendingNavigation, paneHref, pushIfChanged, serverDestination])
+ navigation.push(`/c/channels/${id}`)
+ }, [navigation])
const onHome = useCallback(() => {
- cancelPendingNavigation()
- pushIfChanged(paneHref(pickMeLandingLocation(getLastMeLeaf()), "nav"))
- }, [cancelPendingNavigation, paneHref, pushIfChanged])
+ navigation.push("/c/me")
+ }, [navigation])
const onServerPrefetch = useCallback((id: string) => {
- void resolveServerDestination(id).then((destination) => router.prefetch(destination))
- }, [resolveServerDestination, router])
+ void resolveServerDestination(id).then((destination) => navigation.prefetch(destination))
+ }, [navigation, resolveServerDestination])
const onHomePrefetch = useCallback(
- () => router.prefetch(pickMeLandingLocation(getLastMeLeaf())),
- [router],
+ () => navigation.prefetch(pickMeLandingLocation(getLastMeLeaf())),
+ [navigation],
)
const onCreateServer = useCallback(async (name: string, icon?: File) => {
try {
@@ -148,12 +118,11 @@ export function useShellRailController({
{ onError: (error) => toastApiError(error, "Server created, but the icon failed to upload") },
)
}
- cancelPendingNavigation()
- pushIfChanged(paneHref(`/c/channels/${newId}`, "nav"))
+ navigation.push(`/c/channels/${newId}`)
} catch (error) {
toastApiError(error, "Failed to create server")
}
- }, [cancelPendingNavigation, createServerAsync, paneHref, pushIfChanged, uploadServerIconMutate])
+ }, [createServerAsync, navigation, uploadServerIconMutate])
const onLeaveServer = useCallback((id: string) => {
markVoluntaryLeave(id)
leaveServerMutate(
@@ -162,17 +131,15 @@ export function useShellRailController({
onSuccess: () => {
toast("Left server")
if (currentServerId === id) {
- cancelPendingNavigation()
- router.replace(paneHref(pickPostEjectDestination(servers, id), "nav"))
+ navigation.replace(pickPostEjectDestination(servers, id))
}
},
onError: (error) => toastApiError(error, "Failed to leave server"),
},
)
- }, [cancelPendingNavigation, currentServerId, leaveServerMutate, paneHref, router, servers])
+ }, [currentServerId, leaveServerMutate, navigation, servers])
const onOpenSettings = useCallback((id?: string) => {
if (!id) return
- cancelPendingNavigation()
const action = resolveServerRailOverlayAction({
targetServerId: id,
activeServerId,
@@ -180,11 +147,10 @@ export function useShellRailController({
hasActiveOpener: !!onOpenActiveServerSettings,
})
if (action.kind === "open-active") onOpenActiveServerSettings?.()
- else pushIfChanged(paneHref(action.href, "nav"))
- }, [activeServerId, cancelPendingNavigation, onOpenActiveServerSettings, paneHref, pushIfChanged])
+ else navigation.push(action.href)
+ }, [activeServerId, navigation, onOpenActiveServerSettings])
const onOpenInvitePopover = useCallback((id?: string) => {
if (!id) return
- cancelPendingNavigation()
const action = resolveServerRailOverlayAction({
targetServerId: id,
activeServerId,
@@ -192,8 +158,8 @@ export function useShellRailController({
hasActiveOpener: !!onOpenActiveServerInvite,
})
if (action.kind === "open-active") onOpenActiveServerInvite?.()
- else pushIfChanged(paneHref(action.href, "nav"))
- }, [activeServerId, cancelPendingNavigation, onOpenActiveServerInvite, paneHref, pushIfChanged])
+ else navigation.push(action.href)
+ }, [activeServerId, navigation, onOpenActiveServerInvite])
const onUngroupFolder = useCallback((folderId: string) => {
deleteFolderMutate(
{ folderId },
@@ -228,13 +194,11 @@ export function useShellRailController({
const navigate = useCallback((serverId: string, channelId?: string) => {
markSwitch(channelId ? "channel" : "server", channelId ?? serverId)
if (channelId) {
- cancelPendingNavigation()
- pushIfChanged(paneHref(`/c/channels/${serverId}/${channelId}`, "messages"))
+ navigation.push(`/c/channels/${serverId}/${channelId}`)
return
}
- cancelPendingNavigation()
- pushIfChanged(paneHref(serverDestination(serverId), "messages"))
- }, [cancelPendingNavigation, paneHref, pushIfChanged, serverDestination])
+ navigation.push(serverDestination(serverId))
+ }, [navigation, serverDestination])
return {
railProps: {
@@ -258,7 +222,5 @@ export function useShellRailController({
onDragCreateFolder,
},
navigate,
- cancelPendingNavigation,
- navigationPending,
}
}
diff --git a/src/web/src/components/theme-color-sync.tsx b/src/web/src/components/theme-color-sync.tsx
index 3654f3baf..ede87cc27 100644
--- a/src/web/src/components/theme-color-sync.tsx
+++ b/src/web/src/components/theme-color-sync.tsx
@@ -52,8 +52,7 @@ export function ThemeColorSync() {
syncThemeColorToRailBackground();
scheduleSync();
- // Next can replace viewport metadata during client navigation, including a
- // query-only mobile pane change where usePathname() does not change.
+ // Next can replace viewport metadata during client navigation.
const observer = new MutationObserver(() => {
scheduleSync();
});
diff --git a/src/web/src/hooks/community/use-channel-route-model.ts b/src/web/src/hooks/community/use-channel-route-model.ts
index ea55466ef..8457629cc 100644
--- a/src/web/src/hooks/community/use-channel-route-model.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.ts
@@ -86,7 +86,13 @@ export function useChannelRouteModel(serverId: string, serverParam: string, chan
useCommunityStore.getState().setCurrentChannelMeta(null)
removeForumSidebarUnreadChild(queryClient, serverId, channelId)
removeForumSidebarThreadExact(queryClient, serverId, channelId)
- if (getLastChannel(serverId) === channelId) clearLastChannel(serverId)
+ const lastChannel = getLastChannel(serverId)
+ if (
+ lastChannel === channelId ||
+ lastChannel?.endsWith(`/${channelId}`)
+ ) {
+ clearLastChannel(serverId)
+ }
router.replace(`/c/channels/${serverParam}`)
} else if (metaQuery.data && metaQuery.isVerified) {
useCommunityStore.getState().setCurrentChannelMeta(metaQuery.data)
diff --git a/src/web/src/hooks/use-mobile.test.ts b/src/web/src/hooks/use-mobile.test.ts
index 13a8ce91e..bb3eb1168 100644
--- a/src/web/src/hooks/use-mobile.test.ts
+++ b/src/web/src/hooks/use-mobile.test.ts
@@ -1,7 +1,18 @@
+import { createElement } from "react"
+import { renderToStaticMarkup } from "react-dom/server"
import { describe, it, expect } from "vitest"
-import { resolveBreakpoint } from "./use-mobile"
+import { resolveBreakpoint, useBreakpoint } from "./use-mobile"
describe("resolveBreakpoint", () => {
+ it("starts unknown before client media-query hydration", () => {
+ function Probe() {
+ return createElement("div", { "data-breakpoint": useBreakpoint() })
+ }
+ expect(renderToStaticMarkup(createElement(Probe))).toContain(
+ 'data-breakpoint="unknown"',
+ )
+ })
+
it("returns mobile when the mobile query matches (<640)", () => {
expect(resolveBreakpoint({ mobile: true })).toBe("mobile")
})
diff --git a/src/web/src/hooks/use-mobile.ts b/src/web/src/hooks/use-mobile.ts
index a952e5837..98975f40e 100644
--- a/src/web/src/hooks/use-mobile.ts
+++ b/src/web/src/hooks/use-mobile.ts
@@ -5,7 +5,7 @@ import { useEffect, useState } from "react"
// Aligned to Tailwind's `sm` breakpoint. See DESIGN.md → Breakpoints.
const MOBILE_BREAKPOINT = 640
-export type Breakpoint = "desktop" | "mobile"
+export type Breakpoint = "unknown" | "desktop" | "mobile"
// Pure mapping from matchMedia results to a Breakpoint — exported for testing.
export function resolveBreakpoint(matches: { mobile: boolean }): Breakpoint {
@@ -13,7 +13,7 @@ export function resolveBreakpoint(matches: { mobile: boolean }): Breakpoint {
}
export function useBreakpoint(): Breakpoint {
- const [bp, setBp] = useState<Breakpoint>("desktop")
+ const [bp, setBp] = useState<Breakpoint>("unknown")
useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
const compute = () => setBp(resolveBreakpoint({ mobile: mql.matches }))
diff --git a/src/web/src/lib/community/community-route.test.ts b/src/web/src/lib/community/community-route.test.ts
new file mode 100644
index 000000000..d519f2737
--- /dev/null
+++ b/src/web/src/lib/community/community-route.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it } from "vitest"
+import {
+ channelHref,
+ childChannelHref,
+ removeCommunityParam,
+ resolveCommunityRoute,
+ serverModalMarkerCleanupHref,
+ serverRootHref,
+} from "./community-route"
+
+describe("community route", () => {
+ it.each([
+ ["/c/me", "list", null],
+ ["/c/me/friends", "detail", "/c/me"],
+ ["/c/me/machines", "detail", "/c/me"],
+ ["/c/me/dm_1", "detail", "/c/me"],
+ ["/c/channels/server_1", "list", null],
+ ["/c/channels/server_1/channel_1", "detail", "/c/channels/server_1"],
+ ["/c/channels/server_1/parent_1/child_1", "detail", "/c/channels/server_1/parent_1"],
+ ])("classifies %s", (pathname, surface, parentPath) => {
+ expect(resolveCommunityRoute(pathname)).toEqual({ surface, parentPath })
+ })
+
+ it("builds root, top-level, and canonical child hrefs", () => {
+ expect(serverRootHref("server_1")).toBe("/c/channels/server_1")
+ expect(channelHref("server_1", "channel_1")).toBe("/c/channels/server_1/channel_1")
+ expect(childChannelHref("server_1", "parent_1", "child_1")).toBe(
+ "/c/channels/server_1/parent_1/child_1",
+ )
+ })
+
+ it("removes one query key while preserving the rest and the hash", () => {
+ expect(removeCommunityParam("/c/me/dm_1?seq=4&keep=1#x", "seq")).toBe(
+ "/c/me/dm_1?keep=1#x",
+ )
+ })
+
+ it.each(["settings", "invite"])(
+ "consumes a mobile server-root %s marker without waiting for a channel redirect",
+ (marker) => {
+ expect(
+ serverModalMarkerCleanupHref(
+ `/c/channels/server_1?${marker}=1&keep=1`,
+ {
+ breakpoint: "mobile",
+ hasChannel: false,
+ hasServerChannels: true,
+ },
+ ),
+ ).toBe("/c/channels/server_1?keep=1")
+ },
+ )
+
+ it("defers desktop server-root marker cleanup until the channel redirect wins", () => {
+ expect(
+ serverModalMarkerCleanupHref("/c/channels/server_1?settings=1", {
+ breakpoint: "desktop",
+ hasChannel: false,
+ hasServerChannels: true,
+ }),
+ ).toBeNull()
+ })
+
+ it("cleans desktop modal markers after reaching a channel route", () => {
+ expect(
+ serverModalMarkerCleanupHref(
+ "/c/channels/server_1/channel_1?settings=1&invite=1",
+ {
+ breakpoint: "desktop",
+ hasChannel: true,
+ hasServerChannels: true,
+ },
+ ),
+ ).toBe("/c/channels/server_1/channel_1")
+ })
+})
diff --git a/src/web/src/lib/community/community-route.ts b/src/web/src/lib/community/community-route.ts
new file mode 100644
index 000000000..9669e96c4
--- /dev/null
+++ b/src/web/src/lib/community/community-route.ts
@@ -0,0 +1,100 @@
+export type CommunitySurface = "list" | "detail"
+
+export type CommunityRoute = {
+ surface: CommunitySurface
+ parentPath: string | null
+}
+
+export function resolveCommunityRoute(pathname: string): CommunityRoute {
+ const segments = pathname.split("/").filter(Boolean)
+ if (segments[0] !== "c") return { surface: "detail", parentPath: null }
+
+ if (segments[1] === "me") {
+ return segments.length === 2
+ ? { surface: "list", parentPath: null }
+ : { surface: "detail", parentPath: "/c/me" }
+ }
+
+ if (segments[1] === "channels" && segments[2]) {
+ const serverRoot = `/c/channels/${segments[2]}`
+ if (segments.length === 3) return { surface: "list", parentPath: null }
+ if (segments.length >= 5) {
+ return {
+ surface: "detail",
+ parentPath: `${serverRoot}/${segments[3]}`,
+ }
+ }
+ return { surface: "detail", parentPath: serverRoot }
+ }
+
+ return { surface: "detail", parentPath: null }
+}
+
+export function serverRootHref(serverId: string): string {
+ return `/c/channels/${serverId}`
+}
+
+export function channelHref(serverId: string, channelId: string): string {
+ return `${serverRootHref(serverId)}/${channelId}`
+}
+
+export function childChannelHref(
+ serverId: string,
+ parentChannelId: string,
+ childChannelId: string,
+): string {
+ return `${channelHref(serverId, parentChannelId)}/${childChannelId}`
+}
+
+export function removeCommunityParam(href: string, key: string): string {
+ return updateHrefSearchParams(href, (searchParams) => {
+ searchParams.delete(key)
+ })
+}
+
+export function serverModalMarkerCleanupHref(
+ href: string,
+ {
+ breakpoint,
+ hasChannel,
+ hasServerChannels,
+ }: {
+ breakpoint: "unknown" | "desktop" | "mobile"
+ hasChannel: boolean
+ hasServerChannels: boolean
+ },
+): string | null {
+ const hashIndex = href.indexOf("#")
+ const hrefWithoutHash = hashIndex === -1 ? href : href.slice(0, hashIndex)
+ const queryIndex = hrefWithoutHash.indexOf("?")
+ const searchParams = new URLSearchParams(
+ queryIndex === -1 ? "" : hrefWithoutHash.slice(queryIndex + 1),
+ )
+ const hasModalMarker =
+ searchParams.get("settings") === "1" || searchParams.get("invite") === "1"
+ if (!hasModalMarker) return null
+
+ if (breakpoint === "desktop" && !hasChannel && hasServerChannels) return null
+
+ return removeCommunityParam(removeCommunityParam(href, "settings"), "invite")
+}
+
+function updateHrefSearchParams(
+ href: string,
+ update: (searchParams: URLSearchParams) => void,
+): string {
+ const hashIndex = href.indexOf("#")
+ const hash = hashIndex === -1 ? "" : href.slice(hashIndex)
+ const hrefWithoutHash = hashIndex === -1 ? href : href.slice(0, hashIndex)
+ const queryIndex = hrefWithoutHash.indexOf("?")
+ const pathname = queryIndex === -1
+ ? hrefWithoutHash
+ : hrefWithoutHash.slice(0, queryIndex)
+ const query = queryIndex === -1 ? "" : hrefWithoutHash.slice(queryIndex + 1)
+ const searchParams = new URLSearchParams(query)
+
+ update(searchParams)
+
+ const nextQuery = searchParams.toString()
+ return `${pathname}${nextQuery ? `?${nextQuery}` : ""}${hash}`
+}
diff --git a/src/web/src/lib/community/last-channel.test.ts b/src/web/src/lib/community/last-channel.test.ts
index 7c634e269..bb9674101 100644
--- a/src/web/src/lib/community/last-channel.test.ts
+++ b/src/web/src/lib/community/last-channel.test.ts
@@ -127,6 +127,12 @@ describe("pickServerLandingChannel", () => {
})
describe("pickServerLandingHref", () => {
+ it("restores a canonical parent/child leaf", () => {
+ expect(pickServerLandingHref("srv_1", ["ch_1"], "forum_1/post_1")).toBe(
+ "/c/channels/srv_1/forum_1/post_1",
+ )
+ })
+
it("lands directly on a remembered child thread without top-level validation", () => {
expect(pickServerLandingHref("srv_1", ["ch_1"], "post_1")).toBe(
"/c/channels/srv_1/post_1",
diff --git a/src/web/src/lib/community/last-channel.ts b/src/web/src/lib/community/last-channel.ts
index acbbe4c1b..2986bfe3f 100644
--- a/src/web/src/lib/community/last-channel.ts
+++ b/src/web/src/lib/community/last-channel.ts
@@ -3,12 +3,12 @@
// were; this remembers, per browser, the last channel/post opened in each
// server so the server-landing page can restore to it.
//
-// Deliberately narrow: it stores ONLY which channel (a serverId -> channelId
-// map), never scroll position or read-to-seq — those are server read-state, a
-// separate concern this must not touch. localStorage-only (no backend, no
-// daemon, no cross-device sync). Pure guarded wrappers (SSR + privacy-mode safe)
-// mirroring `composer-draft.ts` — any failure degrades to "no memory", i.e.
-// exactly today's default-channel behavior, never a throw.
+// Deliberately narrow: it stores ONLY the route leaf (a serverId -> channelId or
+// parentId/channelId map), never scroll position or read-to-seq — those are
+// server read-state, a separate concern this must not touch. localStorage-only
+// (no backend, no daemon, no cross-device sync). Pure guarded wrappers (SSR +
+// privacy-mode safe) mirroring `composer-draft.ts` — any failure degrades to
+// "no memory", i.e. exactly today's default-channel behavior, never a throw.
import {
clearNavigationMemory,
diff --git a/src/web/src/lib/community/last-me-location.test.ts b/src/web/src/lib/community/last-me-location.test.ts
index 49422fece..9b1ad2502 100644
--- a/src/web/src/lib/community/last-me-location.test.ts
+++ b/src/web/src/lib/community/last-me-location.test.ts
@@ -32,7 +32,7 @@ describe("last-me-location", () => {
})
it.each([
- "/c/me",
+ "/c/me/friends",
"/c/me/machines",
"/c/me/bots",
"/c/me/dm_123",
@@ -47,6 +47,7 @@ describe("last-me-location", () => {
"/c/me/machines?reconnect=1",
"/c/me/bots#owned",
"/c/me/",
+ "/c/me",
])("rejects %s", (pathname) => {
expect(isRememberableMeLocation(pathname)).toBe(false)
})
@@ -58,9 +59,9 @@ describe("last-me-location", () => {
})
it("falls back to friends for missing or dirty memory", () => {
- expect(pickMeLandingLocation(null)).toBe("/c/me")
- expect(pickMeLandingLocation("dm_1/messages")).toBe("/c/me")
- expect(pickMeLandingLocation("friends")).toBe("/c/me")
+ expect(pickMeLandingLocation(null)).toBe("/c/me/friends")
+ expect(pickMeLandingLocation("dm_1/messages")).toBe("/c/me/friends")
+ expect(pickMeLandingLocation("friends")).toBe("/c/me/friends")
expect(pickMeLandingLocation("dm_1")).toBe("/c/me/dm_1")
})
})
diff --git a/src/web/src/lib/community/last-me-location.ts b/src/web/src/lib/community/last-me-location.ts
index 17b24661d..e624ee972 100644
--- a/src/web/src/lib/community/last-me-location.ts
+++ b/src/web/src/lib/community/last-me-location.ts
@@ -20,7 +20,6 @@ export function lastMeLocationKey(): string {
}
export function meLeafFromPathname(pathname: string): string | null {
- if (pathname === ME_ROOT) return FRIENDS_LEAF
const prefix = `${ME_ROOT}/`
if (!pathname.startsWith(prefix)) return null
const leaf = pathname.slice(prefix.length)
@@ -46,8 +45,10 @@ export function clearLastMeLocation(): void {
}
export function pickMeLandingLocation(lastLeaf: string | null): string {
- if (lastLeaf === null || !lastLeaf || !isSafeMeLeaf(lastLeaf)) return ME_ROOT
- return lastLeaf === FRIENDS_LEAF ? ME_ROOT : `${ME_ROOT}/${lastLeaf}`
+ if (lastLeaf === null || !lastLeaf || !isSafeMeLeaf(lastLeaf)) {
+ return `${ME_ROOT}/${FRIENDS_LEAF}`
+ }
+ return `${ME_ROOT}/${lastLeaf}`
}
export function resolveMeLocationStatus({
diff --git a/src/web/src/lib/community/models/inbox.ts b/src/web/src/lib/community/models/inbox.ts
index a478d7c93..d7e76bf4d 100644
--- a/src/web/src/lib/community/models/inbox.ts
+++ b/src/web/src/lib/community/models/inbox.ts
@@ -34,6 +34,9 @@ export type Marked = {
// For a server message this is the channel id; for a DM it's the DM channel
// id, which is also the frontend `/c/me/<id>` route param.
channelId: string
+ // Child-channel marks include their canonical parent route segment. Optional
+ // for backward compatibility with older cached marked-feed payloads.
+ parentChannelId?: string | null
m: Msg
}
diff --git a/src/web/src/stores/community/index.ts b/src/web/src/stores/community/index.ts
index 07b7cb5ce..3624719b0 100644
--- a/src/web/src/stores/community/index.ts
+++ b/src/web/src/stores/community/index.ts
@@ -78,6 +78,8 @@ type CommunityUiHandlers = {
previewAttachment?: (attachment: FileAttachment) => void
openProfile?: (name: string, e: React.MouseEvent, discriminator?: string, userId?: string) => void
goBackMobile?: () => void
+ navigatePath?: (href: string) => void
+ replacePath?: (href: string) => void
// Jump to message `seq` within the CURRENT channel/DM — the page registers
// this (message already loaded → scroll to it; otherwise open the context
// sheet, which resolves seq→id server-side). A same-channel message ref pill
@@ -277,6 +279,8 @@ const stableUiHandlers: CommunityUiHandlers = {
openProfile: (name, e, discriminator, userId) =>
useCommunityStore.getState().uiHandlers.openProfile?.(name, e, discriminator, userId),
goBackMobile: () => useCommunityStore.getState().uiHandlers.goBackMobile?.(),
+ navigatePath: (href) => useCommunityStore.getState().uiHandlers.navigatePath?.(href),
+ replacePath: (href) => useCommunityStore.getState().uiHandlers.replacePath?.(href),
jumpToSeq: (seq) => useCommunityStore.getState().uiHandlers.jumpToSeq?.(seq),
cancelPendingNavigation: () => useCommunityStore.getState().uiHandlers.cancelPendingNavigation?.(),
navigate: (serverId, channelId) => useCommunityStore.getState().uiHandlers.navigate?.(serverId, channelId),
diff --git a/src/web/src/test/e2e-ui/08-mobile.spec.ts b/src/web/src/test/e2e-ui/08-mobile.spec.ts
index a06793a24..cdd2fb003 100644
--- a/src/web/src/test/e2e-ui/08-mobile.spec.ts
+++ b/src/web/src/test/e2e-ui/08-mobile.spec.ts
@@ -1,38 +1,47 @@
import { test, expect, userId } from "./_fixtures/community-fixture"
import { tid } from "./_fixtures/testids"
-import { seedServer, seedChannel, seedDm, seedMessage } from "./_fixtures/seed"
-
-// Journey 8 — mobile layout. At <640px the community shell switches zones
-// (nav ↔ messages). Opening a channel enters the messages zone; the header
-// back button returns to the nav zone.
+import {
+ seedServer,
+ seedChannel,
+ seedDm,
+ seedMark,
+ seedMessage,
+ seedThread,
+} from "./_fixtures/seed"
+
+// Journey 8 — adaptive list/detail routing. At <640px semantic roots render
+// lists and leaf paths render detail. Header Back replaces with the parent.
test.use({ viewport: { width: 390, height: 844 } })
test.describe.serial("mobile layout", () => {
let serverId: string
let channelId: string
+ let childChannelId: string
let dmId: string
test.beforeAll(async () => {
serverId = await seedServer("alice", `Mobile ${Date.now()}`)
channelId = await seedChannel("alice", serverId, "mobile-chan")
- await seedMessage("alice", channelId, "mobile seq command target")
+ const parentMessageId = await seedMessage("alice", channelId, "mobile seq command target")
+ childChannelId = await seedThread("alice", parentMessageId, "mobile-child")
+ const childMessageId = await seedMessage("alice", childChannelId, "mobile child seq target")
+ await seedMark("alice", childChannelId, childMessageId)
dmId = await seedDm("alice", userId("bob"))
})
- test("a direct channel opens content and Header Back replaces it with nav", async ({ asUser }) => {
+ test("a direct channel opens detail and Header Back replaces it with the server root", async ({ asUser }) => {
const { page } = await asUser("alice")
await page.goto(`/c/channels/${serverId}/${channelId}`)
await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })
- // Composer (messages zone) is present.
await expect(page.getByTestId(tid.composerInput)).toBeVisible()
- // Mobile header exposes a Back control.
const back = page.getByRole("button", { name: "Back" })
await expect(back).toBeVisible()
const historyLength = await page.evaluate(() => history.length)
await back.click()
- await expect.poll(() => page.url()).toContain("pane=nav")
+ await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${serverId}`)
+ expect(new URL(page.url()).searchParams.has("pane")).toBe(false)
await expect(page.getByTestId(tid.serverIcon(serverId))).toBeVisible()
await expect(page.getByTestId(tid.composerInput)).toBeHidden()
expect(await page.evaluate(() => history.length)).toBe(historyLength)
@@ -42,84 +51,144 @@ test.describe.serial("mobile layout", () => {
await expect(page.getByTestId(tid.composerInput)).toBeHidden()
})
- test("browser Back and Forward restore nav and content from the URL", async ({ asUser }) => {
+ test("browser Back and Forward restore list and detail from semantic paths", async ({ asUser }) => {
const { page } = await asUser("alice")
- await page.goto(`/c/channels/${serverId}/${channelId}?pane=nav`)
+ await page.goto(`/c/channels/${serverId}`)
const channelRow = page.getByTestId(tid.channelRow(channelId))
await expect(channelRow).toBeVisible()
await channelRow.click()
- await expect.poll(() => new URL(page.url()).searchParams.has("pane")).toBe(false)
+ await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${serverId}/${channelId}`)
await expect(page.getByTestId(tid.composerInput)).toBeVisible()
await page.goBack()
- await expect.poll(() => new URL(page.url()).searchParams.get("pane")).toBe("nav")
+ await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${serverId}`)
await expect(channelRow).toBeVisible()
await expect(page.getByTestId(tid.composerInput)).toBeHidden()
await page.goForward()
- await expect.poll(() => new URL(page.url()).searchParams.has("pane")).toBe(false)
+ await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${serverId}/${channelId}`)
await expect(page.getByTestId(tid.composerInput)).toBeVisible()
})
test("Friends, Machines, and Bots deep links all default to content", async ({ asUser }) => {
const { page } = await asUser("alice")
- for (const pathname of ["/c/me", "/c/me/machines", "/c/me/bots"]) {
+ 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 back.click()
- await expect.poll(() => new URL(page.url()).pathname).toBe(pathname)
- await expect.poll(() => new URL(page.url()).searchParams.get("pane")).toBe("nav")
+ await expect.poll(() => new URL(page.url()).pathname).toBe("/c/me")
+ expect(new URL(page.url()).searchParams.has("pane")).toBe(false)
await expect(page.getByTestId(tid.homeButton)).toBeVisible()
}
})
- test("the persistent nav layout consumes seq without dropping other URL state", async ({ asUser }) => {
+ test("detail consumes seq without dropping other URL state", async ({ asUser }) => {
const { page } = await asUser("alice")
- await page.goto(`/c/channels/${serverId}/${channelId}?seq=1&keep=nav-seq&pane=nav`)
+ await page.goto(`/c/channels/${serverId}/${channelId}?seq=1&keep=detail-seq`)
await expect.poll(() => new URL(page.url()).searchParams.has("seq")).toBe(false)
- expect(new URL(page.url()).searchParams.get("keep")).toBe("nav-seq")
- expect(new URL(page.url()).searchParams.get("pane")).toBe("nav")
- await expect(page.getByTestId(tid.channelRow(channelId))).toBeVisible()
+ expect(new URL(page.url()).searchParams.get("keep")).toBe("detail-seq")
+ expect(new URL(page.url()).searchParams.has("pane")).toBe(false)
+ await expect(page.getByTestId(tid.composerInput)).toBeVisible()
+ })
+
+ test("canonical child detail consumes seq without dropping route or other URL state", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+ await page.goto(
+ `/c/channels/${serverId}/${channelId}/${childChannelId}?seq=1&keep=child-seq`,
+ )
+
+ await expect.poll(() => new URL(page.url()).pathname).toBe(
+ `/c/channels/${serverId}/${channelId}/${childChannelId}`,
+ )
+ await expect.poll(() => new URL(page.url()).searchParams.has("seq")).toBe(false)
+ expect(new URL(page.url()).searchParams.get("keep")).toBe("child-seq")
+ await expect(page.getByRole("dialog").getByText("mobile child seq target")).toBeVisible()
})
- test("a direct DM opens content and Header Back preserves the resource", async ({ asUser }) => {
+ test("Marked opens a child message on its canonical route without losing context", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+ await page.goto("/c/me")
+ await page.getByRole("button", { name: "Inbox" }).click()
+ await page.getByRole("tab", { name: "Marked" }).click()
+ await page.getByText("mobile child seq target", { exact: true }).click()
+
+ await expect.poll(() => new URL(page.url()).pathname).toBe(
+ `/c/channels/${serverId}/${channelId}/${childChannelId}`,
+ )
+ await expect.poll(() => new URL(page.url()).searchParams.has("seq")).toBe(false)
+ await expect(page.getByRole("dialog").getByText("mobile child seq target")).toBeVisible()
+ })
+
+ test("server-root modal markers are one-shot on mobile", async ({ asUser }) => {
+ for (const marker of ["settings", "invite"]) {
+ const { page } = await asUser("alice")
+ await page.goto(`/c/channels/${serverId}?${marker}=1&keep=${marker}`)
+
+ if (marker === "settings") {
+ await expect(page.getByTestId(tid.settingsShell)).toBeVisible()
+ await page.getByTestId(tid.settingsClose).click()
+ await expect(page.getByTestId(tid.settingsShell)).toBeHidden()
+ } else {
+ const inviteDialog = page.getByRole("dialog")
+ await expect(inviteDialog).toBeVisible()
+ await expect(inviteDialog.getByText(/^Invite friends to Mobile-/)).toBeVisible()
+ await inviteDialog.getByRole("button", { name: "Close" }).click()
+ await expect(inviteDialog).toBeHidden()
+ }
+
+ await expect.poll(() => new URL(page.url()).pathname).toBe(
+ `/c/channels/${serverId}`,
+ )
+ await expect.poll(() => new URL(page.url()).searchParams.has(marker)).toBe(false)
+ expect(new URL(page.url()).searchParams.get("keep")).toBe(marker)
+
+ await page.reload()
+ expect(new URL(page.url()).searchParams.has(marker)).toBe(false)
+ await expect(page.getByTestId(tid.serverIcon(serverId))).toBeVisible()
+ if (marker === "settings") {
+ await expect(page.getByTestId(tid.settingsShell)).toBeHidden()
+ } else {
+ await expect(page.getByRole("dialog")).toBeHidden()
+ }
+ await page.close()
+ }
+ })
+
+ test("a direct DM opens detail and Header Back replaces it with Me root", async ({ asUser }) => {
const { page } = await asUser("alice")
await page.goto(`/c/me/${dmId}`)
await expect(page.getByTestId(tid.composerInput)).toBeVisible()
await page.getByRole("button", { name: "Back" }).click()
- await expect.poll(() => new URL(page.url()).searchParams.get("pane")).toBe("nav")
- expect(new URL(page.url()).pathname).toBe(`/c/me/${dmId}`)
+ await expect.poll(() => new URL(page.url()).pathname).toBe("/c/me")
+ expect(new URL(page.url()).searchParams.has("pane")).toBe(false)
await expect(page.getByTestId(tid.dmRow(dmId))).toBeVisible()
await expect(page.getByTestId(tid.composerInput)).toBeHidden()
})
- test("cross-layout Back and Forward restore each URL-owned pane", async ({ asUser }) => {
+ test("cross-layout Back and Forward restore each route-owned surface", async ({ asUser }) => {
const { page } = await asUser("alice")
- await page.goto(`/c/channels/${serverId}/${channelId}?pane=nav`)
+ await page.goto(`/c/channels/${serverId}`)
await expect(page.getByTestId(tid.homeButton)).toBeVisible()
await page.getByTestId(tid.homeButton).click()
- await expect.poll(() => new URL(page.url()).pathname.startsWith("/c/me")).toBe(true)
- await expect.poll(() => new URL(page.url()).searchParams.get("pane")).toBe("nav")
+ await expect.poll(() => new URL(page.url()).pathname).toBe("/c/me")
await page.getByTestId(tid.dmRow(dmId)).click()
await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/me/${dmId}`)
await expect(page.getByTestId(tid.composerInput)).toBeVisible()
await page.goBack()
- await expect.poll(() => new URL(page.url()).pathname.startsWith("/c/me")).toBe(true)
- await expect.poll(() => new URL(page.url()).searchParams.get("pane")).toBe("nav")
+ await expect.poll(() => new URL(page.url()).pathname).toBe("/c/me")
await expect(page.getByTestId(tid.dmRow(dmId))).toBeVisible()
await page.goBack()
- await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${serverId}/${channelId}`)
- await expect.poll(() => new URL(page.url()).searchParams.get("pane")).toBe("nav")
+ await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${serverId}`)
await expect(page.getByTestId(tid.channelRow(channelId))).toBeVisible()
await page.goForward()
@@ -127,4 +196,22 @@ test.describe.serial("mobile layout", () => {
await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/me/${dmId}`)
await expect(page.getByTestId(tid.composerInput)).toBeVisible()
})
+
+ test("resizing resolves desktop roots to detail without inventing layout URL state", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+ await page.goto(`/c/channels/${serverId}/${channelId}`)
+ await expect(page.getByTestId(tid.composerInput)).toBeVisible()
+ await page.getByRole("button", { name: "Back" }).click()
+ await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${serverId}`)
+ await expect(page.getByTestId(tid.channelRow(channelId))).toBeVisible()
+
+ await page.setViewportSize({ width: 900, height: 844 })
+ await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${serverId}/${channelId}`)
+ await expect(page.getByTestId(tid.channelRow(channelId))).toBeVisible()
+ await expect(page.getByTestId(tid.composerInput)).toBeVisible()
+
+ await page.setViewportSize({ width: 390, height: 844 })
+ await expect(page.getByTestId(tid.composerInput)).toBeVisible()
+ expect(new URL(page.url()).searchParams.has("pane")).toBe(false)
+ })
})
diff --git a/src/web/src/test/e2e-ui/_fixtures/seed.ts b/src/web/src/test/e2e-ui/_fixtures/seed.ts
index ec3287af1..a7eb58821 100644
--- a/src/web/src/test/e2e-ui/_fixtures/seed.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/seed.ts
@@ -159,6 +159,22 @@ export async function seedMessage(author: UserKey, channelId: string, content: s
return data.message.id
}
+export async function seedMark(author: UserKey, channelId: string, messageId: string): Promise<void> {
+ const response = await retrySeedRequest(() => fetch(
+ `${WEB_URL}/api/community/messages/${messageId}/marks`,
+ {
+ method: "PUT",
+ headers: {
+ Cookie: sessionCookie(author),
+ "Content-Type": "application/json",
+ Origin: WEB_URL,
+ },
+ body: JSON.stringify({ channelId }),
+ },
+ ))
+ if (!response.ok) throw new Error(`seedMark failed (${response.status})`)
+}
+
// Create a forum post (a child channel of a `type:"forum"` channel) via API.
// Returns the post's own channel id. The creator is enrolled as a participant
// server-side. Use when a spec needs an existing post before driving the UI.