Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
perf(web): speed up community navigation (#470)
Gener0311b46366e6
diff --git a/src/shared/src/db/queries/community/channel.ts b/src/shared/src/db/queries/community/channel.tsindex b59a401ab..531efdcc4 100644--- a/src/shared/src/db/queries/community/channel.ts+++ b/src/shared/src/db/queries/community/channel.ts@@ -1,8 +1,9 @@-import { eq, and, asc, desc, isNull, max, inArray, count } from "drizzle-orm";+import { eq, and, asc, desc, isNotNull, isNull, max, inArray, count, or, sql } from "drizzle-orm";import {communityChannel,communityCategory,communityChannelMember,+ communityServer,communityServerMember,communityMessage,} from "../../community-schema";@@ -774,6 +775,94 @@ export async function listServerChannelsForViewer(return rows.filter((r) => visibleSet.has(r.id));}+export type ChannelRefDirectoryRow = {+ serverId: string;+ channelId: string;+ channelName: string;+};++export function groupChannelRefDirectoryRows(+ servers: Array<{ id: string; name: string; discriminator: string }>,+ channels: ChannelRefDirectoryRow[]+) {+ const channelsByServer = new Map<string, Array<{ id: string; name: string }>>();+ for (const channel of channels) {+ const current = channelsByServer.get(channel.serverId) ?? [];+ current.push({ id: channel.channelId, name: channel.channelName });+ channelsByServer.set(channel.serverId, current);+ }+ return servers.map((server) => ({+ id: server.id,+ name: server.name,+ discriminator: server.discriminator,+ channels: channelsByServer.get(server.id) ?? [],+ }));+}++export async function listChannelRefDirectoryForUser(db: Database, userId: string) {+ const [servers, channels] = await Promise.all([+ db+ .select({+ id: communityServer.id,+ name: communityServer.name,+ discriminator: communityServer.discriminator,+ })+ .from(communityServer)+ .innerJoin(+ communityServerMember,+ and(+ eq(communityServerMember.serverId, communityServer.id),+ eq(communityServerMember.userId, userId)+ )+ )+ .orderBy(asc(communityServerMember.railOrder), asc(communityServer.id)),+ db+ .select({+ serverId: communityChannel.serverId,+ channelId: communityChannel.id,+ channelName: communityChannel.name,+ })+ .from(communityChannel)+ .innerJoin(+ communityServerMember,+ and(+ eq(communityServerMember.serverId, communityChannel.serverId),+ eq(communityServerMember.userId, userId)+ )+ )+ .leftJoin(communityCategory, eq(communityCategory.id, communityChannel.categoryId))+ .leftJoin(+ communityChannelMember,+ and(+ eq(communityChannelMember.channelId, communityChannel.id),+ eq(communityChannelMember.userId, userId),+ eq(communityChannelMember.relation, "access")+ )+ )+ .where(+ and(+ isNull(communityChannel.parentChannelId),+ or(+ isNull(communityChannel.categoryId),+ eq(communityCategory.private, 0),+ eq(communityChannel.creatorId, userId),+ isNotNull(communityChannelMember.id)+ )+ )+ )+ .orderBy(+ asc(communityServerMember.railOrder),+ asc(communityServerMember.serverId),+ sql`${communityChannel.categoryId} IS NULL`,+ asc(communityCategory.position),+ asc(communityCategory.id),+ asc(communityChannel.position),+ asc(communityChannel.id)+ ),+ ]);+ return groupChannelRefDirectoryRows(servers, channels);+}+// Shared visibility computation for the nested-membership model. Assembles the// set of channel ids a viewer may see across the given servers, applying:// - top-level TEXT channel (private) → creator OR own member row.diff --git a/src/shared/test/queries/community-channel-directory.test.ts b/src/shared/test/queries/community-channel-directory.test.tsnew file mode 100644index 000000000..f479631db--- /dev/null+++ b/src/shared/test/queries/community-channel-directory.test.ts@@ -0,0 +1,136 @@+import Sqlite from "better-sqlite3";+import { drizzle } from "drizzle-orm/better-sqlite3";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import type { Database } from "../../src/db";+import {+ groupChannelRefDirectoryRows,+ listChannelRefDirectoryForUser,+} from "../../src/db/queries/community/channel";++describe("groupChannelRefDirectoryRows", () => {+ it("preserves rail order and includes member servers with no visible channels", () => {+ const result = groupChannelRefDirectoryRows(+ [+ { id: "server_2", name: "Second", discriminator: "0002" },+ { id: "server_1", name: "First", discriminator: "0001" },+ ],+ [+ {+ serverId: "server_1",+ channelId: "channel_1",+ channelName: "general",+ },+ {+ serverId: "server_1",+ channelId: "channel_2",+ channelName: "random",+ },+ ]+ );++ expect(result).toEqual([+ { id: "server_2", name: "Second", discriminator: "0002", channels: [] },+ {+ id: "server_1",+ name: "First",+ discriminator: "0001",+ channels: [+ { id: "channel_1", name: "general" },+ { id: "channel_2", name: "random" },+ ],+ },+ ]);+ });+});++describe("listChannelRefDirectoryForUser", () => {+ let sqlite: Sqlite.Database;+ let db: Database;++ beforeEach(() => {+ sqlite = new Sqlite(":memory:");+ sqlite.exec(`+ CREATE TABLE community_server (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ discriminator TEXT NOT NULL+ );+ CREATE TABLE community_server_member (+ id TEXT PRIMARY KEY,+ server_id TEXT NOT NULL,+ user_id TEXT NOT NULL,+ rail_order INTEGER+ );+ CREATE TABLE community_category (+ id TEXT PRIMARY KEY,+ server_id TEXT NOT NULL,+ position INTEGER,+ private INTEGER+ );+ CREATE TABLE community_channel (+ id TEXT PRIMARY KEY,+ server_id TEXT,+ category_id TEXT,+ name TEXT,+ position INTEGER,+ parent_channel_id TEXT,+ creator_id TEXT+ );+ CREATE TABLE community_channel_member (+ id TEXT PRIMARY KEY,+ channel_id TEXT NOT NULL,+ user_id TEXT NOT NULL,+ relation TEXT NOT NULL+ );++ INSERT INTO community_server (id, name, discriminator) VALUES+ ('s1', 'First', '0001'),+ ('s2', 'Second', '0002'),+ ('s3', 'Not joined', '0003');+ INSERT INTO community_server_member (id, server_id, user_id, rail_order) VALUES+ ('sm2', 's2', 'viewer', 0),+ ('sm1', 's1', 'viewer', 1),+ ('sm3', 's3', 'someone_else', 0);+ INSERT INTO community_category (id, server_id, position, private) VALUES+ ('public', 's1', 0, 0),+ ('private', 's1', 1, 1),+ ('private_s2', 's2', 0, 1);+ INSERT INTO community_channel+ (id, server_id, category_id, name, position, parent_channel_id, creator_id)+ VALUES+ ('uncategorized', 's1', NULL, 'uncategorized', 0, NULL, 'other'),+ ('public_channel', 's1', 'public', 'public-channel', 1, NULL, 'other'),+ ('private_owned', 's1', 'private', 'private-owned', 2, NULL, 'viewer'),+ ('private_access', 's1', 'private', 'private-access', 3, NULL, 'other'),+ ('private_hidden', 's1', 'private', 'private-hidden', 4, NULL, 'other'),+ ('child_thread', 's1', 'public', 'child-thread', 5, 'public_channel', 'viewer'),+ ('s2_hidden', 's2', 'private_s2', 'hidden', 0, NULL, 'other'),+ ('nonmember_public', 's3', NULL, 'nonmember-public', 0, NULL, 'other'),+ ('dm', NULL, NULL, NULL, 0, NULL, 'viewer');+ INSERT INTO community_channel_member (id, channel_id, user_id, relation) VALUES+ ('cm_access', 'private_access', 'viewer', 'access'),+ ('cm_notify', 'private_hidden', 'viewer', 'notify'),+ ('cm_dm', 'dm', 'viewer', 'access');+ `);+ db = drizzle(sqlite) as unknown as Database;+ });++ afterEach(() => sqlite.close());++ it("returns one rail-ordered directory scoped to member-visible top-level channels", async () => {+ await expect(listChannelRefDirectoryForUser(db, "viewer")).resolves.toEqual([+ { id: "s2", name: "Second", discriminator: "0002", channels: [] },+ {+ id: "s1",+ name: "First",+ discriminator: "0001",+ channels: [+ { id: "public_channel", name: "public-channel" },+ { id: "private_owned", name: "private-owned" },+ { id: "private_access", name: "private-access" },+ { id: "uncategorized", name: "uncategorized" },+ ],+ },+ ]);+ });+});diff --git a/src/shared/test/queries/community-channel-threads.test.ts b/src/shared/test/queries/community-channel-threads.test.tsindex c1c7e4009..90979bbc3 100644--- a/src/shared/test/queries/community-channel-threads.test.ts+++ b/src/shared/test/queries/community-channel-threads.test.ts@@ -1,4 +1,7 @@-import { describe, it, expect, vi } from "vitest";+import Sqlite from "better-sqlite3";+import { drizzle } from "drizzle-orm/better-sqlite3";+import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";+import type { Database } from "../../src/db";import {createThreadChannel,} from "../../src/db/queries/community/channel";@@ -115,3 +118,61 @@ describe("createThreadChannel", () => {expect(db.__insertValues).not.toHaveBeenCalled();});});++describe("createThreadChannel against real SQLite", () => {+ let sqlite: Sqlite.Database;+ let db: Database;++ beforeEach(() => {+ sqlite = new Sqlite(":memory:");+ sqlite.exec(`+ CREATE TABLE community_channel (+ id TEXT PRIMARY KEY,+ server_id TEXT,+ category_id TEXT,+ name TEXT,+ type TEXT NOT NULL DEFAULT 'text',+ topic TEXT DEFAULT '',+ position INTEGER DEFAULT 0,+ parent_channel_id TEXT,+ creator_id TEXT,+ message_count INTEGER DEFAULT 0,+ archived INTEGER DEFAULT 0,+ parent_message_id TEXT,+ last_message_at TEXT,+ created_at TEXT NOT NULL+ );+ CREATE TABLE community_message (+ id TEXT PRIMARY KEY,+ content TEXT NOT NULL+ );+ INSERT INTO community_channel+ (id, server_id, name, type, created_at)+ VALUES+ ('parent_1', 'server_1', 'general', 'text', '2026-08-14T00:00:00.000Z');+ INSERT INTO community_message (id, content)+ VALUES ('message_1', 'Thread from a real query');+ `);+ db = drizzle(sqlite) as unknown as Database;+ });++ afterEach(() => sqlite.close());++ it("projects the parent server from the joined query table and creates the child", async () => {+ const created = await createThreadChannel(+ db,+ "parent_1",+ "message_1",+ "creator_1",+ );++ expect(created).toMatchObject({+ serverId: "server_1",+ parentChannelId: "parent_1",+ parentMessageId: "message_1",+ creatorId: "creator_1",+ type: "thread",+ name: "Thread from a real query",+ });+ });+});diff --git a/src/web/package.json b/src/web/package.jsonindex d78dec36b..b86f37f62 100644--- a/src/web/package.json+++ b/src/web/package.json@@ -20,7 +20,7 @@"test:e2e-ui:headed": "playwright test --headed","knip": "knip","seed:stress": "tsx scripts/seed-stress.ts",- "perf:switch": "playwright test --config playwright.perf.config.ts; tsx scripts/perf-report.ts",+ "perf:switch": "tsx scripts/perf-report.ts --clear && playwright test --config playwright.perf.config.ts && tsx scripts/perf-report.ts","typecheck": "tsc --noEmit","seo:check": "lhci autorun --config=lighthouserc.json && node scripts/print-lighthouse-scores.mjs"},diff --git a/src/web/scripts/perf-report.test.ts b/src/web/scripts/perf-report.test.tsindex d19555d41..c5a828b85 100644--- a/src/web/scripts/perf-report.test.ts+++ b/src/web/scripts/perf-report.test.ts@@ -1,5 +1,8 @@+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"+import { tmpdir } from "node:os"+import { join } from "node:path"import { describe, it, expect } from "vitest"-import { analyzeSwitch, renderReport } from "./perf-report"+import { analyzeSwitch, clearPerfArtifacts, renderReport } from "./perf-report"import type { CapturedSwitch, CaptureFile } from "../src/test/e2e-ui/perf/perf-capture-types"function baseSwitch(over: Partial<CapturedSwitch> = {}): CapturedSwitch {@@ -168,3 +171,19 @@ describe("renderReport — cache-state split", () => {expect(md).toMatch(/PERCEIVED/)})})++describe("clearPerfArtifacts", () => {+ it("removes both stale capture and report files", () => {+ const dir = mkdtempSync(join(tmpdir(), "alook-perf-"))+ const capture = join(dir, "switch-events.json")+ const report = join(dir, "switch-report.md")+ writeFileSync(capture, "stale")+ writeFileSync(report, "stale")++ clearPerfArtifacts(capture, report)++ expect(existsSync(capture)).toBe(false)+ expect(existsSync(report)).toBe(false)+ rmSync(dir, { recursive: true, force: true })+ })+})diff --git a/src/web/scripts/perf-report.ts b/src/web/scripts/perf-report.tsindex 5adbcc007..2a94848a2 100644--- a/src/web/scripts/perf-report.ts+++ b/src/web/scripts/perf-report.ts@@ -5,7 +5,7 @@* The correlation core (`analyzeSwitch`, `renderReport`) is pure and exported* for unit testing — no filesystem, no browser.*/-import { readFileSync, writeFileSync } from "node:fs"+import { readFileSync, rmSync, writeFileSync } from "node:fs"import { resolve } from "node:path"import type {CaptureFile,@@ -17,6 +17,11 @@ const ARTIFACTS_DIR = resolve(import.meta.dirname, "..", "perf-artifacts")const CAPTURE_IN = resolve(ARTIFACTS_DIR, "switch-events.json")const REPORT_OUT = resolve(ARTIFACTS_DIR, "switch-report.md")+export function clearPerfArtifacts(capturePath = CAPTURE_IN, reportPath = REPORT_OUT): void {+ rmSync(capturePath, { force: true })+ rmSync(reportPath, { force: true })+}+export interface SwitchAnalysis {kind: stringtargetId: string@@ -237,6 +242,10 @@ export function renderReport(file: CaptureFile): string {}function main(): void {+ if (process.argv.includes("--clear")) {+ clearPerfArtifacts()+ return+ }let file: CaptureFiletry {file = JSON.parse(readFileSync(CAPTURE_IN, "utf8")) as CaptureFilediff --git a/src/web/scripts/seed-stress.test.ts b/src/web/scripts/seed-stress.test.tsindex cc2ddd1f1..d4bd9621e 100644--- a/src/web/scripts/seed-stress.test.ts+++ b/src/web/scripts/seed-stress.test.ts@@ -133,8 +133,8 @@ function installFetchMock(handlers: {if (url.endsWith("/api/community/servers") && method === "POST") {return jsonRes({ server: { id: "new-server" } })}- if (/\/api\/community\/servers\/[^/]+$/.test(url) && method === "GET") {- return jsonRes({ categories: [{ channels: existingChannels }] })+ if (/\/api\/community\/servers\/[^/]+\/channels$/.test(url) && method === "GET") {+ return jsonRes({ channels: existingChannels })}if (/\/channels$/.test(url) && method === "POST") {return jsonRes({ channel: { id: "new-channel" } })@@ -180,6 +180,12 @@ describe("runSeedStress — idempotency", () => {)expect(serverPosts).toHaveLength(0)expect(manifest.servers[0].id).toBe("srv-existing")+ expect(calls).toContainEqual({+ url: "http://localhost:3000/api/community/servers/srv-existing/channels",+ method: "GET",+ body: undefined,+ })+ expect(calls.some((call) => call.url.endsWith("/api/community/servers/srv-existing"))).toBe(false)})it("seeds ZERO messages when the channel already meets the target", async () => {diff --git a/src/web/scripts/seed-stress.ts b/src/web/scripts/seed-stress.tsindex b1a680f68..eb5f544ed 100644--- a/src/web/scripts/seed-stress.ts+++ b/src/web/scripts/seed-stress.ts@@ -285,10 +285,10 @@ async function ensureServer(client: SeedClient, existing: ServerRow[], name: str}async function listChannels(client: SeedClient, serverId: string): Promise<ChannelRow[]> {- const detail = await client.get<{- categories: Array<{ channels: ChannelRow[] }>- }>(`/api/community/servers/${serverId}`)- return detail.categories.flatMap((c) => c.channels)+ const data = await client.get<{ channels: ChannelRow[] }>(+ `/api/community/servers/${serverId}/channels`,+ )+ return data.channels}async function ensureChannel(diff --git a/src/web/src/app/api/community/users/me/channel-directory/route.test.ts b/src/web/src/app/api/community/users/me/channel-directory/route.test.tsnew file mode 100644index 000000000..8ecb9814e--- /dev/null+++ b/src/web/src/app/api/community/users/me/channel-directory/route.test.ts@@ -0,0 +1,58 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"++const listChannelRefDirectoryForUser = vi.fn()+const db = { scoped: true }++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => db) }))++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ communityChannel: {+ listChannelRefDirectoryForUser: (...args: unknown[]) =>+ listChannelRefDirectoryForUser(...args),+ },+ },+ }+})++vi.mock("@/lib/middleware/auth", () => ({+ withAuth: vi.fn((handler: any) => async (req: any) =>+ handler(req, { env: { DB: {} }, userId: "viewer_1", email: "[email protected]" }),+ ),+}))++vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server")+ return { writeJSON: (data: unknown) => NextResponse.json(data) }+})++import { GET } from "./route"++describe("GET /api/community/users/me/channel-directory", () => {+ beforeEach(() => vi.clearAllMocks())++ it("returns the member-scoped directory without a per-server request loop", async () => {+ const directory = [+ {+ id: "server_1",+ name: "Studio",+ discriminator: "0042",+ channels: [{ id: "channel_1", name: "general" }],+ },+ ]+ listChannelRefDirectoryForUser.mockResolvedValue(directory)++ const response = await GET(+ new NextRequest("http://localhost/api/community/users/me/channel-directory"),+ )++ expect(response.status).toBe(200)+ expect(await response.json()).toEqual({ directory })+ expect(listChannelRefDirectoryForUser).toHaveBeenCalledWith(db, "viewer_1")+ expect(listChannelRefDirectoryForUser).toHaveBeenCalledTimes(1)+ })+})diff --git a/src/web/src/app/api/community/users/me/channel-directory/route.ts b/src/web/src/app/api/community/users/me/channel-directory/route.tsnew file mode 100644index 000000000..12adca965--- /dev/null+++ b/src/web/src/app/api/community/users/me/channel-directory/route.ts@@ -0,0 +1,13 @@+import { queries } from "@alook/shared"+import { getDb } from "@/lib/db"+import { withAuth } from "@/lib/middleware/auth"+import { writeJSON } from "@/lib/middleware/helpers"++export const GET = withAuth(async (_req, ctx) => {+ const db = getDb(ctx.env.DB)+ const directory = await queries.communityChannel.listChannelRefDirectoryForUser(+ db,+ ctx.userId,+ )+ return writeJSON({ directory })+})diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsxindex 3e80581ac..f8c00d71a 100644--- a/src/web/src/app/c/channels/layout.tsx+++ b/src/web/src/app/c/channels/layout.tsx@@ -73,6 +73,9 @@ export default function ServerLayout({ children }: { children: ReactNode }) {const router = useRouter()const bp = useBreakpoint()const queryClient = useQueryClient()+ const cancelPendingNavigation = useCallback(() => {+ useCommunityStore.getState().uiHandlers.cancelPendingNavigation?.()+ }, [])const currentUser = useCurrentUser()const { server: currentServer } = useServer(serverId)const membersHook = useServerMembers(serverId)@@ -176,9 +179,12 @@ export default function ServerLayout({ children }: { children: ReactNode }) {consumeVoluntaryLeave,clearLastChannel,toast,- replace: (destination) => router.replace(destination),+ replace: (destination) => {+ cancelPendingNavigation()+ router.replace(destination)+ },})- }, [serverId, serversList.isSuccess, serversList.isFetching, serversList.servers, router])+ }, [cancelPendingNavigation, serverId, serversList.isSuccess, serversList.isFetching, serversList.servers, router])// Reset the guard when the URL changes to a NEW server id — otherwise// navigating server → dangling-server → server would leave the ref// latched and skip the eject.@@ -250,10 +256,11 @@ export default function ServerLayout({ children }: { children: ReactNode }) {!hasChannel && !!currentServer && currentServer.categories.some((c) => c.channels.length > 0)if (stillRedirecting) return+ cancelPendingNavigation()router.replace(hasChannel ? `/c/channels/${serverId}/${params.channelId}` : `/c/channels/${serverId}`,)- }, [searchParams, serverId, router, hasChannel, currentServer, params.channelId])+ }, [cancelPendingNavigation, searchParams, serverId, router, hasChannel, currentServer, params.channelId])const categories = useMemo(() => (currentServer?.categories ?? []).map((category) => ({...category,@@ -267,8 +274,9 @@ export default function ServerLayout({ children }: { children: ReactNode }) {const goHome = useCallback(() => {setMobileZone("nav")+ cancelPendingNavigation()router.push(pickMeLandingLocation(getLastMeLeaf()))- }, [router])+ }, [cancelPendingNavigation, router])const goServer = useCallback(() => { setMobileZone("nav") }, [])const setActiveChannel = useCallback((id: string) => {@@ -301,6 +309,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {// before the user even navigates away — `useChannelTree`'s metadata merge// trusts the cache unconditionally, so both directions must write to it.markSwitch("channel", id)+ cancelPendingNavigation()router.push(`/c/channels/${serverId}/${id}`)channelTree.markRead(id)const hasChildFallback = setForumSidebarParentUnreadBase(@@ -316,15 +325,21 @@ export default function ServerLayout({ children }: { children: ReactNode }) {)}if (bp === "mobile") setMobileZone("messages")- }, [router, serverId, channelTree, bp, queryClient])+ }, [bp, cancelPendingNavigation, channelTree, queryClient, router, serverId])const setActiveForumThread = useCallback((id: string) => {markSwitch("channel", id)+ cancelPendingNavigation()router.push(`/c/channels/${serverId}/${id}`)removeForumSidebarUnreadChild(queryClient, serverId, id)patchForumSidebarUnreadExact(queryClient, serverId, id, false)if (bp === "mobile") setMobileZone("messages")- }, [bp, queryClient, router, serverId])+ }, [bp, cancelPendingNavigation, queryClient, router, serverId])++ const prefetchChannel = useCallback(+ (id: string) => router.prefetch(`/c/channels/${serverId}/${id}`),+ [router, serverId],+ )const onSidebarOpenSettings = useCallback((section?: SettingsSection) => {if (section) setSettingsSection(section)@@ -367,10 +382,14 @@ export default function ServerLayout({ children }: { children: ReactNode }) {method: "PATCH",body: JSON.stringify({ name }),})+ void queryClient.invalidateQueries({+ queryKey: communityKeys.channelRefDirectory(),+ exact: true,+ })} catch (e) {toastApiError(e, "Failed to rename channel")}- }, [])+ }, [queryClient])const onDeleteChannelInSidebar = useCallback((channelId: string) => {deleteChannelMut.mutate({ serverId, channelId }, { onError: (e) => toastApiError(e, "Failed to delete channel") })}, [deleteChannelMut, serverId])@@ -402,6 +421,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {currentUserId: currentUser.id,loading: !currentServer,setActiveChannel,+ prefetchChannel,forumThreadsByParent,activeThreadId: activeForumThreadId,onSelectForumThread: setActiveForumThread,@@ -423,7 +443,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {onInvitePopoverOpenChange: setInvitePopoverOpen,}), [channelTree, currentServer, currentChannelMeta?.parentChannelId,- currentChannelId, isAdmin, currentUser.id, setActiveChannel,+ currentChannelId, isAdmin, currentUser.id, setActiveChannel, prefetchChannel,forumThreadsByParent, activeForumThreadId, setActiveForumThread,onSidebarOpenSettings, onBlockedCreate, mutedChannels,onCreateChannelInSidebar, onCreateCategoryInSidebar, onRenameChannel,@@ -485,6 +505,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {onSuccess: () => {toast("Server deleted")useCommunityStore.getState().setCurrentServerId(null)+ cancelPendingNavigation()router.push("/c/me")},onError: (e) => toastApiError(e, "Failed to delete server"),diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsxindex fb4587de5..9fca16697 100644--- a/src/web/src/app/c/me/[dmId]/page.tsx+++ b/src/web/src/app/c/me/[dmId]/page.tsx@@ -124,7 +124,8 @@ function DmView() {// DM composer has no "current server" — flatten every member server's// channels into one cross-server candidate list so a `/`-ref can be// dropped into a DM (see plan community-channel-ref.md §6).- const { directory: channelRefDirectory } = useChannelRefDirectory()+ const [channelRefDirectoryEnabled, setChannelRefDirectoryEnabled] = useState(false)+ const { directory: channelRefDirectory } = useChannelRefDirectory(channelRefDirectoryEnabled)const channelRefCandidates = useMemo(() =>channelRefDirectory.flatMap((s) =>@@ -428,6 +429,7 @@ function DmView() {// honest without shimming friends into a member shape.members={[]}channelRefCandidates={channelRefCandidates}+ onChannelRefIntent={() => setChannelRefDirectoryEnabled(true)}onAcceptSend={acceptDmSend}onTyping={handleTyping}replyingTo={replyTo?.authorName}diff --git a/src/web/src/app/c/me/layout.tsx b/src/web/src/app/c/me/layout.tsxindex 3fc33b943..7aba31cd6 100644--- a/src/web/src/app/c/me/layout.tsx+++ b/src/web/src/app/c/me/layout.tsx@@ -43,6 +43,9 @@ export default function MeLayout({ children }: { children: ReactNode }) {const { blocked } = useFriends()const currentChannelId = useCurrentChannelId()const queryClient = useQueryClient()+ const cancelPendingNavigation = useCallback(() => {+ useCommunityStore.getState().uiHandlers.cancelPendingNavigation?.()+ }, [])// Clear the active server when entering the DM home. `currentServerId ===// null` is the canonical "no server focused" state — no need for a "@me"@@ -82,8 +85,9 @@ export default function MeLayout({ children }: { children: ReactNode }) {}if (meLocationStatus !== "stale") returnif (getLastMeLeaf() === meLeafFromPathname(pathname)) clearLastMeLocation()+ cancelPendingNavigation()router.replace(ME_ROOT)- }, [meLocationStatus, pathname, router])+ }, [cancelPendingNavigation, meLocationStatus, pathname, router])const [mobileZone, setMobileZone] = useState<MobileZone>(() => (hasDm ? "messages" : "nav"))@@ -108,32 +112,42 @@ export default function MeLayout({ children }: { children: ReactNode }) {? { ...prev, conversations: prev.conversations.map((d) => (d.id === id ? { ...d, unread: false } : d)) }: prev,)+ cancelPendingNavigation()router.push(`/c/me/${id}`)if (bp === "mobile") setMobileZone("messages")- }, [queryClient, router, bp])+ }, [bp, cancelPendingNavigation, queryClient, router])const onShowFriends = useCallback(() => {useCommunityStore.getState().setCurrentChannelId(null)+ cancelPendingNavigation()router.push("/c/me")if (bp === "mobile") setMobileZone("messages")- }, [router, bp])+ }, [bp, cancelPendingNavigation, router])const onShowMachines = useCallback(() => {useCommunityStore.getState().setCurrentChannelId(null)+ cancelPendingNavigation()router.push("/c/me/machines")if (bp === "mobile") setMobileZone("messages")- }, [router, bp])+ }, [bp, cancelPendingNavigation, router])const onShowBots = useCallback(() => {useCommunityStore.getState().setCurrentChannelId(null)+ cancelPendingNavigation()router.push("/c/me/bots")if (bp === "mobile") setMobileZone("messages")- }, [router, bp])+ }, [bp, cancelPendingNavigation, router])++ const prefetchDm = useCallback((id: string) => router.prefetch(`/c/me/${id}`), [router])+ const prefetchFriends = useCallback(() => router.prefetch("/c/me"), [router])+ const prefetchMachines = useCallback(() => router.prefetch("/c/me/machines"), [router])+ const prefetchBots = useCallback(() => router.prefetch("/c/me/bots"), [router])const goHome = useCallback(() => {setMobileZone("nav")+ cancelPendingNavigation()router.push(pickMeLandingLocation(getLastMeLeaf()))- }, [router])+ }, [cancelPendingNavigation, router])const goServer = useCallback(() => { setMobileZone("nav") }, [])const blockedUserIds = useMemo(@@ -148,14 +162,18 @@ export default function MeLayout({ children }: { children: ReactNode }) {blockedUserIds={blockedUserIds}loading={dmsLoading}onPickDm={enterDm}+ onPrefetchDm={prefetchDm}onShowFriends={onShowFriends}+ onPrefetchFriends={prefetchFriends}onShowMachines={onShowMachines}+ onPrefetchMachines={prefetchMachines}onShowBots={onShowBots}+ onPrefetchBots={prefetchBots}friendsActive={friendsActive}machinesActive={machinesActive}botsActive={botsActive}/>- ), [dms, currentChannelId, dmsLoading, blockedUserIds, enterDm, onShowFriends, onShowMachines, onShowBots, friendsActive, machinesActive, botsActive])+ ), [dms, currentChannelId, dmsLoading, blockedUserIds, enterDm, prefetchDm, onShowFriends, prefetchFriends, onShowMachines, prefetchMachines, onShowBots, prefetchBots, friendsActive, machinesActive, botsActive])return (<ShellFramediff --git a/src/web/src/components/community/channel-sidebar.tsx b/src/web/src/components/community/channel-sidebar.tsxindex 6a95d6e0a..ff04f7e87 100644--- a/src/web/src/components/community/channel-sidebar.tsx+++ b/src/web/src/components/community/channel-sidebar.tsx@@ -36,7 +36,7 @@ type Dialog =// right-click) creates; channels right-click to edit/delete. A private category only// lets admins create channels — non-admins are blocked via onBlockedCreate.export const ChannelSidebar = memo(function ChannelSidebar({- tree, serverName, activeChannel, setActiveChannel, noHeader, onOpenSettings,+ tree, serverName, activeChannel, setActiveChannel, prefetchChannel, noHeader, onOpenSettings,isAdmin = true, currentUserId, onBlockedCreate, mutedChannels, loading,onCreateChannel, onCreateCategory, onDeleteChannel, onDeleteCategory,onUpdateCategory, onRenameChannel, onReorderCategories, onReorderChannels,@@ -49,6 +49,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({serverIcon?: string | nullactiveChannel: stringsetActiveChannel: (id: string) => void+ prefetchChannel?: (id: string) => voidnoHeader?: booleanonOpenSettings?: (section?: SettingsSection) => voidisAdmin?: boolean@@ -180,6 +181,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({active={thread.id === activeThreadId}muted={!!mutedChannels?.[parentId]}onClick={() => onSelectForumThread?.(thread.id)}+ onPrefetch={() => prefetchChannel?.(thread.id)}/>))}</div>@@ -230,6 +232,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({active={ch.id === activeChannel && !hasActiveSidebarThread}canReorder={isAdmin}onClick={() => setActiveChannel(ch.id)}+ onPrefetch={() => prefetchChannel?.(ch.id)}onEdit={isAdmin ? () => setDialog({ kind: "edit-channel", id: ch.id, categoryId: noneCatId, name: ch.name, type: ch.type ?? "text" }) : undefined}onDelete={isAdmin ? () => { removeChannel(ch.id); onDeleteChannel?.(ch.id) } : undefined}/>@@ -270,6 +273,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({active={ch.id === activeChannel && !hasActiveSidebarThread}canReorder={isAdmin}onClick={() => setActiveChannel(ch.id)}+ onPrefetch={() => prefetchChannel?.(ch.id)}onEdit={canManageChannel ? () => setDialog({ kind: "edit-channel", id: ch.id, categoryId: id, name: ch.name, type: ch.type ?? "text" }) : undefined}onDelete={canManageChannel ? () => { removeChannel(ch.id); onDeleteChannel?.(ch.id) } : undefined}onManageMembers={(catPrivate[id] && canManageChannel) ? () => setDialog({ kind: "manage-members", channelId: ch.id, channelName: ch.name }) : undefined}@@ -396,11 +400,13 @@ function ForumSidebarThreadRow({active,muted,onClick,+ onPrefetch,}: {thread: ForumSidebarThreadactive: booleanmuted: booleanonClick: () => void+ onPrefetch?: () => void}) {return (<div className="relative h-7">@@ -409,6 +415,8 @@ function ForumSidebarThreadRow({data-testid={tid.forumSidebarThread(thread.id)}aria-current={active ? "page" : undefined}onClick={onClick}+ onPointerEnter={onPrefetch}+ onFocus={onPrefetch}onContextMenu={(event) => {event.preventDefault()event.stopPropagation()diff --git a/src/web/src/components/community/composer.tsx b/src/web/src/components/community/composer.tsxindex 0ef47c2b7..e61571bc8 100644--- a/src/web/src/components/community/composer.tsx+++ b/src/web/src/components/community/composer.tsx@@ -103,6 +103,7 @@ type ComposerBaseProps = {// for DM composers. Always provided by the caller — empty array is fine,// the popup just shows nothing on `/`.channelRefCandidates?: ChannelRefCandidate[]+ onChannelRefIntent?: () => voidonTyping?: () => void// when set, shows a "Replying to X" bar above the inputreplyingTo?: string@@ -166,6 +167,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compomembers,onSearchMembers,channelRefCandidates = [],+ onChannelRefIntent,sendContract,onAcceptSend,onDeferredSubmit,@@ -262,14 +264,17 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo// Same "built once, refs read at runtime" pattern as the mention extension.const channelRefCandidatesRef = useRef(channelRefCandidates)+ const onChannelRefIntentRef = useRef(onChannelRefIntent)const channelRefQueryRef = useRef<string>("")useEffect(() => { channelRefCandidatesRef.current = channelRefCandidates }, [channelRefCandidates])+ useEffect(() => { onChannelRefIntentRef.current = onChannelRefIntent }, [onChannelRefIntent])// eslint-disable-next-line react-hooks/refs -- refs read in runtime callbacks, not renderconst [channelRefExtension] = useState(() =>buildCommunityChannelRefExtension({candidatesRef: channelRefCandidatesRef,popupRef: channelRefPopupRef,+ onIntentRef: onChannelRefIntentRef,setPopup: setChannelRefPopup,queryRef: channelRefQueryRef,}),diff --git a/src/web/src/components/community/dm-sidebar.prefetch.test.ts b/src/web/src/components/community/dm-sidebar.prefetch.test.tsnew file mode 100644index 000000000..8c01c5e41--- /dev/null+++ b/src/web/src/components/community/dm-sidebar.prefetch.test.ts@@ -0,0 +1,78 @@+import { createElement } from "react"+import TestRenderer, { act, type ReactTestRenderer } from "react-test-renderer"+import { describe, expect, it, vi } from "vitest"+import { tid } from "@/lib/community/testids"+import { DmSidebar } from "./dm-sidebar"++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++describe("DmSidebar navigation intent", () => {+ it("prefetches the fixed destinations on pointer and keyboard intent", async () => {+ const onPrefetchFriends = vi.fn()+ const onPrefetchMachines = vi.fn()+ const onPrefetchBots = vi.fn()+ const onShowFriends = vi.fn()+ const onShowMachines = vi.fn()+ const onShowBots = vi.fn()+ let renderer!: ReactTestRenderer++ await act(async () => {+ renderer = TestRenderer.create(createElement(DmSidebar, {+ dms: [],+ activeDm: null,+ onPickDm: vi.fn(),+ onShowFriends,+ onPrefetchFriends,+ onShowMachines,+ onPrefetchMachines,+ onShowBots,+ onPrefetchBots,+ }))+ })++ const [friends, machines, bots] = renderer.root.findAllByType("button")+ act(() => friends!.props.onPointerEnter())+ act(() => machines!.props.onFocus())+ act(() => bots!.props.onPointerEnter())++ expect(onPrefetchFriends).toHaveBeenCalledTimes(1)+ expect(onPrefetchMachines).toHaveBeenCalledTimes(1)+ expect(onPrefetchBots).toHaveBeenCalledTimes(1)+ expect(onShowFriends).not.toHaveBeenCalled()+ expect(onShowMachines).not.toHaveBeenCalled()+ expect(onShowBots).not.toHaveBeenCalled()++ act(() => renderer.unmount())+ })++ it("prefetches the intended DM without selecting it", async () => {+ const onPrefetchDm = vi.fn()+ const onPickDm = vi.fn()+ let renderer!: ReactTestRenderer++ await act(async () => {+ renderer = TestRenderer.create(createElement(DmSidebar, {+ dms: [{+ id: "dm_1",+ userId: "user_1",+ name: "Melly",+ avatar: "M",+ status: "online",+ preview: "hello",+ }],+ activeDm: null,+ onPickDm,+ onPrefetchDm,+ onShowFriends: vi.fn(),+ }))+ })++ const row = renderer.root.findByProps({ "data-testid": tid.dmRow("dm_1") })+ act(() => row.props.onFocus())++ expect(onPrefetchDm).toHaveBeenCalledWith("dm_1")+ expect(onPickDm).not.toHaveBeenCalled()++ act(() => renderer.unmount())+ })+})diff --git a/src/web/src/components/community/dm-sidebar.tsx b/src/web/src/components/community/dm-sidebar.tsxindex d68e23c33..b5186c5b9 100644--- a/src/web/src/components/community/dm-sidebar.tsx+++ b/src/web/src/components/community/dm-sidebar.tsx@@ -9,6 +9,7 @@ import type { DM } from "./_types"export const DmSidebar = memo(function DmSidebar({dms, activeDm, blockedUserIds, loading, onPickDm, onShowFriends, onShowMachines, onShowBots,+ onPrefetchDm, onPrefetchFriends, onPrefetchMachines, onPrefetchBots,friendsActive, machinesActive, botsActive,}: {dms: DM[]@@ -16,9 +17,13 @@ export const DmSidebar = memo(function DmSidebar({blockedUserIds?: Set<string>loading?: booleanonPickDm: (id: string) => void+ onPrefetchDm?: (id: string) => voidonShowFriends: () => void+ onPrefetchFriends?: () => voidonShowMachines?: () => void+ onPrefetchMachines?: () => voidonShowBots?: () => void+ onPrefetchBots?: () => voidfriendsActive?: booleanmachinesActive?: booleanbotsActive?: boolean@@ -29,6 +34,8 @@ export const DmSidebar = memo(function DmSidebar({<div className="flex-1 overflow-y-auto thin-scrollbar px-2 py-4"><buttononClick={onShowFriends}+ onPointerEnter={onPrefetchFriends}+ onFocus={onPrefetchFriends}className={["mb-1 flex h-9 w-full items-center gap-2 rounded-md px-2 text-sm font-medium",isFriendsActive ? "bg-sidebar-accent text-foreground" : "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",@@ -39,6 +46,8 @@ export const DmSidebar = memo(function DmSidebar({{onShowMachines && (<buttononClick={onShowMachines}+ onPointerEnter={onPrefetchMachines}+ onFocus={onPrefetchMachines}className={["mb-1 flex h-9 w-full items-center gap-2 rounded-md px-2 text-sm font-medium",machinesActive ? "bg-sidebar-accent text-foreground" : "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",@@ -50,6 +59,8 @@ export const DmSidebar = memo(function DmSidebar({{onShowBots && (<buttononClick={onShowBots}+ onPointerEnter={onPrefetchBots}+ onFocus={onPrefetchBots}className={["mb-2 flex h-9 w-full items-center gap-2 rounded-md px-2 text-sm font-medium",botsActive ? "bg-sidebar-accent text-foreground" : "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",@@ -75,6 +86,8 @@ export const DmSidebar = memo(function DmSidebar({key={d.id}data-testid={tid.dmRow(d.id)}onClick={() => onPickDm(d.id)}+ onPointerEnter={() => onPrefetchDm?.(d.id)}+ onFocus={() => onPrefetchDm?.(d.id)}className={["flex w-full items-center gap-3 rounded-md px-2 py-2",active ? "bg-sidebar-accent text-foreground" : "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",diff --git a/src/web/src/components/community/server-rail.tsx b/src/web/src/components/community/server-rail.tsxindex 457b4fa41..6ea43144a 100644--- a/src/web/src/components/community/server-rail.tsx+++ b/src/web/src/components/community/server-rail.tsx@@ -25,7 +25,7 @@ import {export const ServerRail = memo(function ServerRail({servers, folders, activeServerId: activeServerIdProp, serversLoading, setMobileZone, view, bottomInset,- onHome, onServer, onServerNavigate, onCreateServer, onLeaveServer,+ onHome, onHomePrefetch, onServer, onServerNavigate, onServerPrefetch, onCreateServer, onLeaveServer,onOpenSettings, onOpenInvitePopover, onUngroupFolder, onReorderRail, onReorderFolders, onFolderItemsChange, onDragCreateFolder,}: {servers: Server[]@@ -36,8 +36,10 @@ export const ServerRail = memo(function ServerRail({view: ViewbottomInset?: numberonHome: () => void+ onHomePrefetch?: () => voidonServer: () => voidonServerNavigate?: (id: string) => void+ onServerPrefetch?: (id: string) => voidonCreateServer?: (name: string, icon?: File) => voidonLeaveServer?: (id: string) => voidonOpenSettings?: (serverId: string) => void@@ -95,6 +97,8 @@ export const ServerRail = memo(function ServerRail({].join(" ")} /><buttononClick={onHome}+ onPointerEnter={onHomePrefetch}+ onFocus={onHomePrefetch}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"@@ -150,6 +154,7 @@ export const ServerRail = memo(function ServerRail({server={{ id: fs.id, name: fs.name, initial: fs.initial, icon: fs.icon, active: false, mentions: 0, isOwner: false }}active={view !== "dm" && activeId === sid}onClick={() => pickServer(sid)}+ onPrefetch={() => onServerPrefetch?.(sid)}onOpenSettings={() => onOpenSettings?.(sid)}onOpenInvitePopover={onOpenInvitePopover ? () => onOpenInvitePopover(sid) : undefined}inFolder@@ -180,6 +185,7 @@ export const ServerRail = memo(function ServerRail({server={s}active={view !== "dm" && s.active}onClick={() => pickServer(id)}+ onPrefetch={() => onServerPrefetch?.(id)}onLeave={() => onLeaveServer?.(id)}onOpenSettings={() => onOpenSettings?.(id)}onOpenInvitePopover={onOpenInvitePopover ? () => onOpenInvitePopover(id) : undefined}diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsxindex 5f874e0b1..c6c1e4247 100644--- a/src/web/src/components/community/shell-frame.tsx+++ b/src/web/src/components/community/shell-frame.tsx@@ -1,7 +1,14 @@"use client"-import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react"-import { useRouter } from "next/navigation"+import {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+ type ReactNode,+} from "react"+import { usePathname, useRouter } from "next/navigation"import { useQueryClient } from "@tanstack/react-query"import { toast } from "sonner"import { toastApiError } from "@/lib/api/client"@@ -45,7 +52,7 @@ import { useCommunityStore } from "@/stores/community"import { useCommunityWsStore, useOnlineUserIds } from "@/stores/community/ws"import { useMessageStreamStore } from "@/stores/community/message-stream"import { useCurrentUser, useSetCurrentUser } from "@/contexts/community/current-user"-import { useServers } from "@/hooks/community/use-servers"+import { serverQueryFn, useServers, type ServerDetail } from "@/hooks/community/use-servers"import { useFolders } from "@/hooks/community/use-folders"import { useFriends } from "@/hooks/community/use-friends"import { useServerMembers } from "@/hooks/community/use-server-members"@@ -70,6 +77,13 @@ import {useUploadUserAvatar,} from "@/hooks/community/mutations"import { useDmMessageSender } from "@/hooks/community/use-dm-message-sender"+import { getLastChannel, pickServerLandingHref } from "@/lib/community/last-channel"+import { getLastMeLeaf, pickMeLandingLocation } from "@/lib/community/last-me-location"+import {+ commitLatestNavigationIntent,+ createNavigationIntentGate,+ supersedeNavigationIntent,+} from "@/lib/community/navigation-intent"/*** Shared community shell — ServerRail on the left, sidebar column with the@@ -109,6 +123,7 @@ export function ShellFrame({goServer: () => void}) {const router = useRouter()+ const pathname = usePathname()const bp = useBreakpoint()const queryClient = useQueryClient()const currentUser = useCurrentUser()@@ -205,8 +220,56 @@ export function ShellFrame({[servers, activeServerId, folderServerIds],)+ const serverNavigationGateRef = useRef(createNavigationIntentGate())+ const cancelPendingServerNavigation = useCallback(() => {+ supersedeNavigationIntent(serverNavigationGateRef.current)+ }, [])+ useEffect(() => {+ cancelPendingServerNavigation()+ }, [cancelPendingServerNavigation, pathname])++ const serverDestination = useCallback((id: string) => {+ const detail = queryClient.getQueryData<ServerDetail>(communityKeys.server(id))+ const channelIds = detail?.categories.flatMap((category) =>+ category.channels.filter((channel) => !channel.pending).map((channel) => channel.id)+ ) ?? []+ return pickServerLandingHref(id, channelIds, getLastChannel(id))+ }, [queryClient])+ 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: serverQueryFn(id),+ staleTime: Infinity,+ })+ } catch {+ return root+ }+ return serverDestination(id)+ }, [queryClient, serverDestination])const onRailServerNavigate = useCallback(- (id: string) => { markSwitch("server", id); router.push(`/c/channels/${id}`) },+ (id: string) => {+ markSwitch("server", id)+ void commitLatestNavigationIntent(+ serverNavigationGateRef.current,+ () => resolveServerDestination(id),+ (destination) => router.push(destination),+ )+ },+ [resolveServerDestination, router],+ )+ const onRailHomeNavigate = useCallback(() => {+ cancelPendingServerNavigation()+ goHome()+ }, [cancelPendingServerNavigation, goHome])+ const onRailServerPrefetch = useCallback((id: string) => {+ void resolveServerDestination(id).then((destination) => router.prefetch(destination))+ }, [resolveServerDestination, router])+ const onRailHomePrefetch = useCallback(+ () => router.prefetch(pickMeLandingLocation(getLastMeLeaf())),[router],)const onRailCreateServer = useCallback(@@ -221,12 +284,13 @@ export function ShellFrame({{ onError: (e) => toastApiError(e, "Server created, but the icon failed to upload") },)}+ cancelPendingServerNavigation()router.push(`/c/channels/${newId}`)} catch (e) {toastApiError(e, "Failed to create server")}},- [createServerAsync, uploadServerIconMutate, router],+ [cancelPendingServerNavigation, createServerAsync, uploadServerIconMutate, router],)const onRailLeaveServer = useCallback((id: string) => {@@ -241,6 +305,7 @@ export function ShellFrame({onSuccess: () => {toast("Left server")if (currentServerId === id) {+ cancelPendingServerNavigation()router.replace(pickPostEjectDestination(servers, id))}},@@ -248,11 +313,12 @@ export function ShellFrame({},)},- [leaveServerMutate, currentServerId, router, servers],+ [cancelPendingServerNavigation, leaveServerMutate, currentServerId, router, servers],)const onRailOpenSettings = useCallback((id?: string) => {if (!id) return+ cancelPendingServerNavigation()const action = resolveServerRailOverlayAction({targetServerId: id,activeServerId,@@ -262,11 +328,12 @@ export function ShellFrame({if (action.kind === "open-active") onOpenActiveServerSettings?.()else router.push(action.href)},- [activeServerId, onOpenActiveServerSettings, router],+ [activeServerId, cancelPendingServerNavigation, onOpenActiveServerSettings, router],)const onRailOpenInvitePopover = useCallback((id?: string) => {if (!id) return+ cancelPendingServerNavigation()const action = resolveServerRailOverlayAction({targetServerId: id,activeServerId,@@ -276,7 +343,7 @@ export function ShellFrame({if (action.kind === "open-active") onOpenActiveServerInvite?.()else router.push(action.href)},- [activeServerId, onOpenActiveServerInvite, router],+ [activeServerId, cancelPendingServerNavigation, onOpenActiveServerInvite, router],)const onRailUngroupFolder = useCallback((fId: string) => {@@ -334,9 +401,11 @@ export function ShellFrame({serversLoading: serversQuery.isLoading,setMobileZone,view,- onHome: goHome,+ onHome: onRailHomeNavigate,+ onHomePrefetch: onRailHomePrefetch,onServer: goServer,onServerNavigate: onRailServerNavigate,+ onServerPrefetch: onRailServerPrefetch,onCreateServer: onRailCreateServer,onLeaveServer: onRailLeaveServer,onOpenSettings: onRailOpenSettings,@@ -450,9 +519,18 @@ export function ShellFrame({const navigate = useCallback((serverId: string, channelId?: string) => {markSwitch(channelId ? "channel" : "server", channelId ?? serverId)- router.push(channelId ? `/c/channels/${serverId}/${channelId}` : `/c/channels/${serverId}`)+ if (channelId) {+ cancelPendingServerNavigation()+ router.push(`/c/channels/${serverId}/${channelId}`)+ return+ }+ void commitLatestNavigationIntent(+ serverNavigationGateRef.current,+ () => resolveServerDestination(serverId),+ (destination) => router.push(destination),+ )},- [router],+ [cancelPendingServerNavigation, resolveServerDestination, router],)useEffect(() => {useCommunityStore.getState().registerUiHandlers({@@ -461,8 +539,9 @@ export function ShellFrame({openProfile,goBackMobile,navigate,+ cancelPendingNavigation: cancelPendingServerNavigation,})- }, [previewImage, previewAttachment, openProfile, goBackMobile, navigate])+ }, [previewImage, previewAttachment, openProfile, goBackMobile, navigate, cancelPendingServerNavigation])// Inline self-status save from the `ProfileCard` header (see status-editor.tsx).// Mirrors `userSettingsDialog`'s onSave status branch exactly — both save@@ -510,6 +589,7 @@ export function ShellFrame({}void receipt.committed}+ cancelPendingServerNavigation()router.push(`/c/me/${dmId}`)}@@ -522,9 +602,10 @@ export function ShellFrame({// a mention click passes `mention:<id>` so the mention row (not the// channel, which may persist to host unread children) drives the collapse.watchInboxItem(watchKey)+ cancelPendingServerNavigation()router.push(`/c/channels/${sid}/${cid}`)},- [router, watchInboxItem],+ [cancelPendingServerNavigation, router, watchInboxItem],)const openForumThreadFromInbox = useCallback(@@ -535,9 +616,10 @@ export function ShellFrame({// opener unread for a later retry.watchInboxItem(`channel:${childChannelId}`)readForumThreadFromInbox({ parentChannelId, openerMessageId })+ cancelPendingServerNavigation()router.push(`/c/channels/${sid}/${childChannelId}`)},- [readForumThreadFromInbox, router, watchInboxItem],+ [cancelPendingServerNavigation, readForumThreadFromInbox, router, watchInboxItem],)// A Marked row is cross-channel — clicking one navigates to the message's@@ -551,6 +633,7 @@ export function ShellFrame({const openMarked = useCallback((mk: Marked) => {watchInboxItem(`marked:${mk.id}`)+ cancelPendingServerNavigation()const seqQuery = mk.m.seq != null ? `?seq=${mk.m.seq}` : ""if (mk.serverId) {router.push(`/c/channels/${mk.serverId}/${mk.channelId}${seqQuery}`)@@ -558,7 +641,7 @@ export function ShellFrame({router.push(`/c/me/${mk.channelId}${seqQuery}`)}},- [router, watchInboxItem],+ [cancelPendingServerNavigation, router, watchInboxItem],)const openInboxDm = useCallback(@@ -576,9 +659,10 @@ export function ShellFrame({: prev,)watchInboxItem(`dm:${dmId}`)+ cancelPendingServerNavigation()router.push(`/c/me/${dmId}`)},- [router, queryClient, watchInboxItem],+ [cancelPendingServerNavigation, router, queryClient, watchInboxItem],)const inboxElement = (@@ -655,6 +739,7 @@ export function ShellFrame({} catch (e) { toastApiError(e, "Failed to save profile") }}}onLogout={async () => {+ cancelPendingServerNavigation()// Clear community-local state (timers, subscription, presence)// before the auth cookie clears so no orphan timers fire after// the user is gone. `useCommunityStore.reset()` also flushes any@@ -716,7 +801,7 @@ export function ShellFrame({if (bp === "desktop") {return (- <Shell>+ <Shell onNavigationIntent={cancelPendingServerNavigation}><ServerRail {...railProps} bottomInset={60} /><div className="relative flex-1 flex flex-col min-w-0 pt-2"><AppSurface className="rounded-tl-xl rounded-tr-none rounded-br-none rounded-bl-none ring-0 border-l border-t border-border/40 shadow-none">@@ -759,7 +844,7 @@ export function ShellFrame({}return (- <Shell>+ <Shell onNavigationIntent={cancelPendingServerNavigation}>{mobileZone === "nav" && (<><ServerRail {...railProps} bottomInset={60} />diff --git a/src/web/src/components/community/shell.navigation-intent.test.ts b/src/web/src/components/community/shell.navigation-intent.test.tsnew file mode 100644index 000000000..0285c6ab3--- /dev/null+++ b/src/web/src/components/community/shell.navigation-intent.test.ts@@ -0,0 +1,77 @@+import { createElement } from "react"+import TestRenderer, { act, type ReactTestRenderer } from "react-test-renderer"+import { describe, expect, it, vi } from "vitest"+import {+ commitLatestNavigationIntent,+ createNavigationIntentGate,+ supersedeNavigationIntent,+} from "@/lib/community/navigation-intent"+import { Shell } from "./shell"++vi.mock("@/components/ui/app-surface", () => ({+ AppBackground: () => createElement("div", { "data-testid": "background" }),+}))++describe("Shell navigation intent capture", () => {+ it("cancels a pending server resolution before a nested Bot DM click runs", async () => {+ let resolveServer!: (href: string) => void+ const pendingServer = new Promise<string>((resolve) => {+ resolveServer = resolve+ })+ const push = vi.fn()+ const gate = createNavigationIntentGate()+ const serverNavigation = commitLatestNavigationIntent(+ gate,+ () => pendingServer,+ push,+ )+ let renderer!: ReactTestRenderer++ await act(async () => {+ renderer = TestRenderer.create(createElement(+ Shell,+ {+ "data-testid": "community-shell",+ onNavigationIntent: () => supersedeNavigationIntent(gate),+ },+ createElement("button", {+ "data-testid": "bot-dm",+ onClick: () => push("/c/me/dm_2"),+ }),+ ))+ })++ const shell = renderer.root.findAllByType("div").find(+ (node) => node.props["data-testid"] === "community-shell",+ )!+ const botDm = renderer.root.findByProps({ "data-testid": "bot-dm" })+ shell.props.onClickCapture({})+ botDm.props.onClick()+ resolveServer("/c/channels/server_1/channel_1")++ await expect(serverNavigation).resolves.toBe(false)+ expect(push).toHaveBeenCalledTimes(1)+ expect(push).toHaveBeenCalledWith("/c/me/dm_2")+ })++ it("captures keyboard activation without treating navigation keys as intent", async () => {+ const onNavigationIntent = vi.fn()+ let renderer!: ReactTestRenderer++ await act(async () => {+ renderer = TestRenderer.create(createElement(Shell, {+ "data-testid": "community-shell",+ onNavigationIntent,+ }))+ })++ const shell = renderer.root.findAllByType("div").find(+ (node) => node.props["data-testid"] === "community-shell",+ )!+ shell.props.onKeyDownCapture({ key: "ArrowDown" })+ shell.props.onKeyDownCapture({ key: "Enter" })+ shell.props.onKeyDownCapture({ key: " " })++ expect(onNavigationIntent).toHaveBeenCalledTimes(2)+ })+})diff --git a/src/web/src/components/community/shell.tsx b/src/web/src/components/community/shell.tsxindex 73c63f138..8f83682e9 100644--- a/src/web/src/components/community/shell.tsx+++ b/src/web/src/components/community/shell.tsx@@ -2,12 +2,31 @@ import type React from "react"import { AppBackground } from "@/components/ui/app-surface"import { cn } from "@/lib/utils"-export function Shell({ children, className }: {- children: React.ReactNode- className?: string-}) {+type ShellProps = React.ComponentPropsWithoutRef<"div"> & {+ onNavigationIntent?: () => void+}++export function Shell({+ children,+ className,+ onNavigationIntent,+ onClickCapture,+ onKeyDownCapture,+ ...props+}: ShellProps) {return (- <div className={cn("fixed inset-0 flex overflow-hidden font-sans text-sm text-foreground", className)}>+ <div+ {...props}+ onClickCapture={(event) => {+ onNavigationIntent?.()+ onClickCapture?.(event)+ }}+ onKeyDownCapture={(event) => {+ if (event.key === "Enter" || event.key === " ") onNavigationIntent?.()+ onKeyDownCapture?.(event)+ }}+ className={cn("fixed inset-0 flex overflow-hidden font-sans text-sm text-foreground", className)}+ ><AppBackground />{children}</div>diff --git a/src/web/src/components/community/sortable-channel.tsx b/src/web/src/components/community/sortable-channel.tsxindex 491d22e7a..148b17a14 100644--- a/src/web/src/components/community/sortable-channel.tsx+++ b/src/web/src/components/community/sortable-channel.tsx@@ -37,10 +37,11 @@ export function PendingChannelRow({ ch }: { ch: Channel }) {// A single drag-sortable channel row. The whole row is the drag surface (no handle);// a 5px activation distance keeps a tap = "switch channel" and a drag = reorder.// Right-click opens an edit/mute/delete menu.-export function SortableChannel({ ch, active, onClick, onEdit, onDelete, onManageMembers, canReorder = true }: {+export function SortableChannel({ ch, active, onClick, onPrefetch, onEdit, onDelete, onManageMembers, canReorder = true }: {ch: Channelactive: booleanonClick: () => void+ onPrefetch?: () => voidonEdit?: () => voidonDelete?: () => voidonManageMembers?: () => void@@ -56,6 +57,8 @@ export function SortableChannel({ ch, active, onClick, onEdit, onDelete, onManagref={setNodeRef}style={style}onClick={onClick}+ onPointerEnter={onPrefetch}+ onFocus={onPrefetch}data-testid={tid.channelRow(ch.id)}{...attributes}{...listeners}diff --git a/src/web/src/components/community/sortable-server.tsx b/src/web/src/components/community/sortable-server.tsxindex 2130a9a5e..37f5453cc 100644--- a/src/web/src/components/community/sortable-server.tsx+++ b/src/web/src/components/community/sortable-server.tsx@@ -26,6 +26,7 @@ type SortableServerProps = {server: Server;active?: boolean;onClick: () => void;+ onPrefetch?: () => void;onLeave?: () => void;onOpenSettings?: () => void;onOpenInvitePopover?: () => void;@@ -39,6 +40,7 @@ function SortableServerImpl({server,active,onClick,+ onPrefetch,onLeave,onOpenSettings,onOpenInvitePopover,@@ -79,14 +81,18 @@ function SortableServerImpl({// mounted before it's invoked).const [activated, setActivated] = useState(false);const activate = activated ? undefined : () => setActivated(true);+ const activateAndPrefetch = () => {+ activate?.();+ onPrefetch?.();+ };const icon = (<divref={setNodeRef}style={style}className="group relative flex w-full justify-center"- onPointerEnter={activate}- onFocusCapture={activate}+ onPointerEnter={activateAndPrefetch}+ onFocusCapture={activateAndPrefetch}onKeyDownCapture={activate}>{showLine && (@@ -247,7 +253,8 @@ function serverPropsEqual(prev: SortableServerProps, next: SortableServerProps):!!prev.onLeave === !!next.onLeave &&!!prev.onOpenSettings === !!next.onOpenSettings &&!!prev.onOpenInvitePopover === !!next.onOpenInvitePopover &&- !!prev.onCreateFolder === !!next.onCreateFolder+ !!prev.onCreateFolder === !!next.onCreateFolder &&+ !!prev.onPrefetch === !!next.onPrefetch);}diff --git a/src/web/src/hooks/community/community-ws/membership-events.ts b/src/web/src/hooks/community/community-ws/membership-events.tsindex 137d190c9..65a763099 100644--- a/src/web/src/hooks/community/community-ws/membership-events.ts+++ b/src/web/src/hooks/community/community-ws/membership-events.ts@@ -80,6 +80,10 @@ export function handleChannelMemberEvent(queryKey: communityKeys.server(event.serverId),exact: true,})+ void queryClient.invalidateQueries({+ queryKey: communityKeys.channelRefDirectory(),+ exact: true,+ })// Refetch the channel roster so an open private-channel Members drawer// (and the manage-members dialog) reflect the add/remove live.void queryClient.invalidateQueries({ queryKey: communityKeys.channelMembers(event.channelId) })@@ -119,6 +123,10 @@ export function handleMemberJoin()dispatchMemberOverlayEvent({ type: "refresh", serverId: event.serverId })if (event.member.userId === viewerUserIdRef.current) {+ void queryClient.invalidateQueries({+ queryKey: communityKeys.channelRefDirectory(),+ exact: true,+ })void queryClient.invalidateQueries({queryKey: communityKeys.servers(),exact: true,@@ -151,6 +159,10 @@ export function handleMemberLeave(// so the layout's eject effect can detect the drop and route// the user away from the now-forbidden URL.if (event.userId === viewerUserIdRef.current) {+ void queryClient.invalidateQueries({+ queryKey: communityKeys.channelRefDirectory(),+ exact: true,+ })useMessageStreamStore.getState().removeServer(event.serverId)queryClient.removeQueries({ queryKey: communityKeys.server(event.serverId) })const store = useCommunityStore.getState()diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.tsindex 1675632ce..5ee0550b8 100644--- a/src/web/src/hooks/community/community-ws/structure-tree-events.ts+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.ts@@ -35,6 +35,15 @@ import {} from "@/hooks/community/community-ws/cache"import type { StructureTreeEventContext } from "@/hooks/community/community-ws/handler-context"+function invalidateChannelRefDirectory(+ queryClient: StructureTreeEventContext["queryClient"],+) {+ void queryClient.invalidateQueries({+ queryKey: communityKeys.channelRefDirectory(),+ exact: true,+ })+}+export function handleChildChannelCreate(event: CommunityChildChannelCreate,{ queryClient }: StructureTreeEventContext,@@ -232,6 +241,7 @@ export function handleServerUpdate(event: CommunityServerUpdate,{ queryClient }: StructureTreeEventContext,) {+ invalidateChannelRefDirectory(queryClient)queryClient.setQueryData<ServerDetail | undefined>(communityKeys.server(event.serverId),(prev) =>@@ -274,6 +284,7 @@ export function handleServerDelete(event: CommunityServerDelete,{ queryClient }: StructureTreeEventContext,) {+ invalidateChannelRefDirectory(queryClient)// Refresh the rail LIST only (drop the deleted server). `exact`// so this doesn't cascade-refetch every other server's nested// detail subtree; the deleted server's own subtree is cleared by@@ -302,6 +313,7 @@ export function handleChannelEvent(event: ChannelEvent,{ queryClient }: StructureTreeEventContext,) {+ invalidateChannelRefDirectory(queryClient)// #3: on channel.delete, evict every channel-scoped cache before// invalidating the server. Without this the messages/pins/threads/// child-thread caches for the dead channel linger forever — a@@ -372,6 +384,7 @@ export function handleCategoryEvent(event: CategoryEvent,{ queryClient }: StructureTreeEventContext,) {+ invalidateChannelRefDirectory(queryClient)void queryClient.invalidateQueries({queryKey: communityKeys.server(event.serverId),exact: true,diff --git a/src/web/src/hooks/community/mutations/channels.test.ts b/src/web/src/hooks/community/mutations/channels.test.tsindex a6f34752f..c08ede9b5 100644--- a/src/web/src/hooks/community/mutations/channels.test.ts+++ b/src/web/src/hooks/community/mutations/channels.test.ts@@ -148,6 +148,10 @@ describe("useMoveChannel", () => {return Array.isArray(k) && k[0] === "community" && k[1] === "servers" && k[2] === "s1"}),).toBe(true)+ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: communityKeys.channelRefDirectory(),+ exact: true,+ })})it("sends categoryId: null when moving to uncategorized", async () => {diff --git a/src/web/src/hooks/community/mutations/channels.ts b/src/web/src/hooks/community/mutations/channels.tsindex 8ad2b4ac0..e8b576c4f 100644--- a/src/web/src/hooks/community/mutations/channels.ts+++ b/src/web/src/hooks/community/mutations/channels.ts@@ -17,6 +17,13 @@ const tempChannelId = () => `tmp_ch_${nanoid()}`const isUncategorizedTarget = (categoryId: string | null) =>!categoryId || categoryId === UNCATEGORIZED_CATEGORY_ID+function invalidateChannelRefDirectory(queryClient: ReturnType<typeof useQueryClient>) {+ void queryClient.invalidateQueries({+ queryKey: communityKeys.channelRefDirectory(),+ exact: true,+ })+}+/*** Channel / category CRUD + reorders. These all invalidate `server(serverId)`* so the tree re-renders with fresh category/channel positions. The WS layer@@ -129,6 +136,7 @@ export function useCreateChannel() {},onSettled: (_data, _err, args) => {void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })+ invalidateChannelRefDirectory(queryClient)},})}@@ -157,6 +165,7 @@ export function useMoveChannel() {},onSuccess: (_data, args) => {void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })+ invalidateChannelRefDirectory(queryClient)},})}@@ -173,6 +182,7 @@ export function useDeleteChannel() {if (args.serverId) {void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })}+ invalidateChannelRefDirectory(queryClient)},})}@@ -244,6 +254,7 @@ export function useCreateCategory() {},onSettled: (_data, _err, args) => {void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })+ invalidateChannelRefDirectory(queryClient)},})}@@ -266,6 +277,7 @@ export function useUpdateCategory() {},onSuccess: (_data, args) => {void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })+ invalidateChannelRefDirectory(queryClient)},})}@@ -303,6 +315,7 @@ export function useDeleteCategory() {},onSettled: (_data, _err, args) => {void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })+ invalidateChannelRefDirectory(queryClient)},})}@@ -344,6 +357,7 @@ export function useReorderServers() {onError: (_err, _args, ctx) => {if (ctx?.snapshot) queryClient.setQueryData(communityKeys.servers(), ctx.snapshot)},+ onSettled: () => invalidateChannelRefDirectory(queryClient),})}@@ -360,6 +374,7 @@ export function useReorderCategories() {},onSuccess: (_data, args) => {void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })+ invalidateChannelRefDirectory(queryClient)},})}@@ -377,6 +392,7 @@ export function useReorderChannels() {},onSuccess: (_data, args) => {void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })+ invalidateChannelRefDirectory(queryClient)},})}diff --git a/src/web/src/hooks/community/mutations/servers.test.ts b/src/web/src/hooks/community/mutations/servers.test.tsindex aa7f2e720..754f5b8df 100644--- a/src/web/src/hooks/community/mutations/servers.test.ts+++ b/src/web/src/hooks/community/mutations/servers.test.ts@@ -22,6 +22,7 @@ type MutConfig<Args, Ctx> = {onMutate?: (args: Args) => Promise<Ctx> | CtxonSuccess?: (data: unknown, args: Args, ctx: Ctx) => unknownonError?: (err: unknown, args: Args, ctx: Ctx) => unknown+ onSettled?: (data: unknown, err: unknown, args: Args, ctx: Ctx) => unknown}let capturedConfig: MutConfig<unknown, unknown> | null = nulllet capturedQc: QueryClient@@ -43,9 +44,11 @@ async function runMutation<Args>(args: Args) {try {const data = cfg.mutationFn ? await cfg.mutationFn(args) : undefinedcfg.onSuccess?.(data, args, ctx)+ cfg.onSettled?.(data, undefined, args, ctx)return { data, ctx }} catch (err) {cfg.onError?.(err, args, ctx)+ cfg.onSettled?.(undefined, err, args, ctx)throw err}}@@ -148,6 +151,20 @@ describe("useUpdateServer — rollback on both caches", () => {const list = capturedQc.getQueryData<{ servers: { name: string }[] }>(communityKeys.servers())expect(list?.servers[0].name).toBe("old")})++ it("invalidates the channel-ref directory after settling", async () => {+ apiFetchMock.mockResolvedValueOnce(undefined)+ const mod = await load()+ mod.useUpdateServer()+ const spy = vi.spyOn(capturedQc, "invalidateQueries")++ await runMutation({ serverId: "srv_1", name: "new", description: "updated" })++ expect(spy).toHaveBeenCalledWith({+ queryKey: communityKeys.channelRefDirectory(),+ exact: true,+ })+ })})describe("useCreateServer — invalidates servers()", () => {diff --git a/src/web/src/hooks/community/mutations/servers.ts b/src/web/src/hooks/community/mutations/servers.tsindex dea742c83..007f61a2f 100644--- a/src/web/src/hooks/community/mutations/servers.ts+++ b/src/web/src/hooks/community/mutations/servers.ts@@ -100,6 +100,10 @@ export function useLeaveServer() {},onSuccess: (_data, args) => {queryClient.removeQueries({ queryKey: communityKeys.server(args.serverId) })+ void queryClient.invalidateQueries({+ queryKey: communityKeys.channelRefDirectory(),+ exact: true,+ })clearDepartedServer(args.serverId)},})@@ -125,6 +129,10 @@ export function useDeleteServer() {},onSuccess: (_data, args) => {queryClient.removeQueries({ queryKey: communityKeys.server(args.serverId) })+ void queryClient.invalidateQueries({+ queryKey: communityKeys.channelRefDirectory(),+ exact: true,+ })clearDepartedServer(args.serverId)},})@@ -180,6 +188,12 @@ export function useUpdateServer() {if (ctx?.serverSnap) queryClient.setQueryData(communityKeys.server(args.serverId), ctx.serverSnap)if (ctx?.listSnap) queryClient.setQueryData(communityKeys.servers(), ctx.listSnap)},+ onSettled: () => {+ void queryClient.invalidateQueries({+ queryKey: communityKeys.channelRefDirectory(),+ exact: true,+ })+ },})}diff --git a/src/web/src/hooks/community/use-channel-ref-directory.test.ts b/src/web/src/hooks/community/use-channel-ref-directory.test.tsindex b59eccbb3..b033898a4 100644--- a/src/web/src/hooks/community/use-channel-ref-directory.test.ts+++ b/src/web/src/hooks/community/use-channel-ref-directory.test.ts@@ -1,59 +1,29 @@-import { describe, it, expect } from "vitest"-import { buildChannelRefDirectory } from "./use-channel-ref-directory"-import type { Server, Category } from "@/components/community/_types"-import type { ServerDetail } from "./use-servers"+import { beforeEach, describe, expect, it, vi } from "vitest"-function server(id: string, name: string, discriminator = "0001"): Server {- return { id, name, discriminator, initial: name[0], active: false, mentions: 0 }-}+const apiFetch = vi.fn()-function detail(id: string, name: string, categories: Category[]): ServerDetail {- return { id, name, description: "", icon: null, ownerId: "u1", categories }-}+vi.mock("@/lib/api/client", () => ({+ apiFetch: (...args: unknown[]) => apiFetch(...args),+}))-function category(id: string, channels: Array<{ id: string; name: string }>): Category {- return {- id,- name: id,- channels: channels.map((c) => ({ id: c.id, name: c.name, active: false, unread: false })),- }-}+import { channelRefDirectoryQueryFn } from "./use-channel-ref-directory"-describe("buildChannelRefDirectory", () => {- it("flattens each server's categories[].channels into one channels array per server", () => {- const servers = [server("s1", "Studio")]- const detailsById = {- s1: detail("s1", "Studio", [- category("cat1", [{ id: "c1", name: "general" }, { id: "c2", name: "random" }]),- category("cat2", [{ id: "c3", name: "dev" }]),- ]),- }- const directory = buildChannelRefDirectory(servers, detailsById)- expect(directory).toEqual([+describe("channelRefDirectoryQueryFn", () => {+ beforeEach(() => vi.clearAllMocks())++ it("loads the complete directory through one lightweight request", async () => {+ const directory = [{- id: "s1",+ id: "server_1",name: "Studio",- discriminator: "0001",- channels: [- { id: "c1", name: "general" },- { id: "c2", name: "random" },- { id: "c3", name: "dev" },- ],+ discriminator: "0042",+ channels: [{ id: "channel_1", name: "general" }],},- ])- })-- it("a server with no fetched detail yet yields an empty channels array, not a crash", () => {- const servers = [server("s1", "Studio"), server("s2", "Other")]- const detailsById = { s1: detail("s1", "Studio", [category("cat1", [{ id: "c1", name: "general" }])]) }- const directory = buildChannelRefDirectory(servers, detailsById)- expect(directory).toEqual([- { id: "s1", name: "Studio", discriminator: "0001", channels: [{ id: "c1", name: "general" }] },- { id: "s2", name: "Other", discriminator: "0001", channels: [] },- ])- })+ ]+ apiFetch.mockResolvedValue({ directory })- it("returns [] for an empty server list", () => {- expect(buildChannelRefDirectory([], {})).toEqual([])+ await expect(channelRefDirectoryQueryFn()).resolves.toEqual(directory)+ expect(apiFetch).toHaveBeenCalledWith("/api/community/users/me/channel-directory")+ expect(apiFetch).toHaveBeenCalledTimes(1)})})diff --git a/src/web/src/hooks/community/use-channel-ref-directory.ts b/src/web/src/hooks/community/use-channel-ref-directory.tsindex 69f174a11..d3e6c630b 100644--- a/src/web/src/hooks/community/use-channel-ref-directory.ts+++ b/src/web/src/hooks/community/use-channel-ref-directory.ts@@ -1,71 +1,32 @@"use client"-import { useMemo } from "react"-import { useQueries } from "@tanstack/react-query"+import { useQuery } from "@tanstack/react-query"+import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"-import { useServers, serverQueryFn, type ServerDetail } from "./use-servers"import type { ChannelRefDirectory } from "@/lib/community/channel-ref"-import type { Server } from "@/components/community/_types"-/**- * Pure — flattens each server's `categories[].channels` into one `channels`- * array per server. A server whose detail hasn't loaded yet (or is- * genuinely still loading) contributes an empty `channels` array rather than- * being omitted or crashing — `resolveChannelRefBase` then simply can't- * resolve into it yet (falls back to plain/muted text upstream), and the- * directory backfills once the detail query resolves.- */-export function buildChannelRefDirectory(- servers: Server[],- detailsById: Record<string, ServerDetail | undefined>,-): ChannelRefDirectory {- return servers.map((s) => {- const detail = detailsById[s.id]- const channels = detail?.categories?.flatMap((c) => c.channels.map((ch) => ({ id: ch.id, name: ch.name }))) ?? []- return { id: s.id, name: s.name, discriminator: s.discriminator ?? "", channels }- })+const EMPTY_DIRECTORY = Object.freeze([]) as unknown as ChannelRefDirectory++export const channelRefDirectoryQueryFn = async (): Promise<ChannelRefDirectory> => {+ const data = await apiFetch<{ directory: ChannelRefDirectory }>(+ "/api/community/users/me/channel-directory",+ )+ return data.directory}-/**- * Directory of every channel-ref-resolvable server + channel the current- * user is a member of. Fetches every member server's channel list in- * parallel via `useQueries` (reusing `serverQueryFn`/`communityKeys.server`- * so the cache is shared with any already-mounted single-server `useServer`- * call), then flattens via `buildChannelRefDirectory`.- *- * Scope decision: eagerly resolves refs to ANY server the user is a member- * of, not just the currently open one — simpler and more correct than- * lazily fetching only the referenced server, at the cost of fetching every- * member server's channel list as soon as a channel-ref pill is on screen- * (bounded, cached, parallel).- */-export function useChannelRefDirectory(): {+export function useChannelRefDirectory(enabled = true): {directory: ChannelRefDirectoryisLoading: boolean} {- const { servers } = useServers()-- const results = useQueries({- queries: servers.map((s) => ({- queryKey: communityKeys.server(s.id),- queryFn: serverQueryFn(s.id),- })),+ const query = useQuery({+ queryKey: communityKeys.channelRefDirectory(),+ queryFn: channelRefDirectoryQueryFn,+ enabled,+ staleTime: Infinity,+ refetchOnReconnect: true,})-- const detailsById = useMemo(() => {- const map: Record<string, ServerDetail | undefined> = {}- servers.forEach((s, i) => {- map[s.id] = results[i]?.data- })- return map- }, [servers, results])-- const directory = useMemo(- () => buildChannelRefDirectory(servers, detailsById),- [servers, detailsById],- )-- const isLoading = results.some((r) => r.isLoading)-- return { directory, isLoading }+ return {+ directory: query.data ?? EMPTY_DIRECTORY,+ isLoading: enabled && query.isLoading,+ }}diff --git a/src/web/src/lib/community/channel-ref-extension.test.ts b/src/web/src/lib/community/channel-ref-extension.test.tsindex 5d71fe0f3..2ba3fe148 100644--- a/src/web/src/lib/community/channel-ref-extension.test.ts+++ b/src/web/src/lib/community/channel-ref-extension.test.ts@@ -100,13 +100,18 @@ function getKeyDownCallback(return onKeyDown}-function build(candidates: ChannelRefCandidate[] = [], popup: ChannelRefPopupState = EMPTY_CHANNEL_REF_STATE) {+function build(+ candidates: ChannelRefCandidate[] = [],+ popup: ChannelRefPopupState = EMPTY_CHANNEL_REF_STATE,+ onIntent?: () => void,+) {const candidatesRef = { current: candidates }const popupRef = { current: popup }+ const onIntentRef = { current: onIntent }const setPopup = vi.fn()const queryRef = { current: "" }- const ext = buildCommunityChannelRefExtension({ candidatesRef, popupRef, setPopup, queryRef })- return { ext, candidatesRef, popupRef, setPopup, queryRef }+ const ext = buildCommunityChannelRefExtension({ candidatesRef, popupRef, onIntentRef, setPopup, queryRef })+ return { ext, candidatesRef, popupRef, onIntentRef, setPopup, queryRef }}describe("toChannelRefCommandProps", () => {@@ -140,6 +145,13 @@ describe("buildCommunityChannelRefExtension — suggestion.items callback", () =items({ query: "general" })expect(queryRef.current).toBe("general")})++ it("signals directory demand when slash suggestions are evaluated", () => {+ const onIntent = vi.fn()+ const { ext } = build([], EMPTY_CHANNEL_REF_STATE, onIntent)+ getItemsCallback(ext)({ query: "" })+ expect(onIntent).toHaveBeenCalledTimes(1)+ })})describe("buildCommunityChannelRefExtension — renderText/renderHTML", () => {diff --git a/src/web/src/lib/community/channel-ref-extension.ts b/src/web/src/lib/community/channel-ref-extension.tsindex 54651267c..df28b7303 100644--- a/src/web/src/lib/community/channel-ref-extension.ts+++ b/src/web/src/lib/community/channel-ref-extension.ts@@ -118,6 +118,7 @@ const ChannelRefNode = Mention.extend({export function buildCommunityChannelRefExtension(opts: {candidatesRef: { current: ChannelRefCandidate[] }popupRef: { current: ChannelRefPopupState }+ onIntentRef?: { current: (() => void) | undefined }setPopup: (next: ChannelRefPopupState | ((cur: ChannelRefPopupState) => ChannelRefPopupState),) => void@@ -127,7 +128,7 @@ export function buildCommunityChannelRefExtension(opts: {// extension's `queryRef`.queryRef?: { current: string }}) {- const { candidatesRef, popupRef, setPopup, queryRef } = opts+ const { candidatesRef, popupRef, onIntentRef, setPopup, queryRef } = optsreturn ChannelRefNode.configure({HTMLAttributes: { class: "channel-ref-highlight" },@@ -158,6 +159,7 @@ export function buildCommunityChannelRefExtension(opts: {char: "/",pluginKey: new PluginKey("channelRefSuggestion"),items: ({ query }: { query: string }) => {+ onIntentRef?.current?.()if (queryRef) queryRef.current = queryreturn rankChannelRefItems(candidatesRef.current, query)},diff --git a/src/web/src/lib/community/last-channel.test.ts b/src/web/src/lib/community/last-channel.test.tsindex 07f40411f..7c634e269 100644--- a/src/web/src/lib/community/last-channel.test.ts+++ b/src/web/src/lib/community/last-channel.test.ts@@ -5,6 +5,7 @@ import {setLastChannel,clearLastChannel,pickServerLandingChannel,+ pickServerLandingHref,} from "./last-channel"describe("last-channel", () => {@@ -124,3 +125,18 @@ describe("pickServerLandingChannel", () => {expect(pickServerLandingChannel([], "post_abc")).toBe("post_abc")})})++describe("pickServerLandingHref", () => {+ it("lands directly on a remembered child thread without top-level validation", () => {+ expect(pickServerLandingHref("srv_1", ["ch_1"], "post_1")).toBe(+ "/c/channels/srv_1/post_1",+ )+ })++ it("uses a cached default leaf and only falls back to the root when none exists", () => {+ expect(pickServerLandingHref("srv_1", ["ch_1", "ch_2"], null)).toBe(+ "/c/channels/srv_1/ch_1",+ )+ expect(pickServerLandingHref("srv_1", [], null)).toBe("/c/channels/srv_1")+ })+})diff --git a/src/web/src/lib/community/last-channel.ts b/src/web/src/lib/community/last-channel.tsindex f352872f8..acbbe4c1b 100644--- a/src/web/src/lib/community/last-channel.ts+++ b/src/web/src/lib/community/last-channel.ts@@ -68,3 +68,14 @@ export function pickServerLandingChannel(if (last !== null) return lastreturn channelIds[0]}++export function pickServerLandingHref(+ serverId: string,+ channelIds: readonly string[],+ last: string | null,+): string {+ const channelId = pickServerLandingChannel(channelIds, last)+ return channelId+ ? `/c/channels/${serverId}/${channelId}`+ : `/c/channels/${serverId}`+}diff --git a/src/web/src/lib/community/navigation-intent.test.ts b/src/web/src/lib/community/navigation-intent.test.tsnew file mode 100644index 000000000..e309d6d8e--- /dev/null+++ b/src/web/src/lib/community/navigation-intent.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it, vi } from "vitest"+import {+ commitLatestNavigationIntent,+ createNavigationIntentGate,+ supersedeNavigationIntent,+} from "./navigation-intent"++describe("navigation intent gate", () => {+ it("does not let a pending server resolution overwrite a Bot DM click captured at the shell root", async () => {+ let resolveServer!: (href: string) => void+ const pendingServer = new Promise<string>((resolve) => {+ resolveServer = resolve+ })+ const push = vi.fn()+ const gate = createNavigationIntentGate()+ const navigation = commitLatestNavigationIntent(+ gate,+ () => pendingServer,+ push,+ )++ const onShellClickCapture = () => supersedeNavigationIntent(gate)+ const onBotDmClick = () => push("/c/me/dm_2")++ onShellClickCapture()+ onBotDmClick()+ resolveServer("/c/channels/server_1/channel_1")++ await expect(navigation).resolves.toBe(false)+ expect(push).toHaveBeenCalledTimes(1)+ expect(push).toHaveBeenCalledWith("/c/me/dm_2")+ })++ it("commits the latest resolved navigation", async () => {+ const push = vi.fn()+ const gate = createNavigationIntentGate()++ await expect(commitLatestNavigationIntent(+ gate,+ async () => "/c/channels/server_1/channel_1",+ push,+ )).resolves.toBe(true)++ expect(push).toHaveBeenCalledWith("/c/channels/server_1/channel_1")+ })+})diff --git a/src/web/src/lib/community/navigation-intent.ts b/src/web/src/lib/community/navigation-intent.tsnew file mode 100644index 000000000..1d033487e--- /dev/null+++ b/src/web/src/lib/community/navigation-intent.ts@@ -0,0 +1,21 @@+export type NavigationIntentGate = { revision: number }++export function createNavigationIntentGate(): NavigationIntentGate {+ return { revision: 0 }+}++export function supersedeNavigationIntent(gate: NavigationIntentGate): void {+ gate.revision += 1+}++export async function commitLatestNavigationIntent<T>(+ gate: NavigationIntentGate,+ resolve: () => Promise<T>,+ commit: (value: T) => void,+): Promise<boolean> {+ const revision = ++gate.revision+ const value = await resolve()+ if (revision !== gate.revision) return false+ commit(value)+ return true+}diff --git a/src/web/src/lib/query-keys.test.ts b/src/web/src/lib/query-keys.test.tsindex 7d2398304..b16133a67 100644--- a/src/web/src/lib/query-keys.test.ts+++ b/src/web/src/lib/query-keys.test.ts@@ -16,6 +16,11 @@ describe("communityKeys", () => {// Sample enough branches to catch a mis-rooted key.expect(communityKeys.servers()[0]).toBe("community")+ expect(communityKeys.channelRefDirectory()).toEqual([+ "community",+ "servers",+ "channel-ref-directory",+ ])expect(communityKeys.inbox()[0]).toBe("community")expect(communityKeys.friends()[0]).toBe("community")expect(communityKeys.machines()[0]).toBe("community")diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.tsindex abc1ffbba..b3caff33f 100644--- a/src/web/src/lib/query-keys.ts+++ b/src/web/src/lib/query-keys.ts@@ -18,6 +18,8 @@ export const communityKeys = {// ── Servers ──────────────────────────────────────────────────────────────servers: () => [...communityKeys.all, "servers"] as const,+ channelRefDirectory: () =>+ [...communityKeys.servers(), "channel-ref-directory"] as const,server: (serverId: string) =>[...communityKeys.servers(), serverId] as const,forumSidebarThreads: (serverId: string) =>diff --git a/src/web/src/stores/community/index.ts b/src/web/src/stores/community/index.tsindex 6fd09c144..f61c476a8 100644--- a/src/web/src/stores/community/index.ts+++ b/src/web/src/stores/community/index.ts@@ -83,6 +83,7 @@ type CommunityUiHandlers = {// clicking still scrolls to the message — the behavior the bare-`#N` pill had// before message-ref-upgrade.md removed it.jumpToSeq?: (seq: number) => void+ cancelPendingNavigation?: () => void// Navigate to a server (channelId omitted) or a channel. Registered by the// shell (shell-frame) where the router is the live App-Router instance.// Channel/server-ref pills call this INSTEAD of a subtree `useRouter()`:@@ -283,6 +284,7 @@ const stableUiHandlers: CommunityUiHandlers = {useCommunityStore.getState().uiHandlers.openProfile?.(name, e, discriminator, userId),goBackMobile: () => useCommunityStore.getState().uiHandlers.goBackMobile?.(),jumpToSeq: (seq) => useCommunityStore.getState().uiHandlers.jumpToSeq?.(seq),+ cancelPendingNavigation: () => useCommunityStore.getState().uiHandlers.cancelPendingNavigation?.(),navigate: (serverId, channelId) => useCommunityStore.getState().uiHandlers.navigate?.(serverId, channelId),openMessageContext: (target) => useCommunityStore.getState().uiHandlers.openMessageContext?.(target),}diff --git a/src/web/src/test/e2e-ui/perf/switch.perf.ts b/src/web/src/test/e2e-ui/perf/switch.perf.tsindex 23a1d48fb..906e43ed2 100644--- a/src/web/src/test/e2e-ui/perf/switch.perf.ts+++ b/src/web/src/test/e2e-ui/perf/switch.perf.ts@@ -16,9 +16,8 @@* - Against a live dev build each switch is slow (full API fan-out + paint +* reflow settle), so the matrix defaults SMALL and is env-tunable:* PERF_CHANNEL_SWITCHES (default 3), PERF_SERVER_SWITCHES (default 3).- * - The capture is flushed to switch-events.json after EVERY switch, and the- * `perf:switch` script runs the report with `;` (not `&&`), so even a- * timed-out run still produces switch-report.md from the partial capture.+ * - The capture is flushed to switch-events.json after every switch. The+ * runner clears old artifacts first and only reports a successful run.** See plans/community-switch-perf-diagnosis.md. LOCAL-ONLY — runs via* playwright.perf.config.ts, which has NO global-setup, so the stress-seeded@@ -209,6 +208,12 @@ test("community switch perceived-latency capture", async ({ browser }) => {expect(process.env.NEXT_PUBLIC_MOCK_NETWORK, "mock-network must be off").not.toBe("true")await page.goto(`${BASE_URL}/c/channels/${targetServer.id}`, { waitUntil: "commit" })+ await page.waitForURL(+ (url) =>+ url.pathname.startsWith(`/c/channels/${targetServer.id}/`) &&+ url.pathname !== `/c/channels/${targetServer.id}/`,+ { timeout: 20_000 },+ )// Prove the react-scan hook registered early enough: commit events must// actually arrive (not merely that hooks are "available").await page.waitForFunction(() => Array.isArray(window.__ALOOK_PERF__) && window.__ALOOK_PERF__.length > 0, {@@ -219,7 +224,10 @@ test("community switch perceived-latency capture", async ({ browser }) => {// Warm the LEAF routes (channel + server) so first-hit dev compile isn't// misattributed to a measured switch.- await page.goto(`${BASE_URL}/c/channels/${targetServer.id}/${channels[0].id}`, { waitUntil: "commit" })+ const firstLeaf = `${BASE_URL}/c/channels/${targetServer.id}/${channels[0].id}`+ if (page.url() !== firstLeaf) {+ await page.goto(firstLeaf, { waitUntil: "commit" })+ }await page.waitForSelector("[data-msg-id]", { timeout: 20_000 }).catch(() => {})const captured: CapturedSwitch[] = []