Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

perf(web): prefetch community navigation routes through links

Generd8aa02627314
diff --git a/src/web/src/components/community/channels/channel-sidebar-tree-owner.dom.test.tsx b/src/web/src/components/community/channels/channel-sidebar-tree-owner.dom.test.tsx
index d475ffec5..274a32b3c 100644
--- a/src/web/src/components/community/channels/channel-sidebar-tree-owner.dom.test.tsx
+++ b/src/web/src/components/community/channels/channel-sidebar-tree-owner.dom.test.tsx
@@ -214,3 +214,5 @@ describe("ChannelSidebarScope", () => {
expect(screen.getByTestId(tid.channelRow("target-two"))).toBeInTheDocument()
})
})
+
+vi.mock("next/link", async () => ({ default: (await import("@/test/community-link-mock")).CommunityLinkMock }))
diff --git a/src/web/src/components/community/channels/channel-sidebar.navigation.dom.test.tsx b/src/web/src/components/community/channels/channel-sidebar.navigation.dom.test.tsx
new file mode 100644
index 000000000..91d7f7082
--- /dev/null
+++ b/src/web/src/components/community/channels/channel-sidebar.navigation.dom.test.tsx
@@ -0,0 +1,47 @@
+import { describe, expect, it, vi } from "vitest"
+import { act, fireEvent, render, setupUser } from "@/test/react-dom-harness"
+import { tid } from "@/lib/community/testids"
+import { ChannelSidebar } from "./channel-sidebar"
+import { useChannelTree } from "./use-channel-tree"
+
+vi.mock("next/link", async () => ({ default: (await import("@/test/community-link-mock")).CommunityLinkMock }))
+
+function Sidebar({ onPick }: { onPick: (id: string) => void }) {
+ const tree = useChannelTree([{ id: "none", name: "", channels: [
+ { id: "one", name: "One", active: false, unread: false, type: "text" },
+ { id: "two", name: "Two", active: false, unread: false, type: "forum" },
+ ] }])
+ return <ChannelSidebar tree={tree} serverId="server" serverName="Server" activeChannel="one"
+ setActiveChannel={onPick} noHeader isAdmin />
+}
+
+describe("real sortable channel navigation surface", () => {
+ it("keeps href and sortable attributes on the anchor and Enter activates once", async () => {
+ const onPick = vi.fn()
+ const view = render(<Sidebar onPick={onPick} />)
+ const anchor = view.getByTestId(tid.channelRow("two"))
+ expect(anchor.tagName).toBe("A")
+ expect(anchor).toHaveAttribute("role", "link")
+ expect(anchor).toHaveAttribute("href", "/c/channels/server/two")
+ expect(anchor).toHaveAttribute("aria-roledescription", "sortable")
+ fireEvent.focus(anchor)
+ expect(anchor).toHaveAttribute("data-prefetch", "true")
+ act(() => anchor.focus())
+ await setupUser().keyboard("{Enter}")
+ expect(onPick.mock.calls).toEqual([["two"]])
+ })
+
+ it("Space starts reorder and Tab ends it without navigating", async () => {
+ const onPick = vi.fn()
+ const view = render(<Sidebar onPick={onPick} />)
+ const anchor = view.getByTestId(tid.channelRow("two"))
+ act(() => anchor.focus())
+ const user = setupUser()
+ await user.keyboard(" ")
+ expect(anchor).toHaveAttribute("aria-pressed", "true")
+ expect(onPick).not.toHaveBeenCalled()
+ await user.keyboard("{Tab}")
+ expect(view.getByText(/was dropped/i)).toBeInTheDocument()
+ expect(onPick).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/components/community/channels/channel-sidebar.touch-dnd.contract.test.ts b/src/web/src/components/community/channels/channel-sidebar.touch-dnd.contract.test.ts
index 083db3424..3556ab98e 100644
--- a/src/web/src/components/community/channels/channel-sidebar.touch-dnd.contract.test.ts
+++ b/src/web/src/components/community/channels/channel-sidebar.touch-dnd.contract.test.ts
@@ -15,7 +15,7 @@ describe("channel sidebar touch drag contracts", () => {
"useSensor(TouchSensor, { activationConstraint: { delay: 250, tolerance: 5 } })",
)
expect(sidebar).toContain(
- "useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })",
+ "useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates, keyboardCodes: { start: [\"Space\"], cancel: [\"Escape\"], end: [\"Space\", \"Enter\", \"Tab\"] } })",
)
expect(sidebar).toContain("collisionDetection={channelSidebarCollisionDetection}")
expect(sidebar).toContain('activeData?.kind !== "category"')
@@ -29,6 +29,7 @@ describe("channel sidebar touch drag contracts", () => {
const category = readSource("./sortable-category.tsx")
expect(channel).toContain("onClick={onClick}")
+ expect(channel).toContain("onActivate={onClick}")
expect(category).toContain("onClick: onToggle")
expect(category).toContain('data: { kind: "category" }')
expect(category).toContain("ref: setActivatorNodeRef")
diff --git a/src/web/src/components/community/channels/channel-sidebar.tsx b/src/web/src/components/community/channels/channel-sidebar.tsx
index 374693d42..58db7f5ba 100644
--- a/src/web/src/components/community/channels/channel-sidebar.tsx
+++ b/src/web/src/components/community/channels/channel-sidebar.tsx
@@ -2,10 +2,12 @@
import { useAtom, useCreateAtom } from "@tanstack/react-store";
import { OfficialServerBadge } from "../official-server-badge"
-import { Fragment, memo, useRef } from "react"
+import { CommunityNavigationLink } from "../shell/community-navigation-link"
+import { channelHref } from "@/lib/community/community-route"
+import { Fragment, memo, useRef, type MouseEvent } from "react"
import { Settings, Users, Link2, Bell, ChevronDown, UserPlus } from "lucide-react"
import {
- DndContext, KeyboardSensor, MouseSensor, TouchSensor, closestCenter, useSensor, useSensors,
+ DndContext, KeyboardSensor, MouseSensor, TouchSensor, closestCenter, useSensor, useSensors, useDndContext,
type CollisionDetection,
} from "@dnd-kit/core"
import { SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy } from "@dnd-kit/sortable"
@@ -165,7 +167,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({
const sensors = useSensors(
useSensor(MouseSensor, { activationConstraint: { distance: 5 } }),
useSensor(TouchSensor, { activationConstraint: { delay: 250, tolerance: 5 } }),
- useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates, keyboardCodes: { start: ["Space"], cancel: ["Escape"], end: ["Space", "Enter", "Tab"] } }),
)
const [dialog, setDialog] = useAtom(useCreateAtom<Dialog>(null))
const withMute = (ch: Channel): Channel => mutedChannels && ch.id in mutedChannels ? { ...ch, muted: mutedChannels[ch.id] } : ch
@@ -204,6 +206,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({
<ForumSidebarThreadRow
key={thread.id}
thread={thread}
+ href={serverId ? channelHref(serverId, thread.id) : undefined}
active={thread.id === activeThreadId}
muted={!!mutedChannels?.[parentId]}
onClick={() => onSelectForumThread?.(parentId, thread.id)}
@@ -244,6 +247,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({
<Fragment key={ch.id}>
<SortableChannel
ch={withMute(ch)}
+ href={serverId ? channelHref(serverId, ch.id) : undefined}
active={ch.id === activeChannel && !hasActiveSidebarThread}
canReorder={isAdmin}
onClick={() => setActiveChannel(ch.id)}
@@ -284,6 +288,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({
<Fragment key={ch.id}>
<SortableChannel
ch={withMute(ch)}
+ href={serverId ? channelHref(serverId, ch.id) : undefined}
active={ch.id === activeChannel && !hasActiveSidebarThread}
canReorder={isAdmin}
onClick={() => setActiveChannel(ch.id)}
@@ -420,47 +425,55 @@ export const ChannelSidebar = memo(function ChannelSidebar({
function ForumSidebarThreadRow({
thread,
+ href,
active,
muted,
onClick,
}: {
thread: ForumSidebarThread
+ href?: string
active: boolean
muted: boolean
onClick: () => void
}) {
+ const { active: dragActive } = useDndContext()
const unread = selectUnreadPresentation({
accountUnread: thread.unread,
active,
muted,
})
+ const rowProps = {
+ "data-testid": tid.forumSidebarThread(thread.id),
+ "aria-current": active ? "page" as const : undefined,
+ onContextMenu: (event: MouseEvent<HTMLElement>) => {
+ event.preventDefault()
+ event.stopPropagation()
+ },
+ className: [
+ "ml-4 flex h-7 w-[calc(100%-1rem)] min-w-0 items-center rounded-md px-2 text-left text-xs font-medium focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
+ active
+ ? "bg-sidebar-accent text-foreground"
+ : muted
+ ? "text-muted-foreground/50 hover:bg-sidebar-accent/60 hover:text-muted-foreground"
+ : unread.emphasize
+ ? "text-foreground hover:bg-sidebar-accent/60"
+ : "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",
+ ].join(" "),
+ }
+ const content = (<>
+ <span className="truncate">{thread.title}</span>
+ {unread.showDot && <span className="ml-auto size-2 shrink-0 rounded-full bg-primary" />}
+ </>)
return (
<div className="relative h-7">
- <button
- type="button"
- data-testid={tid.forumSidebarThread(thread.id)}
- aria-current={active ? "page" : undefined}
- onClick={onClick}
- onContextMenu={(event) => {
- event.preventDefault()
- event.stopPropagation()
- }}
- className={[
- "ml-4 flex h-7 w-[calc(100%-1rem)] min-w-0 items-center rounded-md px-2 text-left text-xs font-medium",
- active
- ? "bg-sidebar-accent text-foreground"
- : muted
- ? "text-muted-foreground/50 hover:bg-sidebar-accent/60 hover:text-muted-foreground"
- : unread.emphasize
- ? "text-foreground hover:bg-sidebar-accent/60"
- : "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",
- ].join(" ")}
- >
- <span className="truncate">{thread.title}</span>
- {unread.showDot ? (
- <span className="ml-auto size-2 shrink-0 rounded-full bg-primary" />
- ) : null}
- </button>
+ {href ? (
+ <CommunityNavigationLink {...rowProps} href={href} active={active} onActivate={onClick}
+ navigationDisabled={dragActive !== null}>
+ {content}
+ </CommunityNavigationLink>
+ ) : (
+ <button {...rowProps} type="button" onClick={onClick}>{content}</button>
+ )}
</div>
)
}
diff --git a/src/web/src/components/community/channels/dm-sidebar.prefetch.dom.test.ts b/src/web/src/components/community/channels/dm-sidebar.prefetch.dom.test.ts
index 05885ba55..6936d6f58 100644
--- a/src/web/src/components/community/channels/dm-sidebar.prefetch.dom.test.ts
+++ b/src/web/src/components/community/channels/dm-sidebar.prefetch.dom.test.ts
@@ -21,7 +21,7 @@ describe("DmSidebar navigation intent", () => {
const badge = renderer.queryByTestId(tid.friendsShortcutBadge)
if (label === null) expect(badge).toBeNull()
else expect(badge).toHaveTextContent(label)
- expect(renderer.getByRole("button", { name: count ? `Friends, ${count} new requests` : "Friends" }))
+ expect(renderer.getByRole("link", { name: count ? `Friends, ${count} new requests` : "Friends" }))
.toBeInTheDocument()
})
@@ -65,7 +65,7 @@ describe("DmSidebar navigation intent", () => {
onShowBots,
}))
- const [friends, machines, bots] = renderer.container.querySelectorAll("button")
+ const [friends, machines, bots] = renderer.container.querySelectorAll("a")
fireEvent.pointerEnter(friends!)
fireEvent.focus(machines!)
fireEvent.pointerEnter(bots!)
@@ -147,3 +147,5 @@ describe("DmSidebar navigation intent", () => {
expect(unreadDots()).toHaveLength(1)
})
})
+
+vi.mock("next/link", async () => ({ default: (await import("@/test/community-link-mock")).CommunityLinkMock }))
diff --git a/src/web/src/components/community/channels/dm-sidebar.tsx b/src/web/src/components/community/channels/dm-sidebar.tsx
index 3248817f4..d08f1416c 100644
--- a/src/web/src/components/community/channels/dm-sidebar.tsx
+++ b/src/web/src/components/community/channels/dm-sidebar.tsx
@@ -1,5 +1,7 @@
"use client"
+import { CommunityNavigationLink } from "../shell/community-navigation-link"
+import { dmHref } from "@/lib/community/community-route"
import { memo } from "react"
import { Users, Ban, Monitor, Bot } from "lucide-react"
import { Avatar } from "../avatar"
@@ -32,11 +34,14 @@ export const DmSidebar = memo(function DmSidebar({
return (
<aside className="flex min-h-0 min-w-0 flex-1 flex-col">
<div data-slot="dm-sidebar-shortcuts" className="shrink-0 px-2 pt-4">
- <button
+ <CommunityNavigationLink
aria-label={requestCount ? `Friends, ${friendRequestCount} new requests` : "Friends"}
- onClick={onShowFriends}
+ href="/c/me/friends"
+ prefetchMode="visible"
+ active={isFriendsActive}
+ onActivate={onShowFriends}
className={[
- "mb-1 flex h-9 w-full items-center gap-2 rounded-md px-2 text-sm font-medium",
+ "mb-1 flex h-9 w-full items-center gap-2 rounded-md px-2 text-sm font-medium focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
isFriendsActive ? "bg-sidebar-accent text-foreground" : "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",
].join(" ")}
>
@@ -49,29 +54,35 @@ export const DmSidebar = memo(function DmSidebar({
{requestCount}
</span>
)}
- </button>
+ </CommunityNavigationLink>
{onShowMachines && (
- <button
+ <CommunityNavigationLink
data-testid={tid.machineGuideIntroSource}
- onClick={onShowMachines}
+ href="/c/me/machines"
+ prefetchMode="visible"
+ active={machinesActive}
+ onActivate={onShowMachines}
className={[
- "mb-1 flex h-9 w-full items-center gap-2 rounded-md px-2 text-sm font-medium",
+ "mb-1 flex h-9 w-full items-center gap-2 rounded-md px-2 text-sm font-medium focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
machinesActive ? "bg-sidebar-accent text-foreground" : "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",
].join(" ")}
>
<Monitor className="size-5" /> Machines
- </button>
+ </CommunityNavigationLink>
)}
{onShowBots && (
- <button
- onClick={onShowBots}
+ <CommunityNavigationLink
+ href="/c/me/bots"
+ prefetchMode="visible"
+ active={botsActive}
+ onActivate={onShowBots}
className={[
- "mb-2 flex h-9 w-full items-center gap-2 rounded-md px-2 text-sm font-medium",
+ "mb-2 flex h-9 w-full items-center gap-2 rounded-md px-2 text-sm font-medium focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
botsActive ? "bg-sidebar-accent text-foreground" : "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",
].join(" ")}
>
<Bot className="size-5" /> My Bots
- </button>
+ </CommunityNavigationLink>
)}
<div className="my-2 h-px bg-border" />
</div>
@@ -93,12 +104,14 @@ export const DmSidebar = memo(function DmSidebar({
muted: isBlocked,
})
return (
- <button
+ <CommunityNavigationLink
key={d.id}
data-testid={tid.dmRow(d.id)}
- onClick={() => onPickDm(d.id)}
+ href={dmHref(d.id)}
+ active={active}
+ onActivate={() => onPickDm(d.id)}
className={[
- "flex w-full items-center gap-3 rounded-md px-2 py-2",
+ "flex w-full items-center gap-3 rounded-md px-2 py-2 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
active ? "bg-sidebar-accent text-foreground" : "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",
].join(" ")}
>
@@ -109,7 +122,7 @@ export const DmSidebar = memo(function DmSidebar({
</div>
{isBlocked && <Ban className="size-4 shrink-0 text-destructive" />}
{unread.showDot && <span className="size-2 shrink-0 rounded-full bg-primary" />}
- </button>
+ </CommunityNavigationLink>
)
})}
</div>
diff --git a/src/web/src/components/community/channels/sortable-channel.tsx b/src/web/src/components/community/channels/sortable-channel.tsx
index 240fa5859..40e17e16c 100644
--- a/src/web/src/components/community/channels/sortable-channel.tsx
+++ b/src/web/src/components/community/channels/sortable-channel.tsx
@@ -1,5 +1,6 @@
"use client"
+import { CommunityNavigationLink } from "../shell/community-navigation-link"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
import { BellOff, Loader2, Pencil, Trash2, Users } from "lucide-react"
@@ -39,8 +40,9 @@ export function PendingChannelRow({ ch }: { ch: Channel }) {
// A single drag-sortable channel row. The whole row is the drag surface (no handle);
// mouse movement or a touch long-press distinguishes navigation from reorder.
// Right-click opens an edit/mute/delete menu.
-export function SortableChannel({ ch, active, onClick, onEdit, onDelete, onManageMembers, canReorder = true }: {
+export function SortableChannel({ ch, href, active, onClick, onEdit, onDelete, onManageMembers, canReorder = true }: {
ch: Channel
+ href?: string
active: boolean
onClick: () => void
onEdit?: () => void
@@ -49,7 +51,7 @@ export function SortableChannel({ ch, active, onClick, onEdit, onDelete, onManag
canReorder?: boolean
}) {
const [confirmingDelete, setConfirmingDelete] = useAtom(useCreateAtom(false))
- const { attributes, listeners, setNodeRef, transform, transition, isDragging, isOver, activeIndex, index } = useSortable({ id: ch.id, disabled: !canReorder })
+ const { attributes, listeners, setNodeRef, transform, transition, isDragging, isOver, activeIndex, index, active: dragActive } = useSortable({ id: ch.id, disabled: !canReorder })
const style = { transform: CSS.Transform.toString(transform), transition, opacity: isDragging ? 0.4 : 1, zIndex: isDragging ? 10 : undefined }
const showLine = isOver && !isDragging
const lineSide: "top" | "bottom" = activeIndex !== -1 && activeIndex < index ? "bottom" : "top"
@@ -58,37 +60,45 @@ export function SortableChannel({ ch, active, onClick, onEdit, onDelete, onManag
active,
muted: ch.muted === true,
})
- const row = (
- <div
- ref={setNodeRef}
- style={style}
- onClick={onClick}
- data-testid={tid.channelRow(ch.id)}
- {...attributes}
- {...listeners}
- className={[
- "group relative flex h-8 w-full cursor-pointer touch-manipulation items-center gap-2 rounded-md px-2 text-sm select-none",
- canReorder ? "active:cursor-grabbing" : "",
- active
- ? "bg-sidebar-accent text-foreground"
- : ch.muted
- ? "text-muted-foreground/50 hover:bg-sidebar-accent/60 hover:text-muted-foreground"
- : unread.emphasize
- ? "text-foreground hover:bg-sidebar-accent/60"
- : "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",
- ].join(" ")}
- >
+ const rowProps = {
+ ref: setNodeRef,
+ style,
+ "data-testid": tid.channelRow(ch.id),
+ ...attributes,
+ ...listeners,
+ className: [
+ "group relative flex h-8 w-full cursor-pointer touch-manipulation items-center gap-2 rounded-md px-2 text-sm select-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
+ canReorder ? "active:cursor-grabbing" : "",
+ active
+ ? "bg-sidebar-accent text-foreground"
+ : ch.muted
+ ? "text-muted-foreground/50 hover:bg-sidebar-accent/60 hover:text-muted-foreground"
+ : unread.emphasize
+ ? "text-foreground hover:bg-sidebar-accent/60"
+ : "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",
+ ].join(" "),
+ }
+ const content = (
+ <>
{showLine && <DropLine side={lineSide} />}
<span className="grid size-5 shrink-0 place-items-center opacity-70">
- <EntityIcon kind={ch.type} className="size-4" />
+ <EntityIcon kind={ch.type} className="size-4" />
</span>
<span className="truncate font-semibold">{ch.name}</span>
{ch.muted ? (
- <BellOff className="ml-auto size-4 shrink-0 opacity-70" />
+ <BellOff className="ml-auto size-4 shrink-0 opacity-70" />
) : unread.showDot ? (
- <span className="ml-auto size-2 rounded-full bg-primary" />
+ <span className="ml-auto size-2 rounded-full bg-primary" />
) : null}
- </div>
+ </>
+ )
+ const row = href ? (
+ <CommunityNavigationLink {...rowProps} role="link" href={href} active={active}
+ draggable={false} navigationDisabled={dragActive !== null} onActivate={onClick}>
+ {content}
+ </CommunityNavigationLink>
+ ) : (
+ <div {...rowProps} onClick={onClick}>{content}</div>
)
if (!hasChannelMenu({ onEdit, onManageMembers, onDelete })) return row
return (
diff --git a/src/web/src/components/community/shell/community-navigation-link.dom.test.tsx b/src/web/src/components/community/shell/community-navigation-link.dom.test.tsx
new file mode 100644
index 000000000..8adaafdc4
--- /dev/null
+++ b/src/web/src/components/community/shell/community-navigation-link.dom.test.tsx
@@ -0,0 +1,94 @@
+import { createStore } from "@tanstack/react-store"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { act, fireEvent, render, setupUser } from "@/test/react-dom-harness"
+import type { CommunityDbRegistry } from "@/lib/community-db/collections"
+import { CommunityNavigationLink } from "./community-navigation-link"
+
+const owner = vi.hoisted(() => ({ registry: null as CommunityDbRegistry | null }))
+vi.mock("@/lib/community-db/projections", () => ({ useOptionalCommunityDbRegistry: () => owner.registry }))
+vi.mock("next/link", async () => ({ default: (await import("@/test/community-link-mock")).CommunityLinkMock }))
+
+beforeEach(() => { owner.registry = null })
+
+describe("community public Link bridge", () => {
+ it("requests full prefetch only on intent and resets it when href changes, retaining the anchor", async () => {
+ const onActivate = vi.fn()
+ const props = { href: "/c/channels/a/one", onActivate }
+ const view = render(<CommunityNavigationLink {...props}>A</CommunityNavigationLink>)
+ const anchor = view.getByRole("link")
+ expect(anchor).toHaveAttribute("data-prefetch", "false")
+ fireEvent.pointerEnter(anchor)
+ expect(anchor).toHaveAttribute("data-prefetch", "true")
+ expect(onActivate).not.toHaveBeenCalled()
+ view.rerender(<CommunityNavigationLink {...props} href="/c/channels/a/two">A</CommunityNavigationLink>)
+ expect(view.getByRole("link")).toBe(anchor)
+ expect(anchor).toHaveAttribute("data-prefetch", "false")
+ view.rerender(<CommunityNavigationLink {...props}>A</CommunityNavigationLink>)
+ expect(anchor).toHaveAttribute("data-prefetch", "false")
+ fireEvent.focus(anchor)
+ expect(anchor).toHaveAttribute("data-prefetch", "true")
+ await setupUser().click(anchor)
+ expect(onActivate).toHaveBeenCalledTimes(1)
+ })
+
+ it("warms a touch intent without navigating before activation", () => {
+ const onActivate = vi.fn()
+ const view = render(<CommunityNavigationLink href="/c/me/dm" onActivate={onActivate}>DM</CommunityNavigationLink>)
+ const event = new Event("pointerdown", { bubbles: true })
+ Object.defineProperty(event, "pointerType", { value: "touch" })
+ fireEvent(view.getByRole("link"), event)
+ expect(view.getByRole("link")).toHaveAttribute("data-prefetch", "true")
+ expect(onActivate).not.toHaveBeenCalled()
+ })
+
+ it("warms visible fixed entries while inactive and preserves click and Enter actions", async () => {
+ const onActivate = vi.fn()
+ const props = { href: "/c/me/bots", onActivate, prefetchMode: "visible" as const }
+ const view = render(<CommunityNavigationLink {...props}>Bots</CommunityNavigationLink>)
+ const anchor = view.getByRole("link")
+ expect(anchor).toHaveAttribute("data-prefetch", "true")
+ view.rerender(<CommunityNavigationLink {...props} active>Bots</CommunityNavigationLink>)
+ expect(anchor).toHaveAttribute("data-prefetch", "false")
+ const user = setupUser()
+ await user.click(anchor)
+ anchor.focus()
+ await user.keyboard("{Enter}")
+ expect(onActivate).toHaveBeenCalledTimes(2)
+ })
+
+ it("leaves modified activation outside the same-tab controller and respects captured suppression", () => {
+ const onActivate = vi.fn()
+ const view = render(<div onClickCapture={(event) => { if (event.altKey) event.preventDefault() }}>
+ <CommunityNavigationLink href="/c/me/friends" onActivate={onActivate}>Friends</CommunityNavigationLink>
+ </div>)
+ const anchor = view.getByRole("link")
+ fireEvent.click(anchor, { ctrlKey: true })
+ fireEvent.click(anchor, { metaKey: true })
+ fireEvent.click(anchor, { altKey: true })
+ expect(onActivate).not.toHaveBeenCalled()
+ fireEvent.click(anchor)
+ expect(onActivate).toHaveBeenCalledTimes(1)
+ })
+
+ it("blocks navigation and warming during dragging, then retires intent on account generation changes", () => {
+ const lifecycle = createStore({ active: true, generation: 0 })
+ owner.registry = { runtime: { lifecycle } } as unknown as CommunityDbRegistry
+ const onActivate = vi.fn()
+ const props = { href: "/c/channels/a/one", onActivate }
+ const view = render(<CommunityNavigationLink {...props} navigationDisabled>A</CommunityNavigationLink>)
+ const anchor = view.getByRole("link")
+ fireEvent.pointerEnter(anchor)
+ fireEvent.click(anchor)
+ expect(anchor).toHaveAttribute("data-prefetch", "false")
+ expect(onActivate).not.toHaveBeenCalled()
+ view.rerender(<CommunityNavigationLink {...props}>A</CommunityNavigationLink>)
+ fireEvent.focus(anchor)
+ expect(anchor).toHaveAttribute("data-prefetch", "true")
+ act(() => lifecycle.setState(() => ({ active: false, generation: 1 })))
+ fireEvent.click(anchor)
+ expect(anchor).toHaveAttribute("data-prefetch", "false")
+ expect(onActivate).not.toHaveBeenCalled()
+ act(() => lifecycle.setState(() => ({ active: true, generation: 2 })))
+ expect(anchor).toHaveAttribute("data-prefetch", "false")
+ })
+})
diff --git a/src/web/src/components/community/shell/community-navigation-link.tsx b/src/web/src/components/community/shell/community-navigation-link.tsx
new file mode 100644
index 000000000..95a1e561e
--- /dev/null
+++ b/src/web/src/components/community/shell/community-navigation-link.tsx
@@ -0,0 +1,60 @@
+"use client"
+
+import Link from "next/link"
+import { useLayoutEffect, type ComponentProps } from "react"
+import { createStore, useAtom, useCreateAtom, useSelector } from "@tanstack/react-store"
+import { useOptionalCommunityDbRegistry } from "@/lib/community-db/projections"
+
+const absentLifecycle = createStore({ active: true, generation: 0 })
+
+type Props = Omit<ComponentProps<typeof Link>, "href" | "prefetch" | "onNavigate"> & {
+ href: string
+ onActivate: () => void
+ prefetchMode?: "intent" | "visible"
+ active?: boolean
+ navigationDisabled?: boolean
+}
+
+export function CommunityNavigationLink({
+ href, onActivate, prefetchMode = "intent", active = false, navigationDisabled = false,
+ onPointerEnter, onFocus, onPointerDown, onClick, ...props
+}: Props) {
+ const registry = useOptionalCommunityDbRegistry()
+ const lifecycle = useSelector(registry?.runtime.lifecycle ?? absentLifecycle, (state) => state)
+ const [intent, setIntent] = useAtom(useCreateAtom<{
+ href: string
+ registry: typeof registry
+ generation: number
+ } | null>(null))
+ useLayoutEffect(() => { setIntent(null) }, [href, registry, lifecycle.generation, setIntent])
+ const enabled = lifecycle.active && !navigationDisabled
+ const warm = () => {
+ if (enabled && !active) setIntent({ href, registry, generation: lifecycle.generation })
+ }
+ const prefetched = enabled && !active && (prefetchMode === "visible"
+ || (intent?.href === href && intent.registry === registry && intent.generation === lifecycle.generation))
+ return (
+ <Link
+ {...props}
+ href={href}
+ prefetch={prefetched}
+ aria-current={active ? "page" : props["aria-current"]}
+ onPointerEnter={(event) => { onPointerEnter?.(event); if (!event.defaultPrevented) warm() }}
+ onFocus={(event) => { onFocus?.(event); if (!event.defaultPrevented) warm() }}
+ onPointerDown={(event) => {
+ onPointerDown?.(event)
+ if (!event.defaultPrevented && event.pointerType === "touch") warm()
+ }}
+ onClick={(event) => {
+ onClick?.(event)
+ if (navigationDisabled || !lifecycle.active) {
+ event.preventDefault()
+ }
+ }}
+ onNavigate={(event) => {
+ event.preventDefault()
+ if (enabled) onActivate()
+ }}
+ />
+ )
+}
diff --git a/src/web/src/components/community/shell/dm-sidebar-slot.tsx b/src/web/src/components/community/shell/dm-sidebar-slot.tsx
index e33e6f5cc..96d48855b 100644
--- a/src/web/src/components/community/shell/dm-sidebar-slot.tsx
+++ b/src/web/src/components/community/shell/dm-sidebar-slot.tsx
@@ -2,6 +2,7 @@
import { useCommunityRuntime } from "@/stores/community/runtime"
+import { dmHref } from "@/lib/community/community-route"
import { useCallback, useMemo } from "react"
import { useCommunityRouteFrame } from "./community-route-context"
import { DmSidebar } from "@/components/community/channels/dm-sidebar"
@@ -40,7 +41,7 @@ function MeSidebar() {
// 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.get().uiHandlers.navigatePath?.(dmHref(id))
}, [communityRuntime.ui])
const onShowFriends = useCallback(() => {
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 23f9784e7..005323dfd 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
@@ -619,3 +619,5 @@ describe("ServerRail one-in-flight structural guard", () => {
},
)
})
+
+vi.mock("next/link", async () => ({ default: (await import("@/test/community-link-mock")).CommunityLinkMock }))
diff --git a/src/web/src/components/community/shell/server-rail.tsx b/src/web/src/components/community/shell/server-rail.tsx
index 2d61d1616..c4a58a753 100644
--- a/src/web/src/components/community/shell/server-rail.tsx
+++ b/src/web/src/components/community/shell/server-rail.tsx
@@ -20,6 +20,8 @@ import { AnimatedAlookLogo } from "./animated-alook-logo"
import { tid } from "@/lib/community/testids"
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"
import { Skeleton } from "@/components/ui/skeleton"
+import { CommunityNavigationLink } from "./community-navigation-link"
+import { serverRootHref } from "@/lib/community/community-route"
import { SortableServer } from "./sortable-server"
import { RailFolder } from "./rail-folder"
import { RailIndicator } from "./rail-indicator"
@@ -108,6 +110,8 @@ function ServerRailFrame({
export const ServerRail = memo(function ServerRail({
servers,
+ homeHref = "/c/me",
+ serverHrefs = {},
folders,
activeServerId: activeServerIdProp,
serversLoading,
@@ -122,6 +126,8 @@ export const ServerRail = memo(function ServerRail({
onOpenInvitePopover,
}: {
servers: Server[]
+ homeHref?: string
+ serverHrefs?: Readonly<Record<string, string>>
folders: CommunityFolder[]
activeServerId?: string
serversLoading?: boolean
@@ -358,14 +364,17 @@ export const ServerRail = memo(function ServerRail({
<Tooltip>
<TooltipTrigger render={<div className="group relative flex w-full justify-center" />}>
<RailIndicator active={view === "dm"} />
- <button
- onClick={onHome}
+ <CommunityNavigationLink
+ href={homeHref}
+ active={view === "dm"}
+ onActivate={onHome}
+ navigationDisabled={dragSource !== null}
aria-label="Home"
data-testid={tid.homeButton}
className="group/alook grid size-10 shrink-0 place-items-center rounded-[20px] focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
>
<AnimatedAlookLogo className="size-10" />
- </button>
+ </CommunityNavigationLink>
</TooltipTrigger>
<TooltipContent side="right" sideOffset={8}>Home</TooltipContent>
</Tooltip>
@@ -382,6 +391,8 @@ export const ServerRail = memo(function ServerRail({
<SortableServer
key={serverId}
server={server}
+ href={serverHrefs[serverId] ?? serverRootHref(serverId)}
+ navigationDisabled={dragSource !== null}
active={view !== "dm" && activeId === serverId}
onClick={() => pickServer(serverId)}
onLeave={() => onLeaveServer?.(serverId)}
@@ -430,6 +441,8 @@ export const ServerRail = memo(function ServerRail({
<SortableServer
key={server.id}
server={server}
+ href={serverHrefs[server.id] ?? serverRootHref(server.id)}
+ navigationDisabled={dragSource !== null}
active={view !== "dm" && activeId === server.id}
onClick={() => pickServer(server.id)}
onOpenSettings={() => serverActivationRef.current.onOpenSettings?.(server.id)}
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 56f992830..9b36aa519 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
@@ -45,7 +45,7 @@ function renderServer(
dragDescriptionId: "rail-help",
...extraProps,
}))
- const button = () => renderer.container.querySelector<HTMLButtonElement>("button")!
+ const button = () => renderer.container.querySelector<HTMLAnchorElement>("a")!
const activationRoot = () => button().closest("div.group") as HTMLDivElement
return { ...renderer, button, activationRoot }
}
@@ -53,6 +53,25 @@ function renderServer(
describe("SortableServer stable menu trigger", () => {
afterEach(() => vi.restoreAllMocks())
+ it("updates href on the same registered anchor with the committed activation dispatcher", async () => {
+ const registerItem = vi.fn(() => vi.fn())
+ const current = { activate: vi.fn() }
+ const dispatch = () => current.activate()
+ const props = { server, onClick: dispatch, registerItem, href: "/c/channels/a/first" }
+ const result = render(createElement(SortableServer, props))
+ const anchor = result.getByTestId(tid.serverIcon("a"))
+ const originalActivate = current.activate
+ current.activate = vi.fn()
+ result.rerender(createElement(SortableServer, { ...props, href: "/c/channels/a/latest" }))
+ expect(result.getByTestId(tid.serverIcon("a"))).toBe(anchor)
+ expect(anchor).toHaveAttribute("href", "/c/channels/a/latest")
+ expect(registerItem).toHaveBeenCalledTimes(1)
+ expect(registerItem).toHaveBeenCalledWith({ kind: "server", id: "a" }, expect.any(HTMLElement), anchor)
+ await setupUser().click(anchor)
+ expect(originalActivate).not.toHaveBeenCalled()
+ expect(current.activate).toHaveBeenCalledTimes(1)
+ })
+
it("announces official status without changing ordinary server labels", () => {
const ordinary = renderServer()
expect(ordinary.button()).toHaveAccessibleName("A")
@@ -149,3 +168,5 @@ describe("SortableServer stable menu trigger", () => {
.toHaveLength(0)
})
})
+
+vi.mock("next/link", async () => ({ default: (await import("@/test/community-link-mock")).CommunityLinkMock }))
diff --git a/src/web/src/components/community/shell/sortable-server.tsx b/src/web/src/components/community/shell/sortable-server.tsx
index 1a258d6bc..cda3354e8 100644
--- a/src/web/src/components/community/shell/sortable-server.tsx
+++ b/src/web/src/components/community/shell/sortable-server.tsx
@@ -24,7 +24,12 @@ import { tid } from "@/lib/community/testids";
import type { Server } from "@/lib/community/models/navigation"
import type { RailEntity, RailOperation } from "@/lib/community/server-rail-model"
+import { CommunityNavigationLink } from "./community-navigation-link"
+import { serverRootHref } from "@/lib/community/community-route"
+
type SortableServerProps = {
+ href?: string;
+ navigationDisabled?: boolean;
server: Server;
active?: boolean;
onClick: () => void;
@@ -44,6 +49,8 @@ type SortableServerProps = {
function SortableServerImpl({
server,
+ href = serverRootHref(server.id),
+ navigationDisabled,
active,
onClick,
onLeave,
@@ -56,15 +63,15 @@ function SortableServerImpl({
dragDescriptionId,
}: SortableServerProps) {
const rootRef = useRef<HTMLDivElement>(null)
- const buttonRef = useRef<HTMLButtonElement>(null)
+ const linkRef = useRef<HTMLAnchorElement>(null)
const [confirmLeave, setConfirmLeave] = useAtom(useCreateAtom(false));
const [activated, setActivated] = useAtom(useCreateAtom(false));
useLayoutEffect(() => {
- if (!registerItem || !rootRef.current || !buttonRef.current) return
+ if (!registerItem || !rootRef.current || !linkRef.current) return
return registerItem(
{ kind: "server", id: server.id },
rootRef.current,
- buttonRef.current,
+ linkRef.current,
)
}, [registerItem, server.id])
const activate = activated ? undefined : () => setActivated(true);
@@ -98,15 +105,19 @@ function SortableServerImpl({
isDragActive ? "rounded-xl border-2 border-dashed border-muted-foreground/40" : "",
].join(" ")}
>
- <button
- ref={buttonRef}
+ <CommunityNavigationLink
+ href={href}
+ active={active}
+ navigationDisabled={navigationDisabled}
+ draggable={false}
+ ref={linkRef}
data-testid={tid.serverIcon(server.id)}
data-dragging={isDragActive || undefined}
data-rail-preview={preview ?? undefined}
aria-label={server.official ? `${server.name}, Official server` : server.name}
aria-describedby={dragDescriptionId}
aria-keyshortcuts="Space ArrowUp ArrowDown ArrowLeft ArrowRight Escape"
- onClick={active ? undefined : onClick}
+ onActivate={() => { if (!active) onClick() }}
className={[
"group/server absolute left-1/2 top-1/2 z-1 grid size-11 -translate-x-1/2 -translate-y-1/2 place-items-center focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none active:cursor-grabbing [-webkit-touch-callout:none]",
active ? "cursor-default" : "cursor-pointer",
@@ -132,7 +143,7 @@ function SortableServerImpl({
].join(" ")}
/>
<OfficialServerBadge official={server.official} className="absolute -left-1 -top-1 z-2" />
- </button>
+ </CommunityNavigationLink>
{server.mentions > 0 && (
<span
data-testid={tid.railUnreadBadge(server.id)}
@@ -230,6 +241,8 @@ export function serverPropsEqual(prev: SortableServerProps, next: SortableServer
a.unread === b.unread &&
a.mentions === b.mentions &&
a.isOwner === b.isOwner &&
+ prev.href === next.href &&
+ prev.navigationDisabled === next.navigationDisabled &&
prev.active === next.active &&
prev.inFolder === next.inFolder &&
prev.dragging === next.dragging &&
diff --git a/src/web/src/components/community/shell/sortable-server.unread.test.ts b/src/web/src/components/community/shell/sortable-server.unread.test.ts
index c813423d2..5615c474f 100644
--- a/src/web/src/components/community/shell/sortable-server.unread.test.ts
+++ b/src/web/src/components/community/shell/sortable-server.unread.test.ts
@@ -15,6 +15,11 @@ const base = {
}
describe("SortableServer unread memo boundary", () => {
+ it("rerenders for changed href and drag qualification while ignoring callbacks", () => {
+ expect(serverPropsEqual({ ...base, href: "/c/channels/server/a" }, { ...base, href: "/c/channels/server/b" })).toBe(false)
+ expect(serverPropsEqual(base, { ...base, navigationDisabled: true })).toBe(false)
+ })
+
it("rerenders when official status changes", () => {
const official = { ...base, server: { ...base.server, official: true } }
expect(serverPropsEqual(base, official)).toBe(false)
diff --git a/src/web/src/components/community/shell/use-community-rail-hrefs.dom.test.tsx b/src/web/src/components/community/shell/use-community-rail-hrefs.dom.test.tsx
new file mode 100644
index 000000000..d5e26a6b4
--- /dev/null
+++ b/src/web/src/components/community/shell/use-community-rail-hrefs.dom.test.tsx
@@ -0,0 +1,121 @@
+import { createElement } from "react"
+import { renderToString } from "react-dom/server"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { act, renderHook } from "@/test/react-dom-harness"
+import { clearLastChannel, setLastChannel } from "@/lib/community/last-channel"
+import { setLastMeLocation } from "@/lib/community/last-me-location"
+import type { CommunityDbRegistry } from "@/lib/community-db/collections"
+import { useCommunityRailHrefs } from "./use-community-rail-hrefs"
+
+const owner = vi.hoisted(() => ({ registry: null as CommunityDbRegistry | null }))
+vi.mock("@/lib/community-db/projections", () => ({ useOptionalCommunityDbRegistry: () => owner.registry }))
+
+function collection<T>(initial: readonly [string, T][]) {
+ const rows = new Map(initial)
+ const listeners = new Set<() => void>()
+ return {
+ get: (id: string) => rows.get(id), values: () => rows.values(),
+ subscribeChanges: (notify: () => void) => {
+ listeners.add(notify)
+ return { unsubscribe: () => listeners.delete(notify) }
+ },
+ put: (id: string, row: T) => { rows.set(id, row); listeners.forEach((notify) => notify()) },
+ listenerCount: () => listeners.size,
+ }
+}
+
+beforeEach(() => { localStorage.clear(); owner.registry = null })
+afterEach(() => { vi.restoreAllMocks() })
+
+describe("rail hrefs derived from canonical rows and existing navigation memory", () => {
+ it.each(["desktop", "mobile", "unknown"] as const)("server-renders deterministic %s links without reading client memory or subscribing", (breakpoint) => {
+ const servers = collection([["s", { detailComplete: true }], ["other", { detailComplete: true }]])
+ const channels = collection([
+ ["first", { id: "first", serverId: "s", type: "text" }],
+ ["second", { id: "second", serverId: "other", type: "text" }],
+ ])
+ owner.registry = { collections: { servers, channels } } as unknown as CommunityDbRegistry
+ setLastMeLocation("/c/me/machines")
+ setLastChannel("s", "remembered")
+ setLastChannel("other", "other-remembered")
+ const getItem = vi.spyOn(Storage.prototype, "getItem")
+ const setItem = vi.spyOn(Storage.prototype, "setItem")
+ const removeItem = vi.spyOn(Storage.prototype, "removeItem")
+ const getServer = vi.spyOn(servers, "get")
+ const channelValues = vi.spyOn(channels, "values")
+
+ function Rail() {
+ const { homeHref, serverHrefs } = useCommunityRailHrefs([{ id: "s" }, { id: "other" }], breakpoint)
+ return createElement("nav", null,
+ Object.entries({ home: homeHref, ...serverHrefs }).map(([id, href]) => createElement("a", { key: id, href }, id)))
+ }
+ const markup = document.createElement("div")
+ markup.innerHTML = renderToString(createElement(Rail))
+ expect(Object.fromEntries(Array.from(markup.querySelectorAll("a"), (link) => [link.textContent, link.getAttribute("href")]))).toEqual({
+ home: breakpoint === "desktop" ? "/c/me/friends" : "/c/me",
+ s: "/c/channels/s",
+ other: "/c/channels/other",
+ })
+ expect(getItem).not.toHaveBeenCalled()
+ expect(setItem).not.toHaveBeenCalled()
+ expect(removeItem).not.toHaveBeenCalled()
+ expect(getServer).not.toHaveBeenCalled()
+ expect(channelValues).not.toHaveBeenCalled()
+ expect(servers.listenerCount()).toBe(0)
+ expect(channels.listenerCount()).toBe(0)
+ expect(localStorage.getItem("community:lastChannel:me")).toBe("machines")
+ expect(localStorage.getItem("community:lastChannel:s")).toBe("remembered")
+ expect(localStorage.getItem("community:lastChannel:other")).toBe("other-remembered")
+ })
+
+ it("updates remembered Home leaves after commit for each non-DM page", () => {
+ const view = renderHook(() => useCommunityRailHrefs([], "desktop"))
+ expect(view.result.current.homeHref).toBe("/c/me/friends")
+ for (const leaf of ["bots", "machines", "friends"]) {
+ act(() => setLastMeLocation(`/c/me/${leaf}`))
+ expect(view.result.current.homeHref).toBe(`/c/me/${leaf}`)
+ }
+ })
+
+ it("subscribes to complete canonical channels, filters placeholders/threads, and follows the latest memory", () => {
+ const servers = collection<{ detailComplete: boolean }>([["s", { detailComplete: false }]])
+ const channels = collection<{ id: string; serverId: string; type: string; pending?: boolean }>([
+ ["pending", { id: "pending", serverId: "s", type: "text", pending: true }],
+ ["thread", { id: "thread", serverId: "s", type: "thread" }],
+ ["first", { id: "first", serverId: "s", type: "text" }],
+ ["foreign", { id: "foreign", serverId: "other", type: "text" }],
+ ])
+ owner.registry = { collections: { servers, channels } } as unknown as CommunityDbRegistry
+ const rows = [{ id: "s" }]
+ const view = renderHook(({ breakpoint }: { breakpoint: "desktop" | "mobile" }) =>
+ useCommunityRailHrefs(rows, breakpoint), { initialProps: { breakpoint: "desktop" } })
+ expect(view.result.current.serverHrefs.s).toBe("/c/channels/s")
+ act(() => servers.put("s", { detailComplete: true }))
+ expect(view.result.current.serverHrefs.s).toBe("/c/channels/s/first")
+ act(() => setLastChannel("s", "latest"))
+ expect(view.result.current.serverHrefs.s).toBe("/c/channels/s/latest")
+ act(() => clearLastChannel("s"))
+ expect(view.result.current.serverHrefs.s).toBe("/c/channels/s/first")
+ view.rerender({ breakpoint: "mobile" })
+ expect(view.result.current.serverHrefs.s).toBe("/c/channels/s")
+ expect(view.result.current.homeHref).toBe("/c/me")
+ view.unmount()
+ expect(servers.listenerCount()).toBe(0)
+ expect(channels.listenerCount()).toBe(0)
+ })
+
+ it("refreshes cross-tab memory from native storage events without writing during render", () => {
+ const view = renderHook(() => useCommunityRailHrefs([{ id: "s" }], "desktop"))
+ act(() => {
+ localStorage.setItem("community:lastChannel:s", "new")
+ window.dispatchEvent(new StorageEvent("storage", { key: "community:lastChannel:s" }))
+ })
+ expect(view.result.current.serverHrefs.s).toBe("/c/channels/s/new")
+ act(() => {
+ localStorage.setItem("community:lastChannel:s", "invalid/path")
+ window.dispatchEvent(new StorageEvent("storage", { key: "community:lastChannel:s" }))
+ })
+ expect(view.result.current.serverHrefs.s).toBe("/c/channels/s")
+ expect(localStorage.getItem("community:lastChannel:s")).toBe("invalid/path")
+ })
+})
diff --git a/src/web/src/components/community/shell/use-community-rail-hrefs.ts b/src/web/src/components/community/shell/use-community-rail-hrefs.ts
new file mode 100644
index 000000000..58880d7f7
--- /dev/null
+++ b/src/web/src/components/community/shell/use-community-rail-hrefs.ts
@@ -0,0 +1,58 @@
+"use client"
+
+import { useCallback, useMemo, useSyncExternalStore } from "react"
+import type { Breakpoint } from "@/hooks/use-mobile"
+import type { CommunityDbRegistry } from "@/lib/community-db/collections"
+import { useOptionalCommunityDbRegistry } from "@/lib/community-db/projections"
+import { lastChannelKey, resolveCommunityLandingHref } from "@/lib/community/last-channel"
+import { lastMeLocationKey } from "@/lib/community/last-me-location"
+import { readNavigationMemory, subscribeNavigationMemory } from "@/lib/community/navigation-memory"
+
+export function communityServerLandingHref(
+ registry: CommunityDbRegistry | null, id: string, last: string | null, breakpoint: Breakpoint, canonicalChannelIds?: readonly string[],
+) {
+ const complete = registry?.collections.servers.get(id)?.detailComplete === true
+ const channelIds = registry && complete
+ ? canonicalChannelIds ?? Array.from(registry.collections.channels.values())
+ .filter((channel) => channel.serverId === id && channel.type !== "thread" && !channel.pending)
+ .map((channel) => channel.id)
+ : []
+ return resolveCommunityLandingHref({ serverId: id, channelIds, last, breakpoint })
+}
+
+export function useCommunityRailHrefs(servers: readonly { id: string }[], breakpoint: Breakpoint) {
+ const registry = useOptionalCommunityDbRegistry()
+ const subscribe = useCallback((notify: () => void) => {
+ const memory = subscribeNavigationMemory(notify)
+ const serverChanges = registry?.collections.servers.subscribeChanges(notify)
+ const channelChanges = registry?.collections.channels.subscribeChanges(notify)
+ return () => {
+ memory()
+ serverChanges?.unsubscribe()
+ channelChanges?.unsubscribe()
+ }
+ }, [registry])
+ const getSnapshot = useCallback(() => {
+ const channelsByServer = new Map<string, string[]>()
+ for (const channel of registry?.collections.channels.values() ?? []) {
+ if (!channel.serverId || channel.type === "thread" || channel.pending) continue
+ const ids = channelsByServer.get(channel.serverId) ?? []
+ ids.push(channel.id)
+ channelsByServer.set(channel.serverId, ids)
+ }
+ return JSON.stringify({
+ homeHref: resolveCommunityLandingHref({ serverId: null, last: readNavigationMemory(lastMeLocationKey()), breakpoint }),
+ serverHrefs: Object.fromEntries(servers.map(({ id }) => [id,
+ communityServerLandingHref(registry, id, readNavigationMemory(lastChannelKey(id)), breakpoint, channelsByServer.get(id) ?? []),
+ ])),
+ })
+ }, [registry, servers, breakpoint])
+ const getServerSnapshot = useCallback(() => JSON.stringify({
+ homeHref: resolveCommunityLandingHref({ serverId: null, last: null, breakpoint }),
+ serverHrefs: Object.fromEntries(servers.map(({ id }) => [id,
+ resolveCommunityLandingHref({ serverId: id, last: null, breakpoint }),
+ ])),
+ }), [servers, breakpoint])
+ const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
+ return useMemo(() => JSON.parse(snapshot) as { homeHref: string; serverHrefs: Record<string, string> }, [snapshot])
+}
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 f60e4d8f5..6ae00d19c 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
@@ -18,8 +18,8 @@ const mocks = vi.hoisted(() => ({
lastChannel: { current: null as string | null },
lastMeLeaf: { current: null as string | null },
communityDb: { current: null as null | { collections: {
- servers: { get: (id: string) => { detailComplete?: boolean } | undefined }
- channels: { values: () => IterableIterator<Record<string, unknown>> }
+ servers: { get: (id: string) => { detailComplete?: boolean } | undefined; subscribeChanges: (notify: () => void) => { unsubscribe: () => void } }
+ channels: { values: () => IterableIterator<Record<string, unknown>>; subscribeChanges: (notify: () => void) => { unsubscribe: () => void } }
} } },
}))
@@ -56,7 +56,8 @@ vi.mock("@/lib/community/last-channel", async (importOriginal) => ({
...await importOriginal<typeof import("@/lib/community/last-channel")>(),
getLastChannel: () => mocks.lastChannel.current,
}))
-vi.mock("@/lib/community/last-me-location", () => ({
+vi.mock("@/lib/community/last-me-location", async (importOriginal) => ({
+ ...await importOriginal<typeof import("@/lib/community/last-me-location")>(),
ME_ROOT: "/c/me",
getLastMeLeaf: () => mocks.lastMeLeaf.current,
pickMeLandingLocation: (leaf: string | null) => `/c/me/${leaf ?? "friends"}`,
@@ -280,8 +281,8 @@ describe("useShellRailController", () => {
["foreign", { id: "foreign", serverId: "s2", type: "text", pending: false }],
])
mocks.communityDb.current = { collections: {
- servers: { get: (id) => servers.get(id) },
- channels: { values: () => channels.values() },
+ servers: { get: (id) => servers.get(id), subscribeChanges: () => ({ unsubscribe: vi.fn() }) },
+ channels: { values: () => channels.values(), subscribeChanges: () => ({ unsubscribe: vi.fn() }) },
} }
const hook = await renderController()
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 d0732f8e6..9edae4804 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
@@ -233,3 +233,5 @@ describe("actual native Rail controller continuation", () => {
expect(getCommunityRuntime(client).ws.get().revokedServerIds.has("s2")).toBe(true)
})
})
+
+vi.mock("next/link", async () => ({ default: (await import("@/test/community-link-mock")).CommunityLinkMock }))
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 531a08211..a99457722 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
@@ -26,6 +26,8 @@ import type { CommunityNavigationController } from "./use-community-navigation-c
import type { QueryClient } from "@tanstack/react-query"
import { useOptionalCommunityDbRegistry } from "@/lib/community-db/projections"
+import { communityServerLandingHref, useCommunityRailHrefs } from "./use-community-rail-hrefs"
+
type Options = Pick<
ShellFrameProps,
| "view"
@@ -95,12 +97,9 @@ export function useShellRailController({
[projectedActiveServerId, servers],
)
+ const { homeHref, serverHrefs } = useCommunityRailHrefs(servers, breakpoint)
const serverDestination = useCallback((id: string) => {
- const complete = communityDb?.collections.servers.get(id)?.detailComplete === true
- const channelIds = communityDb && complete
- ? Array.from(communityDb.collections.channels.values()).filter((channel) => channel.serverId === id && channel.type !== "thread" && !channel.pending).map((channel) => channel.id)
- : []
- return resolveCommunityLandingHref({ serverId: id, channelIds, last: getLastChannel(id), breakpoint })
+ return communityServerLandingHref(communityDb, id, getLastChannel(id), breakpoint)
}, [breakpoint, communityDb])
const onServerNavigate = useCallback((id: string) => {
markSwitch("server", id)
@@ -195,6 +194,8 @@ export function useShellRailController({
return {
railProps: {
servers: railServers,
+ homeHref,
+ serverHrefs,
folders,
activeServerId: projectedActiveServerId,
serversLoading: serversQuery.isPending && servers.length === 0,
diff --git a/src/web/src/lib/community-db/sync.test.ts b/src/web/src/lib/community-db/sync.test.ts
index 6ecfe615c..dd94cd710 100644
--- a/src/web/src/lib/community-db/sync.test.ts
+++ b/src/web/src/lib/community-db/sync.test.ts
@@ -1823,7 +1823,7 @@ describe("community DB sync", () => {
it("cascades roots removed by authoritative server, tree, and DM replacement", async () => {
const db = await registry()
const navigationMemory = new Map<string, string>()
- vi.stubGlobal("window", {})
+ vi.stubGlobal("window", new EventTarget())
vi.stubGlobal("localStorage", {
getItem: (key: string) => navigationMemory.get(key) ?? null,
setItem: (key: string, value: string) => navigationMemory.set(key, value),
@@ -2139,7 +2139,7 @@ describe("community DB sync", () => {
it("purges durable rows and transient owners for channel and server scopes", async () => {
const db = await registry()
const navigationMemory = new Map<string, string>()
- vi.stubGlobal("window", {})
+ vi.stubGlobal("window", new EventTarget())
vi.stubGlobal("localStorage", {
getItem: (key: string) => navigationMemory.get(key) ?? null,
setItem: (key: string, value: string) => navigationMemory.set(key, value),
diff --git a/src/web/src/lib/community/community-route.test.ts b/src/web/src/lib/community/community-route.test.ts
index 4cacb3d34..06ef7e4aa 100644
--- a/src/web/src/lib/community/community-route.test.ts
+++ b/src/web/src/lib/community/community-route.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"
import {
advanceCommunityCommittedFrame,
channelHref,
+ dmHref,
isPublishedNonStructuralCommit,
isStructuralFrameCommit,
normalizeCommunityHref,
@@ -19,6 +20,11 @@ const removedNestedChannelPath = (...segments: string[]) => (
)
describe("community route", () => {
+ it("formats the same direct-message href for preview and activation", () => {
+ expect(dmHref("dm_1")).toBe("/c/me/dm_1")
+ expect(dmHref("dm/id")).toBe("/c/me/dm%2Fid")
+ })
+
it.each([
["/c", "community-root-redirect", "neutral", "none", "route-resolution"],
["/c/me", "me-root", "list", "me", "me-root"],
diff --git a/src/web/src/lib/community/community-route.ts b/src/web/src/lib/community/community-route.ts
index 630d068e9..8f317d170 100644
--- a/src/web/src/lib/community/community-route.ts
+++ b/src/web/src/lib/community/community-route.ts
@@ -391,6 +391,10 @@ export function serverRootHref(serverId: string): string {
return `/c/channels/${serverId}`
}
+export function dmHref(dmId: string): string {
+ return `/c/me/${encodeURIComponent(dmId)}`
+}
+
export function channelHref(serverId: string, channelId: string): string {
return `${serverRootHref(serverId)}/${channelId}`
}
diff --git a/src/web/src/lib/community/eject-server.test.ts b/src/web/src/lib/community/eject-server.test.ts
index 5849e523a..d2b027755 100644
--- a/src/web/src/lib/community/eject-server.test.ts
+++ b/src/web/src/lib/community/eject-server.test.ts
@@ -296,7 +296,7 @@ describe("runAuthoritativeServerEject", () => {
it("clears a matching cold-entry route and falls back once to Machines", () => {
const storage: Record<string, string> = {}
- vi.stubGlobal("window", {})
+ vi.stubGlobal("window", new EventTarget())
vi.stubGlobal("localStorage", {
getItem: vi.fn((key: string) => storage[key] ?? null),
setItem: vi.fn((key: string, value: string) => { storage[key] = value }),
diff --git a/src/web/src/lib/community/last-channel.test.ts b/src/web/src/lib/community/last-channel.test.ts
index 20d59ba39..8531398eb 100644
--- a/src/web/src/lib/community/last-channel.test.ts
+++ b/src/web/src/lib/community/last-channel.test.ts
@@ -32,7 +32,7 @@ describe("last-channel", () => {
beforeEach(() => {
storage = {}
vi.unstubAllGlobals()
- vi.stubGlobal("window", {})
+ vi.stubGlobal("window", new EventTarget())
vi.stubGlobal("localStorage", {
getItem: vi.fn((key: string) => storage[key] ?? null),
setItem: vi.fn((key: string, value: string) => {
diff --git a/src/web/src/lib/community/last-community-route.test.ts b/src/web/src/lib/community/last-community-route.test.ts
index d7ec6f42a..13600b35a 100644
--- a/src/web/src/lib/community/last-community-route.test.ts
+++ b/src/web/src/lib/community/last-community-route.test.ts
@@ -20,7 +20,7 @@ describe("last-community-route", () => {
storage = {}
clearCommunityColdEntryAttempts()
vi.unstubAllGlobals()
- vi.stubGlobal("window", {})
+ vi.stubGlobal("window", new EventTarget())
vi.stubGlobal("localStorage", {
getItem: vi.fn((key: string) => storage[key] ?? null),
setItem: vi.fn((key: string, value: string) => { storage[key] = value }),
diff --git a/src/web/src/lib/community/last-me-location.test.ts b/src/web/src/lib/community/last-me-location.test.ts
index 70a02e502..30717c0df 100644
--- a/src/web/src/lib/community/last-me-location.test.ts
+++ b/src/web/src/lib/community/last-me-location.test.ts
@@ -14,7 +14,7 @@ describe("last-me-location", () => {
beforeEach(() => {
storage = {}
vi.unstubAllGlobals()
- vi.stubGlobal("window", {})
+ vi.stubGlobal("window", new EventTarget())
vi.stubGlobal("localStorage", {
getItem: vi.fn((key: string) => storage[key] ?? null),
setItem: vi.fn((key: string, value: string) => { storage[key] = value }),
diff --git a/src/web/src/lib/community/navigation-memory.dom.test.ts b/src/web/src/lib/community/navigation-memory.dom.test.ts
new file mode 100644
index 000000000..8e16bc4d4
--- /dev/null
+++ b/src/web/src/lib/community/navigation-memory.dom.test.ts
@@ -0,0 +1,31 @@
+import { act } from "@/test/react-dom-harness"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { clearNavigationMemory, subscribeNavigationMemory, writeNavigationMemory } from "./navigation-memory"
+
+beforeEach(() => localStorage.clear())
+
+describe("navigation memory notification", () => {
+ it("notifies once after successful changes and stops after unsubscribe", () => {
+ const notify = vi.fn(() => localStorage.getItem("nav"))
+ const unsubscribe = subscribeNavigationMemory(notify)
+ act(() => writeNavigationMemory("nav", "bots"))
+ act(() => writeNavigationMemory("nav", "bots"))
+ expect(notify.mock.results.map((result) => result.value)).toEqual(["bots"])
+ act(() => clearNavigationMemory("nav"))
+ act(() => clearNavigationMemory("nav"))
+ expect(notify.mock.results.map((result) => result.value)).toEqual(["bots", null])
+ unsubscribe()
+ act(() => writeNavigationMemory("nav", "machines"))
+ expect(notify).toHaveBeenCalledTimes(2)
+ })
+
+ it("does not notify when a write fails", () => {
+ const notify = vi.fn()
+ const unsubscribe = subscribeNavigationMemory(notify)
+ const set = vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { throw new Error("QuotaExceededError") })
+ expect(() => writeNavigationMemory("nav", "bots")).not.toThrow()
+ expect(notify).not.toHaveBeenCalled()
+ set.mockRestore()
+ unsubscribe()
+ })
+})
diff --git a/src/web/src/lib/community/navigation-memory.test.ts b/src/web/src/lib/community/navigation-memory.test.ts
index cffa3fc35..47d2ad5f6 100644
--- a/src/web/src/lib/community/navigation-memory.test.ts
+++ b/src/web/src/lib/community/navigation-memory.test.ts
@@ -1,7 +1,8 @@
-import { beforeEach, describe, expect, it, vi } from "vitest"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import {
clearNavigationMemory,
readNavigationMemory,
+ subscribeNavigationMemory,
writeNavigationMemory,
} from "./navigation-memory"
@@ -11,7 +12,7 @@ describe("navigation-memory", () => {
beforeEach(() => {
storage = {}
vi.unstubAllGlobals()
- vi.stubGlobal("window", {})
+ vi.stubGlobal("window", new EventTarget())
vi.stubGlobal("localStorage", {
getItem: vi.fn((key: string) => storage[key] ?? null),
setItem: vi.fn((key: string, value: string) => {
@@ -22,6 +23,7 @@ describe("navigation-memory", () => {
}),
})
})
+ afterEach(() => { vi.unstubAllGlobals() })
it("round-trips and clears a value", () => {
writeNavigationMemory("nav:key", "/c/me/machines")
@@ -43,8 +45,35 @@ describe("navigation-memory", () => {
it("is SSR-safe", () => {
vi.stubGlobal("window", undefined)
+ const notify = vi.fn()
+ const unsubscribe = subscribeNavigationMemory(notify)
+ expect(() => unsubscribe()).not.toThrow()
expect(readNavigationMemory("nav:key")).toBeNull()
expect(() => writeNavigationMemory("nav:key", "value")).not.toThrow()
expect(() => clearNavigationMemory("nav:key")).not.toThrow()
+ expect(notify).not.toHaveBeenCalled()
+ expect(localStorage.getItem).not.toHaveBeenCalled()
+ expect(localStorage.setItem).not.toHaveBeenCalled()
+ expect(localStorage.removeItem).not.toHaveBeenCalled()
+ })
+
+ it("notifies browser changes and native storage events only until unsubscribe", () => {
+ const notify = vi.fn()
+ const unsubscribe = subscribeNavigationMemory(notify)
+ writeNavigationMemory("nav:key", "value")
+ expect(notify).toHaveBeenCalledTimes(1)
+ writeNavigationMemory("nav:key", "value")
+ expect(notify).toHaveBeenCalledTimes(1)
+ window.dispatchEvent(new Event("storage"))
+ expect(notify).toHaveBeenCalledTimes(2)
+ clearNavigationMemory("nav:key")
+ expect(notify).toHaveBeenCalledTimes(3)
+ clearNavigationMemory("nav:key")
+ expect(notify).toHaveBeenCalledTimes(3)
+ unsubscribe()
+ writeNavigationMemory("nav:key", "after-cleanup")
+ clearNavigationMemory("nav:key")
+ window.dispatchEvent(new Event("storage"))
+ expect(notify).toHaveBeenCalledTimes(3)
})
})
diff --git a/src/web/src/lib/community/navigation-memory.ts b/src/web/src/lib/community/navigation-memory.ts
index ec83eec8a..ad27483a8 100644
--- a/src/web/src/lib/community/navigation-memory.ts
+++ b/src/web/src/lib/community/navigation-memory.ts
@@ -1,3 +1,15 @@
+const MEMORY_CHANGED = "community:navigation-memory-changed"
+
+export function subscribeNavigationMemory(notify: () => void): () => void {
+ if (typeof window === "undefined") return () => {}
+ window.addEventListener(MEMORY_CHANGED, notify)
+ window.addEventListener("storage", notify)
+ return () => {
+ window.removeEventListener(MEMORY_CHANGED, notify)
+ window.removeEventListener("storage", notify)
+ }
+}
+
export function readNavigationMemory(key: string): string | null {
if (typeof window === "undefined") return null
try {
@@ -10,17 +22,21 @@ export function readNavigationMemory(key: string): string | null {
export function writeNavigationMemory(key: string, value: string): void {
if (typeof window === "undefined") return
try {
+ if (localStorage.getItem(key) === value) return
localStorage.setItem(key, value)
} catch {
return
}
+ window.dispatchEvent(new Event(MEMORY_CHANGED))
}
export function clearNavigationMemory(key: string): void {
if (typeof window === "undefined") return
try {
+ if (localStorage.getItem(key) === null) return
localStorage.removeItem(key)
} catch {
return
}
+ window.dispatchEvent(new Event(MEMORY_CHANGED))
}
diff --git a/src/web/src/test/community-link-mock.tsx b/src/web/src/test/community-link-mock.tsx
new file mode 100644
index 000000000..115e943f2
--- /dev/null
+++ b/src/web/src/test/community-link-mock.tsx
@@ -0,0 +1,11 @@
+import type { ComponentProps } from "react"
+import type Link from "next/link"
+
+export function CommunityLinkMock({ href, prefetch, onNavigate, onClick, ...props }: ComponentProps<typeof Link>) {
+ return <a {...props} href={String(href)} data-prefetch={String(prefetch)} onClick={(event) => {
+ onClick?.(event)
+ if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey
+ || (props.target && props.target !== "_self") || props.download) return
+ onNavigate?.({ preventDefault: () => event.preventDefault() })
+ }} />
+}
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 90d84dead..d1afaa1c9 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
@@ -371,7 +371,7 @@ test("server switching exposes one target-scoped cold checkpoint and skips it wh
await expect.poll(coldC.heldNavigation).toBeGreaterThan(0)
await expect(page.getByTestId(tid.channelSidebarPending(serverC))).toBeVisible()
await expect(page.getByTestId(tid.pendingMain("server-landing"))).toBeVisible()
- await expect(page.getByRole("button", { name: channelAName, exact: true })).toHaveCount(0)
+ await expect(page.getByRole("link", { name: channelAName, exact: true })).toHaveCount(0)
await expectActiveServer(page, serverC, serverA)
expect(mutations).toEqual([])
await coldC.release()
@@ -461,7 +461,7 @@ test("server switching exposes one target-scoped cold checkpoint and skips it wh
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, exact: true })).toHaveCount(0)
+ await expect(page.getByRole("link", { name: channelAName, exact: true })).toHaveCount(0)
const mobileBox = await mobileCheckpoint.boundingBox()
expect(mobileBox).not.toBeNull()
expect(mobileBox!.width).toBeGreaterThan(300)
diff --git a/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts b/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts
index 32ca62cfa..b561fffa0 100644
--- a/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts
+++ b/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts
@@ -188,10 +188,10 @@ test("community checkpoint shows target pending for detail and keeps list surfac
await rootGate.release()
await expect(channelHeader(page, channelBName)).toBeVisible({ timeout: 30_000 })
+ const machinesGate = await holdRoute(page, "/c/me/machines")
await page.goto("/c/me/friends")
await expect(page.getByPlaceholder("Search friends")).toBeVisible({ timeout: 30_000 })
- const machinesGate = await holdRoute(page, "/c/me/machines")
- await page.getByRole("button", { name: "Machines", exact: true }).click({ noWaitAfter: true })
+ await page.getByRole("link", { name: "Machines", exact: true }).click({ noWaitAfter: true })
await expect.poll(machinesGate.held).toBeGreaterThan(0)
await expect(page.getByLabel("Resolving conversation")).toHaveCount(0)
await expect(page.getByPlaceholder("Search friends")).toBeVisible()
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 5962901ae..f212e17c2 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
@@ -106,7 +106,7 @@ test("server unread owns exact rail geometry, folder aggregation, read clear, an
const folderId = folderTestId.slice(tid.serverRailFolder("").length)
const folderIndicator = page.getByTestId(tid.serverRailFolderIndicator(folderId))
await page.mouse.move(300, 300)
- await page.getByRole("button", { name: "Home" }).focus()
+ await page.getByRole("link", { name: "Home" }).focus()
await expectIndicatorHeight(folderIndicator, 0)
await page.getByTestId(tid.serverIcon(foregroundServer)).focus()
await expectIndicatorHeight(backgroundIndicator, 10)
diff --git a/src/web/src/test/e2e-ui/42-versioned-avatar-identity.spec.ts b/src/web/src/test/e2e-ui/42-versioned-avatar-identity.spec.ts
index b8c59c8c3..e1b9390bc 100644
--- a/src/web/src/test/e2e-ui/42-versioned-avatar-identity.spec.ts
+++ b/src/web/src/test/e2e-ui/42-versioned-avatar-identity.spec.ts
@@ -180,8 +180,10 @@ test("versioned avatars converge across live, stale, reconnect, cold, and concur
await gotoAfterUserWsAuth(observer.page, "/c/me")
await expectPhoto(observer.page.getByTestId(tid.dmRow(dmId)), second.url)
await gotoAfterUserWsAuth(observer.page, "/c/me/friends")
- const friendRow = observer.page.getByText(userName("alice"), { exact: true })
- .locator("xpath=ancestor::button[1]")
+ const friendName = userName("alice").replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
+ const friendRow = observer.page.getByRole("tabpanel", { name: "All", exact: true })
+ .getByRole("button", { name: new RegExp(`^${friendName}\\s*#\\d{4,18}(?:\\s|$)`) })
+ await expect(friendRow).toHaveCount(1, { timeout: 20_000 })
await expectPhoto(friendRow, second.url)
await observer.context.setOffline(true)
diff --git a/src/web/src/test/e2e-ui/56-inbox-friend-requests.spec.ts b/src/web/src/test/e2e-ui/56-inbox-friend-requests.spec.ts
index 923a7ef82..1436960eb 100644
--- a/src/web/src/test/e2e-ui/56-inbox-friend-requests.spec.ts
+++ b/src/web/src/test/e2e-ui/56-inbox-friend-requests.spec.ts
@@ -247,7 +247,7 @@ test.describe.serial("actionable Inbox friend requests", () => {
await expectNoInboxUnreadCount(bob.page)
await bob.page.getByTestId(tid.inboxTrigger).click()
- await bob.page.getByRole("button", { name: "Friends", exact: true }).click()
+ await bob.page.getByRole("link", { name: "Friends", exact: true }).click()
const accepted = await bob.page.request.get("/api/community/friends/accepted")
expect(accepted.ok()).toBe(true)
const acceptedBody = await accepted.json() as { friends: Array<{ userId: string; name: string }> }
diff --git a/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts b/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts
index 5e1f6d1c5..603be9d8e 100644
--- a/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts
+++ b/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts
@@ -855,7 +855,7 @@ test.describe.serial("desktop default User Bar width", () => {
await saved.page.setViewportSize({ width: 390, height: 844 })
await installLayoutState(saved.page, seededLayout)
await gotoAfterUserWsAuth(saved.page, "/c/me")
- await expect(saved.page.getByRole("button", { name: "Friends", exact: true })).toBeVisible()
+ await expect(saved.page.getByRole("link", { name: "Friends", exact: true })).toBeVisible()
await saved.page.setViewportSize({ width: 639, height: 844 })
await expect(shellPanel(saved.page, "sidebar")).toBeVisible()
const firstSampleCursor = await saved.page.evaluate(() => (
@@ -883,7 +883,7 @@ test.describe.serial("desktop default User Bar width", () => {
await saved.page.setViewportSize({ width: 639, height: 844 })
await expect(shellPanel(saved.page, "sidebar")).toBeHidden()
await saved.page.goto("/c/me")
- await expect(saved.page.getByRole("button", { name: "Friends", exact: true })).toBeVisible()
+ await expect(saved.page.getByRole("link", { name: "Friends", exact: true })).toBeVisible()
await expect(shellPanel(saved.page, "sidebar")).toBeVisible()
const secondSampleCursor = await saved.page.evaluate(() => (
Reflect.get(window, "__desktopWidthSamples") as LayoutSample[]
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 7fd48b3b3..2a16bc323 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
@@ -480,7 +480,7 @@ export async function seedGeometryRoutes(serverIds: string[]): Promise<Omit<Matr
.getByTestId(tid.threadSplitPanel)
.getByTestId(tid.composerInput)
return [
- { name: "me-list", pathname: "/c/me", mobileRail: true, ready: (page) => page.getByRole("button", { name: "Friends", exact: true }) },
+ { name: "me-list", pathname: "/c/me", mobileRail: true, ready: (page) => page.getByRole("link", { name: "Friends", exact: true }) },
{ name: "friends", pathname: "/c/me/friends", ready: (page) => page.getByPlaceholder("Search friends") },
{ name: "machines", pathname: "/c/me/machines", ready: (page) => page.getByTestId(tid.machinePairOpen) },
{ name: "bots", pathname: "/c/me/bots", ready: (page) => page.getByRole("button", { name: /Create a bot|Connect a machine/ }) },
@@ -559,7 +559,7 @@ export async function runAndroidLoadingGeometry(asUser: CommunityAsUser, testInf
communityReads.release()
await expect(
pathname === "/c/me"
- ? page.getByRole("button", { name: "Friends", exact: true })
+ ? page.getByRole("link", { name: "Friends", exact: true })
: page.getByTestId(tid.machinePairOpen),
).toBeVisible({ timeout: 30_000 })
if (pendingHeading) {