Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): stabilize server rail first touch (#765)

Gener0e6863fb130e
diff --git a/src/web/src/components/community/shell/rail-icon.tsx b/src/web/src/components/community/shell/rail-icon.tsx
index e2652c653..4f03cf4fb 100644
--- a/src/web/src/components/community/shell/rail-icon.tsx
+++ b/src/web/src/components/community/shell/rail-icon.tsx
@@ -1,5 +1,6 @@
import type React from "react"
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"
+import { RailIndicator } from "./rail-indicator"
export function RailIcon({ label, round, accent, active, onClick, tooltip, testId, onboardingTarget }: {
label: React.ReactNode
@@ -16,10 +17,7 @@ export function RailIcon({ label, round, accent, active, onClick, tooltip, testI
className="group relative flex w-full justify-center"
data-onboarding-target={onboardingTarget}
>
- <span className={[
- "absolute left-0 top-1/2 w-1 -translate-y-1/2 rounded-r-full bg-foreground transition-all duration-150",
- active ? "h-8" : "h-0 group-hover:h-5",
- ].join(" ")} />
+ <RailIndicator active={active} />
<button
data-testid={testId}
onClick={onClick}
diff --git a/src/web/src/components/community/shell/rail-indicator.test.ts b/src/web/src/components/community/shell/rail-indicator.test.ts
index abc4351ce..1051b7b3b 100644
--- a/src/web/src/components/community/shell/rail-indicator.test.ts
+++ b/src/web/src/components/community/shell/rail-indicator.test.ts
@@ -2,6 +2,7 @@ import { createElement } from "react"
import { renderToStaticMarkup } from "react-dom/server"
import { describe, expect, it } from "vitest"
import { tid } from "@/lib/community/testids"
+import { RailIcon } from "./rail-icon"
import { RailIndicator } from "./rail-indicator"
function markup(props: Parameters<typeof RailIndicator>[0]) {
@@ -10,7 +11,8 @@ function markup(props: Parameters<typeof RailIndicator>[0]) {
describe("RailIndicator", () => {
it.each([
- [{ active: true, unread: true }, "h-10"],
+ [{ active: true, unread: true }, "h-8"],
+ [{ active: true, unread: false }, "h-8"],
[{ active: false, unread: true }, "h-2.5"],
[{ active: false, unread: false }, "h-0"],
] as const)("resolves resting height precedence for %o", (props, height) => {
@@ -20,6 +22,7 @@ describe("RailIndicator", () => {
expect(html).toContain("bg-foreground")
expect(html).toContain("rounded-r-full")
expect(html).toContain("duration-150")
+ expect(html).toContain('data-slot="community-server-rail-indicator"')
if (!props.active) {
expect(html).toContain("group-hover:h-5")
expect(html).toContain("group-focus-within:h-5")
@@ -36,4 +39,18 @@ describe("RailIndicator", () => {
expect(tid.serverRailIndicator("server-id")).toBe("community-server-rail-indicator-server-id")
expect(tid.serverRailFolderIndicator("folder-id")).toBe("community-server-rail-folder-indicator-folder-id")
})
+
+ it("keeps Add Server on the shared idle and hover/focus heights", () => {
+ const html = renderToStaticMarkup(createElement(RailIcon, {
+ label: "+",
+ accent: true,
+ testId: tid.serverAdd,
+ }))
+
+ expect(html).toContain('data-testid="community-server-add"')
+ expect(html).toContain("h-0")
+ expect(html).toContain("group-hover:h-5")
+ expect(html).toContain("group-focus-within:h-5")
+ expect(html).not.toContain("h-8")
+ })
})
diff --git a/src/web/src/components/community/shell/rail-indicator.tsx b/src/web/src/components/community/shell/rail-indicator.tsx
index a1edc1310..e181c640c 100644
--- a/src/web/src/components/community/shell/rail-indicator.tsx
+++ b/src/web/src/components/community/shell/rail-indicator.tsx
@@ -15,11 +15,12 @@ export function RailIndicator({
})
return (
<span
+ data-slot="community-server-rail-indicator"
data-testid={testId}
className={[
"absolute left-0 top-1/2 w-1 -translate-y-1/2 rounded-r-full bg-foreground transition-all duration-150",
presentation.active
- ? "h-10"
+ ? "h-8"
: `${presentation.showDot ? "h-2.5" : "h-0"} group-hover:h-5 group-focus-within:h-5`,
].join(" ")}
/>
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 cf8f70ee1..b4358ca5f 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
@@ -196,6 +196,29 @@ describe("ServerRail one-in-flight structural guard", () => {
.toHaveLength(0)
})
+ it("uses the shared idle, hover/focus, and active heights for Home", () => {
+ const renderer = render(createElement(ServerRail, {
+ servers,
+ folders,
+ view: "server",
+ onHome: vi.fn(),
+ }))
+ const homeIndicator = () => renderer.getByTestId(tid.homeButton)
+ .previousElementSibling as HTMLElement
+
+ expect(homeIndicator()).toHaveAttribute("data-slot", "community-server-rail-indicator")
+ expect(homeIndicator()).toHaveClass("h-0", "group-hover:h-5", "group-focus-within:h-5")
+
+ renderer.rerender(createElement(ServerRail, {
+ servers,
+ folders,
+ view: "dm",
+ onHome: vi.fn(),
+ }))
+ expect(homeIndicator()).toHaveClass("h-8")
+ expect(homeIndicator()).not.toHaveClass("group-hover:h-5", "group-focus-within:h-5")
+ })
+
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 04bad68b8..5f1cc6006 100644
--- a/src/web/src/components/community/shell/server-rail.tsx
+++ b/src/web/src/components/community/shell/server-rail.tsx
@@ -21,6 +21,7 @@ import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip
import { Skeleton } from "@/components/ui/skeleton"
import { SortableServer } from "./sortable-server"
import { RailFolder } from "./rail-folder"
+import { RailIndicator } from "./rail-indicator"
import { CreateServerDialog } from "../settings/create-server-dialog"
import {
cloneRailState,
@@ -390,10 +391,7 @@ export const ServerRail = memo(function ServerRail({
const home = (
<Tooltip>
<TooltipTrigger render={<div className="group relative flex w-full justify-center" />}>
- <span className={[
- "absolute left-0 top-1/2 w-1 -translate-y-1/2 rounded-r-full bg-foreground transition-all duration-150",
- view === "dm" ? "h-8" : "h-0 group-hover:h-5",
- ].join(" ")} />
+ <RailIndicator active={view === "dm"} />
<button
onClick={onHome}
onPointerEnter={onHomePrefetch}
diff --git a/src/web/src/components/community/shell/sortable-server.focus.dom.test.ts b/src/web/src/components/community/shell/sortable-server.focus.dom.test.ts
index e3a872ca2..2394dc7c4 100644
--- a/src/web/src/components/community/shell/sortable-server.focus.dom.test.ts
+++ b/src/web/src/components/community/shell/sortable-server.focus.dom.test.ts
@@ -2,7 +2,7 @@ import { createElement, Fragment, type ReactNode } from "react"
import { afterEach, describe, expect, it, vi } from "vitest"
import { SortableServer } from "./sortable-server"
import { tid } from "@/lib/community/testids"
-import { fireEvent, render } from "@/test/react-dom-harness"
+import { act, fireEvent, render } from "@/test/react-dom-harness"
vi.mock("@/components/ui/context-menu", () => ({
ContextMenu: ({ children }: { children: ReactNode }) => createElement(Fragment, null, children),
@@ -32,19 +32,25 @@ const server = {
mentions: 0,
}
-function renderServer(active = false, mentions = 0, official = false) {
+function renderServer(
+ active = false,
+ mentions = 0,
+ official = false,
+ extraProps: Record<string, unknown> = {},
+) {
const renderer = render(createElement(SortableServer, {
server: { ...server, mentions, official },
active,
onClick: vi.fn(),
dragDescriptionId: "rail-help",
+ ...extraProps,
}))
const button = () => renderer.container.querySelector<HTMLButtonElement>("button")!
const activationRoot = () => button().closest("div.group") as HTMLDivElement
return { ...renderer, button, activationRoot }
}
-describe("SortableServer lazy menu focus", () => {
+describe("SortableServer stable menu trigger", () => {
afterEach(() => vi.restoreAllMocks())
it("announces official status without changing ordinary server labels", () => {
@@ -54,24 +60,48 @@ describe("SortableServer lazy menu focus", () => {
expect(official.button()).toHaveAccessibleName("A, Official server")
})
- it("refocuses the icon after first focus activates and replaces its menu wrapper", () => {
- const focus = vi.spyOn(HTMLElement.prototype, "focus")
+ it("keeps the exact icon button focused when first focus activates menu content", () => {
const result = renderServer()
+ const originalButton = result.button()
- fireEvent.focus(result.button())
+ expect(result.container.querySelectorAll("context-menu-trigger")).toHaveLength(1)
+ expect(result.container.querySelectorAll("context-menu-content")).toHaveLength(0)
+ act(() => originalButton.focus())
+ expect(result.button()).toBe(originalButton)
+ expect(document.activeElement).toBe(originalButton)
expect(result.container.querySelectorAll("context-menu-trigger")).toHaveLength(1)
- expect(focus).toHaveBeenCalledTimes(1)
+ expect(result.container.querySelectorAll("context-menu-content")).toHaveLength(1)
})
- it("does not steal focus when pointer hover activates the menu", () => {
+ it("keeps the same button and drag registration when pointer hover activates the menu", () => {
const focus = vi.spyOn(HTMLElement.prototype, "focus")
- const result = renderServer()
+ const dispose = vi.fn()
+ const registerItem = vi.fn(() => dispose)
+ const onPrefetch = vi.fn()
+ const result = renderServer(false, 0, false, { registerItem, onPrefetch })
+ const originalButton = result.button()
fireEvent.pointerEnter(result.activationRoot())
+ expect(result.button()).toBe(originalButton)
+ expect(registerItem).toHaveBeenCalledTimes(1)
+ expect(onPrefetch).toHaveBeenCalledTimes(1)
expect(result.container.querySelectorAll("context-menu-trigger")).toHaveLength(1)
+ expect(result.container.querySelectorAll("context-menu-content")).toHaveLength(1)
expect(focus).not.toHaveBeenCalled()
+ expect(dispose).not.toHaveBeenCalled()
+ })
+
+ it("keeps the same button for first touch-like pointer activation", () => {
+ const result = renderServer()
+ const originalButton = result.button()
+
+ fireEvent.pointerDown(originalButton, { pointerType: "touch" })
+
+ expect(result.button()).toBe(originalButton)
+ expect(originalButton.isConnected).toBe(true)
+ expect(result.container.querySelectorAll("context-menu-content")).toHaveLength(1)
})
it("exposes keyboard drag help without positional menu shortcuts", () => {
@@ -79,7 +109,8 @@ describe("SortableServer lazy menu focus", () => {
const button = result.button()
expect(button).toHaveAttribute("aria-describedby", "rail-help")
expect(button).toHaveAttribute("aria-keyshortcuts", expect.stringContaining("Space"))
- fireEvent.pointerEnter(result.activationRoot())
+ fireEvent.keyDown(button, { key: "F10", shiftKey: true })
+ expect(result.container.querySelectorAll("context-menu-content")).toHaveLength(1)
const menuText = result.container.textContent
expect(menuText).not.toContain("Move…")
expect(menuText).not.toContain("Create group")
diff --git a/src/web/src/components/community/shell/sortable-server.tsx b/src/web/src/components/community/shell/sortable-server.tsx
index f54e05a22..fc49ccece 100644
--- a/src/web/src/components/community/shell/sortable-server.tsx
+++ b/src/web/src/components/community/shell/sortable-server.tsx
@@ -58,17 +58,7 @@ function SortableServerImpl({
}: SortableServerProps) {
const rootRef = useRef<HTMLDivElement>(null)
const buttonRef = useRef<HTMLButtonElement>(null)
- const restoreFocusAfterActivationRef = useRef(false)
const [confirmLeave, setConfirmLeave] = useState(false);
- // Lazy-mount the row's Base UI ContextMenu + ConfirmDialog. Eagerly mounting
- // them per rail icon (one Tooltip + ContextMenu + Dialog stack × N servers)
- // was the bulk of the switch re-render storm — the DialogPortal /
- // ContextMenuTrigger / FloatingTree ×1000s in perf:switch came from the rail,
- // not the message list (which already lazies its overlays; see message.tsx).
- // Activate on first hover OR focus OR keydown/contextmenu — focus/keydown are
- // required for a11y (keyboard context menu / Tab-to-icon have no pointerenter,
- // and a right-click is always preceded by a pointerenter so the menu is
- // mounted before it's invoked).
const [activated, setActivated] = useState(false);
useLayoutEffect(() => {
if (!registerItem || !rootRef.current || !buttonRef.current) return
@@ -77,21 +67,12 @@ function SortableServerImpl({
rootRef.current,
buttonRef.current,
)
- }, [activated, registerItem, server.id])
- useLayoutEffect(() => {
- if (!activated || !restoreFocusAfterActivationRef.current) return
- restoreFocusAfterActivationRef.current = false
- buttonRef.current?.focus()
- }, [activated])
+ }, [registerItem, server.id])
const activate = activated ? undefined : () => setActivated(true);
const activateAndPrefetch = () => {
activate?.();
onPrefetch?.();
};
- const activateFromFocus = () => {
- if (!activated) restoreFocusAfterActivationRef.current = true
- activateAndPrefetch()
- };
const icon = (
<div
@@ -99,8 +80,10 @@ function SortableServerImpl({
style={{ opacity: isDragActive ? 0.3 : 1 }}
className="group relative flex w-full justify-center"
onPointerEnter={activateAndPrefetch}
- onFocusCapture={activateFromFocus}
+ onPointerDownCapture={activate}
+ onFocusCapture={activateAndPrefetch}
onKeyDownCapture={activate}
+ onContextMenuCapture={activate}
>
{(preview === "reorder-before" || preview === "reorder-after") && (
<div
@@ -167,36 +150,35 @@ function SortableServerImpl({
</div>
);
- // Until activated, the icon carries no ContextMenu root — just the Tooltip.
- const withMenu = !activated ? (
- icon
- ) : (
+ const withMenu = (
<ContextMenu>
<ContextMenuTrigger render={icon} />
- <ContextMenuContent className="w-52">
- <div className="truncate px-2 py-1 text-xs font-semibold text-muted-foreground">
- {server.name}
- </div>
- {onOpenInvitePopover && (
- <ContextMenuItem onClick={onOpenInvitePopover}>
- Invite to Server
- </ContextMenuItem>
- )}
- <ContextMenuItem onClick={onOpenSettings} data-testid={tid.serverSettingsOpen}>
- Server settings
- </ContextMenuItem>
- {!server.isOwner && !inFolder && (
- <>
- <ContextMenuSeparator />
- <ContextMenuItem
- onClick={() => setConfirmLeave(true)}
- className="text-destructive data-highlighted:bg-destructive/10 data-highlighted:text-destructive"
- >
- Leave server
+ {activated && (
+ <ContextMenuContent className="w-52">
+ <div className="truncate px-2 py-1 text-xs font-semibold text-muted-foreground">
+ {server.name}
+ </div>
+ {onOpenInvitePopover && (
+ <ContextMenuItem onClick={onOpenInvitePopover}>
+ Invite to Server
</ContextMenuItem>
- </>
- )}
- </ContextMenuContent>
+ )}
+ <ContextMenuItem onClick={onOpenSettings} data-testid={tid.serverSettingsOpen}>
+ Server settings
+ </ContextMenuItem>
+ {!server.isOwner && !inFolder && (
+ <>
+ <ContextMenuSeparator />
+ <ContextMenuItem
+ onClick={() => setConfirmLeave(true)}
+ className="text-destructive data-highlighted:bg-destructive/10 data-highlighted:text-destructive"
+ >
+ Leave server
+ </ContextMenuItem>
+ </>
+ )}
+ </ContextMenuContent>
+ )}
</ContextMenu>
);
@@ -212,11 +194,9 @@ function SortableServerImpl({
{server.name}
</TooltipContent>
</Tooltip>
- {/* ConfirmDialog only mounts once the menu has been activated AND the
- user chose Leave — never eagerly per rail icon. */}
- {activated && (
+ {confirmLeave && (
<ConfirmDialog
- open={confirmLeave}
+ open
onOpenChange={setConfirmLeave}
title={`Leave ${server.name}?`}
description="You won't see this server's channels anymore, and you'll need a new invite to come back."
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 6a6d4d633..3cf4cc039 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
@@ -720,7 +720,7 @@ describe("useServerRailPdd behavior", () => {
expect(hook.callbacks.onCancel).toHaveBeenCalled()
})
- it("cancels when an active source leaves, but survives its lazy replacement", async () => {
+ it("cancels when an active source leaves, but survives same-entity reconciliation", async () => {
const hook = await renderHook()
const a = register(hook.current, { kind: "server", id: "a" }, rect(0, 40))
key(a.handle, " ")
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 56f807110..1c62e04a1 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
@@ -628,9 +628,8 @@ export function useServerRailPdd({
dragHandle.removeEventListener("click", onClickCapture, true)
dragHandle.removeEventListener("keydown", onKeyDown)
itemsRef.current.delete(element)
- // Lazy context-menu activation briefly remounts the same rail entity.
- // Defer cancellation until the replacement registration has had a chance
- // to land, while still cancelling when an entity truly leaves the rail.
+ // Reconciliation may replace a registered element without removing its
+ // entity, so defer cancellation until a same-entity registration can land.
queueMicrotask(() => {
const stillRegistered = [...itemsRef.current.values()]
.some((item) => sameEntity(item.entity, entity))
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 67a5a5049..6dd883099 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
@@ -29,7 +29,6 @@ vi.mock("@/hooks/community/use-servers", () => ({
servers: mocks.servers,
isLoading: false,
}),
- serverProjectedQueryFn: (_queryClient: unknown, id: string) => () => Promise.resolve({ id }),
}))
vi.mock("@/hooks/community/use-folders", () => ({ useFolders: () => ({ folders: mocks.folders }) }))
vi.mock("@/hooks/community/use-structural-snapshot", () => ({
@@ -276,7 +275,7 @@ describe("useShellRailController", () => {
expect(hook.pushed).toEqual(["/c/channels/s1"])
})
- it("uses cached and fetched destinations for navigation and prefetch fallbacks", async () => {
+ it("keeps rail navigation and prefetch on the semantic server root", async () => {
const hook = await renderController()
hook.cache.set("s1", {
categories: [{ channels: [{ id: "pending", pending: true }, { id: "cached", pending: false }] }],
@@ -286,27 +285,16 @@ describe("useShellRailController", () => {
await act(async () => hook.current.railProps.onServerPrefetch("s1"))
await act(async () => hook.current.railProps.onHomePrefetch())
expect(hook.pushed).toEqual(["/c/channels/s1"])
- expect(hook.prefetched).toEqual(["/c/channels/s1/cached", "/c/me/friends"])
+ expect(hook.prefetched).toEqual(["/c/channels/s1", "/c/me/friends"])
expect(hook.queryClient.fetchQuery).not.toHaveBeenCalled()
- hook.queryClient.fetchQuery.mockImplementationOnce(async ({ queryKey }: { queryKey: unknown[] }) => {
- const id = String(queryKey.at(-1))
- hook.cache.set(id, { categories: [{ channels: [{ id: "fetched", pending: false }] }] })
- })
await act(async () => hook.current.railProps.onServerNavigate("s2"))
expect(hook.pushed).toContain("/c/channels/s2")
- expect(hook.queryClient.fetchQuery).not.toHaveBeenCalled()
await act(async () => hook.current.railProps.onServerPrefetch("s2"))
- expect(hook.prefetched).toContain("/c/channels/s2/fetched")
- expect(hook.queryClient.fetchQuery).toHaveBeenLastCalledWith(expect.objectContaining({
- queryKey: expect.any(Array),
- queryFn: expect.any(Function),
- staleTime: Infinity,
- }))
-
- hook.queryClient.fetchQuery.mockRejectedValueOnce(new Error("offline"))
+ expect(hook.prefetched).toContain("/c/channels/s2")
await act(async () => hook.current.railProps.onServerPrefetch("s3"))
expect(hook.prefetched).toContain("/c/channels/s3")
+ expect(hook.queryClient.fetchQuery).not.toHaveBeenCalled()
})
it("uses one breakpoint-canonical Home destination for click and prefetch", 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 121eb5441..cf1a0caab 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
@@ -6,7 +6,7 @@ import { toastApiError } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import { markSwitch } from "@/lib/perf/switch-mark"
import { markVoluntaryLeave, pickPostEjectDestination } from "@/lib/community/eject-server"
-import { serverProjectedQueryFn, useServers, type ServerDetail } from "@/hooks/community/use-servers"
+import { useServers, type ServerDetail } from "@/hooks/community/use-servers"
import { useFolders } from "@/hooks/community/use-folders"
import {
useCreateServer,
@@ -87,22 +87,6 @@ export function useShellRailController({
?? []
return pickServerLandingHref(id, channelIds, getLastChannel(id))
}, [queryClient, structuralSnapshot])
- const resolveServerDestination = useCallback(async (id: string) => {
- const root = `/c/channels/${id}`
- const immediate = serverDestination(id)
- if (immediate !== root) return immediate
- try {
- await queryClient.fetchQuery({
- queryKey: communityKeys.server(id),
- queryFn: serverProjectedQueryFn(queryClient, id),
- staleTime: Infinity,
- })
- } catch {
- return root
- }
- return serverDestination(id)
- }, [queryClient, serverDestination])
-
const onServerNavigate = useCallback((id: string) => {
markSwitch("server", id)
navigation.push(`/c/channels/${id}`)
@@ -117,8 +101,8 @@ export function useShellRailController({
navigation.push(homeDestination())
}, [homeDestination, navigation])
const onServerPrefetch = useCallback((id: string) => {
- void resolveServerDestination(id).then((destination) => navigation.prefetch(destination))
- }, [navigation, resolveServerDestination])
+ navigation.prefetch(`/c/channels/${id}`)
+ }, [navigation])
const onHomePrefetch = useCallback(
() => navigation.prefetch(homeDestination()),
[homeDestination, navigation],
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 a9ee03042..3e8ce2e3b 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
@@ -11,18 +11,15 @@ type HeldServer = {
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 },
- ] : []),
+ { 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) {
@@ -46,10 +43,9 @@ async function holdServerTransition(
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.
+ // Focus activates the accessible menu path and starts Server-root prefetch.
+ // The trigger and button are already stable, so the same node receives the
+ // following physical click, including during an immediate A→B supersession.
await icon.focus()
await expect(icon.locator("xpath=ancestor::*[@data-slot='context-menu-trigger'][1]"))
.toBeVisible()
@@ -119,28 +115,19 @@ test("server switching exposes one target-scoped cold checkpoint and skips it wh
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}`)
+ // Warm B through the exact Server-root RSC contract before the click.
+ const rootPrefetch = page.waitForResponse((response) => {
+ const url = new URL(response.url())
+ return url.pathname === `/c/channels/${serverB}`
+ && url.searchParams.has("_rsc")
&& 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)
+ const prefetchResponse = await rootPrefetch
+ await prefetchResponse.finished()
await serverBIcon.click({ noWaitAfter: true })
- await expect.poll(warmB.heldNavigation).toBeGreaterThan(0)
await expect(page.getByTestId(tid.channelSidebarPending(serverB))).toHaveCount(0)
await expect(page.getByTestId(tid.pendingMain("server-landing"))).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.locator("#sidebar").getByRole("button", { name: serverBName, exact: true }))
@@ -201,8 +188,8 @@ test("server switching exposes one target-scoped cold checkpoint and skips it wh
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.
+ // button so this remains one immediate E→F intent window; awaiting F's
+ // focus-driven prefetch 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)
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 aa620ba02..0b382bc14 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
@@ -1,6 +1,6 @@
import { devices, type Locator, type Page } from "@playwright/test"
-import { expect, test } from "./_fixtures/community-fixture"
-import { seedChannel, seedServer } from "./_fixtures/seed"
+import { expect, test, userId } from "./_fixtures/community-fixture"
+import { seedChannel, seedDm, seedJoinServer, seedServer } from "./_fixtures/seed"
import { tid } from "./_fixtures/testids"
const RAIL_ENDPOINT = "/api/community/users/me/server-rail"
@@ -308,6 +308,114 @@ async function dragUntilNativeDrop(
}
}
+async function expectFirstNativeServerTap(
+ page: Page,
+ serverId: string,
+ railPatches: string[],
+) {
+ const target = page.getByTestId(tid.serverIcon(serverId))
+ const targetTestId = tid.serverIcon(serverId)
+ const destination = `/c/channels/${serverId}`
+ await expect(target).toBeVisible({ timeout: 30_000 })
+ const patchesBeforeTap = railPatches.length
+ await target.evaluate((element, args) => {
+ const state = {
+ touchStarts: 0,
+ clicks: 0,
+ pushes: [] as string[],
+ sameNodeAtTouchStart: false,
+ sameNodeAtClick: false,
+ }
+ Reflect.set(window, "__railFirstTapProbe", state)
+ element.addEventListener("touchstart", () => {
+ state.touchStarts += 1
+ state.sameNodeAtTouchStart = element.isConnected
+ && document.querySelector(`[data-testid="${args.testId}"]`) === element
+ }, { once: true })
+ element.addEventListener("click", () => {
+ state.clicks += 1
+ state.sameNodeAtClick = element.isConnected
+ && document.querySelector(`[data-testid="${args.testId}"]`) === element
+ }, { once: true })
+ const pushState = history.pushState
+ history.pushState = function (data, unused, url) {
+ const pathname = url === undefined || url === null
+ ? location.pathname
+ : new URL(String(url), location.href).pathname
+ if (pathname === args.destination) state.pushes.push(pathname)
+ return pushState.call(history, data, unused, url)
+ }
+ }, { destination, testId: targetTestId })
+
+ await target.tap()
+ await expect.poll(
+ () => new URL(page.url()).pathname,
+ { timeout: 30_000 },
+ ).toBe(destination)
+ expect(await page.evaluate(() => {
+ const state = Reflect.get(window, "__railFirstTapProbe") as {
+ touchStarts: number
+ clicks: number
+ pushes: string[]
+ sameNodeAtTouchStart: boolean
+ sameNodeAtClick: boolean
+ }
+ return {
+ touchStarts: state.touchStarts,
+ clicks: state.clicks,
+ pushes: state.pushes,
+ sameNodeAtTouchStart: state.sameNodeAtTouchStart,
+ sameNodeAtClick: state.sameNodeAtClick,
+ }
+ })).toEqual({
+ touchStarts: 1,
+ clicks: 1,
+ pushes: [destination],
+ sameNodeAtTouchStart: true,
+ sameNodeAtClick: true,
+ })
+ expect(railPatches).toHaveLength(patchesBeforeTap)
+}
+
+test("first native Server tap is one root push with a stable handle and zero rail PATCH", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const stamp = Date.now()
+ const serverId = await seedServer("alice", `First tap ${stamp}`)
+ await seedChannel("alice", serverId, `first-tap-${stamp}`)
+ await seedJoinServer("alice", "bob", serverId)
+ const dmId = await seedDm("alice", userId("bob"))
+
+ const cold = await asUser("alice", devices["Pixel 7"])
+ const coldPatches: string[] = []
+ cold.page.on("request", (request) => {
+ if (request.method() === "PATCH" && new URL(request.url()).pathname === RAIL_ENDPOINT) {
+ coldPatches.push(request.postData() ?? "")
+ }
+ })
+ await cold.page.goto("/c/me")
+ await expectFirstNativeServerTap(cold.page, serverId, coldPatches)
+
+ const warm = await asUser("bob", devices["Pixel 7"])
+ const warmPatches: string[] = []
+ warm.page.on("request", (request) => {
+ if (request.method() === "PATCH" && new URL(request.url()).pathname === RAIL_ENDPOINT) {
+ warmPatches.push(request.postData() ?? "")
+ }
+ })
+ await warm.page.goto(`/c/channels/${serverId}`)
+ await expect(warm.page.getByTestId(tid.serverIcon(serverId))).toBeVisible({ timeout: 30_000 })
+ await warm.page.getByTestId(tid.homeButton).click()
+ await expect.poll(() => new URL(warm.page.url()).pathname).toBe("/c/me")
+ await warm.page.getByTestId(tid.dmRow(dmId)).click()
+ await expect.poll(() => new URL(warm.page.url()).pathname).toBe(`/c/me/${dmId}`)
+ await warm.page.reload()
+ await expect.poll(() => new URL(warm.page.url()).pathname).toBe(`/c/me/${dmId}`)
+ await warm.page.getByRole("banner").getByRole("button", { name: "Back" }).click()
+ await expect.poll(() => new URL(warm.page.url()).pathname).toBe("/c/me")
+ await expect(warm.page.getByTestId(tid.serverIcon(serverId))).toBeVisible({ timeout: 30_000 })
+ await expectFirstNativeServerTap(warm.page, serverId, warmPatches)
+})
+
test("server rail keeps scroll separate from native, touch, and keyboard drag", async ({ asUser }, testInfo) => {
test.setTimeout(150_000)
const stamp = Date.now()
diff --git a/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts b/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts
index 2b8d64460..5962901ae 100644
--- a/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts
+++ b/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts
@@ -64,6 +64,24 @@ test("server unread owns exact rail geometry, folder aggregation, read clear, an
await page.goto(`/c/channels/${foregroundServer}/${foregroundChannel}`)
await expect(page.getByTestId(tid.serverIcon(backgroundServer))).toBeVisible({ timeout: 30_000 })
+ const indicatorBefore = (testId: string) => page.getByTestId(testId)
+ .locator('xpath=preceding-sibling::*[@data-slot="community-server-rail-indicator"][1]')
+ const foregroundIndicator = page.getByTestId(tid.serverRailIndicator(foregroundServer))
+ const homeButton = page.getByTestId(tid.homeButton)
+ const homeIndicator = indicatorBefore(tid.homeButton)
+ const addButton = page.getByTestId(tid.serverAdd)
+ const addIndicator = indicatorBefore(tid.serverAdd)
+ await expectIndicatorHeight(foregroundIndicator, 32)
+ await expectIndicatorHeight(homeIndicator, 0)
+ await homeButton.hover()
+ await expectIndicatorHeight(homeIndicator, 20)
+ await page.mouse.move(300, 300)
+ await expectIndicatorHeight(homeIndicator, 0)
+ await addButton.hover()
+ await expectIndicatorHeight(addIndicator, 20)
+ await page.mouse.move(300, 300)
+ await expectIndicatorHeight(addIndicator, 0)
+
const backgroundIndicator = page.getByTestId(tid.serverRailIndicator(backgroundServer))
await expectIndicatorHeight(backgroundIndicator, 0)
const firstBody = `background unread ${stamp}`
@@ -104,7 +122,13 @@ test("server unread owns exact rail geometry, folder aggregation, read clear, an
await expectIndicatorHeight(backgroundIndicator, 10)
await backgroundIcon.click()
- await expectIndicatorHeight(backgroundIndicator, 40)
+ await expectIndicatorHeight(backgroundIndicator, 32)
+ await folder.click()
+ await expect(page.getByTestId(tid.serverIcon(backgroundServer))).toHaveCount(0)
+ await expectIndicatorHeight(folderIndicator, 32)
+ await folder.click()
+ await expect(backgroundIcon).toBeVisible()
+ await expectIndicatorHeight(backgroundIndicator, 32)
const backgroundChannelRow = page.getByTestId(tid.channelRow(backgroundChannel))
await expect(backgroundChannelRow).toBeVisible({ timeout: 30_000 })
const readResponse = page.waitForResponse((response) => (
diff --git a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
index 854317039..12be29b6a 100644
--- a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
+++ b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
@@ -286,7 +286,7 @@ test.describe.serial("account unread projection", () => {
await expectNoUnreadDot(bob.page.getByTestId(tid.channelRow(channelId)))
await expect.poll(async () => bob.page
.getByTestId(tid.serverRailIndicator(serverId))
- .evaluate((element) => element.getBoundingClientRect().height)).toBe(40)
+ .evaluate((element) => element.getBoundingClientRect().height)).toBe(32)
await expect(bob.page.getByTestId(tid.railUnreadBadge(serverId))).toHaveCount(0)
await inboxTrigger.click()