Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

perf(web): dedupe community server query (#515)

Gener9b03bb8cd866
diff --git a/DESIGN.md b/DESIGN.md
index 1c20d33b8..afc5b2c8f 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -111,6 +111,15 @@ Two stages, not three. The split lives at **`640px`** — Tailwind's default `sm
| **Mobile** | `< 640px` | Single column with pathname-owned list/detail routing. Back button in detail headers. Popovers may promote to sheets when they'd overflow. |
| **Desktop** | `≥ 640px` | Multi-column shells — server rail + channel/DM sidebar + main (in community), or app sidebar + workspace (elsewhere). Hover surfaces reveal actions. No back button in headers. |
+For Community server routes, the URL owns selection and the checkpoint owns composition:
+
+| Route | Meaning | Mobile `< 640px` | Desktop `≥ 640px` |
+| --- | --- | --- | --- |
+| `/c/channels/{serverId}` | Server list/landing | Server rail + that server's channel list; no channel detail. | Server rail + channel sidebar + main landing. Replace to the remembered channel, otherwise the first top-level channel; an empty server stays on the root. |
+| `/c/channels/{serverId}/{channelId}` | Exact channel detail | Channel detail only, with Header Back to the semantic parent route. | Server rail + channel sidebar + channel detail in one frame. |
+
+Both checkpoints share the same server-scoped data model. A detail route adds channel-scoped content queries; changing checkpoint never changes the route's business meaning or creates a device-specific query contract. Header Back uses replace-style semantic navigation, while browser Back/Forward remains browser-history owned.
+
Rules:
- **Read the breakpoint, don't guess.** Use `useBreakpoint()` (string) or `useIsMobile()` (boolean) for any behavior that must branch by stage. Don't sprinkle raw `window.innerWidth` checks or ad-hoc `matchMedia` calls — they drift away from the shared boundary and re-mount without SSR safety.
- **JS and CSS boundaries are the same 640px.** Use the hook for behavior (which zone to render, whether to show a back button); use Tailwind's `sm:` prefix for pure layout fit at the mobile ↔ desktop split. Both share the same 640px pivot so a mobile page never renders desktop CSS at the same width.
diff --git a/src/web/src/app/c/channels/[serverId]/page.test.ts b/src/web/src/app/c/channels/[serverId]/page.test.ts
new file mode 100644
index 000000000..8aa31746e
--- /dev/null
+++ b/src/web/src/app/c/channels/[serverId]/page.test.ts
@@ -0,0 +1,106 @@
+import { createElement } from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import ServerDefaultPage from "./page"
+
+const mocks = vi.hoisted(() => ({
+ breakpoint: { current: "mobile" as "mobile" | "desktop" | "unknown" },
+ lastChannel: { current: null as string | null },
+ replace: vi.fn(),
+ search: { current: "" },
+ server: { current: null as null | {
+ categories: Array<{ channels: Array<{ id: string }> }>
+ } },
+}))
+
+vi.mock("next/navigation", () => ({
+ useParams: () => ({ serverId: "server_1" }),
+ useRouter: () => ({ replace: mocks.replace }),
+ useSearchParams: () => new URLSearchParams(mocks.search.current),
+}))
+vi.mock("@/hooks/community/use-servers", () => ({
+ useServer: () => ({ server: mocks.server.current }),
+}))
+vi.mock("@/hooks/use-mobile", () => ({
+ useBreakpoint: () => mocks.breakpoint.current,
+}))
+vi.mock("@/lib/community/last-channel", async () => {
+ const actual = await vi.importActual<typeof import("@/lib/community/last-channel")>(
+ "@/lib/community/last-channel",
+ )
+ return {
+ ...actual,
+ getLastChannel: () => mocks.lastChannel.current,
+ }
+})
+vi.mock("@/components/community/messages/message-list", () => ({
+ MessageList: (props: Record<string, unknown>) => createElement("message-list", props),
+}))
+vi.mock("@/components/ui/skeleton", () => ({
+ Skeleton: (props: Record<string, unknown>) => createElement("skeleton-row", props),
+}))
+
+beforeEach(() => {
+ mocks.breakpoint.current = "mobile"
+ mocks.lastChannel.current = null
+ mocks.replace.mockClear()
+ mocks.search.current = ""
+ mocks.server.current = {
+ categories: [{ channels: [{ id: "channel_1" }, { id: "channel_2" }] }],
+ }
+})
+
+describe("ServerDefaultPage checkpoint route contract", () => {
+ it("keeps the mobile server root on the list route without rendering detail", async () => {
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(ServerDefaultPage))
+ })
+
+ expect(mocks.replace).not.toHaveBeenCalled()
+ expect(renderer.toJSON()).toBeNull()
+ })
+
+ it("replaces the desktop server root with the remembered channel and preserves search", async () => {
+ mocks.breakpoint.current = "desktop"
+ mocks.lastChannel.current = "channel_2"
+ mocks.search.current = "settings=1"
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(ServerDefaultPage))
+ })
+
+ expect(mocks.replace).toHaveBeenCalledWith(
+ "/c/channels/server_1/channel_2?settings=1",
+ )
+ expect(renderer.root.findAllByType("message-list")).toHaveLength(1)
+ })
+
+ it("falls back to the first top-level channel on desktop", async () => {
+ mocks.breakpoint.current = "desktop"
+
+ await act(async () => {
+ TestRenderer.create(createElement(ServerDefaultPage))
+ })
+
+ expect(mocks.replace).toHaveBeenCalledWith(
+ "/c/channels/server_1/channel_1",
+ )
+ })
+
+ it("keeps an empty desktop server on its root with an empty state", async () => {
+ mocks.breakpoint.current = "desktop"
+ mocks.server.current = { categories: [{ channels: [] }] }
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(ServerDefaultPage))
+ })
+
+ expect(mocks.replace).not.toHaveBeenCalled()
+ expect(renderer.root.findAllByType("message-list")).toHaveLength(0)
+ expect(renderer.root.findAllByType("span").map((node) => node.children.join(" "))).toEqual([
+ "No channels yet",
+ "Create a channel from the sidebar to get started.",
+ ])
+ })
+})
diff --git a/src/web/src/components/community/shell/shell-frame-view.test.ts b/src/web/src/components/community/shell/shell-frame-view.test.ts
index 374643079..fdd588294 100644
--- a/src/web/src/components/community/shell/shell-frame-view.test.ts
+++ b/src/web/src/components/community/shell/shell-frame-view.test.ts
@@ -141,6 +141,30 @@ describe("ShellFrameView", () => {
expect(mocks.disconnect).toHaveBeenCalledTimes(1)
})
+ it("composes the server-root list surface with desktop rail, sidebar, and landing content", async () => {
+ const sidebar = vi.fn(() => createElement("sidebar-content"))
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(ShellFrameView, {
+ breakpoint: "desktop",
+ surface: "list",
+ navigationPending: false,
+ sidebar,
+ cancelPendingNavigation: vi.fn(),
+ rail,
+ profile,
+ inbox,
+ }, createElement("main-content")), { createNodeMock: () => ({ offsetWidth: 240 }) })
+ })
+
+ expect(renderer.root.findAllByType("server-rail")).toHaveLength(1)
+ expect(renderer.root.findAllByType("sidebar-content")).toHaveLength(1)
+ expect(renderer.root.findAllByType("main-content")).toHaveLength(1)
+ expect(sidebar).toHaveBeenCalledWith()
+
+ await act(async () => renderer.unmount())
+ })
+
it("keeps mobile nav and messages branches distinct and omits status seeds", async () => {
const sidebar = vi.fn(() => createElement("sidebar-content"))
let renderer!: TestRenderer.ReactTestRenderer
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 389358aec..33946c695 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
@@ -84,7 +84,7 @@ export function useShellRailController({
try {
await queryClient.fetchQuery({
queryKey: communityKeys.server(id),
- queryFn: serverQueryFn(id),
+ queryFn: serverQueryFn(queryClient, id),
staleTime: Infinity,
})
} catch {
diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts
index 049af6baf..431083629 100644
--- a/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts
@@ -24,7 +24,7 @@ beforeEach(resetCommunityWsHarness)
afterEach(cleanupCommunityWsHarness)
describe("useCommunityWs — server.update patches server + list caches", () => {
- it("applies name change to server(id) and servers()", async () => {
+ it("applies name and description changes to server(id) and servers()", async () => {
await mountHook()
capturedQueryClient.setQueryData(communityKeys.server("srv_1"), {
id: "srv_1",
@@ -39,6 +39,7 @@ describe("useCommunityWs — server.update patches server + list caches", () =>
{
id: "srv_1",
name: "old",
+ description: "old description",
initial: "O",
active: false,
unread: false,
@@ -49,17 +50,22 @@ describe("useCommunityWs — server.update patches server + list caches", () =>
const event: CommunityServerUpdate = {
type: "community:server.update",
serverId: "srv_1",
- changes: { name: "new" },
+ changes: { name: "new", description: "new description" },
}
capturedOnMessage!(event)
- expect(capturedQueryClient.getQueryData<{ name: string }>(communityKeys.server("srv_1"))).toMatchObject({
+ expect(capturedQueryClient.getQueryData<{ name: string; description: string }>(
+ communityKeys.server("srv_1"),
+ )).toMatchObject({
name: "new",
+ description: "new description",
})
expect(
- capturedQueryClient.getQueryData<{ servers: { name: string; initial: string }[] }>(
+ capturedQueryClient.getQueryData<{
+ servers: { name: string; description: string; initial: string }[]
+ }>(
communityKeys.servers(),
)?.servers[0],
- ).toMatchObject({ name: "new", initial: "N" })
+ ).toMatchObject({ name: "new", description: "new description", initial: "N" })
})
})
describe("useCommunityWs — child channel events", () => {
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.ts
index 5ee0550b8..524e04d4b 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
@@ -271,6 +271,7 @@ export function handleServerUpdate(
? {
...s,
...(event.changes.name ? { name: event.changes.name, initial: avatarInitial(event.changes.name) } : {}),
+ ...(event.changes.description !== undefined ? { description: event.changes.description } : {}),
...(event.changes.icon !== undefined ? { icon: event.changes.icon ?? null } : {}),
}
: s,
diff --git a/src/web/src/hooks/community/mutations/servers.test.ts b/src/web/src/hooks/community/mutations/servers.test.ts
index 754f5b8df..7cea40971 100644
--- a/src/web/src/hooks/community/mutations/servers.test.ts
+++ b/src/web/src/hooks/community/mutations/servers.test.ts
@@ -139,7 +139,15 @@ describe("useUpdateServer — rollback on both caches", () => {
})
capturedQc.setQueryData(communityKeys.servers(), {
servers: [
- { id: "srv_1", name: "old", initial: "O", active: false, unread: false, mentions: 0 },
+ {
+ id: "srv_1",
+ name: "old",
+ description: "d",
+ initial: "O",
+ active: false,
+ unread: false,
+ mentions: 0,
+ },
],
})
apiFetchMock.mockRejectedValueOnce(new Error("boom"))
@@ -148,8 +156,71 @@ describe("useUpdateServer — rollback on both caches", () => {
await runMutation({ serverId: "srv_1", name: "new", description: "d2" }).catch(() => {})
const detail = capturedQc.getQueryData<{ name: string }>(communityKeys.server("srv_1"))
expect(detail?.name).toBe("old")
- const list = capturedQc.getQueryData<{ servers: { name: string }[] }>(communityKeys.servers())
- expect(list?.servers[0].name).toBe("old")
+ const list = capturedQc.getQueryData<{ servers: { name: string; description: string }[] }>(
+ communityKeys.servers(),
+ )
+ expect(list?.servers[0]).toMatchObject({ name: "old", description: "d" })
+ })
+
+ it("keeps the canonical list metadata aligned with an optimistic detail update", async () => {
+ const untouchedServer = {
+ id: "srv_2",
+ name: "untouched",
+ description: "unchanged description",
+ initial: "U",
+ active: false,
+ mentions: 4,
+ }
+ capturedQc.setQueryData(communityKeys.server("srv_1"), {
+ id: "srv_1",
+ name: "old",
+ description: "old description",
+ icon: null,
+ ownerId: "u_1",
+ categories: [],
+ })
+ capturedQc.setQueryData(communityKeys.servers(), {
+ servers: [
+ {
+ id: "srv_1",
+ name: "old",
+ description: "old description",
+ initial: "O",
+ active: false,
+ mentions: 0,
+ },
+ untouchedServer,
+ ],
+ })
+ apiFetchMock.mockResolvedValueOnce(undefined)
+ const mod = await load()
+ mod.useUpdateServer()
+
+ await runMutation({
+ serverId: "srv_1",
+ name: "new",
+ description: "new description",
+ })
+
+ expect(capturedQc.getQueryData(communityKeys.server("srv_1"))).toMatchObject({
+ name: "new",
+ description: "new description",
+ })
+ const list = capturedQc.getQueryData<{
+ servers: Array<{ name: string; description: string; initial: string; mentions: number }>
+ }>(communityKeys.servers())?.servers
+ expect(list?.[0]).toMatchObject({
+ name: "new",
+ description: "new description",
+ initial: "N",
+ })
+ expect(list?.[1]).toBe(untouchedServer)
+ expect(list?.[1]).toMatchObject({
+ name: "untouched",
+ description: "unchanged description",
+ initial: "U",
+ mentions: 4,
+ })
})
it("invalidates the channel-ref directory after settling", async () => {
diff --git a/src/web/src/hooks/community/mutations/servers.ts b/src/web/src/hooks/community/mutations/servers.ts
index 007f61a2f..b1c733687 100644
--- a/src/web/src/hooks/community/mutations/servers.ts
+++ b/src/web/src/hooks/community/mutations/servers.ts
@@ -177,7 +177,14 @@ export function useUpdateServer() {
? {
...prev,
servers: prev.servers.map((s) =>
- s.id === args.serverId ? { ...s, name: args.name, initial: avatarInitial(args.name) } : s,
+ s.id === args.serverId
+ ? {
+ ...s,
+ name: args.name,
+ description: args.description,
+ initial: avatarInitial(args.name),
+ }
+ : s,
),
}
: prev,
diff --git a/src/web/src/hooks/community/use-servers.test.ts b/src/web/src/hooks/community/use-servers.test.ts
index d7ff40e5c..88c4ab5d3 100644
--- a/src/web/src/hooks/community/use-servers.test.ts
+++ b/src/web/src/hooks/community/use-servers.test.ts
@@ -7,15 +7,44 @@ vi.mock("@/lib/api/client", () => ({
apiFetch: (...args: unknown[]) => apiFetchMock(...args),
}))
+type CapturedQueryConfig = {
+ enabled?: boolean
+ queryFn?: () => unknown
+}
+let capturedQueryConfig: CapturedQueryConfig | null = null
+let capturedHookQueryClient: QueryClient
+vi.mock("@tanstack/react-query", async () => {
+ const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query")
+ return {
+ ...actual,
+ useQueryClient: () => capturedHookQueryClient,
+ useQuery: (config: CapturedQueryConfig) => {
+ capturedQueryConfig = config
+ return { data: undefined }
+ },
+ }
+})
+
beforeEach(() => {
apiFetchMock.mockReset()
+ capturedQueryConfig = null
+ capturedHookQueryClient = new QueryClient()
})
describe("useServers / serversQueryFn", () => {
it("materialises raw server rows into render-ready Server shape", async () => {
apiFetchMock.mockResolvedValueOnce({
servers: [
- { id: "srv_1", name: "Alook", discriminator: "0042", icon: null, role: "owner", mentions: 3 },
+ {
+ id: "srv_1",
+ name: "Alook",
+ discriminator: "0042",
+ description: "Build together",
+ icon: null,
+ ownerId: "u_1",
+ role: "owner",
+ mentions: 3,
+ },
{ id: "srv_2", name: "Beta", discriminator: "12345", icon: null, role: "member" },
],
})
@@ -27,6 +56,8 @@ describe("useServers / serversQueryFn", () => {
expect(data.servers[0].mentions).toBe(3)
expect(data.servers[0].active).toBe(false)
expect(data.servers[0].discriminator).toBe("0042")
+ expect(data.servers[0].description).toBe("Build together")
+ expect(data.servers[0].ownerId).toBe("u_1")
// `unread` has been removed from the Server type — the mapper must not
// project it. Pin the invariant so a future revival gets caught.
expect((data.servers[0] as { unread?: boolean }).unread).toBeUndefined()
@@ -59,6 +90,18 @@ describe("useServers / serversQueryFn", () => {
})
describe("useServer / serverQueryFn", () => {
+ it("keeps the null-server query disabled without issuing API requests", async () => {
+ const { useServer } = await import("./use-servers")
+
+ useServer(null)
+
+ expect(capturedQueryConfig?.enabled).toBe(false)
+ const disabledQueryFn = capturedQueryConfig?.queryFn
+ expect(disabledQueryFn).toBeTypeOf("function")
+ await expect(disabledQueryFn?.()).rejects.toThrow("disabled")
+ expect(apiFetchMock).not.toHaveBeenCalled()
+ })
+
it("composes a single server detail from canonical resources", async () => {
const detail = { id: "srv_1", name: "Alook", description: "", icon: null, ownerId: "u_1" }
apiFetchMock.mockImplementation(async (url: string) => {
@@ -72,7 +115,7 @@ describe("useServer / serverQueryFn", () => {
throw new Error(`unexpected ${url}`)
})
const { serverQueryFn } = await import("./use-servers")
- const data = await serverQueryFn("srv_1")()
+ const data = await serverQueryFn(new QueryClient(), "srv_1")()
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers")
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers/srv_1/categories")
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers/srv_1/channels")
@@ -83,6 +126,77 @@ describe("useServer / serverQueryFn", () => {
], forumUnreadState: {} })
})
+ it("joins the canonical servers request on cold concurrency and reuses warm caches", async () => {
+ let releaseServers!: (value: {
+ servers: Array<{
+ id: string
+ name: string
+ discriminator: string
+ description: string
+ icon: null
+ ownerId: string
+ }>
+ }) => void
+ const pendingServers = new Promise<Parameters<typeof releaseServers>[0]>((resolve) => {
+ releaseServers = resolve
+ })
+ apiFetchMock.mockImplementation(async (url: string) => {
+ if (url === "/api/community/servers") return pendingServers
+ if (url.endsWith("/categories")) return { categories: [] }
+ if (url.endsWith("/channels")) return { channels: [] }
+ if (url.endsWith("/unreads")) return { channelIds: [] }
+ throw new Error(`unexpected ${url}`)
+ })
+ const { serverQueryFn, serversQueryFn } = await import("./use-servers")
+ const qc = new QueryClient()
+ const list = qc.fetchQuery({
+ queryKey: communityKeys.servers(),
+ queryFn: serversQueryFn,
+ staleTime: Infinity,
+ })
+ const detail = qc.fetchQuery({
+ queryKey: communityKeys.server("srv_1"),
+ queryFn: serverQueryFn(qc, "srv_1"),
+ staleTime: Infinity,
+ })
+
+ await vi.waitFor(() => {
+ expect(apiFetchMock.mock.calls.filter(([url]) => url === "/api/community/servers")).toHaveLength(1)
+ })
+ releaseServers({
+ servers: [{
+ id: "srv_1",
+ name: "Alook",
+ discriminator: "0001",
+ description: "Build together",
+ icon: null,
+ ownerId: "u_1",
+ }],
+ })
+ await Promise.all([list, detail])
+ expect(apiFetchMock).toHaveBeenCalledTimes(4)
+ for (const resource of ["categories", "channels", "unreads"]) {
+ expect(apiFetchMock.mock.calls.filter(
+ ([url]) => url === `/api/community/servers/srv_1/${resource}`,
+ )).toHaveLength(1)
+ }
+
+ apiFetchMock.mockClear()
+ await Promise.all([
+ qc.fetchQuery({
+ queryKey: communityKeys.servers(),
+ queryFn: serversQueryFn,
+ staleTime: Infinity,
+ }),
+ qc.fetchQuery({
+ queryKey: communityKeys.server("srv_1"),
+ queryFn: serverQueryFn(qc, "srv_1"),
+ staleTime: Infinity,
+ }),
+ ])
+ expect(apiFetchMock).not.toHaveBeenCalled()
+ })
+
it("cold-boots a forum fallback from a canonical unread child outside the sidebar projection", async () => {
apiFetchMock.mockImplementation(async (url: string) => {
if (url === "/api/community/servers") return { servers: [{
@@ -100,7 +214,7 @@ describe("useServer / serverQueryFn", () => {
})
const { serverQueryFn } = await import("./use-servers")
- const data = await serverQueryFn("srv_1")()
+ const data = await serverQueryFn(new QueryClient(), "srv_1")()
expect(data.categories[0]?.channels[0]?.unread).toBe(true)
expect(data.forumUnreadState).toEqual({
@@ -120,11 +234,20 @@ describe("useServer / serverQueryFn", () => {
const { serverQueryFn } = await import("./use-servers")
const qc = new QueryClient()
const key = communityKeys.server("srv_1")
- await qc.fetchQuery({ queryKey: key, queryFn: serverQueryFn("srv_1") })
+ await qc.fetchQuery({ queryKey: key, queryFn: serverQueryFn(qc, "srv_1") })
expect(qc.getQueryData(key)).toBeDefined()
// Invalidating the servers() prefix invalidates the detail entry too.
await qc.invalidateQueries({ queryKey: communityKeys.servers() })
expect(qc.getQueryState(key)?.isInvalidated).toBe(true)
+
+ apiFetchMock.mockClear()
+ await qc.fetchQuery({
+ queryKey: key,
+ queryFn: serverQueryFn(qc, "srv_1"),
+ staleTime: Infinity,
+ })
+ expect(apiFetchMock.mock.calls.filter(([url]) => url === "/api/community/servers")).toHaveLength(1)
+ expect(apiFetchMock).toHaveBeenCalledTimes(4)
})
it("rejects a stale raw unread read instead of caching false read badges", async () => {
@@ -137,6 +260,6 @@ describe("useServer / serverQueryFn", () => {
})
const { serverQueryFn } = await import("./use-servers")
- await expect(serverQueryFn("srv_1")()).rejects.toThrow("stale D1 read")
+ await expect(serverQueryFn(new QueryClient(), "srv_1")()).rejects.toThrow("stale D1 read")
})
})
diff --git a/src/web/src/hooks/community/use-servers.ts b/src/web/src/hooks/community/use-servers.ts
index 0b75532e2..a6df42fa8 100644
--- a/src/web/src/hooks/community/use-servers.ts
+++ b/src/web/src/hooks/community/use-servers.ts
@@ -1,6 +1,11 @@
"use client"
-import { useQuery, type UseQueryResult } from "@tanstack/react-query"
+import {
+ useQuery,
+ useQueryClient,
+ type QueryClient,
+ type UseQueryResult,
+} from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import { avatarInitial } from "@/lib/community/avatar"
@@ -40,6 +45,8 @@ export const serversQueryFn = async (): Promise<ServersResponse> => {
id: s.id,
name: s.name,
discriminator: s.discriminator,
+ description: s.description ?? "",
+ ownerId: s.ownerId,
initial: avatarInitial(s.name),
active: false,
// Defensive fallback: the API always projects `mentions` now, but during
@@ -52,12 +59,19 @@ export const serversQueryFn = async (): Promise<ServersResponse> => {
return { servers }
}
+function serversQueryOptions() {
+ return {
+ queryKey: communityKeys.servers(),
+ queryFn: serversQueryFn,
+ staleTime: Infinity,
+ } as const
+}
+
export function useServers(): UseQueryResult<ServersResponse> & {
servers: Server[]
} {
const query = useQuery({
- queryKey: communityKeys.servers(),
- queryFn: serversQueryFn,
+ ...serversQueryOptions(),
// WS-maintained like the other server-scoped queries: server.update
// live-patches this list (name/icon) and mention/member events invalidate
// it to refresh counts. So a remount doesn't need to refetch — this is a
@@ -104,9 +118,12 @@ type UnreadResponse = {
childChannels?: Array<{ id: string; parentChannelId: string }>
}
-export const serverQueryFn = (serverId: string) => async (): Promise<ServerDetail> => {
+export const serverQueryFn = (
+ queryClient: QueryClient,
+ serverId: string,
+) => async (): Promise<ServerDetail> => {
const [serverData, categoryData, channelData, unreadData] = await Promise.all([
- apiFetch<{ servers: RawServerRow[] }>("/api/community/servers"),
+ queryClient.fetchQuery(serversQueryOptions()),
apiFetch<{ categories: Array<Omit<Category, "channels"> & { serverId?: string }> }>(`/api/community/servers/${serverId}/categories`),
apiFetch<{ channels: RawChannel[] }>(`/api/community/servers/${serverId}/channels`),
apiFetch<UnreadResponse>(`/api/community/servers/${serverId}/unreads`),
@@ -150,10 +167,10 @@ export const serverQueryFn = (serverId: string) => async (): Promise<ServerDetai
return {
id: server.id,
name: server.name,
- discriminator: server.discriminator,
+ discriminator: server.discriminator ?? "",
description: server.description ?? "",
- icon: server.icon,
- ownerId: server.ownerId,
+ icon: server.icon ?? null,
+ ownerId: server.ownerId ?? "",
categories,
forumUnreadState,
}
@@ -167,10 +184,13 @@ export const serverQueryFn = (serverId: string) => async (): Promise<ServerDetai
export function useServer(
serverId: string | null,
): UseQueryResult<ServerDetail> & { server: ServerDetail | null } {
+ const queryClient = useQueryClient()
const enabled = !!serverId
const query = useQuery({
queryKey: enabled ? communityKeys.server(serverId!) : communityKeys.server("__none__"),
- queryFn: enabled ? serverQueryFn(serverId!) : (() => Promise.reject(new Error("disabled"))),
+ queryFn: enabled
+ ? serverQueryFn(queryClient, serverId!)
+ : (() => Promise.reject(new Error("disabled"))),
enabled,
// WS events (member.*, channel/category changes) live-patch this
// ServerDetail cache, so a remount doesn't need to refetch — this is a
diff --git a/src/web/src/lib/community/models/navigation.ts b/src/web/src/lib/community/models/navigation.ts
index ea45b2d13..0c9f93ffd 100644
--- a/src/web/src/lib/community/models/navigation.ts
+++ b/src/web/src/lib/community/models/navigation.ts
@@ -7,6 +7,8 @@ export type Server = {
id: string // nanoid
name: string
discriminator?: string
+ description?: string
+ ownerId?: string
initial: string
active: boolean
mentions: number