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(community): gate eager-read rail refetch on server mentions
Shelly#38631f96e5e9452f
diff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsxindex b8d3a53ab..142313b21 100644--- a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx@@ -399,6 +399,7 @@ function ChannelView() {// settled (fetching done; `null` = never-visited is a valid resolved state).useEagerChannelRead({channelId,+ serverId,isChildChannel,snapshotReady: !readSnapshotFetching,})diff --git a/src/web/src/hooks/community/use-eager-channel-read.test.ts b/src/web/src/hooks/community/use-eager-channel-read.test.tsnew file mode 100644index 000000000..9c9ceeb95--- /dev/null+++ b/src/web/src/hooks/community/use-eager-channel-read.test.ts@@ -0,0 +1,184 @@+/**+ * `useEagerChannelRead` — the once-per-mount "mark this channel read on open"+ * PUT, and the query invalidations that follow it.+ *+ * The vitest env is node (no jsdom), so we drive the hook through the same+ * minimal React shim the other community-hook tests use: useRef + useEffect+ * are mocked so we can flush the mount effect by hand. `apiFetch` is stubbed+ * to resolve immediately; `useQueryClient` returns a spy client so we can+ * assert exactly which query keys get invalidated after the PUT.+ *+ * The behaviour under test (WS1 rail-fan-out fix): the eager PUT must always+ * refresh `inbox()`, but must refresh the rail mention badge+ * (`server(serverId)`) ONLY when this server actually carries mentions —+ * never the whole `servers()` prefix. A plain switch into a mention-free+ * server must not trigger any server-level refetch.+ */+import { describe, it, expect, vi, beforeEach } from "vitest"+import { communityKeys } from "@/lib/query-keys"+import type { ServersResponse } from "@/hooks/community/use-servers"++// ── React shim ────────────────────────────────────────────────────────────+let refs: Map<string, { current: unknown }> = new Map()+let refCounter = 0+let pendingEffects: Array<() => void> = []++vi.mock("react", () => ({+ useRef: (initial: unknown) => {+ const id = `ref-${refCounter++}`+ if (!refs.has(id)) refs.set(id, { current: initial })+ return refs.get(id)!+ },+ useEffect: (fn: () => void, _deps: unknown[]) => {+ pendingEffects.push(fn)+ },+}))++function flushEffects() {+ const effects = pendingEffects+ pendingEffects = []+ for (const fn of effects) fn()+}++// ── apiFetch stub — the PUT resolves immediately ───────────────────────────+const apiFetchMock = vi.fn(() => Promise.resolve({}))+vi.mock("@/lib/api/client", () => ({+ apiFetch: (...args: unknown[]) => apiFetchMock(...args),+}))++// ── TanStack Query shim — a spy client with a controllable cache ───────────+let serversCache: ServersResponse | undefined+const invalidateQueries = vi.fn()+const getQueryData = vi.fn((_key: unknown) => serversCache)+vi.mock("@tanstack/react-query", () => ({+ useQueryClient: () => ({ invalidateQueries, getQueryData }),+}))++function resetHarness() {+ refs = new Map()+ refCounter = 0+ pendingEffects = []+ serversCache = undefined+ apiFetchMock.mockClear()+ invalidateQueries.mockClear()+ getQueryData.mockClear()+}++async function loadHook() {+ const mod = await import("./use-eager-channel-read")+ return mod.useEagerChannelRead+}++// Awaits the microtasks the eager PUT's `.then()` chain schedules.+const settle = () => new Promise((r) => setTimeout(r, 0))++function invalidatedKeys() {+ return invalidateQueries.mock.calls.map((c) => JSON.stringify(c[0].queryKey))+}++beforeEach(() => {+ resetHarness()+})++const server = (id: string, mentions: number) => ({+ id,+ name: id,+ initial: id[0]?.toUpperCase() ?? "?",+ active: false,+ mentions,+ icon: null,+})++describe("useEagerChannelRead — rail-badge fan-out gate", () => {+ it("fires exactly one mark-read PUT per mount", async () => {+ const useHook = await loadHook()+ useHook({+ channelId: "ch_1",+ serverId: "srv_1",+ isChildChannel: false,+ snapshotReady: true,+ })+ flushEffects()+ await settle()+ expect(apiFetchMock).toHaveBeenCalledTimes(1)+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/ch_1/read", {+ method: "PUT",+ })+ })++ it("uses the thread endpoint for a child channel", async () => {+ const useHook = await loadHook()+ useHook({+ channelId: "th_9",+ serverId: "srv_1",+ isChildChannel: true,+ snapshotReady: true,+ })+ flushEffects()+ await settle()+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/threads/th_9/read", {+ method: "PUT",+ })+ })++ it("always invalidates inbox() after the PUT", async () => {+ const useHook = await loadHook()+ serversCache = { servers: [server("srv_1", 0)] }+ useHook({+ channelId: "ch_1",+ serverId: "srv_1",+ isChildChannel: false,+ snapshotReady: true,+ })+ flushEffects()+ await settle()+ expect(invalidatedKeys()).toContain(JSON.stringify(communityKeys.inbox()))+ })++ it("does NOT refetch any server-level query when this server has no mentions", async () => {+ const useHook = await loadHook()+ serversCache = { servers: [server("srv_1", 0), server("srv_2", 5)] }+ useHook({+ channelId: "ch_1",+ serverId: "srv_1",+ isChildChannel: false,+ snapshotReady: true,+ })+ flushEffects()+ await settle()+ const keys = invalidatedKeys()+ // inbox only — no server(), no servers() cascade.+ expect(keys).toContain(JSON.stringify(communityKeys.inbox()))+ expect(keys).not.toContain(JSON.stringify(communityKeys.server("srv_1")))+ expect(keys).not.toContain(JSON.stringify(communityKeys.servers()))+ })++ it("refreshes ONLY server(serverId) — not the servers() prefix — when this server has mentions", async () => {+ const useHook = await loadHook()+ serversCache = { servers: [server("srv_1", 3)] }+ useHook({+ channelId: "ch_1",+ serverId: "srv_1",+ isChildChannel: false,+ snapshotReady: true,+ })+ flushEffects()+ await settle()+ const keys = invalidatedKeys()+ expect(keys).toContain(JSON.stringify(communityKeys.server("srv_1")))+ expect(keys).not.toContain(JSON.stringify(communityKeys.servers()))+ })++ it("does not PUT until the read-state snapshot is ready", async () => {+ const useHook = await loadHook()+ useHook({+ channelId: "ch_1",+ serverId: "srv_1",+ isChildChannel: false,+ snapshotReady: false,+ })+ flushEffects()+ await settle()+ expect(apiFetchMock).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/hooks/community/use-eager-channel-read.ts b/src/web/src/hooks/community/use-eager-channel-read.tsindex 350e48d71..e0110dc44 100644--- a/src/web/src/hooks/community/use-eager-channel-read.ts+++ b/src/web/src/hooks/community/use-eager-channel-read.ts@@ -4,6 +4,7 @@ import { useEffect, useRef } from "react"import { useQueryClient } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"+import type { ServersResponse } from "@/hooks/community/use-servers"/*** Eager "mark this channel/thread read on open."@@ -36,10 +37,12 @@ import { communityKeys } from "@/lib/query-keys"*/export function useEagerChannelRead({channelId,+ serverId,isChildChannel,snapshotReady,}: {channelId: string | null | undefined+ serverId: string | null | undefinedisChildChannel: booleansnapshotReady: boolean}) {@@ -58,12 +61,31 @@ export function useEagerChannelRead({: `/api/community/channels/${channelId}/read`void apiFetch(endpoint, { method: "PUT" }).then(() => {- // Refresh the inbox feeds and the rail badge (mention rows dropped).+ // Always refresh the inbox feeds — the mass mark-read cleared them.void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })- void queryClient.invalidateQueries({ queryKey: communityKeys.servers() })++ // The rail mention badge (`server.mentions`) only needs refreshing when+ // this server actually carries mentions the PUT may have cleared. Read+ // it from the `servers()` cache and gate on it: the common case (no+ // mentions anywhere in the server) skips the invalidate entirely, so a+ // plain channel switch no longer cascade-refetches every server-level+ // query. When there ARE mentions, refresh only `server(serverId)` — the+ // one query that feeds the badge — not the whole `servers()` prefix.+ if (!serverId) return+ const servers = queryClient.getQueryData<ServersResponse>(+ communityKeys.servers(),+ )+ const hasMentions = servers?.servers.some(+ (s) => s.id === serverId && s.mentions > 0,+ )+ if (hasMentions) {+ void queryClient.invalidateQueries({+ queryKey: communityKeys.server(serverId),+ })+ }}).catch(() => {// Silent — the watermark / WS invalidate reconciles the inbox anyway.})- }, [channelId, isChildChannel, snapshotReady, queryClient])+ }, [channelId, serverId, isChildChannel, snapshotReady, queryClient])}