Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): keep community shell mounted across routes (#870)

Generbb7d7896ad8f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 05af75ca3..8669daeb8 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -405,6 +405,8 @@ jobs:
if: env.RUN_COVERAGE == 'true'
uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7
with:
+ use_pypi: true
+ version: v11.3.1
token: ${{ secrets.CODECOV_TOKEN }}
files: ./coverage/coverage-final.json
fail_ci_if_error: true
diff --git a/src/web/src/app/c/@sidebar/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/@sidebar/channels/[serverId]/[channelId]/page.tsx
new file mode 100644
index 000000000..ec02727e4
--- /dev/null
+++ b/src/web/src/app/c/@sidebar/channels/[serverId]/[channelId]/page.tsx
@@ -0,0 +1,3 @@
+export default function SidebarLeaf() {
+ return null
+}
diff --git a/src/web/src/app/c/@sidebar/channels/[serverId]/layout.tsx b/src/web/src/app/c/@sidebar/channels/[serverId]/layout.tsx
new file mode 100644
index 000000000..8f16389e7
--- /dev/null
+++ b/src/web/src/app/c/@sidebar/channels/[serverId]/layout.tsx
@@ -0,0 +1,10 @@
+import type { ReactNode } from "react"
+import { ServerSidebarSlot } from "@/components/community/shell/server-sidebar-slot"
+
+export default async function ServerSidebarLayout({ children, params }: {
+ children: ReactNode
+ params: Promise<{ serverId: string }>
+}) {
+ const { serverId } = await params
+ return <><ServerSidebarSlot serverId={serverId} />{children}</>
+}
diff --git a/src/web/src/app/c/@sidebar/channels/[serverId]/page.tsx b/src/web/src/app/c/@sidebar/channels/[serverId]/page.tsx
new file mode 100644
index 000000000..ad07a7472
--- /dev/null
+++ b/src/web/src/app/c/@sidebar/channels/[serverId]/page.tsx
@@ -0,0 +1,3 @@
+export default function SidebarRoot() {
+ return null
+}
diff --git a/src/web/src/app/c/@sidebar/channels/[serverId]/settings/page.tsx b/src/web/src/app/c/@sidebar/channels/[serverId]/settings/page.tsx
new file mode 100644
index 000000000..ec02727e4
--- /dev/null
+++ b/src/web/src/app/c/@sidebar/channels/[serverId]/settings/page.tsx
@@ -0,0 +1,3 @@
+export default function SidebarLeaf() {
+ return null
+}
diff --git a/src/web/src/app/c/@sidebar/default.tsx b/src/web/src/app/c/@sidebar/default.tsx
new file mode 100644
index 000000000..ec02727e4
--- /dev/null
+++ b/src/web/src/app/c/@sidebar/default.tsx
@@ -0,0 +1,3 @@
+export default function SidebarLeaf() {
+ return null
+}
diff --git a/src/web/src/app/c/@sidebar/invite/[token]/page.tsx b/src/web/src/app/c/@sidebar/invite/[token]/page.tsx
new file mode 100644
index 000000000..ec02727e4
--- /dev/null
+++ b/src/web/src/app/c/@sidebar/invite/[token]/page.tsx
@@ -0,0 +1,3 @@
+export default function SidebarLeaf() {
+ return null
+}
diff --git a/src/web/src/app/c/@sidebar/me/[dmId]/page.tsx b/src/web/src/app/c/@sidebar/me/[dmId]/page.tsx
new file mode 100644
index 000000000..ec02727e4
--- /dev/null
+++ b/src/web/src/app/c/@sidebar/me/[dmId]/page.tsx
@@ -0,0 +1,3 @@
+export default function SidebarLeaf() {
+ return null
+}
diff --git a/src/web/src/app/c/@sidebar/me/bots/page.tsx b/src/web/src/app/c/@sidebar/me/bots/page.tsx
new file mode 100644
index 000000000..ec02727e4
--- /dev/null
+++ b/src/web/src/app/c/@sidebar/me/bots/page.tsx
@@ -0,0 +1,3 @@
+export default function SidebarLeaf() {
+ return null
+}
diff --git a/src/web/src/app/c/@sidebar/me/friends/page.tsx b/src/web/src/app/c/@sidebar/me/friends/page.tsx
new file mode 100644
index 000000000..ec02727e4
--- /dev/null
+++ b/src/web/src/app/c/@sidebar/me/friends/page.tsx
@@ -0,0 +1,3 @@
+export default function SidebarLeaf() {
+ return null
+}
diff --git a/src/web/src/app/c/@sidebar/me/layout.tsx b/src/web/src/app/c/@sidebar/me/layout.tsx
new file mode 100644
index 000000000..a2f4264a1
--- /dev/null
+++ b/src/web/src/app/c/@sidebar/me/layout.tsx
@@ -0,0 +1,6 @@
+import type { ReactNode } from "react"
+import { DmSidebarSlot } from "@/components/community/shell/dm-sidebar-slot"
+
+export default function MeSidebarLayout({ children }: { children: ReactNode }) {
+ return <><DmSidebarSlot />{children}</>
+}
diff --git a/src/web/src/app/c/@sidebar/me/machines/page.tsx b/src/web/src/app/c/@sidebar/me/machines/page.tsx
new file mode 100644
index 000000000..ec02727e4
--- /dev/null
+++ b/src/web/src/app/c/@sidebar/me/machines/page.tsx
@@ -0,0 +1,3 @@
+export default function SidebarLeaf() {
+ return null
+}
diff --git a/src/web/src/app/c/@sidebar/me/page.tsx b/src/web/src/app/c/@sidebar/me/page.tsx
new file mode 100644
index 000000000..ad07a7472
--- /dev/null
+++ b/src/web/src/app/c/@sidebar/me/page.tsx
@@ -0,0 +1,3 @@
+export default function SidebarRoot() {
+ return null
+}
diff --git a/src/web/src/app/c/@sidebar/onboarding-preview/page.tsx b/src/web/src/app/c/@sidebar/onboarding-preview/page.tsx
new file mode 100644
index 000000000..ec02727e4
--- /dev/null
+++ b/src/web/src/app/c/@sidebar/onboarding-preview/page.tsx
@@ -0,0 +1,3 @@
+export default function SidebarLeaf() {
+ return null
+}
diff --git a/src/web/src/app/c/@sidebar/page.tsx b/src/web/src/app/c/@sidebar/page.tsx
new file mode 100644
index 000000000..ec02727e4
--- /dev/null
+++ b/src/web/src/app/c/@sidebar/page.tsx
@@ -0,0 +1,3 @@
+export default function SidebarLeaf() {
+ return null
+}
diff --git a/src/web/src/app/c/channels/[serverId]/page.dom.test.ts b/src/web/src/app/c/channels/[serverId]/page.dom.test.ts
index 129d7dde8..ea6b0b4b5 100644
--- a/src/web/src/app/c/channels/[serverId]/page.dom.test.ts
+++ b/src/web/src/app/c/channels/[serverId]/page.dom.test.ts
@@ -2,6 +2,7 @@ import { createElement } from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { render, screen } from "@/test/react-dom-harness"
import ServerDefaultPage from "./page"
+import { CommunityServerRouteContext } from "@/components/community/shell/community-route-context"
const mocks = vi.hoisted(() => ({
breakpoint: { current: "mobile" as "mobile" | "desktop" | "unknown" },
@@ -18,7 +19,7 @@ vi.mock("@/components/brand/alook-loading/AlookLoading", () => ({
}))
vi.mock("next/navigation", () => ({
- useParams: () => ({ serverId: "server_1" }),
+ useParams: () => ({ serverId: "wrong_sidebar_server" }),
useRouter: () => ({ replace: mocks.replace }),
useSearchParams: () => new URLSearchParams(mocks.search.current),
}))
@@ -51,7 +52,7 @@ beforeEach(() => {
describe("ServerDefaultPage checkpoint route contract", () => {
it.each(["mobile", "unknown"] as const)("keeps the %s server root on the list route without rendering detail", async (breakpoint) => {
mocks.breakpoint.current = breakpoint
- const rendered = render(createElement(ServerDefaultPage))
+ const rendered = render(createElement(CommunityServerRouteContext, { value: { serverId: "server_1", serverParam: "server_1" } }, createElement(ServerDefaultPage)))
expect(mocks.replace).not.toHaveBeenCalled()
expect(rendered.container).toBeEmptyDOMElement()
@@ -60,7 +61,7 @@ describe("ServerDefaultPage checkpoint route contract", () => {
it("keeps cold or incomplete detail on the root, then redirects only when canonical detail is known", async () => {
mocks.breakpoint.current = "desktop"
mocks.server.current = null
- const rendered = render(createElement(ServerDefaultPage))
+ const rendered = render(createElement(CommunityServerRouteContext, { value: { serverId: "server_1", serverParam: "server_1" } }, createElement(ServerDefaultPage)))
expect(mocks.replace).not.toHaveBeenCalled()
expect(screen.getByRole("main", { name: "Loading server" })).toHaveAttribute("aria-busy", "true")
@@ -69,7 +70,7 @@ describe("ServerDefaultPage checkpoint route contract", () => {
expect(rendered.container.querySelectorAll("header, button, form, textarea")).toHaveLength(0)
mocks.server.current = { categories: [{ channels: [{ id: "channel_ready" }] }] }
- rendered.rerender(createElement(ServerDefaultPage))
+ rendered.rerender(createElement(CommunityServerRouteContext, { value: { serverId: "server_1", serverParam: "server_1" } }, createElement(ServerDefaultPage)))
expect(mocks.replace).toHaveBeenCalledExactlyOnceWith("/c/channels/server_1/channel_ready")
expect(screen.getByRole("main", { name: "Loading server" })).toBeInTheDocument()
})
@@ -78,7 +79,7 @@ describe("ServerDefaultPage checkpoint route contract", () => {
mocks.breakpoint.current = "desktop"
mocks.lastChannel.current = "channel_2"
mocks.search.current = "settings=1"
- render(createElement(ServerDefaultPage))
+ render(createElement(CommunityServerRouteContext, { value: { serverId: "server_1", serverParam: "server_1" } }, createElement(ServerDefaultPage)))
expect(mocks.replace).toHaveBeenCalledWith(
"/c/channels/server_1/channel_2?settings=1",
@@ -89,19 +90,19 @@ describe("ServerDefaultPage checkpoint route contract", () => {
it("does not enqueue the same landing redirect again while restored detail reconciles", async () => {
mocks.breakpoint.current = "desktop"
mocks.lastChannel.current = "channel_2"
- const rendered = render(createElement(ServerDefaultPage))
+ const rendered = render(createElement(CommunityServerRouteContext, { value: { serverId: "server_1", serverParam: "server_1" } }, createElement(ServerDefaultPage)))
mocks.server.current = {
categories: [{ channels: [{ id: "channel_1" }, { id: "channel_2" }] }],
}
- rendered.rerender(createElement(ServerDefaultPage))
+ rendered.rerender(createElement(CommunityServerRouteContext, { value: { serverId: "server_1", serverParam: "server_1" } }, createElement(ServerDefaultPage)))
expect(mocks.replace).toHaveBeenCalledExactlyOnceWith(
"/c/channels/server_1/channel_2",
)
mocks.lastChannel.current = null
mocks.server.current = { categories: [{ channels: [{ id: "channel_3" }] }] }
- rendered.rerender(createElement(ServerDefaultPage))
+ rendered.rerender(createElement(CommunityServerRouteContext, { value: { serverId: "server_1", serverParam: "server_1" } }, createElement(ServerDefaultPage)))
expect(mocks.replace).toHaveBeenNthCalledWith(
2,
"/c/channels/server_1/channel_3",
@@ -111,7 +112,7 @@ describe("ServerDefaultPage checkpoint route contract", () => {
it("falls back to the first top-level channel on desktop", async () => {
mocks.breakpoint.current = "desktop"
- render(createElement(ServerDefaultPage))
+ render(createElement(CommunityServerRouteContext, { value: { serverId: "server_1", serverParam: "server_1" } }, createElement(ServerDefaultPage)))
expect(mocks.replace).toHaveBeenCalledWith(
"/c/channels/server_1/channel_1",
@@ -121,7 +122,7 @@ describe("ServerDefaultPage checkpoint route contract", () => {
it("keeps an empty desktop server on its root with an empty state", async () => {
mocks.breakpoint.current = "desktop"
mocks.server.current = { categories: [{ channels: [] }] }
- const rendered = render(createElement(ServerDefaultPage))
+ const rendered = render(createElement(CommunityServerRouteContext, { value: { serverId: "server_1", serverParam: "server_1" } }, createElement(ServerDefaultPage)))
expect(mocks.replace).not.toHaveBeenCalled()
expect(rendered.container.querySelector("[aria-label='Loading server']")).not.toBeInTheDocument()
diff --git a/src/web/src/app/c/channels/[serverId]/page.tsx b/src/web/src/app/c/channels/[serverId]/page.tsx
index 03b03d19c..f6d7b917f 100644
--- a/src/web/src/app/c/channels/[serverId]/page.tsx
+++ b/src/web/src/app/c/channels/[serverId]/page.tsx
@@ -1,17 +1,17 @@
"use client"
+import { useCommunityServerRoute } from "@/components/community/shell/community-route-context"
import { useEffect, useRef } from "react"
-import { useParams, useRouter, useSearchParams } from "next/navigation"
+import { useRouter, useSearchParams } from "next/navigation"
import { ServerLandingPendingFrame } from "@/components/community/shell/server-landing-pending-frame"
import { useServer } from "@/hooks/community/use-servers"
import { useBreakpoint } from "@/hooks/use-mobile"
import { getLastChannel, resolveCommunityLandingHref } from "@/lib/community/last-channel"
export default function ServerDefaultPage() {
- const params = useParams<{ serverId: string }>()
+ const { serverId } = useCommunityServerRoute()
const router = useRouter()
const searchParams = useSearchParams()
- const serverId = decodeURIComponent(params.serverId)
const { server: currentServer } = useServer(serverId)
const breakpoint = useBreakpoint()
const replacingHrefRef = useRef<string | null>(null)
diff --git a/src/web/src/app/c/channels/[serverId]/settings/page.tsx b/src/web/src/app/c/channels/[serverId]/settings/page.tsx
index f9d59a09a..d98e334e6 100644
--- a/src/web/src/app/c/channels/[serverId]/settings/page.tsx
+++ b/src/web/src/app/c/channels/[serverId]/settings/page.tsx
@@ -1,16 +1,17 @@
"use client"
+import { useCommunityServerRoute } from "@/components/community/shell/community-route-context"
import { useEffect } from "react"
-import { useParams, useRouter, useSearchParams } from "next/navigation"
+import { useRouter, useSearchParams } from "next/navigation"
export default function ServerSettingsRedirect() {
- const params = useParams<{ serverId: string }>()
+ const { serverId } = useCommunityServerRoute()
const router = useRouter()
const searchParams = useSearchParams()
useEffect(() => {
const nextSearchParams = new URLSearchParams(searchParams.toString())
nextSearchParams.set("settings", "1")
- router.replace(`/c/channels/${params.serverId}?${nextSearchParams.toString()}`)
- }, [params.serverId, router, searchParams])
+ router.replace(`/c/channels/${encodeURIComponent(serverId)}?${nextSearchParams.toString()}`)
+ }, [serverId, router, searchParams])
return null
}
diff --git a/src/web/src/app/c/channels/layout.route-memory.dom.test.ts b/src/web/src/app/c/channels/layout.route-memory.dom.test.ts
index 518e12bc7..d99bb6ef1 100644
--- a/src/web/src/app/c/channels/layout.route-memory.dom.test.ts
+++ b/src/web/src/app/c/channels/layout.route-memory.dom.test.ts
@@ -11,6 +11,11 @@ import { registerOwnerServerDeleteRoute, type OwnerServerDeleteRouteToken } from
const mocks = vi.hoisted(() => ({
replace: vi.fn(),
+ search: { current: "" },
+ captureIntent: vi.fn(() => () => true),
+ serverSnapshot: { current: null as null | {
+ categories: Array<{ channels: Array<{ id: string; pending?: boolean }> }>
+ } },
navigatePath: vi.fn(),
cancelPendingNavigation: vi.fn(),
setCurrentServerId: vi.fn(),
@@ -43,10 +48,11 @@ vi.mock("@tanstack/react-query", async (importOriginal) => ({ ...await importOri
}))
vi.mock("next/navigation", () => ({
- useParams: () => ({ serverId: "missing-server", channelId: "missing-channel" }),
+ useParams: () => ({ serverId: "another-slot-server", channelId: "missing-channel" }),
+ useSelectedLayoutSegments: () => ["missing-server", "missing-channel"],
usePathname: () => "/c/channels/missing-server/missing-channel",
useRouter: () => ({ replace: mocks.replace, prefetch: vi.fn() }),
- useSearchParams: () => new URLSearchParams(),
+ useSearchParams: () => new URLSearchParams(mocks.search.current),
}))
vi.mock("sonner", () => ({ toast: mocks.toast }))
vi.mock("@/lib/api/client", () => ({ toastApiError: mocks.toastApiError }))
@@ -78,14 +84,14 @@ vi.mock("@/components/community/shell/shell-frame", () => ({
return createElement("shell-frame", null, children, extraDialogs)
},
}))
-vi.mock("@/lib/community/community-route", () => ({
+vi.mock("@/lib/community/community-route", async (importOriginal) => ({
+ ...await importOriginal<typeof import("@/lib/community/community-route")>(),
channelHref: (serverId: string, channelId: string) => `/c/channels/${serverId}/${channelId}`,
communityServerId: (pathname: string) => mocks.communityServerId(pathname),
serverRootHref: (serverId: string) => `/c/channels/${serverId}`,
- serverModalMarkerCleanupHref: () => null,
}))
vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))
-vi.mock("@/components/community/channels/channel-sidebar", () => ({ ChannelSidebar: () => null }))
+vi.mock("@/components/community/channels/channel-sidebar", () => ({ ChannelSidebar: () => null, ChannelSidebarSkeleton: () => null }))
vi.mock("@/components/community/channels/channel-route", () => ({ ChannelRoute: () => null }))
vi.mock("@/components/community/shell/community-pending-frame", () => ({
CommunityPendingFrame: ({ href }: { href: string }) => createElement("div", {
@@ -130,7 +136,7 @@ vi.mock("@/hooks/community/use-servers", () => ({
serverProjectedQueryFn: () => vi.fn(),
useServer: (serverId: string | null) => {
mocks.useServer(serverId)
- return { server: undefined }
+ return { server: serverId ? mocks.serverSnapshot.current ?? undefined : undefined }
},
useServers: () => ({
servers: mocks.servers.current,
@@ -238,7 +244,22 @@ vi.mock("@/hooks/community/mutations", async () => {
}
})
-import ServerLayout from "./layout"
+import ServerContent from "./layout"
+import { ServerSidebarSlot } from "@/components/community/shell/server-sidebar-slot"
+import { CommunityRouteContext } from "@/components/community/shell/community-route-context"
+import { normalizeCommunityHref } from "@/lib/community/community-route"
+
+function ServerLayout({ children }: { children?: React.ReactNode }) {
+ const scope = { serverId: "missing-server", token: mocks.routeToken }
+ useLayoutEffect(() => {
+ registerOwnerServerDeleteRoute(mocks.queryClient, scope.serverId, scope.token)
+ }, [scope.serverId, scope.token])
+ return createElement(CommunityRouteContext, { value: {
+ frame: { ...normalizeCommunityHref("/c/channels/missing-server/missing-channel"), revision: 0 },
+ navigation: { captureIntent: mocks.captureIntent } as never,
+ ownerDeleteRouteScope: scope,
+ } }, createElement(ServerSidebarSlot, { serverId: scope.serverId }), createElement(ServerContent, null, children))
+}
function render(node: React.ReactNode) {
ingestServers(getCommunityDbRegistry(mocks.queryClient)!, { servers: mocks.servers.current.map(({ id }) => ({ id, name: id, unread: false, mentions: 0 })) })
@@ -256,6 +277,10 @@ describe("ServerLayout deletion routing", () => {
vi.spyOn(client, "fetchQuery")
window.history.replaceState({}, "", "/c/channels/missing-server/missing-channel")
mocks.replace.mockClear()
+ mocks.search.current = ""
+ mocks.serverSnapshot.current = null
+ mocks.captureIntent.mockReset()
+ mocks.captureIntent.mockImplementation(() => () => true)
mocks.navigatePath.mockClear()
mocks.cancelPendingNavigation.mockClear()
mocks.setCurrentServerId.mockClear()
@@ -295,6 +320,32 @@ describe("ServerLayout deletion routing", () => {
mocks.runEject.mockReturnValue(false)
})
+ it("keeps the original delete navigation qualified while its protected route still has a modal marker", async () => {
+ mocks.search.current = "settings=1"
+ mocks.serverSnapshot.current = { categories: [] }
+ const view = render(createElement(ServerLayout))
+ expect(mocks.cancelPendingNavigation).toHaveBeenCalled()
+ expect(mocks.replace).toHaveBeenCalledWith("/c/channels/missing-server/missing-channel")
+ mocks.replace.mockClear()
+ mocks.cancelPendingNavigation.mockClear()
+ mocks.captureIntent.mockImplementation(() => {
+ const cancellations = mocks.cancelPendingNavigation.mock.calls.length
+ return () => mocks.cancelPendingNavigation.mock.calls.length === cancellations
+ })
+
+ await act(async () => { await mocks.deleteServerAction.current!() })
+ expect(getCommunityDbRegistry(mocks.queryClient)!.runtime.serverEject.get()
+ .transactions.get("missing-server")?.request).toBe("pending")
+ expect(mocks.cancelPendingNavigation).not.toHaveBeenCalled()
+ expect(mocks.replace).not.toHaveBeenCalled()
+
+ await act(async () => {
+ mocks.deleteServer.mock.calls[0]![1].onSuccess()
+ })
+ expect(mocks.replace).toHaveBeenCalledExactlyOnceWith("/c/me")
+ view.unmount()
+ })
+
it("checks the current pathname before running the generic eject", () => {
expect(window.location.href).toContain("://")
@@ -531,7 +582,7 @@ describe("ServerLayout deletion routing", () => {
await act(async () => callbacks.onError(error))
rendered.rerender(createElement(ServerLayout, null, createElement("div")))
expect(mocks.replace).not.toHaveBeenCalled()
- expect(mocks.toastApiError).toHaveBeenCalledWith(error, "Failed to delete server")
+ expect(mocks.toastApiError).toHaveBeenCalledWith(error, "Failed to delete server", expect.any(Function))
expect(mocks.useServer).toHaveBeenLastCalledWith("missing-server")
mocks.servers.current = [{ id: "surviving-server" }]
diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsx
index e33d60e13..d4f6df9d9 100644
--- a/src/web/src/app/c/channels/layout.tsx
+++ b/src/web/src/app/c/channels/layout.tsx
@@ -1,643 +1,36 @@
"use client"
-import { useAtom, useCreateAtom, useSelector } from "@tanstack/react-store";
-import { getCommunityRuntime } from "@/stores/community/runtime"
-
-import { useCallback, useEffect, useMemo, useRef, type ReactNode } from "react"
-import { useParams, usePathname, useRouter, useSearchParams } from "next/navigation"
+import type { ReactNode } from "react"
+import { useSelectedLayoutSegments, usePathname } from "next/navigation"
import { useQueryClient } from "@tanstack/react-query"
-import { toast } from "sonner"
-import { toastApiError } from "@/lib/api/client"
-import { markSwitch } from "@/lib/perf/switch-mark"
-import { Dialog, DialogContent } from "@/components/ui/dialog"
-import { ShellFrame } from "@/components/community/shell/shell-frame"
-import {
- channelHref,
- communityServerId,
- serverModalMarkerCleanupHref,
- serverRootHref,
-} from "@/lib/community/community-route"
-import { useBreakpoint } from "@/hooks/use-mobile"
-import { ChannelSidebarRevealBoundary } from "@/components/community/channels/channel-sidebar-tree-owner"
+import { useSelector } from "@tanstack/react-store"
+import { useCurrentUser } from "@/contexts/community/current-user"
+import { getCommunityRuntime } from "@/stores/community/runtime"
+import { CommunityServerRouteContext, useCommunityRouteFrame } from "@/components/community/shell/community-route-context"
import { ChannelRoute } from "@/components/community/channels/channel-route"
+import { resolveCommunityModulePlan } from "@/lib/community/community-route"
import { CommunityPendingFrame } from "@/components/community/shell/community-pending-frame"
-import { ServerSettings } from "@/components/community/settings/server-settings"
-import { ImageCropDialog } from "@/components/community/image-crop-dialog"
-import { validateIconSourceFile } from "@/lib/community/image-crop"
-import type { SettingsSection } from "@/components/community/settings/settings-types"
-import { canManageServer, isForum, notifLevelDisplay, type ChannelType } from "@alook/shared"
-import { readCommunityProfile } from "@/lib/community/profile-read"
-import { useCurrentChannelId, useCurrentChannelMeta } from "@/stores/community"
-import { useCurrentUser } from "@/contexts/community/current-user"
-import {
- useServer,
- useServers,
- serverProjectedQueryFn,
-} from "@/hooks/community/use-servers"
-import { useServerMembers } from "@/hooks/community/use-server-members"
-import {
- claimOwnerServerDeleteNavigation,
- consumeVoluntaryLeave,
- createOwnerServerDeleteRouteToken,
- isOwnerServerDeleteRouteProtected,
- runAuthoritativeServerEject,
-} from "@/lib/community/eject-server"
-import {
- clearLastChannel,
- getLastChannel,
- pickServerLandingHref,
-} from "@/lib/community/last-channel"
-import { communityKeys } from "@/lib/query-keys"
-import { usePresence } from "@/hooks/community/use-server-panels"
-import { useCommunityViewSource } from "@/hooks/community/use-community-view-source"
-import {
- resolveForumSidebarRouteCandidate,
- useForumSidebarThreads,
- type ForumSidebarThread,
-} from "@/hooks/community/use-forum-sidebar-threads"
-import { useCommunityWsStore } from "@/stores/community/ws"
-import {
- resolveServerNotificationDisplayLevel,
- useNotificationSettings,
-} from "@/hooks/community/use-notification-settings"
-import {
- useCreateChannel,
- useRenameChannel,
- useDeleteChannel,
- useMoveChannel,
- useCreateCategory,
- useUpdateCategory,
- useDeleteCategory,
- useReorderCategories,
- useReorderChannels,
- useDeleteServer,
- useUpdateServer,
- useUploadServerIcon,
- useSetServerNotifLevel,
- useSetMemberRole,
- useKickMember,
- useRevokeInvite,
-} from "@/hooks/community/mutations"
-import {
- useCanonicalProfilesByUserId,
- useOptionalCommunityDbRegistry,
- useTrustedRestoredPrimary,
-} from "@/lib/community-db/projections"
export default function ServerLayout({ children }: { children: ReactNode }) {
- const params = useParams<{ serverId: string; channelId?: string }>()
- const searchParams = useSearchParams()
+ const segments = useSelectedLayoutSegments()
+ const serverParam = segments[0]
const pathname = usePathname()
- const serverId = decodeURIComponent(params.serverId)
- const routeChannelId = params.channelId ? decodeURIComponent(params.channelId) : null
const queryClient = useQueryClient()
- const ownerDeleteRouteIdentity = useMemo(
- () => ({
- serverId,
- token: createOwnerServerDeleteRouteToken(queryClient),
- }),
- [queryClient, serverId],
- )
- const ownerDeleteRouteToken = ownerDeleteRouteIdentity.token
- const ownerDeleteRouteProtected = useSelector(getCommunityRuntime(queryClient).serverEject, (state) => state.transactions.has(serverId) || state.tombstones.get(ownerDeleteRouteToken) === serverId)
- const hasChannel = !!routeChannelId
- const breakpoint = useBreakpoint()
-
- const router = useRouter()
- const communityDb = useOptionalCommunityDbRegistry()
- const trustedRestoredPrimary = useTrustedRestoredPrimary()
- const cancelPendingNavigation = useCallback(() => {
- getCommunityRuntime(queryClient).ui.get().uiHandlers.cancelPendingNavigation?.()
- }, [queryClient])
const currentUser = useCurrentUser()
- const serverAccessRevoked = useCommunityWsStore(
- (state) => state.revokedServerIds.has(serverId),
- )
- const {
- server: currentServer,
- data: authoritativeServer,
- } = useServer(ownerDeleteRouteProtected ? null : serverId)
- const sidebarCategories = useMemo(
- () => currentServer?.categories ?? [],
- [currentServer],
- )
- const sidebarHintOnly = Boolean(currentServer && !authoritativeServer)
- const membersHook = useServerMembers(currentServer ? serverId : null)
- const profilesByUserId = useCanonicalProfilesByUserId()
- const enrichedMembers = useMemo(
- () =>
- membersHook.members.map((m) => {
- const canonical = profilesByUserId.get(m.userId)
- const profile = canonical
- ? readCommunityProfile(canonical, m.userId)
- : { ...m, presence: m.status }
- return {
- ...m,
- name: profile.name,
- discriminator: profile.discriminator,
- avatar: profile.avatar,
- avatarVersion: profile.avatarVersion,
- status: m.userId === currentUser.id ? "online" as const : profile.presence,
- statusEmoji: profile.statusEmoji,
- statusText: profile.statusText,
- }
- }),
- [currentUser.id, membersHook.members, profilesByUserId],
- )
- // `myMember` comes from the raw (not enriched) members list so this stays
- // stable across presence ticks.
- const myMember = membersHook.members.find((m) => m.userId === currentUser.id)
- const isAdmin = canManageServer(myMember?.role)
- usePresence(currentServer ? serverId : null)
- const notifs = useNotificationSettings()
- const notifLevel = resolveServerNotificationDisplayLevel(notifs.server[serverId])
- const channelNotif = notifs.channel
- const currentChannelId = useCurrentChannelId()
- const currentChannelMeta = useCurrentChannelMeta()
- const activeForumThreadId = useMemo(() => {
- if (!currentChannelId || !currentChannelMeta?.parentChannelId) return null
- const parent = sidebarCategories
- .flatMap((category) => category.channels)
- .find((channel) => channel.id === currentChannelMeta.parentChannelId)
- return isForum(parent?.type) ? currentChannelId : null
- }, [currentChannelId, currentChannelMeta?.parentChannelId, sidebarCategories])
- const sidebarRouteCandidate = useMemo(() => {
- const topLevelChannels = sidebarCategories.length > 0
- ? sidebarCategories.flatMap((category) => category.channels)
- : null
- const parent = currentChannelId === routeChannelId && currentChannelMeta?.parentChannelId
- ? topLevelChannels?.find((channel) => channel.id === currentChannelMeta.parentChannelId)
- : null
- return resolveForumSidebarRouteCandidate(
- routeChannelId,
- topLevelChannels?.map((channel) => channel.id) ?? null,
- isForum(parent?.type),
- )
- }, [currentChannelId, currentChannelMeta?.parentChannelId, routeChannelId, sidebarCategories])
- const forumSidebar = useForumSidebarThreads(
- serverId,
- sidebarRouteCandidate,
- !!currentServer?.categories,
- )
- const forumThreadsByParent = useMemo(() => {
- const grouped: Record<string, ForumSidebarThread[]> = {}
- for (const thread of forumSidebar.threads) {
- const siblings = grouped[thread.parentChannelId] ?? []
- siblings.push(thread)
- grouped[thread.parentChannelId] = siblings
- }
- return grouped
- }, [forumSidebar.threads])
-
- const serversList = useServers()
- const serverDestination = useCallback(async (id: string) => {
- const lastChannel = getLastChannel(id)
- const read = () => communityDb ? Array.from(communityDb.collections.channels.values()).filter((channel) => channel.serverId === id && channel.type !== "thread" && !channel.pending).map((channel) => channel.id) : []
- if (!communityDb?.collections.servers.get(id)?.detailComplete && !lastChannel && read().length === 0) {
- try {
- await queryClient.fetchQuery({ queryKey: communityKeys.server(id), queryFn: ({ signal }) => serverProjectedQueryFn(queryClient, id, signal)(), staleTime: Infinity })
- } catch {}
- }
- const channelIds = read()
- return pickServerLandingHref(id, channelIds, lastChannel)
- }, [communityDb, queryClient])
-
- // Mutations
- const createChannelMut = useCreateChannel()
- const renameChannelMut = useRenameChannel()
- const deleteChannelMut = useDeleteChannel()
- const moveChannelMut = useMoveChannel()
- const createCategoryMut = useCreateCategory()
- const updateCategoryMut = useUpdateCategory()
- const deleteCategoryMut = useDeleteCategory()
- const reorderCategoriesMut = useReorderCategories()
- const reorderChannelsMut = useReorderChannels()
- const deleteServerMut = useDeleteServer({
- routeToken: ownerDeleteRouteToken,
- onSuccess: ({ serverId: deletedServerId }, { needsNavigation }) => {
- toast("Server deleted")
- clearLastChannel(deletedServerId)
- if (!needsNavigation) return
- void (async () => {
- const allowed = new Set([...communityDb!.collections.serverMemberships.values()].filter((row) => row.viewer && row.userId === currentUser.id).map((row) => row.serverId))
- const survivor = [...communityDb!.collections.servers.values()].filter((server) => allowed.has(server.id)).sort((a, b) => (a.position ?? 0) - (b.position ?? 0)).find((server) => server.id !== deletedServerId)
- const destination = survivor
- ? await serverDestination(survivor.id)
- : "/c/me"
- if (!claimOwnerServerDeleteNavigation(queryClient,
- deletedServerId,
- ownerDeleteRouteToken,
- destination,
- )) return
- cancelPendingNavigation()
- router.replace(destination)
- })()
- },
- onError: (error) => toastApiError(error, "Failed to delete server"),
- })
- const updateServerMut = useUpdateServer()
- const uploadServerIconMut = useUploadServerIcon()
- const setServerNotifMut = useSetServerNotifLevel()
- const setMemberRoleMut = useSetMemberRole()
- const kickMemberMut = useKickMember()
- const revokeInviteMut = useRevokeInvite()
-
- useEffect(() => {
- getCommunityRuntime(queryClient).ui.actions.setCurrentServerId(serverId)
- }, [queryClient, serverId])
-
- // Eject when the URL is scoped to a server the viewer isn't in. Covers
- // four triggers with one effect:
- // 1. Viewer clicked "Leave" (rail button pre-marks the id via
- // markVoluntaryLeave — we stay silent, the button owns the toast).
- // 2. Viewer was kicked from another tab (WS member.leave invalidates
- // `servers()` when userId === viewer, list drops the row).
- // 3. Owner deleted the server (WS server.delete invalidates same).
- // 4. Viewer pasted a URL for a server they were never in (list
- // finishes loading, id is missing from the start).
- //
- // Only a settled SUCCESSFUL snapshot can prove absence. `isFetched` is also
- // true after a first 5xx, while a failed background refetch may retain
- // last-good data; treating either as authoritative ejects valid URLs on a
- // transient read failure. The ref prevents a re-fire during navigation.
- const ejectedRef = useRef(false)
- useEffect(() => {
- if (ejectedRef.current) return
- if (typeof window !== "undefined"
- && communityServerId(window.location.pathname) !== serverId) return
- ejectedRef.current = runAuthoritativeServerEject({
- serverId,
- servers: serversList.servers,
- // A target-specific 403/404 is already definitive even if revoking the
- // target advanced the access epoch and retired an in-flight list read.
- // A restored list is renderable but its absence is not an access
- // verdict. Only a live list confirmed for this QueryClient + auth
- // generation may drive the generic eject path.
- isSuccess: serverAccessRevoked
- || (serversList.isSuccess && serversList.isLiveAuthoritative),
- isFetching: serverAccessRevoked ? false : serversList.isFetching,
- ownerDeleteRouteProtected: isOwnerServerDeleteRouteProtected(queryClient, serverId),
- consumeVoluntaryLeave: (id) => consumeVoluntaryLeave(queryClient, id),
- clearLastChannel,
- toast,
- accountId: currentUser.id,
- routeHref: pathname,
- replace: (destination) => {
- cancelPendingNavigation()
- router.replace(destination)
- },
- })
- }, [cancelPendingNavigation, currentUser.id, pathname, serverAccessRevoked, serverId, serversList.isLiveAuthoritative, serversList.isSuccess, serversList.isFetching, serversList.servers, router, searchParams, queryClient])
- // Reset the guard when the URL changes to a NEW server id — otherwise
- // navigating server → dangling-server → server would leave the ref
- // latched and skip the eject.
- useEffect(() => {
- ejectedRef.current = false
- }, [serverId])
-
- const [serverSettingsOpen, setServerSettingsOpen] = useAtom(useCreateAtom(false))
- const settingsView = useCommunityViewSource("server-settings:" + serverId, serverSettingsOpen)
- const [settingsSection, setSettingsSection] = useAtom(useCreateAtom<SettingsSection>("overview"))
- const [invitePopoverOpen, setInvitePopoverOpen] = useAtom(useCreateAtom(false))
- const [pendingIconCrop, setPendingIconCrop] = useAtom(useCreateAtom<{ src: string; fileName: string } | null>(null))
-
- // Close server-scoped dialogs when the user navigates to another server —
- // without this, settings for server A would remain open after switching
- // to server B, mixing A's draft with B's loaded metadata.
- useEffect(() => {
- setServerSettingsOpen(false)
- setSettingsSection("overview")
- setInvitePopoverOpen(false)
- }, [serverId, setInvitePopoverOpen, setServerSettingsOpen, setSettingsSection])
-
- // Open the dialog the instant we see the flag — this only touches local
- // state, so it can't race with the sibling default-channel page's own
- // redirect below. (Splitting this from the URL cleanup fixes a bug where
- // waiting to open the dialog until *after* the redirect meant the flag —
- // and the URL query string carrying it — was already gone by then, so the
- // dialog silently never opened.)
- useEffect(() => {
- if (searchParams.get("settings") === "1") setServerSettingsOpen(true)
- if (searchParams.get("invite") === "1") setInvitePopoverOpen(true)
- }, [searchParams, setInvitePopoverOpen, setServerSettingsOpen])
-
- useEffect(() => {
- // 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 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 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(() => sidebarCategories.map((category) => ({
- ...category,
- channels: category.channels.map((channel) =>
- forumSidebar.parentUnread[channel.id] === undefined
- ? channel
- : { ...channel, unread: forumSidebar.parentUnread[channel.id] },
- ),
- })), [forumSidebar.parentUnread, sidebarCategories])
- const sidebarDataReady = Boolean(currentServer)
- const channelTreeScopeKey = `server:${serverId}`
-
- const setActiveChannel = useCallback((id: string) => {
- // Only navigate — do NOT eagerly set the store's currentChannelId here.
- // The currently-mounted ChannelView is still keyed to the old channelId;
- // flipping the store now triggers its reset effect (messagesLoading=true)
- // while the URL still points at the OLD channel, so the loading skeleton
- // renders using the old channel's type for one frame. Letting the newly-
- // mounted ChannelView sync the store in its own useEffect keeps skeleton
- // type consistent with the target channel.
- //
- // The visible-row observer is the only optimistic/read writer. Navigation
- // itself must leave account unread state untouched.
- markSwitch("channel", id)
- cancelPendingNavigation()
- getCommunityRuntime(queryClient).ui.get().uiHandlers.navigatePath?.(channelHref(serverId, id))
- }, [cancelPendingNavigation, queryClient, serverId])
-
- const setActiveForumThread = useCallback((_parentId: string, id: string) => {
- markSwitch("channel", id)
- cancelPendingNavigation()
- getCommunityRuntime(queryClient).ui.get().uiHandlers.navigatePath?.(
- channelHref(serverId, id),
- )
- }, [cancelPendingNavigation, queryClient, serverId])
-
- const onSidebarOpenSettings = useCallback((section?: SettingsSection) => {
- if (section) setSettingsSection(section)
- setServerSettingsOpen(true)
- }, [setServerSettingsOpen, setSettingsSection])
-
- const onRailOpenActiveInvite = useCallback(() => {
- setInvitePopoverOpen(true)
- }, [setInvitePopoverOpen])
-
- const onBlockedCreate = useCallback(() => {
- toast("Only admins can create channels in a private category")
- }, [])
-
- const mutedChannels = useMemo(
- () => Object.fromEntries(
- Object.entries(channelNotif).map(([k, v]) => [k, v === notifLevelDisplay("nothing")])
- ),
- [channelNotif]
- )
-
- const onCreateChannelInSidebar = useCallback(async (categoryId: string, name: string, type: ChannelType) => {
- try {
- const res = await createChannelMut.mutateAsync({ serverId, categoryId, name, type })
- return res.channel.id
- } catch (e) {
- toastApiError(e, "Failed to create channel")
- return null
- }
- }, [createChannelMut, serverId])
- const onCreateCategoryInSidebar = useCallback((name: string, opts?: { private?: boolean }) => {
- createCategoryMut.mutate(
- { serverId, name, private: opts?.private },
- { onError: (e) => toastApiError(e, "Failed to create category") },
- )
- }, [createCategoryMut, serverId])
- const onRenameChannel = useCallback((channelId: string, name: string) => {
- renameChannelMut.mutate(
- { serverId, channelId, name },
- { onError: (e) => toastApiError(e, "Failed to rename channel") },
- )
- }, [renameChannelMut, serverId])
- const onDeleteChannelInSidebar = useCallback((channelId: string) => {
- deleteChannelMut.mutate({ serverId, channelId }, { onError: (e) => toastApiError(e, "Failed to delete channel") })
- }, [deleteChannelMut, serverId])
- const onDeleteCategoryInSidebar = useCallback((categoryId: string) => {
- deleteCategoryMut.mutate({ serverId, categoryId }, { onError: (e) => toastApiError(e, "Failed to delete category") })
- }, [deleteCategoryMut, serverId])
- const onUpdateCategoryInSidebar = useCallback((categoryId: string, opts: { name?: string }) => {
- updateCategoryMut.mutate({ serverId, categoryId, name: opts.name }, { onError: (e) => toastApiError(e, "Failed to update category") })
- }, [updateCategoryMut, serverId])
- const onReorderCategoriesInSidebar = useCallback((categoryIds: string[]) => {
- reorderCategoriesMut.mutate({ serverId, categoryIds }, { onError: (e) => toastApiError(e, "Failed to save category order") })
- }, [reorderCategoriesMut, serverId])
- const onReorderChannelsInSidebar = useCallback((channelIds: string[]) => {
- reorderChannelsMut.mutate({ serverId, channelIds }, { onError: (e) => toastApiError(e, "Failed to save channel order") })
- }, [reorderChannelsMut, serverId])
- const onMoveChannelInSidebar = useCallback((channelId: string, categoryId: string | null) => {
- moveChannelMut.mutate({ serverId, channelId, categoryId }, { onError: (e) => toastApiError(e, "Failed to move channel") })
- }, [moveChannelMut, serverId])
- const onBlockedMove = useCallback(() => {
- toast("Can't move a channel between public and private categories")
- }, [])
-
- const channelProps = useMemo(() => ({
- serverName: currentServer?.name ?? "",
- serverIcon: currentServer?.icon ?? null,
- official: currentServer?.official ?? false,
- activeChannel: currentChannelMeta?.parentChannelId ?? currentChannelId ?? "",
- isAdmin,
- currentUserId: currentUser.id,
- setActiveChannel,
- forumThreadsByParent,
- activeThreadId: activeForumThreadId,
- onSelectForumThread: setActiveForumThread,
- onOpenSettings: !sidebarHintOnly && isAdmin ? onSidebarOpenSettings : undefined,
- onBlockedCreate,
- mutedChannels,
- onCreateChannel: sidebarHintOnly ? undefined : onCreateChannelInSidebar,
- onCreateCategory: sidebarHintOnly ? undefined : onCreateCategoryInSidebar,
- onRenameChannel: sidebarHintOnly ? undefined : onRenameChannel,
- onDeleteChannel: sidebarHintOnly ? undefined : onDeleteChannelInSidebar,
- onDeleteCategory: sidebarHintOnly ? undefined : onDeleteCategoryInSidebar,
- onUpdateCategory: sidebarHintOnly ? undefined : onUpdateCategoryInSidebar,
- onReorderCategories: sidebarHintOnly ? undefined : onReorderCategoriesInSidebar,
- onReorderChannels: sidebarHintOnly ? undefined : onReorderChannelsInSidebar,
- onMoveChannel: sidebarHintOnly ? undefined : onMoveChannelInSidebar,
- onBlockedMove,
- serverId,
- invitePopoverOpen,
- onInvitePopoverOpenChange: sidebarHintOnly ? undefined : setInvitePopoverOpen,
- }), [currentServer?.name, currentServer?.icon, currentServer?.official, currentChannelMeta?.parentChannelId, currentChannelId, isAdmin, currentUser.id, setActiveChannel, forumThreadsByParent, activeForumThreadId, setActiveForumThread, sidebarHintOnly, onSidebarOpenSettings, onBlockedCreate, mutedChannels, onCreateChannelInSidebar, onCreateCategoryInSidebar, onRenameChannel, onDeleteChannelInSidebar, onDeleteCategoryInSidebar, onUpdateCategoryInSidebar, onReorderCategoriesInSidebar, onReorderChannelsInSidebar, onMoveChannelInSidebar, onBlockedMove, serverId, invitePopoverOpen, setInvitePopoverOpen])
-
- const openProfile = (name: string, e: React.MouseEvent, discriminator?: string, userId?: string) => {
- // Delegate to the shell's registered openProfile via the community store.
- getCommunityRuntime(queryClient).ui.get().uiHandlers.openProfile?.(name, e, discriminator, userId)
- }
-
- const closeSettings = () => { settingsView.retire(); setServerSettingsOpen(false); setSettingsSection("overview") }
-
- const sidebar = useCallback((opts: { noHeader?: boolean } = {}) => (
- <ChannelSidebarRevealBoundary
- key={channelTreeScopeKey}
- scopeKey={channelTreeScopeKey}
- categories={categories}
- primaryReady={sidebarDataReady}
- forumProjectionMissing={!forumSidebar.projectionReady}
- trustedRestoredPrimary={trustedRestoredPrimary}
- targetServerId={serverId}
- {...channelProps}
- {...opts}
- />
- ), [
- categories,
- channelProps,
- channelTreeScopeKey,
- forumSidebar.projectionReady,
- serverId,
- sidebarDataReady,
- trustedRestoredPrimary,
- ])
-
- const serverSettingsDialog = (
- <Dialog open={serverSettingsOpen && !!currentServer && isAdmin} onOpenChange={(o) => { if (!o) closeSettings() }}>
- <DialogContent className="flex h-dvh max-h-dvh w-screen max-w-none flex-col gap-0 overflow-hidden rounded-none p-0 sm:h-[calc(100vh-4rem)] sm:max-h-180 sm:w-[calc(100vw-4rem)] sm:max-w-4xl sm:rounded-xl" showCloseButton={false}>
- <ServerSettings
- isAdmin={isAdmin}
- section={settingsSection}
- setSection={setSettingsSection}
- onClose={closeSettings}
- serverId={serverId}
- serverName={currentServer?.name ?? ""}
- serverDescription={currentServer?.description ?? ""}
- serverIcon={currentServer?.icon ?? null}
- members={enrichedMembers}
- membersLoading={membersHook.loading}
- membersLoadingMore={membersHook.loadingMore}
- membersHasMore={membersHook.hasMore}
- membersTotal={membersHook.total}
- onLoadMoreMembers={membersHook.loadMore}
- onSearchMembers={membersHook.searchMembers}
- onKickMember={(memberId) => {
- const assert = settingsView.capture()
- kickMemberMut.mutate({ serverId, memberId, assertActive: assert }, {
- onSuccess: () => { try { assert(); toast("Member kicked") } catch {} },
- onError: (e) => toastApiError(e, "Failed to kick member", assert),
- })
- }}
- onSetRole={(memberId, role) => {
- const assert = settingsView.capture()
- setMemberRoleMut.mutate({ serverId, memberId, role, assertActive: assert }, {
- onSuccess: () => { try { assert(); toast("Role updated") } catch {} },
- onError: (e) => toastApiError(e, "Failed to update role", assert),
- })
- }}
- onRevokeInvite={(code) => {
- const assert = settingsView.capture()
- revokeInviteMut.mutate({ serverId, code, assertActive: assert }, {
- onSuccess: () => { try { assert(); toast("Invite revoked") } catch {} },
- onError: (e) => toastApiError(e, "Failed to revoke invite", assert),
- })
- }}
- onCopyInvite={(code) => {
- const assert = settingsView.capture()
- assert()
- void navigator.clipboard.writeText(`${window.location.origin}/c/invite/${code}`).then(() => { try { assert(); toast("Invite copied") } catch {} }, (error) => toastApiError(error, "Couldn't copy invite", assert))
- }}
- onDeleteServer={async () => {
- closeSettings()
- deleteServerMut.mutate({ serverId })
- }}
- onUploadIcon={() => {
- const input = document.createElement("input")
- input.type = "file"
- input.accept = "image/png,image/jpeg,image/webp"
- input.onchange = () => {
- const f = input.files?.[0]
- if (!f) return
- const check = validateIconSourceFile(f)
- if (!check.ok) {
- toast(check.error)
- return
- }
- setPendingIconCrop({ src: URL.createObjectURL(f), fileName: f.name })
- }
- input.click()
- }}
- onUpdateServer={(name, desc) =>
- updateServerMut.mutate({ serverId, name, description: desc }, {
- onSuccess: () => toast("Server updated"),
- onError: (e) => toastApiError(e, "Failed to update server"),
- })
- }
- notifLevel={notifLevel}
- onSetNotifLevel={(level) => setServerNotifMut.mutate({ serverId, level }, {
- onError: (e) => toastApiError(e, "Failed to update notification level"),
- })}
- onOpenProfile={openProfile}
- />
- </DialogContent>
- </Dialog>
- )
-
- const iconCropDialog = pendingIconCrop && (
- <ImageCropDialog
- imageSrc={pendingIconCrop.src}
- originalFileName={pendingIconCrop.fileName}
- maskShape="square"
- onCropped={(file) => {
- uploadServerIconMut.mutate({ serverId, file }, {
- onSuccess: () => toast("Server icon updated"),
- onError: (e) => toastApiError(e, "Failed to upload icon"),
- })
- URL.revokeObjectURL(pendingIconCrop.src)
- setPendingIconCrop(null)
- }}
- onCancel={() => {
- URL.revokeObjectURL(pendingIconCrop.src)
- setPendingIconCrop(null)
- }}
- />
- )
-
- const structuralFrameHref = routeChannelId
- ? channelHref(serverId, routeChannelId)
- : serverRootHref(serverId)
- const content = ownerDeleteRouteProtected
+ const { ownerDeleteRouteScope } = useCommunityRouteFrame()
+ const serverId = serverParam ? decodeURIComponent(serverParam) : ""
+ const modulePlan = resolveCommunityModulePlan(`/c/channels/${segments.join("/")}`)
+ const routeChannelId = modulePlan.main.kind === "server-conversation"
+ ? modulePlan.main.leafId : null
+ const protectedRoute = useSelector(getCommunityRuntime(queryClient).serverEject, (state) =>
+ state.transactions.has(serverId) || Boolean(ownerDeleteRouteScope?.serverId === serverId
+ && state.tombstones.get(ownerDeleteRouteScope.token) === serverId))
+ const content = protectedRoute
? <CommunityPendingFrame href={pathname} />
: routeChannelId
- ? (
- <ChannelRoute
- key={`${serverId}/${routeChannelId}`}
- serverParam={params.serverId}
- channelId={routeChannelId}
- />
- )
- : children
-
- return (
- <ShellFrame
- view="server"
- activeServerId={serverId}
- frameHref={structuralFrameHref}
- sidebar={sidebar}
- extraDialogs={<>{serverSettingsDialog}{iconCropDialog}</>}
- onOpenActiveServerSettings={onSidebarOpenSettings}
- onOpenActiveServerInvite={onRailOpenActiveInvite}
- ownerDeleteRouteScope={ownerDeleteRouteIdentity}
- >
- {content}
- </ShellFrame>
- )
+ ? <ChannelRoute key={`${currentUser.id}/${serverId}/${routeChannelId}`} serverParam={serverParam!} channelId={routeChannelId} />
+ : children
+ return <CommunityServerRouteContext value={{ serverId, serverParam: serverParam ?? "" }}>
+ {content}
+ </CommunityServerRouteContext>
}
diff --git a/src/web/src/app/c/community-layout-client.tsx b/src/web/src/app/c/community-layout-client.tsx
index c80733ec3..2d8d0879c 100644
--- a/src/web/src/app/c/community-layout-client.tsx
+++ b/src/web/src/app/c/community-layout-client.tsx
@@ -3,6 +3,7 @@
import { useEffect, type ReactNode } from "react"
import { usePathname, useRouter } from "next/navigation"
import { CommunityShell } from "./community-shell"
+import { CommunityRouteFrame } from "@/components/community/shell/community-route-frame"
import { SignupTracker } from "@/components/signup-tracker"
import { CommunitySessionPendingFrame } from "@/components/community/shell/community-session-pending-frame"
import { resolveCommunityModulePlan } from "@/lib/community/community-route"
@@ -20,9 +21,11 @@ function isPublicCommunityPath(pathname: string): boolean {
export function CommunityLayoutClient({
children,
+ sidebar,
currentUser,
}: {
children: ReactNode
+ sidebar: ReactNode
currentUser: CurrentUser | null
}) {
const router = useRouter()
@@ -49,7 +52,7 @@ export function CommunityLayoutClient({
<AuthenticatedNativeOauthCleanup />
<CommunityShell currentUser={currentUser}>
<SignupTracker redirectTo="/c/me/machines" />
- {children}
+ <CommunityRouteFrame sidebar={sidebar}>{children}</CommunityRouteFrame>
</CommunityShell>
</AuthenticatedContextMenuBoundary>
)
diff --git a/src/web/src/app/c/layout.dom.test.ts b/src/web/src/app/c/layout.dom.test.ts
index c48131f03..8107d0d0c 100644
--- a/src/web/src/app/c/layout.dom.test.ts
+++ b/src/web/src/app/c/layout.dom.test.ts
@@ -50,7 +50,7 @@ const user = {
function renderLayout(currentUser: typeof user | null = null) {
return render(createElement(
CommunityLayoutClient,
- { currentUser },
+ { currentUser, sidebar: null },
createElement("div", { "data-testid": "child" }),
))
}
@@ -110,7 +110,7 @@ describe("CommunityLayout session boundary", () => {
"src/app/c/layout.tsx",
), "utf8")
expect(source).toContain("await getSession()")
- expect(source).toContain("<CommunityLayoutClient currentUser={currentUser}>")
+ expect(source).toContain("<CommunityLayoutClient currentUser={currentUser} sidebar={sidebar}>")
expect(source).not.toContain("useSession")
})
@@ -121,7 +121,7 @@ describe("CommunityLayout session boundary", () => {
"src/app/c/me/layout.tsx",
), "utf8")
expect(source).not.toContain("useDmRouteVerification")
- expect(source).toContain('<DmRoute key={`${currentUser.id}/${params.dmId}`} dmId={params.dmId} />')
+ expect(source).toContain('<DmRoute key={`${currentUser.id}/${dmId}`} dmId={dmId} />')
expect(source).not.toMatch(/isFetching:\s*dmsFetching/)
})
diff --git a/src/web/src/app/c/layout.tsx b/src/web/src/app/c/layout.tsx
index 18d196c58..6c5212d63 100644
--- a/src/web/src/app/c/layout.tsx
+++ b/src/web/src/app/c/layout.tsx
@@ -3,7 +3,7 @@ import { getSession } from "@/lib/session"
import { avatarInitial } from "@/lib/community/avatar"
import { CommunityLayoutClient } from "./community-layout-client"
-export default async function CommunityLayout({ children }: { children: ReactNode }) {
+export default async function CommunityLayout({ children, sidebar }: { children: ReactNode; sidebar: ReactNode }) {
const session = await getSession()
const currentUser = session
? {
@@ -16,7 +16,7 @@ export default async function CommunityLayout({ children }: { children: ReactNod
: null
return (
- <CommunityLayoutClient currentUser={currentUser}>
+ <CommunityLayoutClient currentUser={currentUser} sidebar={sidebar}>
{children}
</CommunityLayoutClient>
)
diff --git a/src/web/src/app/c/me/layout.route-memory.dom.test.ts b/src/web/src/app/c/me/layout.route-memory.dom.test.ts
index e611351eb..2e22d3dcd 100644
--- a/src/web/src/app/c/me/layout.route-memory.dom.test.ts
+++ b/src/web/src/app/c/me/layout.route-memory.dom.test.ts
@@ -10,6 +10,7 @@ import { ingestAttentionSnapshot, publishCommunityFriendDecision, captureCommuni
const mocks = vi.hoisted(() => ({
pathname: "/c/me/friends",
dmId: undefined as string | undefined,
+ childSegments: null as string[] | null,
dmStatus: "idle" as "idle" | "pending" | "present" | "missing" | "error",
locationStatus: "remember" as "ignore" | "wait" | "remember" | "stale",
replace: vi.fn(),
@@ -32,7 +33,7 @@ vi.mock("next/navigation", () => ({
useRouter: () => ({ replace: mocks.replace, prefetch: vi.fn() }),
usePathname: () => mocks.pathname,
useParams: () => ({ dmId: mocks.dmId }),
- useSelectedLayoutSegments: () => mocks.pathname.slice("/c/me/".length).split("/").filter(Boolean),
+ useSelectedLayoutSegments: () => mocks.childSegments ?? mocks.pathname.slice("/c/me/".length).split("/").filter(Boolean),
}))
vi.mock("@/contexts/community/current-user", () => ({
useCurrentUser: () => ({ id: "viewer-1" }),
@@ -111,14 +112,25 @@ vi.mock("@/lib/community/last-community-route", () => ({
consumeCommunityColdEntryFailure: (...args: unknown[]) => mocks.consumeColdEntryFailure(...args),
}))
-import MeLayout from "./layout"
+import MeContent from "./layout"
+import { DmSidebarSlot } from "@/components/community/shell/dm-sidebar-slot"
+import { CommunityRouteContext } from "@/components/community/shell/community-route-context"
+import { normalizeCommunityHref } from "@/lib/community/community-route"
+
+function MeLayout({ children }: { children?: React.ReactNode }) {
+ return createElement(CommunityRouteContext, { value: {
+ frame: { ...normalizeCommunityHref(mocks.pathname), revision: 0 },
+ navigation: {} as never,
+ ownerDeleteRouteScope: undefined,
+ } }, createElement(DmSidebarSlot), createElement(MeContent, null, children))
+}
let layoutClient: QueryClient
function renderLayout(queryClient = layoutClient) {
return render(createElement(
QueryClientProvider,
{ client: queryClient, userId: "viewer-1" },
- createElement(MeLayout, null, createElement("div")),
+ createElement(MeLayout, null, createElement("div", { "data-testid": "static-content" })),
))
}
@@ -127,6 +139,7 @@ describe("MeLayout route memory", () => {
layoutClient = (await createCommunityQueryOwner("viewer-1")).client
mocks.pathname = "/c/me/friends"
mocks.dmId = undefined
+ mocks.childSegments = null
mocks.dmStatus = "idle"
mocks.locationStatus = "remember"
mocks.replace.mockClear()
@@ -149,6 +162,36 @@ describe("MeLayout route memory", () => {
expect(mocks.replace).not.toHaveBeenCalled()
})
+ it.each(["friends", "machines", "bots"])("keeps its own %s child when another slot exposes a DM param", (leaf) => {
+ mocks.pathname = `/c/me/${leaf}`
+ mocks.childSegments = [leaf]
+ mocks.dmId = "foreign-slot-dm"
+ const rendered = renderLayout()
+ expect(rendered.queryByTestId("target-dm")).toBeNull()
+ expect(rendered.getByTestId("static-content")).toBeVisible()
+ expect(mocks.setLastMeLocation).toHaveBeenCalledWith(`/c/me/${leaf}`)
+ })
+
+ it("uses its own committed DM child instead of another slot's DM param", () => {
+ mocks.pathname = "/c/me/own-dm"
+ mocks.childSegments = ["own-dm"]
+ mocks.dmId = "foreign-slot-dm"
+ const rendered = renderLayout()
+ expect(rendered.getByTestId("target-dm")).toHaveAttribute("data-channel-id", "own-dm")
+ expect(mocks.setLastMeLocation).not.toHaveBeenCalled()
+ })
+
+ it("does not mount a foreign DM while its own children remain at the root", () => {
+ mocks.pathname = "/c/me/dm-pending"
+ mocks.childSegments = []
+ mocks.dmId = "foreign-slot-dm"
+ const rendered = renderLayout()
+ expect(rendered.queryByTestId("target-dm")).toBeNull()
+ expect(rendered.getByTestId("static-content")).toBeVisible()
+ expect(mocks.setLastMeLocation).not.toHaveBeenCalled()
+ expect(mocks.commitLastCommunityRoute).not.toHaveBeenCalled()
+ })
+
it.each(["wait", "ignore"] as const)("does not write a %s route", (status) => {
mocks.locationStatus = status
renderLayout()
@@ -181,6 +224,7 @@ describe("MeLayout route memory", () => {
it("does not commit a DM pathname while its layout params are still unresolved", () => {
mocks.pathname = "/c/me/dm-pending"
mocks.dmId = undefined
+ mocks.childSegments = null
mocks.locationStatus = "remember"
renderLayout()
expect(mocks.setLastMeLocation).not.toHaveBeenCalled()
diff --git a/src/web/src/app/c/me/layout.tsx b/src/web/src/app/c/me/layout.tsx
index 622fc558e..3698f6753 100644
--- a/src/web/src/app/c/me/layout.tsx
+++ b/src/web/src/app/c/me/layout.tsx
@@ -1,121 +1,26 @@
"use client"
-import { useCommunityRuntime } from "@/stores/community/runtime"
-
-import { useCallback, useEffect, useMemo, type ReactNode } from "react"
-import {
- useParams,
- usePathname,
- useSelectedLayoutSegments,
-} from "next/navigation"
-import { ShellFrame } from "@/components/community/shell/shell-frame"
+import { useEffect, type ReactNode } from "react"
+import { useSelectedLayoutSegments, usePathname } from "next/navigation"
import { DmRoute } from "@/components/community/channels/dm-route"
-import { DmSidebar } from "@/components/community/channels/dm-sidebar"
-import { useCurrentChannelId } from "@/stores/community"
-import { useDms } from "@/hooks/community/use-dms"
-import { useFriends, useFriendsPresence } from "@/hooks/community/use-friends"
-import { useInboxUnreads } from "@/hooks/community/use-inbox"
import { useCurrentUser } from "@/contexts/community/current-user"
-import {
- isRememberableMeLocation,
- setLastMeLocation,
-} from "@/lib/community/last-me-location"
+import { isRememberableMeLocation, setLastMeLocation } from "@/lib/community/last-me-location"
import { commitLastCommunityRoute } from "@/lib/community/last-community-route"
+import { resolveCommunityModulePlan } from "@/lib/community/community-route"
-// DM-side layout. The DM subtree has no server settings, no channel sidebar,
-// and no `[serverId]` param — everything is scoped to the current user.
export default function MeLayout({ children }: { children: ReactNode }) {
- const communityRuntime = useCommunityRuntime()
const pathname = usePathname()
const currentUser = useCurrentUser()
- const params = useParams<{ dmId?: string }>()
- const selectedSegments = useSelectedLayoutSegments()
- const structuralFrameHref = selectedSegments.length === 0
- ? "/c/me"
- : `/c/me/${selectedSegments.join("/")}`
- const {
- dms,
- isLoading: dmsLoading,
- } = useDms()
- const { blocked } = useFriends()
- const friendRequestCount = useInboxUnreads().friendRequests.length
- const currentChannelId = useCurrentChannelId()
-
- // Clear the active server when entering the DM home. `currentServerId ===
- // null` is the canonical "no server focused" state — no need for a "@me"
- // sentinel string.
+ const segments = useSelectedLayoutSegments()
+ const modulePlan = resolveCommunityModulePlan(segments.length ? `/c/me/${segments.join("/")}` : "/c/me")
+ const dmId = modulePlan.main.kind === "dm" ? modulePlan.main.dmId : undefined
useEffect(() => {
- communityRuntime.ui.actions.setCurrentServerId(null)
- }, [communityRuntime.ui.actions])
-
- // Seed online friends into the global profile map. The endpoint is a subset
- // of the full WS audience, so it only patches the ids it explicitly returns.
- useFriendsPresence()
-
- const machinesActive = pathname === "/c/me/machines"
- const botsActive = pathname === "/c/me/bots"
- const friendsActive = pathname === "/c/me/friends"
- const staticModuleActive = machinesActive || botsActive || friendsActive
-
- useEffect(() => {
- if (params.dmId || !staticModuleActive || !isRememberableMeLocation(pathname)) return
+ const staticModuleActive = ["/c/me/friends", "/c/me/machines", "/c/me/bots"].includes(pathname)
+ if (dmId || !staticModuleActive || !isRememberableMeLocation(pathname)) return
setLastMeLocation(pathname)
commitLastCommunityRoute(currentUser.id, pathname)
- }, [currentUser.id, params.dmId, pathname, staticModuleActive])
-
- // Navigation is intentionally read-neutral. The visible-row observer owns
- // both optimistic clearing and the durable cursor write.
- const enterDm = useCallback((id: string) => {
- communityRuntime.ui.get().uiHandlers.navigatePath?.(`/c/me/${id}`)
- }, [communityRuntime.ui])
-
- const onShowFriends = useCallback(() => {
- communityRuntime.ui.actions.setCurrentChannelId(null)
- communityRuntime.ui.get().uiHandlers.navigatePath?.("/c/me/friends")
- }, [communityRuntime.ui])
-
- const onShowMachines = useCallback(() => {
- communityRuntime.ui.actions.setCurrentChannelId(null)
- communityRuntime.ui.get().uiHandlers.navigatePath?.("/c/me/machines")
- }, [communityRuntime.ui])
-
- const onShowBots = useCallback(() => {
- communityRuntime.ui.actions.setCurrentChannelId(null)
- communityRuntime.ui.get().uiHandlers.navigatePath?.("/c/me/bots")
- }, [communityRuntime.ui])
-
- const blockedUserIds = useMemo(
- () => new Set(blocked.map((b) => b.userId ?? b.id)),
- [blocked],
- )
-
- const sidebar = useCallback(() => (
- <DmSidebar
- dms={dms}
- activeDm={currentChannelId}
- blockedUserIds={blockedUserIds}
- loading={dmsLoading}
- onPickDm={enterDm}
- onShowFriends={onShowFriends}
- friendRequestCount={friendRequestCount}
- onShowMachines={onShowMachines}
- onShowBots={onShowBots}
- friendsActive={friendsActive}
- machinesActive={machinesActive}
- botsActive={botsActive}
- />
- ), [dms, currentChannelId, dmsLoading, blockedUserIds, enterDm, onShowFriends, friendRequestCount, onShowMachines, onShowBots, friendsActive, machinesActive, botsActive])
-
- return (
- <ShellFrame
- view="dm"
- activeServerId={undefined}
- frameHref={structuralFrameHref}
- sidebar={sidebar}
- >
- {params.dmId
- ? <DmRoute key={`${currentUser.id}/${params.dmId}`} dmId={params.dmId} />
- : children}
- </ShellFrame>
- )
+ }, [currentUser.id, dmId, pathname])
+ return dmId
+ ? <DmRoute key={`${currentUser.id}/${dmId}`} dmId={dmId} />
+ : children
}
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
index eba3690ed..07b204fe1 100644
--- a/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.ts
+++ b/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.ts
@@ -7,7 +7,7 @@ const readSource = (relativePath: string) =>
describe("adaptive navigation cutover contracts", () => {
it("uses the one flat route builder while preserving parent-aware sidebar callbacks", () => {
const contextSheet = readSource("../messages/message-context-sheet.tsx")
- const layout = readSource("../../../app/c/channels/layout.tsx")
+ const layout = readSource("../shell/server-sidebar-slot.tsx")
const sidebar = readSource("./channel-sidebar.tsx")
expect(contextSheet).toContain(
@@ -31,7 +31,7 @@ describe("adaptive navigation cutover contracts", () => {
expect(layout).toContain(
'import { ChannelRoute } from "@/components/community/channels/channel-route"',
)
- expect(layout).toContain("key={`${serverId}/${routeChannelId}`}")
+ expect(layout).toContain("key={`${currentUser.id}/${serverId}/${routeChannelId}`}")
expect(layout).not.toContain("parentChannelId={routeParent" + "ChannelId}")
expect(flatPage).toContain("return null")
expect(flatPage).not.toContain("<ChannelRoute")
diff --git a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts
index cb97fb704..94e31eac5 100644
--- a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts
+++ b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts
@@ -8,6 +8,8 @@ import { MessageList } from "../messages/message-list"
import { useChannelMemberViewModel } from "../members/channel-member-view-model"
import { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"
import type { ConversationNavigationTarget } from "@/lib/community/conversation-navigation-proof"
+import { useCommunityRuntime } from "@/stores/community/runtime"
+import { runAuthoritativeServerEject } from "@/lib/community/eject-server"
const {
mockRouteModel,
@@ -672,6 +674,35 @@ describe("ChannelRoute message surface ownership", () => {
)
})
+ it("keeps server ejection when revocation removes the former top-level channel", () => {
+ mockSearchParams.value = ""
+ mockedUseChannelMessageFeed.mockReturnValue(feed())
+ let runtime!: ReturnType<typeof useCommunityRuntime>
+ function Route() {
+ runtime = useCommunityRuntime()
+ return React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" })
+ }
+ const renderer = render(React.createElement(Route))
+ mockRouter.replace.mockClear()
+ mockedUseChannelMessageFeed.mockClear()
+
+ act(() => {
+ runtime.ws.actions.revokeServerAccess("server_1")
+ expect(runAuthoritativeServerEject({
+ serverId: "server_1", servers: [], isSuccess: true, isFetching: false,
+ consumeVoluntaryLeave: () => false, clearLastChannel: mockClearLastChannel,
+ toast: vi.fn(), replace: mockRouter.replace,
+ })).toBe(true)
+ Object.assign(mockRouteModel, { server: null, channel: null, isChild: false,
+ routeHydrated: false, routeLifecycle: "pending" })
+ renderer.rerender(React.createElement(Route))
+ })
+
+ expect(mockRouter.replace).toHaveBeenCalledExactlyOnceWith("/c/me")
+ expect(mockClearLastChannel).toHaveBeenCalledExactlyOnceWith("server_1")
+ expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()
+ })
+
it("commits and dismisses only a ready top-level channel for the active account", async () => {
mockedUseChannelMessageFeed.mockReturnValue(feed())
await act(async () => {
diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsx
index ce4d79552..b37d21da6 100644
--- a/src/web/src/components/community/channels/channel-route.tsx
+++ b/src/web/src/components/community/channels/channel-route.tsx
@@ -185,7 +185,8 @@ const [topLevelRouteOwnership, setTopLevelRouteOwnership] = useAtom(useCreateAto
uiHandlers.replacePath?.(serverRootHref(serverParam))
}, [serverParam, uiHandlers])
useEffect(() => {
- if (!routeWasTopLevel || channelInServer !== null) return
+ if (!routeWasTopLevel || channelInServer !== null
+ || getCommunityRuntime(queryClient).ws.get().revokedServerIds.has(serverId)) return
clearLastChannel(serverId)
const survivor = currentServer?.categories
.flatMap((category) => category.channels)
@@ -193,7 +194,7 @@ const [topLevelRouteOwnership, setTopLevelRouteOwnership] = useAtom(useCreateAto
router.replace(survivor
? channelHref(serverParam, survivor.id)
: serverRootHref(serverParam))
- }, [channelId, channelInServer, currentServer, routeWasTopLevel, router, serverId, serverParam])
+ }, [channelId, channelInServer, currentServer, queryClient, routeWasTopLevel, router, serverId, serverParam])
const navigateParent = useCallback(() => {
const parentChannelId = currentChannelMeta?.parentChannelId
if (!parentChannelId) return
diff --git a/src/web/src/components/community/messages/use-composer-controller.dom.test.ts b/src/web/src/components/community/messages/use-composer-controller.dom.test.ts
index 63020085b..4d832e0a4 100644
--- a/src/web/src/components/community/messages/use-composer-controller.dom.test.ts
+++ b/src/web/src/components/community/messages/use-composer-controller.dom.test.ts
@@ -961,6 +961,37 @@ describe("useComposerController", () => {
expect(focus).not.toHaveBeenCalled()
})
+ it("leaves a focused persistent rail item in charge when a conversation mounts", async () => {
+ const rail = document.createElement("div")
+ rail.setAttribute("data-testid", "community-server-rail-scroll")
+ const button = document.createElement("button")
+ rail.append(button)
+ document.body.append(rail)
+ button.focus()
+ let renderer!: ReturnType<typeof render>
+ try {
+ await act(async () => {
+ renderer = render(createElement(Harness, {
+ ...acceptedProps(vi.fn(() => true)),
+ autoFocus: true,
+ }))
+ })
+ expect(document.activeElement).toBe(button)
+ expect(focus).not.toHaveBeenCalled()
+ button.blur()
+ await act(async () => {
+ renderer.rerender(createElement(Harness, {
+ ...acceptedProps(vi.fn(() => true)),
+ channel: "random",
+ autoFocus: true,
+ }))
+ })
+ expect(focus).toHaveBeenCalledWith("end")
+ } finally {
+ rail.remove()
+ }
+ })
+
it("preserves autofocus, reply edge, drop, dropdown, upload, and emoji timing", async () => {
const accept = vi.fn(() => true)
let renderer!: ReturnType<typeof render>
diff --git a/src/web/src/components/community/messages/use-composer-controller.ts b/src/web/src/components/community/messages/use-composer-controller.ts
index d63e693fc..ed8819ca8 100644
--- a/src/web/src/components/community/messages/use-composer-controller.ts
+++ b/src/web/src/components/community/messages/use-composer-controller.ts
@@ -16,6 +16,7 @@ import { DOMParser as PMDOMParser } from "@tiptap/pm/model"
import { MAX_ATTACHMENTS_PER_MESSAGE, MAX_ATTACHMENT_SIZE_BYTES } from "@alook/shared"
import { useFileAttachments } from "@/hooks/use-file-attachments"
import { useHoverCapable } from "@/hooks/use-hover-capable"
+import { tid } from "@/lib/community/testids"
import {
clearComposerDraft,
readComposerDraft,
@@ -315,6 +316,7 @@ export function useComposerController(
useEffect(() => {
if (!autoFocus || !editor || isForumThreadBody) return
+ if (document.activeElement?.closest(`[data-testid="${tid.serverRailScroll}"]`)) return
editor.commands.focus("end")
}, [autoFocus, editor, channel, isForumThreadBody])
diff --git a/src/web/src/components/community/shell/community-route-context.tsx b/src/web/src/components/community/shell/community-route-context.tsx
new file mode 100644
index 000000000..1058d1645
--- /dev/null
+++ b/src/web/src/components/community/shell/community-route-context.tsx
@@ -0,0 +1,29 @@
+"use client"
+
+import { createContext, useContext } from "react"
+import type { CommunityCommittedFrame } from "@/lib/community/community-route"
+import type { ShellFrameProps } from "./shell-frame-types"
+import type { CommunityNavigationController } from "./use-community-navigation-controller"
+
+export const CommunityRouteContext = createContext<{
+ frame: CommunityCommittedFrame
+ navigation: CommunityNavigationController
+ ownerDeleteRouteScope: ShellFrameProps["ownerDeleteRouteScope"]
+} | null>(null)
+
+export function useCommunityRouteFrame() {
+ const context = useContext(CommunityRouteContext)
+ if (!context) throw new Error("Missing community route frame")
+ return context
+}
+
+export const CommunityServerRouteContext = createContext<{
+ serverId: string
+ serverParam: string
+} | null>(null)
+
+export function useCommunityServerRoute() {
+ const context = useContext(CommunityServerRouteContext)
+ if (!context) throw new Error("Missing server content route")
+ return context
+}
diff --git a/src/web/src/components/community/shell/community-route-frame.dom.test.tsx b/src/web/src/components/community/shell/community-route-frame.dom.test.tsx
new file mode 100644
index 000000000..d922dd27d
--- /dev/null
+++ b/src/web/src/components/community/shell/community-route-frame.dom.test.tsx
@@ -0,0 +1,165 @@
+import { createElement, type ReactNode } from "react"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { act, fireEvent, render } from "@/test/react-dom-harness"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { CommunityRouteFrame } from "./community-route-frame"
+import { useCommunityRouteFrame } from "./community-route-context"
+import ServerContent from "@/app/c/channels/layout"
+
+const mocks = vi.hoisted(() => ({
+ segments: ["me", "friends"],
+ pathname: "/c/me/friends",
+ mergedServerId: "wrong-sidebar-server",
+ breakpoint: "desktop",
+ userId: "viewer-a",
+ push: vi.fn(),
+ replace: vi.fn(),
+ channel: vi.fn(),
+}))
+vi.mock("next/navigation", () => ({
+ useSelectedLayoutSegments: () => mocks.segments,
+ useParams: () => ({ serverId: mocks.mergedServerId }),
+ usePathname: () => mocks.pathname,
+ useSearchParams: () => new URLSearchParams(),
+ useRouter: () => ({ push: mocks.push, replace: mocks.replace }),
+}))
+vi.mock("@/contexts/community/current-user", () => ({
+ useCurrentUser: () => ({ id: mocks.userId }),
+}))
+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mocks.breakpoint }))
+vi.mock("@/lib/community-onboarding", () => ({ useCommunityOnboarding: () => null }))
+vi.mock("./use-shell-rail-controller", () => ({
+ useShellRailController: () => ({ railProps: {}, navigate: vi.fn() }),
+}))
+vi.mock("./use-shell-profile-controller", () => ({
+ useShellProfileController: () => ({
+ currentUser: { id: mocks.userId, name: mocks.userId, avatar: "V" },
+ profile: null, closeProfile: vi.fn(), openProfile: vi.fn(),
+ }),
+}))
+vi.mock("./use-shell-inbox-controller", () => ({
+ useShellInboxController: () => ({ open: false, popoverProps: {}, onOpenChange: vi.fn() }),
+}))
+vi.mock("./use-shell-daemon-update-controller", () => ({
+ useShellDaemonUpdateController: () => ({ update: null, eligibleMachines: [], collapse: vi.fn() }),
+}))
+vi.mock("@/hooks/community/use-running-owned-bots", () => ({
+ useRunningOwnedBots: () => ({ runningBots: [] }),
+}))
+vi.mock("react-resizable-panels", () => ({
+ useDefaultLayout: () => ({ defaultLayout: undefined, onLayoutChanged: vi.fn() }),
+}))
+vi.mock("@/components/ui/resizable", () => {
+ const Panel = ({ children }: { children: ReactNode }) => createElement("div", null, children)
+ return { ResizablePanelGroup: Panel, ResizablePanel: Panel, ResizableHandle: () => null }
+})
+vi.mock("./server-rail", () => ({ ServerRail: () => <div data-testid="rail"><button data-testid="home">Home</button><input data-testid="rail-state" /></div> }))
+vi.mock("./user-bar", () => ({ UserBar: () => <div data-testid="userbar">{mocks.userId}</div> }))
+vi.mock("./community-inbox-popover", () => ({ InboxPopover: () => null }))
+vi.mock("./shell-frame-overlays", () => ({ ShellFrameOverlays: () => null }))
+vi.mock("@/components/community/channels/channel-route", () => ({
+ ChannelRoute: (props: { serverParam: string; channelId: string }) => {
+ mocks.channel(props)
+ return <div data-testid="channel">{props.serverParam}/{props.channelId}</div>
+ },
+}))
+
+function Sidebar({ serverId }: { serverId: string | null }) {
+ const { frame, ownerDeleteRouteScope } = useCommunityRouteFrame()
+ const valid = serverId ? frame.scope.kind === "server" && frame.scope.serverId === serverId
+ && ownerDeleteRouteScope?.serverId === serverId : frame.scope.kind === "me"
+ return valid ? <input data-testid="sidebar" data-server-id={serverId ?? "me"} /> : null
+}
+
+let owner: Awaited<ReturnType<typeof createCommunityQueryOwner>>
+beforeEach(async () => {
+ owner = await createCommunityQueryOwner("viewer-a")
+ mocks.userId = "viewer-a"
+ mocks.segments = ["me", "friends"]
+ mocks.pathname = "/c/me/friends"
+ mocks.breakpoint = "desktop"
+ mocks.channel.mockClear()
+ mocks.push.mockClear()
+ mocks.replace.mockClear()
+})
+
+function tree(serverId: string | null = null) {
+ return <CommunityTestProvider client={owner.client} registry={owner.registry} retainOwner>
+ <CommunityRouteFrame sidebar={<Sidebar key={serverId ?? "me"} serverId={serverId} />}>
+ <div data-testid="main">{mocks.segments.join("/")}</div>
+ </CommunityRouteFrame>
+ </CommunityTestProvider>
+}
+
+describe("common committed community frame", () => {
+ it("retains global nodes and state across me/server and preserves same-server sidebar", () => {
+ const view = render(tree())
+ const rail = view.getByTestId("rail")
+ const home = view.getByTestId("home")
+ const userbar = view.getByTestId("userbar")
+ fireEvent.change(view.getByTestId("rail-state"), { target: { value: "retained" } })
+ for (const [serverId, leaf] of [["a", "one"], ["a", "two"], ["b", "one"], [null, "friends"]] as const) {
+ mocks.segments = serverId ? ["channels", serverId, leaf] : ["me", leaf]
+ mocks.pathname = `/c/${mocks.segments.join("/")}`
+ const previousSidebar = view.queryByTestId("sidebar")
+ const previousServer = previousSidebar?.getAttribute("data-server-id")
+ view.rerender(tree(serverId))
+ expect(view.getByTestId("rail")).toBe(rail)
+ expect(view.getByTestId("home")).toBe(home)
+ expect(view.getByTestId("userbar")).toBe(userbar)
+ expect(view.getByTestId("rail-state")).toHaveValue("retained")
+ if (previousServer === serverId) expect(view.getByTestId("sidebar")).toBe(previousSidebar)
+ expect(owner.registry.runtime.ui.get().currentServerId).toBe(serverId)
+ }
+ act(() => owner.registry.runtime.ws.setState((state) => ({ ...state, accessEpoch: state.accessEpoch + 1 })))
+ expect(view.getByTestId("rail")).toBe(rail)
+ })
+
+ it("ignores ahead-of-commit pathname and gates mismatched sidebar scope", () => {
+ const view = render(tree())
+ mocks.pathname = "/c/channels/b/two"
+ view.rerender(tree("b"))
+ expect(view.queryByTestId("sidebar")).toBeNull()
+ expect(owner.registry.runtime.ui.get().currentServerId).toBeNull()
+ expect(view.getByTestId("main")).toHaveTextContent("me/friends")
+ mocks.segments = ["channels", "b", "two"]
+ view.rerender(tree("b"))
+ expect(view.getByTestId("sidebar")).toHaveAttribute("data-server-id", "b")
+ })
+
+ it("preserves hidden global mobile nodes and rebuilds them for a new account", async () => {
+ mocks.breakpoint = "mobile"
+ mocks.segments = ["me"]
+ const view = render(tree())
+ const home = view.getByTestId("home")
+ const userbar = view.getByTestId("userbar")
+ mocks.segments = ["me", "dm-a"]
+ mocks.pathname = "/c/me/dm-a"
+ view.rerender(tree())
+ expect(view.getByTestId("home")).toBe(home)
+ expect(view.getByTestId("rail").parentElement).toHaveAttribute("inert")
+ expect(view.getByTestId("userbar")).toBe(userbar)
+ expect(userbar.parentElement).toHaveAttribute("aria-hidden", "true")
+ expect(userbar.parentElement).toHaveAttribute("inert")
+ owner = await createCommunityQueryOwner("viewer-b")
+ mocks.userId = "viewer-b"
+ view.rerender(tree())
+ expect(view.getByTestId("home")).not.toBe(home)
+ expect(view.getByTestId("userbar")).not.toBe(userbar)
+ })
+
+ it("takes server content identity from its own segments despite merged slot params", () => {
+ mocks.segments = ["a", "channel-a"]
+ const view = render(<CommunityTestProvider client={owner.client} registry={owner.registry} retainOwner>
+ <CommunityRouteFrame sidebar={null}><ServerContent><span>static child</span></ServerContent></CommunityRouteFrame>
+ </CommunityTestProvider>)
+ expect(mocks.channel).toHaveBeenLastCalledWith({ serverParam: "a", channelId: "channel-a" })
+ mocks.segments = ["a", "settings"]
+ view.rerender(<CommunityTestProvider client={owner.client} registry={owner.registry} retainOwner>
+ <CommunityRouteFrame sidebar={null}><ServerContent><span>static child</span></ServerContent></CommunityRouteFrame>
+ </CommunityTestProvider>)
+ expect(view.getByText("static child")).toBeInTheDocument()
+ expect(view.queryByTestId("channel")).toBeNull()
+ })
+})
diff --git a/src/web/src/components/community/shell/community-route-frame.tsx b/src/web/src/components/community/shell/community-route-frame.tsx
new file mode 100644
index 000000000..9b9277720
--- /dev/null
+++ b/src/web/src/components/community/shell/community-route-frame.tsx
@@ -0,0 +1,43 @@
+"use client"
+
+import { useCallback, useLayoutEffect, useMemo, type ReactNode } from "react"
+import { useSelectedLayoutSegments } from "next/navigation"
+import { useQueryClient } from "@tanstack/react-query"
+import { useCurrentUser } from "@/contexts/community/current-user"
+import { getCommunityRuntime } from "@/stores/community/runtime"
+import { communityServerId } from "@/lib/community/community-route"
+import { createOwnerServerDeleteRouteToken } from "@/lib/community/eject-server"
+import { ShellFrame } from "./shell-frame"
+
+export function CommunityRouteFrame({ sidebar, children }: {
+ sidebar: ReactNode
+ children: ReactNode
+}) {
+ const segments = useSelectedLayoutSegments()
+ const frameHref = segments.length ? `/c/${segments.join("/")}` : "/c"
+ const serverId = communityServerId(frameHref)
+ const queryClient = useQueryClient()
+ const currentUser = useCurrentUser()
+ const ownerDeleteRouteScope = useMemo(() => serverId ? {
+ serverId,
+ token: createOwnerServerDeleteRouteToken(queryClient),
+ } : undefined, [queryClient, serverId])
+ const renderSidebar = useCallback(() => sidebar, [sidebar])
+
+ useLayoutEffect(() => {
+ getCommunityRuntime(queryClient).ui.actions.setCurrentServerId(serverId)
+ }, [queryClient, serverId])
+
+ return (
+ <ShellFrame
+ key={currentUser.id}
+ view={serverId ? "server" : "dm"}
+ activeServerId={serverId ?? undefined}
+ frameHref={frameHref}
+ sidebar={renderSidebar}
+ ownerDeleteRouteScope={ownerDeleteRouteScope}
+ >
+ {children}
+ </ShellFrame>
+ )
+}
diff --git a/src/web/src/components/community/shell/community-shell-layout.tsx b/src/web/src/components/community/shell/community-shell-layout.tsx
index 879cb70eb..8612c1ca9 100644
--- a/src/web/src/components/community/shell/community-shell-layout.tsx
+++ b/src/web/src/components/community/shell/community-shell-layout.tsx
@@ -387,7 +387,7 @@ export function CommunityShellLayout({
data-slot="community-shell-root"
>
{(!isMobileDetail || preserveHiddenMobileModules) && (
- <div className={cn(
+ <div inert={isMobileDetail} aria-hidden={isMobileDetail || undefined} className={cn(
"flex min-h-0",
isInitialDetail && "hidden sm:contents",
isMobileDetail && preserveHiddenMobileModules && "hidden",
@@ -450,6 +450,8 @@ export function CommunityShellLayout({
data-slot="community-sidebar-panel-content"
data-community-mobile-surface={isMobileList ? "list" : undefined}
hidden={isMobileDetail}
+ inert={isMobileDetail}
+ aria-hidden={isMobileDetail || undefined}
className={cn(
"flex min-h-0 min-w-0 flex-1 flex-col",
isInitialDetail && "max-sm:hidden",
@@ -479,6 +481,8 @@ export function CommunityShellLayout({
data-slot="community-main-panel-content"
data-community-mobile-surface={isMobileDetail ? "detail" : undefined}
hidden={isMobileList}
+ inert={isMobileList}
+ aria-hidden={isMobileList || undefined}
className={cn(
"flex min-h-0 flex-1 flex-col",
isInitial && surface === "list" && "max-sm:hidden",
@@ -494,6 +498,8 @@ export function CommunityShellLayout({
<div
ref={userBarOverlayRef}
data-slot="community-user-bar-overlay"
+ inert={isMobileDetail}
+ aria-hidden={isMobileDetail || undefined}
className={cn(
"absolute bottom-0 left-0 z-10",
isDesktop && "w-(--community-desktop-user-bar-width)",
diff --git a/src/web/src/components/community/shell/dm-sidebar-slot.tsx b/src/web/src/components/community/shell/dm-sidebar-slot.tsx
new file mode 100644
index 000000000..e33e6f5cc
--- /dev/null
+++ b/src/web/src/components/community/shell/dm-sidebar-slot.tsx
@@ -0,0 +1,84 @@
+"use client"
+import { useCommunityRuntime } from "@/stores/community/runtime"
+
+
+import { useCallback, useMemo } from "react"
+import { useCommunityRouteFrame } from "./community-route-context"
+import { DmSidebar } from "@/components/community/channels/dm-sidebar"
+import { useCurrentChannelId } from "@/stores/community"
+import { useDms } from "@/hooks/community/use-dms"
+import { useFriends, useFriendsPresence } from "@/hooks/community/use-friends"
+import { useInboxUnreads } from "@/hooks/community/use-inbox"
+// DM-side layout. The DM subtree has no server settings, no channel sidebar,
+// and no `[serverId]` param — everything is scoped to the current user.
+export function DmSidebarSlot() {
+ const { frame } = useCommunityRouteFrame()
+ if (frame.scope.kind !== "me") return null
+ return <MeSidebar />
+}
+
+function MeSidebar() {
+ const communityRuntime = useCommunityRuntime()
+ const { frame } = useCommunityRouteFrame()
+ const pathname = frame.pathname
+ const {
+ dms,
+ isLoading: dmsLoading,
+ } = useDms()
+ const { blocked } = useFriends()
+ const friendRequestCount = useInboxUnreads().friendRequests.length
+ const currentChannelId = useCurrentChannelId()
+
+ // Seed online friends into the global profile map. The endpoint is a subset
+ // of the full WS audience, so it only patches the ids it explicitly returns.
+ useFriendsPresence()
+
+ const machinesActive = pathname === "/c/me/machines"
+ const botsActive = pathname === "/c/me/bots"
+ const friendsActive = pathname === "/c/me/friends"
+
+ // Navigation is intentionally read-neutral. The visible-row observer owns
+ // both optimistic clearing and the durable cursor write.
+ const enterDm = useCallback((id: string) => {
+ communityRuntime.ui.get().uiHandlers.navigatePath?.(`/c/me/${id}`)
+ }, [communityRuntime.ui])
+
+ const onShowFriends = useCallback(() => {
+ communityRuntime.ui.actions.setCurrentChannelId(null)
+ communityRuntime.ui.get().uiHandlers.navigatePath?.("/c/me/friends")
+ }, [communityRuntime.ui])
+
+ const onShowMachines = useCallback(() => {
+ communityRuntime.ui.actions.setCurrentChannelId(null)
+ communityRuntime.ui.get().uiHandlers.navigatePath?.("/c/me/machines")
+ }, [communityRuntime.ui])
+
+ const onShowBots = useCallback(() => {
+ communityRuntime.ui.actions.setCurrentChannelId(null)
+ communityRuntime.ui.get().uiHandlers.navigatePath?.("/c/me/bots")
+ }, [communityRuntime.ui])
+
+ const blockedUserIds = useMemo(
+ () => new Set(blocked.map((b) => b.userId ?? b.id)),
+ [blocked],
+ )
+
+ const sidebar = useCallback(() => (
+ <DmSidebar
+ dms={dms}
+ activeDm={currentChannelId}
+ blockedUserIds={blockedUserIds}
+ loading={dmsLoading}
+ onPickDm={enterDm}
+ onShowFriends={onShowFriends}
+ friendRequestCount={friendRequestCount}
+ onShowMachines={onShowMachines}
+ onShowBots={onShowBots}
+ friendsActive={friendsActive}
+ machinesActive={machinesActive}
+ botsActive={botsActive}
+ />
+ ), [dms, currentChannelId, dmsLoading, blockedUserIds, enterDm, onShowFriends, friendRequestCount, onShowMachines, onShowBots, friendsActive, machinesActive, botsActive])
+
+ return sidebar()
+}
diff --git a/src/web/src/components/community/shell/server-rail-actions.test.ts b/src/web/src/components/community/shell/server-rail-actions.test.ts
index e11ce3a87..68682b259 100644
--- a/src/web/src/components/community/shell/server-rail-actions.test.ts
+++ b/src/web/src/components/community/shell/server-rail-actions.test.ts
@@ -40,4 +40,30 @@ describe("resolveServerRailOverlayAction", () => {
href: "/c/channels/server_1?settings=1",
})
})
+
+ it.each(["settings", "invite"] as const)(
+ "keeps the committed active leaf and unrelated URL state for %s",
+ (overlay) => {
+ expect(resolveServerRailOverlayAction({
+ targetServerId: "server_1",
+ activeServerId: "server_1",
+ overlay,
+ hasActiveOpener: false,
+ publishedHref: "/c/channels/server_1/channel_1?keep=1#message_1",
+ })).toEqual({
+ kind: "navigate",
+ href: `/c/channels/server_1/channel_1?keep=1&${overlay}=1#message_1`,
+ })
+ },
+ )
+
+ it("does not borrow a published leaf from another server", () => {
+ expect(resolveServerRailOverlayAction({
+ targetServerId: "server_1",
+ activeServerId: "server_1",
+ overlay: "settings",
+ hasActiveOpener: false,
+ publishedHref: "/c/channels/server_2/channel_2?keep=1",
+ })).toEqual({ kind: "navigate", href: "/c/channels/server_1?settings=1" })
+ })
})
diff --git a/src/web/src/components/community/shell/server-rail-actions.ts b/src/web/src/components/community/shell/server-rail-actions.ts
index c97f5e89b..c3e48688f 100644
--- a/src/web/src/components/community/shell/server-rail-actions.ts
+++ b/src/web/src/components/community/shell/server-rail-actions.ts
@@ -1,3 +1,5 @@
+import { communityServerId } from "@/lib/community/community-route"
+
export type ServerRailOverlay = "settings" | "invite"
export type ServerRailOverlayAction =
@@ -9,15 +11,23 @@ export function resolveServerRailOverlayAction({
activeServerId,
overlay,
hasActiveOpener,
+ publishedHref,
}: {
targetServerId: string
activeServerId?: string
overlay: ServerRailOverlay
hasActiveOpener: boolean
+ publishedHref?: string
}): ServerRailOverlayAction {
if (targetServerId === activeServerId && hasActiveOpener) {
return { kind: "open-active" }
}
+ if (targetServerId === activeServerId && publishedHref
+ && communityServerId(publishedHref) === targetServerId) {
+ const href = new URL(publishedHref, "https://alook.local")
+ href.searchParams.set(overlay, "1")
+ return { kind: "navigate", href: `${href.pathname}${href.search}${href.hash}` }
+ }
return {
kind: "navigate",
href: `/c/channels/${targetServerId}?${overlay}=1`,
diff --git a/src/web/src/components/community/shell/server-rail.pending.dom.test.ts b/src/web/src/components/community/shell/server-rail.pending.dom.test.ts
index 473077f97..23f9784e7 100644
--- a/src/web/src/components/community/shell/server-rail.pending.dom.test.ts
+++ b/src/web/src/components/community/shell/server-rail.pending.dom.test.ts
@@ -5,6 +5,7 @@ import { renderCommunity as render } from "@/test/community-owner-harness"
import { ServerRail, ServerRailPending, ServerRailSkeleton } from "./server-rail"
import { tid } from "@/lib/community/testids"
import type { RailInstruction } from "@/lib/community/server-rail-model"
+import { resolveServerRailOverlayAction } from "./server-rail-actions"
const mocks = vi.hoisted(() => ({
mutate: vi.fn(),
@@ -292,6 +293,44 @@ describe("ServerRail one-in-flight structural guard", () => {
},
)
+ it.each(["top-level", "folder"] as const)(
+ "keeps retained %s menu callbacks on the latest committed server leaf",
+ async (placement) => {
+ const hrefs: string[] = []
+ const openAt = (activeServerId: string, publishedHref: string, overlay: "settings" | "invite") => (id?: string) => {
+ const action = resolveServerRailOverlayAction({
+ targetServerId: id!,
+ activeServerId,
+ publishedHref,
+ hasActiveOpener: false,
+ overlay,
+ })
+ if (action.kind === "navigate") hrefs.push(action.href)
+ }
+ const menuFolders = placement === "folder" ? [{
+ id: "menu-folder", name: "Menu", position: 0, servers: [servers[0]],
+ }] : []
+ const element = (committed: string) => createElement(ServerRail, {
+ servers, folders: menuFolders, view: "server", activeServerId: "a",
+ onHome: vi.fn(),
+ onOpenSettings: openAt(committed, `/c/channels/${committed}/channel`, "settings"),
+ onOpenInvitePopover: openAt(committed, `/c/channels/${committed}/channel`, "invite"),
+ })
+ const renderer = render(element("b"))
+ if (placement === "folder") {
+ await act(async () => (latestFolderProps("menu-folder").onToggle as () => void)())
+ }
+ const settings = latestSortableProps("a").onOpenSettings as () => void
+ const invite = latestSortableProps("a").onOpenInvitePopover as () => void
+ renderer.rerender(element("a"))
+ await act(async () => { settings(); invite() })
+ expect(hrefs).toEqual([
+ "/c/channels/a/channel?settings=1",
+ "/c/channels/a/channel?invite=1",
+ ])
+ },
+ )
+
it.each([
["empty", 0],
["one", 1],
diff --git a/src/web/src/components/community/shell/server-rail.tsx b/src/web/src/components/community/shell/server-rail.tsx
index f531dc644..2d61d1616 100644
--- a/src/web/src/components/community/shell/server-rail.tsx
+++ b/src/web/src/components/community/shell/server-rail.tsx
@@ -143,7 +143,7 @@ export const ServerRail = memo(function ServerRail({
const [dragSource, setDragSource] = useAtom(useCreateAtom<RailEntity | null>(null))
const [createOpen, setCreateOpen] = useAtom(useCreateAtom(false))
const scrollRef = useRef<HTMLDivElement>(null)
- const serverActivationRef = useRef({ onServer, onServerNavigate })
+ const serverActivationRef = useRef({ onServer, onServerNavigate, onOpenSettings, onOpenInvitePopover })
const railMutation = useServerRailCommit()
const communityRuntime = useCommunityRuntime()
const registry = useOptionalCommunityDbRegistry()
@@ -177,8 +177,8 @@ export const ServerRail = memo(function ServerRail({
} catch {}
}, [storageKey, setExpanded])
useLayoutEffect(() => {
- serverActivationRef.current = { onServer, onServerNavigate }
- }, [onServer, onServerNavigate])
+ serverActivationRef.current = { onServer, onServerNavigate, onOpenSettings, onOpenInvitePopover }
+ }, [onServer, onServerNavigate, onOpenSettings, onOpenInvitePopover])
useEffect(() => {
sessionStorage.setItem(storageKey, JSON.stringify(expanded))
@@ -385,8 +385,8 @@ export const ServerRail = memo(function ServerRail({
active={view !== "dm" && activeId === serverId}
onClick={() => pickServer(serverId)}
onLeave={() => onLeaveServer?.(serverId)}
- onOpenSettings={() => onOpenSettings?.(serverId)}
- onOpenInvitePopover={onOpenInvitePopover ? () => onOpenInvitePopover(serverId) : undefined}
+ onOpenSettings={() => serverActivationRef.current.onOpenSettings?.(serverId)}
+ onOpenInvitePopover={onOpenInvitePopover ? () => serverActivationRef.current.onOpenInvitePopover?.(serverId) : undefined}
dragging={dragging({ kind: "server", id: serverId })}
preview={previewFor({ kind: "server", id: serverId })}
registerItem={registerItem}
@@ -432,8 +432,8 @@ export const ServerRail = memo(function ServerRail({
server={server}
active={view !== "dm" && activeId === server.id}
onClick={() => pickServer(server.id)}
- onOpenSettings={() => onOpenSettings?.(server.id)}
- onOpenInvitePopover={onOpenInvitePopover ? () => onOpenInvitePopover(server.id) : undefined}
+ onOpenSettings={() => serverActivationRef.current.onOpenSettings?.(server.id)}
+ onOpenInvitePopover={onOpenInvitePopover ? () => serverActivationRef.current.onOpenInvitePopover?.(server.id) : undefined}
inFolder
dragging={dragging({ kind: "server", id: server.id })}
preview={previewFor({ kind: "server", id: server.id })}
diff --git a/src/web/src/components/community/shell/server-sidebar-slot.tsx b/src/web/src/components/community/shell/server-sidebar-slot.tsx
new file mode 100644
index 000000000..7cf6407d6
--- /dev/null
+++ b/src/web/src/components/community/shell/server-sidebar-slot.tsx
@@ -0,0 +1,612 @@
+"use client"
+import { useAtom, useCreateAtom, useSelector } from "@tanstack/react-store";
+import { getCommunityRuntime } from "@/stores/community/runtime"
+
+
+import { useCallback, useEffect, useMemo, useRef } from "react"
+import { usePathname, useRouter, useSearchParams } from "next/navigation"
+import { useQueryClient } from "@tanstack/react-query"
+import { toast } from "sonner"
+import { toastApiError } from "@/lib/api/client"
+import { markSwitch } from "@/lib/perf/switch-mark"
+import { Dialog, DialogContent } from "@/components/ui/dialog"
+import { useCommunityRouteFrame } from "./community-route-context"
+import {
+ channelHref,
+ communityServerId,
+ serverModalMarkerCleanupHref,
+ resolveCommunityModulePlan,
+} from "@/lib/community/community-route"
+import { useBreakpoint } from "@/hooks/use-mobile"
+import { ChannelSidebarRevealBoundary } from "@/components/community/channels/channel-sidebar-tree-owner"
+import { ServerSettings } from "@/components/community/settings/server-settings"
+import { ImageCropDialog } from "@/components/community/image-crop-dialog"
+import { validateIconSourceFile } from "@/lib/community/image-crop"
+import type { SettingsSection } from "@/components/community/settings/settings-types"
+import { canManageServer, isForum, notifLevelDisplay, type ChannelType } from "@alook/shared"
+import { readCommunityProfile } from "@/lib/community/profile-read"
+import { useCurrentChannelId, useCurrentChannelMeta } from "@/stores/community"
+import { useCurrentUser } from "@/contexts/community/current-user"
+import {
+ useServer,
+ useServers,
+ serverProjectedQueryFn,
+} from "@/hooks/community/use-servers"
+import { useServerMembers } from "@/hooks/community/use-server-members"
+import {
+ claimOwnerServerDeleteNavigation,
+ consumeVoluntaryLeave,
+ isOwnerServerDeleteRouteProtected,
+ runAuthoritativeServerEject,
+} from "@/lib/community/eject-server"
+import {
+ clearLastChannel,
+ getLastChannel,
+ pickServerLandingHref,
+} from "@/lib/community/last-channel"
+import { communityKeys } from "@/lib/query-keys"
+import { usePresence } from "@/hooks/community/use-server-panels"
+import { useCommunityViewSource } from "@/hooks/community/use-community-view-source"
+import {
+ resolveForumSidebarRouteCandidate,
+ useForumSidebarThreads,
+ type ForumSidebarThread,
+} from "@/hooks/community/use-forum-sidebar-threads"
+import { useCommunityWsStore } from "@/stores/community/ws"
+import {
+ resolveServerNotificationDisplayLevel,
+ useNotificationSettings,
+} from "@/hooks/community/use-notification-settings"
+import {
+ useCreateChannel,
+ useRenameChannel,
+ useDeleteChannel,
+ useMoveChannel,
+ useCreateCategory,
+ useUpdateCategory,
+ useDeleteCategory,
+ useReorderCategories,
+ useReorderChannels,
+ useDeleteServer,
+ useUpdateServer,
+ useUploadServerIcon,
+ useSetServerNotifLevel,
+ useSetMemberRole,
+ useKickMember,
+ useRevokeInvite,
+} from "@/hooks/community/mutations"
+import {
+ useCanonicalProfilesByUserId,
+ useOptionalCommunityDbRegistry,
+ useTrustedRestoredPrimary,
+} from "@/lib/community-db/projections"
+
+export function ServerSidebarSlot({ serverId }: { serverId: string }) {
+ const { frame, ownerDeleteRouteScope } = useCommunityRouteFrame()
+ if (frame.scope.kind !== "server" || frame.scope.serverId !== serverId
+ || ownerDeleteRouteScope?.serverId !== serverId) return null
+ return <ServerSidebar key={serverId} serverId={serverId} />
+}
+
+function ServerSidebar({ serverId }: { serverId: string }) {
+ const { frame, navigation, ownerDeleteRouteScope } = useCommunityRouteFrame()
+ const searchParams = useSearchParams()
+ const pathname = usePathname()
+ const modulePlan = resolveCommunityModulePlan(frame.pathname)
+ const routeChannelId = modulePlan.main.kind === "server-conversation" ? modulePlan.main.leafId : null
+ const queryClient = useQueryClient()
+ const ownerDeleteRouteToken = ownerDeleteRouteScope!.token
+ const ownerDeleteRouteProtected = useSelector(getCommunityRuntime(queryClient).serverEject, (state) => state.transactions.has(serverId) || state.tombstones.get(ownerDeleteRouteToken) === serverId)
+ const hasChannel = !!routeChannelId
+ const breakpoint = useBreakpoint()
+
+ const router = useRouter()
+ const communityDb = useOptionalCommunityDbRegistry()
+ const trustedRestoredPrimary = useTrustedRestoredPrimary()
+ const cancelPendingNavigation = useCallback(() => {
+ getCommunityRuntime(queryClient).ui.get().uiHandlers.cancelPendingNavigation?.()
+ }, [queryClient])
+ const currentUser = useCurrentUser()
+ const serverAccessRevoked = useCommunityWsStore(
+ (state) => state.revokedServerIds.has(serverId),
+ )
+ const {
+ server: currentServer,
+ data: authoritativeServer,
+ } = useServer(ownerDeleteRouteProtected ? null : serverId)
+ const sidebarCategories = useMemo(
+ () => currentServer?.categories ?? [],
+ [currentServer],
+ )
+ const sidebarHintOnly = Boolean(currentServer && !authoritativeServer)
+ const membersHook = useServerMembers(currentServer ? serverId : null)
+ const profilesByUserId = useCanonicalProfilesByUserId()
+ const enrichedMembers = useMemo(
+ () =>
+ membersHook.members.map((m) => {
+ const canonical = profilesByUserId.get(m.userId)
+ const profile = canonical
+ ? readCommunityProfile(canonical, m.userId)
+ : { ...m, presence: m.status }
+ return {
+ ...m,
+ name: profile.name,
+ discriminator: profile.discriminator,
+ avatar: profile.avatar,
+ avatarVersion: profile.avatarVersion,
+ status: m.userId === currentUser.id ? "online" as const : profile.presence,
+ statusEmoji: profile.statusEmoji,
+ statusText: profile.statusText,
+ }
+ }),
+ [currentUser.id, membersHook.members, profilesByUserId],
+ )
+ // `myMember` comes from the raw (not enriched) members list so this stays
+ // stable across presence ticks.
+ const myMember = membersHook.members.find((m) => m.userId === currentUser.id)
+ const isAdmin = canManageServer(myMember?.role)
+ usePresence(currentServer ? serverId : null)
+ const notifs = useNotificationSettings()
+ const notifLevel = resolveServerNotificationDisplayLevel(notifs.server[serverId])
+ const channelNotif = notifs.channel
+ const currentChannelId = useCurrentChannelId()
+ const currentChannelMeta = useCurrentChannelMeta()
+ const activeForumThreadId = useMemo(() => {
+ if (!currentChannelId || !currentChannelMeta?.parentChannelId) return null
+ const parent = sidebarCategories
+ .flatMap((category) => category.channels)
+ .find((channel) => channel.id === currentChannelMeta.parentChannelId)
+ return isForum(parent?.type) ? currentChannelId : null
+ }, [currentChannelId, currentChannelMeta?.parentChannelId, sidebarCategories])
+ const sidebarRouteCandidate = useMemo(() => {
+ const topLevelChannels = sidebarCategories.length > 0
+ ? sidebarCategories.flatMap((category) => category.channels)
+ : null
+ const parent = currentChannelId === routeChannelId && currentChannelMeta?.parentChannelId
+ ? topLevelChannels?.find((channel) => channel.id === currentChannelMeta.parentChannelId)
+ : null
+ return resolveForumSidebarRouteCandidate(
+ routeChannelId,
+ topLevelChannels?.map((channel) => channel.id) ?? null,
+ isForum(parent?.type),
+ )
+ }, [currentChannelId, currentChannelMeta?.parentChannelId, routeChannelId, sidebarCategories])
+ const forumSidebar = useForumSidebarThreads(
+ serverId,
+ sidebarRouteCandidate,
+ !!currentServer?.categories,
+ )
+ const forumThreadsByParent = useMemo(() => {
+ const grouped: Record<string, ForumSidebarThread[]> = {}
+ for (const thread of forumSidebar.threads) {
+ const siblings = grouped[thread.parentChannelId] ?? []
+ siblings.push(thread)
+ grouped[thread.parentChannelId] = siblings
+ }
+ return grouped
+ }, [forumSidebar.threads])
+
+ const serversList = useServers()
+ const serverDestination = useCallback(async (id: string) => {
+ const lastChannel = getLastChannel(id)
+ const read = () => communityDb ? Array.from(communityDb.collections.channels.values()).filter((channel) => channel.serverId === id && channel.type !== "thread" && !channel.pending).map((channel) => channel.id) : []
+ if (!communityDb?.collections.servers.get(id)?.detailComplete && !lastChannel && read().length === 0) {
+ try {
+ await queryClient.fetchQuery({ queryKey: communityKeys.server(id), queryFn: ({ signal }) => serverProjectedQueryFn(queryClient, id, signal)(), staleTime: Infinity })
+ } catch {}
+ }
+ const channelIds = read()
+ return pickServerLandingHref(id, channelIds, lastChannel)
+ }, [communityDb, queryClient])
+
+ // Mutations
+ const createChannelMut = useCreateChannel()
+ const renameChannelMut = useRenameChannel()
+ const deleteChannelMut = useDeleteChannel()
+ const moveChannelMut = useMoveChannel()
+ const createCategoryMut = useCreateCategory()
+ const updateCategoryMut = useUpdateCategory()
+ const deleteCategoryMut = useDeleteCategory()
+ const reorderCategoriesMut = useReorderCategories()
+ const reorderChannelsMut = useReorderChannels()
+ const deleteServerMut = useDeleteServer({
+ routeToken: ownerDeleteRouteToken,
+ onSuccess: ({ serverId: deletedServerId, isUiCurrent }, { needsNavigation }) => {
+ if (isUiCurrent?.()) toast("Server deleted")
+ clearLastChannel(deletedServerId)
+ if (!needsNavigation) return
+ void (async () => {
+ const allowed = new Set([...communityDb!.collections.serverMemberships.values()].filter((row) => row.viewer && row.userId === currentUser.id).map((row) => row.serverId))
+ const survivor = [...communityDb!.collections.servers.values()].filter((server) => allowed.has(server.id)).sort((a, b) => (a.position ?? 0) - (b.position ?? 0)).find((server) => server.id !== deletedServerId)
+ const destination = survivor
+ ? await serverDestination(survivor.id)
+ : "/c/me"
+ if (!isUiCurrent?.()) return
+ if (!claimOwnerServerDeleteNavigation(queryClient,
+ deletedServerId,
+ ownerDeleteRouteToken,
+ destination,
+ )) return
+ cancelPendingNavigation()
+ router.replace(destination)
+ })()
+ },
+ onError: (error, { isUiCurrent }) => { if (isUiCurrent?.()) toastApiError(error, "Failed to delete server", () => { if (!isUiCurrent?.()) throw new DOMException("Retired delete navigation", "AbortError") }) },
+ })
+ const updateServerMut = useUpdateServer()
+ const uploadServerIconMut = useUploadServerIcon()
+ const setServerNotifMut = useSetServerNotifLevel()
+ const setMemberRoleMut = useSetMemberRole()
+ const kickMemberMut = useKickMember()
+ const revokeInviteMut = useRevokeInvite()
+
+ // Eject when the URL is scoped to a server the viewer isn't in. Covers
+ // four triggers with one effect:
+ // 1. Viewer clicked "Leave" (rail button pre-marks the id via
+ // markVoluntaryLeave — we stay silent, the button owns the toast).
+ // 2. Viewer was kicked from another tab (WS member.leave invalidates
+ // `servers()` when userId === viewer, list drops the row).
+ // 3. Owner deleted the server (WS server.delete invalidates same).
+ // 4. Viewer pasted a URL for a server they were never in (list
+ // finishes loading, id is missing from the start).
+ //
+ // Only a settled SUCCESSFUL snapshot can prove absence. `isFetched` is also
+ // true after a first 5xx, while a failed background refetch may retain
+ // last-good data; treating either as authoritative ejects valid URLs on a
+ // transient read failure. The ref prevents a re-fire during navigation.
+ const ejectedRef = useRef(false)
+ useEffect(() => {
+ if (ejectedRef.current) return
+ if (navigation.navigationPending
+ && communityServerId(navigation.pendingHref ?? "") !== serverId) return
+ if (typeof window !== "undefined"
+ && communityServerId(window.location.pathname) !== serverId) return
+ ejectedRef.current = runAuthoritativeServerEject({
+ serverId,
+ servers: serversList.servers,
+ // A target-specific 403/404 is already definitive even if revoking the
+ // target advanced the access epoch and retired an in-flight list read.
+ // A restored list is renderable but its absence is not an access
+ // verdict. Only a live list confirmed for this QueryClient + auth
+ // generation may drive the generic eject path.
+ isSuccess: serverAccessRevoked
+ || (serversList.isSuccess && serversList.isLiveAuthoritative),
+ isFetching: serverAccessRevoked ? false : serversList.isFetching,
+ ownerDeleteRouteProtected: isOwnerServerDeleteRouteProtected(queryClient, serverId),
+ consumeVoluntaryLeave: (id) => consumeVoluntaryLeave(queryClient, id),
+ clearLastChannel,
+ toast,
+ accountId: currentUser.id,
+ routeHref: pathname,
+ replace: (destination) => {
+ cancelPendingNavigation()
+ router.replace(destination)
+ },
+ })
+ }, [cancelPendingNavigation, currentUser.id, navigation.navigationPending, navigation.pendingHref, pathname, serverAccessRevoked, serverId, serversList.isLiveAuthoritative, serversList.isSuccess, serversList.isFetching, serversList.servers, router, searchParams, queryClient])
+ // Reset the guard when the URL changes to a NEW server id — otherwise
+ // navigating server → dangling-server → server would leave the ref
+ // latched and skip the eject.
+ useEffect(() => {
+ ejectedRef.current = false
+ }, [serverId])
+
+ const [serverSettingsOpen, setServerSettingsOpen] = useAtom(useCreateAtom(false))
+ const settingsView = useCommunityViewSource("server-settings:" + serverId, serverSettingsOpen)
+ const [settingsSection, setSettingsSection] = useAtom(useCreateAtom<SettingsSection>("overview"))
+ const [invitePopoverOpen, setInvitePopoverOpen] = useAtom(useCreateAtom(false))
+ const [pendingIconCrop, setPendingIconCrop] = useAtom(useCreateAtom<{ src: string; fileName: string } | null>(null))
+
+ // Close server-scoped dialogs when the user navigates to another server —
+ // without this, settings for server A would remain open after switching
+ // to server B, mixing A's draft with B's loaded metadata.
+ useEffect(() => {
+ setServerSettingsOpen(false)
+ setSettingsSection("overview")
+ setInvitePopoverOpen(false)
+ }, [serverId, setInvitePopoverOpen, setServerSettingsOpen, setSettingsSection])
+
+ // Open the dialog the instant we see the flag — this only touches local
+ // state, so it can't race with the sibling default-channel page's own
+ // redirect below. (Splitting this from the URL cleanup fixes a bug where
+ // waiting to open the dialog until *after* the redirect meant the flag —
+ // and the URL query string carrying it — was already gone by then, so the
+ // dialog silently never opened.)
+ useEffect(() => {
+ if (communityServerId(pathname) !== serverId) return
+ if (searchParams.get("settings") === "1") setServerSettingsOpen(true)
+ if (searchParams.get("invite") === "1") setInvitePopoverOpen(true)
+ }, [pathname, serverId, searchParams, setInvitePopoverOpen, setServerSettingsOpen])
+
+ useEffect(() => {
+ // 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 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.
+ if (ownerDeleteRouteProtected || communityServerId(pathname) !== serverId) return
+ const search = searchParams.toString()
+ const currentHref = `${pathname}${search ? `?${search}` : ""}`
+ const cleanupHref = serverModalMarkerCleanupHref(currentHref, {
+ breakpoint,
+ hasChannel,
+ hasServerChannels: Boolean(
+ currentServer?.categories.some((category) => category.channels.length > 0),
+ ),
+ })
+ if (!cleanupHref) return
+
+ cancelPendingNavigation()
+ router.replace(cleanupHref)
+ }, [
+ breakpoint,
+ serverId,
+ cancelPendingNavigation,
+ searchParams,
+ pathname,
+ router,
+ hasChannel,
+ currentServer,
+ ownerDeleteRouteProtected,
+ ])
+
+ const categories = useMemo(() => sidebarCategories.map((category) => ({
+ ...category,
+ channels: category.channels.map((channel) =>
+ forumSidebar.parentUnread[channel.id] === undefined
+ ? channel
+ : { ...channel, unread: forumSidebar.parentUnread[channel.id] },
+ ),
+ })), [forumSidebar.parentUnread, sidebarCategories])
+ const sidebarDataReady = Boolean(currentServer)
+ const channelTreeScopeKey = `server:${serverId}`
+
+ const setActiveChannel = useCallback((id: string) => {
+ // Only navigate — do NOT eagerly set the store's currentChannelId here.
+ // The currently-mounted ChannelView is still keyed to the old channelId;
+ // flipping the store now triggers its reset effect (messagesLoading=true)
+ // while the URL still points at the OLD channel, so the loading skeleton
+ // renders using the old channel's type for one frame. Letting the newly-
+ // mounted ChannelView sync the store in its own useEffect keeps skeleton
+ // type consistent with the target channel.
+ //
+ // The visible-row observer is the only optimistic/read writer. Navigation
+ // itself must leave account unread state untouched.
+ markSwitch("channel", id)
+ cancelPendingNavigation()
+ getCommunityRuntime(queryClient).ui.get().uiHandlers.navigatePath?.(channelHref(serverId, id))
+ }, [cancelPendingNavigation, queryClient, serverId])
+
+ const setActiveForumThread = useCallback((_parentId: string, id: string) => {
+ markSwitch("channel", id)
+ cancelPendingNavigation()
+ getCommunityRuntime(queryClient).ui.get().uiHandlers.navigatePath?.(
+ channelHref(serverId, id),
+ )
+ }, [cancelPendingNavigation, queryClient, serverId])
+
+ const onSidebarOpenSettings = useCallback((section?: SettingsSection) => {
+ if (section) setSettingsSection(section)
+ setServerSettingsOpen(true)
+ }, [setServerSettingsOpen, setSettingsSection])
+
+
+ const onBlockedCreate = useCallback(() => {
+ toast("Only admins can create channels in a private category")
+ }, [])
+
+ const mutedChannels = useMemo(
+ () => Object.fromEntries(
+ Object.entries(channelNotif).map(([k, v]) => [k, v === notifLevelDisplay("nothing")])
+ ),
+ [channelNotif]
+ )
+
+ const onCreateChannelInSidebar = useCallback(async (categoryId: string, name: string, type: ChannelType) => {
+ try {
+ const res = await createChannelMut.mutateAsync({ serverId, categoryId, name, type })
+ return res.channel.id
+ } catch (e) {
+ toastApiError(e, "Failed to create channel")
+ return null
+ }
+ }, [createChannelMut, serverId])
+ const onCreateCategoryInSidebar = useCallback((name: string, opts?: { private?: boolean }) => {
+ createCategoryMut.mutate(
+ { serverId, name, private: opts?.private },
+ { onError: (e) => toastApiError(e, "Failed to create category") },
+ )
+ }, [createCategoryMut, serverId])
+ const onRenameChannel = useCallback((channelId: string, name: string) => {
+ renameChannelMut.mutate(
+ { serverId, channelId, name },
+ { onError: (e) => toastApiError(e, "Failed to rename channel") },
+ )
+ }, [renameChannelMut, serverId])
+ const onDeleteChannelInSidebar = useCallback((channelId: string) => {
+ deleteChannelMut.mutate({ serverId, channelId }, { onError: (e) => toastApiError(e, "Failed to delete channel") })
+ }, [deleteChannelMut, serverId])
+ const onDeleteCategoryInSidebar = useCallback((categoryId: string) => {
+ deleteCategoryMut.mutate({ serverId, categoryId }, { onError: (e) => toastApiError(e, "Failed to delete category") })
+ }, [deleteCategoryMut, serverId])
+ const onUpdateCategoryInSidebar = useCallback((categoryId: string, opts: { name?: string }) => {
+ updateCategoryMut.mutate({ serverId, categoryId, name: opts.name }, { onError: (e) => toastApiError(e, "Failed to update category") })
+ }, [updateCategoryMut, serverId])
+ const onReorderCategoriesInSidebar = useCallback((categoryIds: string[]) => {
+ reorderCategoriesMut.mutate({ serverId, categoryIds }, { onError: (e) => toastApiError(e, "Failed to save category order") })
+ }, [reorderCategoriesMut, serverId])
+ const onReorderChannelsInSidebar = useCallback((channelIds: string[]) => {
+ reorderChannelsMut.mutate({ serverId, channelIds }, { onError: (e) => toastApiError(e, "Failed to save channel order") })
+ }, [reorderChannelsMut, serverId])
+ const onMoveChannelInSidebar = useCallback((channelId: string, categoryId: string | null) => {
+ moveChannelMut.mutate({ serverId, channelId, categoryId }, { onError: (e) => toastApiError(e, "Failed to move channel") })
+ }, [moveChannelMut, serverId])
+ const onBlockedMove = useCallback(() => {
+ toast("Can't move a channel between public and private categories")
+ }, [])
+
+ const channelProps = useMemo(() => ({
+ serverName: currentServer?.name ?? "",
+ serverIcon: currentServer?.icon ?? null,
+ official: currentServer?.official ?? false,
+ activeChannel: currentChannelMeta?.parentChannelId ?? currentChannelId ?? "",
+ isAdmin,
+ currentUserId: currentUser.id,
+ setActiveChannel,
+ forumThreadsByParent,
+ activeThreadId: activeForumThreadId,
+ onSelectForumThread: setActiveForumThread,
+ onOpenSettings: !sidebarHintOnly && isAdmin ? onSidebarOpenSettings : undefined,
+ onBlockedCreate,
+ mutedChannels,
+ onCreateChannel: sidebarHintOnly ? undefined : onCreateChannelInSidebar,
+ onCreateCategory: sidebarHintOnly ? undefined : onCreateCategoryInSidebar,
+ onRenameChannel: sidebarHintOnly ? undefined : onRenameChannel,
+ onDeleteChannel: sidebarHintOnly ? undefined : onDeleteChannelInSidebar,
+ onDeleteCategory: sidebarHintOnly ? undefined : onDeleteCategoryInSidebar,
+ onUpdateCategory: sidebarHintOnly ? undefined : onUpdateCategoryInSidebar,
+ onReorderCategories: sidebarHintOnly ? undefined : onReorderCategoriesInSidebar,
+ onReorderChannels: sidebarHintOnly ? undefined : onReorderChannelsInSidebar,
+ onMoveChannel: sidebarHintOnly ? undefined : onMoveChannelInSidebar,
+ onBlockedMove,
+ serverId,
+ invitePopoverOpen,
+ onInvitePopoverOpenChange: sidebarHintOnly ? undefined : setInvitePopoverOpen,
+ }), [currentServer?.name, currentServer?.icon, currentServer?.official, currentChannelMeta?.parentChannelId, currentChannelId, isAdmin, currentUser.id, setActiveChannel, forumThreadsByParent, activeForumThreadId, setActiveForumThread, sidebarHintOnly, onSidebarOpenSettings, onBlockedCreate, mutedChannels, onCreateChannelInSidebar, onCreateCategoryInSidebar, onRenameChannel, onDeleteChannelInSidebar, onDeleteCategoryInSidebar, onUpdateCategoryInSidebar, onReorderCategoriesInSidebar, onReorderChannelsInSidebar, onMoveChannelInSidebar, onBlockedMove, serverId, invitePopoverOpen, setInvitePopoverOpen])
+
+ const openProfile = (name: string, e: React.MouseEvent, discriminator?: string, userId?: string) => {
+ // Delegate to the shell's registered openProfile via the community store.
+ getCommunityRuntime(queryClient).ui.get().uiHandlers.openProfile?.(name, e, discriminator, userId)
+ }
+
+ const closeSettings = () => { settingsView.retire(); setServerSettingsOpen(false); setSettingsSection("overview") }
+
+ const sidebar = useCallback((opts: { noHeader?: boolean } = {}) => (
+ <ChannelSidebarRevealBoundary
+ key={channelTreeScopeKey}
+ scopeKey={channelTreeScopeKey}
+ categories={categories}
+ primaryReady={sidebarDataReady}
+ forumProjectionMissing={!forumSidebar.projectionReady}
+ trustedRestoredPrimary={trustedRestoredPrimary}
+ targetServerId={serverId}
+ {...channelProps}
+ {...opts}
+ />
+ ), [
+ categories,
+ channelProps,
+ channelTreeScopeKey,
+ forumSidebar.projectionReady,
+ serverId,
+ sidebarDataReady,
+ trustedRestoredPrimary,
+ ])
+
+ const serverSettingsDialog = (
+ <Dialog open={serverSettingsOpen && !!currentServer && isAdmin} onOpenChange={(o) => { if (!o) closeSettings() }}>
+ <DialogContent className="flex h-dvh max-h-dvh w-screen max-w-none flex-col gap-0 overflow-hidden rounded-none p-0 sm:h-[calc(100vh-4rem)] sm:max-h-180 sm:w-[calc(100vw-4rem)] sm:max-w-4xl sm:rounded-xl" showCloseButton={false}>
+ <ServerSettings
+ isAdmin={isAdmin}
+ section={settingsSection}
+ setSection={setSettingsSection}
+ onClose={closeSettings}
+ serverId={serverId}
+ serverName={currentServer?.name ?? ""}
+ serverDescription={currentServer?.description ?? ""}
+ serverIcon={currentServer?.icon ?? null}
+ members={enrichedMembers}
+ membersLoading={membersHook.loading}
+ membersLoadingMore={membersHook.loadingMore}
+ membersHasMore={membersHook.hasMore}
+ membersTotal={membersHook.total}
+ onLoadMoreMembers={membersHook.loadMore}
+ onSearchMembers={membersHook.searchMembers}
+ onKickMember={(memberId) => {
+ const assert = settingsView.capture()
+ kickMemberMut.mutate({ serverId, memberId, assertActive: assert }, {
+ onSuccess: () => { try { assert(); toast("Member kicked") } catch {} },
+ onError: (e) => toastApiError(e, "Failed to kick member", assert),
+ })
+ }}
+ onSetRole={(memberId, role) => {
+ const assert = settingsView.capture()
+ setMemberRoleMut.mutate({ serverId, memberId, role, assertActive: assert }, {
+ onSuccess: () => { try { assert(); toast("Role updated") } catch {} },
+ onError: (e) => toastApiError(e, "Failed to update role", assert),
+ })
+ }}
+ onRevokeInvite={(code) => {
+ const assert = settingsView.capture()
+ revokeInviteMut.mutate({ serverId, code, assertActive: assert }, {
+ onSuccess: () => { try { assert(); toast("Invite revoked") } catch {} },
+ onError: (e) => toastApiError(e, "Failed to revoke invite", assert),
+ })
+ }}
+ onCopyInvite={(code) => {
+ const assert = settingsView.capture()
+ assert()
+ void navigator.clipboard.writeText(`${window.location.origin}/c/invite/${code}`).then(() => { try { assert(); toast("Invite copied") } catch {} }, (error) => toastApiError(error, "Couldn't copy invite", assert))
+ }}
+ onDeleteServer={async () => {
+ closeSettings()
+ deleteServerMut.mutate({ serverId, isUiCurrent: navigation.captureIntent() })
+ }}
+ onUploadIcon={() => {
+ const input = document.createElement("input")
+ input.type = "file"
+ input.accept = "image/png,image/jpeg,image/webp"
+ input.onchange = () => {
+ const f = input.files?.[0]
+ if (!f) return
+ const check = validateIconSourceFile(f)
+ if (!check.ok) {
+ toast(check.error)
+ return
+ }
+ setPendingIconCrop({ src: URL.createObjectURL(f), fileName: f.name })
+ }
+ input.click()
+ }}
+ onUpdateServer={(name, desc) =>
+ updateServerMut.mutate({ serverId, name, description: desc }, {
+ onSuccess: () => toast("Server updated"),
+ onError: (e) => toastApiError(e, "Failed to update server"),
+ })
+ }
+ notifLevel={notifLevel}
+ onSetNotifLevel={(level) => setServerNotifMut.mutate({ serverId, level }, {
+ onError: (e) => toastApiError(e, "Failed to update notification level"),
+ })}
+ onOpenProfile={openProfile}
+ />
+ </DialogContent>
+ </Dialog>
+ )
+
+ const iconCropDialog = pendingIconCrop && (
+ <ImageCropDialog
+ imageSrc={pendingIconCrop.src}
+ originalFileName={pendingIconCrop.fileName}
+ maskShape="square"
+ onCropped={(file) => {
+ uploadServerIconMut.mutate({ serverId, file }, {
+ onSuccess: () => toast("Server icon updated"),
+ onError: (e) => toastApiError(e, "Failed to upload icon"),
+ })
+ URL.revokeObjectURL(pendingIconCrop.src)
+ setPendingIconCrop(null)
+ }}
+ onCancel={() => {
+ URL.revokeObjectURL(pendingIconCrop.src)
+ setPendingIconCrop(null)
+ }}
+ />
+ )
+
+ return <>{sidebar()}{serverSettingsDialog}{iconCropDialog}</>
+}
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 a7e099200..d8398c55f 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
@@ -15,27 +15,16 @@ describe("ShellFrame public contract", () => {
expectTypeOf<ComponentProps<typeof ShellFrame>>().toEqualTypeOf<ShellFrameProps>()
})
- it("keeps both layout importers on the one public ShellFrame API", () => {
- const channels = readWeb("src/app/c/channels/layout.tsx")
- const dm = readWeb("src/app/c/me/layout.tsx")
-
- for (const source of [channels, dm]) {
- expect(source).toContain(
- 'import { ShellFrame } from "@/components/community/shell/shell-frame"',
- )
- expect(source).toContain("<ShellFrame")
- expect(source).toContain("sidebar={sidebar}")
- expect(source).not.toContain("mobileZone={mobileZone}")
- expect(source).not.toContain("setMobileZone={setMobileZone}")
- expect(source).not.toContain("useState<MobileZone>")
+ it("keeps the one frame above both native slots and content layouts", () => {
+ const frame = readWeb("src/components/community/shell/community-route-frame.tsx")
+ expect(frame).toContain("useSelectedLayoutSegments()")
+ expect(frame).toContain("<ShellFrame")
+ expect(readWeb("src/app/c/community-layout-client.tsx")).toContain("<CommunityRouteFrame")
+ for (const path of ["src/app/c/channels/layout.tsx", "src/app/c/me/layout.tsx"]) {
+ expect(readWeb(path)).not.toContain("<ShellFrame")
}
- expect(channels).toContain('view="server"')
- expect(channels).toContain("activeServerId={serverId}")
- expect(channels).toContain("frameHref={structuralFrameHref}")
- expect(dm).toContain('view="dm"')
- expect(dm).toContain("activeServerId={undefined}")
- expect(dm).toContain("useSelectedLayoutSegments")
- expect(dm).toContain("frameHref={structuralFrameHref}")
+ expect(readWeb("src/app/c/@sidebar/me/layout.tsx")).toContain("<DmSidebarSlot")
+ expect(readWeb("src/app/c/@sidebar/channels/[serverId]/layout.tsx")).toContain("serverId={serverId}")
})
it("keeps shell-frame as orchestration with one public component", () => {
diff --git a/src/web/src/components/community/shell/shell-frame-types.ts b/src/web/src/components/community/shell/shell-frame-types.ts
index b93010541..203e6d0d5 100644
--- a/src/web/src/components/community/shell/shell-frame-types.ts
+++ b/src/web/src/components/community/shell/shell-frame-types.ts
@@ -18,6 +18,7 @@ export type ShellFrameProps = {
}
export type ShellRouter = {
+ captureIntent?: () => () => boolean
push: (href: string) => void
pushImmediate?: (href: string) => void
replace: (href: string) => void
diff --git a/src/web/src/components/community/shell/shell-frame-view.dom.test.ts b/src/web/src/components/community/shell/shell-frame-view.dom.test.ts
index fc6c2ae3a..c141f402a 100644
--- a/src/web/src/components/community/shell/shell-frame-view.dom.test.ts
+++ b/src/web/src/components/community/shell/shell-frame-view.dom.test.ts
@@ -737,10 +737,10 @@ describe("ShellFrameView", () => {
profile,
inbox,
}, createElement("main-content")))
- expect(renderer.container.querySelectorAll("[data-server-rail]")).toHaveLength(0)
- expect(renderer.container.querySelectorAll("[data-user-bar]")).toHaveLength(0)
- expect(renderer.container.querySelectorAll('[data-slot="community-user-bar-overlay"]')).toHaveLength(0)
- expect(renderer.container.querySelectorAll('[data-slot="community-user-bar-underlay"]')).toHaveLength(0)
+ expect(renderer.container.querySelectorAll("[data-server-rail]")).toHaveLength(1)
+ expect(renderer.container.querySelectorAll("[data-user-bar]")).toHaveLength(1)
+ expect(renderer.container.querySelectorAll('[data-slot="community-user-bar-overlay"]')).toHaveLength(1)
+ expect(renderer.container.querySelectorAll('[data-slot="community-user-bar-underlay"]')).toHaveLength(1)
expect(renderer.container.querySelectorAll("[data-app-surface]")).toHaveLength(1)
expect(renderer.container.querySelector("[data-app-surface]")?.className).toContain("rounded-none")
expect(renderer.container.querySelectorAll("main-content")).toHaveLength(1)
@@ -899,6 +899,7 @@ describe("ShellFrameView", () => {
expect(sidebarMounts).toBe(1)
})
+
it("preserves child component identity across the 639 to 640 breakpoint", async () => {
let mounts = 0
function StatefulMain() {
@@ -1229,8 +1230,10 @@ describe("ShellFrameView", () => {
createElement("old-main"),
))
- expect(sidebar).not.toHaveBeenCalled()
- expect(renderer.container.querySelectorAll("old-sidebar")).toHaveLength(0)
+ expect(sidebar).toHaveBeenCalled()
+ expect(renderer.container.querySelectorAll("old-sidebar")).toHaveLength(1)
+ expect(renderer.container.querySelector("old-sidebar")?.parentElement).toHaveAttribute("hidden")
+ expect(renderer.container.querySelector("old-sidebar")?.parentElement).toHaveAttribute("inert")
expect(latestProps(mocks.channelSkeletonProps).targetServerId).toBe("s2")
expect(latestProps(mocks.pendingProps).href).toBe("/c/channels/s2")
@@ -1246,7 +1249,7 @@ describe("ShellFrameView", () => {
expect(renderer.container.querySelector(
'[data-slot="community-main-panel-content"]',
)).toHaveAttribute("hidden")
- expect(sidebar).not.toHaveBeenCalled()
+ expect(sidebar).toHaveBeenCalled()
})
it("renders an inert me sidebar checkpoint for a cold server-to-home target", async () => {
@@ -1273,8 +1276,10 @@ describe("ShellFrameView", () => {
createElement("old-main"),
))
- expect(sidebar).not.toHaveBeenCalled()
- expect(renderer.container.querySelectorAll("old-sidebar")).toHaveLength(0)
+ expect(sidebar).toHaveBeenCalled()
+ expect(renderer.container.querySelectorAll("old-sidebar")).toHaveLength(1)
+ expect(renderer.container.querySelector("old-sidebar")?.parentElement).toHaveAttribute("hidden")
+ expect(renderer.container.querySelector("old-sidebar")?.parentElement).toHaveAttribute("inert")
expect(renderer.container.querySelectorAll("old-main")).toHaveLength(0)
expect(renderer.container.querySelectorAll("[data-dm-sidebar-skeleton]")).toHaveLength(1)
expect(latestProps(mocks.pendingProps).href).toBe("/c/me")
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 d9a8d9a68..1e0aa02f4 100644
--- a/src/web/src/components/community/shell/shell-frame-view.tsx
+++ b/src/web/src/components/community/shell/shell-frame-view.tsx
@@ -97,11 +97,20 @@ export function ShellFrameView({
breakpoint={breakpoint}
surface={surface}
rail={<ServerRail {...rail.railProps} bottomInset={60} />}
- sidebar={checkpoint.sidebar.kind === "server-skeleton"
+ preserveHiddenMobileModules
+ sidebar={<>
+ <div
+ hidden={checkpoint.sidebar.kind !== "keep"}
+ inert={checkpoint.sidebar.kind !== "keep"}
+ aria-hidden={checkpoint.sidebar.kind !== "keep" || undefined}
+ className="flex min-h-0 flex-1 flex-col"
+ >
+ {breakpoint === "desktop" ? sidebar() : sidebar({ noHeader: false })}
+ </div>
+ {checkpoint.sidebar.kind === "server-skeleton"
? <ChannelSidebarSkeleton targetServerId={checkpoint.sidebar.serverId} />
- : checkpoint.sidebar.kind === "me-skeleton"
- ? <DmSidebarSkeleton />
- : breakpoint === "desktop" ? sidebar() : sidebar({ noHeader: false })}
+ : checkpoint.sidebar.kind === "me-skeleton" ? <DmSidebarSkeleton /> : null}
+ </>}
main={checkpoint.main.kind === "target-skeleton" ? (
<CommunityPendingFrame
href={checkpoint.targetHref}
diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsx
index 4d6c528fc..966483aeb 100644
--- a/src/web/src/components/community/shell/shell-frame.tsx
+++ b/src/web/src/components/community/shell/shell-frame.tsx
@@ -19,6 +19,7 @@ import { communityKeys } from "@/lib/query-keys"
import { useCommunityWsStore } from "@/stores/community/ws"
import { useCurrentUser } from "@/contexts/community/current-user"
+import { CommunityRouteContext } from "./community-route-context"
import { ShellFrameView } from "./shell-frame-view"
import { useShellRailController } from "./use-shell-rail-controller"
import { useShellProfileController } from "./use-shell-profile-controller"
@@ -208,11 +209,16 @@ const [committedFrame, setCommittedFrame] = useAtom(useCreateAtom(initialCommitt
extension: userBarExtension.active,
})
}, [daemonUpdate, dispatchUserBarExtension, inbox, profile, userBarExtension.active])
+ useEffect(() => {
+ if (breakpoint !== "mobile" || checkpoint.surface !== "detail" || userBarExtension.active === "none") return
+ dismissUserBarExtension()
+ }, [breakpoint, checkpoint.surface, dismissUserBarExtension, userBarExtension.active])
const dismissNativeBackShellOverlay = useCallback(() => {
+ if (breakpoint === "mobile" && checkpoint.surface === "detail") return false
if (userBarExtension.active === "none") return false
dismissUserBarExtension()
return true
- }, [dismissUserBarExtension, userBarExtension.active])
+ }, [breakpoint, checkpoint.surface, dismissUserBarExtension, userBarExtension.active])
const goBackMobile = useCallback(() => {
if (route.parentPath) navigation.replace(route.parentPath)
}, [navigation, route.parentPath])
@@ -260,6 +266,7 @@ const [committedFrame, setCommittedFrame] = useAtom(useCreateAtom(initialCommitt
}, [goBackMobile, profile.openProfile, profile.previewAttachment, profile.previewImage, rail.navigate, navigation.cancelPendingNavigation, navigation.push, navigation.replace, queryClient])
return (
+ <CommunityRouteContext value={{ frame: committedFrame, navigation, ownerDeleteRouteScope }}>
<ShellFrameView
breakpoint={breakpoint}
checkpoint={checkpoint}
@@ -277,5 +284,6 @@ const [committedFrame, setCommittedFrame] = useAtom(useCreateAtom(initialCommitt
>
{children}
</ShellFrameView>
+ </CommunityRouteContext>
)
}
diff --git a/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts b/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts
index b92ebbae3..96eacc695 100644
--- a/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts
+++ b/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts
@@ -198,6 +198,36 @@ describe("Shell input and explicit navigation ownership", () => {
expect(mocks.push).toHaveBeenCalledExactlyOnceWith(nextTarget)
})
+ it("retires a captured UI intent on any newer intent and does not revive it at the same URL", () => {
+ const shell = renderShell("desktop")
+ const current = shell.navigation.captureIntent()
+ expect(current()).toBe(true)
+ act(() => shell.navigation.push(nextTarget))
+ expect(current()).toBe(false)
+ shell.commit(nextTarget, 1)
+ shell.commit("/c/channels/s1/a", 2)
+ expect(current()).toBe(false)
+ const returned = shell.navigation.captureIntent()
+ expect(returned()).toBe(true)
+ shell.commit("/c/me/friends", 3)
+ expect(returned()).toBe(false)
+ })
+
+ it("does not clear a newer pending checkpoint when an older resolver rejects", async () => {
+ const shell = renderShell("desktop")
+ let reject!: (error: Error) => void
+ const delayed = new Promise<string>((_, fail) => { reject = fail })
+ let result!: Promise<boolean>
+ act(() => { result = shell.navigation.resolveAndPush(() => delayed) })
+ fireEvent.click(screen.getByRole("button", { name: "New destination" }))
+ await act(async () => {
+ reject(new Error("old resolver failed"))
+ await expect(result).rejects.toThrow("old resolver failed")
+ })
+ expect(shell.navigation.pendingHref).toBe(nextTarget)
+ expect(shell.navigation.navigationPending).toBe(true)
+ })
+
it("settles an exact frame without an extra click while retaining the independent proof", () => {
const shell = renderShell()
const proof = beginInboxNavigation(shell)
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
index 9479cd1e4..0ea26944e 100644
--- a/src/web/src/components/community/shell/use-community-navigation-controller.ts
+++ b/src/web/src/components/community/shell/use-community-navigation-controller.ts
@@ -1,7 +1,7 @@
"use client"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useCallback, useEffect, useRef } from "react"
+import { useCallback, useEffect, useLayoutEffect, useRef } from "react"
import { flushSync } from "react-dom"
import { usePathname, useRouter, useSearchParams } from "next/navigation"
import { useQueryClient } from "@tanstack/react-query"
@@ -20,6 +20,7 @@ import type { ShellRouter } from "./shell-frame-types"
import { cancelActiveConversationNavigationProof } from "@/lib/community/conversation-navigation-proof"
export type CommunityNavigationController = {
+ captureIntent: () => () => boolean
publishedHref: string
navigationPending: boolean
pendingHref: string | null
@@ -40,6 +41,19 @@ export function useCommunityNavigationController(
const publishedHref = search ? `${pathname}?${search}` : pathname
const queryClient = useQueryClient()
const gateRef = useRef(createNavigationIntentGate())
+ const mountedRef = useRef(false)
+ useLayoutEffect(() => {
+ mountedRef.current = true
+ return () => { mountedRef.current = false }
+ }, [])
+ const committedFrameRef = useRef(committedFrame)
+ useLayoutEffect(() => { committedFrameRef.current = committedFrame }, [committedFrame])
+ const captureIntent = useCallback(() => {
+ const revision = gateRef.current.revision
+ const frameRevision = committedFrameRef.current.revision
+ return () => mountedRef.current && revision === gateRef.current.revision
+ && frameRevision === committedFrameRef.current.revision
+ }, [])
const pendingBaselineRevisionRef = useRef(committedFrame.revision)
const pendingBaselineLeafRef = useRef(committedFrame.leafKey)
const [navigationPending, setNavigationPending] = useAtom(useCreateAtom(false))
@@ -124,8 +138,7 @@ export function useCommunityNavigationController(
pendingBaselineLeafRef.current = committedFrame.leafKey
setNavigationPending(true)
setPendingHref(null)
- try {
- return await commitLatestNavigationIntent(gateRef.current, resolve, (href) => {
+ const operation = commitLatestNavigationIntent(gateRef.current, resolve, (href) => {
if (href === publishedHref) {
setNavigationPending(false)
setPendingHref(null)
@@ -133,15 +146,21 @@ export function useCommunityNavigationController(
}
setPendingHref(href)
router.push(href)
- })
+ })
+ const revision = gateRef.current.revision
+ try {
+ return await operation
} catch (error) {
- setNavigationPending(false)
- setPendingHref(null)
+ if (gateRef.current.revision === revision) {
+ setNavigationPending(false)
+ setPendingHref(null)
+ }
throw error
}
}, [committedFrame.leafKey, committedFrame.revision, publishedHref, queryClient, router, setNavigationPending, setPendingHref])
return {
+ captureIntent,
publishedHref,
navigationPending,
pendingHref,
diff --git a/src/web/src/components/community/shell/use-server-rail-pdd.behavior.dom.test.ts b/src/web/src/components/community/shell/use-server-rail-pdd.behavior.dom.test.ts
index 3cf4cc039..c298b1719 100644
--- a/src/web/src/components/community/shell/use-server-rail-pdd.behavior.dom.test.ts
+++ b/src/web/src/components/community/shell/use-server-rail-pdd.behavior.dom.test.ts
@@ -111,6 +111,7 @@ function rect(top: number, bottom: number, left = 0, right = 40): Rect {
class FakeElement extends FakeEventTarget {
scrollTop = 0
+ scrollLeft = 0
isConnected = true
clickCount = 0
lastClickEvent: FakeMouseEvent | null = null
@@ -541,6 +542,7 @@ describe("useServerRailPdd behavior", () => {
expect(scrollMove.defaultPrevented).toBe(false)
touch(a.handle, "touchstart", [point(3, 10, 10)])
+ hook.scroll.scrollTop += 1
hook.scroll.dispatch("scroll")
touch(a.handle, "touchmove", [point(3, 10, 30)])
expect(hook.callbacks.onDragStart).not.toHaveBeenCalled()
@@ -650,6 +652,38 @@ describe("useServerRailPdd behavior", () => {
expect(a.handle.lastClickEvent?.defaultPrevented).toBe(false)
})
+ it("keeps a stationary hold when a prior scroll notification arrives after touchstart", async () => {
+ const hook = await renderHook()
+ const a = register(hook.current, { kind: "server", id: "a" }, rect(0, 40))
+ const b = register(hook.current, { kind: "server", id: "b" }, rect(80, 120))
+ hook.scroll.scrollTop = 349
+ touch(a.handle, "touchstart", [point(1, 20, 10)])
+ hook.scroll.dispatch("scroll")
+ await act(async () => vi.advanceTimersByTime(SERVER_RAIL_TOUCH_HOLD_MS))
+ fakeDocument.points = [b.element]
+ const move = touch(a.handle, "touchmove", [point(1, 20, 100)])
+ expect(move.defaultPrevented).toBe(true)
+ expect(hook.callbacks.onDragStart).toHaveBeenCalledWith(a.entity)
+ expect(fakeDocument.body.children.filter((element) => !element.removed)).toHaveLength(1)
+ touch(a.handle, "touchend", [], [point(1, 20, 100)])
+ expect(hook.callbacks.onDrop).toHaveBeenCalled()
+ })
+
+ it.each(["scrollTop", "scrollLeft"] as const)("cancels a hold when %s changes after touchstart", async (offset) => {
+ const hook = await renderHook()
+ const a = register(hook.current, { kind: "server", id: "a" }, rect(0, 40))
+ register(hook.current, { kind: "server", id: "b" }, rect(80, 120))
+ hook.scroll[offset] = 349
+ touch(a.handle, "touchstart", [point(1, 20, 10)])
+ hook.scroll[offset] += 1
+ hook.scroll.dispatch("scroll")
+ await act(async () => vi.advanceTimersByTime(SERVER_RAIL_TOUCH_HOLD_MS))
+ const move = touch(a.handle, "touchmove", [point(1, 20, 100)])
+ expect(move.defaultPrevented).toBe(false)
+ expect(hook.callbacks.onDragStart).not.toHaveBeenCalled()
+ expect(fakeDocument.body.children).toHaveLength(0)
+ })
+
it("drags by touch through every hit region and owns edge scroll only after hold", async () => {
const hook = await renderHook()
hook.scroll.bounds = rect(0, 100, 0, 56)
diff --git a/src/web/src/components/community/shell/use-server-rail-pdd.ts b/src/web/src/components/community/shell/use-server-rail-pdd.ts
index 1c62e04a1..99ab8006e 100644
--- a/src/web/src/components/community/shell/use-server-rail-pdd.ts
+++ b/src/web/src/components/community/shell/use-server-rail-pdd.ts
@@ -204,6 +204,8 @@ export function useServerRailPdd({
identifier: number
startX: number
startY: number
+ startScrollTop: number
+ startScrollLeft: number
clientX: number
clientY: number
armX: number
@@ -479,6 +481,8 @@ export function useServerRailPdd({
identifier: touch.identifier,
startX: touch.clientX,
startY: touch.clientY,
+ startScrollTop: scrollRef.current?.scrollTop ?? 0,
+ startScrollLeft: scrollRef.current?.scrollLeft ?? 0,
clientX: touch.clientX,
clientY: touch.clientY,
armX: touch.clientX,
@@ -641,7 +645,7 @@ export function useServerRailPdd({
cleanupTarget()
cleanupDraggable()
}
- }, [begin, cancelActive, clearTouch, finishDrop, handleKeyboardCommand, itemAtPoint, runTouchFrame, setPreview])
+ }, [begin, cancelActive, clearTouch, finishDrop, handleKeyboardCommand, itemAtPoint, runTouchFrame, scrollRef, setPreview])
useEffect(() => monitorForElements({
canMonitor: ({ source }) => railEntityFromData(source.data) !== null,
@@ -669,7 +673,10 @@ export function useServerRailPdd({
if (!element) return
const cancelPendingTouchForNativeScroll = () => {
const pending = touchRef.current
- if (pending && !pending.dragging) clearTouch()
+ if (pending && !pending.dragging && (
+ element.scrollTop !== pending.startScrollTop
+ || element.scrollLeft !== pending.startScrollLeft
+ )) clearTouch()
}
element.addEventListener("scroll", cancelPendingTouchForNativeScroll, { passive: true })
const cleanupAutoScroll = autoScrollForElements({
diff --git a/src/web/src/components/community/shell/use-shell-daemon-update-controller.dom.test.ts b/src/web/src/components/community/shell/use-shell-daemon-update-controller.dom.test.ts
index e7ea80ec3..f44eff77e 100644
--- a/src/web/src/components/community/shell/use-shell-daemon-update-controller.dom.test.ts
+++ b/src/web/src/components/community/shell/use-shell-daemon-update-controller.dom.test.ts
@@ -1,6 +1,8 @@
import { createElement, useReducer } from "react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act, render as rtlRender } from "@/test/react-dom-harness"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
import type { MachineSummary } from "@/hooks/community/use-machines"
import {
daemonUpdateCollapseStorageKey,
@@ -49,6 +51,9 @@ function machine(
}
}
+let owner: Awaited<ReturnType<typeof createCommunityQueryOwner>>
+const render: typeof rtlRender = (node, options) => rtlRender(node, { ...options, wrapper: ({ children }) => createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "user-1", retainOwner: true }, children) })
+
type Controller = ReturnType<typeof useShellDaemonUpdateController>
type Snapshot = { state: UserBarExtensionState; controller: Controller }
@@ -93,11 +98,14 @@ async function renderController({
onResult: (snapshot) => { current = snapshot },
})
await act(async () => {
- renderer = rtlRender(element())
+ renderer = render(element())
})
return {
get current() { return current },
- rerender: async () => act(async () => renderer.rerender(element())),
+ rerender: async (nextVersion?: string) => {
+ if (nextVersion !== undefined) version = nextVersion
+ await act(async () => renderer.rerender(element()))
+ },
unmount: () => renderer.unmount(),
}
}
@@ -117,7 +125,8 @@ function activeUpdate(values: Partial<NonNullable<UserBarExtensionState["update"
}
describe("useShellDaemonUpdateController", () => {
- beforeEach(() => {
+ beforeEach(async () => {
+ owner = await createCommunityQueryOwner("user-1")
window.localStorage.clear()
mocks.warn.mockReset()
mocks.machines = { machines: [], isSuccess: true }
@@ -136,7 +145,7 @@ describe("useShellDaemonUpdateController", () => {
let renderer!: ReturnType<typeof rtlRender>
await act(async () => {
- renderer = rtlRender(createElement(Capture, {
+ renderer = render(createElement(Capture, {
initialState: initialUserBarExtensionState,
onResult: (snapshot) => { current = snapshot },
}))
@@ -231,6 +240,61 @@ describe("useShellDaemonUpdateController", () => {
})
})
+ it.each(["release", "authentication"] as const)("retires a late batch on %s replacement", async (retirement) => {
+ mocks.machines = { machines: [machine("machine-1")], isSuccess: true }
+ let resolve!: () => void
+ const held = new Promise<void>((done) => { resolve = done })
+ const hook = await renderController({ initialState: activeUpdate(), requestUpdate: () => held })
+ let request!: Promise<void>
+ act(() => { request = hook.current.controller.request() })
+ if (retirement === "release") await hook.rerender("0.1.36")
+ else act(() => owner.registry.authenticationView.setState((state) => ({ active: false, generation: state.generation + 1 })))
+ await act(async () => { resolve(); await request })
+ expect(hook.current.state.update?.acceptedMachineIds ?? []).toEqual([])
+ if (retirement === "release") expect(hook.current.state.update?.pendingMachineIds).toEqual([])
+ })
+
+ it("retires an ineligible target from its original pending batch even if it becomes eligible again", async () => {
+ mocks.machines = { machines: [machine("machine-1"), machine("machine-2")], isSuccess: true }
+ let resolve!: () => void
+ const held = new Promise<void>((done) => { resolve = done })
+ const requestUpdate = vi.fn((_machineId: string) => held)
+ const hook = await renderController({
+ initialState: activeUpdate({ targetMachineIds: ["machine-1", "machine-2"] }),
+ requestUpdate,
+ })
+ let request!: Promise<void>
+ act(() => { request = hook.current.controller.request() })
+ expect(hook.current.state.update?.pendingMachineIds).toEqual(["machine-1", "machine-2"])
+
+ mocks.machines = { machines: [machine("machine-2")], isSuccess: true }
+ await hook.rerender()
+ expect(hook.current.state.update?.pendingMachineIds).toEqual(["machine-2"])
+ mocks.machines = { machines: [machine("machine-1"), machine("machine-2")], isSuccess: true }
+ await hook.rerender()
+ await act(async () => { resolve(); await request })
+
+ expect(requestUpdate.mock.calls).toEqual([["machine-1"], ["machine-2"]])
+ expect(hook.current.state.update?.acceptedMachineIds).toEqual(["machine-2"])
+ expect(hook.current.state.update?.failedMachineIds).toEqual([])
+ expect(hook.current.state.update?.pendingMachineIds).toEqual([])
+ expect(hook.current.state.update?.targetMachineIds).toEqual(["machine-1", "machine-2"])
+ expect(mocks.warn).not.toHaveBeenCalled()
+ hook.unmount()
+ })
+
+ it("settles its same-account batch across unrelated community permission changes", async () => {
+ mocks.machines = { machines: [machine("machine-1")], isSuccess: true }
+ let resolve!: () => void
+ const held = new Promise<void>((done) => { resolve = done })
+ const hook = await renderController({ initialState: activeUpdate(), requestUpdate: () => held })
+ let request!: Promise<void>
+ act(() => { request = hook.current.controller.request() })
+ act(() => owner.registry.runtime.ws.setState((state) => ({ ...state, accessEpoch: state.accessEpoch + 1 })))
+ await act(async () => { resolve(); await request })
+ expect(hook.current.state.update?.acceptedMachineIds).toEqual(["machine-1"])
+ })
+
it("does not dispatch without update state, with pending requests, or with no requestable target", async () => {
const requestUpdate = vi.fn(async () => {})
mocks.machines = { machines: [], isSuccess: false }
diff --git a/src/web/src/components/community/shell/use-shell-daemon-update-controller.ts b/src/web/src/components/community/shell/use-shell-daemon-update-controller.ts
index 203773b0b..ee2552196 100644
--- a/src/web/src/components/community/shell/use-shell-daemon-update-controller.ts
+++ b/src/web/src/components/community/shell/use-shell-daemon-update-controller.ts
@@ -1,11 +1,12 @@
"use client"
-import { useCallback, useEffect, useMemo, type Dispatch } from "react"
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, type Dispatch } from "react"
import { parseReleaseVersion } from "@alook/shared"
import {
eligibleDaemonUpdateMachines,
requestMachineUpdate,
} from "@/components/daemon-update-notice"
+import { useCommunityMutationOrigin } from "@/hooks/community/community-origin"
import { useMachines } from "@/hooks/community/use-machines"
import { log } from "@/lib/logger"
import type {
@@ -91,6 +92,9 @@ export function useShellDaemonUpdateController({
latestDaemonVersion?: string
requestUpdate?: (machineId: string) => Promise<unknown>
}) {
+ const origin = useCommunityMutationOrigin()
+ const batchRef = useRef<{ machineIds: Set<string> } | null>(null)
+ useLayoutEffect(() => () => { batchRef.current = null }, [origin.registry, userId, latestDaemonVersion])
const machines = useMachines()
const eligibleMachines = useMemo(() => (
latestDaemonVersion
@@ -101,6 +105,19 @@ export function useShellDaemonUpdateController({
() => eligibleMachines.map((machine) => machine.id),
[eligibleMachines],
)
+ useLayoutEffect(() => {
+ const eligible = new Set(eligibleMachineIds)
+ for (const id of batchRef.current?.machineIds ?? []) {
+ if (!eligible.has(id)) batchRef.current?.machineIds.delete(id)
+ }
+ }, [eligibleMachineIds])
+ const updateScope = useMemo(() => ({ registry: origin.registry, userId, latestDaemonVersion }), [origin.registry, userId, latestDaemonVersion])
+ const previousScope = useRef(updateScope)
+ useEffect(() => {
+ if (previousScope.current === updateScope) return
+ previousScope.current = updateScope
+ dispatch({ type: "update.clear" })
+ }, [dispatch, updateScope])
const update = extensionState.update
useEffect(() => {
@@ -139,13 +156,25 @@ export function useShellDaemonUpdateController({
if (!current || current.pendingMachineIds.length > 0) return
const machineIds = daemonUpdateRequestMachineIds(current, eligibleMachineIds)
if (machineIds.length === 0) return
+ const token = origin.begin().token
+ const authentication = origin.registry!.authenticationView.get()
+ origin.assertOwner(token)
+ const batch = { machineIds: new Set(machineIds) }
+ batchRef.current = batch
dispatch({ type: "update.dispatch", machineIds })
const result = await dispatchMachineUpdateRequests(machineIds, requestUpdate)
+ try { origin.assertOwner(token) } catch { return }
+ const currentAuthentication = origin.registry!.authenticationView.get()
+ if (!currentAuthentication.active || currentAuthentication.generation !== authentication.generation) return
+ if (batchRef.current !== batch) return
+ const pending = batch.machineIds
+ result.acceptedMachineIds = result.acceptedMachineIds.filter((id) => pending.has(id))
+ result.failedMachineIds = result.failedMachineIds.filter((id) => pending.has(id))
for (const machineId of result.failedMachineIds) {
log.warn("daemon update request failed", { machineId })
}
dispatch({ type: "update.settle", ...result })
- }, [dispatch, eligibleMachineIds, extensionState.update, requestUpdate])
+ }, [dispatch, eligibleMachineIds, extensionState.update, requestUpdate, origin])
return {
eligibleMachines,
diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts b/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts
index 85534f8c3..e591de2b3 100644
--- a/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts
+++ b/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts
@@ -117,10 +117,11 @@ function Capture({ options, onResult }: {
}
const realDocument = document
-async function renderController() {
+async function renderController(overrides: Partial<Parameters<typeof useShellProfileController>[0]> = {}) {
const rtlContainer = realDocument.createElement("div")
const pushed: string[] = []
const router = {
+ captureIntent: () => () => true,
push: vi.fn((href: string) => { pushed.push(href) }),
replace: vi.fn(),
prefetch: vi.fn(),
@@ -139,6 +140,7 @@ async function renderController() {
cancelPendingNavigation,
view: "server",
activeServerId: "s1",
+ ...overrides,
} as never,
onResult: (result) => { current = result },
})
@@ -445,6 +447,21 @@ describe("useShellProfileController", () => {
expect(hook.cancelPendingNavigation).toHaveBeenCalledOnce()
})
+ it("passes the captured intent through deferred DM error display within the same view", async () => {
+ const hook = await renderController()
+ let current = true
+ hook.router.captureIntent = () => () => current
+ const error = new Error("DM rejected")
+ mocks.createDm.mockRejectedValueOnce(error)
+ await act(async () => hook.current.profileMessage("remote", ""))
+ expect(mocks.toastApiError).toHaveBeenLastCalledWith(error, "Failed to open DM", expect.any(Function))
+ const assert = mocks.toastApiError.mock.calls.at(-1)![2] as () => void
+ expect(() => assert()).not.toThrow()
+ current = false
+ expect(() => assert()).toThrow("Retired profile navigation")
+ expect(hook.router.push).not.toHaveBeenCalled()
+ })
+
it("opens empty-text DMs, does not await accepted commits, and blocks rejected sends", async () => {
mocks.createDm.mockResolvedValue({ conversation: { id: "dm1" } })
const hook = await renderController()
@@ -610,6 +627,63 @@ describe("useShellProfileController", () => {
)
})
+ it("retires the original crop across server scopes without granting a new source", async () => {
+ let input!: { files?: File[]; onchange?: () => void; click: () => void }
+ vi.stubGlobal("document", { createElement: () => (input = { click: vi.fn() }) })
+ const revoke = vi.fn()
+ let id = 0
+ vi.stubGlobal("URL", { createObjectURL: () => `blob:avatar-${++id}`, revokeObjectURL: revoke })
+ const options = { activeServerId: "s1" }
+ const hook = await renderController(options)
+ const select = async () => {
+ await act(async () => hook.current.userSettingsProps.onUploadAvatar())
+ input.files = [new File(["image"], "avatar.png", { type: "image/png" })]
+ await act(async () => input.onchange?.())
+ }
+ await select()
+ const original = hook.current.pendingAvatarCrop!
+ options.activeServerId = "s2"
+ await hook.rerender()
+ expect(hook.current.pendingAvatarCrop).toBeNull()
+ expect(revoke).toHaveBeenCalledExactlyOnceWith("blob:avatar-1")
+ await select()
+ const replacement = hook.current.pendingAvatarCrop!
+ await act(async () => {
+ original.onCropped(new File(["crop"], "old.png"))
+ original.onCancel()
+ })
+ expect(mocks.uploadAvatar).not.toHaveBeenCalled()
+ expect(hook.current.pendingAvatarCrop?.imageSrc).toBe(replacement.imageSrc)
+ expect(revoke).toHaveBeenCalledTimes(1)
+ await act(async () => replacement.onCropped(new File(["crop"], "new.png")))
+ expect(mocks.uploadAvatar).toHaveBeenCalledOnce()
+ expect(revoke.mock.calls).toEqual([["blob:avatar-1"], ["blob:avatar-2"]])
+ })
+
+ it("an older same-source completion and cancel cannot clear or upload the replacement crop", async () => {
+ let input!: { files?: File[]; onchange?: () => void; click: () => void }
+ vi.stubGlobal("document", { createElement: () => (input = { click: vi.fn() }) })
+ const revoke = vi.fn()
+ let id = 0
+ vi.stubGlobal("URL", { createObjectURL: () => `blob:avatar-${++id}`, revokeObjectURL: revoke })
+ const hook = await renderController()
+ const select = async () => {
+ await act(async () => hook.current.userSettingsProps.onUploadAvatar())
+ input.files = [new File(["image"], "avatar.png", { type: "image/png" })]
+ await act(async () => input.onchange?.())
+ }
+ await select()
+ const original = hook.current.pendingAvatarCrop!
+ await select()
+ const replacement = hook.current.pendingAvatarCrop!
+ await act(async () => { original.onCancel(); original.onCropped(new File(["old"], "old.png")) })
+ expect(hook.current.pendingAvatarCrop?.imageSrc).toBe(replacement.imageSrc)
+ expect(mocks.uploadAvatar).not.toHaveBeenCalled()
+ await act(async () => replacement.onCropped(new File(["new"], "new.png")))
+ expect(mocks.uploadAvatar).toHaveBeenCalledOnce()
+ expect(revoke.mock.calls).toEqual([["blob:avatar-1"], ["blob:avatar-2"]])
+ })
+
it("rejects invalid avatar files before object URL creation", async () => {
let input: { files?: File[]; onchange?: () => void; click: () => void } | undefined
const createObjectURL = vi.fn(() => "blob:invalid")
diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.ts b/src/web/src/components/community/shell/use-shell-profile-controller.ts
index e7dee4bdc..df341b4be 100644
--- a/src/web/src/components/community/shell/use-shell-profile-controller.ts
+++ b/src/web/src/components/community/shell/use-shell-profile-controller.ts
@@ -4,7 +4,7 @@ import { useAtom, useCreateAtom } from "@tanstack/react-store";
import { useCommunityRuntime } from "@/stores/community/runtime"
-import { useCallback, useMemo, type ComponentProps } from "react"
+import { useCallback, useLayoutEffect, useMemo, type ComponentProps } from "react"
import { useQuery } from "@tanstack/react-query"
import { useCanonicalCommunityProfile } from "@/lib/community-db/projections"
import { useCommunityViewSource } from "@/hooks/community/use-community-view-source"
@@ -94,10 +94,28 @@ export function useShellProfileController({
const [profileTarget, setProfile] = useAtom(useCreateAtom<ShellProfileState | null>(null))
const [preview, setPreview] = useAtom(useCreateAtom<ImagePreview | null>(null))
const [attachmentPreview, setAttachmentPreview] = useAtom(useCreateAtom<FileAttachment | null>(null))
- const [pendingAvatarCrop, setPendingAvatarCrop] = useAtom(useCreateAtom<{
+ const avatarCropTask = useCreateAtom<{
src: string
fileName: string
- } | null>(null))
+ assertActive: ReturnType<typeof source.capture>
+ release: () => void
+ } | null>(null)
+ const [pendingAvatarCrop, setPendingAvatarCrop] = useAtom(avatarCropTask)
+ const finishAvatarCrop = useCallback((task: NonNullable<typeof pendingAvatarCrop>) => {
+ task.release()
+ setPendingAvatarCrop((current) => current === task ? null : current)
+ }, [setPendingAvatarCrop])
+ useLayoutEffect(() => {
+ if (!pendingAvatarCrop) return
+ const task = pendingAvatarCrop
+ const retire = () => finishAvatarCrop(task)
+ if (task.assertActive.signal.aborted) retire()
+ else task.assertActive.signal.addEventListener("abort", retire, { once: true })
+ return () => {
+ task.assertActive.signal.removeEventListener("abort", retire)
+ task.release()
+ }
+ }, [finishAvatarCrop, pendingAvatarCrop])
const profileUserId = profileTarget?.data.userId
const canonicalProfile = useCanonicalCommunityProfile(profileUserId)
useQuery({ queryKey: communityKeys.profile(profileUserId ?? "__none__"), enabled: !!profileUserId && profileUserId !== currentUser.id,
@@ -208,13 +226,18 @@ export function useShellProfileController({
return
}
cancelPendingNavigation()
+ const intentCurrent = router.captureIntent?.() ?? (() => true)
+ const assertUi = () => {
+ assert()
+ if (!intentCurrent()) throw new DOMException("Retired profile navigation", "AbortError")
+ }
let dmId: string
try {
const data = await createOrGetDm.mutateAsync({ userId, assertActive: assert })
- assert()
+ assertUi()
dmId = data.conversation.id
} catch (error) {
- toastApiError(error, "Failed to open DM", assert)
+ toastApiError(error, "Failed to open DM", assertUi)
return
}
const trimmed = text.trim()
@@ -252,7 +275,15 @@ export function useShellProfileController({
toast(check.error)
return
}
- setPendingAvatarCrop({ src: URL.createObjectURL(file), fileName: file.name })
+ const src = URL.createObjectURL(file)
+ let released = false
+ const release = () => {
+ if (released) return
+ released = true
+ URL.revokeObjectURL(src)
+ }
+ avatarCropTask.get()?.release()
+ setPendingAvatarCrop({ src, fileName: file.name, assertActive: assert, release })
}
input.click()
}
@@ -312,7 +343,10 @@ export function useShellProfileController({
imageSrc: pendingAvatarCrop.src,
originalFileName: pendingAvatarCrop.fileName,
onCropped: (file) => {
- const assert = source.capture()
+ const task = pendingAvatarCrop
+ const assert = task.assertActive
+ if (avatarCropTask.get() !== task) { task.release(); return }
+ try { assert() } catch { finishAvatarCrop(task); return }
uploadUserAvatar.mutate(
{ file, assertActive: assert },
{
@@ -323,12 +357,10 @@ export function useShellProfileController({
onError: (error) => toastApiError(error, "Failed to upload avatar", assert),
},
)
- URL.revokeObjectURL(pendingAvatarCrop.src)
- setPendingAvatarCrop(null)
+ finishAvatarCrop(pendingAvatarCrop)
},
onCancel: () => {
- URL.revokeObjectURL(pendingAvatarCrop.src)
- setPendingAvatarCrop(null)
+ finishAvatarCrop(pendingAvatarCrop)
},
}
}
diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.dom.test.ts b/src/web/src/components/community/shell/use-shell-rail-controller.dom.test.ts
index fb19c88f7..f60e4d8f5 100644
--- a/src/web/src/components/community/shell/use-shell-rail-controller.dom.test.ts
+++ b/src/web/src/components/community/shell/use-shell-rail-controller.dom.test.ts
@@ -82,6 +82,7 @@ async function renderController(overrides: Record<string, unknown> = {}) {
prefetch: (href: string) => { prefetched.push(href) },
}
const navigation = {
+ captureIntent: () => () => true,
publishedHref: "/c/channels/s1",
navigationPending: false,
pendingHref: null,
@@ -199,6 +200,20 @@ describe("useShellRailController", () => {
expect(mocks.markSwitch).toHaveBeenLastCalledWith("channel", "c1")
})
+ it("keeps active-server overlays on their current leaf without a direct opener", async () => {
+ const hook = await renderController()
+ hook.navigation.publishedHref = "/c/channels/s1/c1?keep=1#message_1"
+ await hook.rerender()
+ await act(async () => {
+ hook.current.railProps.onOpenSettings("s1")
+ hook.current.railProps.onOpenInvitePopover("s1")
+ })
+ expect(hook.pushed).toEqual([
+ "/c/channels/s1/c1?keep=1&settings=1#message_1",
+ "/c/channels/s1/c1?keep=1&invite=1#message_1",
+ ])
+ })
+
it("keeps settings and invite actions synchronous and scoped to their target", async () => {
const openSettings = vi.fn()
const openInvite = vi.fn()
@@ -382,17 +397,18 @@ describe("useShellRailController", () => {
expect(mocks.toastApiError).toHaveBeenCalledWith(
iconError,
"Server created, but the icon failed to upload",
+ expect.any(Function),
)
const createError = new Error("create")
mocks.createServer.mockRejectedValueOnce(createError)
await act(async () => hook.current.railProps.onCreateServer("Broken"))
- expect(mocks.toastApiError).toHaveBeenCalledWith(createError, "Failed to create server")
+ expect(mocks.toastApiError).toHaveBeenCalledWith(createError, "Failed to create server", expect.any(Function))
await act(async () => hook.current.railProps.onLeaveServer("s2"))
const leaveError = new Error("leave")
mocks.leaveServer.mock.calls.at(-1)![1].onError(leaveError)
- expect(mocks.toastApiError).toHaveBeenCalledWith(leaveError, "Failed to leave server")
+ expect(mocks.toastApiError).toHaveBeenCalledWith(leaveError, "Failed to leave server", expect.any(Function))
})
it("passes complete memberships to the normalized rail and no legacy mutation callbacks", async () => {
diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx b/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx
index 0e8388fec..d0732f8e6 100644
--- a/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx
+++ b/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx
@@ -1,32 +1,68 @@
-import { useLayoutEffect } from "react"
+import { useLayoutEffect, useMemo } from "react"
import "fake-indexeddb/auto"
import React from "react"
import { useQueryClient, type QueryClient } from "@tanstack/react-query"
import { beforeEach, afterEach, describe, expect, it, vi } from "vitest"
-import { act, render, waitFor } from "@/test/react-dom-harness"
+import { act, fireEvent, render, waitFor, within } from "@/test/react-dom-harness"
import { QueryProvider } from "@/app/c/QueryProvider"
import { clearAllPersistedCaches } from "@/lib/query-persister"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { useShellRailController } from "./use-shell-rail-controller"
-import type { CommunityNavigationController } from "./use-community-navigation-controller"
+import { useCommunityNavigationController, type CommunityNavigationController } from "./use-community-navigation-controller"
+import { normalizeCommunityHref } from "@/lib/community/community-route"
+import { createOwnerServerDeleteRouteToken } from "@/lib/community/eject-server"
+import { getCommunityRuntime } from "@/stores/community/runtime"
+import { CommunityRouteContext } from "./community-route-context"
+import { ServerSidebarSlot } from "./server-sidebar-slot"
+import { ServerRail } from "./server-rail"
+import { tid } from "@/lib/community/testids"
+import { evictServerChannelScopes } from "@/hooks/community/community-ws/scope-eviction"
const api = vi.hoisted(() => vi.fn())
-const ui = vi.hoisted(() => ({ toast: vi.fn(), error: vi.fn(), push: vi.fn(), replace: vi.fn() }))
-vi.mock("sonner", () => ({ toast: ui.toast }))
-vi.mock("@/lib/api/client", () => ({ apiFetch: api, toastApiError: ui.error }))
+const route = vi.hoisted(() => ({ pathname: "/c/channels/s1", revision: 0 }))
+const ui = vi.hoisted(() => ({ toast: vi.fn(), error: vi.fn(), push: vi.fn(), replace: vi.fn(), queuedError: vi.fn() }))
+vi.mock("sonner", () => ({ toast: Object.assign(ui.toast, { error: ui.error }) }))
+vi.mock("@/lib/api/client", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/lib/api/client")>()
+ return { ...actual, apiFetch: api, toastApiError: (...args: Parameters<typeof actual.toastApiError>) => { actual.toastApiError(...args); ui.queuedError() } }
+})
vi.mock("@/lib/auth-client", () => { const sessionSDK = { useSession: () => ({ data: { user: { id: "A" } }, isPending: false, error: null }) }; return { ...sessionSDK, currentSessionViewer: () => { const value = sessionSDK.useSession(); return !value || value.isPending || value.error ? undefined : value.data?.user.id ?? null } } })
-vi.mock("next/navigation", () => ({ useRouter: () => ({ refresh: vi.fn(), replace: vi.fn() }) }))
+vi.mock("next/navigation", () => ({ usePathname: () => route.pathname, useSearchParams: () => new URLSearchParams(), useRouter: () => ({ refresh: vi.fn(), push: ui.push, replace: ui.replace }) }))
vi.mock("@tanstack/react-query-devtools", () => ({ ReactQueryDevtools: () => null }))
-vi.mock("@/hooks/community/mutations", async () => await import("@/hooks/community/mutations/servers"))
+vi.mock("@/contexts/community/current-user", () => ({ useCurrentUser: () => ({ id: "A" }) }))
+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))
+vi.mock("@/hooks/community/use-servers", async (original) => ({
+ ...await original<typeof import("@/hooks/community/use-servers")>(),
+ useServer: (id: string | null) => ({ server: id ? { id, name: id, categories: [] } : null, data: undefined }),
+}))
+vi.mock("@/hooks/community/use-server-members", () => ({ useServerMembers: () => ({ members: [] }) }))
+vi.mock("@/hooks/community/use-server-panels", async (original) => ({ ...await original<typeof import("@/hooks/community/use-server-panels")>(), usePresence: () => undefined }))
+vi.mock("@/hooks/community/use-forum-sidebar-threads", async (original) => ({
+ ...await original<typeof import("@/hooks/community/use-forum-sidebar-threads")>(),
+ useForumSidebarThreads: () => ({ threads: [], parentUnread: {}, projectionReady: true }),
+}))
+vi.mock("@/hooks/community/use-notification-settings", async (original) => ({
+ ...await original<typeof import("@/hooks/community/use-notification-settings")>(),
+ useNotificationSettings: () => ({ server: {}, channel: {} }),
+}))
+vi.mock("@/components/community/channels/channel-sidebar-tree-owner", () => ({ ChannelSidebarRevealBoundary: () => <aside /> }))
+vi.mock("@/components/community/settings/server-settings", () => ({ ServerSettings: () => null }))
let controller: ReturnType<typeof useShellRailController>, client: QueryClient
-const navigation: CommunityNavigationController = { publishedHref: "/c/channels/s1", navigationPending: false, pendingHref: null, push: ui.push, pushImmediate: ui.push, replace: ui.replace, resolveAndPush: vi.fn(), cancelPendingNavigation: vi.fn() }
-function Probe() {
+let navigation: CommunityNavigationController
+function Probe({ sidebar = false }: { sidebar?: boolean }) {
const currentClient = useQueryClient()
- const current = useShellRailController({ navigation, queryClient: currentClient, breakpoint: "desktop", view: "server", activeServerId: "s1", projectedActiveServerId: "s1", accountId: "A" })
- useLayoutEffect(() => { client = currentClient; controller = current })
- return null
+ const frame = { ...normalizeCommunityHref(route.pathname), revision: route.revision }
+ const serverId = frame.scope.kind === "server" ? frame.scope.serverId : "s1"
+ const currentNavigation = useCommunityNavigationController(frame)
+ const ownerDeleteRouteScope = useMemo(() => ({ serverId, token: createOwnerServerDeleteRouteToken(currentClient) }), [currentClient, serverId])
+ const current = useShellRailController({ navigation: currentNavigation, queryClient: currentClient, breakpoint: "desktop", view: "server", activeServerId: "s1", projectedActiveServerId: "s1", accountId: "A" })
+ useLayoutEffect(() => {
+ client = currentClient; controller = current; navigation = currentNavigation
+ if (sidebar) getCommunityRuntime(currentClient).ui.actions.registerUiHandlers({ cancelPendingNavigation: currentNavigation.cancelPendingNavigation })
+ })
+ return sidebar ? <CommunityRouteContext value={{ frame, navigation: currentNavigation, ownerDeleteRouteScope }}><ServerRail {...current.railProps} bottomInset={60} /><ServerSidebarSlot serverId={serverId} /></CommunityRouteContext> : null
}
-function Root({ visible = true }: { visible?: boolean }) { return <QueryProvider userId="A">{visible && <Probe />}</QueryProvider> }
-async function mount() {
+function Root({ visible = true, sidebar = false }: { visible?: boolean; sidebar?: boolean }) { return <QueryProvider userId="A">{visible && <Probe sidebar={sidebar} />}</QueryProvider> }
+async function mount(sidebar = false) {
let resolve!: (value: unknown) => void, reject!: (error: Error) => void
const held = new Promise<unknown>((done, fail) => { resolve = done; reject = fail })
const seen = new Set<string>()
@@ -35,14 +71,18 @@ async function mount() {
if (options.method === "POST") return held
if (seen.has(path)) return new Promise((_, fail) => options.signal?.addEventListener("abort", () => fail(new DOMException("cancelled", "AbortError")), { once: true }))
seen.add(path)
- return Promise.resolve(path.endsWith("server-folders") ? { folders: [] } : { servers: [{ id: "s1", name: "One", discriminator: "0001", icon: null, ownerId: "A", role: "owner" }] })
+ return Promise.resolve(path.endsWith("server-folders") ? { folders: [] } : { servers: [{ id: "s1", name: "One", discriminator: "0001", icon: null, ownerId: sidebar ? "other-owner" : "A", role: sidebar ? "member" : "owner" }, ...(sidebar ? [{ id: "s2", name: "Two", discriminator: "0002", icon: null, ownerId: "other-owner", role: "member" }] : [])] })
})
- const view = render(<Root />)
- await waitFor(() => expect(controller.railProps.servers).toHaveLength(1))
+ const view = render(<Root sidebar={sidebar} />)
+ await waitFor(() => expect(controller.railProps.servers).toHaveLength(sidebar ? 2 : 1))
return { view, resolve, reject, original: client }
}
-beforeEach(async () => { await clearAllPersistedCaches(); api.mockReset(); Object.values(ui).forEach((fn) => fn.mockReset()); navigation.publishedHref = "/c/channels/s1"; navigation.pendingHref = null })
-afterEach(() => api.mockReset())
+beforeEach(async () => {
+ await clearAllPersistedCaches(); api.mockReset(); Object.values(ui).forEach((fn) => fn.mockReset())
+ route.pathname = "/c/channels/s1"; route.revision = 0; window.history.replaceState(null, "", route.pathname)
+ vi.stubGlobal("matchMedia", (query: string) => ({ matches: query.includes("prefers-reduced-motion"), media: query, addEventListener: vi.fn(), removeEventListener: vi.fn() }))
+})
+afterEach(() => { api.mockReset(); vi.unstubAllGlobals() })
describe("actual native Rail controller continuation", () => {
it("current create continues icon upload and navigation through the original account", async () => {
const { resolve } = await mount()
@@ -63,6 +103,37 @@ describe("actual native Rail controller continuation", () => {
expect(api.mock.calls.some(([path]) => path.endsWith("/icon"))).toBe(false)
expect(ui.push).not.toHaveBeenCalled(); expect(ui.toast).not.toHaveBeenCalled(); expect(ui.error).not.toHaveBeenCalled()
})
+ it.each(["new-pending", "scope-return"] as const)("retires late create UI on %s while keeping its original account operation", async (change) => {
+ const { view, resolve, original } = await mount()
+ let result!: Promise<unknown>
+ act(() => { result = controller.railProps.onCreateServer("New", new File(["x"], "icon.png")) })
+ await waitFor(() => expect(api.mock.calls.some(([, options]) => options.method === "POST")).toBe(true))
+ if (change === "new-pending") act(() => navigation.push("/c/channels/s2"))
+ else {
+ route.pathname = "/c/me/friends"; route.revision = 1
+ view.rerender(<Root />)
+ route.pathname = "/c/channels/s1"; route.revision = 2
+ view.rerender(<Root />)
+ }
+ await act(async () => { resolve({ server: { id: "created" } }); await result })
+ expect(getCommunityDbRegistry(original)!.runtime.lifecycle.get().active).toBe(true)
+ expect(api.mock.calls.some(([path]) => path.endsWith("/icon"))).toBe(false)
+ expect(ui.push).not.toHaveBeenCalledWith("/c/channels/created")
+ expect(ui.toast).not.toHaveBeenCalled()
+ expect(ui.error).not.toHaveBeenCalled()
+ if (change === "new-pending") expect(navigation.pendingHref).toBe("/c/channels/s2")
+ })
+ it("rechecks the original rail intent after a failure is queued for deferred display", async () => {
+ const { reject } = await mount()
+ let result!: Promise<unknown>
+ act(() => { result = controller.railProps.onCreateServer("New") })
+ await waitFor(() => expect(api.mock.calls.some(([, options]) => options.method === "POST")).toBe(true))
+ ui.queuedError.mockImplementation(() => navigation.push("/c/channels/s2"))
+ await act(async () => { reject(new Error("late failure")); await result })
+ expect(ui.queuedError).toHaveBeenCalled()
+ expect(navigation.pendingHref).toBe("/c/channels/s2")
+ expect(ui.error).not.toHaveBeenCalled()
+ })
it("confirmed leave still navigates the original published route after native scope eviction clears its UI pointer", async () => {
const { resolve } = await mount()
act(() => controller.railProps.onLeaveServer!("s1"))
@@ -74,9 +145,91 @@ describe("actual native Rail controller continuation", () => {
const { view, resolve } = await mount()
act(() => controller.railProps.onLeaveServer!("s1"))
await waitFor(() => expect(api.mock.calls.some(([path]) => path.endsWith("/leave"))).toBe(true))
- act(() => { navigation.pendingHref = "/c/channels/s2"; view.rerender(<Root />) })
+ act(() => { navigation.push("/c/channels/s2"); view.rerender(<Root />) })
await act(async () => resolve(undefined))
- await waitFor(() => expect(ui.toast).toHaveBeenCalledWith("Left server"))
+ await waitFor(() => expect(api.mock.calls.some(([path]) => path.endsWith("/leave"))).toBe(true))
+ expect(ui.toast).not.toHaveBeenCalled()
+ expect(navigation.pendingHref).toBe("/c/channels/s2")
expect(ui.replace).not.toHaveBeenCalled()
})
+
+ it.each(["/c/channels/s2", "/c/me/friends"])("mounted old sidebar preserves newer %s while the real leave retires its account scope", async (target) => {
+ const { resolve, original } = await mount(true)
+ act(() => controller.railProps.onLeaveServer!("s1"))
+ await waitFor(() => expect(api.mock.calls.some(([path]) => path.endsWith("/leave"))).toBe(true))
+ act(() => navigation.push(target))
+ await act(async () => resolve(undefined))
+ const registry = getCommunityDbRegistry(original)!
+ await waitFor(() => expect(registry.runtime.ws.get().revokedServerIds.has("s1")).toBe(true))
+ expect([...registry.collections.serverMemberships.values()].some((row) => row.serverId === "s1" && row.viewer)).toBe(false)
+ expect([...registry.collections.serverMemberships.values()].some((row) => row.serverId === "s2" && row.viewer)).toBe(true)
+ expect(navigation.pendingHref).toBe(target)
+ expect(navigation.navigationPending).toBe(true)
+ expect(ui.replace).not.toHaveBeenCalled()
+ expect(ui.toast).not.toHaveBeenCalled()
+ })
+
+ it("real rail Leave dialog and destination click keep B pending after the old member leave succeeds", async () => {
+ const { view, resolve } = await mount(true)
+ fireEvent.contextMenu(view.getByTestId(tid.serverIcon("s1")))
+ fireEvent.click(await view.findByRole("menuitem", { name: /^Leave server$/ }))
+ const dialog = await view.findByRole("dialog")
+ fireEvent.click(within(dialog).getByRole("button", { name: /^Leave server$/ }))
+ await waitFor(() => expect(api.mock.calls.some(([path]) => path.endsWith("/leave"))).toBe(true))
+ fireEvent.click(view.getByTestId(tid.serverIcon("s2")))
+ expect(navigation.pendingHref).toBe("/c/channels/s2")
+ await act(async () => resolve(undefined))
+ await waitFor(() => expect(getCommunityRuntime(client).ws.get().revokedServerIds.has("s1")).toBe(true))
+ expect(view.queryByTestId(tid.serverIcon("s1"))).toBeNull()
+ expect(view.getByTestId(tid.serverIcon("s2"))).toBeTruthy()
+ expect(navigation.pendingHref).toBe("/c/channels/s2")
+ expect(navigation.navigationPending).toBe(true)
+ expect(ui.replace).not.toHaveBeenCalled()
+ })
+
+ it("mounted old sidebar preserves an unresolved newer intent and ejects if it is canceled", async () => {
+ const { resolve } = await mount(true)
+ act(() => controller.railProps.onLeaveServer!("s1"))
+ await waitFor(() => expect(api.mock.calls.some(([path]) => path.endsWith("/leave"))).toBe(true))
+ let finish!: (href: string) => void, operation!: Promise<boolean>
+ act(() => { operation = navigation.resolveAndPush(() => new Promise<string>((done) => { finish = done })) })
+ await act(async () => resolve(undefined))
+ await waitFor(() => expect(getCommunityRuntime(client).ws.get().revokedServerIds.has("s1")).toBe(true))
+ expect(navigation.navigationPending).toBe(true)
+ expect(navigation.pendingHref).toBeNull()
+ expect(ui.replace).not.toHaveBeenCalled()
+ act(() => navigation.cancelPendingNavigation())
+ await waitFor(() => expect(ui.replace).toHaveBeenCalledWith("/c/channels/s2"))
+ await act(async () => { finish("/c/me/friends"); await operation })
+ expect(ui.push).not.toHaveBeenCalledWith("/c/me/friends")
+ })
+
+ it.each([false, true])("mounted sidebar still ejects the revoked current scope with same-server pending=%s", async (sameServerPending) => {
+ const { resolve } = await mount(true)
+ act(() => controller.railProps.onLeaveServer!("s1"))
+ await waitFor(() => expect(api.mock.calls.some(([path]) => path.endsWith("/leave"))).toBe(true))
+ if (sameServerPending) act(() => navigation.push("/c/channels/s1/channel-2"))
+ await act(async () => resolve(undefined))
+ await waitFor(() => expect(ui.replace).toHaveBeenCalledWith("/c/channels/s2"))
+ expect(navigation.pendingHref).not.toBe("/c/channels/s1/channel-2")
+ })
+
+ it("new destination sidebar ejects when its own server access is revoked", async () => {
+ const { view, resolve } = await mount(true)
+ act(() => controller.railProps.onLeaveServer!("s1"))
+ await waitFor(() => expect(api.mock.calls.some(([path]) => path.endsWith("/leave"))).toBe(true))
+ act(() => navigation.push("/c/channels/s2"))
+ await act(async () => resolve(undefined))
+ await waitFor(() => expect(getCommunityRuntime(client).ws.get().revokedServerIds.has("s1")).toBe(true))
+ expect(ui.replace).not.toHaveBeenCalled()
+ act(() => {
+ route.pathname = "/c/channels/s2"; route.revision = 1
+ window.history.replaceState(null, "", route.pathname)
+ view.rerender(<Root sidebar />)
+ })
+ await waitFor(() => expect(navigation.navigationPending).toBe(false))
+ act(() => { evictServerChannelScopes(client, "s2") })
+ await waitFor(() => expect(ui.replace).toHaveBeenCalledWith("/c/me"))
+ expect(getCommunityRuntime(client).ws.get().revokedServerIds.has("s2")).toBe(true)
+ })
})
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 2423ff9aa..531a08211 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
@@ -8,6 +8,7 @@ import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { communityServerId } from "@/lib/community/community-route"
import { markSwitch } from "@/lib/perf/switch-mark"
import { markVoluntaryLeave, pickPostEjectDestination } from "@/lib/community/eject-server"
+import { useCommunityMutationOrigin } from "@/hooks/community/community-origin"
import { useServers } from "@/hooks/community/use-servers"
import { useFolders } from "@/hooks/community/use-folders"
import {
@@ -53,6 +54,7 @@ export function useShellRailController({
accountId,
}: Options) {
const communityDb = useOptionalCommunityDbRegistry()
+ const origin = useCommunityMutationOrigin()
const serversQuery = useServers()
const foldersQuery = useFolders()
const servers = serversQuery.servers
@@ -66,6 +68,24 @@ export function useShellRailController({
useLayoutEffect(() => { viewOwner.set((state) => ({ ...state, navigation })) }, [navigation, viewOwner])
const viewCurrent = useCallback((generation: number) => viewOwner.get().active && viewOwner.get().generation === generation
&& !!communityDb?.runtime.lifecycle.get().active && getCommunityDbRegistry(queryClient) === communityDb, [communityDb, queryClient, viewOwner])
+ const captureOperation = useCallback(() => {
+ const generation = viewOwner.get().generation
+ const token = origin.begin().token
+ const authentication = communityDb!.authenticationView.get()
+ const intentCurrent = navigation.captureIntent()
+ const assertAccount = () => {
+ origin.assertOwner(token)
+ const current = communityDb!.authenticationView.get()
+ if (!viewCurrent(generation) || !current.active || current.generation !== authentication.generation) {
+ throw new DOMException("Retired rail account", "AbortError")
+ }
+ }
+ const assertUi = () => {
+ assertAccount()
+ if (!intentCurrent()) throw new DOMException("Retired rail intent", "AbortError")
+ }
+ return { assertAccount, assertUi }
+ }, [communityDb, navigation, origin, viewCurrent, viewOwner])
const { mutateAsync: createServerAsync } = useCreateServer()
const { mutate: leaveServerMutate } = useLeaveServer()
const { mutate: uploadServerIconMutate } = useUploadServerIcon()
@@ -96,43 +116,49 @@ export function useShellRailController({
const onCreateServer = useCallback(async (name: string, icon?: File) => {
const generation = viewOwner.get().generation
if (!viewCurrent(generation)) return
+ const { assertAccount, assertUi } = captureOperation()
try {
+ assertAccount()
const data = await createServerAsync({ name })
- if (!viewCurrent(generation)) return
+ assertUi()
const newId = data.server.id
toast(`Server "${name}" created`)
if (icon) {
uploadServerIconMutate(
{ serverId: newId, file: icon },
- { onError: (error) => { if (viewCurrent(generation)) toastApiError(error, "Server created, but the icon failed to upload") } },
+ { onError: (error) => toastApiError(error, "Server created, but the icon failed to upload", assertUi) },
)
}
navigation.push(`/c/channels/${newId}`)
} catch (error) {
- if (viewCurrent(generation)) toastApiError(error, "Failed to create server")
+ toastApiError(error, "Failed to create server", assertUi)
}
- }, [createServerAsync, navigation, uploadServerIconMutate, viewOwner, viewCurrent])
+ }, [captureOperation, createServerAsync, navigation, uploadServerIconMutate, viewOwner, viewCurrent])
const onLeaveServer = useCallback((id: string) => {
const generation = viewOwner.get().generation
if (!viewCurrent(generation)) return
+ const { assertAccount, assertUi } = captureOperation()
+ try { assertAccount() } catch { return }
markVoluntaryLeave(queryClient, id)
leaveServerMutate(
{ serverId: id },
{
onSuccess: () => {
- if (!viewCurrent(generation)) return
- toast("Left server")
+ try { assertAccount() } catch { return }
+ try { assertUi(); toast("Left server") } catch {}
const currentNavigation = viewOwner.get().navigation
- if (currentNavigation && communityServerId(currentNavigation.pendingHref ?? currentNavigation.publishedHref) === id) {
+ if (currentNavigation && communityServerId(currentNavigation.navigationPending
+ ? currentNavigation.pendingHref ?? ""
+ : currentNavigation.publishedHref) === id) {
const allowed = new Set([...communityDb!.collections.serverMemberships.values()].filter((row) => row.viewer && row.userId === communityDb!.accountId).map((row) => row.serverId))
const remaining = [...communityDb!.collections.servers.values()].filter((row) => allowed.has(row.id)).sort((a, b) => (a.position ?? 0) - (b.position ?? 0))
currentNavigation.replace(pickPostEjectDestination(remaining, id))
}
},
- onError: (error) => { if (viewCurrent(generation)) toastApiError(error, "Failed to leave server") },
+ onError: (error) => toastApiError(error, "Failed to leave server", assertUi),
},
)
- }, [communityDb, leaveServerMutate, queryClient, viewCurrent, viewOwner])
+ }, [captureOperation, communityDb, leaveServerMutate, queryClient, viewCurrent, viewOwner])
const onOpenSettings = useCallback((id?: string) => {
if (!id) return
const action = resolveServerRailOverlayAction({
@@ -140,6 +166,7 @@ export function useShellRailController({
activeServerId,
overlay: "settings",
hasActiveOpener: !!onOpenActiveServerSettings,
+ publishedHref: navigation.publishedHref,
})
if (action.kind === "open-active") onOpenActiveServerSettings?.()
else navigation.push(action.href)
@@ -151,6 +178,7 @@ export function useShellRailController({
activeServerId,
overlay: "invite",
hasActiveOpener: !!onOpenActiveServerInvite,
+ publishedHref: navigation.publishedHref,
})
if (action.kind === "open-active") onOpenActiveServerInvite?.()
else navigation.push(action.href)
diff --git a/src/web/src/hooks/community/mutations/forum-commands.dom.test.ts b/src/web/src/hooks/community/mutations/forum-commands.dom.test.ts
index 72c11a06b..023e479e2 100644
--- a/src/web/src/hooks/community/mutations/forum-commands.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/forum-commands.dom.test.ts
@@ -9,6 +9,7 @@ import { getMessageOverlay } from "@/stores/community/message-stream"
import { useCanonicalChannelsById, useCanonicalMessagesById, useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
import { captureCommunityLiveSnapshotToken, projectCommunityWsEventToDb, publishCommunityForumSidebar, publishCommunityForumFeed, publishCommunityForumTags, getCanonicalCommunityChannelMemberships, removeCanonicalCommunityChannelMembership } from "@/lib/community-db/sync"
import { mapForumFeedPages } from "../use-forum-feed"
+import { useForumTags } from "../use-channel-panels"
import { forumFeedWindow, forumFeedMatchesTags, type ForumFeedPage, type ForumFeedTransportPage } from "../forum-feed-window"
import { getForumSidebarBase } from "../use-forum-sidebar-threads"
import { getActiveAccountUnreadProjection } from "../account-unread-projection"
@@ -39,19 +40,20 @@ function wire(ids: string[]): ForumFeedTransportPage {
}
const tagInput = { serverId: "server_1", forumChannelId: "forum_1", threadId: "p2", openerMessageId: "opener_p2", previousTags: ["bug"], tags: ["bug", "archived"] }
const deleteInput = { serverId: "server_1", forumChannelId: "forum_1", threadId: "p2", openerMessageId: "opener_p2" }
-async function setup(ids = ["before", "p2", "after"]) {
+async function setup(ids = ["before", "p2", "after"], observeCatalog = false) {
const owner = await createCommunityQueryOwner(), navigate = vi.fn()
const frames: Array<{ pending: boolean; all: string[]; archived: string[] }> = []
const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, retainOwner: true }, children)
const view = renderHook(() => {
const create = useCreateForumThread(), tags = useUpdatePostTags(), remove = useDeleteForumThread()
+ const catalog = useForumTags("forum_1", observeCatalog)
const channels = useCanonicalChannelsById(), messages = useCanonicalMessagesById(), profiles = useCanonicalProfilesByUserId()
const all = useQuery<InfiniteData<ForumFeedPage>>({ queryKey: communityKeys.forumFeed("forum_1", null), queryFn: skipToken, enabled: false }).data
const bug = useQuery<InfiniteData<ForumFeedPage>>({ queryKey: communityKeys.forumFeed("forum_1", "bug"), queryFn: skipToken, enabled: false }).data
const archived = useQuery<InfiniteData<ForumFeedPage>>({ queryKey: communityKeys.forumFeed("forum_1", "archived"), queryFn: skipToken, enabled: false }).data
const windows = new Map<string | null, InfiniteData<ForumFeedPage> | undefined>([[null, all], ["bug", bug], ["archived", archived]])
const posts = (filter: string | null) => mapForumFeedPages(windows.get(filter)?.pages ?? [], messages ?? new Map(), channels, profiles, filter)
- const result = { create, tags, remove, channels, messages, all: posts(null), bug: posts("bug"), archived: posts("archived") }
+ const result = { create, tags, remove, catalog, channels, messages, all: posts(null), bug: posts("bug"), archived: posts("archived") }
useLayoutEffect(() => { frames.push({ pending: tags.isPending, all: result.all.map(({ id }) => id), archived: result.archived.map(({ id }) => id) }) })
return result
}, { wrapper })
@@ -66,7 +68,7 @@ async function setup(ids = ["before", "p2", "after"]) {
seed(ids)
owner.client.setQueryData(communityKeys.channelMessages("forum_1"), { pages: [{ messages: ids.map((id) => ({ id: `opener_${id}` })) }], pageParams: [null] })
owner.client.setQueryData([...communityKeys.channelMessages("forum_1"), "tag", "bug"], { pages: [], pageParams: [null] })
- owner.client.setQueryData(communityKeys.forumTags("forum_1"), { tags: ["bug"] })
+ if (!observeCatalog) owner.client.setQueryData(communityKeys.forumTags("forum_1"), { tags: ["bug"] })
owner.client.setQueryData(communityKeys.forumSidebarThreads("server_1"), { serverNow: new Date().toISOString(), serverClockOffsetMs: 0, threads: [] })
})
await waitFor(() => expect(view.result.current.all).toHaveLength(ids.length))
@@ -110,6 +112,71 @@ describe("Native forum creation", () => {
})
describe("Native forum tag transactions", () => {
+ it.each(["refetch", "initial"] as const)("refreshes the catalog when an older %s read spans an archive ACK", async (kind) => {
+ const stale = deferred()
+ let reads = 0, oldSignal: AbortSignal | undefined
+ mocks.api.mockImplementation((path, options) => {
+ if (path === "/api/community/channels/forum_1/messages/tags") {
+ reads += 1
+ if (reads === (kind === "initial" ? 1 : 2)) {
+ oldSignal = options?.signal
+ return stale.promise
+ }
+ return Promise.resolve({ tags: kind === "refetch" && reads === 1 ? ["bug"] : ["archived", "bug"] })
+ }
+ if (options?.method === "PUT") return Promise.resolve({ tags: ["bug", "archived"] })
+ throw new Error(`Unexpected request: ${path}`)
+ })
+ const view = await setup(undefined, true)
+ let oldRead: Promise<void> | undefined
+ if (kind === "refetch") {
+ await waitFor(() => expect(view.view.result.current.catalog.data?.tags).toEqual(["bug"]))
+ act(() => { oldRead = view.client.refetchQueries({ queryKey: communityKeys.forumTags("forum_1"), exact: true }) })
+ await waitFor(() => expect(reads).toBe(2))
+ } else {
+ await waitFor(() => expect(reads).toBe(1))
+ expect(view.view.result.current.catalog.data).toBeUndefined()
+ }
+ await act(async () => { await view.view.result.current.tags.mutateAsync(tagInput) })
+ await act(async () => { stale.resolve({ tags: ["bug"] }); await oldRead })
+ await waitFor(() => expect(view.view.result.current.catalog.data?.tags).toEqual(["archived", "bug"]))
+ expect(oldSignal?.aborted).toBe(true)
+ expect(view.view.result.current.all.map(({ id }) => id)).not.toContain("p2")
+ })
+
+ it("does not cancel or invalidate a replacement catalog read after an older command ACK", async () => {
+ mocks.api.mockResolvedValue({ tags: ["bug"] })
+ const view = await setup(undefined, true)
+ await waitFor(() => expect(view.view.result.current.catalog.data?.tags).toEqual(["bug"]))
+ const pending = await begin(view, "tags"), key = communityKeys.forumTags("forum_1"), held = deferred()
+ let replacementSignal: AbortSignal | undefined, replacementRead!: Promise<{ tags: string[] }>
+ act(() => {
+ view.client.removeQueries({ queryKey: key, exact: true })
+ replacementRead = view.client.fetchQuery({ queryKey: key, queryFn: ({ signal }) => {
+ replacementSignal = signal
+ return held.promise as Promise<{ tags: string[] }>
+ } })
+ })
+ const replacement = view.client.getQueryCache().find({ queryKey: key, exact: true })
+ await act(async () => { pending.held.resolve({ tags: ["bug", "archived"] }); await pending.request })
+ expect(replacementSignal?.aborted).toBe(false)
+ expect(replacement?.state.isInvalidated).toBe(false)
+ await act(async () => { held.resolve({ tags: ["replacement"] }); await replacementRead })
+ expect(view.client.getQueryCache().find({ queryKey: key, exact: true })).toBe(replacement)
+ expect(view.client.getQueryData(key)).toEqual({ tags: ["replacement"] })
+ })
+
+ it("does not refresh a catalog after its command view retires", async () => {
+ mocks.api.mockResolvedValue({ tags: ["bug"] })
+ const view = await setup(undefined, true)
+ await waitFor(() => expect(view.view.result.current.catalog.data?.tags).toEqual(["bug"]))
+ const pending = await begin(view, "tags")
+ act(() => view.view.unmount())
+ await act(async () => { pending.held.resolve({ tags: ["bug", "archived"] }); await pending.request })
+ expect(mocks.api.mock.calls.filter(([path]) => path.endsWith("/messages/tags"))).toHaveLength(1)
+ expect(view.client.getQueryData(communityKeys.forumTags("forum_1"))).toEqual({ tags: ["bug"] })
+ })
+
it("does not publish an old opener ACK onto a reused child identity", async () => {
const view = await setup(["p2"]), { held, request } = await begin(view, "tags", { ...tagInput, openerMessageId: "retired_opener" })
expect(view.registry.collections.channels.get("p2")).toMatchObject({ parentMessageId: "opener_p2", tags: ["bug"] })
diff --git a/src/web/src/hooks/community/mutations/forum.ts b/src/web/src/hooks/community/mutations/forum.ts
index ec198e459..84c7bb146 100644
--- a/src/web/src/hooks/community/mutations/forum.ts
+++ b/src/web/src/hooks/community/mutations/forum.ts
@@ -145,6 +145,8 @@ export function useUpdatePostTags() {
transaction.mutate(() => { const thread = registry.collections.channels.get(args.threadId); if (thread?.parentMessageId === args.openerMessageId) registry.collections.channels.update(args.threadId, (row) => { row.tags = tags }) })
try { if (transaction.mutations.length) await transaction.commit(); else await persist() } catch (error) { assert(); throw error }
assert()
+ await queryClient.cancelQueries({ queryKey: communityKeys.forumTags(args.forumChannelId), exact: true, predicate: (query) => resources.has(query) })
+ assert()
for (const query of args.resources) if (queryClient.getQueryCache().find({ queryKey: query.queryKey, exact: true }) === query) void queryClient.invalidateQueries({ queryKey: query.queryKey, exact: true }, { cancelRefetch: false }).catch(() => undefined)
return result
},
diff --git a/src/web/src/hooks/community/mutations/servers.ts b/src/web/src/hooks/community/mutations/servers.ts
index 47eb27686..b53c7c3e5 100644
--- a/src/web/src/hooks/community/mutations/servers.ts
+++ b/src/web/src/hooks/community/mutations/servers.ts
@@ -83,13 +83,14 @@ export function useJoinServer() {
// ── Leave / delete server ──────────────────────────────────────────────────
export type LeaveServerArgs = { serverId: string }
+type DeleteServerArgs = LeaveServerArgs & { isUiCurrent?: () => boolean }
type DeleteServerCallbacks = {
routeToken: OwnerServerDeleteRouteToken
onSuccess?: (
- args: LeaveServerArgs,
+ args: DeleteServerArgs,
result: { needsNavigation: boolean },
) => void
- onError?: (error: Error, args: LeaveServerArgs) => void
+ onError?: (error: Error, args: DeleteServerArgs) => void
}
function mutateViewerMembership(registry: NonNullable<ReturnType<typeof useCommunityMutationOrigin>["registry"]>, serverId: string) {
@@ -141,7 +142,7 @@ export function useLeaveServer() {
export function useDeleteServer(callbacks: DeleteServerCallbacks) {
const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()
const unreadProjection = getActiveAccountUnreadProjection(queryClient)
- return useCommunityCommandMutation<void, Error, LeaveServerArgs, { token: AccountUnreadScopeToken; proof: CommunityLiveSnapshotToken } & DeleteServerCallbacks>(origin, {
+ return useCommunityCommandMutation<void, Error, DeleteServerArgs, { token: AccountUnreadScopeToken; proof: CommunityLiveSnapshotToken } & DeleteServerCallbacks>(origin, {
scope: { id: "community-server-membership" },
onMutate: async (args) => {
const token = args.original
diff --git a/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts b/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts
index e3742aa89..d638ad002 100644
--- a/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts
@@ -9,6 +9,7 @@ import { ApiError } from "@/lib/errors"
import { communityKeys } from "@/lib/query-keys"
import { useCommunityStore } from "@/stores/community"
import { useCommunityWsStore } from "@/stores/community/ws"
+import { runAuthoritativeServerEject } from "@/lib/community/eject-server"
const mocks = vi.hoisted(() => ({ apiFetch: vi.fn(), replace: vi.fn(), toast: vi.fn(),
server: { server: { id: "server-1", categories: [{ channels: [{ id: "parent-1", name: "parent", type: "text" }] }] } as { id: string; categories: { channels: { id: string; name: string; type: string }[] }[] } | null,
@@ -180,6 +181,25 @@ describe("unresolved metadata terminal error and retry", () => {
expect(mocks.replace).not.toHaveBeenCalled()
})
+ it("does not overwrite a server eject with the denied channel's server root", async () => {
+ const owner = getCommunityDbRegistry(client)!
+ owner.runtime.ws.actions.revokeServerAccess("server-1")
+ client.getQueryCache().build(client, {
+ queryKey: communityKeys.channelMeta("server-1", "post-1"),
+ }).setState({ error: new ApiError("denied", 403), status: "error", fetchStatus: "idle" })
+ expect(runAuthoritativeServerEject({
+ serverId: "server-1", servers: [], isSuccess: true, isFetching: false,
+ consumeVoluntaryLeave: () => false, clearLastChannel: vi.fn(),
+ toast: mocks.toast, replace: mocks.replace,
+ })).toBe(true)
+ await mount()
+ await until(() => current.routeLifecycle === "terminal-error")
+
+ expect(mocks.replace).toHaveBeenCalledExactlyOnceWith("/c/me")
+ expect(owner.runtime.ws.actions.isChannelAccessRevoked("post-1", "server-1")).toBe(true)
+ expect(current.metadataError).toBe(false)
+ })
+
it.each([0, 500])("keeps a verified thread ready through disconnect, failed %s revalidation, and recovery", async (status) => {
mocks.apiFetch.mockResolvedValue(payload())
await mount()
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 c09dbac69..858f1bf9a 100644
--- a/src/web/src/hooks/community/use-channel-route-model.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.ts
@@ -203,7 +203,7 @@ export function useChannelRouteModel(
// A top-level delete clears the live pointer and starts its survivor
// navigation before this fallback metadata request can settle. Do not
// let the late 403/404 supersede that newer navigation with the root.
- if (!routeStillCurrent) return
+ if (!routeStillCurrent || runtime.ws.get().revokedServerIds.has(serverId)) return
const destination = consumeCommunityColdEntryFailure(
accountId,
`/c/channels/${serverParam}/${channelId}`,
@@ -214,7 +214,7 @@ export function useChannelRouteModel(
} else if (metaQuery.error) {
toastApiError(metaQuery.error, "Failed to load channel")
}
- }, [accountId, channelId, communityDb, isChild, metaQuery.data, metaQuery.error, metaQuery.isVerified, metaQuery.isArchived, queryClient, renderableChannelMeta, router, runtime.ui, runtime.ws.actions, serverId, serverParam, metadataExited, exitScope, setExitedMetadata])
+ }, [accountId, channelId, communityDb, isChild, metaQuery.data, metaQuery.error, metaQuery.isVerified, metaQuery.isArchived, queryClient, renderableChannelMeta, router, runtime.ui, runtime.ws, runtime.ws.actions, serverId, serverParam, metadataExited, exitScope, setExitedMetadata])
return {
...model,
routeHydrated: model.routeHydrated && metaQuery.isVerified,
diff --git a/src/web/src/test/e2e-fixture-isolation.test.ts b/src/web/src/test/e2e-fixture-isolation.test.ts
new file mode 100644
index 000000000..ca7392181
--- /dev/null
+++ b/src/web/src/test/e2e-fixture-isolation.test.ts
@@ -0,0 +1,93 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { cleanupGeometryServers, seedGeometryRoutes } from "./e2e-ui/_fixtures/community-loading-geometry"
+import { seedChannel, seedDm, seedForumThread, seedMessage, seedServer, seedThread } from "./e2e-ui/_fixtures/seed"
+
+vi.mock("./e2e-ui/_fixtures/community-fixture", () => ({
+ expect: {},
+ sessionCookie: (key: string) => `fixture-user=${key}`,
+ userId: (key: string) => `user-${key}`,
+}))
+
+vi.mock("./e2e-ui/_fixtures/seed", async (importOriginal) => ({
+ ...await importOriginal<typeof import("./e2e-ui/_fixtures/seed")>(),
+ seedServer: vi.fn(),
+ seedChannel: vi.fn(),
+ seedDm: vi.fn(),
+ seedForumThread: vi.fn(),
+ seedMessage: vi.fn(),
+ seedThread: vi.fn(),
+}))
+
+describe("geometry fixture backend resource isolation", () => {
+ beforeEach(() => {
+ vi.resetAllMocks()
+ vi.mocked(seedChannel).mockResolvedValue("channel")
+ vi.mocked(seedDm).mockResolvedValue("dm")
+ vi.mocked(seedForumThread).mockResolvedValue("forum-post")
+ vi.mocked(seedMessage).mockResolvedValue("message")
+ vi.mocked(seedThread).mockResolvedValue("thread")
+ })
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ })
+
+ it("retires only this fixture's twenty servers after the journey", async () => {
+ const owned: string[] = []
+ let nextId = 0
+ vi.mocked(seedServer).mockImplementation(async () => `owned-${++nextId}`)
+ const request = vi.fn().mockResolvedValue(new Response(null, { status: 204 }))
+ vi.stubGlobal("fetch", request)
+
+ const routes = await seedGeometryRoutes(owned)
+ await cleanupGeometryServers(owned)
+
+ expect(routes).toHaveLength(9)
+ expect(owned).toEqual(Array.from({ length: 20 }, (_, index) => `owned-${index + 1}`))
+ expect(request.mock.calls.map(([url]) => new URL(url).pathname)).toEqual(
+ owned.map((id) => `/api/community/servers/${id}`),
+ )
+ expect(request.mock.calls.every(([, options]) => options.method === "DELETE"
+ && options.headers.Cookie === "fixture-user=dave")).toBe(true)
+ })
+
+ it("keeps successful IDs available for teardown when later seeding fails", async () => {
+ const owned: string[] = []
+ vi.mocked(seedServer)
+ .mockResolvedValueOnce("owned-first")
+ .mockResolvedValueOnce("owned-second")
+ .mockRejectedValueOnce(new Error("seed failed"))
+ const request = vi.fn().mockResolvedValue(new Response(null, { status: 204 }))
+ vi.stubGlobal("fetch", request)
+
+ await expect(seedGeometryRoutes(owned)).rejects.toThrow("seed failed")
+ await cleanupGeometryServers(owned)
+
+ expect(owned).toEqual(["owned-first", "owned-second"])
+ expect(request.mock.calls.map(([url]) => new URL(url).pathname)).toEqual([
+ "/api/community/servers/owned-first",
+ "/api/community/servers/owned-second",
+ ])
+ })
+
+ it("attempts every owned ID and reports cleanup errors without treating 404 as failure", async () => {
+ const request = vi.fn()
+ .mockResolvedValueOnce(new Response(null, { status: 400 }))
+ .mockRejectedValueOnce(new Error("connection failed"))
+ .mockResolvedValueOnce(new Response(null, { status: 404 }))
+ .mockResolvedValueOnce(new Response(null, { status: 204 }))
+ vi.stubGlobal("fetch", request)
+
+ const error = await cleanupGeometryServers(["failed", "disconnected", "already-gone", "remaining"])
+ .catch((failure: AggregateError) => failure)
+
+ expect(error).toBeInstanceOf(AggregateError)
+ expect((error as AggregateError).errors).toHaveLength(2)
+ expect(request.mock.calls.map(([url]) => new URL(url).pathname)).toEqual([
+ "/api/community/servers/failed",
+ "/api/community/servers/disconnected",
+ "/api/community/servers/already-gone",
+ "/api/community/servers/remaining",
+ ])
+ })
+})
diff --git a/src/web/src/test/e2e-ui/36-server-switch-pending-checkpoint.spec.ts b/src/web/src/test/e2e-ui/36-server-switch-pending-checkpoint.spec.ts
index 044f85167..90d84dead 100644
--- a/src/web/src/test/e2e-ui/36-server-switch-pending-checkpoint.spec.ts
+++ b/src/web/src/test/e2e-ui/36-server-switch-pending-checkpoint.spec.ts
@@ -12,6 +12,7 @@ type SidebarFrame = {
pathname: string
ownerId: number | null
scope: string | null
+ retainedOwner: { scope: string | null; hidden: boolean; inert: boolean } | null
pendingServer: string | null
skeleton: boolean
rows: string[]
@@ -56,7 +57,18 @@ async function installSidebarFrameProbe(page: Page) {
const sample = () => {
const surface = document.querySelector<HTMLElement>('[data-community-mobile-surface="list"]')
const sidebar = surface ?? document.querySelector<HTMLElement>("#sidebar")
- const owner = sidebar?.querySelector<HTMLElement>("[data-community-channel-tree-scope]") ?? null
+ const retainedOwner = sidebar?.querySelector<HTMLElement>("[data-community-channel-tree-scope]") ?? null
+ const ownerStyle = retainedOwner ? getComputedStyle(retainedOwner) : null
+ const ownerHasLayout = retainedOwner !== null && (
+ retainedOwner.getClientRects().length > 0
+ || Array.from(retainedOwner.children).some((child) => child.getClientRects().length > 0)
+ )
+ const ownerHidden = retainedOwner !== null && (
+ ownerStyle?.display === "none" || ownerStyle?.visibility === "hidden"
+ || !ownerHasLayout
+ )
+ const ownerInert = retainedOwner !== null && retainedOwner.closest("[inert]") !== null
+ const owner = ownerHidden || ownerInert ? null : retainedOwner
let ownerId: number | null = null
if (owner) {
ownerId = ownerIds.get(owner) ?? ++nextOwnerId
@@ -73,6 +85,11 @@ async function installSidebarFrameProbe(page: Page) {
pathname: location.pathname,
ownerId,
scope: owner?.dataset.communityChannelTreeScope ?? null,
+ retainedOwner: retainedOwner ? {
+ scope: retainedOwner.dataset.communityChannelTreeScope ?? null,
+ hidden: ownerHidden,
+ inert: ownerInert,
+ } : null,
pendingServer: sidebar?.querySelector<HTMLElement>("[data-pending-server-id]")
?.dataset.pendingServerId ?? null,
skeleton: sidebar?.querySelector('[data-slot="skeleton"]') !== null,
@@ -377,6 +394,8 @@ test("server switching exposes one target-scoped cold checkpoint and skips it wh
expect(coldPendingFrames.length).toBeGreaterThan(0)
expect(coldPendingFrames.every((frame) => frame.ownerId === null && frame.rows.length === 0))
.toBe(true)
+ expect(coldPendingFrames.every((frame) => !frame.retainedOwner
+ || frame.retainedOwner.hidden && frame.retainedOwner.inert)).toBe(true)
expectAtomicTargetFrames(coldFrames, `server:${serverC}`, channelC, [channelA])
await clickServer(page, serverA)
diff --git a/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts b/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts
index a134edc1e..f55e88b5a 100644
--- a/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts
+++ b/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts
@@ -737,6 +737,11 @@ test("short server rail keeps Add adjacent and desktop geometry stable", async (
expect(mobile.targetOwnsCenter).toBe(true)
await page.setViewportSize({ width: 1280, height: 844 })
+ await expect(page).toHaveURL(new RegExp(`/c/channels/${serverId}/[^/]+$`))
+ const channelId = new URL(page.url()).pathname.split("/").at(-1)!
+ await expect(page.locator(
+ `[data-slot="community-conversation-surface"][data-channel-id="${channelId}"]`,
+ ).getByTestId(tid.composerInput)).toBeVisible()
const desktop = await railGeometry(page, serverId)
expect(desktop.rootScrollTop).toBe(0)
expect(desktop.target).toEqual(mobile.target)
diff --git a/src/web/src/test/e2e-ui/46-community-loading-geometry-dark.spec.ts b/src/web/src/test/e2e-ui/46-community-loading-geometry-dark.spec.ts
index 4c1256a2a..8b87809a7 100644
--- a/src/web/src/test/e2e-ui/46-community-loading-geometry-dark.spec.ts
+++ b/src/web/src/test/e2e-ui/46-community-loading-geometry-dark.spec.ts
@@ -1,5 +1,6 @@
import { test } from "./_fixtures/community-fixture"
import {
+ cleanupGeometryServers,
runDesktopPersistedPendingGeometry,
runNeutralRootGeometry,
runRouteLoadingGeometry,
@@ -8,10 +9,15 @@ import {
test.describe.serial("community dark loading geometry", () => {
let routes!: Awaited<ReturnType<typeof seedGeometryRoutes>>
+ const serverIds: string[] = []
test.beforeAll(async () => {
test.setTimeout(120_000)
- routes = await seedGeometryRoutes()
+ routes = await seedGeometryRoutes(serverIds)
+ })
+
+ test.afterAll(async () => {
+ await cleanupGeometryServers(serverIds)
})
test("dark: neutral root owns two viewport cold restores", async ({ asUser }, testInfo) => {
diff --git a/src/web/src/test/e2e-ui/46-community-loading-geometry-light.spec.ts b/src/web/src/test/e2e-ui/46-community-loading-geometry-light.spec.ts
index a9a19d3b1..c099c1494 100644
--- a/src/web/src/test/e2e-ui/46-community-loading-geometry-light.spec.ts
+++ b/src/web/src/test/e2e-ui/46-community-loading-geometry-light.spec.ts
@@ -1,5 +1,6 @@
import { test } from "./_fixtures/community-fixture"
import {
+ cleanupGeometryServers,
runDesktopPersistedPendingGeometry,
runNeutralRootGeometry,
runRouteLoadingGeometry,
@@ -8,10 +9,15 @@ import {
test.describe.serial("community light loading geometry", () => {
let routes!: Awaited<ReturnType<typeof seedGeometryRoutes>>
+ const serverIds: string[] = []
test.beforeAll(async () => {
test.setTimeout(120_000)
- routes = await seedGeometryRoutes()
+ routes = await seedGeometryRoutes(serverIds)
+ })
+
+ test.afterAll(async () => {
+ await cleanupGeometryServers(serverIds)
})
test("light: neutral root owns two viewport cold restores", async ({ asUser }, testInfo) => {
diff --git a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
index d81ec4f69..0b8332869 100644
--- a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
+++ b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
@@ -1137,32 +1137,6 @@ test.describe.serial("message scroll characterization", () => {
}
await editable.fill("")
- const rapidPrecondition = await establishScrollDistancePrecondition(scroller, "rapid-resize-away", 2)
- await markScrollTrace(alice.page, "rapid-resize-away-precondition", { detail: rapidPrecondition })
- await beginScrollTraceAnalysis(alice.page, "rapid-composer-resizes")
- const rapidBase = await waitForCommittedGeometry(scroller)
- await editable.fill(composerLines("rapid-small", 2))
- const rapidGrowOne = await waitForCommittedGeometry(scroller)
- await editable.fill(composerLines("rapid-large", 6))
- const rapidGrowTwo = await waitForCommittedGeometry(scroller)
- await editable.fill(composerLines("rapid-small", 2))
- const rapidShrinkOne = await waitForCommittedGeometry(scroller)
- await editable.fill("")
- const rapidShrinkTwo = await waitForCommittedGeometry(scroller)
- expect(rapidGrowOne.clientHeight).toBeLessThan(rapidBase.clientHeight)
- expect(rapidGrowTwo.clientHeight).toBeLessThan(rapidGrowOne.clientHeight)
- expect(rapidShrinkOne.clientHeight).toBe(rapidGrowOne.clientHeight)
- expect(rapidShrinkTwo.clientHeight).toBe(rapidBase.clientHeight)
- for (const [label, geometry] of [
- ["grow-one", rapidGrowOne],
- ["grow-two", rapidGrowTwo],
- ["shrink-one", rapidShrinkOne],
- ["shrink-two", rapidShrinkTwo],
- ] as const) {
- expectResizeAnchorPreserved(rapidBase, geometry, 2, `rapid-${label}`)
- expectInFlowMessageGeometry(geometry, `rapid-${label}`)
- }
- await endScrollTraceAnalysis(alice.page, "rapid-composer-resizes")
await advanceScrollTraceFrame(scroller)
const selectionDraft = composerLines("selection-draft", 8)
diff --git a/src/web/src/test/e2e-ui/57-server-delete-navigation-races.spec.ts b/src/web/src/test/e2e-ui/57-server-delete-navigation-races.spec.ts
index 749286f4f..643f0c5ec 100644
--- a/src/web/src/test/e2e-ui/57-server-delete-navigation-races.spec.ts
+++ b/src/web/src/test/e2e-ui/57-server-delete-navigation-races.spec.ts
@@ -1,5 +1,5 @@
import type { Page, WebSocket } from "@playwright/test"
-import { expect, sessionCookie, test } from "./_fixtures/community-fixture"
+import { expect, sessionCookie, test, userId } from "./_fixtures/community-fixture"
import { gotoAfterUserWsAuth, openServer } from "./_fixtures/actions"
import { seedChannel, seedServer } from "./_fixtures/seed"
import { tid } from "./_fixtures/testids"
@@ -77,11 +77,17 @@ async function seedServerRoute(
return { serverId, channelId }
}
-async function clickDeleteServer(page: Page, serverId: string): Promise<void> {
+async function clickDeleteServer(
+ page: Page,
+ serverId: string,
+ beforeConfirm?: () => Promise<void>,
+): Promise<void> {
await page.getByTestId(tid.serverIcon(serverId)).click({ button: "right" })
await page.getByTestId(tid.serverSettingsOpen).click()
await expect(page.getByTestId(tid.settingsShell)).toBeVisible()
await page.getByRole("button", { name: "Delete Server", exact: true }).click()
+ await expect(page.getByRole("dialog")).toBeVisible()
+ await beforeConfirm?.()
await page.getByRole("dialog").getByRole("button", {
name: "Delete Server",
exact: true,
@@ -193,25 +199,36 @@ async function expectServerLeaf(page: Page, serverId: string): Promise<string> {
test.describe.configure({ mode: "serial" })
test("deleting the only Server replaces once to Home", async ({ asUser }) => {
- const route = await seedServerRoute("dave", `delete-only-${Date.now()}`)
- const dave = await asUser("dave")
+ const key = "sole-delete"
+ expect(await serverIds(key)).toEqual([])
+ const route = await seedServerRoute(key, `delete-only-${Date.now()}`)
+ const page = (await asUser(key)).page
await gotoAfterUserWsAuth(
- dave.page,
+ page,
`/c/channels/${route.serverId}/${route.channelId}`,
)
- await installHistoryRecorder(dave.page)
- await resetHistoryRecorder(dave.page)
- const response = dave.page.waitForResponse((candidate) => (
+ await installHistoryRecorder(page)
+ const response = page.waitForResponse((candidate) => (
candidate.request().method() === "DELETE"
&& new URL(candidate.url()).pathname === `/api/community/servers/${route.serverId}`
))
- await clickDeleteServer(dave.page, route.serverId)
+ await clickDeleteServer(page, route.serverId, async () => {
+ expect(await serverIds(key)).toEqual([route.serverId])
+ const membershipResponse = await page.request.get(`/api/community/servers/${route.serverId}/members`)
+ expect(membershipResponse.status()).toBe(200)
+ const body = await membershipResponse.json() as { members: Array<{ userId: string }> }
+ expect(body.members.map((member) => member.userId)).toContain(userId(key))
+ await expect(page).toHaveURL(`/c/channels/${route.serverId}/${route.channelId}`)
+ await resetHistoryRecorder(page)
+ })
expect((await response).status()).toBe(204)
- await expect(dave.page).toHaveURL("/c/me")
- await expect(dave.page.getByTestId(tid.serverIcon(route.serverId))).toHaveCount(0)
- expect(await divergentHistoryWrites(dave.page, "/c/me")).toEqual([])
+ await expect(page).toHaveURL("/c/me")
+ await expect(page.getByTestId(tid.serverIcon(route.serverId))).toHaveCount(0)
+ await expect(page.getByText("Server deleted", { exact: true })).toBeVisible()
+ expect(await divergentHistoryWrites(page, "/c/me")).toEqual([])
+ expect(await serverIds(key)).toEqual([])
})
for (const testCase of [
@@ -243,7 +260,8 @@ for (const testCase of [
expect((await deletion.response).status()).toBe(204)
await expect(page).toHaveURL(safePathname)
- await expect(page.getByText("Server deleted", { exact: true })).toBeVisible()
+ await expect(page.getByTestId(tid.serverIcon(deleted.serverId))).toHaveCount(0)
+ await expect(page.getByText("Server deleted", { exact: true })).toHaveCount(0)
expect(await divergentHistoryWrites(page, safePathname)).toEqual([])
await deletion.cleanup()
})
@@ -339,7 +357,8 @@ test("a Back visit after terminal cleanup is an ordinary missing route", async (
deletion.release()
expect((await deletion.response).status()).toBe(204)
await expect(page).toHaveURL(safePathname)
- await expect(page.getByText("Server deleted", { exact: true })).toBeVisible()
+ await expect(page.getByTestId(tid.serverIcon(deleted.serverId))).toHaveCount(0)
+ await expect(page.getByText("Server deleted", { exact: true })).toHaveCount(0)
await page.goBack({ waitUntil: "commit" })
await expect(page).not.toHaveURL(new RegExp(`/c/channels/${deleted.serverId}(?:/|$)`))
diff --git a/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts b/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts
index d3d680719..7fd48b3b3 100644
--- a/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts
@@ -14,6 +14,7 @@ import {
COMMUNITY_SURFACE_BORDER_WIDTH,
} from "@/components/community/shell/shell-frame-geometry"
import {
+ retireSeedServers,
seedChannel,
seedDm,
seedForumThread,
@@ -433,11 +434,16 @@ async function visibleSkeletonAnimationProperties(page: Page) {
)).sort())
}
-export async function seedGeometryRoutes(): Promise<Omit<MatrixCase, "width">[]> {
+export async function cleanupGeometryServers(serverIds: readonly string[]): Promise<void> {
+ await retireSeedServers(ISOLATED_GEOMETRY_USER, serverIds)
+}
+
+export async function seedGeometryRoutes(serverIds: string[]): Promise<Omit<MatrixCase, "width">[]> {
const stamp = Date.now()
const serverId = await seedServer(ISOLATED_GEOMETRY_USER, `Geometry ${stamp}`)
+ serverIds.push(serverId)
for (let index = 1; index < RAIL_OVERFLOW_SERVER_COUNT; index += 1) {
- await seedServer(ISOLATED_GEOMETRY_USER, `Geometry rail ${stamp}-${index}`)
+ serverIds.push(await seedServer(ISOLATED_GEOMETRY_USER, `Geometry rail ${stamp}-${index}`))
}
const textId = await seedChannel(ISOLATED_GEOMETRY_USER, serverId, `geometry-text-${stamp}`)
const forumId = await seedChannel(
@@ -792,7 +798,15 @@ export async function runRouteLoadingGeometry(
expect(await railScroll.evaluate((element) => element.scrollHeight > element.clientHeight))
.toBe(true)
} else {
- await expect(loadedAdd).toHaveCount(0)
+ await expect(loadedAdd).toHaveCount(1)
+ await expect(loadedAdd).toBeHidden()
+ expect(await loadedAdd.evaluate((element) => (
+ element.closest('[inert][aria-hidden="true"]') !== null
+ ))).toBe(true)
+ expect(await loadedAdd.evaluate((element) => {
+ element.focus()
+ return document.activeElement === element
+ })).toBe(false)
}
expect(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth))
.toBe(true)
diff --git a/src/web/src/test/e2e-ui/_fixtures/seed.ts b/src/web/src/test/e2e-ui/_fixtures/seed.ts
index a01083bd6..09d1e2467 100644
--- a/src/web/src/test/e2e-ui/_fixtures/seed.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/seed.ts
@@ -38,6 +38,24 @@ export async function seedServer(owner: UserKey, name: string): Promise<string>
return data.server.id
}
+export async function retireSeedServers(owner: UserKey, serverIds: readonly string[]): Promise<void> {
+ const errors: unknown[] = []
+ for (const serverId of serverIds) {
+ try {
+ const response = await retrySeedRequest(() => fetch(`${WEB_URL}/api/community/servers/${serverId}`, {
+ method: "DELETE",
+ headers: { Cookie: sessionCookie(owner), Origin: WEB_URL },
+ }))
+ if (response.status !== 204 && response.status !== 404) {
+ throw new Error(`DELETE fixture server ${serverId} failed (${response.status})`)
+ }
+ } catch (error) {
+ errors.push(error)
+ }
+ }
+ if (errors.length > 0) throw new AggregateError(errors, "Fixture server retirement failed")
+}
+
export async function seedChannel(
owner: UserKey,
serverId: string,
diff --git a/src/web/src/test/e2e-ui/_setup/users.ts b/src/web/src/test/e2e-ui/_setup/users.ts
index 2d29da75f..a822c123d 100644
--- a/src/web/src/test/e2e-ui/_setup/users.ts
+++ b/src/web/src/test/e2e-ui/_setup/users.ts
@@ -1,6 +1,6 @@
-export type UserKey = "alice" | "bob" | "carol" | "dave" | "logout"
+export type UserKey = "alice" | "bob" | "carol" | "dave" | "logout" | "sole-delete"
-export const USER_KEYS: UserKey[] = ["alice", "bob", "carol", "dave", "logout"]
+export const USER_KEYS: UserKey[] = ["alice", "bob", "carol", "dave", "logout", "sole-delete"]
export function emailFor(key: UserKey, stamp: string): string {
return `e2e-${key}-${stamp}@alook.test`