Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): checkpoint pending server switches (#584)

Generb5bc5fa85478
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index e28b49802..3b40dea23 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -46,6 +46,7 @@ export const SPEC_SECONDS = {
"33-picker-async-layout.spec.ts": 57,
"34-inbox-read-race.spec.ts": 42,
"35-channel-ref-directory-states.spec.ts": 60,
+ "36-server-switch-pending-checkpoint.spec.ts": 60,
}
function walk(directory) {
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index f730d73cf..9ab06ac44 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -70,7 +70,7 @@ describe("planE2eShards", () => {
expect(first).toHaveLength(E2E_SHARD_COUNT)
expect([...assigned].sort()).toEqual(specs)
expect(new Set(assigned).size).toBe(specs.length)
- expect(totals.sort((left, right) => left - right)).toEqual([288, 289, 290, 292, 293])
+ expect(totals.sort((left, right) => left - right)).toEqual([301, 302, 302, 303, 304])
expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)
})
diff --git a/src/web/src/components/community/channels/channel-sidebar.tsx b/src/web/src/components/community/channels/channel-sidebar.tsx
index 89c648490..797b82967 100644
--- a/src/web/src/components/community/channels/channel-sidebar.tsx
+++ b/src/web/src/components/community/channels/channel-sidebar.tsx
@@ -461,15 +461,23 @@ function ForumSidebarThreadRow({
// Loading placeholder for the channel sidebar. Kept colocated so changes to
// row density or header height stay in sync with the live sidebar above.
-function ChannelSidebarSkeleton({
+export function ChannelSidebarSkeleton({
noHeader,
- showInviteAction,
+ showInviteAction = false,
+ targetServerId,
}: {
noHeader?: boolean
- showInviteAction: boolean
+ showInviteAction?: boolean
+ targetServerId?: string
}) {
return (
- <aside className="flex min-h-0 min-w-0 flex-1 flex-col">
+ <aside
+ data-testid={targetServerId ? tid.channelSidebarPending(targetServerId) : undefined}
+ data-pending-server-id={targetServerId}
+ aria-label={targetServerId ? "Loading server channels" : undefined}
+ aria-busy={targetServerId ? true : undefined}
+ className="flex min-h-0 min-w-0 flex-1 flex-col"
+ >
{!noHeader && (
<header className="flex h-12 items-center gap-1 border-b border-border/40 px-2">
<Skeleton className="ml-2 h-7 w-32 rounded" />
diff --git a/src/web/src/components/community/shell/server-rail-brand.test.ts b/src/web/src/components/community/shell/server-rail-brand.test.ts
index 08d0144bf..1b889c3ac 100644
--- a/src/web/src/components/community/shell/server-rail-brand.test.ts
+++ b/src/web/src/components/community/shell/server-rail-brand.test.ts
@@ -33,4 +33,12 @@ describe("ServerRail Home brand mark", () => {
expect(scrollViewport).not.toContain("flex-1")
expect(source).not.toContain("pb-2 overflow-y-auto overflow-x-clip thin-scrollbar")
})
+
+ it("keeps an explicit active server controlled until the route commits", () => {
+ const source = readFileSync(new URL("./server-rail.tsx", import.meta.url), "utf8")
+
+ expect(source).toContain("const activeId = activeFromProps || localActiveId")
+ expect(source).toContain("setLocalActiveId(id)")
+ expect(source).not.toContain("const [activeId, setActiveId]")
+ })
})
diff --git a/src/web/src/components/community/shell/server-rail.tsx b/src/web/src/components/community/shell/server-rail.tsx
index cdc0ae52b..f851b3051 100644
--- a/src/web/src/components/community/shell/server-rail.tsx
+++ b/src/web/src/components/community/shell/server-rail.tsx
@@ -70,13 +70,14 @@ export const ServerRail = memo(function ServerRail({
}
const activeFromProps = activeServerIdProp ?? servers.find((s) => s.active)?.id ?? ""
- const [activeId, setActiveId] = useState(activeFromProps)
- useEffect(() => { if (activeFromProps) setActiveId(activeFromProps) }, [activeFromProps])
+ const [localActiveId, setLocalActiveId] = useState(activeFromProps)
+ const activeId = activeFromProps || localActiveId
+ useEffect(() => { if (activeFromProps) setLocalActiveId(activeFromProps) }, [activeFromProps])
const [createOpen, setCreateOpen] = useState(false)
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }))
- const pickServer = (id: string) => { setActiveId(id); onServer?.(); onServerNavigate?.(id) }
+ const pickServer = (id: string) => { setLocalActiveId(id); onServer?.(); onServerNavigate?.(id) }
const serverById = useMemo(() => new Map(servers.map((s) => [s.id, s])), [servers])
const folderById = useMemo(() => new Map(folders.map((f) => [f.id, f])), [folders])
diff --git a/src/web/src/components/community/shell/shell-frame-view.test.ts b/src/web/src/components/community/shell/shell-frame-view.test.ts
index 95c5d6434..69739a5c3 100644
--- a/src/web/src/components/community/shell/shell-frame-view.test.ts
+++ b/src/web/src/components/community/shell/shell-frame-view.test.ts
@@ -39,6 +39,9 @@ vi.mock("./shell-frame-overlays", () => ({
vi.mock("./community-pending-frame", () => ({
CommunityPendingFrame: (props: Record<string, unknown>) => createElement("channel-loading-frame", props),
}))
+vi.mock("@/components/community/channels/channel-sidebar", () => ({
+ ChannelSidebarSkeleton: (props: Record<string, unknown>) => createElement("channel-sidebar-skeleton", props),
+}))
const rail = { railProps: { activeServerId: "s1" } } as never
const profile = {
@@ -405,4 +408,45 @@ describe("ShellFrameView", () => {
expect(renderer.root.findByType("channel-loading-frame").props.reserveBackSlot).toBe(true)
expect(renderer.root.findByType("channel-loading-frame").props.onBack).toBeUndefined()
})
+
+ it("replaces the committed sidebar with one target-scoped cold server checkpoint", async () => {
+ const sidebar = vi.fn(() => createElement("old-sidebar"))
+ const common = {
+ surface: "list" as const,
+ loadingHref: "/c/channels/s2",
+ cancelPendingNavigation: vi.fn(),
+ navigationPending: true,
+ serverSwitchTargetId: "s2",
+ sidebar,
+ rail,
+ profile,
+ inbox,
+ }
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(
+ ShellFrameView,
+ { ...common, breakpoint: "desktop" },
+ createElement("old-main"),
+ ), { createNodeMock: () => ({ offsetWidth: 240 }) })
+ })
+
+ expect(sidebar).not.toHaveBeenCalled()
+ expect(renderer.root.findAllByType("old-sidebar")).toHaveLength(0)
+ expect(renderer.root.findByType("channel-sidebar-skeleton").props.targetServerId).toBe("s2")
+ expect(renderer.root.findByType("channel-loading-frame").props.href).toBe("/c/channels/s2")
+
+ await act(async () => {
+ renderer.update(createElement(
+ ShellFrameView,
+ { ...common, breakpoint: "mobile" },
+ createElement("old-main"),
+ ))
+ })
+ const [sidebarPanel, mainPanel] = renderer.root.findAllByType("panel")
+ expect(sidebarPanel?.props["data-mobile-active"]).toBe(true)
+ expect(sidebarPanel?.findAllByType("channel-sidebar-skeleton")).toHaveLength(1)
+ expect(mainPanel?.props.hidden).toBe(true)
+ expect(sidebar).not.toHaveBeenCalled()
+ })
})
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 f3be305e6..fdc39e786 100644
--- a/src/web/src/components/community/shell/shell-frame-view.tsx
+++ b/src/web/src/components/community/shell/shell-frame-view.tsx
@@ -4,6 +4,7 @@ import { useEffect, useRef, useState, type CSSProperties } from "react"
import { useDefaultLayout } from "react-resizable-panels"
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@/components/ui/resizable"
import { AppSurface } from "@/components/ui/app-surface"
+import { ChannelSidebarSkeleton } from "@/components/community/channels/channel-sidebar"
import { CommunityPendingFrame } from "./community-pending-frame"
import { Shell } from "./shell"
import { ServerRail } from "./server-rail"
@@ -28,6 +29,7 @@ type Props = Pick<ShellFrameProps, "sidebar" | "children" | "extraDialogs"> & {
loadingHref: string
cancelPendingNavigation: () => void
navigationPending: boolean
+ serverSwitchTargetId?: string | null
rail: ReturnType<typeof useShellRailController>
profile: ReturnType<typeof useShellProfileController>
inbox: ReturnType<typeof useShellInboxController>
@@ -44,6 +46,7 @@ export function ShellFrameView({
extraDialogs,
cancelPendingNavigation,
navigationPending,
+ serverSwitchTargetId = null,
rail,
profile,
inbox,
@@ -129,7 +132,11 @@ export function ShellFrameView({
)}
>
<div ref={sidebarPanelRef} className="flex min-h-0 min-w-0 flex-1 flex-col">
- {!isMobileDetail && (isDesktop ? sidebar() : sidebar({ noHeader: false }))}
+ {!isMobileDetail && (
+ serverSwitchTargetId
+ ? <ChannelSidebarSkeleton targetServerId={serverSwitchTargetId} />
+ : isDesktop ? sidebar() : sidebar({ noHeader: false })
+ )}
</div>
</ResizablePanel>
<ResizableHandle className={cn("bg-transparent", !isDesktop && "hidden")} />
diff --git a/src/web/src/components/community/shell/shell-frame.test.ts b/src/web/src/components/community/shell/shell-frame.test.ts
index 605412adc..27ce7feb2 100644
--- a/src/web/src/components/community/shell/shell-frame.test.ts
+++ b/src/web/src/components/community/shell/shell-frame.test.ts
@@ -14,6 +14,8 @@ const mocks = vi.hoisted(() => {
return {
currentHref: { current: "/c/channels/s1" },
pendingHref: { current: null as string | null },
+ navigationPending: { current: false },
+ serverCache: new Set<string>(),
breakpoint: { current: "desktop" },
onboardingState: { current: null as Record<string, unknown> | null },
replace: vi.fn(),
@@ -35,7 +37,13 @@ const mocks = vi.hoisted(() => {
}
})
-vi.mock("@tanstack/react-query", () => ({ useQueryClient: () => ({}) }))
+vi.mock("@tanstack/react-query", () => ({
+ useQueryClient: () => ({
+ getQueryData: (key: unknown[]) => mocks.serverCache.has(String(key.at(-1)))
+ ? { id: key.at(-1) }
+ : undefined,
+ }),
+}))
vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mocks.breakpoint.current }))
vi.mock("@/lib/community-onboarding", () => ({
useCommunityOnboarding: () => mocks.onboardingState.current,
@@ -43,7 +51,7 @@ vi.mock("@/lib/community-onboarding", () => ({
vi.mock("./use-community-navigation-controller", () => ({
useCommunityNavigationController: () => ({
currentHref: mocks.currentHref.current,
- navigationPending: false,
+ navigationPending: mocks.navigationPending.current,
pendingHref: mocks.pendingHref.current,
push: mocks.push,
replace: mocks.replace,
@@ -83,6 +91,8 @@ describe("ShellFrame orchestration", () => {
beforeEach(() => {
mocks.currentHref.current = "/c/channels/s1"
mocks.pendingHref.current = null
+ mocks.navigationPending.current = false
+ mocks.serverCache.clear()
mocks.breakpoint.current = "desktop"
mocks.onboardingState.current = null
mocks.registerUiHandlers.mockClear()
@@ -127,6 +137,51 @@ describe("ShellFrame orchestration", () => {
.toBe("/c/me/dm_1?from=inbox")
})
+ it("projects one cold cross-server target into rail, middle, and right", async () => {
+ mocks.currentHref.current = "/c/channels/s1/c1"
+ mocks.pendingHref.current = "/c/channels/s2"
+ mocks.navigationPending.current = true
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(ShellFrame, baseProps))
+ })
+
+ const view = renderer.root.findByType("shell-frame-view")
+ expect(view.props).toMatchObject({
+ surface: "list",
+ loadingHref: "/c/channels/s2",
+ navigationPending: true,
+ serverSwitchTargetId: "s2",
+ })
+ expect(mocks.railOptions).toHaveBeenLastCalledWith(expect.objectContaining({
+ activeServerId: "s1",
+ projectedActiveServerId: "s2",
+ }))
+ })
+
+ it("lets an exact warm target skip both forced checkpoints without relabeling A", async () => {
+ mocks.currentHref.current = "/c/channels/s1/c1"
+ mocks.pendingHref.current = "/c/channels/s2"
+ mocks.navigationPending.current = true
+ mocks.serverCache.add("s2")
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(ShellFrame, baseProps))
+ })
+
+ const view = renderer.root.findByType("shell-frame-view")
+ expect(view.props).toMatchObject({
+ surface: "detail",
+ loadingHref: "/c/channels/s1/c1",
+ navigationPending: false,
+ serverSwitchTargetId: null,
+ })
+ expect(mocks.railOptions).toHaveBeenLastCalledWith(expect.objectContaining({
+ activeServerId: "s1",
+ projectedActiveServerId: "s1",
+ }))
+ })
+
it("replaces a mobile detail with its semantic parent", async () => {
mocks.breakpoint.current = "mobile"
mocks.currentHref.current = "/c/channels/s1/c1"
diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsx
index e7a2a01d6..23f1ded54 100644
--- a/src/web/src/components/community/shell/shell-frame.tsx
+++ b/src/web/src/components/community/shell/shell-frame.tsx
@@ -4,7 +4,12 @@ import { useCallback, useEffect } from "react"
import { useQueryClient } from "@tanstack/react-query"
import { useBreakpoint } from "@/hooks/use-mobile"
import { useCommunityOnboarding } from "@/lib/community-onboarding"
-import { resolveCommunityRoute } from "@/lib/community/community-route"
+import {
+ communityServerId,
+ resolveCommunityRoute,
+ resolveServerSwitchCheckpoint,
+} from "@/lib/community/community-route"
+import { communityKeys } from "@/lib/query-keys"
import { useCommunityStore } from "@/stores/community"
import { ShellFrameView } from "./shell-frame-view"
import { useShellRailController } from "./use-shell-rail-controller"
@@ -33,6 +38,20 @@ export function ShellFrame(props: ShellFrameProps) {
const route = resolveCommunityRoute(pathname)
const pendingPathname = navigation.pendingHref?.split("?")[0]
const pendingRoute = pendingPathname ? resolveCommunityRoute(pendingPathname) : null
+ const pendingServerId = navigation.pendingHref
+ ? communityServerId(navigation.pendingHref)
+ : null
+ const serverSwitch = resolveServerSwitchCheckpoint({
+ currentHref: navigation.currentHref,
+ pendingHref: navigation.pendingHref,
+ hasExactServerDetail: pendingServerId
+ ? queryClient.getQueryData(communityKeys.server(pendingServerId)) !== undefined
+ : false,
+ })
+ const coldServerSwitchTargetId = serverSwitch?.cold
+ ? serverSwitch.targetServerId
+ : null
+ const warmServerSwitch = serverSwitch != null && !serverSwitch.cold
const rail = useShellRailController({
navigation,
@@ -40,6 +59,7 @@ export function ShellFrame(props: ShellFrameProps) {
breakpoint,
view,
activeServerId,
+ projectedActiveServerId: coldServerSwitchTargetId ?? activeServerId,
onOpenActiveServerSettings,
onOpenActiveServerInvite,
})
@@ -95,12 +115,15 @@ export function ShellFrame(props: ShellFrameProps) {
return (
<ShellFrameView
breakpoint={breakpoint}
- surface={pendingRoute?.surface ?? route.surface}
- loadingHref={navigation.pendingHref ?? navigation.currentHref}
+ surface={warmServerSwitch ? route.surface : pendingRoute?.surface ?? route.surface}
+ loadingHref={warmServerSwitch
+ ? navigation.currentHref
+ : navigation.pendingHref ?? navigation.currentHref}
sidebar={sidebar}
extraDialogs={extraDialogs}
cancelPendingNavigation={navigation.cancelPendingNavigation}
- navigationPending={navigation.navigationPending}
+ navigationPending={navigation.navigationPending && !warmServerSwitch}
+ serverSwitchTargetId={coldServerSwitchTargetId}
rail={rail}
profile={profile}
inbox={inbox}
diff --git a/src/web/src/components/community/shell/use-community-navigation-controller.test.ts b/src/web/src/components/community/shell/use-community-navigation-controller.test.ts
index 9c6df88c7..1aed5c843 100644
--- a/src/web/src/components/community/shell/use-community-navigation-controller.test.ts
+++ b/src/web/src/components/community/shell/use-community-navigation-controller.test.ts
@@ -68,6 +68,32 @@ describe("useCommunityNavigationController", () => {
expect(hook.current.pendingHref).toBeNull()
})
+ it("keeps only rapid B pending when stale A commits before B", async () => {
+ const hook = await renderController()
+ await act(async () => {
+ hook.current.push("/c/channels/s1")
+ hook.current.push("/c/channels/s2")
+ })
+ expect(mocks.push.mock.calls.map(([href]) => href)).toEqual([
+ "/c/channels/s1",
+ "/c/channels/s2",
+ ])
+ expect(hook.current.pendingHref).toBe("/c/channels/s2")
+
+ mocks.pathname.current = "/c/channels/s1"
+ await hook.rerender()
+ expect(hook.current.navigationPending).toBe(true)
+ expect(hook.current.pendingHref).toBe("/c/channels/s2")
+
+ // The semantic server-root intent may commit through its canonical
+ // landing redirect. That leaf still commits the exact latest server
+ // target; the stale s1 leaf above must not.
+ mocks.pathname.current = "/c/channels/s2/c2"
+ await hook.rerender()
+ expect(hook.current.navigationPending).toBe(false)
+ expect(hook.current.pendingHref).toBeNull()
+ })
+
it("uses replace for semantic parent navigation", async () => {
const hook = await renderController()
await act(async () => hook.current.replace("/c/channels/s1"))
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 de4a19303..9bd234af5 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
@@ -7,6 +7,7 @@ import {
createNavigationIntentGate,
supersedeNavigationIntent,
} from "@/lib/community/navigation-intent"
+import { communityServerId, serverRootHref } from "@/lib/community/community-route"
import type { ShellRouter } from "./shell-frame-types"
export type CommunityNavigationController = {
@@ -20,6 +21,15 @@ export type CommunityNavigationController = {
cancelPendingNavigation: () => void
}
+function hasCommittedPendingHref(currentHref: string, pendingHref: string): boolean {
+ if (currentHref === pendingHref) return true
+ const pendingServerId = communityServerId(pendingHref)
+ if (!pendingServerId) return false
+ const pendingPathname = pendingHref.split(/[?#]/, 1)[0]
+ return pendingPathname === serverRootHref(pendingServerId)
+ && communityServerId(currentHref) === pendingServerId
+}
+
export function useCommunityNavigationController(): CommunityNavigationController {
const router = useRouter() as ShellRouter
const pathname = usePathname()
@@ -37,10 +47,14 @@ export function useCommunityNavigationController(): CommunityNavigationControlle
}, [])
useEffect(() => {
+ // A stale route commit must not clear a newer synchronous intent. Keep the
+ // latest pending href until that exact destination becomes current; Shell
+ // navigation intent/cancellation still clears it explicitly.
+ if (pendingHref !== null && !hasCommittedPendingHref(currentHref, pendingHref)) return
supersedeNavigationIntent(gateRef.current)
setNavigationPending(false)
- setPendingHref(null)
- }, [currentHref])
+ if (pendingHref !== null) setPendingHref(null)
+ }, [currentHref, pendingHref])
const push = useCallback((href: string) => {
if (href === currentHref) return
diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.test.ts b/src/web/src/components/community/shell/use-shell-rail-controller.test.ts
index 6c89fa078..057b02a26 100644
--- a/src/web/src/components/community/shell/use-shell-rail-controller.test.ts
+++ b/src/web/src/components/community/shell/use-shell-rail-controller.test.ts
@@ -83,6 +83,7 @@ async function renderController(overrides: Record<string, unknown> = {}) {
const navigation = {
currentHref: "/c/channels/s1",
navigationPending: false,
+ pendingHref: null,
push: router.push,
replace: router.replace,
prefetch: router.prefetch,
@@ -152,6 +153,22 @@ describe("useShellRailController", () => {
})
+ it("projects the pending target for every rail entry without changing committed actions", async () => {
+ const openSettings = vi.fn()
+ const hook = await renderController({
+ projectedActiveServerId: "s2",
+ onOpenActiveServerSettings: openSettings,
+ })
+
+ expect(hook.current.railProps.activeServerId).toBe("s2")
+ expect(hook.current.railProps.servers.map((server) => [server.id, server.active]))
+ .toEqual([["s1", false], ["s2", true]])
+
+ await act(async () => hook.current.railProps.onOpenSettings("s2"))
+ expect(openSettings).not.toHaveBeenCalled()
+ expect(hook.pushed).toEqual(["/c/channels/s2?settings=1"])
+ })
+
it("does not leave deferred server work that can overwrite a direct channel navigation", async () => {
const hook = await renderController()
await act(async () => {
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 fc40e9675..df8e3df29 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
@@ -37,6 +37,7 @@ type Options = Pick<
navigation: CommunityNavigationController
queryClient: QueryClient
breakpoint: Breakpoint
+ projectedActiveServerId?: string
}
export function useShellRailController({
@@ -45,6 +46,7 @@ export function useShellRailController({
breakpoint,
view,
activeServerId,
+ projectedActiveServerId = activeServerId,
onOpenActiveServerSettings,
onOpenActiveServerInvite,
}: Options) {
@@ -69,8 +71,8 @@ export function useShellRailController({
const railServers = useMemo(
() => servers
.filter((server) => !folderServerIds.has(server.id))
- .map((server) => ({ ...server, active: server.id === activeServerId })),
- [activeServerId, folderServerIds, servers],
+ .map((server) => ({ ...server, active: server.id === projectedActiveServerId })),
+ [folderServerIds, projectedActiveServerId, servers],
)
const serverDestination = useCallback((id: string) => {
@@ -213,7 +215,7 @@ export function useShellRailController({
railProps: {
servers: railServers,
folders,
- activeServerId,
+ activeServerId: projectedActiveServerId,
serversLoading: serversQuery.isLoading,
view,
onHome,
diff --git a/src/web/src/lib/community/community-route.test.ts b/src/web/src/lib/community/community-route.test.ts
index 8b4a7641d..8cd0e1bfd 100644
--- a/src/web/src/lib/community/community-route.test.ts
+++ b/src/web/src/lib/community/community-route.test.ts
@@ -1,8 +1,10 @@
import { describe, expect, it } from "vitest"
import {
channelHref,
+ communityServerId,
removeCommunityParam,
resolveCommunityRoute,
+ resolveServerSwitchCheckpoint,
serverModalMarkerCleanupHref,
serverRootHref,
} from "./community-route"
@@ -25,6 +27,55 @@ describe("community route", () => {
expect(channelHref("server_1", "child_1")).toBe("/c/channels/server_1/child_1")
})
+ it.each([
+ ["/c/channels/server_1", "server_1"],
+ ["/c/channels/server_1/channel_1?keep=1#message", "server_1"],
+ ["/c/me", null],
+ ["/not-community/channels/server_1", null],
+ ])("extracts the community server identity from %s", (href, serverId) => {
+ expect(communityServerId(href)).toBe(serverId)
+ })
+
+ it("keeps a cold target checkpoint through eager pathname publication", () => {
+ expect(resolveServerSwitchCheckpoint({
+ currentHref: "/c/channels/server_1/channel_1",
+ pendingHref: "/c/channels/server_2?settings=1",
+ hasExactServerDetail: false,
+ })).toEqual({ targetServerId: "server_2", cold: true })
+ expect(resolveServerSwitchCheckpoint({
+ currentHref: "/c/channels/server_1/channel_1",
+ pendingHref: "/c/channels/server_2",
+ hasExactServerDetail: true,
+ })).toEqual({ targetServerId: "server_2", cold: false })
+ expect(resolveServerSwitchCheckpoint({
+ currentHref: "/c/channels/server_2",
+ pendingHref: "/c/channels/server_2",
+ hasExactServerDetail: false,
+ })).toEqual({ targetServerId: "server_2", cold: true })
+ expect(resolveServerSwitchCheckpoint({
+ currentHref: "/c/channels/server_1/channel_1",
+ pendingHref: "/c/channels/server_1/channel_2#message",
+ hasExactServerDetail: true,
+ })).toBeNull()
+
+ for (const pendingHref of [
+ null,
+ "/c/me/friends",
+ "/malformed",
+ ]) {
+ expect(resolveServerSwitchCheckpoint({
+ currentHref: "/c/channels/server_1/channel_1",
+ pendingHref,
+ hasExactServerDetail: false,
+ })).toBeNull()
+ }
+ expect(resolveServerSwitchCheckpoint({
+ currentHref: "/c/me/friends",
+ pendingHref: "/c/channels/server_2",
+ hasExactServerDetail: false,
+ })).toBeNull()
+ })
+
it("removes one query key while preserving the rest and the hash", () => {
expect(removeCommunityParam("/c/me/dm_1?seq=4&keep=1#x", "seq")).toBe(
"/c/me/dm_1?keep=1#x",
diff --git a/src/web/src/lib/community/community-route.ts b/src/web/src/lib/community/community-route.ts
index 7b39a6507..d4c77ae13 100644
--- a/src/web/src/lib/community/community-route.ts
+++ b/src/web/src/lib/community/community-route.ts
@@ -5,6 +5,40 @@ export type CommunityRoute = {
parentPath: string | null
}
+export type ServerSwitchCheckpoint = {
+ targetServerId: string
+ cold: boolean
+}
+
+export function communityServerId(href: string): string | null {
+ const pathname = href.split(/[?#]/, 1)[0]
+ const segments = pathname?.split("/").filter(Boolean) ?? []
+ return segments[0] === "c" && segments[1] === "channels" && segments[2]
+ ? segments[2]
+ : null
+}
+
+export function resolveServerSwitchCheckpoint({
+ currentHref,
+ pendingHref,
+ hasExactServerDetail,
+}: {
+ currentHref: string
+ pendingHref: string | null
+ hasExactServerDetail: boolean
+}): ServerSwitchCheckpoint | null {
+ if (!pendingHref) return null
+ const currentServerId = communityServerId(currentHref)
+ const targetServerId = communityServerId(pendingHref)
+ if (!currentServerId || !targetServerId) return null
+ // Next may publish the target pathname before the target layout's exact
+ // server detail is ready. pendingHref is still authoritative during that
+ // gap: keep the target-scoped cold checkpoint instead of exposing an empty
+ // target sidebar merely because both parsed ids now match.
+ if (currentServerId === targetServerId && hasExactServerDetail) return null
+ return { targetServerId, cold: !hasExactServerDetail }
+}
+
export function resolveCommunityRoute(pathname: string): CommunityRoute {
const segments = pathname.split("/").filter(Boolean)
if (segments[0] !== "c") return { surface: "detail", parentPath: null }
diff --git a/src/web/src/lib/community/testids.test.ts b/src/web/src/lib/community/testids.test.ts
index e9ca90c9c..b6fa996cc 100644
--- a/src/web/src/lib/community/testids.test.ts
+++ b/src/web/src/lib/community/testids.test.ts
@@ -44,6 +44,11 @@ describe("community QA selectors", () => {
expect(tid.messageScroller).toBe("community-message-scroller")
})
+ it("keys a pending channel sidebar by its target server", () => {
+ expect(tid.channelSidebarPending("server_1"))
+ .toBe("community-channel-sidebar-pending-server_1")
+ })
+
it("exposes attachment preview selectors from one canonical map", () => {
expect(tid.attachmentCard("notes.md")).toBe("community-attachment-card-notes.md")
expect(tid.attachmentPreviewSheet).toBe("community-attachment-preview-sheet")
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 446317658..a79dd18e3 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -16,6 +16,7 @@ export const tid = {
serverAdd: "community-server-add",
serverRailScroll: "community-server-rail-scroll",
channelSidebarScroll: "community-channel-sidebar-scroll",
+ channelSidebarPending: (serverId: string) => `community-channel-sidebar-pending-${serverId}`,
createServerSubmit: "community-create-server-submit",
createServerName: "community-create-server-name",
createChannelSubmit: "community-create-channel-submit",
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
new file mode 100644
index 000000000..aa9757319
--- /dev/null
+++ b/src/web/src/test/e2e-ui/36-server-switch-pending-checkpoint.spec.ts
@@ -0,0 +1,217 @@
+import type { Page, Route } from "@playwright/test"
+import { test, expect } from "./_fixtures/community-fixture"
+import { seedChannel, seedServer } from "./_fixtures/seed"
+import { tid } from "./_fixtures/testids"
+
+type HeldServer = {
+ heldNavigation: () => number
+ release: () => Promise<void>
+}
+
+async function holdServerTransition(
+ page: Page,
+ serverId: string,
+ { detail = true }: { detail?: boolean } = {},
+): Promise<HeldServer> {
+ let releaseGate!: () => void
+ const gate = new Promise<void>((resolve) => { releaseGate = resolve })
+ let heldNavigation = 0
+ const patterns: Array<{ pattern: string; navigation: boolean }> = [
+ { pattern: `**/c/channels/${serverId}**`, navigation: true },
+ ...(detail ? [
+ { pattern: `**/api/community/servers/${serverId}/categories**`, navigation: false },
+ { pattern: `**/api/community/servers/${serverId}/channels**`, navigation: false },
+ { pattern: `**/api/community/servers/${serverId}/unreads**`, navigation: false },
+ ] : []),
+ ]
+ const handlers = new Map<string, (route: Route) => Promise<void>>()
+ for (const { pattern, navigation } of patterns) {
+ const handler = async (route: Route) => {
+ if (navigation) heldNavigation += 1
+ await gate
+ await route.continue()
+ }
+ handlers.set(pattern, handler)
+ await page.route(pattern, handler)
+ }
+ return {
+ heldNavigation: () => heldNavigation,
+ release: async () => {
+ releaseGate()
+ await page.waitForTimeout(100)
+ await Promise.all([...handlers].map(([pattern, handler]) => page.unroute(pattern, handler)))
+ },
+ }
+}
+
+async function activateServerIcon(page: Page, serverId: string) {
+ const icon = page.getByTestId(tid.serverIcon(serverId))
+ // The first focus lazily mounts the icon's context-menu wrapper and replaces
+ // the trigger node. Let that a11y activation path settle so the following
+ // physical click targets the stable button rather than the pre-activation
+ // node, including during an immediate A→B supersession.
+ await icon.focus()
+ await expect(icon.locator("xpath=ancestor::*[@data-slot='context-menu-trigger'][1]"))
+ .toBeVisible()
+ return icon
+}
+
+async function clickServer(page: Page, serverId: string): Promise<void> {
+ const icon = await activateServerIcon(page, serverId)
+ await icon.click({ noWaitAfter: true })
+}
+
+async function expectActiveServer(page: Page, activeId: string, inactiveId: string): Promise<void> {
+ await expect(page.getByTestId(tid.serverIcon(activeId))).toHaveClass(/cursor-default/)
+ await expect(page.getByTestId(tid.serverIcon(inactiveId))).toHaveClass(/cursor-pointer/)
+}
+
+test("server switching exposes one target-scoped cold checkpoint and skips it when warm", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const stamp = Date.now()
+ const serverA = await seedServer("alice", `Checkpoint A ${stamp}`)
+ const serverB = await seedServer("alice", `Checkpoint B ${stamp}`)
+ const serverC = await seedServer("alice", `Checkpoint C ${stamp}`)
+ const serverD = await seedServer("alice", `Checkpoint D ${stamp}`)
+ const serverE = await seedServer("alice", `Checkpoint E ${stamp}`)
+ const serverF = await seedServer("alice", `Checkpoint F ${stamp}`)
+ const serverAName = `Checkpoint-A-${stamp}`
+ const serverBName = `Checkpoint-B-${stamp}`
+ const channelAName = `checkpoint-a-${stamp}`
+ const channelBName = `checkpoint-b-${stamp}`
+ const channelCName = `checkpoint-c-${stamp}`
+ const channelDName = `checkpoint-d-${stamp}`
+ const channelA = await seedChannel("alice", serverA, channelAName)
+ const channelB = await seedChannel("alice", serverB, channelBName)
+ const channelC = await seedChannel("alice", serverC, channelCName)
+ const channelD = await seedChannel("alice", serverD, channelDName)
+ await seedChannel("alice", serverE, `checkpoint-e-${stamp}`)
+ await seedChannel("alice", serverF, `checkpoint-f-${stamp}`)
+
+ const { page } = await asUser("alice")
+ await page.setViewportSize({ width: 1280, height: 900 })
+ await page.goto(`/c/channels/${serverA}/${channelA}`)
+ await expect(page.getByRole("heading", { name: channelAName })).toBeVisible({ timeout: 30_000 })
+
+ const readOnlyPostPaths = new Set([
+ "/api/community/messages/batch",
+ "/api/community/messages/tags/batch",
+ "/api/community/channels/participants/batch",
+ ])
+ const mutations: string[] = []
+ page.on("request", (request) => {
+ const method = request.method()
+ const pathname = new URL(request.url()).pathname
+ if (
+ !["GET", "HEAD", "OPTIONS"].includes(method)
+ && !(method === "POST" && readOnlyPostPaths.has(pathname))
+ ) {
+ mutations.push(`${method} ${pathname}`)
+ }
+ })
+
+ // Install every cold gate before the first physical rail movement. Moving
+ // the pointer between vertically stacked icons can cross another icon and
+ // legitimately trigger its hover prefetch; those targets must stay cold
+ // until their explicit phase below.
+ const coldC = await holdServerTransition(page, serverC)
+ const coldD = await holdServerTransition(page, serverD)
+ const coldE = await holdServerTransition(page, serverE)
+ const coldF = await holdServerTransition(page, serverF)
+
+ // A warm destination means the exact server detail has already settled in
+ // this page's QueryClient. Let B's focus prefetch fill that cache while only
+ // its RSC request is held, and wait for every constituent detail response
+ // to finish before the actual navigation intent begins.
+ const warmB = await holdServerTransition(page, serverB, { detail: false })
+ const detailResponses = Promise.all([
+ "categories", "channels", "unreads",
+ ].map((resource) => page.waitForResponse((response) =>
+ response.url().includes(`/api/community/servers/${serverB}/${resource}`)
+ && response.status() === 200
+ )))
+ const serverBIcon = await activateServerIcon(page, serverB)
+ const responses = await detailResponses
+ await Promise.all(responses.map((response) => response.finished()))
+ await page.waitForTimeout(100)
+ await serverBIcon.click({ noWaitAfter: true })
+ await expect.poll(warmB.heldNavigation).toBeGreaterThan(0)
+ await expect(page.getByTestId(tid.channelSidebarPending(serverB))).toHaveCount(0)
+ await expect(page.getByLabel("Loading conversation")).toHaveCount(0)
+ await expect(page.getByRole("heading", { name: channelAName })).toBeVisible()
+ await expectActiveServer(page, serverA, serverB)
+ await warmB.release()
+ await expect.poll(() => new URL(page.url()).pathname.startsWith(`/c/channels/${serverB}`))
+ .toBe(true)
+ await expect(page.getByRole("button", { name: serverBName, exact: true }))
+ .toBeVisible({ timeout: 30_000 })
+ await expect(page.getByTestId(tid.channelRow(channelB))).toBeVisible({ timeout: 30_000 })
+
+ await clickServer(page, serverA)
+ await expect.poll(() => new URL(page.url()).pathname.startsWith(`/c/channels/${serverA}`))
+ .toBe(true)
+ await expect(page.getByRole("button", { name: serverAName, exact: true }))
+ .toBeVisible({ timeout: 30_000 })
+ await expect(page.getByRole("heading", { name: channelAName })).toBeVisible({ timeout: 30_000 })
+ await expectActiveServer(page, serverA, serverB)
+
+ await clickServer(page, serverC)
+ await expect.poll(coldC.heldNavigation).toBeGreaterThan(0)
+ await expect(page.getByTestId(tid.channelSidebarPending(serverC))).toBeVisible()
+ await expect(page.getByLabel("Loading conversation")).toBeVisible()
+ await expect(page.getByRole("button", { name: channelAName })).toHaveCount(0)
+ await expectActiveServer(page, serverC, serverA)
+ expect(mutations).toEqual([])
+ await coldC.release()
+ await expect.poll(() => new URL(page.url()).pathname.startsWith(`/c/channels/${serverC}`))
+ .toBe(true)
+ await expect(page.getByTestId(tid.channelSidebarPending(serverC))).toHaveCount(0)
+ await expect(page.getByTestId(tid.channelRow(channelC))).toBeVisible({ timeout: 30_000 })
+
+ await clickServer(page, serverA)
+ await expect.poll(() => new URL(page.url()).pathname.startsWith(`/c/channels/${serverA}`))
+ .toBe(true)
+ await expect(page.getByRole("button", { name: serverAName, exact: true }))
+ .toBeVisible({ timeout: 30_000 })
+ await expect(page.getByRole("heading", { name: channelAName })).toBeVisible({ timeout: 30_000 })
+ await expectActiveServer(page, serverA, serverC)
+
+ await page.setViewportSize({ width: 390, height: 844 })
+ await page.getByRole("button", { name: "Back" }).click()
+ await expect.poll(() => new URL(page.url()).pathname === `/c/channels/${serverA}`)
+ .toBe(true)
+ await expect(page.getByTestId(tid.serverIcon(serverD))).toBeVisible()
+
+ await clickServer(page, serverD)
+ await expect.poll(coldD.heldNavigation).toBeGreaterThan(0)
+ const mobileCheckpoint = page.getByTestId(tid.channelSidebarPending(serverD))
+ await expect(mobileCheckpoint).toBeVisible()
+ await expect(page.getByRole("button", { name: channelAName })).toHaveCount(0)
+ const mobileBox = await mobileCheckpoint.boundingBox()
+ expect(mobileBox).not.toBeNull()
+ expect(mobileBox!.width).toBeGreaterThan(300)
+ expect(mobileBox!.x + mobileBox!.width).toBeLessThanOrEqual(390)
+ await expectActiveServer(page, serverD, serverA)
+ await coldD.release()
+ await expect.poll(() => new URL(page.url()).pathname.startsWith(`/c/channels/${serverD}`))
+ .toBe(true)
+ await expect(page.getByTestId(tid.channelRow(channelD))).toBeVisible({ timeout: 30_000 })
+
+ await page.setViewportSize({ width: 1280, height: 900 })
+ await expect(page.getByTestId(tid.serverIcon(serverE))).toBeVisible()
+ await clickServer(page, serverE)
+ // Dispatch the superseding click directly against the current stable
+ // button so this remains one immediate E→F intent window; waiting for F's
+ // unrelated lazy context-menu wrapper would serialize the two intents.
+ await page.getByTestId(tid.serverIcon(serverF)).dispatchEvent("click")
+ await expect.poll(coldF.heldNavigation).toBeGreaterThan(0)
+ await expect(page.getByTestId(tid.channelSidebarPending(serverE))).toHaveCount(0)
+ await expect(page.getByTestId(tid.channelSidebarPending(serverF))).toBeVisible()
+ await expectActiveServer(page, serverF, serverD)
+ await coldE.release()
+ await expect(page.getByTestId(tid.channelSidebarPending(serverF))).toBeVisible()
+ await expectActiveServer(page, serverF, serverD)
+ await coldF.release()
+ await expect.poll(() => new URL(page.url()).pathname.startsWith(`/c/channels/${serverF}`))
+ .toBe(true)
+})