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
fix(web): unify account unread projection (#708)
Generf9e40247b8af
diff --git a/src/web/src/app/api/community/users/me/inbox/mentions/route.test.ts b/src/web/src/app/api/community/users/me/inbox/mentions/route.test.tsindex 8b5cc346e..e4e2c6ca2 100644--- a/src/web/src/app/api/community/users/me/inbox/mentions/route.test.ts+++ b/src/web/src/app/api/community/users/me/inbox/mentions/route.test.ts@@ -73,7 +73,12 @@ describe("GET /api/community/users/me/inbox/mentions", () => {author: { id: "u-alice", name: "Alice", email: "[email protected]", image: null },},])- mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "general", serverId: "s1" }])+ mockGetChannelsByIds.mockResolvedValue([{+ id: "c1",+ name: "general",+ serverId: "s1",+ parentChannelId: "forum-1",+ }])mockGetServersByIds.mockResolvedValue([{ id: "s1", name: "Server 1" }])const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/mentions"))@@ -86,6 +91,7 @@ describe("GET /api/community/users/me/inbox/mentions", () => {serverId: "s1",channel: "general",channelId: "c1",+ parentChannelId: "forum-1",// authorId is the beam-avatar seed the inbox popover renders from// (<Avatar seed={mn.m.authorId}>) — omitting it blanked image-less// authors' avatars, same bug the pins route had.diff --git a/src/web/src/app/api/community/users/me/inbox/mentions/route.ts b/src/web/src/app/api/community/users/me/inbox/mentions/route.tsindex 3b84b2565..9d8bb2111 100644--- a/src/web/src/app/api/community/users/me/inbox/mentions/route.ts+++ b/src/web/src/app/api/community/users/me/inbox/mentions/route.ts@@ -71,6 +71,7 @@ export const GET = withAuth(async (req, ctx) => {serverId: ch?.serverId,channel: ch ? ch.name : "Unknown",channelId: row.message.channelId,+ parentChannelId: ch?.parentChannelId ?? null,m: {id: row.message.id,seq: row.message.seq,diff --git a/src/web/src/app/api/community/users/me/inbox/unreads/route.ts b/src/web/src/app/api/community/users/me/inbox/unreads/route.tsindex 41bb1cfed..c18604dd8 100644--- a/src/web/src/app/api/community/users/me/inbox/unreads/route.ts+++ b/src/web/src/app/api/community/users/me/inbox/unreads/route.ts@@ -108,6 +108,7 @@ export const GET = withAuth(async (req, ctx) => {lastMessageAt: stringmentionCount: numberlastUnreadSeq: number+ lastAttentionSeq: number | nullopenerMessageId?: stringparentChannelId?: stringopenerSeq?: number@@ -125,6 +126,7 @@ export const GET = withAuth(async (req, ctx) => {lastMessageAt: stringmentionCount: numberlastUnreadSeq: number+ lastAttentionSeq: number | nullhasDirectUnread: booleanchildren: UnreadChild[]}@@ -144,6 +146,7 @@ export const GET = withAuth(async (req, ctx) => {lastMessageAt: row.lastMessageAt,mentionCount: row.mentionCount,lastUnreadSeq: row.lastUnreadSeq,+ lastAttentionSeq: row.lastAttentionSeq,sortSeq: 0,sortId: row.channelId,})@@ -158,6 +161,7 @@ export const GET = withAuth(async (req, ctx) => {lastMessageAt: row.lastMessageAt,mentionCount: row.mentionCount,lastUnreadSeq: row.lastUnreadSeq,+ lastAttentionSeq: row.lastAttentionSeq,hasDirectUnread: true,children: [],})@@ -198,6 +202,7 @@ export const GET = withAuth(async (req, ctx) => {lastMessageAt: opener.createdAt,mentionCount: unreadChild?.mentionCount ?? 0,lastUnreadSeq: Math.max(unreadChild?.lastUnreadSeq ?? 0, opener.openerSeq),+ lastAttentionSeq: unreadChild?.lastAttentionSeq ?? null,parentChannelId: opener.parentChannelId,openerMessageId: opener.openerMessageId,openerSeq: opener.openerSeq,@@ -235,6 +240,7 @@ export const GET = withAuth(async (req, ctx) => {lastMessageAt: "",mentionCount: 0,lastUnreadSeq: 0,+ lastAttentionSeq: null,hasDirectUnread: false,children: [],})@@ -298,6 +304,7 @@ export const GET = withAuth(async (req, ctx) => {lastMessageAt: c.lastMessageAt,mentionCount: c.mentionCount,lastUnreadSeq: c.lastUnreadSeq,+ lastAttentionSeq: c.lastAttentionSeq,hasDirectUnread: c.hasDirectUnread,children: c.children.map((k) => ({channelId: k.channelId,@@ -306,6 +313,7 @@ export const GET = withAuth(async (req, ctx) => {lastMessageAt: k.lastMessageAt,mentionCount: k.mentionCount,lastUnreadSeq: k.lastUnreadSeq,+ lastAttentionSeq: k.lastAttentionSeq,...(k.parentChannelId ? { parentChannelId: k.parentChannelId } : {}),...(k.openerMessageId ? { openerMessageId: k.openerMessageId } : {}),...(k.openerSeq !== undefined ? { openerSeq: k.openerSeq } : {}),diff --git a/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.test.ts b/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.test.tsindex fe54761f2..f04f5300c 100644--- a/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.test.ts+++ b/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.test.ts@@ -58,9 +58,10 @@ describe("human DM notification settings", () => {userId: "user_1", channelId: "dm_1", level: "mentions", actorKind: "human",})expect(broadcastToUserSafe).toHaveBeenCalledWith("user_1", {- type: "community:read_state.advanced",+ type: "community:inbox.changed",revision: 2,inboxChanged: true,+ reason: "notification_policy",})})@@ -77,9 +78,10 @@ describe("human DM notification settings", () => {actorKind: "human",})expect(broadcastToUserSafe).toHaveBeenCalledWith("user_1", {- type: "community:read_state.advanced",+ type: "community:inbox.changed",revision: 3,inboxChanged: true,+ reason: "notification_policy",})})})diff --git a/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.ts b/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.tsindex 5e097a0a0..ea8284c34 100644--- a/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.ts+++ b/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.ts@@ -8,9 +8,10 @@ import { broadcastToUserSafe } from "@/lib/community/fanout"async function broadcastRevision(userId: string, revision: number) {await broadcastToUserSafe(userId, {- type: WS_EVENTS.READ_STATE_ADVANCED,+ type: WS_EVENTS.INBOX_CHANGED,revision,inboxChanged: true,+ reason: "notification_policy",})}diff --git a/src/web/src/app/api/community/users/me/notifications/server/[id]/route.test.ts b/src/web/src/app/api/community/users/me/notifications/server/[id]/route.test.tsindex 60ba448e6..d6bffe552 100644--- a/src/web/src/app/api/community/users/me/notifications/server/[id]/route.test.ts+++ b/src/web/src/app/api/community/users/me/notifications/server/[id]/route.test.ts@@ -58,9 +58,10 @@ describe("human server notification settings", () => {actorKind: "human",})expect(broadcastToUserSafe).toHaveBeenCalledWith("user_1", {- type: "community:read_state.advanced",+ type: "community:inbox.changed",revision: 7,inboxChanged: true,+ reason: "notification_policy",})})})diff --git a/src/web/src/app/api/community/users/me/notifications/server/[id]/route.ts b/src/web/src/app/api/community/users/me/notifications/server/[id]/route.tsindex cd836c56a..0f0b36aeb 100644--- a/src/web/src/app/api/community/users/me/notifications/server/[id]/route.ts+++ b/src/web/src/app/api/community/users/me/notifications/server/[id]/route.ts@@ -33,9 +33,10 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {})if (result.readStateRevision !== null) {await broadcastToUserSafe(ctx.userId, {- type: WS_EVENTS.READ_STATE_ADVANCED,+ type: WS_EVENTS.INBOX_CHANGED,revision: result.readStateRevision,inboxChanged: true,+ reason: "notification_policy",})}diff --git a/src/web/src/app/c/QueryProvider.test.ts b/src/web/src/app/c/QueryProvider.test.tsindex 86bc2ee51..f82028496 100644--- a/src/web/src/app/c/QueryProvider.test.ts+++ b/src/web/src/app/c/QueryProvider.test.ts@@ -2,10 +2,19 @@ import { beforeEach, describe, expect, it, vi } from "vitest"import React from "react"import TestRenderer, { act } from "react-test-renderer"import { useCommunityWsStore } from "@/stores/community/ws"+import { communityKeys } from "@/lib/query-keys"-const queryClient = vi.hoisted(() => ({ id: "query-client" }))+const queryClient = vi.hoisted(() => ({+ id: "query-client",+ invalidateQueries: vi.fn(() => Promise.resolve()),+}))const createQueryClient = vi.hoisted(() => vi.fn(() => queryClient))const seedPersistedMessageProfiles = vi.hoisted(() => vi.fn())+const setReconcileScheduler = vi.hoisted(() => vi.fn())+const getAccountUnreadProjection = vi.hoisted(() => vi.fn(() => ({+ setReconcileScheduler,+})))+const disposeAccountUnreadProjection = vi.hoisted(() => vi.fn())vi.mock("@tanstack/react-query-devtools", () => ({ ReactQueryDevtools: () => null }))vi.mock("@tanstack/react-query-persist-client", async () => {@@ -36,8 +45,8 @@ vi.mock("@/hooks/community/community-ws/read-state-reconciliation", () => ({}))vi.mock("@/hooks/community/read-coordinator", () => ({ disposeReadCoordinator: vi.fn() }))vi.mock("@/hooks/community/account-unread-projection", () => ({- disposeAccountUnreadProjection: vi.fn(),- getAccountUnreadProjection: vi.fn(),+ disposeAccountUnreadProjection,+ getAccountUnreadProjection,}))import { QueryProvider } from "./QueryProvider"@@ -49,6 +58,10 @@ beforeEach(() => {useCommunityWsStore.getState().reset()createQueryClient.mockClear()seedPersistedMessageProfiles.mockClear()+ setReconcileScheduler.mockClear()+ getAccountUnreadProjection.mockClear()+ disposeAccountUnreadProjection.mockClear()+ queryClient.invalidateQueries.mockClear()})describe("QueryProvider profile account lifecycle", () => {@@ -93,4 +106,44 @@ describe("QueryProvider profile account lifecycle", () => {expect(seedPersistedMessageProfiles).toHaveBeenCalledWith(queryClient, expectedSnapshot)act(() => renderer.unmount())})++ it("routes projection reconciliation through the canonical source prefixes", async () => {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(+ QueryProvider,+ { userId: "viewer-c" },+ React.createElement("span", null, "content"),+ ))+ })++ expect(getAccountUnreadProjection).toHaveBeenCalledWith(queryClient, "viewer-c")+ const reconcile = setReconcileScheduler.mock.calls.at(-1)?.[0]+ expect(reconcile).toBeTypeOf("function")+ await act(async () => reconcile())+ expect(queryClient.invalidateQueries).toHaveBeenCalledWith({+ queryKey: communityKeys.inboxUnreads(),+ exact: true,+ })+ expect(queryClient.invalidateQueries).toHaveBeenCalledWith({+ queryKey: communityKeys.inboxMentions(),+ exact: true,+ })+ expect(queryClient.invalidateQueries).toHaveBeenCalledWith({+ queryKey: communityKeys.dms(),+ exact: true,+ })+ expect(queryClient.invalidateQueries).toHaveBeenCalledWith({+ queryKey: communityKeys.servers(),+ exact: true,+ })+ const detailPredicate = queryClient.invalidateQueries.mock.calls+ .map(([filters]) => filters.predicate)+ .find((predicate) => typeof predicate === "function")+ expect(detailPredicate).toBeTypeOf("function")+ expect(detailPredicate({ queryKey: communityKeys.server("server-1") })).toBe(true)+ expect(detailPredicate({ queryKey: communityKeys.members("server-1") })).toBe(false)+ expect(detailPredicate({ queryKey: communityKeys.channelRefDirectory() })).toBe(false)+ act(() => renderer.unmount())+ })})diff --git a/src/web/src/app/c/QueryProvider.tsx b/src/web/src/app/c/QueryProvider.tsxindex 36d03dc22..6c0ebd783 100644--- a/src/web/src/app/c/QueryProvider.tsx+++ b/src/web/src/app/c/QueryProvider.tsx@@ -1,6 +1,6 @@"use client"-import { useEffect, useRef, useState, type ReactNode } from "react"+import { useEffect, useMemo, useRef, useState, type ReactNode } from "react"import { ReactQueryDevtools } from "@tanstack/react-query-devtools"import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client"import { createQueryClient } from "@/lib/query-client"@@ -18,6 +18,7 @@ import {disposeAccountUnreadProjection,getAccountUnreadProjection,} from "@/hooks/community/account-unread-projection"+import { communityKeys } from "@/lib/query-keys"/*** Owns the TanStack QueryClient for the community subtree.@@ -44,7 +45,34 @@ export function QueryProvider({() => useCommunityWsStore.getState().beginProfileSnapshot(),)const [queryClient] = useState(() => createQueryClient())- if (userId) getAccountUnreadProjection(queryClient, userId)+ const unreadProjection = useMemo(+ () => userId ? getAccountUnreadProjection(queryClient, userId) : null,+ [queryClient, userId],+ )+ useEffect(() => {+ if (!unreadProjection) return+ unreadProjection.setReconcileScheduler(() => {+ void queryClient.invalidateQueries({+ queryKey: communityKeys.inboxUnreads(),+ exact: true,+ })+ void queryClient.invalidateQueries({+ queryKey: communityKeys.inboxMentions(),+ exact: true,+ })+ void queryClient.invalidateQueries({ queryKey: communityKeys.dms(), exact: true })+ void queryClient.invalidateQueries({ queryKey: communityKeys.servers(), exact: true })+ void queryClient.invalidateQueries({+ predicate: ({ queryKey }) => (+ queryKey.length === 3+ && queryKey[0] === communityKeys.all[0]+ && queryKey[1] === communityKeys.servers()[1]+ && queryKey[2] !== communityKeys.channelRefDirectory()[2]+ ),+ })+ })+ return () => unreadProjection.setReconcileScheduler(null)+ }, [queryClient, unreadProjection])// Persister is bound to the userId at construction; on account switch the// whole community subtree unmounts and the shell re-renders with the new// id, so we don't need to reactively rebuild the persister mid-session.diff --git a/src/web/src/app/c/community-shell.identity.test.ts b/src/web/src/app/c/community-shell.identity.test.tsindex c7599703a..d3f44042a 100644--- a/src/web/src/app/c/community-shell.identity.test.ts+++ b/src/web/src/app/c/community-shell.identity.test.ts@@ -14,6 +14,7 @@ let activeUser: TestUser = { id: "user-a", name: "A", email: "[email protected]", avlet providerInstance = 0const renderedProviders: Array<{ userId: string | null; instance: number }> = []const apiFetchProfiles = vi.hoisted(() => vi.fn(() => Promise.resolve({})))+const useNotificationSettings = vi.hoisted(() => vi.fn(() => ({ data: undefined })))vi.mock("./QueryProvider", () => ({QueryProvider: ({ children, userId }: { children: React.ReactNode; userId: string | null }) => {@@ -27,6 +28,7 @@ vi.mock("@/contexts/community/current-user", () => ({useCurrentUser: () => activeUser,}))vi.mock("@/hooks/community/use-community-ws", () => ({ useCommunityWs: vi.fn() }))+vi.mock("@/hooks/community/use-notification-settings", () => ({ useNotificationSettings }))vi.mock("@/lib/community/profile-seed", () => ({apiFetchProfiles: (...args: unknown[]) => apiFetchProfiles(...args),}))@@ -50,6 +52,7 @@ beforeEach(() => {renderedProviders.length = 0apiFetchProfiles.mockReset()apiFetchProfiles.mockResolvedValue({})+ useNotificationSettings.mockClear()})describe("CommunityShell identity boundary", () => {@@ -191,4 +194,18 @@ describe("CommunityShell identity boundary", () => {}])renderer.unmount()})++ it("hydrates account notification policy at the community root", () => {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(+ CommunityShell,+ { currentUser: activeUser },+ React.createElement("span", null, "content"),+ ))+ })++ expect(useNotificationSettings).toHaveBeenCalledOnce()+ act(() => renderer.unmount())+ })})diff --git a/src/web/src/app/c/community-shell.tsx b/src/web/src/app/c/community-shell.tsxindex 0bbab38a8..a2954b24b 100644--- a/src/web/src/app/c/community-shell.tsx+++ b/src/web/src/app/c/community-shell.tsx@@ -9,6 +9,7 @@ import {type CurrentUser,} from "@/contexts/community/current-user"import { useCommunityWs } from "@/hooks/community/use-community-ws"+import { useNotificationSettings } from "@/hooks/community/use-notification-settings"import { PerfTraceBootstrap } from "@/components/perf/perf-trace-bootstrap"import { CommunityOnboardingForm } from "@/components/community/onboarding/community-onboarding-form"import { CommunityWsReconnectBoundary } from "@/components/community/shell/community-ws-reconnect-overlay"@@ -24,8 +25,9 @@ import { useCommunityWsStore } from "@/stores/community/ws"* mounts the single WS handler and hydrates the viewer's aboutMe field once* on mount — the old God-context's on-mount side-effects that survived Step 3.*- * Notification-setting hydration is done via `useNotificationSettings()` in- * consumers, so we don't fire it here.+ * Notification-setting hydration lives at this root so every unread source+ * request is reconciled against one account policy, including `/c` routes+ * that do not mount a settings consumer.*/export function CommunityShell({currentUser,@@ -75,6 +77,7 @@ function ProfileAccountBoundary({function CommunityBootstrap({ children }: { children: ReactNode }) {const currentUser = useCurrentUser()+ useNotificationSettings()// Wire the WS handler once for the whole community subtree. `viewerUserId`// powers the `me` flag on incoming reactions — passing null would leave that// flag stuck at false for the viewer's own reactions.diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsxindex dbdc6a93a..07bfa0397 100644--- a/src/web/src/app/c/me/[dmId]/page.tsx+++ b/src/web/src/app/c/me/[dmId]/page.tsx@@ -2,7 +2,6 @@import { useCallback, useEffect, useMemo, useState } from "react"import { useParams, useSearchParams } from "next/navigation"-import { useQuery } from "@tanstack/react-query"import { toast } from "sonner"import { useBreakpoint } from "@/hooks/use-mobile"import { DmHeader } from "@/components/community/channels/dm-header"@@ -24,7 +23,7 @@ import { useCommunityWsStore } from "@/stores/community/ws"import { tid } from "@/lib/community/testids"import { readCommunityProfile } from "@/lib/community/profile-read"import { makeUserNameResolver } from "@/lib/community/display-name"-import { dmsQueryFn, type DmsResponse } from "@/hooks/community/use-dms"+import { useDms } from "@/hooks/community/use-dms"import { useFriends } from "@/hooks/community/use-friends"import { useDmMessages } from "@/hooks/community/use-messages"import { useDmReadStateSnapshot } from "@/hooks/community/use-dm-read-state"@@ -52,11 +51,8 @@ import { notifLevelDisplay, type NotifLevel } from "@alook/shared"import { useNotificationSettings } from "@/hooks/community/use-notification-settings"import { useSetChannelNotif } from "@/hooks/community/mutations"import { toastApiError } from "@/lib/api/client"-import { communityKeys } from "@/lib/query-keys"import { displayReplyContent } from "@/lib/community/reply-content"-const EMPTY_DMS: DmsResponse["conversations"] = []-// Thin re-mount wrapper — same reason as the server-side channel view: the// dynamic segment reuses the same component instance across DM switches, so// keying by dmId tears down the previous view before the next paints.@@ -99,12 +95,8 @@ function DmView() {// MeLayout owns the canonical cold DMs fetch. This second observer consumes// that result without treating it as stale on mount; explicit WS/query// invalidation still refetches the active canonical key.- const dmsQuery = useQuery<DmsResponse>({- queryKey: communityKeys.dms(),- queryFn: dmsQueryFn,- staleTime: Infinity,- })- const dms = dmsQuery.data?.conversations ?? EMPTY_DMS+ const dmsQuery = useDms()+ const dms = dmsQuery.dmsconst dmsLoading = dmsQuery.isLoadingconst { friends: rawFriends, blocked } = useFriends()const profilesByUserId = useCommunityWsStore((s) => s.profilesByUserId)diff --git a/src/web/src/components/community/shell/community-inbox-popover.test.ts b/src/web/src/components/community/shell/community-inbox-popover.test.tsindex e8bf8966e..f8752b584 100644--- a/src/web/src/components/community/shell/community-inbox-popover.test.ts+++ b/src/web/src/components/community/shell/community-inbox-popover.test.ts@@ -57,6 +57,8 @@ function popover(onOpenChannel: ReturnType<typeof vi.fn>, onOpenThread: ReturnTyunreadDms: [],mentions: [],marked: [],+ hasProjectedUnreads: true,+ hasProjectedMentions: false,onOpenChannel,onOpenThread,})@@ -128,6 +130,8 @@ describe("InboxPopover thread opener rows", () => {unreadDms: [],mentions: [],marked: [],+ hasProjectedUnreads: true,+ hasProjectedMentions: false,onOpenChannel,onOpenThread: vi.fn(),}))@@ -158,6 +162,8 @@ describe("InboxPopover thread opener rows", () => {unreadDms: [],mentions: [],marked: [],+ hasProjectedUnreads: true,+ hasProjectedMentions: false,onOpenChannel,onOpenThread: vi.fn(),}))@@ -189,6 +195,8 @@ describe("InboxPopover thread opener rows", () => {unreadDms: [],mentions: [],marked: [],+ hasProjectedUnreads: true,+ hasProjectedMentions: false,onOpenThread: vi.fn(),isProjected: (target) => target?.kind === "thread",}))@@ -215,6 +223,8 @@ describe("InboxPopover thread opener rows", () => {unreadDms: [],mentions: [],marked: [],+ hasProjectedUnreads: true,+ hasProjectedMentions: false,onOpenChannel,onOpenThread: vi.fn(),isProjected: (target) => target?.kind === "channel-direct",@@ -258,6 +268,8 @@ describe("InboxPopover DM rows", () => {unreadDms: [dm],mentions: [],marked: [],+ hasProjectedUnreads: true,+ hasProjectedMentions: false,onOpenThread: vi.fn(),onOpenDm,}))@@ -285,6 +297,8 @@ describe("InboxPopover responsive continuity", () => {unreadDms: [],mentions: [],marked: [],+ hasProjectedUnreads: false,+ hasProjectedMentions: false,activeTab: "mentions",onActiveTabChange,onMarkedTabSelected,diff --git a/src/web/src/components/community/shell/community-inbox-popover.tsx b/src/web/src/components/community/shell/community-inbox-popover.tsxindex af7063985..ebde3cd5d 100644--- a/src/web/src/components/community/shell/community-inbox-popover.tsx+++ b/src/web/src/components/community/shell/community-inbox-popover.tsx@@ -354,8 +354,8 @@ export function InboxPopover({marked: Marked[]markedLoading?: booleanloading?: boolean- hasProjectedUnreads?: boolean- hasProjectedMentions?: boolean+ hasProjectedUnreads: boolean+ hasProjectedMentions: booleanonOpenChannel?: (server: UnreadServer,channel: UnreadChannel,@@ -385,8 +385,8 @@ export function InboxPopover({surface?: "desktop" | "mobile"}) {const profilesByUserId = useProfilesByUserId()- const hasUnreads = hasProjectedUnreads ?? (unreads.length > 0 || unreadDms.length > 0)- const hasMentions = hasProjectedMentions ?? mentions.length > 0+ const hasUnreads = hasProjectedUnreads+ const hasMentions = hasProjectedMentionsconst showUnreadDot = selectUnreadPresentation({accountUnread: hasUnreads,}).showDotdiff --git a/src/web/src/components/community/shell/community-inbox-surface.tsx b/src/web/src/components/community/shell/community-inbox-surface.tsxindex 5dc577f80..aa2c18509 100644--- a/src/web/src/components/community/shell/community-inbox-surface.tsx+++ b/src/web/src/components/community/shell/community-inbox-surface.tsx@@ -21,7 +21,7 @@ type Props = {breakpoint: Breakpointopen?: booleanonOpenChange?: (open: boolean) => void- hasUnread?: boolean+ hasUnread: booleananchorRef: RefObject<HTMLDivElement | null>suppressFocusReturnRef: MutableRefObject<boolean>children: ReactNode@@ -38,7 +38,7 @@ export function CommunityInboxSurface({}: Props) {const triggerRef = useRef<HTMLButtonElement>(null)const mobile = breakpoint === "mobile"- const unread = selectUnreadPresentation({ accountUnread: hasUnread === true })+ const unread = selectUnreadPresentation({ accountUnread: hasUnread })return (<Popoverdiff --git a/src/web/src/components/community/shell/use-shell-rail-controller.test.ts b/src/web/src/components/community/shell/use-shell-rail-controller.test.tsindex eddfcab38..bfa76e2ab 100644--- a/src/web/src/components/community/shell/use-shell-rail-controller.test.ts+++ b/src/web/src/components/community/shell/use-shell-rail-controller.test.ts@@ -28,7 +28,7 @@ vi.mock("@/hooks/community/use-servers", () => ({servers: mocks.servers,isLoading: false,}),- serverQueryFn: (id: string) => () => Promise.resolve({ id }),+ serverProjectedQueryFn: (_queryClient: unknown, id: string) => () => Promise.resolve({ id }),}))vi.mock("@/hooks/community/use-folders", () => ({ useFolders: () => ({ folders: mocks.folders }) }))vi.mock("@/hooks/community/mutations", () => ({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.tsindex 293677e0b..44382f917 100644--- a/src/web/src/components/community/shell/use-shell-rail-controller.ts+++ b/src/web/src/components/community/shell/use-shell-rail-controller.ts@@ -6,7 +6,7 @@ import { toastApiError } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import { markSwitch } from "@/lib/perf/switch-mark"import { markVoluntaryLeave, pickPostEjectDestination } from "@/lib/community/eject-server"-import { serverQueryFn, useServers, type ServerDetail } from "@/hooks/community/use-servers"+import { serverProjectedQueryFn, useServers, type ServerDetail } from "@/hooks/community/use-servers"import { useFolders } from "@/hooks/community/use-folders"import {useCreateServer,@@ -75,7 +75,7 @@ export function useShellRailController({try {await queryClient.fetchQuery({queryKey: communityKeys.server(id),- queryFn: serverQueryFn(queryClient, id),+ queryFn: serverProjectedQueryFn(queryClient, id),staleTime: Infinity,})} catch {diff --git a/src/web/src/components/community/shell/user-bar.tsx b/src/web/src/components/community/shell/user-bar.tsxindex 169b9aa29..8c3713892 100644--- a/src/web/src/components/community/shell/user-bar.tsx+++ b/src/web/src/components/community/shell/user-bar.tsx@@ -22,7 +22,7 @@ export function UserBar({ breakpoint, user, onOpenProfile, onEditProfile, inbox,onOpenProfile?: OpenProfileonEditProfile?: () => voidinbox?: ReactNode- hasUnread?: boolean+ hasUnread: booleaninboxOpen?: booleanonInboxOpenChange?: (open: boolean) => void}) {@@ -85,7 +85,7 @@ function Inner({ breakpoint, user, onOpenProfile, onEditProfile, inbox, hasUnreaonOpenProfile?: OpenProfileonEditProfile?: () => voidinbox?: ReactNode- hasUnread?: boolean+ hasUnread: booleaninboxOpen?: booleanonInboxOpenChange?: (open: boolean) => voidinboxAnchorRef: RefObject<HTMLDivElement | null>diff --git a/src/web/src/components/home/landing-shell-motion.tsx b/src/web/src/components/home/landing-shell-motion.tsxindex 83bde650d..7d592e750 100644--- a/src/web/src/components/home/landing-shell-motion.tsx+++ b/src/web/src/components/home/landing-shell-motion.tsx@@ -926,6 +926,8 @@ function PrototypeUserBar({unreadDms={[]}mentions={[]}marked={[]}+ hasProjectedUnreads={unreads.length > 0}+ hasProjectedMentions={false}onOpenForumThread={() => {}}/></div>diff --git a/src/web/src/hooks/community/account-unread-projection.test.ts b/src/web/src/hooks/community/account-unread-projection.test.tsindex 22e8ae9f8..cc9b48b80 100644--- a/src/web/src/hooks/community/account-unread-projection.test.ts+++ b/src/web/src/hooks/community/account-unread-projection.test.ts@@ -62,6 +62,32 @@ describe("AccountUnreadProjection", () => {expect(projection.projectServerUnread("s1", [], false)).toBe(true)})+ it("rejects unordered legacy rows until fresh access authority clears the fence", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.retireAccessScope({ kind: "server", serverId: "s1" })+ projection.grantAccessScope({ kind: "server", serverId: "s1" })++ projection.recordLegacySnapshot({}, [{+ family: "inbox-unreads",+ channelId: "legacy",+ serverId: "s1",+ }])+ const authority = projection.beginSnapshot("servers", "channels")+ projection.absorbSnapshot(authority, [], {+ confirmedAccessScopes: [{ kind: "server", serverId: "s1" }],+ })++ expect(projection.projectUnread("inbox-unreads", "legacy", false)).toBe(false)+ expect(projection.inspectForTests().stickyCount).toBe(0)++ projection.recordLegacySnapshot({}, [{+ family: "inbox-unreads",+ channelId: "legacy",+ serverId: "s1",+ }])+ expect(projection.projectUnread("inbox-unreads", "legacy", false)).toBe(true)+ })+it("merges duplicate exact evidence and ignores older read cursors", () => {const projection = new AccountUnreadProjection("u1")projection.recordArrival({ channelId: "c1", serverId: "s1", messageId: "m1", seq: 2 })@@ -69,6 +95,7 @@ describe("AccountUnreadProjection", () => {channelId: "c1",railChannelId: "forum",messageId: "m1",+ attentionId: "mention-1",seq: 2,isMention: true,})@@ -100,27 +127,58 @@ describe("AccountUnreadProjection", () => {expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(false)})- it("keeps an exact arrival until matching family evidence absorbs it", () => {+ it("keeps positive family evidence canonical until a later full snapshot omits it", () => {const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})projection.recordArrival({ channelId: "c1", serverId: "s1", messageId: "m2", seq: 2 })expect(projection.projectUnread("servers", "c1", false)).toBe(true)- projection.absorbFamily("servers", [{ channelId: "c1", lastUnreadSeq: 1 }])+ const positive = projection.beginSnapshot("servers")+ projection.absorbSnapshot(positive, [{ channelId: "c1", serverId: "s1", lastUnreadSeq: 2 }])expect(projection.projectUnread("servers", "c1", false)).toBe(true)- projection.absorbFamily("servers", [{ channelId: "c1", lastUnreadSeq: 2 }])+ const empty = projection.beginSnapshot("servers")+ projection.absorbSnapshot(empty, [])expect(projection.projectUnread("servers", "c1", false)).toBe(false)})- it("does not clear a sticky unknown on empty, same, or truncated evidence", () => {+ it("retires sticky unknowns only from a full current snapshot", () => {const projection = new AccountUnreadProjection("u1")- projection.absorbFamily("inbox-unreads", [{ channelId: "c1", lastUnreadSeq: 8 }])+ projection.setNotificationPolicy({})projection.recordArrival({ channelId: "c1", serverId: "s1" })- projection.absorbFamily("inbox-unreads", [], { truncated: false })- projection.absorbFamily("inbox-unreads", [{ channelId: "c1", lastUnreadSeq: 8 }])+ const truncated = projection.beginSnapshot("inbox-unreads", "channels")+ projection.absorbSnapshot(truncated, [], { truncated: true })expect(projection.projectUnread("inbox-unreads", "c1", false)).toBe(true)- projection.absorbFamily("inbox-unreads", [{ channelId: "c1", lastUnreadSeq: 9 }])+ const full = projection.beginSnapshot("inbox-unreads", "channels")+ projection.absorbSnapshot(full, [])expect(projection.projectUnread("inbox-unreads", "c1", false)).toBe(false)})+ it("retires a covered sticky family after newer full positive evidence", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})+ projection.recordArrival({ channelId: "c1", serverId: "s1" })+ const token = projection.beginSnapshot("inbox-unreads", "channels")+ projection.absorbSnapshot(token, [{+ channelId: "c1",+ serverId: "s1",+ lastUnreadSeq: 7,+ }])++ expect(projection.inspectForTests()).toMatchObject({+ sourceCount: 2,+ exactCount: 1,+ stickyCount: 1,+ })+ expect(projection.hasPending("inbox-unreads", "channels")).toBe(true)+ expect(projection.projectUnread(+ "inbox-unreads",+ "c1",+ false,+ undefined,+ "channels",+ { channelId: "c1", throughSeq: 7 },+ )).toBe(false)+ })+it("lets a visible read cover exact seq but never an unsequenced sticky bump", () => {const exact = new AccountUnreadProjection("u1")exact.recordArrival({ channelId: "c1", serverId: "s1", seq: 4 })@@ -292,29 +350,29 @@ describe("AccountUnreadProjection", () => {expect(projection.projectMentionCount("inbox-mentions", "c1", 0, 1)).toBe(1)})- it("absorbs mention arrivals with mention-seq and unread-seq evidence", () => {+ it("keeps positive mention evidence and retires it on a later full empty", () => {const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})projection.recordMentionArrival({ channelId: "c1", seq: 4, isMention: true })- projection.absorbFamily("inbox-mentions", [{+ const positive = projection.beginSnapshot("inbox-mentions")+ projection.absorbSnapshot(positive, [{channelId: "c1",lastUnreadSeq: 5,lastMentionSeq: 3,}])expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(true)- projection.absorbFamily("inbox-mentions", [{- channelId: "c1",- lastUnreadSeq: 5,- lastMentionSeq: null,- }])+ const empty = projection.beginSnapshot("inbox-mentions")+ projection.absorbSnapshot(empty, [])expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(false)})- it("absorbs a single-family sticky mention only after newer evidence", () => {+ it("retires a single-family sticky mention on authoritative absence", () => {const projection = new AccountUnreadProjection("u1")- projection.absorbFamily("inbox-mentions", [{ channelId: "c1", lastUnreadSeq: 4 }])+ projection.setNotificationPolicy({})projection.recordMentionArrival({ channelId: "c1", isMention: true })- projection.absorbFamily("inbox-mentions", [{ channelId: "c1", lastUnreadSeq: 5 }])+ const token = projection.beginSnapshot("inbox-mentions")+ projection.absorbSnapshot(token, [])expect(projection.hasPending("inbox-mentions", "mentions")).toBe(false)})@@ -338,8 +396,8 @@ describe("AccountUnreadProjection", () => {it("projects server and channel fallbacks, exact arrivals, and hidden forum children", () => {const projection = new AccountUnreadProjection("u1")- expect(projection.projectServerUnread("s1", [], true)).toBe(true)- expect(projection.projectServerChannelUnread("s1", "c1", [], true)).toBe(true)+ expect(projection.projectServerUnread("s1", [], true)).toBe(false)+ expect(projection.projectServerChannelUnread("s1", "c1", [], true)).toBe(false)projection.recordArrival({channelId: "post",@@ -391,7 +449,7 @@ describe("AccountUnreadProjection", () => {)).toBe(true)})- it("projects canonical server sources and raw mention fallbacks", () => {+ it("projects canonical server sources without aggregate-only fallbacks", () => {const projection = new AccountUnreadProjection("u1")expect(projection.projectServerUnread("s1", [{channelId: "c1",@@ -401,7 +459,7 @@ describe("AccountUnreadProjection", () => {channelId: "c1",lastUnreadSeq: 2,}])).toBe(true)- expect(projection.projectServerMentionCount("s1", [], 7)).toBe(7)+ expect(projection.projectServerMentionCount("s1", [], 7)).toBe(0)expect(projection.projectServerMentionCount("s1", [{channelId: "c1",count: 3,@@ -542,87 +600,52 @@ describe("AccountUnreadProjection", () => {expect(projection.projectServerChannelUnread("s-after", "overflow-after", [])).toBe(true)})- it("exposes fixed overflow sentinels through family pending checks", () => {+ it("evicts the oldest scoped sticky source without inventing an unrelated dot", () => {const projection = new AccountUnreadProjection("u1")+ const reconcile = vi.fn()+ projection.setReconcileScheduler(reconcile)for (let index = 0; index < MAX_STICKY_SCOPES; index += 1) {projection.recordArrival({ channelId: `c${index}`, serverId: `s${index}` })}projection.recordArrival({ channelId: "overflow", serverId: "s-overflow" })+ expect(projection.inspectForTests().stickyCount).toBe(MAX_STICKY_SCOPES)+ expect(projection.projectUnread("servers", "c0", false)).toBe(false)+ expect(projection.projectUnread("servers", "overflow", false)).toBe(true)expect(projection.hasPending("servers")).toBe(true)expect(projection.hasPending("servers", "channels")).toBe(true)- expect(projection.projectUnread("servers", "unrelated", false)).toBe(true)- expect(projection.projectServerUnread("unrelated", [], false)).toBe(true)+ expect(projection.projectUnread("servers", "unrelated", false)).toBe(false)+ expect(projection.projectServerUnread("unrelated", [], false)).toBe(false)expect(projection.projectForumParentUnread("unrelated","forum",false,null,new Set(),- )).toBe(true)- })-- it("clears a sentinel only with advancing evidence for its retained witness", () => {- const projection = new AccountUnreadProjection("u1")- for (let index = 0; index < MAX_STICKY_SCOPES; index += 1) {- projection.recordArrival({ channelId: `c${index}`, serverId: `s${index}` })- }- projection.absorbFamily("servers", [{ channelId: "overflow", lastUnreadSeq: 8 }])- projection.recordArrival({ channelId: "overflow", serverId: "s-overflow" })-- projection.absorbFamily("servers", [{ channelId: "other", lastUnreadSeq: 999 }])- expect(projection.projectUnread("servers", "unrelated", false)).toBe(true)- projection.absorbFamily("servers", [{ channelId: "overflow", lastUnreadSeq: 8 }])- expect(projection.projectUnread("servers", "unrelated", false)).toBe(true)- projection.absorbFamily("servers", [{ channelId: "overflow", lastUnreadSeq: 9 }])- expect(projection.projectUnread("servers", "unrelated", false)).toBe(false)- })-- it("clears a mention sentinel with advancing mention evidence", () => {- const projection = new AccountUnreadProjection("u1")- for (let index = 0; index < MAX_STICKY_SCOPES; index += 1) {- projection.recordArrival({ channelId: `c${index}`, serverId: `s${index}` })- }- projection.recordArrival({- channelId: "mention-overflow",- serverId: "s-overflow",- isMention: true,- })- expect(projection.hasPending("inbox-mentions", "mentions")).toBe(true)-- projection.absorbFamily("inbox-mentions", [{- channelId: "mention-overflow",- lastUnreadSeq: 1,- lastMentionSeq: 1,- }], { truncated: false })- expect(projection.hasPending("inbox-mentions", "mentions")).toBe(false)+ )).toBe(false)+ expect(reconcile).toHaveBeenCalledOnce()})- it("makes a sentinel non-clearable when another scope folds into it", () => {+ it("coalesces reconciliation across repeated sticky overflow", () => {const projection = new AccountUnreadProjection("u1")+ const reconcile = vi.fn()+ projection.setReconcileScheduler(reconcile)for (let index = 0; index < MAX_STICKY_SCOPES; index += 1) {projection.recordArrival({ channelId: `c${index}`, serverId: `s${index}` })}projection.recordArrival({ channelId: "first", serverId: "s-first" })projection.recordArrival({ channelId: "second", serverId: "s-second" })- projection.absorbFamily("servers", [- { channelId: "first", lastUnreadSeq: 9 },- { channelId: "second", lastUnreadSeq: 9 },- ])- expect(projection.projectUnread("servers", "unrelated", false)).toBe(true)+ expect(reconcile).toHaveBeenCalledOnce()})- it("makes a normalized server-detail sentinel non-clearable across families", () => {+ it("retires a compacted scoped source on a complete empty snapshot", () => {const projection = new AccountUnreadProjection("u1")- for (let index = 0; index < MAX_STICKY_SCOPES; index += 1) {- projection.recordArrival({ channelId: `c${index}`, serverId: `s${index}` })+ projection.setNotificationPolicy({})+ for (let seq = 1; seq <= MAX_EXACT_ARRIVALS_PER_CHANNEL + 1; seq += 1) {+ projection.recordArrival({ channelId: "shared", serverId: "s1", seq })}- projection.recordArrival({ channelId: "shared", serverId: "s-first" })- projection.recordArrival({ channelId: "shared", serverId: "s-second" })- projection.absorbFamily("server-detail:s-first", [{- channelId: "shared",- lastUnreadSeq: 9,- }])- expect(projection.hasPending("server-detail:s-first", "channels")).toBe(true)+ const token = projection.beginSnapshot("servers", "channels")+ projection.absorbSnapshot(token, [])+ expect(projection.projectUnread("servers", "shared", false)).toBe(false)})it("ignores superseded mark-all tokens", () => {@@ -646,7 +669,7 @@ describe("AccountUnreadProjection", () => {projection.rollbackMarkAll(token)})- it("keeps sticky family epochs independent on the same channel", () => {+ it("keeps a post-mark-all mention as a new ordinary and attention source", () => {const projection = new AccountUnreadProjection("u1")projection.recordArrival({ channelId: "c1", serverId: "s1" })const token = projection.beginMarkAll("channels")@@ -654,8 +677,873 @@ describe("AccountUnreadProjection", () => {projection.commitMarkAll(token, 2)projection.acceptPrimarySnapshot({ revision: 2, readStates: [] })+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)+ expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(true)+ })++ it("stores one canonical source across unread and attention families", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.recordArrival({+ channelId: "c1",+ serverId: "s1",+ messageId: "m1",+ seq: 7,+ isMention: true,+ })+ expect(projection.inspectForTests().sourceCount).toBe(1)+ expect(projection.projectUnread("inbox-unreads", "c1", false)).toBe(true)+ expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(true)+ })++ it("coalesces bundled unread and mention events by channel sequence", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 7 })+ projection.recordMentionArrival({ channelId: "c1", messageId: "m1", seq: 7 })++ expect(projection.inspectForTests().sourceCount).toBe(1)+ expect(projection.projectUnread("inbox-unreads", "c1", false)).toBe(true)+ expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(true)+ })++ it("excludes the reserved mention from the server attention badge", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.recordArrival({+ channelId: "c1",+ serverId: "s1",+ messageId: "m1",+ seq: 7,+ isMention: true,+ })++ expect(projection.projectServerMentionCount("s1", [{+ channelId: "c1",+ count: 1,+ lastSeq: 7,+ }], 1, { channelId: "c1", throughSeq: 7 })).toBe(0)+ })++ it("upgrades a correlated unsequenced mention to the later exact unread source", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.recordMentionArrival({ channelId: "c1", messageId: "m1" })+ projection.recordArrival({+ channelId: "c1",+ serverId: "s1",+ messageId: "m1",+ seq: 7,+ })++ expect(projection.inspectForTests()).toMatchObject({+ sourceCount: 1,+ exactCount: 1,+ stickyCount: 0,+ })+ const exclusion = { channelId: "c1", throughSeq: 7 }+ expect(projection.projectUnread(+ "inbox-unreads",+ "c1",+ false,+ undefined,+ "channels",+ exclusion,+ )).toBe(false)+ expect(projection.projectUnread(+ "inbox-mentions",+ "c1",+ false,+ undefined,+ "mentions",+ exclusion,+ )).toBe(false)+ })++ it("enriches a bump-first sticky before a truncated exact mention snapshot", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.recordArrival({+ channelId: "post-1",+ serverId: "s1",+ railChannelId: "forum-1",+ isMention: true,+ })+ projection.recordMentionArrival({ channelId: "post-1", messageId: "m1" })+ const token = projection.beginSnapshot("inbox-mentions", "mentions")+ projection.absorbSnapshot(token, [{+ channelId: "post-1",+ serverId: "s1",+ railChannelId: "forum-1",+ messageId: "m1",+ attentionId: "attention-1",+ lastUnreadSeq: 7,+ lastMentionSeq: 7,+ }], { truncated: true })++ expect(projection.inspectForTests()).toMatchObject({+ sourceCount: 1,+ exactCount: 1,+ stickyCount: 0,+ })+ })++ it("keeps m1 to m2 to m1 sticky identities aggregated", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.recordMentionArrival({ channelId: "c1", messageId: "m1" })+ projection.recordMentionArrival({ channelId: "c1", messageId: "m2" })+ projection.recordMentionArrival({ channelId: "c1", messageId: "m1" })+ projection.recordArrival({ channelId: "c1", messageId: "m1", seq: 7 })++ expect(projection.inspectForTests()).toMatchObject({+ sourceCount: 2,+ exactCount: 1,+ stickyCount: 1,+ })+ })++ it("does not classify an unscoped mention frame as a DM", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.recordMentionArrival({ channelId: "unknown", seq: 7 })++ expect(projection.projectUnread("inbox-unreads", "unknown", false)).toBe(true)+ expect(projection.projectUnread("inbox-mentions", "unknown", false)).toBe(true)+ expect(projection.projectUnread("dms", "unknown", false)).toBe(false)+ })++ it("keeps live and snapshot mentions in a previously known DM family", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})+ projection.recordArrival({ channelId: "dm", seq: 1 })+ projection.recordMentionArrival({ channelId: "dm", seq: 2 })+ projection.recordRead("dm", 1)++ expect(projection.projectUnread("dms", "dm", false)).toBe(true)+ expect(projection.projectUnread("inbox-mentions", "dm", false)).toBe(true)++ const token = projection.beginSnapshot("inbox-mentions", "mentions")+ projection.absorbSnapshot(token, [{+ channelId: "dm",+ lastUnreadSeq: 3,+ lastMentionSeq: 3,+ }], { truncated: true })+ projection.recordRead("dm", 2)++ expect(projection.projectUnread("dms", "dm", false)).toBe(true)+ expect(projection.projectUnread("inbox-mentions", "dm", false)).toBe(true)+ })++ it("projects an exact attention row without borrowing a newer channel source", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.recordMentionArrival({ channelId: "c1", seq: 4, isMention: true })+ projection.recordMentionArrival({ channelId: "c1", seq: 5, isMention: true })+ const exclusion = { channelId: "c1", throughSeq: 4 }++ expect(projection.projectUnread(+ "inbox-mentions",+ "c1",+ true,+ 4,+ "mentions",+ exclusion,+ true,+ )).toBe(false)+ expect(projection.projectUnread(+ "inbox-mentions",+ "c1",+ true,+ 5,+ "mentions",+ exclusion,+ true,+ )).toBe(true)+ })++ it("uses full absence as negative evidence but keeps post-request arrivals", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})+ projection.recordArrival({ channelId: "before", serverId: "s1", seq: 1 })+ const token = projection.beginSnapshot("servers", "channels")+ projection.recordArrival({ channelId: "after", serverId: "s1", seq: 2 })+ projection.absorbSnapshot(token, [])+ expect(projection.projectUnread("servers", "before", false)).toBe(false)+ expect(projection.projectUnread("servers", "after", false)).toBe(true)+ })++ it("does not let a pre-mark-all snapshot refresh an old source past the fence", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})+ projection.recordArrival({ channelId: "before", serverId: "s1", seq: 1 })+ const snapshot = projection.beginSnapshot("servers")+ const markAll = projection.beginMarkAll("channels")++ projection.absorbSnapshot(snapshot, [{+ channelId: "before",+ serverId: "s1",+ lastUnreadSeq: 1,+ }])++ expect(projection.projectUnread("servers", "before", false)).toBe(false)+ projection.rollbackMarkAll(markAll)+ expect(projection.projectUnread("servers", "before", false)).toBe(true)+ })++ it("keeps a source confirmed by a newer snapshot when an older empty arrives last", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })+ const older = projection.beginSnapshot("servers", "channels")+ const newer = projection.beginSnapshot("servers", "channels")++ projection.absorbSnapshot(newer, [{+ channelId: "c1",+ serverId: "s1",+ lastUnreadSeq: 1,+ }])+ projection.absorbSnapshot(older, [])++ expect(projection.projectUnread("servers", "c1", false)).toBe(true)+ })++ it("treats stale and truncated snapshots as positive-only", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })+ const stale = projection.beginSnapshot("servers", "channels")+ projection.absorbSnapshot(stale, [], { stale: true })+ const truncated = projection.beginSnapshot("servers", "channels")+ projection.absorbSnapshot(truncated, [], { truncated: true })+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)++ const positive = projection.beginSnapshot("servers", "channels")+ projection.absorbSnapshot(positive, [{+ channelId: "c2",+ serverId: "s1",+ lastUnreadSeq: 2,+ }], { stale: true })+ expect(projection.projectUnread("servers", "c2", false)).toBe(true)+ })++ it("merges a positive family snapshot with its default domain", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})+ const beginSnapshot = vi.spyOn(projection, "beginSnapshot")++ projection.mergeSources("dms", [{ channelId: "dm", lastUnreadSeq: 2 }])++ expect(beginSnapshot).toHaveBeenCalledWith("dms", "dms")+ expect(projection.projectUnread("dms", "dm", false)).toBe(true)+ })++ it("treats snapshots started before policy hydration as positive-only", () => {+ const projection = new AccountUnreadProjection("u1")+ const reconcile = vi.fn()+ projection.setReconcileScheduler(reconcile)+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })+ const token = projection.beginSnapshot("servers", "channels")+ projection.absorbSnapshot(token, [])+ projection.setNotificationPolicy({ server: { s1: "all" } })+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)+ expect(reconcile).toHaveBeenCalledOnce()+ })++ it("reconciles pre-policy snapshots that would retire exact or sticky attention", () => {+ const exact = new AccountUnreadProjection("u1")+ const exactReconcile = vi.fn()+ exact.setReconcileScheduler(exactReconcile)+ exact.recordArrival({ channelId: "channel", serverId: "s1", seq: 1, isMention: true })+ const exactToken = exact.beginSnapshot("servers", "channels")+ exact.absorbSnapshot(exactToken, [{+ channelId: "channel",+ serverId: "s1",+ lastUnreadSeq: 1,+ }])+ exact.setNotificationPolicy({})++ expect(exact.projectUnread("servers", "channel", false)).toBe(true)+ expect(exactReconcile).toHaveBeenCalledOnce()++ const sticky = new AccountUnreadProjection("u1")+ const stickyReconcile = vi.fn()+ sticky.setReconcileScheduler(stickyReconcile)+ sticky.recordArrival({ channelId: "dm", isMention: true })+ const stickyToken = sticky.beginSnapshot("dms", "dms")+ sticky.absorbSnapshot(stickyToken, [{ channelId: "dm", lastUnreadSeq: 1 }])+ sticky.setNotificationPolicy({})++ expect(sticky.projectUnread("dms", "dm", false)).toBe(true)+ expect(stickyReconcile).toHaveBeenCalledOnce()+ })++ it("does not refetch a pre-policy snapshot that had no negative work", () => {+ const projection = new AccountUnreadProjection("u1")+ const reconcile = vi.fn()+ projection.setReconcileScheduler(reconcile)+ const token = projection.beginSnapshot("dms", "dms")+ projection.absorbSnapshot(token, [])++ projection.setNotificationPolicy({})++ expect(reconcile).not.toHaveBeenCalled()+ })++ it("makes an old-policy full empty positive-only and coalesces reconciliation", () => {+ const projection = new AccountUnreadProjection("u1")+ const reconcile = vi.fn()+ projection.setReconcileScheduler(reconcile)+ projection.setNotificationPolicy({ server: { s1: "all" } })+ reconcile.mockClear()+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })+ const token = projection.beginSnapshot("servers", "channels")+ projection.setNotificationPolicy({ server: { s1: "nothing" } })+ projection.absorbSnapshot(token, [])+ projection.absorbSnapshot(token, [])+ expect(reconcile).toHaveBeenCalledOnce()+ projection.setNotificationPolicy({ server: { s1: "all" } })+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)+ })++ it("runs a reconciliation requested before its scheduler attaches", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})+ const token = projection.beginSnapshot("servers")+ projection.setNotificationPolicy({ server: { s1: "nothing" } })+ projection.absorbSnapshot(token, [])++ const reconcile = vi.fn()+ projection.setReconcileScheduler(reconcile)+ expect(reconcile).toHaveBeenCalledOnce()+ })++ it("absorbs each issued snapshot token at most once", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})+ const token = projection.beginSnapshot("servers", "channels")+ projection.absorbSnapshot(token, [{+ channelId: "c1",+ serverId: "s1",+ lastUnreadSeq: 1,+ }])+ projection.absorbSnapshot(token, [{+ channelId: "c2",+ serverId: "s1",+ lastUnreadSeq: 2,+ }])++ expect(projection.projectUnread("servers", "c1", false)).toBe(true)+ expect(projection.projectUnread("servers", "c2", false)).toBe(false)+ })++ it("applies exact channel over parent over server policy without consuming sources", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.recordArrival({+ channelId: "child",+ railChannelId: "parent",+ serverId: "s1",+ seq: 1,+ isMention: true,+ })+ const before = projection.inspectForTests()+ projection.setNotificationPolicy({+ server: { s1: "nothing" },+ channel: { parent: "mentions", child: "all" },+ })+ expect(projection.projectUnread("servers", "child", false)).toBe(true)+ projection.setNotificationPolicy({+ server: { s1: "nothing" },+ channel: { parent: "mentions" },+ })+ expect(projection.projectUnread("servers", "child", false)).toBe(true)+ projection.setNotificationPolicy({ server: { s1: "nothing" } })+ expect(projection.projectUnread("servers", "child", false)).toBe(false)+ projection.setNotificationPolicy({ server: { s1: "all" } })+ expect(projection.projectUnread("servers", "child", false)).toBe(true)+ expect(projection.inspectForTests().sourceCount).toBe(before.sourceCount)+ expect(projection.inspectForTests().readState).toEqual(before.readState)+ })++ it("shows only attention-bearing unread under mentions policy", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.recordArrival({ channelId: "plain", serverId: "s1", seq: 1 })+ projection.recordArrival({+ channelId: "attention",+ serverId: "s1",+ seq: 1,+ isMention: true,+ })+ projection.setNotificationPolicy({ server: { s1: "mentions" } })+ expect(projection.projectUnread("servers", "plain", false)).toBe(false)+ expect(projection.projectUnread("servers", "attention", false)).toBe(true)+ expect(projection.projectUnread("inbox-mentions", "attention", false)).toBe(true)+ })++ it("does not let a retired mention identity qualify a later plain raw row", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({ server: { s1: "mentions" } })+ projection.recordArrival({+ channelId: "c1",+ serverId: "s1",+ seq: 1,+ isMention: true,+ })+ projection.recordRead("c1", 1)++ expect(projection.inspectForTests().sourceCount).toBe(0)+ expect(projection.projectUnread("inbox-unreads", "c1", true, 2)).toBe(false)++ projection.recordArrival({+ channelId: "c1",+ serverId: "s1",+ seq: 2,+ isMention: true,+ })+ expect(projection.projectUnread("inbox-unreads", "c1", true, 2)).toBe(true)+ })++ it("rolls back one policy overlay without overwriting a newer committed overlay", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({ server: { s1: "all" } })+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })+ const older = projection.beginNotificationPolicyOverlay({+ kind: "server",+ id: "s1",+ level: "nothing",+ })+ const newer = projection.beginNotificationPolicyOverlay({+ kind: "channel",+ id: "c1",+ level: "all",+ })++ projection.commitNotificationPolicyOverlay(newer)+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)+ projection.rollbackNotificationPolicyOverlay(older)+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)+ })++ it("rolls a channel-default overlay back to the exact override", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({+ server: { s1: "nothing" },+ channel: { c1: "all" },+ })+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })+ const token = projection.beginNotificationPolicyOverlay({+ kind: "channel",+ id: "c1",+ level: null,+ })+expect(projection.projectUnread("servers", "c1", false)).toBe(false)+ projection.rollbackNotificationPolicyOverlay(token)+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)+ })++ it("dismisses only the matching attention facet and rolls it back", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})+ projection.recordArrival({+ channelId: "c1",+ serverId: "s1",+ messageId: "m1",+ seq: 4,+ isMention: true,+ })+ const token = projection.beginDismissMention({+ mentionId: "mention-1",+ channelId: "c1",+ seq: 4,+ })+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)+ expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(false)+ expect(projection.projectServerMentionCount("s1", [{+ channelId: "c1",+ count: 2,+ lastSeq: 4,+ }])).toBe(1)+ projection.rollbackDismissMention(token)expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(true)+ expect(projection.projectServerMentionCount("s1", [{+ channelId: "c1",+ count: 2,+ lastSeq: 4,+ }])).toBe(2)++ const staleSnapshot = projection.beginSnapshot("inbox-mentions", "mentions")+ const committed = projection.beginDismissMention({+ mentionId: "mention-1",+ channelId: "c1",+ seq: 4,+ })+ projection.commitDismissMention(committed, 3)+ projection.absorbSnapshot(staleSnapshot, [], { truncated: false })+ expect(projection.projectUnread(+ "inbox-mentions",+ "c1",+ true,+ 4,+ "mentions",+ null,+ true,+ "mention-1",+ )).toBe(false)+ projection.absorbFamily("servers", [{+ channelId: "c1",+ serverId: "s1",+ lastUnreadSeq: 4,+ lastMentionSeq: 4,+ isMention: true,+ }])+ expect(projection.projectServerMentionCount("s1", [{+ channelId: "c1",+ count: 2,+ lastSeq: 4,+ }])).toBe(1)++ const confirmingSnapshot = projection.beginSnapshot("inbox-mentions", "mentions")+ projection.absorbSnapshot(confirmingSnapshot, [], { truncated: false })+ expect(projection.projectServerMentionCount("s1", [{+ channelId: "c1",+ count: 2,+ lastSeq: 4,+ }])).toBe(2)+ })++ it("keeps same-seq sibling attention identities and counts only direct mentions", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})+ for (const attentionId of ["reply-1", "mention-1"]) {+ projection.recordArrival({+ channelId: "c1",+ serverId: "s1",+ messageId: "m1",+ attentionId,+ seq: 4,+ isMention: true,+ })+ }++ const reply = projection.beginDismissMention({+ mentionId: "reply-1",+ channelId: "c1",+ seq: 4,+ countsServerMention: false,+ })+ expect(projection.projectUnread(+ "inbox-mentions", "c1", true, 4, "mentions", null, true, "reply-1",+ )).toBe(false)+ expect(projection.projectUnread(+ "inbox-mentions", "c1", true, 4, "mentions", null, true, "mention-1",+ )).toBe(true)+ expect(projection.projectServerMentionCount("s1", [{+ channelId: "c1", count: 1, lastSeq: 4,+ }])).toBe(1)++ projection.rollbackDismissMention(reply)+ projection.beginDismissMention({+ mentionId: "mention-1",+ channelId: "c1",+ seq: 4,+ countsServerMention: true,+ })+ expect(projection.projectUnread(+ "inbox-mentions", "c1", true, 4, "mentions", null, true, "mention-1",+ )).toBe(false)+ expect(projection.projectUnread(+ "inbox-mentions", "c1", true, 4, "mentions", null, true, "reply-1",+ )).toBe(true)+ expect(projection.projectServerMentionCount("s1", [{+ channelId: "c1", count: 1, lastSeq: 4,+ }])).toBe(0)+ })++ it("does not let a revision hint alone retire a committed mark-all fence", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.recordArrival({ channelId: "sticky", serverId: "s1" })+ const token = projection.beginMarkAll("channels")+ projection.commitMarkAll(token, 5)+ projection.acceptPrimarySnapshot({ revision: 5, readStates: [] })+ projection.rollbackMarkAll(token)+ expect(projection.projectUnread("servers", "sticky", false)).toBe(true)+ })++ it("retires access scope atomically and restores it on rollback", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })+ const token = projection.beginScopeRetirement({ kind: "server", serverId: "s1" })+ expect(projection.projectUnread("servers", "c1", false)).toBe(false)+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 2 })+ projection.rollbackScopeRetirement(token)+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)+ projection.retireAccessScope({ kind: "server", serverId: "s1" })+ expect(projection.projectUnread("servers", "c1", false)).toBe(false)+ expect(projection.projectUnread("servers", "c1", true, 1)).toBe(false)+ projection.grantAccessScope({ kind: "server", serverId: "s1" })+ expect(projection.projectUnread("servers", "c1", true, 1)).toBe(false)+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 2 })+ expect(projection.projectUnread("servers", "c1", false)).toBe(false)+ const confirmation = projection.beginAccessConfirmation()+ projection.confirmAccessScopes(+ [{ kind: "server", serverId: "s1" }],+ confirmation,+ )+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)+ })++ it("lets a post-retirement authority recover a committed access tombstone", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })+ projection.retireAccessScope({ kind: "server", serverId: "s1" })++ const serverSnapshot = projection.beginSnapshot("servers", "channels")+ projection.absorbSnapshot(serverSnapshot, [{+ channelId: "c1",+ serverId: "s1",+ lastUnreadSeq: 2,+ }], {+ confirmedAccessScopes: [{ kind: "server", serverId: "s1" }],+ })++ expect(projection.projectUnread("servers", "c1", false)).toBe(true)+ expect(projection.inspectForTests().sourceCount).toBe(1)++ projection.retireAccessScope({ kind: "channel", channelId: "c1" })+ const channelSnapshot = projection.beginSnapshot("server-detail:s1", "channels")+ projection.absorbSnapshot(channelSnapshot, [{+ channelId: "c1",+ serverId: "s1",+ lastUnreadSeq: 3,+ }], {+ confirmedAccessScopes: [{ kind: "channel", channelId: "c1" }],+ })++ expect(projection.projectUnread("server-detail:s1", "c1", false)).toBe(true)+ })++ it("rejects a pre-retirement snapshot after a later access grant", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })+ const staleSnapshot = projection.beginSnapshot("servers", "channels")++ projection.retireAccessScope({ kind: "server", serverId: "s1" })+ projection.grantAccessScope({ kind: "server", serverId: "s1" })+ projection.absorbSnapshot(staleSnapshot, [{+ channelId: "c1",+ serverId: "s1",+ lastUnreadSeq: 2,+ }], {+ confirmedAccessScopes: [{ kind: "server", serverId: "s1" }],+ })++ expect(projection.projectUnread("servers", "c1", false)).toBe(false)+ expect(projection.projectUnread("servers", "c1", true, 2)).toBe(false)+ expect(projection.inspectForTests().sourceCount).toBe(0)+ })++ it("inherits a server retirement floor for channels learned behind its tombstone", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.recordArrival({ channelId: "known", serverId: "s1", seq: 1 })+ projection.retireAccessScope({ kind: "server", serverId: "s1" })++ projection.recordArrival({ channelId: "late", serverId: "s1", seq: 2 })+ projection.grantAccessScope({ kind: "server", serverId: "s1" })+ const empty = projection.beginSnapshot("servers", "channels")+ projection.absorbSnapshot(empty, [], {+ confirmedAccessScopes: [{ kind: "server", serverId: "s1" }],+ })++ expect(projection.projectUnread("inbox-unreads", "late", true, 2)).toBe(false)+ expect(projection.inspectForTests().sourceCount).toBe(0)+ })++ it("keeps a retired channel raw row fenced until a fresh snapshot confirms access", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.recordArrival({ channelId: "private", serverId: "s1", seq: 1 })+ projection.retireAccessScope({ kind: "channel", channelId: "private" })++ expect(projection.projectUnread("inbox-unreads", "private", true, 1)).toBe(false)+ projection.grantAccessScope({ kind: "channel", channelId: "private" })+ expect(projection.projectUnread("inbox-unreads", "private", true, 1)).toBe(false)++ const empty = projection.beginSnapshot("server-detail:s1", "channels")+ projection.absorbSnapshot(empty, [], {+ confirmedAccessScopes: [{ kind: "channel", channelId: "private" }],+ })+ expect(projection.projectUnread("inbox-unreads", "private", true, 1)).toBe(false)+ expect(projection.projectUnread("server-detail:s1", "private", true, 1)).toBe(false)++ const positive = projection.beginSnapshot("server-detail:s1", "channels")+ projection.absorbSnapshot(positive, [{+ channelId: "private",+ serverId: "s1",+ lastUnreadSeq: 2,+ }])+ expect(projection.projectUnread("server-detail:s1", "private", true, 2)).toBe(true)+ })++ it("releases abandoned snapshot tokens without accepting late evidence", () => {+ const projection = new AccountUnreadProjection("u1")+ const token = projection.beginSnapshot("servers")+ expect(projection.inspectForTests().pendingSnapshots).toBe(1)+ projection.cancelSnapshot(token)+ projection.absorbSnapshot(token, [{ channelId: "late", lastUnreadSeq: 2 }])+ expect(projection.inspectForTests()).toMatchObject({+ pendingSnapshots: 0,+ sourceCount: 0,+ })+ })++ it("enriches duplicate exact rows from arrivals and canonical snapshot evidence", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})+ projection.recordArrival({ channelId: "arrival", seq: 2 })+ projection.recordArrival({+ channelId: "arrival",+ serverId: "s1",+ railChannelId: "forum-1",+ seq: 2,+ })+ expect(projection.hasPending(undefined, "channels")).toBe(true)+ expect(projection.projectServerChannelUnread("s1", "forum-1", [], false)).toBe(true)++ projection.recordArrival({ channelId: "snapshot", seq: 3 })+ const token = projection.beginSnapshot("inbox-mentions", "mentions")+ projection.absorbSnapshot(token, [{+ channelId: "snapshot",+ serverId: "s1",+ railChannelId: "forum-1",+ lastUnreadSeq: 3,+ lastMentionSeq: 3,+ isMention: true,+ attentionId: "attention-1",+ }], { truncated: true })++ expect(projection.projectUnread(+ "inbox-mentions", "snapshot", false, 3, "mentions", null, true, "attention-1",+ )).toBe(true)+ expect(projection.projectServerChannelUnread("s1", "forum-1", [], false)).toBe(true)+ })++ it("preserves authoritative server and channel bases beneath pending policy overlays", () => {+ const serverProjection = new AccountUnreadProjection("u1")+ serverProjection.setNotificationPolicy({ server: { s1: "mentions" } })+ const serverToken = serverProjection.beginNotificationPolicyOverlay({+ kind: "server",+ id: "s1",+ level: "nothing",+ })+ serverProjection.setNotificationPolicy({ server: { s1: "all" } })+ serverProjection.rollbackNotificationPolicyOverlay(serverToken)+ serverProjection.recordArrival({+ channelId: "c1", serverId: "s1", seq: 1, isMention: true,+ })+ expect(serverProjection.projectUnread("servers", "c1", false)).toBe(true)++ const channelProjection = new AccountUnreadProjection("u1")+ channelProjection.setNotificationPolicy({ channel: { c1: "mentions" } })+ const channelToken = channelProjection.beginNotificationPolicyOverlay({+ kind: "channel",+ id: "c1",+ level: "nothing",+ })+ channelProjection.setNotificationPolicy({ channel: { c1: "all" } })+ channelProjection.rollbackNotificationPolicyOverlay(channelToken)+ channelProjection.recordArrival({+ channelId: "c1", serverId: "s1", seq: 1, isMention: true,+ })+ expect(channelProjection.projectUnread("servers", "c1", false)).toBe(true)++ const absentChannelProjection = new AccountUnreadProjection("u1")+ absentChannelProjection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })+ const absentToken = absentChannelProjection.beginNotificationPolicyOverlay({+ kind: "channel",+ id: "c1",+ level: "nothing",+ })+ expect(absentChannelProjection.projectUnread("servers", "c1", false)).toBe(false)+ absentChannelProjection.setNotificationPolicy({})+ expect(absentChannelProjection.projectUnread("servers", "c1", false)).toBe(false)+ absentChannelProjection.rollbackNotificationPolicyOverlay(absentToken)+ expect(absentChannelProjection.projectUnread("servers", "c1", false)).toBe(true)+ })++ it("matches identity-free attention dismissals by seq and ignores newer dismissals in counts", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})+ projection.beginDismissMention({+ mentionId: "same-seq", channelId: "c1", seq: 4, countsServerMention: false,+ })+ expect(projection.projectUnread(+ "inbox-mentions", "c1", true, 4, "mentions", null, true,+ )).toBe(false)++ projection.beginDismissMention({+ mentionId: "future",+ channelId: "c1",+ seq: 5,+ countsServerMention: true,+ })+ expect(projection.projectMentionCount("servers", "c1", 1, 4)).toBe(1)+ })++ it("settles a confirmed mark-all fence after its captured source is read", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })+ const markAll = projection.beginMarkAll("channels")+ projection.commitMarkAll(markAll, 1)+ projection.acceptPrimarySnapshot({ revision: 1, readStates: [] })+ projection.recordRead("c1", 1)++ const snapshot = projection.beginSnapshot("servers", "channels")+ projection.absorbSnapshot(snapshot, [])++ expect(projection.projectUnread("servers", "fresh", true, 2)).toBe(true)+ })++ it("keeps every public operation inert after disposal", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.dispose()+ const listener = vi.fn()+ projection.subscribe(listener)()+ projection.setReconcileScheduler(listener)+ projection.settleOptimisticRead(1, true, 1)+ projection.acceptPrimarySnapshot({ revision: 1, readStates: [] })+ projection.absorbFamily("servers", [{ channelId: "c1", lastUnreadSeq: 1 }])+ expect(projection.projectUnread("servers", "c1", true, 1)).toBe(false)+ expect(projection.projectMentionCount("servers", "c1", 1, 1)).toBe(0)++ const policy = projection.beginNotificationPolicyOverlay({+ kind: "server",+ id: "s1",+ level: "nothing",+ })+ projection.commitNotificationPolicyOverlay(policy)+ projection.rollbackNotificationPolicyOverlay(policy)+ const dismissal = projection.beginDismissMention({ mentionId: "m1", channelId: "c1" })+ projection.commitDismissMention(dismissal)+ projection.rollbackDismissMention(dismissal)+ const retirement = projection.beginScopeRetirement({ kind: "server", serverId: "s1" })+ projection.commitScopeRetirement(retirement)+ projection.rollbackScopeRetirement(retirement)+ projection.retireAccessScope({ kind: "server", serverId: "s1" })+ projection.grantAccessScope({ kind: "server", serverId: "s1" })+ projection.confirmAccessScopes(+ [{ kind: "server", serverId: "s1" }],+ projection.beginAccessConfirmation(),+ )+ const markAll = projection.beginMarkAll("channels")+ projection.commitMarkAll(markAll, 1)+ projection.rollbackMarkAll(markAll)+ projection.dispose()++ expect(listener).not.toHaveBeenCalled()+ })++ it("fences late snapshots and mutations after disposal", () => {+ const projection = new AccountUnreadProjection("u1")+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })+ const snapshot = projection.beginSnapshot("servers")+ const scope = projection.beginScopeRetirement({ kind: "server", serverId: "s1" })+ projection.dispose()+ projection.absorbSnapshot(snapshot, [{ channelId: "late", lastUnreadSeq: 2 }])+ projection.rollbackScopeRetirement(scope)+ projection.recordArrival({ channelId: "late", seq: 2 })+ expect(projection.inspectForTests()).toMatchObject({ sourceCount: 0, disposed: true })})it("disposes one account or an entire query-client ledger", () => {diff --git a/src/web/src/hooks/community/account-unread-projection.ts b/src/web/src/hooks/community/account-unread-projection.tsindex 9296cb3db..cc5e7c439 100644--- a/src/web/src/hooks/community/account-unread-projection.ts+++ b/src/web/src/hooks/community/account-unread-projection.ts@@ -15,7 +15,8 @@ export type AccountUnreadArrival = {channelId: stringrailChannelId?: stringserverId?: string- messageId?: string+ messageId?: string | null+ attentionId?: stringseq?: numberisMention?: boolean}@@ -25,6 +26,11 @@ export type AccountUnreadSource = {lastUnreadSeq: numbermentionCount?: numberlastMentionSeq?: number | null+ serverId?: string+ railChannelId?: string+ messageId?: string+ attentionId?: string+ isMention?: boolean}export type AccountUnreadPresentationExclusion = {@@ -48,22 +54,94 @@ type PendingArrival = {seq: numberordinal: numberisMention: boolean- families: Set<AccountUnreadFamily>+ attentionIds: Set<string>+ families: Map<AccountUnreadFamily, number>}type StickyUnknown = {channelId: stringserverId?: stringrailChannelId?: string+ messageId?: string | nullisMention: boolean+ attentionIds: Set<string>families: Map<AccountUnreadFamily, { boundary: number; ordinal: number }>}-type OverflowSentinel = {+export type AccountUnreadFacet = "ordinary" | "attention"++type AccountUnreadPolicyLevel = "all" | "mentions" | "nothing"++export type AccountUnreadPolicySnapshot = {+ all?: AccountUnreadPolicyLevel | string+ server?: Readonly<Record<string, AccountUnreadPolicyLevel | string>>+ channel?: Readonly<Record<string, AccountUnreadPolicyLevel | string>>+ parentByChannel?: Readonly<Record<string, string>>+}++export type AccountUnreadPolicyPatch =+ | { kind: "server"; id: string; level: AccountUnreadPolicyLevel | string }+ | { kind: "channel"; id: string; level: AccountUnreadPolicyLevel | string | null }++export type AccountUnreadPolicyToken = {+ nonce: symbol+ ownerEpoch: number+}++type FrozenPolicy = {+ all: AccountUnreadPolicyLevel+ server: ReadonlyMap<string, AccountUnreadPolicyLevel>+ channel: ReadonlyMap<string, AccountUnreadPolicyLevel>+ parentByChannel: ReadonlyMap<string, string>+}++type MutablePolicy = {+ all: AccountUnreadPolicyLevel+ server: Map<string, AccountUnreadPolicyLevel>+ channel: Map<string, AccountUnreadPolicyLevel>+ parentByChannel: Map<string, string>+}++export type AccountUnreadSnapshotToken = {+ family: AccountUnreadFamily+ domain: AccountUnreadDomain+ startOrdinal: number+ policyGeneration: number+ eligibleCoverage: ReadonlySet<AccountUnreadFacet>+ nonce: symbol+ ownerEpoch: number+ policy: FrozenPolicy+}++export type AccountUnreadScope =+ | { kind: "server"; serverId: string }+ | { kind: "channel"; channelId: string }++export type AccountUnreadScopeToken = {+ scope: AccountUnreadScope+ ordinal: number+ nonce: symbol+ ownerEpoch: number+}++export type AccountUnreadAccessConfirmationToken = {ordinal: number- witnessChannelId: string | null- witnessFamily: AccountUnreadFamily | null- boundary: number+ ownerEpoch: number+}++type AccountUnreadScopeHint = Pick<+ PendingArrival,+ "channelId" | "serverId" | "railChannelId"+>++export type AccountUnreadDismissToken = {+ mentionId: string+ channelId: string+ seq?: number+ countsServerMention: boolean+ ordinal: number+ nonce: symbol+ ownerEpoch: number}export type MarkAllToken = {@@ -84,10 +162,6 @@ export const MAX_STICKY_SCOPES = 256const owners = new WeakMap<QueryClient, Map<string, AccountUnreadProjection>>()const activeOwners = new WeakMap<QueryClient, string>()-function sentinelFamily(family: AccountUnreadFamily) {- return family.startsWith("server-detail:") ? "server-detail" : family-}-function familiesFor(arrival: AccountUnreadArrival): AccountUnreadFamily[] {const families: AccountUnreadFamily[] = ["inbox-unreads"]if (arrival.serverId) {@@ -113,10 +187,6 @@ function arrivalDomain(return serverId ? "channels" : "dms"}-function sentinelKey(family: AccountUnreadFamily, domain: AccountUnreadDomain) {- return `${sentinelFamily(family)}\u0000${domain}`-}-function excludesUnread(exclusion: AccountUnreadPresentationExclusion | null | undefined,channelId: string,@@ -127,19 +197,83 @@ function excludesUnread(return seq !== undefined && seq !== null && seq <= exclusion.throughSeq}+function normalizePolicyLevel(value?: string): AccountUnreadPolicyLevel {+ const normalized = value?.trim().toLowerCase()+ if (normalized === "nothing") return "nothing"+ if (normalized === "mentions" || normalized?.includes("mention")) return "mentions"+ return "all"+}++function freezePolicy(snapshot: AccountUnreadPolicySnapshot): MutablePolicy {+ return {+ all: normalizePolicyLevel(snapshot.all),+ server: new Map(Object.entries(snapshot.server ?? {}).map(([id, level]) => (+ [id, normalizePolicyLevel(level)]+ ))),+ channel: new Map(Object.entries(snapshot.channel ?? {}).map(([id, level]) => (+ [id, normalizePolicyLevel(level)]+ ))),+ parentByChannel: new Map(Object.entries(snapshot.parentByChannel ?? {})),+ }+}++function policySignature(policy: FrozenPolicy) {+ const sortEntries = <T,>(values: ReadonlyMap<string, T>) => (+ [...values.entries()].sort(([left], [right]) => left.localeCompare(right))+ )+ return JSON.stringify([+ policy.all,+ sortEntries(policy.server),+ sortEntries(policy.channel),+ sortEntries(policy.parentByChannel),+ ])+}++function scopeKey(scope: AccountUnreadScope) {+ return scope.kind === "server"+ ? `server:${scope.serverId}`+ : `channel:${scope.channelId}`+}+/**- * Account-wide optimistic unread ledger. It deliberately owns no fetches,- * timers, cache writes, or route transitions: raw TanStack resources remain- * authoritative and feed evidence into this synchronous projection.+ * Account-wide optimistic unread ledger. Raw TanStack resources remain+ * authoritative and feed evidence into this synchronous projection; the+ * owner may request their coalesced reconciliation but owns no transport,+ * timer, cache write, or route transition itself.*/export class AccountUnreadProjection {private ordinal = 0private version = 0+ private ownerEpoch = 0+ private disposed = false+ private highestRevision = -1+ private policyGeneration = 0+ private policyReady = false+ private policy: FrozenPolicy = {+ all: "all",+ server: new Map(),+ channel: new Map(),+ parentByChannel: new Map(),+ }+ private policyBase: MutablePolicy = {+ all: "all",+ server: new Map(),+ channel: new Map(),+ parentByChannel: new Map(),+ }+ private readonly policyOverlays = new Map<symbol, {+ patch: AccountUnreadPolicyPatch+ state: "pending" | "committed"+ }>()+ private reconcileScheduled = false+ private reconcilePendingDelivery = false+ private lastPolicyReconcileGeneration = -1+ private prePolicySnapshotNeedsReconcile = false+ private reconcile: (() => void) | null = nullprivate readonly listeners = new Set<() => void>()private readonly exact = new Map<string, PendingArrival>()private readonly exactByChannel = new Map<string, Set<string>>()private readonly sticky = new Map<string, StickyUnknown>()- private readonly sentinels = new Map<string, OverflowSentinel>()private readonly evidence = new Map<string, number>()private readonly readSeq = new Map<string, number>()private readonly optimisticReads = new Map<@@ -147,32 +281,78 @@ export class AccountUnreadProjection {{ channelId: string; seq: number; committed: boolean }>()private readonly markAll = new Map<AccountUnreadDomain, MarkAllFence>()+ // Scope identity outlives the unread source itself. Access retirement prunes+ // canonical evidence, but cached raw rows still need their server identity+ // so a committed fence cannot be bypassed by the sourceScope fallback.+ private readonly scopeHints = new Map<string, AccountUnreadScopeHint>()+ // A re-grant restores access, not unread truth. Keep raw values from every+ // family below this ordinal suppressed until that family contributes new+ // positive evidence after the retirement.+ private readonly rawRetirementFloors = new Map<string, number>()+ private readonly accessFences = new Map<+ string,+ AccountUnreadScopeToken & { state: "pending" | "committed" | "grant-pending" }+ >()+ private readonly dismissals = new Map<+ symbol,+ AccountUnreadDismissToken & { state: "pending" | "committed" }+ >()+ private readonly snapshots = new Set<symbol>()private readonly legacySnapshots = new WeakSet<object>()constructor(readonly ownerUserId: string) {}subscribe = (listener: () => void) => {+ if (this.disposed) return () => undefinedthis.listeners.add(listener)return () => this.listeners.delete(listener)}getSnapshot = () => this.version+ setReconcileScheduler(reconcile: (() => void) | null) {+ if (this.disposed) return+ this.reconcile = reconcile+ if (reconcile && this.reconcilePendingDelivery) {+ this.reconcilePendingDelivery = false+ reconcile()+ }+ }+recordArrival(arrival: AccountUnreadArrival) {this.recordArrivalForFamilies(arrival, familiesFor(arrival))}recordMentionArrival(arrival: AccountUnreadArrival) {- this.recordArrivalForFamilies(arrival, ["inbox-mentions"])+ const knownSource = this.findSourceScope(arrival.channelId)+ const knownScope = knownSource ?? this.scopeHints.get(arrival.channelId)+ const enriched = {+ ...arrival,+ serverId: arrival.serverId ?? knownScope?.serverId,+ railChannelId: arrival.railChannelId ?? knownScope?.railChannelId,+ isMention: true,+ }+ const families: AccountUnreadFamily[] = enriched.serverId+ ? familiesFor(enriched)+ : knownSource?.families.has("dms")+ ? ["inbox-unreads", "inbox-mentions", "dms"]+ : ["inbox-unreads", "inbox-mentions"]+ this.recordArrivalForFamilies(enriched, families)}recordLegacySnapshot(snapshot: object,sources: readonly AccountUnreadLegacySource[],) {- if (this.legacySnapshots.has(snapshot)) return+ if (this.disposed || this.legacySnapshots.has(snapshot)) returnthis.legacySnapshots.add(snapshot)for (const source of sources) {+ // Legacy rows carry no request-start token. While a committed/granting+ // access fence exists they cannot prove that their unread bit was read+ // after the retirement, so let fresh structural authority clear the+ // fence before admitting them.+ this.rememberScope(source)+ if (!this.scopeAllowsLegacySnapshot(source)) continuethis.recordSticky(source.channelId,[source.family],@@ -187,7 +367,7 @@ export class AccountUnreadProjection {serverId: string,sources: readonly AccountUnreadSource[],) {- if (sources.length === 0) return+ if (this.disposed || sources.length === 0) returnconst channelId = `\u0000legacy-server:${serverId}`const unknown = this.sticky.get(channelId)if (!unknown?.families.delete("servers")) return@@ -198,8 +378,11 @@ export class AccountUnreadProjection {private recordArrivalForFamilies(arrival: AccountUnreadArrival,families: AccountUnreadFamily[],+ observedOrdinal?: number,) {- if (!arrival.channelId) return+ if (this.disposed || !arrival.channelId) return+ this.rememberScope(arrival)+ if (!this.scopeAllowsArrival(arrival, observedOrdinal)) returnconst seq = arrival.seqif (!Number.isSafeInteger(seq) || (seq ?? 0) <= 0) {this.recordSticky(@@ -208,6 +391,9 @@ export class AccountUnreadProjection {arrival.isMention === true,arrival.serverId,arrival.railChannelId,+ observedOrdinal,+ arrival.messageId,+ arrival.attentionId,)return}@@ -215,16 +401,43 @@ export class AccountUnreadProjection {const key = arrival.messageId? `${arrival.channelId}:${arrival.messageId}`: `${arrival.channelId}:seq:${seq}`- const existing = this.exact.get(key)+ const channelKeys = this.exactByChannel.get(arrival.channelId) ?? new Set<string>()+ const existing = this.exact.get(key) ?? [...channelKeys]+ .map((candidate) => this.exact.get(candidate))+ .find((candidate) => candidate?.seq === seq)if (existing) {- for (const family of families) existing.families.add(family)- existing.isMention ||= arrival.isMention === true- existing.serverId ??= arrival.serverId- existing.railChannelId ??= arrival.railChannelId- this.publish()+ let changed = false+ let membershipOrdinal = this.ordinal+ for (const family of families) {+ const previous = existing.families.get(family)+ // Snapshot evidence with an observed ordinal is merged by+ // recordSnapshotSource before this fallback. An existing row here is+ // therefore always a live-arrival merge and gets a fresh ordinal.+ if (previous === undefined) {+ if (!changed) membershipOrdinal = ++this.ordinal+ existing.families.set(family, membershipOrdinal)+ changed = true+ }+ }+ if (!existing.isMention && arrival.isMention === true) {+ existing.isMention = true+ changed = true+ }+ if (arrival.attentionId && !existing.attentionIds.has(arrival.attentionId)) {+ existing.attentionIds.add(arrival.attentionId)+ changed = true+ }+ if (!existing.serverId && arrival.serverId) {+ existing.serverId = arrival.serverId+ changed = true+ }+ if (!existing.railChannelId && arrival.railChannelId) {+ existing.railChannelId = arrival.railChannelId+ changed = true+ }+ if (changed) this.publish()return}- const channelKeys = this.exactByChannel.get(arrival.channelId) ?? new Set<string>()if (this.exact.size >= MAX_EXACT_ARRIVALS|| channelKeys.size >= MAX_EXACT_ARRIVALS_PER_CHANNEL@@ -233,12 +446,14 @@ export class AccountUnreadProjection {let isMention = arrival.isMention === truelet serverId = arrival.serverIdlet railChannelId = arrival.railChannelId+ const attentionIds = new Set(arrival.attentionId ? [arrival.attentionId] : [])for (const exactKey of [...channelKeys]) {const folded = this.exact.get(exactKey)!- for (const family of folded.families) foldedFamilies.add(family)+ for (const family of folded.families.keys()) foldedFamilies.add(family)isMention ||= folded.isMentionserverId ??= folded.serverIdrailChannelId ??= folded.railChannelId+ for (const attentionId of folded.attentionIds) attentionIds.add(attentionId)this.removeExact(exactKey)}this.recordSticky(@@ -247,19 +462,48 @@ export class AccountUnreadProjection {isMention,serverId,railChannelId,+ observedOrdinal,+ undefined,+ undefined,+ attentionIds,)return}+ const matchingSticky = this.sticky.get(arrival.channelId)+ const correlatedSticky = arrival.messageId+ && matchingSticky?.messageId === arrival.messageId+ ? matchingSticky+ : undefined+ const pendingOrdinal = observedOrdinal ?? ++this.ordinalconst pending: PendingArrival = {key,channelId: arrival.channelId,- serverId: arrival.serverId,- railChannelId: arrival.railChannelId,+ serverId: arrival.serverId ?? correlatedSticky?.serverId,+ railChannelId: arrival.railChannelId ?? correlatedSticky?.railChannelId,seq: seq!,- ordinal: ++this.ordinal,- isMention: arrival.isMention === true,- families: new Set(families),+ ordinal: Math.max(+ pendingOrdinal,+ ...[...(correlatedSticky?.families.values() ?? [])].map((membership) => (+ membership.ordinal+ )),+ ),+ isMention: arrival.isMention === true || correlatedSticky?.isMention === true,+ attentionIds: new Set([+ ...(correlatedSticky?.attentionIds ?? []),+ ...(arrival.attentionId ? [arrival.attentionId] : []),+ ]),+ families: new Map(),+ }+ for (const [family, membership] of correlatedSticky?.families ?? []) {+ pending.families.set(family, membership.ordinal)}+ for (const family of families) {+ pending.families.set(+ family,+ Math.max(pending.families.get(family) ?? -1, pendingOrdinal),+ )+ }+ if (correlatedSticky) this.sticky.delete(arrival.channelId)this.exact.set(key, pending)channelKeys.add(key)this.exactByChannel.set(arrival.channelId, channelKeys)@@ -267,7 +511,7 @@ export class AccountUnreadProjection {}recordRead(channelId: string, seq: number) {- if (!Number.isSafeInteger(seq) || seq <= 0) return+ if (this.disposed || !Number.isSafeInteger(seq) || seq <= 0) returnconst previous = this.readSeq.get(channelId) ?? 0if (seq <= previous) returnthis.readSeq.set(channelId, seq)@@ -279,7 +523,7 @@ export class AccountUnreadProjection {}recordOptimisticRead(channelId: string, seq: number, generation: number) {- if (!Number.isSafeInteger(seq) || seq <= 0) return+ if (this.disposed || !Number.isSafeInteger(seq) || seq <= 0) returnthis.optimisticReads.set(generation, { channelId, seq, committed: false })this.publish()}@@ -289,6 +533,7 @@ export class AccountUnreadProjection {committed: boolean,confirmedSeq?: number,) {+ if (this.disposed) returnconst optimistic = this.optimisticReads.get(generation)if (!optimistic) returnif (committed) {@@ -305,6 +550,8 @@ export class AccountUnreadProjection {revision: numberreadStates: Array<{ channelId: string; lastReadSeq: number }>}) {+ if (this.disposed || snapshot.revision < this.highestRevision) return+ this.highestRevision = snapshot.revisionfor (const row of snapshot.readStates) {this.recordRead(row.channelId, row.lastReadSeq)for (const [generation, optimistic] of this.optimisticReads) {@@ -321,103 +568,189 @@ export class AccountUnreadProjection {&& fence.revision !== null&& snapshot.revision >= fence.revision) {- for (const [key, arrival] of this.exact) {- if (arrival.ordinal > fence.ordinal) continue- for (const family of [...arrival.families]) {- if (arrivalDomain(family, arrival.serverId) === domain) {- arrival.families.delete(family)- }- }- if (arrival.families.size === 0) this.removeExact(key)- }- for (const [channelId, unknown] of this.sticky) {- for (const [family, pending] of [...unknown.families]) {- if (- pending.ordinal <= fence.ordinal- && arrivalDomain(family, unknown.serverId) === domain- ) {- unknown.families.delete(family)- }- }- if (unknown.families.size === 0) this.sticky.delete(channelId)+ if (!this.hasCapturedDomainSource(domain, fence.ordinal)) {+ this.markAll.delete(domain)+ changed = true}- this.markAll.delete(domain)- for (const [key, sentinel] of this.sentinels) {- if (sentinel.ordinal <= fence.ordinal && key.endsWith(`\u0000${domain}`)) {- this.sentinels.delete(key)- }- }- changed = true}}if (changed) this.publish()}- absorbFamily(+ beginSnapshot(family: AccountUnreadFamily,+ domain: AccountUnreadDomain = familyDomain(family),+ eligibleCoverage: Iterable<AccountUnreadFacet> = [+ family === "inbox-mentions" ? "attention" : "ordinary",+ ],+ ): AccountUnreadSnapshotToken {+ this.reconcileScheduled = false+ const token = {+ family,+ domain,+ startOrdinal: this.disposed ? this.ordinal : ++this.ordinal,+ policyGeneration: this.policyGeneration,+ eligibleCoverage: new Set(this.policyReady ? eligibleCoverage : []),+ nonce: Symbol(family),+ ownerEpoch: this.ownerEpoch,+ policy: this.clonePolicy(),+ }+ if (!this.disposed) this.snapshots.add(token.nonce)+ return token+ }++ absorbSnapshot(+ token: AccountUnreadSnapshotToken,sources: readonly AccountUnreadSource[],options: {truncated?: booleanstale?: boolean- domain?: AccountUnreadDomain+ confirmedAccessScopes?: readonly AccountUnreadScope[]} = {},) {- if (options.stale) return- const byChannel = new Map(sources.map((source) => [source.channelId, source]))- let changed = false- for (const source of sources) {- if (source.lastUnreadSeq > 0) {- const evidenceKey = this.evidenceKey(family, source.channelId)- this.evidence.set(- evidenceKey,- Math.max(this.evidence.get(evidenceKey) ?? 0, source.lastUnreadSeq),- )- }+ if (+ this.disposed+ || token.ownerEpoch !== this.ownerEpoch+ || !this.snapshots.delete(token.nonce)+ ) return+ const family = token.family+ const facet = family === "inbox-mentions" ? "attention" : "ordinary"+ if (!options.stale && !options.truncated && options.confirmedAccessScopes) {+ this.confirmAccessScopes(options.confirmedAccessScopes, {+ ordinal: token.startOrdinal,+ ownerEpoch: token.ownerEpoch,+ })}- for (const [key, arrival] of this.exact) {- if (!arrival.families.has(family)) continue- const source = byChannel.get(arrival.channelId)+ const positiveChannels = new Map<string, number>()+ const positiveAttentionChannels = new Map<string, number>()+ const positiveAttentionIds = new Set(+ sources.flatMap((source) => source.attentionId ? [source.attentionId] : []),+ )+ for (const source of sources) {const evidenceSeq = family === "inbox-mentions"- ? source?.lastMentionSeq ?? source?.lastUnreadSeq- : source?.lastUnreadSeq- if (evidenceSeq !== undefined && evidenceSeq !== null && evidenceSeq >= arrival.seq) {- arrival.families.delete(family)- changed = true- if (arrival.families.size === 0) this.removeExact(key)+ ? source.lastMentionSeq ?? source.lastUnreadSeq+ : source.lastUnreadSeq+ if (!source.channelId || !Number.isSafeInteger(evidenceSeq) || evidenceSeq <= 0) continue+ positiveChannels.set(+ source.channelId,+ Math.max(positiveChannels.get(source.channelId) ?? 0, evidenceSeq),+ )+ if (family === "inbox-mentions" || source.isMention) {+ positiveAttentionChannels.set(+ source.channelId,+ Math.max(positiveAttentionChannels.get(source.channelId) ?? 0, evidenceSeq),+ )}+ this.recordSnapshotSource(family, source, evidenceSeq, token.startOrdinal)}- for (const [channelId, unknown] of this.sticky) {- const pending = unknown.families.get(family)- if (!pending) continue- const source = byChannel.get(channelId)- const evidenceSeq = family === "inbox-mentions"- ? source?.lastMentionSeq ?? source?.lastUnreadSeq- : source?.lastUnreadSeq- if (evidenceSeq !== undefined && evidenceSeq !== null && evidenceSeq > pending.boundary) {- unknown.families.delete(family)- changed = true- if (unknown.families.size === 0) this.sticky.delete(channelId)- }++ if (token.policyGeneration !== this.policyGeneration) {+ this.requestPolicyReconcile()+ return}- if (!options.truncated) {- const key = sentinelKey(family, options.domain ?? familyDomain(family))- const sentinel = this.sentinels.get(key)+ if (options.stale || options.truncated) return+ if (!token.eligibleCoverage.has(facet)) {if (- sentinel?.witnessChannelId- && sentinel.witnessFamily === family- ) {- const source = byChannel.get(sentinel.witnessChannelId)- const evidenceSeq = family === "inbox-mentions"- ? source?.lastMentionSeq ?? source?.lastUnreadSeq- : source?.lastUnreadSeq- if (evidenceSeq !== undefined && evidenceSeq !== null && evidenceSeq > sentinel.boundary) {- changed = this.sentinels.delete(key) || changed+ !this.policyReady+ && this.snapshotWouldRetire(+ token,+ family,+ facet,+ positiveChannels,+ positiveAttentionChannels,+ )+ ) this.prePolicySnapshotNeedsReconcile = true+ return+ }++ let changed = false+ if (family === "inbox-mentions") {+ for (const [nonce, dismissal] of this.dismissals) {+ if (+ dismissal.state === "committed"+ && dismissal.ordinal < token.startOrdinal+ && !positiveAttentionIds.has(dismissal.mentionId)+ ) {+ this.dismissals.delete(nonce)+ changed = true}}}+ for (const [key, arrival] of [...this.exact]) {+ const membershipOrdinal = arrival.families.get(family)+ if (+ membershipOrdinal === undefined+ || membershipOrdinal > token.startOrdinal+ || arrivalDomain(family, arrival.serverId) !== token.domain+ || !this.policyAllows(arrival, facet, token.policy)+ ) continue+ const positiveSeq = (+ family === "inbox-mentions" || arrival.isMention+ ? positiveAttentionChannels+ : positiveChannels+ ).get(arrival.channelId)+ if (positiveSeq !== undefined && positiveSeq >= arrival.seq) continue+ arrival.families.delete(family)+ if (arrival.families.size === 0) this.removeExact(key)+ changed = true+ }+ for (const [channelId, unknown] of [...this.sticky]) {+ const membership = unknown.families.get(family)+ const positiveSeq = (+ family === "inbox-mentions" || unknown.isMention+ ? positiveAttentionChannels+ : positiveChannels+ ).get(channelId)+ if (+ !membership+ || membership.ordinal > token.startOrdinal+ || arrivalDomain(family, unknown.serverId) !== token.domain+ || !this.policyAllows(unknown, facet, token.policy)+ || (positiveSeq !== undefined && positiveSeq <= membership.boundary)+ ) continue+ // A complete response whose channel evidence advanced past the+ // sticky's previous boundary has materialized that unsequenced source+ // into the exact record added above. Retire only this family membership;+ // other families still need their own complete coverage.+ unknown.families.delete(family)+ if (unknown.families.size === 0) this.sticky.delete(channelId)+ changed = true+ }+ changed = this.settleConfirmedMarkAllFences() || changedif (changed) this.publish()}+ cancelSnapshot(token: AccountUnreadSnapshotToken) {+ if (!this.validOwnerToken(token)) return+ this.snapshots.delete(token.nonce)+ }++ absorbFamily(+ family: AccountUnreadFamily,+ sources: readonly AccountUnreadSource[],+ options: {+ truncated?: boolean+ stale?: boolean+ domain?: AccountUnreadDomain+ } = {},+ ) {+ if (this.disposed) return+ const token = this.beginSnapshot(+ family,+ options.domain ?? familyDomain(family),+ )+ this.absorbSnapshot(token, sources, options)+ }++ mergeSources(+ family: AccountUnreadFamily,+ sources: readonly AccountUnreadSource[],+ domain: AccountUnreadDomain = familyDomain(family),+ ) {+ const token = this.beginSnapshot(family, domain)+ this.absorbSnapshot(token, sources, { truncated: true })+ }+projectUnread(family: AccountUnreadFamily,channelId: string,@@ -425,27 +758,52 @@ export class AccountUnreadProjection {sourceSeq?: number | null,domain: AccountUnreadDomain = familyDomain(family),exclusion?: AccountUnreadPresentationExclusion | null,+ exactSourceOnly = false,+ attentionId?: string,) {+ if (this.disposed) return falseconst fence = this.markAll.get(domain)const read = this.effectiveReadSeq(channelId)+ const facet = family === "inbox-mentions" ? "attention" : "ordinary"+ const policySource = this.sourceScope(channelId, sourceSeq)+ if (!this.scopeAllowed(policySource)) return falseconst rawVisible = rawUnread&& !(sourceSeq && read >= sourceSeq)&& !fence+ && this.rawAccessAllowed(family, channelId)&& !excludesUnread(exclusion, channelId, sourceSeq)+ && this.policyAllows(policySource, facet, this.policy)+ && (facet !== "attention" || !this.attentionIdentityDismissed(+ channelId,+ sourceSeq,+ attentionId,+ ))if (rawVisible) return true- const sentinel = this.sentinels.get(sentinelKey(family, domain))- if (sentinel && (!fence || sentinel.ordinal > fence.ordinal)) return truefor (const key of this.exactByChannel.get(channelId) ?? []) {const arrival = this.exact.get(key)if (!arrival || !arrival.families.has(family) || arrival.seq <= read) continue+ if (exactSourceOnly && sourceSeq !== arrival.seq) continueif (excludesUnread(exclusion, channelId, arrival.seq)) continue- if (!fence || arrival.ordinal > fence.ordinal) return true+ const membershipOrdinal = arrival.families.get(family)!+ if (+ (!fence || membershipOrdinal > fence.ordinal)+ && this.policyAllows(arrival, facet, this.policy)+ && (facet !== "attention" || (+ attentionId+ ? !this.attentionIdentityDismissed(channelId, arrival.seq, attentionId)+ : !this.attentionDismissed(arrival)+ ))+ ) return true}+ if (exactSourceOnly) return falseconst sticky = this.sticky.get(channelId)const pending = sticky?.families.get(family)if (pending) {if (excludesUnread(exclusion, channelId)) return false- if (!fence || pending.ordinal > fence.ordinal) return true+ if (+ (!fence || pending.ordinal > fence.ordinal)+ && this.policyAllows(sticky!, facet, this.policy)+ ) return true}return false}@@ -455,10 +813,21 @@ export class AccountUnreadProjection {channelId: string,rawCount: number,sourceSeq?: number | null,+ exclusion?: AccountUnreadPresentationExclusion | null,) {+ if (this.disposed) return 0const fence = this.markAll.get("mentions")const read = this.effectiveReadSeq(channelId)- let count = !fence && !(sourceSeq && read >= sourceSeq) ? rawCount : 0+ const policySource = this.sourceScope(channelId)+ if (!this.scopeAllowed(policySource)) return 0+ let count = !fence+ && !(sourceSeq && read >= sourceSeq)+ && this.rawAccessAllowed(family, channelId)+ && !excludesUnread(exclusion, channelId, sourceSeq)+ && this.policyAllows(policySource, "attention", this.policy)+ ? rawCount+ : 0+ count = Math.max(0, count - this.dismissedAttentionCount(channelId, sourceSeq))for (const key of this.exactByChannel.get(channelId) ?? []) {const arrival = this.exact.get(key)if (@@ -467,7 +836,10 @@ export class AccountUnreadProjection {&& arrival.families.has(family)&& arrival.seq > read&& !(sourceSeq && sourceSeq >= arrival.seq)- && (!fence || arrival.ordinal > fence.ordinal)+ && !excludesUnread(exclusion, channelId, arrival.seq)+ && (!fence || arrival.families.get(family)! > fence.ordinal)+ && this.policyAllows(arrival, "attention", this.policy)+ && !this.attentionDismissed(arrival)) count += 1}return count@@ -489,10 +861,7 @@ export class AccountUnreadProjection {exclusion,)))) return true- if (rawUnread && sources.length === 0 && !this.markAll.get("channels")) return true- const sentinel = this.sentinels.get(sentinelKey("servers", "channels"))- const fence = this.markAll.get("channels")- if (sentinel && (!fence || sentinel.ordinal > fence.ordinal)) return true+ void rawUnreadfor (const arrival of this.exact.values()) {if (arrival.serverId === serverId@@ -540,10 +909,7 @@ export class AccountUnreadProjection {exclusion,)))) return true- if (rawUnread && sources.length === 0 && !this.markAll.get("channels")) return true- const sentinel = this.sentinels.get(sentinelKey(family, "channels"))- const fence = this.markAll.get("channels")- if (sentinel && (!fence || sentinel.ordinal > fence.ordinal)) return true+ void rawUnreadfor (const arrival of this.exact.values()) {if (arrival.serverId === serverId@@ -631,14 +997,15 @@ export class AccountUnreadProjection {_serverId: string,sources: ReadonlyArray<{ channelId: string; count: number; lastSeq: number }>,rawFallback = 0,+ exclusion?: AccountUnreadPresentationExclusion | null,) {- return sources.length === 0 && !this.markAll.get("mentions")- ? rawFallback- : sources.reduce((sum, source) => sum + this.projectMentionCount(+ void rawFallback+ return sources.reduce((sum, source) => sum + this.projectMentionCount("servers",source.channelId,source.count,source.lastSeq,+ exclusion,), 0)}@@ -647,44 +1014,257 @@ export class AccountUnreadProjection {domain?: AccountUnreadDomain,exclusion?: AccountUnreadPresentationExclusion | null,) {- if (family && domain) {- const sentinel = this.sentinels.get(sentinelKey(family, domain))- const fence = this.markAll.get(domain)- if (sentinel && (!fence || sentinel.ordinal > fence.ordinal)) return true- }- if (family && !domain) {- const prefix = `${sentinelFamily(family)}\u0000`- for (const [key, sentinel] of this.sentinels) {- if (!key.startsWith(prefix)) continue- const sentinelDomain = key.slice(prefix.length) as AccountUnreadDomain- const fence = this.markAll.get(sentinelDomain)- if (!fence || sentinel.ordinal > fence.ordinal) return true- }- }+ if (this.disposed) return falsefor (const arrival of this.exact.values()) {if (family && !arrival.families.has(family)) continue+ if (!this.scopeAllowed(arrival)) continueif (excludesUnread(exclusion, arrival.channelId, arrival.seq)) continue- const arrivalDomain = family === "inbox-mentions" || arrival.isMention && domain === "mentions"+ const sourceDomain = family === "inbox-mentions" || arrival.isMention && domain === "mentions"? "mentions": arrival.serverId ? "channels" : "dms"- if (domain && arrivalDomain !== domain) continue- const fence = this.markAll.get(domain ?? arrivalDomain)- if (!fence || arrival.ordinal > fence.ordinal) return true+ if (domain && sourceDomain !== domain) continue+ const fence = this.markAll.get(domain ?? sourceDomain)+ const relevantFamily = family ?? [...arrival.families.keys()].find((candidate) => (+ arrivalDomain(candidate, arrival.serverId) === (domain ?? sourceDomain)+ ))+ if (!relevantFamily) continue+ const facet = relevantFamily === "inbox-mentions" ? "attention" : "ordinary"+ const membershipOrdinal = arrival.families.get(relevantFamily)!+ if (+ (!fence || membershipOrdinal > fence.ordinal)+ && this.policyAllows(arrival, facet, this.policy)+ && (facet !== "attention" || !this.attentionDismissed(arrival))+ ) return true}for (const unknown of this.sticky.values()) {+ if (!this.scopeAllowed(unknown)) continueif (excludesUnread(exclusion, unknown.channelId)) continuefor (const [pendingFamily, pending] of unknown.families) {if (family && pendingFamily !== family) continueconst pendingDomain = arrivalDomain(pendingFamily, unknown.serverId)if (domain && pendingDomain !== domain) continueconst fence = this.markAll.get(domain ?? pendingDomain)- if (!fence || pending.ordinal > fence.ordinal) return true+ const facet = pendingFamily === "inbox-mentions" ? "attention" : "ordinary"+ if (+ (!fence || pending.ordinal > fence.ordinal)+ && this.policyAllows(unknown, facet, this.policy)+ ) return true}}return false}+ setNotificationPolicy(snapshot: AccountUnreadPolicySnapshot) {+ if (this.disposed) return+ const wasReady = this.policyReady+ const nextBase = freezePolicy(snapshot)+ // Query cache writes mirror optimistic controls for the settings UI. They+ // are not authoritative policy while the matching overlay is unresolved,+ // otherwise a failed request could hydrate its own optimistic value into+ // the base and make rollback ineffective.+ for (const overlay of this.policyOverlays.values()) {+ if (overlay.patch.kind === "server") {+ const prior = this.policyBase.server.get(overlay.patch.id)+ if (prior === undefined) nextBase.server.delete(overlay.patch.id)+ else nextBase.server.set(overlay.patch.id, prior)+ } else {+ const prior = this.policyBase.channel.get(overlay.patch.id)+ if (prior === undefined) nextBase.channel.delete(overlay.patch.id)+ else nextBase.channel.set(overlay.patch.id, prior)+ }+ }+ this.policyBase = nextBase+ const changed = this.refreshPolicy(true)+ if (+ changed+ && (wasReady || this.prePolicySnapshotNeedsReconcile)+ ) this.requestPolicyReconcile()+ this.prePolicySnapshotNeedsReconcile = false+ }++ beginNotificationPolicyOverlay(+ patch: AccountUnreadPolicyPatch,+ ): AccountUnreadPolicyToken {+ const token = { nonce: Symbol(patch.id), ownerEpoch: this.ownerEpoch }+ if (this.disposed) return token+ this.policyOverlays.set(token.nonce, { patch, state: "pending" })+ this.refreshPolicy(false)+ return token+ }++ commitNotificationPolicyOverlay(token: AccountUnreadPolicyToken) {+ if (!this.validOwnerToken(token)) return+ const overlay = this.policyOverlays.get(token.nonce)+ if (!overlay) return+ overlay.state = "committed"+ this.flushCommittedPolicyOverlays()+ this.refreshPolicy(false)+ this.requestPolicyReconcile()+ }++ rollbackNotificationPolicyOverlay(token: AccountUnreadPolicyToken) {+ if (!this.validOwnerToken(token) || !this.policyOverlays.delete(token.nonce)) return+ this.flushCommittedPolicyOverlays()+ this.refreshPolicy(false)+ }++ getPolicyGeneration() {+ return this.policyGeneration+ }++ beginDismissMention(input: {+ mentionId: string+ channelId: string+ seq?: number+ countsServerMention?: boolean+ }): AccountUnreadDismissToken {+ const token: AccountUnreadDismissToken = {+ ...input,+ countsServerMention: input.countsServerMention ?? true,+ ordinal: this.disposed ? this.ordinal : ++this.ordinal,+ nonce: Symbol(input.mentionId),+ ownerEpoch: this.ownerEpoch,+ }+ if (!this.disposed) {+ this.dismissals.set(token.nonce, { ...token, state: "pending" })+ this.publish()+ }+ return token+ }++ commitDismissMention(token: AccountUnreadDismissToken, _revision?: number) {+ if (!this.validOwnerToken(token)) return+ // The optimistic facet fence remains until the next complete Mentions+ // snapshot supplies matching negative evidence. A revision hint alone is+ // deliberately insufficient to settle a destructive transaction.+ const dismissal = this.dismissals.get(token.nonce)+ if (!dismissal) return+ dismissal.state = "committed"+ this.publish()+ }++ rollbackDismissMention(token: AccountUnreadDismissToken) {+ if (!this.validOwnerToken(token) || !this.dismissals.delete(token.nonce)) return+ this.publish()+ }++ beginScopeRetirement(scope: AccountUnreadScope): AccountUnreadScopeToken {+ const token: AccountUnreadScopeToken = {+ scope,+ ordinal: this.ordinal,+ nonce: Symbol(scope.kind),+ ownerEpoch: this.ownerEpoch,+ }+ if (!this.disposed) {+ this.accessFences.set(scopeKey(scope), { ...token, state: "pending" })+ this.publish()+ }+ return token+ }++ commitScopeRetirement(token: AccountUnreadScopeToken, _revision?: number) {+ if (!this.validOwnerToken(token)) return+ const current = this.accessFences.get(scopeKey(token.scope))+ if (current?.nonce !== token.nonce) return+ current.state = "committed"+ this.recordRawRetirementFloor(token.scope, this.ordinal)+ this.pruneScope(token.scope, this.ordinal)+ this.publish()+ }++ rollbackScopeRetirement(token: AccountUnreadScopeToken) {+ if (!this.validOwnerToken(token)) return+ const key = scopeKey(token.scope)+ if (this.accessFences.get(key)?.nonce !== token.nonce) return+ this.accessFences.delete(key)+ this.publish()+ }++ retireAccessScope(scope: AccountUnreadScope) {+ if (this.disposed) return+ const token = this.beginScopeRetirement(scope)+ this.commitScopeRetirement(token)+ }++ grantAccessScope(scope: AccountUnreadScope) {+ if (this.disposed) return+ const fence = this.accessFences.get(scopeKey(scope))+ if (!fence) return+ fence.state = "grant-pending"+ // A grant only permits fresh authoritative evidence to seed the scope; it+ // does not expose raw cache retained from before the retirement.+ this.requestReconcile()+ }++ beginAccessConfirmation(): AccountUnreadAccessConfirmationToken {+ return {+ ordinal: this.disposed ? this.ordinal : ++this.ordinal,+ ownerEpoch: this.ownerEpoch,+ }+ }++ confirmAccessScopes(+ scopes: readonly AccountUnreadScope[],+ token: AccountUnreadAccessConfirmationToken,+ ) {+ if (!this.validOwnerToken(token)) return+ let changed = false+ for (const scope of scopes) {+ const key = scopeKey(scope)+ const fence = this.accessFences.get(key)+ if (+ !fence+ || fence.state === "pending"+ || fence.ordinal >= token.ordinal+ ) continue+ this.accessFences.delete(key)+ changed = true+ }+ if (changed) this.publish()+ }++ dispose() {+ if (this.disposed) return+ this.disposed = true+ this.ownerEpoch += 1+ this.exact.clear()+ this.exactByChannel.clear()+ this.sticky.clear()+ this.evidence.clear()+ this.readSeq.clear()+ this.optimisticReads.clear()+ this.markAll.clear()+ this.scopeHints.clear()+ this.rawRetirementFloors.clear()+ this.accessFences.clear()+ this.dismissals.clear()+ this.snapshots.clear()+ this.policyOverlays.clear()+ this.reconcile = null+ this.reconcileScheduled = false+ this.reconcilePendingDelivery = false+ this.listeners.clear()+ this.version += 1+ }++ inspectForTests() {+ return {+ sourceCount: this.exact.size + this.sticky.size,+ exactCount: this.exact.size,+ stickyCount: this.sticky.size,+ readState: [...this.readSeq.entries()].sort(),+ policyGeneration: this.policyGeneration,+ policyReady: this.policyReady,+ highestRevision: this.highestRevision,+ pendingSnapshots: this.snapshots.size,+ disposed: this.disposed,+ }+ }+beginMarkAll(domain: AccountUnreadDomain): MarkAllToken {+ if (this.disposed) {+ return { domain, ordinal: this.ordinal, nonce: Symbol(domain) }+ }const token: MarkAllToken = { domain, ordinal: this.ordinal, nonce: Symbol(domain) }this.markAll.set(domain, { ...token, state: "pending", revision: null })this.publish()@@ -692,6 +1272,7 @@ export class AccountUnreadProjection {}commitMarkAll(token: MarkAllToken, revision: number) {+ if (this.disposed) returnconst fence = this.markAll.get(token.domain)if (!fence || fence.nonce !== token.nonce) returnfence.state = "committed"@@ -700,57 +1281,459 @@ export class AccountUnreadProjection {}rollbackMarkAll(token: MarkAllToken) {+ if (this.disposed) returnconst fence = this.markAll.get(token.domain)if (!fence || fence.nonce !== token.nonce) returnthis.markAll.delete(token.domain)this.publish()}+ private recordSnapshotSource(+ family: AccountUnreadFamily,+ source: AccountUnreadSource,+ evidenceSeq: number,+ observedOrdinal: number,+ ) {+ const evidenceKey = this.evidenceKey(family, source.channelId)+ this.evidence.set(+ evidenceKey,+ Math.max(this.evidence.get(evidenceKey) ?? 0, evidenceSeq),+ )+ const knownSource = this.findSourceScope(source.channelId)+ const knownScope = knownSource ?? this.scopeHints.get(source.channelId)+ const sourceArrival = {+ channelId: source.channelId,+ serverId: source.serverId ?? knownScope?.serverId,+ railChannelId: source.railChannelId ?? knownScope?.railChannelId,+ messageId: source.messageId,+ attentionId: source.attentionId,+ seq: evidenceSeq,+ isMention: source.isMention === true || family === "inbox-mentions",+ }+ const observedFamilies: AccountUnreadFamily[] = family === "inbox-mentions"+ ? sourceArrival.serverId+ ? familiesFor(sourceArrival)+ : knownSource?.families.has("dms")+ ? ["inbox-unreads", "inbox-mentions", "dms"]+ : ["inbox-unreads", "inbox-mentions"]+ : [family]+ for (const key of this.exactByChannel.get(source.channelId) ?? []) {+ const existing = this.exact.get(key)+ if (!existing || existing.seq !== evidenceSeq) continue+ for (const observedFamily of observedFamilies) {+ existing.families.set(+ observedFamily,+ Math.max(existing.families.get(observedFamily) ?? -1, observedOrdinal),+ )+ }+ if (sourceArrival.isMention && !existing.isMention) {+ existing.isMention = true+ }+ if (source.attentionId) existing.attentionIds.add(source.attentionId)+ if (!existing.serverId && source.serverId) {+ existing.serverId = source.serverId+ }+ if (!existing.railChannelId && source.railChannelId) {+ existing.railChannelId = source.railChannelId+ }+ this.publish()+ return+ }+ this.recordArrivalForFamilies(sourceArrival, observedFamilies, observedOrdinal)+ }++ private clonePolicy(): FrozenPolicy {+ return {+ all: this.policy.all,+ server: new Map(this.policy.server),+ channel: new Map(this.policy.channel),+ parentByChannel: new Map(this.policy.parentByChannel),+ }+ }++ private applyPolicyPatch(policy: MutablePolicy, patch: AccountUnreadPolicyPatch) {+ if (patch.kind === "server") {+ policy.server.set(patch.id, normalizePolicyLevel(patch.level))+ return+ }+ if (patch.level === null) policy.channel.delete(patch.id)+ else policy.channel.set(patch.id, normalizePolicyLevel(patch.level))+ }++ private flushCommittedPolicyOverlays() {+ for (const [nonce, overlay] of this.policyOverlays) {+ if (overlay.state !== "committed") break+ this.applyPolicyPatch(this.policyBase, overlay.patch)+ this.policyOverlays.delete(nonce)+ }+ }++ private refreshPolicy(markReady: boolean) {+ const next: MutablePolicy = {+ all: this.policyBase.all,+ server: new Map(this.policyBase.server),+ channel: new Map(this.policyBase.channel),+ parentByChannel: new Map(this.policyBase.parentByChannel),+ }+ for (const overlay of this.policyOverlays.values()) {+ this.applyPolicyPatch(next, overlay.patch)+ }+ const becameReady = markReady && !this.policyReady+ if (!becameReady && policySignature(next) === policySignature(this.policy)) return false+ this.policy = next+ if (markReady) this.policyReady = true+ this.policyGeneration += 1+ this.publish()+ return true+ }++ private policyLevelFor(+ source: Pick<PendingArrival, "channelId" | "serverId" | "railChannelId">,+ policy: FrozenPolicy,+ ) {+ const exact = policy.channel.get(source.channelId)+ if (exact) return exact+ const parentId = source.railChannelId ?? policy.parentByChannel.get(source.channelId)+ if (parentId) {+ const parent = policy.channel.get(parentId)+ if (parent) return parent+ }+ if (source.serverId) return policy.server.get(source.serverId) ?? policy.all+ return policy.all+ }++ private policyAllows(+ source: Pick<PendingArrival, "channelId" | "serverId" | "railChannelId" | "isMention">,+ facet: AccountUnreadFacet,+ policy: FrozenPolicy,+ ) {+ const level = this.policyLevelFor(source, policy)+ if (level === "nothing") return false+ if (facet === "attention") return true+ return level === "all" || source.isMention+ }++ private sourceScope(channelId: string, sourceSeq?: number | null): Pick<+ PendingArrival,+ "channelId" | "serverId" | "railChannelId" | "isMention"+ > {+ if (sourceSeq !== undefined && sourceSeq !== null) {+ for (const key of this.exactByChannel.get(channelId) ?? []) {+ const source = this.exact.get(key)+ if (source?.seq === sourceSeq) return source+ }+ }+ return this.findSourceScope(channelId) ?? {+ ...this.scopeHints.get(channelId),+ channelId,+ isMention: false,+ }+ }++ private findSourceScope(channelId: string): PendingArrival | StickyUnknown | undefined {+ for (const key of this.exactByChannel.get(channelId) ?? []) {+ const source = this.exact.get(key)+ if (source) return source+ }+ return this.sticky.get(channelId)+ }++ private attentionDismissed(+ source: Pick<+ PendingArrival,+ "channelId" | "seq" | "ordinal" | "isMention" | "attentionIds"+ >,+ ) {+ if (!source.isMention) return false+ if (source.attentionIds.size > 0) {+ return [...source.attentionIds].every((attentionId) => (+ this.attentionIdentityDismissed(source.channelId, source.seq, attentionId)+ ))+ }+ for (const dismissal of this.dismissals.values()) {+ if (dismissal.channelId !== source.channelId) continue+ if (dismissal.seq !== undefined && dismissal.seq !== source.seq) continue+ if (source.ordinal <= dismissal.ordinal) return true+ }+ return false+ }++ private attentionIdentityDismissed(+ channelId: string,+ seq?: number | null,+ attentionId?: string,+ ) {+ for (const dismissal of this.dismissals.values()) {+ if (dismissal.channelId !== channelId) continue+ if (attentionId) {+ if (dismissal.mentionId === attentionId) return true+ continue+ }+ if (+ seq !== undefined+ && seq !== null+ && dismissal.seq !== undefined+ && dismissal.seq === seq+ ) return true+ }+ return false+ }++ private dismissedAttentionCount(channelId: string, sourceSeq?: number | null) {+ const identities = new Set<string>()+ for (const dismissal of this.dismissals.values()) {+ if (dismissal.channelId !== channelId) continue+ if (!dismissal.countsServerMention) continue+ if (+ sourceSeq !== undefined+ && sourceSeq !== null+ && dismissal.seq !== undefined+ && dismissal.seq > sourceSeq+ ) continue+ identities.add(dismissal.mentionId)+ }+ return identities.size+ }++ private validOwnerToken(token: { ownerEpoch: number }) {+ return !this.disposed && token.ownerEpoch === this.ownerEpoch+ }++ private scopeAllowed(source: { channelId: string; serverId?: string }) {+ if (this.accessFences.has(`channel:${source.channelId}`)) return false+ return !source.serverId || !this.accessFences.has(`server:${source.serverId}`)+ }++ private scopeAllowsArrival(+ source: { channelId: string; serverId?: string },+ observedOrdinal?: number,+ ) {+ const allowsFence = (+ fence: (AccountUnreadScopeToken & {+ state: "pending" | "committed" | "grant-pending"+ }) | undefined,+ ) => {+ if (!fence || fence.state === "pending") return true+ if (fence.state === "committed") return false+ return observedOrdinal === undefined || observedOrdinal > fence.ordinal+ }+ return allowsFence(this.accessFences.get(`channel:${source.channelId}`))+ && (!source.serverId || allowsFence(this.accessFences.get(`server:${source.serverId}`)))+ }++ private scopeAllowsLegacySnapshot(source: { channelId: string; serverId?: string }) {+ const allowsFence = (+ fence: (AccountUnreadScopeToken & {+ state: "pending" | "committed" | "grant-pending"+ }) | undefined,+ ) => !fence || fence.state === "pending"+ return allowsFence(this.accessFences.get(`channel:${source.channelId}`))+ && (!source.serverId || allowsFence(this.accessFences.get(`server:${source.serverId}`)))+ }++ private rememberScope(source: AccountUnreadScopeHint) {+ const previous = this.scopeHints.get(source.channelId)+ const next = {+ channelId: source.channelId,+ serverId: source.serverId ?? previous?.serverId,+ railChannelId: source.railChannelId ?? previous?.railChannelId,+ }+ this.scopeHints.set(source.channelId, next)+ if (!next.serverId) return+ const serverFence = this.accessFences.get(`server:${next.serverId}`)+ if (!serverFence || serverFence.state === "pending") return+ this.rawRetirementFloors.set(+ source.channelId,+ Math.max(this.rawRetirementFloors.get(source.channelId) ?? -1, serverFence.ordinal),+ )+ }++ private recordRawRetirementFloor(scope: AccountUnreadScope, ordinal: number) {+ if (scope.kind === "channel") {+ this.rawRetirementFloors.set(scope.channelId, ordinal)+ return+ }+ for (const [channelId, hint] of this.scopeHints) {+ if (hint.serverId === scope.serverId) {+ this.rawRetirementFloors.set(channelId, ordinal)+ }+ }+ }++ private rawAccessAllowed(family: AccountUnreadFamily, channelId: string) {+ const floor = this.rawRetirementFloors.get(channelId)+ if (floor === undefined) return true+ for (const key of this.exactByChannel.get(channelId) ?? []) {+ const membership = this.exact.get(key)?.families.get(family)+ if (membership !== undefined && membership > floor) return true+ }+ return (this.sticky.get(channelId)?.families.get(family)?.ordinal ?? -1) > floor+ }++ private pruneScope(scope: AccountUnreadScope, throughOrdinal: number) {+ const matches = (source: { channelId: string; serverId?: string }) => (+ scope.kind === "server"+ ? source.serverId === scope.serverId+ : source.channelId === scope.channelId+ )+ for (const [key, source] of [...this.exact]) {+ if (!matches(source)) continue+ for (const [family, membershipOrdinal] of [...source.families]) {+ if (membershipOrdinal <= throughOrdinal) source.families.delete(family)+ }+ if (source.families.size === 0) this.removeExact(key)+ }+ for (const [channelId, source] of [...this.sticky]) {+ if (!matches(source)) continue+ for (const [family, membership] of [...source.families]) {+ if (membership.ordinal <= throughOrdinal) source.families.delete(family)+ }+ if (source.families.size === 0) this.sticky.delete(channelId)+ }+ }++ private hasCapturedDomainSource(domain: AccountUnreadDomain, throughOrdinal: number) {+ for (const source of this.exact.values()) {+ for (const [family, membershipOrdinal] of source.families) {+ if (+ membershipOrdinal <= throughOrdinal+ && arrivalDomain(family, source.serverId) === domain+ ) return true+ }+ }+ for (const source of this.sticky.values()) {+ for (const [family, membership] of source.families) {+ if (+ membership.ordinal <= throughOrdinal+ && arrivalDomain(family, source.serverId) === domain+ ) return true+ }+ }+ return false+ }++ private settleConfirmedMarkAllFences() {+ let changed = false+ for (const [domain, fence] of [...this.markAll]) {+ if (+ fence.state === "committed"+ && fence.revision !== null+ && fence.revision <= this.highestRevision+ && !this.hasCapturedDomainSource(domain, fence.ordinal)+ ) {+ this.markAll.delete(domain)+ changed = true+ }+ }+ return changed+ }++ private snapshotWouldRetire(+ token: AccountUnreadSnapshotToken,+ family: AccountUnreadFamily,+ facet: AccountUnreadFacet,+ positiveChannels: ReadonlyMap<string, number>,+ positiveAttentionChannels: ReadonlyMap<string, number>,+ ) {+ for (const arrival of this.exact.values()) {+ const membershipOrdinal = arrival.families.get(family)+ if (+ membershipOrdinal !== undefined+ && membershipOrdinal <= token.startOrdinal+ && arrivalDomain(family, arrival.serverId) === token.domain+ && this.policyAllows(arrival, facet, token.policy)+ && ((family === "inbox-mentions" || arrival.isMention+ ? positiveAttentionChannels+ : positiveChannels+ ).get(arrival.channelId) ?? -1) < arrival.seq+ ) return true+ }+ for (const [channelId, source] of this.sticky) {+ const membership = source.families.get(family)+ if (+ membership+ && membership.ordinal <= token.startOrdinal+ && arrivalDomain(family, source.serverId) === token.domain+ && this.policyAllows(source, facet, token.policy)+ && !(family === "inbox-mentions" || source.isMention+ ? positiveAttentionChannels+ : positiveChannels+ ).has(channelId)+ ) return true+ }+ return false+ }++ private requestPolicyReconcile() {+ if (this.lastPolicyReconcileGeneration === this.policyGeneration) return+ this.lastPolicyReconcileGeneration = this.policyGeneration+ this.requestReconcile()+ }++ private requestReconcile() {+ if (this.disposed || this.reconcileScheduled) return+ this.reconcileScheduled = true+ if (this.reconcile) this.reconcile()+ else this.reconcilePendingDelivery = true+ }+private recordSticky(channelId: string,families: AccountUnreadFamily[],isMention: boolean,serverId?: string,railChannelId?: string,+ observedOrdinal?: number,+ messageId?: string | null,+ attentionId?: string,+ attentionIds: ReadonlySet<string> = new Set(),) {- const arrivalOrdinal = ++this.ordinal+ if (this.disposed || !channelId) return+ this.rememberScope({ channelId, serverId, railChannelId })+ if (!this.scopeAllowsArrival({ channelId, serverId })) return+ const arrivalOrdinal = observedOrdinal ?? ++this.ordinallet unknown = this.sticky.get(channelId)if (!unknown) {if (this.sticky.size >= MAX_STICKY_SCOPES) {- for (const family of families) {- const key = sentinelKey(family, arrivalDomain(family, serverId))- const existing = this.sentinels.get(key)- if (existing) {- existing.ordinal = arrivalOrdinal- if (- existing.witnessChannelId !== channelId- || existing.witnessFamily !== family- ) {- existing.witnessChannelId = null- existing.witnessFamily = null- }- } else {- this.sentinels.set(key, {- ordinal: arrivalOrdinal,- witnessChannelId: channelId,- witnessFamily: family,- boundary: this.evidence.get(this.evidenceKey(family, channelId)) ?? 0,- })- }- }- this.publish()- return+ const oldest = [...this.sticky.entries()].reduce<+ [string, StickyUnknown] | null+ >((candidate, entry) => {+ if (!candidate) return entry+ const oldestOrdinal = Math.min(...[...candidate[1].families.values()].map((v) => v.ordinal))+ const entryOrdinal = Math.min(...[...entry[1].families.values()].map((v) => v.ordinal))+ return entryOrdinal < oldestOrdinal ? entry : candidate+ }, null)+ if (oldest) this.sticky.delete(oldest[0])+ this.requestReconcile()}unknown = {channelId,serverId,railChannelId,+ messageId,isMention,+ attentionIds: new Set([+ ...attentionIds,+ ...(attentionId ? [attentionId] : []),+ ]),families: new Map(),}this.sticky.set(channelId, unknown)+ } else if (unknown.messageId === undefined && messageId !== undefined) {+ unknown.messageId = messageId+ } else if (+ unknown.messageId !== null+ && messageId !== undefined+ && unknown.messageId !== messageId+ ) {+ // A channel-scoped sticky may summarize more than one unsequenced+ // arrival. Once identities disagree it is no longer safe to correlate+ // the aggregate with a later exact message.+ unknown.messageId = null}unknown.isMention ||= isMention+ if (attentionId) unknown.attentionIds.add(attentionId)+ for (const id of attentionIds) unknown.attentionIds.add(id)unknown.serverId ??= serverIdunknown.railChannelId ??= railChannelIdfor (const family of families) {@@ -827,8 +1810,13 @@ export function disposeAccountUnreadProjection() {const byUser = owners.get(queryClient)if (!byUser) return- if (ownerUserId) byUser.delete(ownerUserId)- else byUser.clear()+ if (ownerUserId) {+ byUser.get(ownerUserId)?.dispose()+ byUser.delete(ownerUserId)+ } else {+ for (const projection of byUser.values()) projection.dispose()+ byUser.clear()+ }if (!ownerUserId || activeOwners.get(queryClient) === ownerUserId) {activeOwners.delete(queryClient)}diff --git a/src/web/src/hooks/community/community-ws/channel-scope-projection.ts b/src/web/src/hooks/community/community-ws/channel-scope-projection.tsindex 8c123e0b2..55d9332fb 100644--- a/src/web/src/hooks/community/community-ws/channel-scope-projection.ts+++ b/src/web/src/hooks/community/community-ws/channel-scope-projection.ts@@ -19,6 +19,7 @@ import {removeForumSidebarUnreadChild,} from "@/hooks/community/use-forum-sidebar-threads"import type { CommunityWsProjectionTransaction } from "./projection-transaction"+import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"export function projectChannelScopeEviction(projection: CommunityWsProjectionTransaction,@@ -132,6 +133,10 @@ export function applyForumPostUnitClientEffects(queryClient: QueryClient,unit: ForumPostUnitIdentity,) {+ getActiveAccountUnreadProjection(queryClient).retireAccessScope({+ kind: "channel",+ channelId: unit.childChannelId,+ })evictForumPostUnitQueryCaches(queryClient, unit)useMessageStreamStore.getState().removeScope({kind: "channel",diff --git a/src/web/src/hooks/community/community-ws/membership-events.test.ts b/src/web/src/hooks/community/community-ws/membership-events.test.tsindex 5219f40ca..7b4a9e090 100644--- a/src/web/src/hooks/community/community-ws/membership-events.test.ts+++ b/src/web/src/hooks/community/community-ws/membership-events.test.ts@@ -4,6 +4,7 @@ import type { CommunityMemberJoin, CommunityMemberLeave, CommunityMemberUpdate }import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"import type { PresenceResponse } from "@/hooks/community/use-server-panels"import { communityKeys } from "@/lib/query-keys"+import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"import {subscribeMemberOverlayEvents,type MemberOverlayEvent,@@ -13,6 +14,7 @@ import {capturedQueryClient,cleanupCommunityWsHarness,forumSidebarFixture,+ getCommunityApiFetchMock,mountHook,resetCommunityWsHarness,} from "./test-harness"@@ -23,6 +25,8 @@ afterEach(cleanupCommunityWsHarness)describe("useCommunityWs — member events", () => {it("clears the active private route immediately when the viewer leaves the server", async () => {await mountHook({ viewerUserId: "u_me" })+ const unreadProjection = getAccountUnreadProjection(capturedQueryClient, "u_me")+ unreadProjection.recordArrival({ channelId: "private_child", serverId: "srv_1", seq: 1 })const { useCommunityStore } = await import("@/stores/community")useCommunityStore.getState().setCurrentServerId("srv_1")useCommunityStore.getState().setCurrentChannelId("private_child")@@ -59,6 +63,8 @@ describe("useCommunityWs — member events", () => {expect(capturedQueryClient.getQueryState(communityKeys.server("srv_1"))).toBeUndefined()expect(capturedQueryClient.getQueryState(communityKeys.reactionDetails("message_1"))).toBeUndefined()expect(capturedQueryClient.getQueryState(communityKeys.reactionDetails("message_2"))).toBeDefined()+ expect(unreadProjection.projectUnread("servers", "private_child", false)).toBe(false)+ expect(unreadProjection.projectUnread("inbox-unreads", "private_child", true, 1)).toBe(false)})it("evicts an unresolved reaction-details request when the viewer leaves", async () => {@@ -390,6 +396,65 @@ describe("useCommunityWs — member events", () => {})})describe("useCommunityWs — channel.member_add/remove → invalidate rosters", () => {+ it("keeps a viewer's cached raw row fenced across remove then add until fresh access confirms", async () => {+ await mountHook({ viewerUserId: "u_me" })+ const sidebarKey = communityKeys.forumSidebarThreads("srv_1")+ capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture(["private"]))+ const unreadProjection = getAccountUnreadProjection(capturedQueryClient, "u_me")+ unreadProjection.recordArrival({ channelId: "private", serverId: "srv_1", seq: 1 })++ capturedOnMessage!({+ type: "community:channel.member_remove",+ serverId: "srv_1",+ channelId: "private",+ userId: "u_me",+ })+ expect(unreadProjection.projectUnread("inbox-unreads", "private", true, 1)).toBe(false)++ const apiFetch = getCommunityApiFetchMock()+ apiFetch.mockImplementation(async (url: string) => {+ if (url === "/api/community/users/me/read-state") {+ return { revision: 0, readStates: [] }+ }+ if (url.startsWith("/api/community/servers/srv_1/channels?")) {+ return {+ channels: [],+ canonicalChannels: [],+ retainedChannel: {+ id: "private",+ name: "Private",+ parentChannelId: "forum_1",+ parentMessageId: "opener-private",+ activityAt: "2026-08-01T00:00:00.000Z",+ expiresAt: "2099-08-04T00:00:00.000Z",+ unread: false,+ serverId: "srv_1",+ type: "thread",+ },+ retainedDisposition: "eligible",+ included: {+ parentMessages: [{ id: "opener-private", content: "Private" }],+ },+ serverNow: "2026-08-01T00:00:00.000Z",+ }+ }+ throw new Error(`unexpected API fetch: ${url}`)+ })+ capturedOnMessage!({+ type: "community:channel.member_add",+ serverId: "srv_1",+ channelId: "private",+ userId: "u_me",+ })+ await vi.waitFor(() => expect(+ capturedQueryClient.getQueryData(communityKeys.forumSidebarRetained("srv_1", "private")),+ ).toMatchObject({ id: "private" }))+ expect(unreadProjection.projectUnread("inbox-unreads", "private", true, 1)).toBe(false)++ unreadProjection.recordArrival({ channelId: "private", serverId: "srv_1", seq: 2 })+ expect(unreadProjection.projectUnread("inbox-unreads", "private", true, 2)).toBe(true)+ })+it("member_add invalidates channelMembers AND threadParticipants for a child thread", async () => {await mountHook()const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")diff --git a/src/web/src/hooks/community/community-ws/membership-events.ts b/src/web/src/hooks/community/community-ws/membership-events.tsindex da45e1cbe..9629c1554 100644--- a/src/web/src/hooks/community/community-ws/membership-events.ts+++ b/src/web/src/hooks/community/community-ws/membership-events.ts@@ -34,6 +34,7 @@ import {refreshServerReactionDetails,removeServerReactionDetails,} from "./reaction-details-invalidation"+import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"type ChannelMemberEvent = Extract<CommunityWsEvent,@@ -52,6 +53,13 @@ export function handleChannelMemberEvent(event.type === "community:channel.member_remove" &&event.userId === viewerUserIdRef.current) {+ const viewerId = viewerUserIdRef.current+ if (viewerId) {+ getAccountUnreadProjection(queryClient, viewerId).retireAccessScope({+ kind: "channel",+ channelId: event.channelId,+ })+ }projectChannelScopeEviction(projection,queryClient,@@ -62,8 +70,16 @@ export function handleChannelMemberEvent(event.type === "community:channel.member_add" &&event.userId === viewerUserIdRef.current) {+ const viewerId = viewerUserIdRef.current+ if (viewerId) {+ getAccountUnreadProjection(queryClient, viewerId).grantAccessScope({+ kind: "channel",+ channelId: event.channelId,+ })+ }if (!isKnownNonForumSidebarChannel(queryClient, event.serverId, event.channelId)) {void grantForumSidebarChild(queryClient, event.serverId, event.channelId)+ .catch(() => undefined)}}invalidateServerDetail(projection, event.serverId)@@ -119,6 +135,13 @@ export function handleMemberJoin(invalidatePresence(projection, event.serverId)refreshServerReactionDetails(queryClient, event.serverId)if (event.member.userId === viewerUserIdRef.current) {+ const viewerId = viewerUserIdRef.current+ if (viewerId) {+ getAccountUnreadProjection(queryClient, viewerId).grantAccessScope({+ kind: "server",+ serverId: event.serverId,+ })+ }invalidateChannelRefDirectory(projection)invalidateServersList(projection)invalidateServerDetail(projection, event.serverId)@@ -146,6 +169,13 @@ 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) {+ const viewerId = viewerUserIdRef.current+ if (viewerId) {+ getAccountUnreadProjection(queryClient, viewerId).retireAccessScope({+ kind: "server",+ serverId: event.serverId,+ })+ }removeServerReactionDetails(queryClient, event.serverId)invalidateChannelRefDirectory(projection)useMessageStreamStore.getState().removeServer(event.serverId)diff --git a/src/web/src/hooks/community/community-ws/read-state-events.test.ts b/src/web/src/hooks/community/community-ws/read-state-events.test.tsindex 5def451f6..1003fb650 100644--- a/src/web/src/hooks/community/community-ws/read-state-events.test.ts+++ b/src/web/src/hooks/community/community-ws/read-state-events.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from "vitest"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { QueryClient } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"@@ -9,6 +9,9 @@ vi.mock("@/lib/api/client", () => ({import { dispatchCommunityWsEvent } from "./registry"import type { CommunityWsDispatchContext } from "./handler-context"+import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"+import { notificationSettingsQueryFn } from "@/hooks/community/use-notification-settings"+import { disposeAccountReadStateReconciliation } from "./read-state-reconciliation"function context(queryClient: QueryClient,@@ -34,6 +37,11 @@ describe("same-account read-state WS events", () => {apiFetch.mockReset()})+ afterEach(() => {+ disposeAccountReadStateReconciliation(queryClient)+ queryClient.clear()+ })+it("pulls and projects the authoritative replacement for an exact-next hint", async () => {queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {revision: 2,@@ -145,7 +153,9 @@ describe("same-account read-state WS events", () => {}, context(queryClient))await vi.waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())- await Promise.resolve()+ await vi.waitFor(() => expect(queryClient.getQueryState(+ communityKeys.accountReadStateSnapshot(),+ )?.fetchStatus).toBe("idle"))expect(queryClient.getQueryData(communityKeys.accountReadStateSnapshot())).toMatchObject({ revision: 2 })})@@ -190,4 +200,93 @@ describe("same-account read-state WS events", () => {queryKey: communityKeys.dms(),}), expect.anything())})++ it.each([+ ["nothing", "all", [], true],+ ["all", "nothing", [{ serverId: "s1", channelId: null, level: "nothing" }], false],+ ] as const)("reconciles a peer tab from %s to %s policy", async (+ initial,+ _next,+ settings,+ expected,+ ) => {+ const sourceClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ const peerClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ const source = getAccountUnreadProjection(sourceClient, "u1")+ const peer = getAccountUnreadProjection(peerClient, "u1")+ source.setNotificationPolicy({ server: { s1: expected ? "all" : "nothing" } })+ peer.setNotificationPolicy({ server: { s1: initial } })+ source.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })+ peer.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })+ peerClient.setQueryData(communityKeys.accountReadStateSnapshot(), {+ revision: 1,+ readStates: [],+ })+ apiFetch.mockImplementation(async (path: string) => (+ path === "/api/community/users/me/notifications"+ ? settings+ : { revision: 2, readStates: [] }+ ))++ dispatchCommunityWsEvent({+ type: "community:inbox.changed",+ revision: 2,+ inboxChanged: true,+ reason: "notification_policy",+ }, context(peerClient))++ await vi.waitFor(() => expect(+ peer.projectUnread("servers", "c1", false),+ ).toBe(expected))+ expect(peer.projectUnread("servers", "c1", false)).toBe(+ source.projectUnread("servers", "c1", false),+ )+ })++ it("cancels an older in-flight policy fetch and keeps an old unread snapshot positive-only", async () => {+ const projection = getAccountUnreadProjection(queryClient, "u1")+ projection.setNotificationPolicy({ server: { s1: "nothing" } })+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })+ const stalePolicySnapshot = projection.beginSnapshot("servers", "channels")+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {+ revision: 1,+ readStates: [],+ })+ let resolveOldPolicy!: (value: unknown) => void+ let policyCalls = 0+ apiFetch.mockImplementation((path: string) => {+ if (path !== "/api/community/users/me/notifications") {+ return Promise.resolve({ revision: 2, readStates: [] })+ }+ policyCalls += 1+ if (policyCalls === 1) {+ return new Promise((resolve) => { resolveOldPolicy = resolve })+ }+ return Promise.resolve([])+ })+ const oldRequest = queryClient.fetchQuery({+ queryKey: communityKeys.notificationSettings(),+ queryFn: notificationSettingsQueryFn,+ }).catch(() => undefined)+ await vi.waitFor(() => expect(policyCalls).toBe(1))++ dispatchCommunityWsEvent({+ type: "community:inbox.changed",+ revision: 2,+ inboxChanged: true,+ reason: "notification_policy",+ }, context(queryClient))+ await vi.waitFor(() => expect(policyCalls).toBe(2))+ resolveOldPolicy([{ serverId: "s1", channelId: null, level: "nothing" }])+ await oldRequest+ await vi.waitFor(() => expect(projection.getPolicyGeneration()).toBeGreaterThan(1))+ expect(queryClient.getQueryData(communityKeys.notificationSettings())).toMatchObject({+ raw: [],+ server: {},+ channel: {},+ })++ projection.absorbSnapshot(stalePolicySnapshot, [], { truncated: false })+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)+ })})diff --git a/src/web/src/hooks/community/community-ws/social-events.test.ts b/src/web/src/hooks/community/community-ws/social-events.test.tsindex 1c845a57a..5faf66aeb 100644--- a/src/web/src/hooks/community/community-ws/social-events.test.ts+++ b/src/web/src/hooks/community/community-ws/social-events.test.ts@@ -3,6 +3,12 @@ import type {CommunityFriendBlock,CommunityFriendRequest,CommunityMentionCreate,+ CommunityWsEvent,+} from "@alook/shared"+import {+ deriveCommunityDeliveryOperationId,+ encodeCommunityBrowserEventBatch,+ prepareCommunityDeliveryEvents,} from "@alook/shared"import { getMessageOverlay } from "@/stores/community/message-stream"import { communityKeys } from "@/lib/query-keys"@@ -21,6 +27,19 @@ import {beforeEach(resetCommunityWsHarness)afterEach(cleanupCommunityWsHarness)+async function batchFor(messageId: string, events: readonly CommunityWsEvent[]) {+ const operationId = await deriveCommunityDeliveryOperationId(messageId)+ const prepared = await prepareCommunityDeliveryEvents(events)+ if (!prepared.ok) throw new Error("bundle fixture must prepare")+ const encoded = await encodeCommunityBrowserEventBatch({+ operationId,+ operationDigest: prepared.prepared.digest,+ events,+ })+ if (!encoded.ok) throw new Error("bundle fixture must encode")+ return encoded.batch+}+describe("useCommunityWs — account unread projection", () => {function serverDetailFixture(channelId: string) {return {@@ -112,7 +131,20 @@ describe("useCommunityWs — account unread projection", () => {isMention: true,}))expect(getActiveAccountUnreadProjection(capturedQueryClient)- .projectServerMentionCount("srv_x", [], 7)).toBe(7)+ .projectServerMentionCount("srv_x", [], 7)).toBe(0)+ })++ it("merges a valid WS bump before applying the current policy overlay", async () => {+ await mountHook({ viewerUserId: "u_me" })+ const projection = getActiveAccountUnreadProjection(capturedQueryClient)+ projection.setNotificationPolicy({ server: { srv_x: "nothing" } })++ capturedOnMessage!(unreadBump("ch_a", "u_me", { serverId: "srv_x" }))++ expect(projection.inspectForTests().sourceCount).toBe(1)+ expect(projection.projectUnread("servers", "ch_a", false)).toBe(false)+ projection.setNotificationPolicy({ server: { srv_x: "all" } })+ expect(projection.projectUnread("servers", "ch_a", false)).toBe(true)})it("ignores bumps addressed to a different account", async () => {@@ -251,4 +283,39 @@ describe("useCommunityWs — friend + mention → invalidate", () => {return key?.length === 2 && key[0] === "community" && key[1] === "servers"})).toHaveLength(1)})++ it("projects a mention-only delivery into its server and parent scope immediately", async () => {+ await mountHook({ viewerUserId: "u_1" })+ const projection = getActiveAccountUnreadProjection(capturedQueryClient)+ projection.setNotificationPolicy({+ server: { srv_1: "mentions" },+ channel: { forum_1: "mentions" },+ })++ capturedOnMessage!(await batchFor("m_1", [+ unreadBump("post_1", "u_1", {+ serverId: "srv_1",+ railChannelId: "forum_1",+ isMention: true,+ }),+ {+ type: "community:mention.create",+ userId: "u_1",+ messageId: "m_1",+ channelId: "post_1",+ authorName: "A",+ },+ ]))++ expect(projection.projectServerUnread("srv_1", [])).toBe(true)+ expect(projection.projectForumParentUnread(+ "srv_1",+ "forum_1",+ false,+ undefined,+ new Set(),+ )).toBe(true)+ projection.retireAccessScope({ kind: "server", serverId: "srv_1" })+ expect(projection.projectServerUnread("srv_1", [])).toBe(false)+ })})diff --git a/src/web/src/hooks/community/community-ws/social-events.ts b/src/web/src/hooks/community/community-ws/social-events.tsindex 6c9d60973..954c3ae65 100644--- a/src/web/src/hooks/community/community-ws/social-events.ts+++ b/src/web/src/hooks/community/community-ws/social-events.ts@@ -20,6 +20,7 @@ import {} from "./read-state-reconciliation"import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"import { removeDmReactionDetails } from "./reaction-details-invalidation"+import { reconcileNotificationSettings } from "@/hooks/community/use-notification-settings"export function handleReadStateAdvanced(event: CommunityReadStateAdvanced,@@ -46,6 +47,9 @@ export function handleInboxChanged(event: CommunityInboxChanged,context: SocialEventContext,) {+ if (event.reason === "notification_policy") {+ void reconcileNotificationSettings(context.queryClient).catch(() => undefined)+ }applyReadStateEnvelope(event, context)}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.tsindex 1116ef5dd..adfd1f252 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@@ -11,6 +11,7 @@ import type {} from "@alook/shared"import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"import { communityKeys } from "@/lib/query-keys"+import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"import {capturedOnMessage,capturedQueryClient,@@ -168,6 +169,20 @@ describe("useCommunityWs — invite.create", () => {})describe("useCommunityWs — channel.delete evicts channel-scoped caches", () => {+ it("fences a deleted channel's cached raw Inbox row", async () => {+ await mountHook({ viewerUserId: "u_me" })+ const unreadProjection = getAccountUnreadProjection(capturedQueryClient, "u_me")+ unreadProjection.recordArrival({ channelId: "ch_dead", serverId: "srv_1", seq: 1 })++ capturedOnMessage!({+ type: "community:channel.delete",+ serverId: "srv_1",+ channelId: "ch_dead",+ } satisfies CommunityChannelDelete)++ expect(unreadProjection.projectUnread("inbox-unreads", "ch_dead", true, 1)).toBe(false)+ })+it("removes channelMessages, pins, and threads for the deleted channel", async () => {await mountHook()// Seed every canonical cache for the target channel so we can observe eviction.@@ -856,6 +871,19 @@ describe("useCommunityWs — server.update icon removal", () => {})describe("useCommunityWs — server.delete resets store when focused server dies", () => {+ it("fences cached raw Inbox rows from the deleted server", async () => {+ await mountHook({ viewerUserId: "u_me" })+ const unreadProjection = getAccountUnreadProjection(capturedQueryClient, "u_me")+ unreadProjection.recordArrival({ channelId: "ch_dead", serverId: "srv_doomed", seq: 1 })++ capturedOnMessage!({+ type: "community:server.delete",+ serverId: "srv_doomed",+ } satisfies CommunityServerDelete)++ expect(unreadProjection.projectUnread("inbox-unreads", "ch_dead", true, 1)).toBe(false)+ })+it("clears currentServerId + currentChannelId if the deleted server is currently focused", async () => {await mountHook()const { useCommunityStore } = await import("@/stores/community")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 6497108e6..ef817d747 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@@ -46,6 +46,7 @@ import {invalidateServersList,invalidateThreads,} from "./invalidation-projections"+import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"export function handleChildChannelCreate(event: CommunityChildChannelCreate,@@ -162,6 +163,7 @@ export function handleChildChannelUpdate(removeForumSidebarThreadExact(queryClient, sidebarServerId, event.channelId)} else if (changes.archived === false) {void grantForumSidebarChild(queryClient, sidebarServerId, event.channelId)+ .catch(() => undefined)} else if (changes.tags !== undefined) {void reconcileForumSidebarArchiveTag(queryClient,@@ -297,6 +299,10 @@ export function handleServerDelete(event: CommunityServerDelete,{ queryClient, projection }: StructureTreeEventContext,) {+ getActiveAccountUnreadProjection(queryClient).retireAccessScope({+ kind: "server",+ serverId: event.serverId,+ })invalidateChannelRefDirectory(projection)// Refresh the rail LIST only (drop the deleted server). `exact`// so this doesn't cascade-refetch every other server's nested@@ -347,6 +353,10 @@ export function handleChannelEvent(exact: true,})} else {+ getActiveAccountUnreadProjection(queryClient).retireAccessScope({+ kind: "channel",+ channelId: event.channelId,+ })projectChannelScopeEviction(projection,queryClient,diff --git a/src/web/src/hooks/community/mutations/channels.test.ts b/src/web/src/hooks/community/mutations/channels.test.tsindex 741bfc4c2..a589cb892 100644--- a/src/web/src/hooks/community/mutations/channels.test.ts+++ b/src/web/src/hooks/community/mutations/channels.test.ts@@ -450,6 +450,40 @@ describe("useCreateCategory — optimistic pending category", () => {})})+describe("useDeleteChannel", () => {+ it("retires projected unread after a successful DELETE without waiting for self-WS", async () => {+ const mod = await load()+ const { getActiveAccountUnreadProjection } = await import(+ "@/hooks/community/account-unread-projection"+ )+ const projection = getActiveAccountUnreadProjection(capturedQc)+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })+ mod.useDeleteChannel()+ apiFetchMock.mockResolvedValueOnce(undefined)++ await runMutation({ serverId: "s1", channelId: "c1" })++ expect(projection.projectUnread("servers", "c1", false)).toBe(false)+ expect(projection.projectUnread("inbox-unreads", "c1", true, 1)).toBe(false)+ })++ it("keeps projected unread when the DELETE fails", async () => {+ const mod = await load()+ const { getActiveAccountUnreadProjection } = await import(+ "@/hooks/community/account-unread-projection"+ )+ const projection = getActiveAccountUnreadProjection(capturedQc)+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })+ mod.useDeleteChannel()+ apiFetchMock.mockRejectedValueOnce(new Error("500"))++ await expect(runMutation({ serverId: "s1", channelId: "c1" })).rejects.toThrow("500")++ expect(projection.projectUnread("servers", "c1", false)).toBe(true)+ expect(projection.projectUnread("inbox-unreads", "c1", true, 1)).toBe(true)+ })+})+describe("useDeleteCategory — optimistic removal with rollback", () => {type Cat = { id: string; name: string; channels: unknown[] }const seed = (categories: Cat[]) =>diff --git a/src/web/src/hooks/community/mutations/channels.ts b/src/web/src/hooks/community/mutations/channels.tsindex 10bbc472a..2844a0c21 100644--- a/src/web/src/hooks/community/mutations/channels.ts+++ b/src/web/src/hooks/community/mutations/channels.ts@@ -7,6 +7,7 @@ import { communityKeys } from "@/lib/query-keys"import type { ChannelRefDirectory } from "@/lib/community/channel-ref"import type { ServerDetail } from "@/hooks/community/use-servers"import { UNCATEGORIZED_CATEGORY_ID, type ChannelType } from "@alook/shared"+import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"// Prefix marks an optimistic row so every consumer can tell it from a real// `ch_…` id without a separate flag, and guarantees it never collides with one.@@ -287,6 +288,10 @@ export function useDeleteChannel() {await apiFetch(`/api/community/channels/${channelId}`, { method: "DELETE" })},onSuccess: (_data, args) => {+ getActiveAccountUnreadProjection(queryClient).retireAccessScope({+ kind: "channel",+ channelId: args.channelId,+ })if (args.serverId) {void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })}diff --git a/src/web/src/hooks/community/mutations/forum.test.ts b/src/web/src/hooks/community/mutations/forum.test.tsindex d43ad4130..1e2a1ea8b 100644--- a/src/web/src/hooks/community/mutations/forum.test.ts+++ b/src/web/src/hooks/community/mutations/forum.test.ts@@ -319,6 +319,11 @@ describe("useDeleteForumThread", () => {const { useCommunityStore } = await import("@/stores/community")const { getMessageOverlay, useMessageStreamStore } = await import("@/stores/community/message-stream")const { applyForumPostUnitClientEffects } = await import("@/hooks/community/community-ws/channel-scope-projection")+ const { getActiveAccountUnreadProjection } = await import(+ "@/hooks/community/account-unread-projection"+ )+ const unreadProjection = getActiveAccountUnreadProjection(capturedQc)+ unreadProjection.recordArrival({ channelId: "p2", serverId: "server_1", seq: 1 })useCommunityStore.getState().reset()useMessageStreamStore.getState().resetAll()const replacePath = vi.fn()@@ -366,6 +371,8 @@ describe("useDeleteForumThread", () => {expect(clearLastChannelMock).toHaveBeenCalledOnce()expect(replacePath).toHaveBeenCalledOnce()expect(replacePath).toHaveBeenCalledWith("/c/channels/server_1/forum_1")+ expect(unreadProjection.projectUnread("servers", "p2", false)).toBe(false)+ expect(unreadProjection.projectUnread("inbox-unreads", "p2", true, 1)).toBe(false)applyForumPostUnitClientEffects(capturedQc, {serverId: "server_1",@@ -438,6 +445,11 @@ describe("useDeleteForumThread", () => {it("restores exact feed/sidebar/meta snapshots when the DELETE fails", async () => {const { useDeleteForumThread } = await load()+ const { getActiveAccountUnreadProjection } = await import(+ "@/hooks/community/account-unread-projection"+ )+ const unreadProjection = getActiveAccountUnreadProjection(capturedQc)+ unreadProjection.recordArrival({ channelId: "p2", serverId: "server_1", seq: 1 })useDeleteForumThread()const before = { pages: [{ messages: [{ id: "m_p2" }] }], pageParams: [null] }@@ -476,6 +488,9 @@ describe("useDeleteForumThread", () => {openerMessageId: "m_p2",})+ expect(unreadProjection.projectUnread("servers", "p2", false)).toBe(true)+ expect(unreadProjection.projectUnread("inbox-unreads", "p2", true, 1)).toBe(true)+expect(capturedQc.getQueryData(communityKeys.channelMessages("forum_1"))).toEqual(before)expect(capturedQc.getQueryData(communityKeys.forumFeed("forum_1", null))).toEqual(feedBefore)expect(capturedQc.getQueryData(sidebarKey)).toEqual(sidebarBefore)diff --git a/src/web/src/hooks/community/mutations/messages.test.ts b/src/web/src/hooks/community/mutations/messages.test.tsindex 7b1b5b48e..52285b5ca 100644--- a/src/web/src/hooks/community/mutations/messages.test.ts+++ b/src/web/src/hooks/community/mutations/messages.test.ts@@ -1051,6 +1051,98 @@ describe("useMarkAllInboxRead", () => {// ── useDeleteMention — rollback ──────────────────────────────────────────describe("useDeleteMention — rollback", () => {+ it("keeps a same-seq sibling and only decrements badges for direct mentions", async () => {+ const reply = {+ id: "reply-1",+ kind: "reply",+ channelId: "ch_1",+ m: { id: "msg_1", seq: 4 },+ }+ const mention = {+ id: "mention-1",+ kind: "mention",+ channelId: "ch_1",+ m: { id: "msg_1", seq: 4 },+ }+ capturedQc.setQueryData(communityKeys.inboxMentions(), {+ mentions: [reply, mention],+ })+ const mod = await loadMod()+ const { getActiveAccountUnreadProjection } = await import(+ "@/hooks/community/account-unread-projection"+ )+ const projection = getActiveAccountUnreadProjection(capturedQc)+ projection.setNotificationPolicy({})+ for (const attentionId of [reply.id, mention.id]) {+ projection.recordArrival({+ channelId: "ch_1",+ serverId: "srv_1",+ messageId: "msg_1",+ attentionId,+ seq: 4,+ isMention: true,+ })+ }+ mod.useDeleteMention()+ const cfg = capturedConfig as MutConfig<+ { mentionId: string },+ { token?: unknown; snapshot?: unknown }+ >++ const replyContext = await cfg.onMutate?.({ mentionId: reply.id })+ expect(capturedQc.getQueryData<{ mentions: Array<{ id: string }> }>(+ communityKeys.inboxMentions(),+ )?.mentions.map((row) => row.id)).toEqual([mention.id])+ expect(projection.projectUnread(+ "inbox-mentions", "ch_1", true, 4, "mentions", null, true, mention.id,+ )).toBe(true)+ expect(projection.projectServerMentionCount("srv_1", [{+ channelId: "ch_1", count: 1, lastSeq: 4,+ }])).toBe(1)++ cfg.onError?.(new Error("retry direct"), { mentionId: reply.id }, replyContext)+ const mentionContext = await cfg.onMutate?.({ mentionId: mention.id })+ expect(capturedQc.getQueryData<{ mentions: Array<{ id: string }> }>(+ communityKeys.inboxMentions(),+ )?.mentions.map((row) => row.id)).toEqual([reply.id])+ expect(projection.projectUnread(+ "inbox-mentions", "ch_1", true, 4, "mentions", null, true, reply.id,+ )).toBe(true)+ expect(projection.projectServerMentionCount("srv_1", [{+ channelId: "ch_1", count: 1, lastSeq: 4,+ }])).toBe(0)+ cfg.onError?.(new Error("cleanup"), { mentionId: mention.id }, mentionContext)+ })++ it("hides only the exact attention facet and restores it on failure", async () => {+ capturedQc.setQueryData(communityKeys.inboxMentions(), {+ mentions: [{ id: "men_1", channelId: "ch_1", m: { id: "msg_1", seq: 4 } }],+ })+ const mod = await loadMod()+ const { getActiveAccountUnreadProjection } = await import(+ "@/hooks/community/account-unread-projection"+ )+ const projection = getActiveAccountUnreadProjection(capturedQc)+ projection.recordArrival({+ channelId: "ch_1",+ serverId: "srv_1",+ messageId: "msg_1",+ seq: 4,+ isMention: true,+ })+ mod.useDeleteMention()+ const cfg = capturedConfig as MutConfig<+ { mentionId: string },+ { token?: unknown; snapshot?: unknown }+ >+ const context = await cfg.onMutate?.({ mentionId: "men_1" })+ expect(projection.projectUnread("inbox-unreads", "ch_1", false)).toBe(true)+ expect(projection.projectUnread("inbox-mentions", "ch_1", false)).toBe(false)++ cfg.onError?.(new Error("boom"), { mentionId: "men_1" }, context)+ expect(projection.projectUnread("inbox-mentions", "ch_1", false)).toBe(true)+ })+it("restores mention on failure", async () => {capturedQc.setQueryData(communityKeys.inboxMentions(), {mentions: [{ id: "men_1" }],diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.tsindex 4cf4c546a..8ce386d39 100644--- a/src/web/src/hooks/community/mutations/messages.ts+++ b/src/web/src/hooks/community/mutations/messages.ts@@ -27,7 +27,11 @@ import {} from "@/lib/community/message-stream"import type { Attachment, MessagesPage, Msg } from "@/lib/community/models/message"import type { PinsResponse } from "@/hooks/community/use-channel-panels"-import type { MarkedResponse, MessageMarkedResponse } from "@/hooks/community/use-inbox"+import type {+ MarkedResponse,+ MentionsResponse,+ MessageMarkedResponse,+} from "@/hooks/community/use-inbox"import {getForumSidebarBase,hasForumSidebarThread,@@ -39,6 +43,7 @@ import { reconcileForumOpenerTitle } from "@/hooks/community/forum-opener-title-import { isBlocked, type MentionType } from "@alook/shared"import {getActiveAccountUnreadProjection,+ type AccountUnreadDismissToken,type AccountUnreadDomain,type MarkAllToken,} from "@/hooks/community/account-unread-projection"@@ -913,24 +918,44 @@ export type DeleteMentionArgs = { mentionId: string }export function useDeleteMention() {const queryClient = useQueryClient()- return useMutation<void, Error, DeleteMentionArgs, { snapshot: unknown }>({+ const unreadProjection = getActiveAccountUnreadProjection(queryClient)+ return useMutation<+ { revision: number },+ Error,+ DeleteMentionArgs,+ { snapshot: MentionsResponse | undefined; token?: AccountUnreadDismissToken }+ >({mutationFn: async ({ mentionId }) => {- await apiFetch(`/api/community/users/me/inbox/mentions/${mentionId}`, { method: "DELETE" })+ return apiFetch<{ revision: number }>(+ `/api/community/users/me/inbox/mentions/${mentionId}`,+ { method: "DELETE" },+ )},onMutate: async (args) => {const key = communityKeys.inboxMentions()- const snapshot = queryClient.getQueryData(key)+ const snapshot = queryClient.getQueryData<MentionsResponse>(key)+ const row = snapshot?.mentions.find((mention) => mention.id === args.mentionId)+ const token = row?.channelId+ ? unreadProjection.beginDismissMention({+ mentionId: args.mentionId,+ channelId: row.channelId,+ seq: row.m.seq,+ countsServerMention: row.kind !== "reply",+ })+ : undefinedqueryClient.setQueryData(key, (prev: { mentions: { id: string }[] } | undefined) =>prev ? { ...prev, mentions: prev.mentions.filter((m) => m.id !== args.mentionId) } : prev,)- return { snapshot }+ return { snapshot, token }},- onSuccess: () => {+ onSuccess: (result, _args, context) => {+ if (context.token) unreadProjection.commitDismissMention(context.token, result?.revision)// Deleting a mention row removes it from the unread-mention aggregate// that feeds the server rail badge — refresh so the count drops.void queryClient.invalidateQueries({ queryKey: communityKeys.servers() })},onError: (err, _args, ctx) => {+ if (ctx?.token) unreadProjection.rollbackDismissMention(ctx.token)if (ctx?.snapshot) queryClient.setQueryData(communityKeys.inboxMentions(), ctx.snapshot)toastApiError(err, "Failed to remove mention")},diff --git a/src/web/src/hooks/community/mutations/notifications.test.ts b/src/web/src/hooks/community/mutations/notifications.test.tsindex 86dc3c7cd..edcfc884c 100644--- a/src/web/src/hooks/community/mutations/notifications.test.ts+++ b/src/web/src/hooks/community/mutations/notifications.test.ts@@ -1,12 +1,16 @@import { beforeEach, describe, expect, it, vi } from "vitest"import { QueryClient } from "@tanstack/react-query"+import { USE_SERVER_DEFAULT } from "@alook/shared"import { communityKeys } from "@/lib/query-keys"const apiFetch = vi.fn()vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetch(...args) }))type MutationConfig = {- onSuccess?: (data: unknown, args: any) => void+ mutationFn?: (args: any) => Promise<unknown>+ onSuccess?: (data: unknown, args: any, context?: any) => void+ onMutate?: (args: any) => Promise<any>+ onError?: (error: unknown, args: any, context: any) => void}let config: MutationConfig | null = nulllet queryClient: QueryClient@@ -30,6 +34,71 @@ beforeEach(() => {})describe("notification mutation cache refresh", () => {+ it("changes only reversible eligibility and restores it on failure", async () => {+ const settings = {+ raw: [],+ server: { server_1: "All Messages" },+ channel: {},+ }+ queryClient.setQueryData(communityKeys.notificationSettings(), settings)+ const { getActiveAccountUnreadProjection } = await import("../account-unread-projection")+ const projection = getActiveAccountUnreadProjection(queryClient)+ projection.recordArrival({ channelId: "channel_1", serverId: "server_1", seq: 2 })+ const before = projection.inspectForTests()+ const { useSetServerNotifLevel } = await import("./notifications")+ useSetServerNotifLevel()++ const context = await config!.onMutate?.({ serverId: "server_1", level: "Nothing" })+ expect(projection.projectUnread("servers", "channel_1", false)).toBe(false)+ expect(projection.inspectForTests().sourceCount).toBe(before.sourceCount)+ expect(projection.inspectForTests().readState).toEqual(before.readState)++ projection.setNotificationPolicy({ server: { server_1: "Nothing" } })++ config!.onError?.(new Error("failed"), { serverId: "server_1", level: "Nothing" }, context)+ expect(projection.projectUnread("servers", "channel_1", false)).toBe(true)+ })++ it("keeps an absent settings cache absent while applying a reversible server overlay", async () => {+ const { getActiveAccountUnreadProjection } = await import("../account-unread-projection")+ const projection = getActiveAccountUnreadProjection(queryClient)+ projection.setNotificationPolicy({})+ projection.recordArrival({ channelId: "channel_1", serverId: "server_1", seq: 2 })+ const { useSetServerNotifLevel } = await import("./notifications")+ useSetServerNotifLevel()++ const args = { serverId: "server_1", level: "Nothing" }+ const context = await config!.onMutate?.(args)++ expect(queryClient.getQueryData(communityKeys.notificationSettings())).toBeUndefined()+ expect(projection.projectUnread("servers", "channel_1", false)).toBe(false)+ config!.onError?.(new Error("failed"), args, context)+ expect(projection.projectUnread("servers", "channel_1", false)).toBe(true)+ })++ it("rolls back one server field without clobbering a concurrent success", async () => {+ queryClient.setQueryData(communityKeys.notificationSettings(), {+ raw: [],+ server: { server_1: "All Messages", server_2: "All Messages" },+ channel: {},+ })+ const { useSetServerNotifLevel } = await import("./notifications")+ useSetServerNotifLevel()++ const first = await config!.onMutate?.({ serverId: "server_1", level: "Nothing" })+ const second = await config!.onMutate?.({ serverId: "server_2", level: "Nothing" })+ config!.onSuccess?.(undefined, { serverId: "server_2", level: "Nothing" }, second)+ config!.onError?.(+ new Error("first failed"),+ { serverId: "server_1", level: "Nothing" },+ first,+ )++ expect(queryClient.getQueryData(communityKeys.notificationSettings())).toMatchObject({+ server: { server_1: "All Messages", server_2: "Nothing" },+ })+ })+it("refreshes settings, inbox, and all read-state snapshots after a server change", async () => {const invalidate = vi.spyOn(queryClient, "invalidateQueries")const { useSetServerNotifLevel } = await import("./notifications")@@ -60,4 +129,79 @@ describe("notification mutation cache refresh", () => {expect(predicate!({ queryKey: communityKeys.dmReadStateSnapshot("dm_1") } as any)).toBe(true)expect(predicate!({ queryKey: communityKeys.inbox() } as any)).toBe(false)})++ it("PUTs and rolls back a new channel override", async () => {+ queryClient.setQueryData(communityKeys.notificationSettings(), {+ raw: [],+ server: {},+ channel: {},+ })+ const { useSetChannelNotif } = await import("./notifications")+ useSetChannelNotif()++ const args = { channelId: "channel_1", level: "Nothing" }+ const context = await config!.onMutate?.(args)+ expect(queryClient.getQueryData(communityKeys.notificationSettings())).toMatchObject({+ channel: { channel_1: "Nothing" },+ })+ await config!.mutationFn?.(args)+ expect(apiFetch).toHaveBeenCalledWith(+ "/api/community/users/me/notifications/channel/channel_1",+ { method: "PUT", body: JSON.stringify({ level: "nothing" }) },+ )++ config!.onError?.(new Error("failed"), args, context)+ expect(queryClient.getQueryData(communityKeys.notificationSettings())).toMatchObject({+ channel: {},+ })+ })++ it("DELETEs and restores an inherited channel override", async () => {+ queryClient.setQueryData(communityKeys.notificationSettings(), {+ raw: [],+ server: {},+ channel: { channel_1: "Nothing" },+ })+ const { useSetChannelNotif } = await import("./notifications")+ useSetChannelNotif()++ const args = { channelId: "channel_1", level: USE_SERVER_DEFAULT }+ const context = await config!.onMutate?.(args)+ expect(queryClient.getQueryData(communityKeys.notificationSettings())).toMatchObject({+ channel: {},+ })+ await config!.mutationFn?.(args)+ expect(apiFetch).toHaveBeenCalledWith(+ "/api/community/users/me/notifications/channel/channel_1",+ { method: "DELETE" },+ )++ config!.onError?.(new Error("failed"), args, context)+ expect(queryClient.getQueryData(communityKeys.notificationSettings())).toMatchObject({+ channel: { channel_1: "Nothing" },+ })+ })++ it("does not let a failed channel override clobber a concurrent value", async () => {+ queryClient.setQueryData(communityKeys.notificationSettings(), {+ raw: [],+ server: {},+ channel: {},+ })+ const { useSetChannelNotif } = await import("./notifications")+ useSetChannelNotif()+ const args = { channelId: "channel_1", level: "Nothing" }+ const context = await config!.onMutate?.(args)+ queryClient.setQueryData(communityKeys.notificationSettings(), {+ raw: [],+ server: {},+ channel: { channel_1: "All Messages" },+ })++ config!.onError?.(new Error("failed"), args, context)++ expect(queryClient.getQueryData(communityKeys.notificationSettings())).toMatchObject({+ channel: { channel_1: "All Messages" },+ })+ })})diff --git a/src/web/src/hooks/community/mutations/notifications.ts b/src/web/src/hooks/community/mutations/notifications.tsindex b7db46cac..bd2b7ed2a 100644--- a/src/web/src/hooks/community/mutations/notifications.ts+++ b/src/web/src/hooks/community/mutations/notifications.ts@@ -5,6 +5,8 @@ import { normalizeNotifLevel, USE_SERVER_DEFAULT } from "@alook/shared"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import type { NotificationSettings } from "@/hooks/community/use-notification-settings"+import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"+import type { AccountUnreadPolicyToken } from "@/hooks/community/account-unread-projection"/*** Notification-level mutations. UI presents display strings ("All Messages",@@ -20,11 +22,15 @@ export type SetServerNotifLevelArgs = { serverId: string; level: string }export function useSetServerNotifLevel() {const queryClient = useQueryClient()+ const projection = getActiveAccountUnreadProjection(queryClient)return useMutation<void,Error,SetServerNotifLevelArgs,- { snapshot: NotificationSettings | undefined }+ {+ previousLevel: string | undefined+ token: AccountUnreadPolicyToken+ }>({mutationFn: async ({ serverId, level }) => {await apiFetch(`/api/community/users/me/notifications/server/${serverId}`, {@@ -36,15 +42,32 @@ export function useSetServerNotifLevel() {const key = communityKeys.notificationSettings()await queryClient.cancelQueries({ queryKey: key })const snapshot = queryClient.getQueryData<NotificationSettings>(key)- queryClient.setQueryData<NotificationSettings | undefined>(key, (prev) =>- prev ? { ...prev, server: { ...prev.server, [args.serverId]: args.level } } : prev,- )- return { snapshot }+ const next = snapshot+ ? { ...snapshot, server: { ...snapshot.server, [args.serverId]: args.level } }+ : undefined+ queryClient.setQueryData<NotificationSettings | undefined>(key, next)+ const token = projection.beginNotificationPolicyOverlay({+ kind: "server",+ id: args.serverId,+ level: args.level,+ })+ return { previousLevel: snapshot?.server[args.serverId], token }},- onError: (_err, _args, ctx) => {- if (ctx?.snapshot) queryClient.setQueryData(communityKeys.notificationSettings(), ctx.snapshot)+ onError: (_err, args, ctx) => {+ if (ctx) projection.rollbackNotificationPolicyOverlay(ctx.token)+ queryClient.setQueryData<NotificationSettings | undefined>(+ communityKeys.notificationSettings(),+ (current) => {+ if (!current || !ctx || current.server[args.serverId] !== args.level) return current+ const server = { ...current.server }+ if (ctx.previousLevel === undefined) delete server[args.serverId]+ else server[args.serverId] = ctx.previousLevel+ return { ...current, server }+ },+ )},- onSuccess: () => {+ onSuccess: (_data, _args, ctx) => {+ if (ctx) projection.commitNotificationPolicyOverlay(ctx.token)queryClient.invalidateQueries({ queryKey: communityKeys.notificationSettings() })queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })queryClient.invalidateQueries({ queryKey: communityKeys.servers() })@@ -61,11 +84,16 @@ export type SetChannelNotifArgs = { channelId: string; level: string }export function useSetChannelNotif() {const queryClient = useQueryClient()+ const projection = getActiveAccountUnreadProjection(queryClient)return useMutation<void,Error,SetChannelNotifArgs,- { snapshot: NotificationSettings | undefined }+ {+ previousLevel: string | undefined+ optimisticLevel: string | undefined+ token: AccountUnreadPolicyToken+ }>({mutationFn: async ({ channelId, level }) => {if (level === USE_SERVER_DEFAULT) {@@ -83,22 +111,42 @@ export function useSetChannelNotif() {const key = communityKeys.notificationSettings()await queryClient.cancelQueries({ queryKey: key })const snapshot = queryClient.getQueryData<NotificationSettings>(key)- queryClient.setQueryData<NotificationSettings | undefined>(key, (prev) => {- if (!prev) return prev- const nextChannel = { ...prev.channel }- if (args.level === USE_SERVER_DEFAULT) {- delete nextChannel[args.channelId]- } else {- nextChannel[args.channelId] = args.level- }- return { ...prev, channel: nextChannel }+ let next: NotificationSettings | undefined+ if (snapshot) {+ const nextChannel = { ...snapshot.channel }+ if (args.level === USE_SERVER_DEFAULT) delete nextChannel[args.channelId]+ else nextChannel[args.channelId] = args.level+ next = { ...snapshot, channel: nextChannel }+ }+ queryClient.setQueryData<NotificationSettings | undefined>(key, next)+ const token = projection.beginNotificationPolicyOverlay({+ kind: "channel",+ id: args.channelId,+ level: args.level === USE_SERVER_DEFAULT ? null : args.level,})- return { snapshot }+ return {+ previousLevel: snapshot?.channel[args.channelId],+ optimisticLevel: args.level === USE_SERVER_DEFAULT ? undefined : args.level,+ token,+ }},- onError: (_err, _args, ctx) => {- if (ctx?.snapshot) queryClient.setQueryData(communityKeys.notificationSettings(), ctx.snapshot)+ onError: (_err, args, ctx) => {+ if (ctx) projection.rollbackNotificationPolicyOverlay(ctx.token)+ queryClient.setQueryData<NotificationSettings | undefined>(+ communityKeys.notificationSettings(),+ (current) => {+ if (!current || !ctx || current.channel[args.channelId] !== ctx.optimisticLevel) {+ return current+ }+ const channel = { ...current.channel }+ if (ctx.previousLevel === undefined) delete channel[args.channelId]+ else channel[args.channelId] = ctx.previousLevel+ return { ...current, channel }+ },+ )},- onSuccess: () => {+ onSuccess: (_data, _args, ctx) => {+ if (ctx) projection.commitNotificationPolicyOverlay(ctx.token)queryClient.invalidateQueries({ queryKey: communityKeys.notificationSettings() })queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })queryClient.invalidateQueries({ queryKey: communityKeys.servers() })diff --git a/src/web/src/hooks/community/mutations/servers.test.ts b/src/web/src/hooks/community/mutations/servers.test.tsindex 7cea40971..dc0491ddc 100644--- a/src/web/src/hooks/community/mutations/servers.test.ts+++ b/src/web/src/hooks/community/mutations/servers.test.ts@@ -65,7 +65,27 @@ beforeEach(() => {})describe("useLeaveServer — optimistic + rollback", () => {- it("removes the server row and restores on failure", async () => {+ it("fences every unread source in the departing scope and rolls back atomically", async () => {+ const mod = await load()+ const { getActiveAccountUnreadProjection } = await import(+ "@/hooks/community/account-unread-projection"+ )+ const projection = getActiveAccountUnreadProjection(capturedQc)+ projection.recordArrival({ channelId: "c1", serverId: "srv_1", seq: 1 })+ projection.recordArrival({ channelId: "c2", serverId: "srv_2", seq: 1 })+ mod.useLeaveServer()+ const cfg = capturedConfig as MutConfig<+ { serverId: string },+ { token: unknown; snapshot: unknown }+ >+ const context = await cfg.onMutate?.({ serverId: "srv_1" })+ expect(projection.projectUnread("servers", "c1", false)).toBe(false)+ expect(projection.projectUnread("servers", "c2", false)).toBe(true)+ cfg.onError?.(new Error("failed"), { serverId: "srv_1" }, context)+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)+ })++ it.each(["leave", "delete"] as const)("%s removes the server row and restores on failure", async (operation) => {capturedQc.setQueryData(communityKeys.servers(), {servers: [{ id: "srv_1", name: "n", initial: "N", active: false, unread: false, mentions: 0 },@@ -73,7 +93,8 @@ describe("useLeaveServer — optimistic + rollback", () => {})apiFetchMock.mockRejectedValueOnce(new Error("boom"))const mod = await load()- mod.useLeaveServer()+ if (operation === "leave") mod.useLeaveServer()+ else mod.useDeleteServer()await runMutation({ serverId: "srv_1" }).catch(() => {})const cache = capturedQc.getQueryData<{ servers: { id: string }[] }>(communityKeys.servers())expect(cache?.servers).toHaveLength(1)diff --git a/src/web/src/hooks/community/mutations/servers.ts b/src/web/src/hooks/community/mutations/servers.tsindex b1c733687..423211801 100644--- a/src/web/src/hooks/community/mutations/servers.ts+++ b/src/web/src/hooks/community/mutations/servers.ts@@ -7,6 +7,10 @@ import { avatarInitial } from "@/lib/community/avatar"import type { ServersResponse, ServerDetail } from "@/hooks/community/use-servers"import { useCommunityStore } from "@/stores/community"import { useMessageStreamStore } from "@/stores/community/message-stream"+import {+ getActiveAccountUnreadProjection,+ type AccountUnreadScopeToken,+} from "@/hooks/community/account-unread-projection"/*** Server-scoped mutations. `create`/`join` invalidate the rail; `leave`/`delete`@@ -82,7 +86,11 @@ function clearDepartedServer(serverId: string) {export function useLeaveServer() {const queryClient = useQueryClient()- return useMutation<void, Error, LeaveServerArgs, { snapshot: ServersResponse | undefined }>({+ const unreadProjection = getActiveAccountUnreadProjection(queryClient)+ return useMutation<void, Error, LeaveServerArgs, {+ snapshot: ServersResponse | undefined+ token: AccountUnreadScopeToken+ }>({mutationFn: async ({ serverId }) => {await apiFetch(`/api/community/servers/${serverId}/leave`, { method: "POST" })},@@ -93,12 +101,17 @@ export function useLeaveServer() {queryClient.setQueryData<ServersResponse | undefined>(key, (prev) =>prev ? { ...prev, servers: prev.servers.filter((s) => s.id !== args.serverId) } : prev,)- return { snapshot }+ return {+ snapshot,+ token: unreadProjection.beginScopeRetirement({ kind: "server", serverId: args.serverId }),+ }},onError: (_err, _args, ctx) => {+ if (ctx) unreadProjection.rollbackScopeRetirement(ctx.token)if (ctx?.snapshot) queryClient.setQueryData(communityKeys.servers(), ctx.snapshot)},- onSuccess: (_data, args) => {+ onSuccess: (_data, args, context) => {+ unreadProjection.commitScopeRetirement(context.token)queryClient.removeQueries({ queryKey: communityKeys.server(args.serverId) })void queryClient.invalidateQueries({queryKey: communityKeys.channelRefDirectory(),@@ -111,7 +124,11 @@ export function useLeaveServer() {export function useDeleteServer() {const queryClient = useQueryClient()- return useMutation<void, Error, LeaveServerArgs, { snapshot: ServersResponse | undefined }>({+ const unreadProjection = getActiveAccountUnreadProjection(queryClient)+ return useMutation<void, Error, LeaveServerArgs, {+ snapshot: ServersResponse | undefined+ token: AccountUnreadScopeToken+ }>({mutationFn: async ({ serverId }) => {await apiFetch(`/api/community/servers/${serverId}`, { method: "DELETE" })},@@ -122,12 +139,17 @@ export function useDeleteServer() {queryClient.setQueryData<ServersResponse | undefined>(key, (prev) =>prev ? { ...prev, servers: prev.servers.filter((s) => s.id !== args.serverId) } : prev,)- return { snapshot }+ return {+ snapshot,+ token: unreadProjection.beginScopeRetirement({ kind: "server", serverId: args.serverId }),+ }},onError: (_err, _args, ctx) => {+ if (ctx) unreadProjection.rollbackScopeRetirement(ctx.token)if (ctx?.snapshot) queryClient.setQueryData(communityKeys.servers(), ctx.snapshot)},- onSuccess: (_data, args) => {+ onSuccess: (_data, args, context) => {+ unreadProjection.commitScopeRetirement(context.token)queryClient.removeQueries({ queryKey: communityKeys.server(args.serverId) })void queryClient.invalidateQueries({queryKey: communityKeys.channelRefDirectory(),diff --git a/src/web/src/hooks/community/use-dms.test.ts b/src/web/src/hooks/community/use-dms.test.tsindex 86b475861..4bcc16f80 100644--- a/src/web/src/hooks/community/use-dms.test.ts+++ b/src/web/src/hooks/community/use-dms.test.ts@@ -39,6 +39,30 @@ describe("useDms / dmsQueryFn", () => {expect(qc.getQueryData(key)).toEqual({ conversations: [] })})+ it("uses a complete DM list as authoritative negative evidence", async () => {+ apiFetchMock.mockResolvedValueOnce({ conversations: [] })+ const { dmsProjectedQueryFn } = await import("./use-dms")+ const { AccountUnreadProjection } = await import("./account-unread-projection")+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})+ projection.recordArrival({ channelId: "dm_1", seq: 3 })++ await dmsProjectedQueryFn(projection)()++ expect(projection.projectUnread("dms", "dm_1", false)).toBe(false)+ })++ it("cancels DM snapshot coverage when the transport fails", async () => {+ apiFetchMock.mockRejectedValueOnce(new Error("offline"))+ const { dmsProjectedQueryFn } = await import("./use-dms")+ const { AccountUnreadProjection } = await import("./account-unread-projection")+ const projection = new AccountUnreadProjection("u1")++ await expect(dmsProjectedQueryFn(projection)()).rejects.toThrow("offline")++ expect(projection.inspectForTests().pendingSnapshots).toBe(0)+ })+it("reuses a projected DM across layout mounts without refetching the canonical list", async () => {const conversations = [{id: "dm_projected",diff --git a/src/web/src/hooks/community/use-dms.ts b/src/web/src/hooks/community/use-dms.tsindex 2fba38556..3e43ef8f1 100644--- a/src/web/src/hooks/community/use-dms.ts+++ b/src/web/src/hooks/community/use-dms.ts@@ -10,7 +10,11 @@ import type { DM } from "@/lib/community/models/people"import { useEffect, useMemo, useSyncExternalStore } from "react"import { useProfilesByUserId } from "@/stores/community/ws"import { readCommunityProfile } from "@/lib/community/profile-read"-import { getActiveAccountUnreadProjection } from "./account-unread-projection"+import {+ getActiveAccountUnreadProjection,+ type AccountUnreadProjection,+ type AccountUnreadSource,+} from "./account-unread-projection"import { useInboxProjectionTarget } from "./use-inbox-auto-collapse"import {reservedUnreadExclusion,@@ -36,6 +40,25 @@ export const dmsQueryFn = () =>(data) => data.conversations.map((dm) => communityUserProfilePatch(dm.userId, dm)),)+function dmUnreadSources(data: DmsResponse): AccountUnreadSource[] {+ return data.conversations.flatMap((dm) => dm.lastUnreadSeq === undefined ? [] : [{+ channelId: dm.id,+ lastUnreadSeq: dm.lastUnreadSeq,+ }])+}++export const dmsProjectedQueryFn = (projection: AccountUnreadProjection) => async () => {+ const token = projection.beginSnapshot("dms", "dms")+ try {+ const data = await dmsQueryFn()+ projection.absorbSnapshot(token, dmUnreadSources(data))+ return data+ } catch (error) {+ projection.cancelSnapshot(token)+ throw error+ }+}+export function useDms(): UseQueryResult<DmsResponse> & { dms: DM[] } {const queryClient = useQueryClient()const unreadProjection = useMemo(@@ -52,9 +75,10 @@ export function useDms(): UseQueryResult<DmsResponse> & { dms: DM[] } {() => reservedUnreadExclusion(reservationTarget, "dms"),[reservationTarget],)+ const queryFn = useMemo(() => dmsProjectedQueryFn(unreadProjection), [unreadProjection])const query = useQuery({queryKey: communityKeys.dms(),- queryFn: dmsQueryFn,+ queryFn,// Inbox navigation projects the destination into this canonical cache// before routing. Reusing that projection across /c/me layout mounts keeps// the transition request-neutral; WS and reconnect invalidations still@@ -64,12 +88,10 @@ export function useDms(): UseQueryResult<DmsResponse> & { dms: DM[] } {const profilesByUserId = useProfilesByUserId()useEffect(() => {if (!query.data) return- unreadProjection.absorbFamily(+ unreadProjection.mergeSources(+ "dms",+ dmUnreadSources(query.data),"dms",- query.data.conversations.flatMap((dm) => dm.lastUnreadSeq === undefined ? [] : [{- channelId: dm.id,- lastUnreadSeq: dm.lastUnreadSeq,- }]),)unreadProjection.recordLegacySnapshot(query.data,diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.test.tsindex 7ca55da83..12877457e 100644--- a/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts@@ -158,6 +158,51 @@ describe("useForumSidebarThreads", () => {await act(async () => renderer.unmount())})+ it("confirms a freshly retained child as authoritative access", async () => {+ const base = envelope([])+ const retained = envelope(["post-1"])+ apiFetchMock+ .mockResolvedValueOnce(base)+ .mockResolvedValueOnce({+ ...base,+ canonicalChannels: [],+ retainedChannel: retained.channels[0],+ retainedDisposition: "eligible",+ included: retained.included,+ })+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ const projection = getActiveAccountUnreadProjection(queryClient)+ projection.retireAccessScope({ kind: "channel", channelId: "post-1" })+ projection.grantAccessScope({ kind: "channel", channelId: "post-1" })+ projection.recordArrival({ channelId: "post-1", serverId: "server-1", seq: 2 })+ expect(projection.projectUnread("inbox-unreads", "post-1", false, 2)).toBe(false)++ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(+ QueryClientProvider,+ { client: queryClient },+ React.createElement(Capture, { retainId: null, onRender: () => undefined }),+ ))+ })+ await waitFor(() => queryClient.getQueryState(+ communityKeys.forumSidebarThreads("server-1"),+ )?.status === "success")+ await act(async () => {+ renderer.update(React.createElement(+ QueryClientProvider,+ { client: queryClient },+ React.createElement(Capture, { retainId: "post-1", onRender: () => undefined }),+ ))+ })+ await waitFor(() => queryClient.getQueryState(+ communityKeys.forumSidebarRetained("server-1", "post-1"),+ )?.status === "success")++ expect(projection.projectUnread("inbox-unreads", "post-1", false, 2)).toBe(true)+ await act(async () => renderer.unmount())+ })+it("preserves a genuine parent unread when a child fallback becomes locatable", () => {const queryClient = new QueryClient()queryClient.setQueryData(communityKeys.server("server-1"), serverDetail(true))@@ -1169,6 +1214,13 @@ describe("forum sidebar Stage B resources", () => {it("clears an exact negative retained result on a grant without touching siblings", async () => {const queryClient = new QueryClient()+ const negative = envelope([])+ apiFetchMock.mockResolvedValueOnce({+ ...negative,+ canonicalChannels: [],+ retainedChannel: null,+ retainedDisposition: "genuine-negative",+ })queryClient.setQueryData(communityKeys.forumSidebarRetained("server-1", "post-1"), null)queryClient.setQueryData(communityKeys.forumSidebarRetained("server-1", "post-2"),@@ -1177,9 +1229,9 @@ describe("forum sidebar Stage B resources", () => {await grantForumSidebarChild(queryClient, "server-1", "post-1")- expect(queryClient.getQueryState(+ expect(queryClient.getQueryData(communityKeys.forumSidebarRetained("server-1", "post-1"),- )).toBeUndefined()+ )).toBeNull()expect(queryClient.getQueryData(communityKeys.forumSidebarRetained("server-1", "post-2"),)).toEqual({ id: "post-2" })diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.tsindex 54c1fcfdb..a114112e2 100644--- a/src/web/src/hooks/community/use-forum-sidebar-threads.ts+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.ts@@ -723,11 +723,13 @@ export async function invalidateForumSidebarBaseExact(queryClient: QueryClient,})}-export function grantForumSidebarChild(+export async function grantForumSidebarChild(queryClient: QueryClient,serverId: string,childId: string,) {+ const unreadProjection = getActiveAccountUnreadProjection(queryClient)+ const accessConfirmation = unreadProjection.beginAccessConfirmation()recordInflightDelta(serverId, (delta) => {delta.removed.delete(childId)})@@ -743,7 +745,38 @@ export function grantForumSidebarChild(queryKey: communityKeys.channelMeta(serverId, childId),exact: true,})- return invalidateForumSidebarBaseExact(queryClient, serverId)+ await invalidateForumSidebarBaseExact(queryClient, serverId)+ if (hasForumSidebarThread(getForumSidebarBase(queryClient, serverId), childId)) {+ unreadProjection.confirmAccessScopes(+ [{ kind: "channel", channelId: childId }],+ accessConfirmation,+ )+ return+ }++ // The base query may be inactive, and its activity window may omit the+ // newly re-granted child. A retained fetch is the authoritative access+ // check for that exact child; only a positive result releases its fence.+ const requestEpoch = useCommunityWsStore.getState().accessEpoch+ const normalized = await fetchForumSidebar(serverId, childId)+ seedForumSidebarResources(queryClient, serverId, normalized, requestEpoch, childId)+ queryClient.setQueryData(+ communityKeys.forumSidebarThreads(serverId),+ { ...normalized.base, verifiedEpoch: requestEpoch },+ )+ queryClient.setQueryData(+ communityKeys.forumSidebarRetained(serverId, childId),+ normalized.retained,+ )+ if (+ hasForumSidebarThread(normalized.base, childId)+ || normalized.retainedDisposition === "eligible" && normalized.retained?.id === childId+ ) {+ unreadProjection.confirmAccessScopes(+ [{ kind: "channel", channelId: childId }],+ accessConfirmation,+ )+ }}export function reconcileForumSidebarArchiveTag(@@ -1006,10 +1039,24 @@ export function useForumSidebarThreads(enabled: !!serverId && enabled,staleTime: Infinity,queryFn: async ({ signal }) => {+ const unreadProjection = getActiveAccountUnreadProjection(queryClient)+ const accessConfirmation = unreadProjection.beginAccessConfirmation()const requestEpoch = useCommunityWsStore.getState().accessEpochconst normalized = await fetchForumSidebar(serverId, retainId, signal)throwIfConsumerAborted(signal)seedForumSidebarResources(queryClient, serverId, normalized, requestEpoch, retainId)+ unreadProjection.confirmAccessScopes(+ [+ ...normalized.base.threads,+ ...(normalized.retainedDisposition === "eligible" && normalized.retained+ ? [normalized.retained]+ : []),+ ].map((thread) => ({+ kind: "channel" as const,+ channelId: thread.id,+ })),+ accessConfirmation,+ )if (retainId) {queryClient.setQueryData(communityKeys.forumSidebarRetained(serverId, retainId),@@ -1047,10 +1094,18 @@ export function useForumSidebarThreads(staleTime: Infinity,gcTime: 5 * 60 * 1000,queryFn: async ({ signal }) => {+ const unreadProjection = getActiveAccountUnreadProjection(queryClient)+ const accessConfirmation = unreadProjection.beginAccessConfirmation()const requestEpoch = useCommunityWsStore.getState().accessEpochconst normalized = await fetchForumSidebar(serverId, retainId, signal)throwIfConsumerAborted(signal)seedForumSidebarResources(queryClient, serverId, normalized, requestEpoch, retainId)+ if (normalized.retainedDisposition === "eligible" && normalized.retained) {+ unreadProjection.confirmAccessScopes(+ [{ kind: "channel", channelId: normalized.retained.id }],+ accessConfirmation,+ )+ }queryClient.setQueryData(communityKeys.forumSidebarThreads(serverId),{ ...normalized.base, verifiedEpoch: requestEpoch },diff --git a/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts b/src/web/src/hooks/community/use-inbox-auto-collapse.test.tsindex 0bf6a8a59..0f9fd441e 100644--- a/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts+++ b/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts@@ -206,6 +206,21 @@ describe("useInboxAutoCollapse", () => {expect(mocks.activate).toHaveBeenCalledTimes(1)})+ it("keeps the projection through the submitted-to-pending router gap", async () => {+ const href = "/c/channels/s1/c1"+ const hook = await renderHook()+ let epoch = 0+ await hook.call(() => { epoch = hook.current.beginProjection(target(), href) })+ await hook.call(() => hook.current.markProjectionSubmitted(epoch))++ expect(hook.current.isProjected(target())).toBe(true)+ expect(mocks.cancel).not.toHaveBeenCalled()++ await hook.rerender({ navigationPending: true, pendingHref: href })+ await hook.rerender({ publishedHref: href, navigationPending: false, pendingHref: null })+ expect(mocks.activate).toHaveBeenCalledTimes(1)+ })+it("rolls back a canceled pre-commit intent without reopening", async () => {const href = "/c/channels/s1/c1"const hook = await renderHook({ navigationPending: true, pendingHref: href })diff --git a/src/web/src/hooks/community/use-inbox-auto-collapse.ts b/src/web/src/hooks/community/use-inbox-auto-collapse.tsindex 79942d143..e125ff87d 100644--- a/src/web/src/hooks/community/use-inbox-auto-collapse.ts+++ b/src/web/src/hooks/community/use-inbox-auto-collapse.ts@@ -14,9 +14,11 @@ type ProjectionLease = {epoch: numbertarget: InboxRowTargetdestinationHref: string+ originHref: stringpreviousOpen: booleanphase: "submitting" | "committed"submitted: boolean+ navigationObserved: booleanticket: InboxProjectionTicket}@@ -140,16 +142,18 @@ export function useInboxAutoCollapse({epoch,target,destinationHref,+ originHref: publishedHref,previousOpen,phase: "submitting",submitted: false,+ navigationObserved: false,ticket,}publishProjection(store, lease)openRef.current = falsesetOpen(false)return epoch- }, [queryClient, store])+ }, [publishedHref, queryClient, store])const markProjectionSubmitted = useCallback((epoch: number) => {const lease = store.current@@ -194,8 +198,21 @@ export function useInboxAutoCollapse({commitLease(lease)return}- if (navigationPending && destinationMatches(pendingHref, lease.destinationHref)) return- rollbackProjection(lease.epoch)+ if (navigationPending && destinationMatches(pendingHref, lease.destinationHref)) {+ if (!lease.navigationObserved) {+ publishProjection(store, { ...lease, navigationObserved: true })+ }+ return+ }+ // router.pushImmediate() can publish the intent one render before the+ // navigation store exposes pendingHref. Keep the exact tombstone through+ // that gap; a synchronous throw is handled by the caller. Once this lease+ // has observed its pending destination, an idle mismatch is a real cancel.+ if (+ lease.navigationObserved+ || publishedHref !== lease.originHref+ || (navigationPending && pendingHref !== null)+ ) rollbackProjection(lease.epoch)}, [commitLease, navigationPending, pendingHref, projection, publishedHref, rollbackProjection, store])useEffect(() => {diff --git a/src/web/src/hooks/community/use-inbox.test.ts b/src/web/src/hooks/community/use-inbox.test.tsindex 0217daf32..24b13d5b5 100644--- a/src/web/src/hooks/community/use-inbox.test.ts+++ b/src/web/src/hooks/community/use-inbox.test.ts@@ -20,6 +20,17 @@ beforeEach(() => {})describe("useInboxUnreads / inboxUnreadsQueryFn", () => {+ it("supports direct reads without a query context", async () => {+ apiFetchMock.mockResolvedValueOnce({ servers: [], dms: [] })+ const { inboxUnreadsQueryFn } = await import("./use-inbox")++ await expect(inboxUnreadsQueryFn()).resolves.toEqual({ servers: [], dms: [] })+ expect(apiFetchMock).toHaveBeenCalledWith(+ "/api/community/users/me/inbox/unreads",+ { signal: undefined },+ )+ })+it("fetches /inbox/unreads and populates queryClient at communityKeys.inboxUnreads()", async () => {apiFetchMock.mockResolvedValueOnce({ servers: [], dms: [] })const { inboxUnreadsQueryFn } = await import("./use-inbox")@@ -49,6 +60,210 @@ describe("useInboxUnreads / inboxUnreadsQueryFn", () => {await pending})+ it("starts canonical Inbox snapshot fences before transport", async () => {+ let resolve!: (value: { servers: []; dms: []; truncated: false }) => void+ apiFetchMock.mockReturnValueOnce(new Promise((next) => { resolve = next }))+ const {+ inboxUnreadsProjectedQueryFn,+ } = await import("./use-inbox")+ const { AccountUnreadProjection } = await import("./account-unread-projection")+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})+ const qc = new QueryClient()++ const pending = inboxUnreadsProjectedQueryFn(qc, projection)()+ projection.recordArrival({ channelId: "later", serverId: "s1", seq: 2 })+ resolve({ servers: [], dms: [], truncated: false })+ await pending++ expect(projection.projectUnread("inbox-unreads", "later", false)).toBe(true)+ })++ it("releases both canonical snapshot fences when transport fails", async () => {+ apiFetchMock.mockRejectedValueOnce(new Error("offline"))+ const { inboxUnreadsProjectedQueryFn } = await import("./use-inbox")+ const { AccountUnreadProjection } = await import("./account-unread-projection")+ const projection = new AccountUnreadProjection("u1")++ await expect(inboxUnreadsProjectedQueryFn(new QueryClient(), projection)())+ .rejects.toThrow("offline")+ expect(projection.inspectForTests().pendingSnapshots).toBe(0)+ })++ it("lets a complete empty Inbox response retire pre-request channel and DM sources", async () => {+ apiFetchMock.mockResolvedValueOnce({ servers: [], dms: [], truncated: false })+ const { inboxUnreadsProjectedQueryFn } = await import("./use-inbox")+ const { AccountUnreadProjection } = await import("./account-unread-projection")+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})+ projection.recordArrival({ channelId: "channel", serverId: "s1", seq: 1 })+ projection.recordArrival({ channelId: "dm", seq: 1 })++ await inboxUnreadsProjectedQueryFn(new QueryClient(), projection)()++ expect(projection.projectUnread("inbox-unreads", "channel", false, 1, "channels")).toBe(false)+ expect(projection.projectUnread("inbox-unreads", "dm", false, 1, "dms")).toBe(false)+ })++ it("retires a complete empty DM domain when the server domain is truncated", async () => {+ apiFetchMock.mockResolvedValueOnce({ servers: [], dms: [], truncated: true })+ const { inboxUnreadsProjectedQueryFn } = await import("./use-inbox")+ const { AccountUnreadProjection } = await import("./account-unread-projection")+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})+ projection.recordArrival({ channelId: "channel", serverId: "s1" })+ projection.recordArrival({ channelId: "dm" })++ await inboxUnreadsProjectedQueryFn(new QueryClient(), projection)()++ expect(projection.projectUnread("inbox-unreads", "channel", false, null, "channels"))+ .toBe(true)+ expect(projection.projectUnread("inbox-unreads", "dm", false, null, "dms"))+ .toBe(false)+ })++ it("preserves cold attention facets under mentions-only policy", async () => {+ apiFetchMock.mockResolvedValueOnce({+ servers: [{+ serverId: "s1",+ serverName: "One",+ channels: [+ {+ channelId: "attention",+ channelName: "Attention",+ lastMessageAt: "2026-09-04T00:00:00.000Z",+ lastUnreadSeq: 2,+ lastAttentionSeq: 2,+ mentionCount: 1,+ children: [],+ },+ {+ channelId: "ordinary",+ channelName: "Ordinary",+ lastMessageAt: "2026-09-04T00:00:00.000Z",+ lastUnreadSeq: 3,+ mentionCount: 0,+ children: [],+ },+ ],+ }],+ dms: [],+ truncated: false,+ })+ const { inboxUnreadsProjectedQueryFn } = await import("./use-inbox")+ const { AccountUnreadProjection } = await import("./account-unread-projection")+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({ server: { s1: "mentions" } })++ await inboxUnreadsProjectedQueryFn(new QueryClient(), projection)()++ expect(projection.projectUnread("inbox-unreads", "attention", false)).toBe(true)+ expect(projection.projectUnread("inbox-unreads", "ordinary", false)).toBe(false)+ })++ it("does not treat a later ordinary unread as the older mention facet", async () => {+ apiFetchMock.mockResolvedValueOnce({+ servers: [{+ serverId: "s1",+ serverName: "One",+ channels: [{+ channelId: "mixed",+ channelName: "Mixed",+ lastMessageAt: "2026-09-04T00:00:00.000Z",+ lastUnreadSeq: 10,+ lastAttentionSeq: 5,+ mentionCount: 1,+ children: [],+ }],+ }],+ dms: [],+ truncated: false,+ })+ const { inboxUnreadsProjectedQueryFn } = await import("./use-inbox")+ const { AccountUnreadProjection } = await import("./account-unread-projection")+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({ server: { s1: "mentions" } })++ await inboxUnreadsProjectedQueryFn(new QueryClient(), projection)()+ expect(projection.projectUnread("inbox-unreads", "mixed", false)).toBe(true)++ projection.recordRead("mixed", 5)+ expect(projection.projectUnread("inbox-unreads", "mixed", false)).toBe(false)+ })++ it.each([+ ["nothing", false],+ ["mentions", true],+ ["all", true],+ ] as const)("applies cold parent %s policy through the Mentions adapter", async (+ parentLevel,+ expected,+ ) => {+ apiFetchMock.mockResolvedValueOnce({+ mentions: [{+ id: "attention-1",+ kind: "mention",+ server: "One",+ serverId: "s1",+ channel: "Post",+ channelId: "post-1",+ parentChannelId: "forum-1",+ m: { id: "message-1", seq: 4 },+ }],+ truncated: false,+ })+ const { inboxMentionsProjectedQueryFn } = await import("./use-inbox")+ const { AccountUnreadProjection } = await import("./account-unread-projection")+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({+ server: { s1: "all" },+ channel: { "forum-1": parentLevel },+ })++ await inboxMentionsProjectedQueryFn(projection)()++ expect(projection.projectUnread(+ "inbox-mentions",+ "post-1",+ false,+ 4,+ "mentions",+ null,+ true,+ "attention-1",+ )).toBe(expected)+ })++ it("merges positive rows from a stale response without using its absence", async () => {+ apiFetchMock.mockResolvedValueOnce({+ servers: [{+ serverId: "s1",+ serverName: "One",+ channels: [{+ channelId: "positive",+ channelName: "Positive",+ lastMessageAt: "2026-09-04T00:00:00.000Z",+ lastUnreadSeq: 2,+ hasDirectUnread: true,+ children: [],+ }],+ }],+ dms: [],+ truncated: false,+ stale: true,+ })+ const { inboxUnreadsProjectedQueryFn } = await import("./use-inbox")+ const { AccountUnreadProjection } = await import("./account-unread-projection")+ const projection = new AccountUnreadProjection("u1")+ projection.recordArrival({ channelId: "absent", serverId: "s1", seq: 1 })++ await expect(inboxUnreadsProjectedQueryFn(new QueryClient(), projection)())+ .rejects.toThrow("stale D1 read")++ expect(projection.projectUnread("inbox-unreads", "positive", false)).toBe(true)+ expect(projection.projectUnread("inbox-unreads", "absent", false)).toBe(true)+ })+it("fences the production query result until a focused candidate is classified", async () => {const data = {servers: [{ channels: [{@@ -357,6 +572,30 @@ describe("useInboxMentions / inboxMentionsQueryFn", () => {expect(qc.getQueryData(key)).toEqual({ mentions: [] })})+ it("retires an orphan attention source after a complete empty Mentions response", async () => {+ apiFetchMock.mockResolvedValueOnce({ mentions: [], truncated: false })+ const { inboxMentionsProjectedQueryFn } = await import("./use-inbox")+ const { AccountUnreadProjection } = await import("./account-unread-projection")+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})+ projection.recordMentionArrival({ channelId: "c1", seq: 4, isMention: true })++ await inboxMentionsProjectedQueryFn(projection)()++ expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(false)+ })++ it("cancels Mentions snapshot coverage when the transport fails", async () => {+ apiFetchMock.mockRejectedValueOnce(new Error("offline"))+ const { inboxMentionsProjectedQueryFn } = await import("./use-inbox")+ const { AccountUnreadProjection } = await import("./account-unread-projection")+ const projection = new AccountUnreadProjection("u1")++ await expect(inboxMentionsProjectedQueryFn(projection)()).rejects.toThrow("offline")++ expect(projection.inspectForTests().pendingSnapshots).toBe(0)+ })+it("filters read mentions, preserves unscoped rows, and reports pending arrivals", async () => {const scoped = { id: "m1", channelId: "c1", m: { seq: 2 } }const unscoped = { id: "m2", m: { seq: 1 } }@@ -388,6 +627,91 @@ describe("useInboxMentions / inboxMentionsQueryFn", () => {await act(async () => renderer.unmount())})+ it("suppresses same-sequence attention with an Unread reservation and keeps newer attention", async () => {+ const channel = {+ channelId: "shared",+ channelName: "Shared",+ lastMessageAt: "2026-09-04T02:00:00.000Z",+ lastUnreadSeq: 4,+ mentionCount: 1,+ hasDirectUnread: true,+ children: [],+ }+ const server = { serverId: "s1", serverName: "One", channels: [channel] }+ const same = {+ id: "mention-same",+ serverId: "s1",+ channelId: "shared",+ m: { id: "message-same", seq: 4 },+ }+ const newer = {+ id: "mention-newer",+ serverId: "s1",+ channelId: "shared",+ m: { id: "message-newer", seq: 5 },+ }+ apiFetchMock.mockImplementation((url: string) => Promise.resolve(+ url.endsWith("/unreads")+ ? { servers: [server], dms: [], truncated: false }+ : { mentions: [same, newer], truncated: false },+ ))+ const { useInboxMentions, useInboxUnreads } = await import("./use-inbox")+ const { useInboxAutoCollapse } = await import("./use-inbox-auto-collapse")+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ qc.setQueryData(communityKeys.inboxUnreads(), {+ servers: [server],+ dms: [],+ truncated: false,+ })+ qc.setQueryData(communityKeys.inboxMentions(), {+ mentions: [same, newer],+ truncated: false,+ })+ let unreads: ReturnType<typeof useInboxUnreads> | undefined+ let mentions: ReturnType<typeof useInboxMentions> | undefined+ let collapse: ReturnType<typeof useInboxAutoCollapse> | undefined+ function Harness() {+ unreads = useInboxUnreads()+ mentions = useInboxMentions()+ collapse = useInboxAutoCollapse({+ queryClient: qc,+ publishedHref: "/c/channels/s0",+ navigationPending: false,+ pendingHref: null,+ })+ return null+ }+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(+ QueryClientProvider,+ { client: qc },+ React.createElement(Harness),+ ))+ })+ expect(mentions?.mentions).toEqual([same, newer])++ let epoch = 0+ await act(async () => {+ epoch = collapse!.beginProjection(+ inboxChannelRowTarget(server, channel)!,+ "/c/channels/s1/shared",+ )+ })++ expect(unreads?.servers).toEqual([server])+ expect(unreads?.hasProjectedUnread).toBe(true)+ expect(mentions?.mentions).toEqual([newer])+ expect(mentions?.hasProjectedMention).toBe(true)++ await act(async () => {+ collapse!.rollbackProjection(epoch)+ })+ expect(unreads?.servers).toEqual([server])+ expect(mentions?.mentions).toEqual([same, newer])+ await act(async () => renderer.unmount())+ })+it("returns an empty mention projection before query data arrives", async () => {apiFetchMock.mockReturnValue(new Promise(() => undefined))const { useInboxMentions } = await import("./use-inbox")diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.tsindex 8c49ced9d..92633b09e 100644--- a/src/web/src/hooks/community/use-inbox.ts+++ b/src/web/src/hooks/community/use-inbox.ts@@ -10,7 +10,11 @@ import {inboxMentionRowTarget,reserveInboxUnreadsResponse,} from "./inbox-read-reservation"-import { getActiveAccountUnreadProjection } from "./account-unread-projection"+import {+ getActiveAccountUnreadProjection,+ type AccountUnreadProjection,+ type AccountUnreadSource,+} from "./account-unread-projection"import { useInboxProjectionTarget } from "./use-inbox-auto-collapse"import {isInboxTargetReserved,@@ -32,6 +36,23 @@ const EMPTY_DMS: readonly UnreadDm[] = Object.freeze([])const EMPTY_MENTIONS: readonly Mention[] = Object.freeze([])const EMPTY_MARKED: readonly Marked[] = Object.freeze([])+type ProjectedUnreadChild = UnreadServer["channels"][number]["children"][number] & {+ lastAttentionSeq?: number | null+}++type ProjectedUnreadChannel = Omit<UnreadServer["channels"][number], "children"> & {+ lastAttentionSeq?: number | null+ children: ProjectedUnreadChild[]+}++type ProjectedUnreadServer = Omit<UnreadServer, "channels"> & {+ channels: ProjectedUnreadChannel[]+}++type ProjectedMention = Mention & {+ parentChannelId?: string | null+}+/*** The inbox popover shows two sibling feeds. Each has its own endpoint and* its own query key nested under `communityKeys.inbox()` so a single@@ -46,17 +67,16 @@ const EMPTY_MARKED: readonly Marked[] = Object.freeze([])*/export type UnreadsResponse = {- servers: UnreadServer[]+ servers: ProjectedUnreadServer[]dms: UnreadDm[]limit?: numbertruncated?: boolean}-export const inboxUnreadsQueryFn = ({ signal }: { signal?: AbortSignal } = {}) =>+const inboxUnreadsTransportFn = ({ signal }: { signal?: AbortSignal } = {}) =>apiFetchProfiles<UnreadsResponse & { stale?: boolean }>("/api/community/users/me/inbox/unreads",(data) => {- throwIfStale(data)return data.dms.map((dm) => ({id: dm.otherUserId,identityAbout: {@@ -72,12 +92,86 @@ export const inboxUnreadsQueryFn = ({ signal }: { signal?: AbortSignal } = {}) ={ signal },)+export const inboxUnreadsQueryFn = async (+ context: { signal?: AbortSignal } = {},+) => throwIfStale(await inboxUnreadsTransportFn(context))+export const inboxUnreadsReservedQueryFn = (queryClient: ReturnType<typeof useQueryClient>) => ({ signal }: { signal?: AbortSignal } = {},) => inboxUnreadsQueryFn({ signal }).then((data) => reserveInboxUnreadsResponse(queryClient, data, signal),)+function inboxUnreadSources(data: UnreadsResponse) {+ const channels: AccountUnreadSource[] = data.servers.flatMap((server) => (+ server.channels.flatMap((channel) => [+ ...(channel.lastUnreadSeq === undefined ? [] : [{+ channelId: channel.channelId,+ serverId: server.serverId,+ lastUnreadSeq: channel.lastUnreadSeq,+ }]),+ ...(channel.lastAttentionSeq === undefined || channel.lastAttentionSeq === null ? [] : [{+ channelId: channel.channelId,+ serverId: server.serverId,+ lastUnreadSeq: channel.lastAttentionSeq,+ lastMentionSeq: channel.lastAttentionSeq,+ isMention: true,+ }]),+ ...channel.children.flatMap((child) => [+ ...(child.lastUnreadSeq === undefined ? [] : [{+ channelId: child.channelId,+ serverId: server.serverId,+ railChannelId: channel.channelId,+ lastUnreadSeq: child.lastUnreadSeq,+ }]),+ ...(child.lastAttentionSeq === undefined || child.lastAttentionSeq === null ? [] : [{+ channelId: child.channelId,+ serverId: server.serverId,+ railChannelId: channel.channelId,+ lastUnreadSeq: child.lastAttentionSeq,+ lastMentionSeq: child.lastAttentionSeq,+ isMention: true,+ }]),+ ]),+ ])+ ))+ const dms: AccountUnreadSource[] = data.dms.flatMap((dm) => (+ dm.lastUnreadSeq === undefined ? [] : [{+ channelId: dm.channelId,+ lastUnreadSeq: dm.lastUnreadSeq,+ }]+ ))+ return { channels, dms }+}++export const inboxUnreadsProjectedQueryFn = (+ queryClient: ReturnType<typeof useQueryClient>,+ projection: AccountUnreadProjection,+) => async ({ signal }: { signal?: AbortSignal } = {}) => {+ const channelsToken = projection.beginSnapshot("inbox-unreads", "channels")+ const dmsToken = projection.beginSnapshot("inbox-unreads", "dms")+ try {+ const data = await inboxUnreadsTransportFn({ signal })+ const sources = inboxUnreadSources(data)+ projection.absorbSnapshot(channelsToken, sources.channels, {+ truncated: data.truncated ?? true,+ stale: data.stale,+ })+ // The route's cap and `truncated` bit cover server nodes only. DMs are+ // always returned as a complete, independently authoritative domain.+ projection.absorbSnapshot(dmsToken, sources.dms, {+ truncated: false,+ stale: data.stale,+ })+ throwIfStale(data)+ return reserveInboxUnreadsResponse(queryClient, data, signal)+ } catch (error) {+ projection.cancelSnapshot(channelsToken)+ projection.cancelSnapshot(dmsToken)+ throw error+ }+}+export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {servers: UnreadServer[]dms: UnreadDm[]@@ -102,7 +196,10 @@ export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {() => reservedUnreadExclusion(reservationTarget, "dms"),[reservationTarget],)- const queryFn = useMemo(() => inboxUnreadsReservedQueryFn(queryClient), [queryClient])+ const queryFn = useMemo(+ () => inboxUnreadsProjectedQueryFn(queryClient, unreadProjection),+ [queryClient, unreadProjection],+ )const query = useQuery({queryKey: communityKeys.inboxUnreads(),queryFn,@@ -112,28 +209,9 @@ export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {})useEffect(() => {if (!query.data) return- const channelSources = query.data.servers.flatMap((server) => server.channels.flatMap((channel) => [- ...(channel.lastUnreadSeq === undefined ? [] : [{- channelId: channel.channelId,- lastUnreadSeq: channel.lastUnreadSeq,- }]),- ...channel.children.flatMap((child) => child.lastUnreadSeq === undefined ? [] : [{- channelId: child.channelId,- lastUnreadSeq: child.lastUnreadSeq,- }]),- ]))- const dmSources = query.data.dms.flatMap((dm) => dm.lastUnreadSeq === undefined ? [] : [{- channelId: dm.channelId,- lastUnreadSeq: dm.lastUnreadSeq,- }])- unreadProjection.absorbFamily("inbox-unreads", channelSources, {- truncated: query.data.truncated ?? true,- domain: "channels",- })- unreadProjection.absorbFamily("inbox-unreads", dmSources, {- truncated: false,- domain: "dms",- })+ const sources = inboxUnreadSources(query.data)+ unreadProjection.mergeSources("inbox-unreads", sources.channels, "channels")+ unreadProjection.mergeSources("inbox-unreads", sources.dms, "dms")unreadProjection.recordLegacySnapshot(query.data, [...query.data.servers.flatMap((server) => server.channels.flatMap((channel) => [...(channel.lastUnreadSeq === undefined && channel.hasDirectUnread !== false@@ -231,20 +309,54 @@ export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {}export type MentionsResponse = {- mentions: Mention[]+ mentions: ProjectedMention[]limit?: numbertruncated?: boolean}-export const inboxMentionsQueryFn = () =>+const inboxMentionsTransportFn = () =>apiFetchProfiles<MentionsResponse & { stale?: boolean }>("/api/community/users/me/inbox/mentions",- (data) => {- throwIfStale(data)- return messageProfilePatches(data.mentions.map((mention) => mention.m))- },+ (data) => messageProfilePatches(data.mentions.map((mention) => mention.m)),)+export const inboxMentionsQueryFn = async () => (+ throwIfStale(await inboxMentionsTransportFn())+)++function inboxMentionSources(data: MentionsResponse): AccountUnreadSource[] {+ return data.mentions.flatMap((mention) => (+ mention.channelId && mention.m.seq+ ? [{+ channelId: mention.channelId,+ serverId: mention.serverId,+ railChannelId: mention.parentChannelId ?? undefined,+ messageId: mention.m.id,+ attentionId: mention.id,+ lastUnreadSeq: mention.m.seq,+ lastMentionSeq: mention.m.seq,+ }]+ : []+ ))+}++export const inboxMentionsProjectedQueryFn = (+ projection: AccountUnreadProjection,+) => async () => {+ const token = projection.beginSnapshot("inbox-mentions", "mentions")+ try {+ const data = await inboxMentionsTransportFn()+ projection.absorbSnapshot(token, inboxMentionSources(data), {+ truncated: data.truncated ?? true,+ stale: data.stale,+ })+ return throwIfStale(data)+ } catch (error) {+ projection.cancelSnapshot(token)+ throw error+ }+}+export function useInboxMentions(): UseQueryResult<MentionsResponse> & {mentions: Mention[]hasProjectedMention: boolean@@ -260,27 +372,27 @@ export function useInboxMentions(): UseQueryResult<MentionsResponse> & {unreadProjection.getSnapshot,)const reservationTarget = useInboxProjectionTarget(queryClient)+ const mentionExclusion = useMemo(+ () => reservedUnreadExclusion(reservationTarget, "channels"),+ [reservationTarget],+ )+ const queryFn = useMemo(+ () => inboxMentionsProjectedQueryFn(unreadProjection),+ [unreadProjection],+ )const query = useQuery({queryKey: communityKeys.inboxMentions(),- queryFn: inboxMentionsQueryFn,+ queryFn,placeholderData: keepPreviousData,staleTime: Infinity,refetchOnReconnect: true,})useEffect(() => {if (!query.data) return- unreadProjection.absorbFamily(+ unreadProjection.mergeSources("inbox-mentions",- query.data.mentions.flatMap((mention) => (- mention.channelId && mention.m.seq- ? [{- channelId: mention.channelId,- lastUnreadSeq: mention.m.seq,- lastMentionSeq: mention.m.seq,- }]- : []- )),- { truncated: query.data.truncated ?? true },+ inboxMentionSources(query.data),+ "mentions",)unreadProjection.recordLegacySnapshot(query.data,@@ -307,6 +419,10 @@ export function useInboxMentions(): UseQueryResult<MentionsResponse> & {mention.channelId,true,mention.m.seq,+ "mentions",+ mentionExclusion,+ true,+ mention.id,),reserved: isInboxTargetReserved(reservationTarget,@@ -315,12 +431,17 @@ export function useInboxMentions(): UseQueryResult<MentionsResponse> & {}).effectiveUnread))return projected.length === raw.length ? raw : projected- }, [query.data, reservationTarget, unreadProjection, unreadVersion])+ }, [mentionExclusion, query.data, reservationTarget, unreadProjection, unreadVersion])return {...query,mentions,hasProjectedMention:- mentions.length > 0 || unreadProjection.hasPending("inbox-mentions", "mentions"),+ mentions.length > 0+ || unreadProjection.hasPending(+ "inbox-mentions",+ "mentions",+ mentionExclusion,+ ),}}diff --git a/src/web/src/hooks/community/use-notification-settings.test.ts b/src/web/src/hooks/community/use-notification-settings.test.tsindex 80c4fbe8b..5d9aafca3 100644--- a/src/web/src/hooks/community/use-notification-settings.test.ts+++ b/src/web/src/hooks/community/use-notification-settings.test.ts@@ -1,5 +1,7 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"import { describe, it, expect, vi, beforeEach } from "vitest"-import { QueryClient } from "@tanstack/react-query"+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"const apiFetchMock = vi.fn()@@ -40,4 +42,39 @@ describe("useNotificationSettings / notificationSettingsQueryFn", () => {await qc.fetchQuery({ queryKey: key, queryFn: notificationSettingsQueryFn })expect(qc.getQueryData(key)).toBeDefined()})++ it("projects fetched settings into the active account unread owner", async () => {+ apiFetchMock.mockResolvedValueOnce([+ { serverId: "srv_1", channelId: null, level: "nothing" },+ ])+ const { useNotificationSettings } = await import("./use-notification-settings")+ const {+ disposeAccountUnreadProjection,+ getAccountUnreadProjection,+ } = await import("./account-unread-projection")+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ const projection = getAccountUnreadProjection(qc, "viewer_1")+ projection.recordArrival({ channelId: "channel_1", serverId: "srv_1", seq: 1 })+ let latest: ReturnType<typeof useNotificationSettings> | undefined+ function Harness() {+ latest = useNotificationSettings()+ return null+ }++ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(+ QueryClientProvider,+ { client: qc },+ React.createElement(Harness),+ ))+ })+ await vi.waitFor(() => expect(latest?.isSuccess).toBe(true))++ expect(latest?.server).toEqual({ srv_1: "Nothing" })+ expect(projection.projectUnread("servers", "channel_1", false)).toBe(false)++ await act(async () => renderer.unmount())+ disposeAccountUnreadProjection(qc)+ })})diff --git a/src/web/src/hooks/community/use-notification-settings.ts b/src/web/src/hooks/community/use-notification-settings.tsindex 72d980a1b..8e077b6ed 100644--- a/src/web/src/hooks/community/use-notification-settings.ts+++ b/src/web/src/hooks/community/use-notification-settings.ts@@ -1,9 +1,21 @@"use client"-import { useMutation, useQuery, useQueryClient, type UseQueryResult } from "@tanstack/react-query"+import {+ useMutation,+ useQuery,+ useQueryClient,+ type QueryClient,+ type QueryFunctionContext,+ type UseQueryResult,+} from "@tanstack/react-query"import { notifLevelDisplay } from "@alook/shared"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"+import { useEffect, useMemo } from "react"+import {+ getActiveAccountUnreadProjection,+ type AccountUnreadProjection,+} from "./account-unread-projection"/*** Fetches the user's notification-setting rows and materialises them into@@ -40,10 +52,17 @@ export function resolveServerNotificationDisplayLevel(level?: string): string {return level ?? DEFAULT_SERVER_NOTIFICATION_LEVEL}-export const notificationSettingsQueryFn = async (): Promise<NotificationSettings> => {- const rows = await apiFetch<NotificationSettingRow[]>(- "/api/community/users/me/notifications",- )+export const notificationSettingsQueryFn = async (+ context: QueryFunctionContext = {} as QueryFunctionContext,+): Promise<NotificationSettings> => {+ const rows = context.signal+ ? await apiFetch<NotificationSettingRow[]>(+ "/api/community/users/me/notifications",+ { signal: context.signal },+ )+ : await apiFetch<NotificationSettingRow[]>(+ "/api/community/users/me/notifications",+ )const server: Record<string, string> = {}const channel: Record<string, string> = {}for (const s of rows) {@@ -54,14 +73,47 @@ export const notificationSettingsQueryFn = async (): Promise<NotificationSettingreturn { raw: rows, server, channel }}+function projectNotificationSettings(+ projection: AccountUnreadProjection,+ settings: Pick<NotificationSettings, "server" | "channel"> | undefined,+) {+ projection.setNotificationPolicy({+ server: settings?.server ?? {},+ channel: settings?.channel ?? {},+ })+}++export async function reconcileNotificationSettings(queryClient: QueryClient) {+ const queryKey = communityKeys.notificationSettings()+ // A policy WS event is newer than any transport already in flight. Cancel+ // that generation first so TanStack cannot dedupe this repair onto the old+ // request and install its stale response after the event.+ await queryClient.cancelQueries({ queryKey, exact: true })+ const settings = await queryClient.fetchQuery({+ queryKey,+ queryFn: notificationSettingsQueryFn,+ staleTime: 0,+ })+ projectNotificationSettings(getActiveAccountUnreadProjection(queryClient), settings)+ return settings+}+export function useNotificationSettings(): UseQueryResult<NotificationSettings> & {server: Record<string, string>channel: Record<string, string>} {+ const queryClient = useQueryClient()+ const projection = useMemo(+ () => getActiveAccountUnreadProjection(queryClient),+ [queryClient],+ )const query = useQuery({queryKey: communityKeys.notificationSettings(),queryFn: notificationSettingsQueryFn,})+ useEffect(() => {+ if (query.data) projectNotificationSettings(projection, query.data)+ }, [projection, query.data])return {...query,server: query.data?.server ?? (EMPTY_NOTIF_SERVER as Record<string, string>),diff --git a/src/web/src/hooks/community/use-servers.test.ts b/src/web/src/hooks/community/use-servers.test.tsindex b02464df4..369a2e8ae 100644--- a/src/web/src/hooks/community/use-servers.test.ts+++ b/src/web/src/hooks/community/use-servers.test.ts@@ -19,7 +19,7 @@ vi.mock("@/lib/api/client", () => ({type CapturedQueryConfig = {enabled?: boolean- queryFn?: () => unknown+ queryFn?: (context?: { signal?: AbortSignal }) => unknown}let capturedQueryConfig: CapturedQueryConfig | null = nulllet capturedHookQueryClient: QueryClient@@ -111,6 +111,60 @@ describe("useServers / serversQueryFn", () => {expect(qc.getQueryData(key)).toEqual({ servers: [] })})+ it("uses a complete server list as authoritative unread negative evidence", async () => {+ apiFetchMock.mockResolvedValueOnce({ servers: [] })+ const { serversProjectedQueryFn } = await import("./use-servers")+ const { AccountUnreadProjection } = await import("./account-unread-projection")+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({})+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 2 })++ await serversProjectedQueryFn(projection)()++ expect(projection.projectUnread("servers", "c1", false)).toBe(false)+ })++ it("cancels server-list snapshot coverage when the transport fails", async () => {+ apiFetchMock.mockRejectedValueOnce(new Error("offline"))+ const { serversProjectedQueryFn } = await import("./use-servers")+ const { AccountUnreadProjection } = await import("./account-unread-projection")+ const projection = new AccountUnreadProjection("u1")++ await expect(serversProjectedQueryFn(projection)()).rejects.toThrow("offline")++ expect(projection.inspectForTests().pendingSnapshots).toBe(0)+ })++ it("correlates cold rail unread sources with their attention facets", async () => {+ apiFetchMock.mockResolvedValueOnce({ servers: [{+ id: "s1",+ name: "One",+ discriminator: "0001",+ icon: null,+ ownerId: "u1",+ unreadSources: [+ { channelId: "attention", lastUnreadSeq: 10 },+ { channelId: "ordinary", lastUnreadSeq: 3 },+ ],+ mentionSources: [+ { channelId: "attention", count: 1, lastSeq: 5 },+ { channelId: "ignored", count: 0, lastSeq: 99 },+ ],+ }] })+ const { serversProjectedQueryFn } = await import("./use-servers")+ const { AccountUnreadProjection } = await import("./account-unread-projection")+ const projection = new AccountUnreadProjection("u1")+ projection.setNotificationPolicy({ server: { s1: "mentions" } })++ await serversProjectedQueryFn(projection)()++ expect(projection.projectUnread("servers", "attention", false)).toBe(true)+ expect(projection.projectUnread("servers", "ordinary", false)).toBe(false)+ expect(projection.projectUnread("servers", "ignored", false)).toBe(false)+ projection.recordRead("attention", 5)+ expect(projection.projectUnread("servers", "attention", false)).toBe(false)+ })+it("projects a live unread arrival and preserves unchanged server identity", async () => {const changed = {id: "s1",@@ -206,7 +260,162 @@ describe("useServer / serverQueryFn", () => {expect(apiFetchMock).not.toHaveBeenCalled()})- it("projects server-detail channels while preserving unchanged category paths", async () => {+ it("executes the enabled hook query through the projected detail adapter", async () => {+ capturedHookQueryClient.setQueryData(communityKeys.servers(), { servers: [{+ id: "srv_1",+ name: "Alook",+ discriminator: "0001",+ description: "",+ icon: null,+ ownerId: "u_1",+ }] })+ apiFetchMock.mockImplementation(async (url: string) => {+ if (url.endsWith("/categories")) return { categories: [] }+ if (url.endsWith("/channels")) return { channels: [] }+ if (url.endsWith("/unreads")) return { channelIds: [], sources: [] }+ throw new Error(`unexpected ${url}`)+ })+ const { useServer } = await import("./use-servers")+ useServer("srv_1")++ await expect(capturedQueryConfig?.queryFn?.()).resolves.toMatchObject({ id: "srv_1" })+ })++ it("starts server-detail coverage before transport and preserves a later arrival", async () => {+ let resolveUnreads!: (value: { channelIds: string[]; sources: never[] }) => void+ const unreadResponse = new Promise<{ channelIds: string[]; sources: never[] }>(+ (resolve) => { resolveUnreads = resolve },+ )+ apiFetchMock.mockImplementation(async (url: string) => {+ if (url.endsWith("/categories")) return { categories: [] }+ if (url.endsWith("/channels")) return { channels: [] }+ if (url.endsWith("/unreads")) return unreadResponse+ throw new Error(`unexpected ${url}`)+ })+ const qc = new QueryClient()+ qc.setQueryData(communityKeys.servers(), { servers: [{+ id: "srv_1",+ name: "Alook",+ discriminator: "0001",+ description: "",+ icon: null,+ ownerId: "u_1",+ }] })+ const {+ getAccountUnreadProjection,+ } = await import("./account-unread-projection")+ const projection = getAccountUnreadProjection(qc, "u1")+ projection.setNotificationPolicy({})+ projection.recordArrival({ channelId: "before", serverId: "srv_1", seq: 1 })+ const { serverProjectedQueryFn } = await import("./use-servers")++ const request = serverProjectedQueryFn(qc, "srv_1")()+ projection.recordArrival({ channelId: "after", serverId: "srv_1", seq: 2 })+ resolveUnreads({ channelIds: [], sources: [] })+ await request++ expect(projection.projectUnread("server-detail:srv_1", "before", false))+ .toBe(false)+ expect(projection.projectUnread("server-detail:srv_1", "after", false))+ .toBe(true)+ })++ it("cancels server-detail snapshot coverage when transport fails before unread data", async () => {+ apiFetchMock.mockRejectedValue(new Error("offline"))+ const qc = new QueryClient()+ qc.setQueryData(communityKeys.servers(), { servers: [{+ id: "srv_1",+ name: "Alook",+ discriminator: "0001",+ description: "",+ icon: null,+ ownerId: "u_1",+ }] })+ const { getAccountUnreadProjection } = await import("./account-unread-projection")+ const projection = getAccountUnreadProjection(qc, "u1")+ const { serverProjectedQueryFn } = await import("./use-servers")++ await expect(serverProjectedQueryFn(qc, "srv_1")()).rejects.toThrow("offline")++ expect(projection.inspectForTests().pendingSnapshots).toBe(0)+ })++ it("merges stale server-detail positives before rejecting the cache write", async () => {+ apiFetchMock.mockImplementation(async (url: string) => {+ if (url.endsWith("/categories")) return { categories: [] }+ if (url.endsWith("/channels")) return { channels: [] }+ if (url.endsWith("/unreads")) return {+ channelIds: ["c1"],+ sources: [{ channelId: "c1", lastUnreadSeq: 3, lastAttentionSeq: null }],+ stale: true,+ }+ throw new Error(`unexpected ${url}`)+ })+ const qc = new QueryClient()+ qc.setQueryData(communityKeys.servers(), { servers: [{+ id: "srv_1",+ name: "Alook",+ discriminator: "0001",+ description: "",+ icon: null,+ ownerId: "u_1",+ }] })+ const { getAccountUnreadProjection } = await import("./account-unread-projection")+ const projection = getAccountUnreadProjection(qc, "u1")+ const { serverProjectedQueryFn } = await import("./use-servers")++ await expect(serverProjectedQueryFn(qc, "srv_1")()).rejects.toThrow("stale D1 read")++ expect(projection.projectUnread("server-detail:srv_1", "c1", false)).toBe(true)+ })++ it("projects child scope metadata and confirms every loaded channel", async () => {+ apiFetchMock.mockImplementation(async (url: string) => {+ if (url.endsWith("/categories")) {+ return { categories: [{ id: "cat_1", name: "Main", private: 0 }] }+ }+ if (url.endsWith("/channels")) {+ return { channels: [{+ id: "forum_1",+ name: "Forum",+ type: "forum",+ categoryId: "cat_1",+ }] }+ }+ if (url.endsWith("/unreads")) return {+ channelIds: ["post_1"],+ sources: [{ channelId: "post_1", lastUnreadSeq: 4, lastAttentionSeq: null }],+ childChannels: [{ id: "post_1", parentChannelId: "forum_1" }],+ }+ throw new Error(`unexpected ${url}`)+ })+ const qc = new QueryClient()+ qc.setQueryData(communityKeys.servers(), { servers: [{+ id: "srv_1",+ name: "Alook",+ discriminator: "0001",+ description: "",+ icon: null,+ ownerId: "u_1",+ }] })+ const { getAccountUnreadProjection } = await import("./account-unread-projection")+ const projection = getAccountUnreadProjection(qc, "u1")+ projection.setNotificationPolicy({+ server: { srv_1: "all" },+ channel: { forum_1: "nothing" },+ })+ projection.retireAccessScope({ kind: "channel", channelId: "forum_1" })+ projection.grantAccessScope({ kind: "channel", channelId: "forum_1" })+ const { serverProjectedQueryFn } = await import("./use-servers")++ await serverProjectedQueryFn(qc, "srv_1")()++ expect(projection.projectUnread("server-detail:srv_1", "post_1", false, 4)).toBe(false)+ projection.recordArrival({ channelId: "forum_1", serverId: "srv_1", seq: 5 })+ expect(projection.projectUnread("server-detail:srv_1", "forum_1", false, 5)).toBe(false)+ })++ it("projects server-detail channels from canonical sources only", async () => {const changedChannel = { id: "c1", unread: false }const unchangedChannel = { id: "c2", unread: true }const changedCategory = { id: "cat1", channels: [changedChannel] }@@ -231,8 +440,9 @@ describe("useServer / serverQueryFn", () => {expect(result.server).not.toBe(detail)expect(result.server?.categories[0]).not.toBe(changedCategory)expect(result.server?.categories[0]?.channels[0]?.unread).toBe(true)- expect(result.server?.categories[1]).toBe(unchangedCategory)- expect(result.server?.categories[1]?.channels[0]).toBe(unchangedChannel)+ expect(result.server?.categories[1]).not.toBe(unchangedCategory)+ expect(result.server?.categories[1]?.channels[0]).not.toBe(unchangedChannel)+ expect(result.server?.categories[1]?.channels[0]?.unread).toBe(false)})it("retains rolling-deploy server-detail unread rows without source vectors", async () => {diff --git a/src/web/src/hooks/community/use-servers.ts b/src/web/src/hooks/community/use-servers.tsindex 98dacc10e..f7988f334 100644--- a/src/web/src/hooks/community/use-servers.ts+++ b/src/web/src/hooks/community/use-servers.ts@@ -13,7 +13,12 @@ import { communityKeys } from "@/lib/query-keys"import { avatarInitial } from "@/lib/community/avatar"import { isServerOwner, UNCATEGORIZED_CATEGORY_ID } from "@alook/shared"import type { Server, Category, Channel } from "@/lib/community/models/navigation"-import { getActiveAccountUnreadProjection } from "./account-unread-projection"+import {+ getActiveAccountUnreadProjection,+ type AccountUnreadProjection,+ type AccountUnreadScope,+ type AccountUnreadSource,+} from "./account-unread-projection"import { useInboxProjectionTarget } from "./use-inbox-auto-collapse"import { reservedUnreadExclusion } from "./unread-presentation"@@ -74,6 +79,43 @@ export const serversQueryFn = async (return { servers }}+function serverListUnreadSources(data: ServersResponse): AccountUnreadSource[] {+ return data.servers.flatMap((server) => (+ [+ ...(server.unreadSources ?? []).map((source) => ({+ ...source,+ serverId: server.id,+ })),+ ...(server.mentionSources ?? []).flatMap((source) => source.count > 0 ? [{+ channelId: source.channelId,+ serverId: server.id,+ lastUnreadSeq: source.lastSeq,+ lastMentionSeq: source.lastSeq,+ isMention: true,+ }] : []),+ ]+ ))+}++export const serversProjectedQueryFn = (+ projection: AccountUnreadProjection,+) => async (context?: QueryFunctionContext) => {+ const token = projection.beginSnapshot("servers", "channels")+ try {+ const data = await serversQueryFn(context)+ projection.absorbSnapshot(token, serverListUnreadSources(data), {+ confirmedAccessScopes: data.servers.map((server) => ({+ kind: "server" as const,+ serverId: server.id,+ })),+ })+ return data+ } catch (error) {+ projection.cancelSnapshot(token)+ throw error+ }+}+function serversQueryOptions() {return {queryKey: communityKeys.servers(),@@ -85,8 +127,18 @@ function serversQueryOptions() {export function useServers(): UseQueryResult<ServersResponse> & {servers: Server[]} {+ const queryClient = useQueryClient()+ const unreadProjection = useMemo(+ () => getActiveAccountUnreadProjection(queryClient),+ [queryClient],+ )+ const queryFn = useMemo(+ () => serversProjectedQueryFn(unreadProjection),+ [unreadProjection],+ )const query = useQuery({...serversQueryOptions(),+ queryFn,// 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@@ -99,11 +151,6 @@ export function useServers(): UseQueryResult<ServersResponse> & {staleTime: Infinity,refetchOnReconnect: true,})- const queryClient = useQueryClient()- const unreadProjection = useMemo(- () => getActiveAccountUnreadProjection(queryClient),- [queryClient],- )const unreadVersion = useSyncExternalStore(unreadProjection.subscribe,unreadProjection.getSnapshot,@@ -115,8 +162,13 @@ export function useServers(): UseQueryResult<ServersResponse> & {[reservationTarget],)useEffect(() => {- const sources = query.data?.servers.flatMap((server) => server.unreadSources ?? [])- if (sources) unreadProjection.absorbFamily("servers", sources)+ if (query.data) {+ unreadProjection.mergeSources(+ "servers",+ serverListUnreadSources(query.data),+ "channels",+ )+ }if (!query.data) returnfor (const server of query.data.servers) {if (server.unreadSources) {@@ -152,6 +204,7 @@ export function useServers(): UseQueryResult<ServersResponse> & {server.id,server.mentionSources ?? [],server.mentions,+ unreadExclusion,)if (unread === server.unread && mentions === server.mentions) return serverchanged = true@@ -218,14 +271,42 @@ async function resolveServerIdentity(?.servers.find((server) => server.id === serverId)if (cached) return cached- const fetched = await serversQueryFn({ signal } as QueryFunctionContext)+ const fetched = await serversProjectedQueryFn(+ getActiveAccountUnreadProjection(queryClient),+ )({ signal } as QueryFunctionContext)return fetched.servers.find((server) => server.id === serverId)}+function serverDetailUnreadSources(+ serverId: string,+ unreadData: UnreadResponse,+): AccountUnreadSource[] {+ const parentByChild = new Map(+ (unreadData.childChannels ?? []).map((child) => [child.id, child.parentChannelId]),+ )+ return (unreadData.sources ?? []).flatMap((source) => [+ {+ channelId: source.channelId,+ lastUnreadSeq: source.lastUnreadSeq,+ serverId,+ railChannelId: parentByChild.get(source.channelId),+ },+ ...(source.lastAttentionSeq == null ? [] : [{+ channelId: source.channelId,+ lastUnreadSeq: source.lastAttentionSeq,+ lastMentionSeq: source.lastAttentionSeq,+ serverId,+ railChannelId: parentByChild.get(source.channelId),+ isMention: true,+ }]),+ ])+}+export const serverQueryFn = (queryClient: QueryClient,serverId: string,signal?: AbortSignal,+ options: { onUnreadResponse?: (data: UnreadResponse) => void } = {},) => async (): Promise<ServerDetail> => {const fetchResource = <T,>(path: string) => signal? apiFetch<T>(path, { signal })@@ -236,6 +317,7 @@ export const serverQueryFn = (fetchResource<{ channels: RawChannel[] }>(`/api/community/servers/${serverId}/channels`),fetchResource<UnreadResponse>(`/api/community/servers/${serverId}/unreads`),])+ options.onUnreadResponse?.(unreadData)if (unreadData.stale) throw new Error("stale D1 read")if (!server) throw new Error("server not found")const unreadIds = new Set(unreadData.channelIds)@@ -284,6 +366,49 @@ export const serverQueryFn = (}}+export const serverProjectedQueryFn = (+ queryClient: QueryClient,+ serverId: string,+ signal?: AbortSignal,+) => async () => {+ const projection = getActiveAccountUnreadProjection(queryClient)+ const family = `server-detail:${serverId}` as const+ const token = projection.beginSnapshot(family, "channels")+ let unreadData: UnreadResponse | undefined+ try {+ const data = await serverQueryFn(queryClient, serverId, signal, {+ onUnreadResponse: (response) => {+ unreadData = response+ },+ })()+ if (!unreadData) throw new Error("server unread response missing")+ const confirmedAccessScopes: AccountUnreadScope[] = [+ { kind: "server", serverId },+ ...data.categories.flatMap((category) => category.channels.map((channel) => ({+ kind: "channel" as const,+ channelId: channel.id,+ }))),+ ]+ projection.absorbSnapshot(+ token,+ serverDetailUnreadSources(serverId, unreadData),+ { stale: unreadData.stale, confirmedAccessScopes },+ )+ return data+ } catch (error) {+ if (unreadData) {+ projection.absorbSnapshot(+ token,+ serverDetailUnreadSources(serverId, unreadData),+ { stale: true },+ )+ } else {+ projection.cancelSnapshot(token)+ }+ throw error+ }+}+/*** Fetches the detail (categories + channels) for one server. Pass `null` for* "no active server" (including the DM home) — the query stays disabled and@@ -308,11 +433,15 @@ export function useServer([reservationTarget],)const enabled = !!serverId+ const queryFn = useMemo(() => {+ if (!serverId) return () => Promise.reject(new Error("disabled"))+ return ({ signal }: QueryFunctionContext = {} as QueryFunctionContext) => (+ serverProjectedQueryFn(queryClient, serverId, signal)()+ )+ }, [queryClient, serverId])const query = useQuery({queryKey: enabled ? communityKeys.server(serverId!) : communityKeys.server("__none__"),- queryFn: enabled- ? serverQueryFn(queryClient, serverId!)- : (() => Promise.reject(new Error("disabled"))),+ queryFn,enabled,// WS events (member.*, channel/category changes) live-patch this// ServerDetail cache, so a remount doesn't need to refetch — this is a@@ -326,7 +455,11 @@ export function useServer(if (!serverId || !query.data) returnconst family = `server-detail:${serverId}` as constif (query.data.unreadSources) {- unreadProjection.absorbFamily(family, query.data.unreadSources)+ unreadProjection.mergeSources(+ family,+ query.data.unreadSources.map((source) => ({ ...source, serverId })),+ "channels",+ )return}unreadProjection.recordLegacySnapshot(diff --git a/src/web/src/hooks/community/use-thread-participants.test.ts b/src/web/src/hooks/community/use-thread-participants.test.tsindex 4b3d21847..4cc38c02c 100644--- a/src/web/src/hooks/community/use-thread-participants.test.ts+++ b/src/web/src/hooks/community/use-thread-participants.test.ts@@ -1,6 +1,10 @@-import { beforeEach, describe, expect, it, vi } from "vitest"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { QueryClient } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"+import {+ disposeAccountUnreadProjection,+ getAccountUnreadProjection,+} from "./account-unread-projection"const apiFetchMock = vi.fn()vi.mock("@/lib/api/client", () => ({@@ -50,12 +54,23 @@ beforeEach(() => {queryClient = new QueryClient()})+afterEach(() => {+ disposeAccountUnreadProjection(queryClient)+ queryClient.clear()+})+describe("useRemoveThreadParticipant", () => {it("removes the child from every sidebar view when the viewer leaves", async () => {const key = communityKeys.forumSidebarThreads("server_1")const metaKey = communityKeys.channelMeta("server_1", "post_1")queryClient.setQueryData(key, sidebarData())queryClient.setQueryData(metaKey, { id: "post_1", parentChannelId: "forum_1" })+ const unreadProjection = getAccountUnreadProjection(queryClient, "viewer_1")+ unreadProjection.recordArrival({+ channelId: "post_1",+ serverId: "server_1",+ seq: 7,+ })const { useRemoveThreadParticipant } = await import("./use-thread-participants")useRemoveThreadParticipant("post_1", "server_1", "viewer_1")@@ -68,11 +83,34 @@ describe("useRemoveThreadParticipant", () => {)expect(queryClient.getQueryData<ReturnType<typeof sidebarData>>(key)?.threads).toEqual([])expect(queryClient.getQueryData(metaKey)).toEqual({ id: "post_1", parentChannelId: "forum_1" })+ expect(unreadProjection.projectUnread("inbox-unreads", "post_1", false, 7)).toBe(false)+ })++ it("does not retire viewer unread scope when participant removal fails", async () => {+ const unreadProjection = getAccountUnreadProjection(queryClient, "viewer_1")+ unreadProjection.recordArrival({+ channelId: "post_1",+ serverId: "server_1",+ seq: 7,+ })+ apiFetchMock.mockRejectedValueOnce(new Error("failed"))+ const { useRemoveThreadParticipant } = await import("./use-thread-participants")+ useRemoveThreadParticipant("post_1", "server_1", "viewer_1")++ await expect(config.mutationFn("viewer_1")).rejects.toThrow("failed")++ expect(unreadProjection.projectUnread("inbox-unreads", "post_1", false, 7)).toBe(true)})it("keeps the viewer's sidebar row when the creator removes someone else", async () => {const key = communityKeys.forumSidebarThreads("server_1")queryClient.setQueryData(key, sidebarData())+ const unreadProjection = getAccountUnreadProjection(queryClient, "viewer_1")+ unreadProjection.recordArrival({+ channelId: "post_1",+ serverId: "server_1",+ seq: 7,+ })const { useRemoveThreadParticipant } = await import("./use-thread-participants")useRemoveThreadParticipant("post_1", "server_1", "viewer_1")@@ -80,6 +118,7 @@ describe("useRemoveThreadParticipant", () => {config.onSuccess?.(result, "other_1")expect(queryClient.getQueryData<ReturnType<typeof sidebarData>>(key)?.threads).toHaveLength(1)+ expect(unreadProjection.projectUnread("inbox-unreads", "post_1", false, 7)).toBe(true)})it("does not revalidate the viewer's forum access when adding someone else", async () => {@@ -95,6 +134,19 @@ describe("useRemoveThreadParticipant", () => {expect(queryClient.getQueryData<ReturnType<typeof sidebarData>>(key)?.threads).toHaveLength(1)})+ it("contains a failed retained-authority fetch after the viewer is re-added", async () => {+ apiFetchMock.mockRejectedValueOnce(new Error("offline"))+ const { useAddThreadParticipant } = await import("./use-thread-participants")+ useAddThreadParticipant("post_1", "server_1", "viewer_1")++ config.onSuccess?.(undefined, "viewer_1")++ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledWith(+ expect.stringContaining("/api/community/servers/server_1/channels?"),+ expect.objectContaining({ signal: expect.any(AbortSignal) }),+ ))+ })+it("does not touch forum sidebar resources for an ordinary text thread", async () => {const baseKey = communityKeys.forumSidebarThreads("server_1")const retainedKey = communityKeys.forumSidebarRetained("server_1", "forum_post")diff --git a/src/web/src/hooks/community/use-thread-participants.ts b/src/web/src/hooks/community/use-thread-participants.tsindex f2ec592e1..d1e163cee 100644--- a/src/web/src/hooks/community/use-thread-participants.ts+++ b/src/web/src/hooks/community/use-thread-participants.ts@@ -8,6 +8,7 @@ import {removeForumSidebarProjectionExact,removeForumSidebarUnreadChild,} from "@/hooks/community/use-forum-sidebar-threads"+import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"// The participant READ hook was retired: the post/thread member panel now reads// the unified `/members` endpoint (via `useChannelMembers`), which returns the@@ -32,6 +33,7 @@ export function useAddThreadParticipant(void qc.invalidateQueries({ queryKey: communityKeys.channelMembers(channelId) })if (serverId && userId === viewerUserId) {void grantForumSidebarChild(qc, serverId, channelId)+ .catch(() => undefined)}},})@@ -54,6 +56,10 @@ export function useRemoveThreadParticipant(onSuccess: (_data, userId) => {void qc.invalidateQueries({ queryKey: communityKeys.channelMembers(channelId) })if (serverId && userId === viewerUserId) {+ getActiveAccountUnreadProjection(qc).retireAccessScope({+ kind: "channel",+ channelId,+ })if (forumSidebar) {removeForumSidebarUnreadChild(qc, serverId, channelId)removeForumSidebarProjectionExact(qc, serverId, channelId)diff --git a/src/web/src/lib/community/conversation-navigation-warmup.test.ts b/src/web/src/lib/community/conversation-navigation-warmup.test.tsindex 39bb61730..092c2a4c6 100644--- a/src/web/src/lib/community/conversation-navigation-warmup.test.ts+++ b/src/web/src/lib/community/conversation-navigation-warmup.test.ts@@ -69,7 +69,7 @@ vi.mock("@/hooks/community/use-messages", () => ({}),}))vi.mock("@/hooks/community/use-servers", () => ({- serverQueryFn: (_queryClient: unknown, serverId: string, signal?: AbortSignal) => () => (+ serverProjectedQueryFn: (_queryClient: unknown, serverId: string, signal?: AbortSignal) => () => (new Promise((resolve, reject) => {mocks.servers.push({serverId,diff --git a/src/web/src/lib/community/conversation-navigation-warmup.ts b/src/web/src/lib/community/conversation-navigation-warmup.tsindex 660a437d0..81397fce2 100644--- a/src/web/src/lib/community/conversation-navigation-warmup.ts+++ b/src/web/src/lib/community/conversation-navigation-warmup.ts@@ -6,7 +6,7 @@ import { ApiError } from "@/lib/errors"import { communityKeys } from "@/lib/query-keys"import type { MessagesPageParam } from "@/lib/community/models/message"import { channelMessagesQueryFn, dmMessagesQueryFn } from "@/hooks/community/use-messages"-import { serverQueryFn, type ServerDetail } from "@/hooks/community/use-servers"+import { serverProjectedQueryFn, type ServerDetail } from "@/hooks/community/use-servers"import { useMessageStreamStore } from "@/stores/community/message-stream"import {beginConversationNavigationProof,@@ -112,7 +112,7 @@ export function startConversationNavigationWarmup(.catch(() => undefined)if (target.serverId) {- void serverQueryFn(queryClient, target.serverId, signal)()+ void serverProjectedQueryFn(queryClient, target.serverId, signal)().then((detail) => {if (!isCurrentConversationNavigation(queryClient, epoch, accessEpoch)) returnqueryClient.setQueryData<ServerDetail>(communityKeys.server(target.serverId!), detail)diff --git a/src/web/src/test/architecture/community-unread-projection-owner-contract.test.ts b/src/web/src/test/architecture/community-unread-projection-owner-contract.test.tsnew file mode 100644index 000000000..7489069d4--- /dev/null+++ b/src/web/src/test/architecture/community-unread-projection-owner-contract.test.ts@@ -0,0 +1,72 @@+import { readdirSync, readFileSync } from "node:fs"+import { relative, resolve } from "node:path"+import { fileURLToPath } from "node:url"+import { describe, expect, it } from "vitest"++const repositoryRoot = fileURLToPath(new URL("../../../../../", import.meta.url))++function source(path: string): string {+ return readFileSync(resolve(repositoryRoot, path), "utf8")+}++function walkTypeScript(directory: string, files: string[] = []): string[] {+ for (const entry of readdirSync(directory, { withFileTypes: true })) {+ const path = resolve(directory, entry.name)+ if (entry.isDirectory()) walkTypeScript(path, files)+ else if (/\.tsx?$/.test(entry.name)) files.push(path)+ }+ return files+}++describe("community unread projection owner contract", () => {+ it("creates the authenticated account owner only at the query boundary", () => {+ const webSourceRoot = resolve(repositoryRoot, "src/web/src")+ const constructors = walkTypeScript(webSourceRoot)+ .filter((path) => !path.includes("/test/") && !path.endsWith(".test.ts"))+ .filter((path) => /new AccountUnreadProjection\s*\(/.test(readFileSync(path, "utf8")))+ .map((path) => relative(repositoryRoot, path).replaceAll("\\", "/"))++ expect(constructors).toEqual([+ "src/web/src/hooks/community/account-unread-projection.ts",+ ])+ expect(source("src/web/src/app/c/QueryProvider.tsx"))+ .toContain("getAccountUnreadProjection(queryClient, userId)")+ })++ it("keeps dot components presentation-only", () => {+ const consumers = [+ "src/web/src/components/community/shell/community-inbox-popover.tsx",+ "src/web/src/components/community/shell/community-inbox-surface.tsx",+ "src/web/src/components/community/shell/rail-folder.tsx",+ "src/web/src/components/community/shell/sortable-server.tsx",+ "src/web/src/components/community/channels/channel-sidebar.tsx",+ "src/web/src/components/community/channels/sortable-channel.tsx",+ "src/web/src/components/community/channels/dm-sidebar.tsx",+ ]++ for (const path of consumers) {+ expect(source(path)).not.toMatch(+ /\b(?:useInboxUnreads|useInboxMentions|useServers|useServer|useDms)\s*\(/,+ )+ expect(source(path)).not.toContain("communityKeys.")+ expect(source(path)).not.toContain("getActiveAccountUnreadProjection")+ }+ })++ it("requires projected inbox dot state without raw row-count fallback", () => {+ const popover = source(+ "src/web/src/components/community/shell/community-inbox-popover.tsx",+ )+ expect(popover).toContain("hasProjectedUnreads: boolean")+ expect(popover).toContain("hasProjectedMentions: boolean")+ expect(popover).toContain("const hasUnreads = hasProjectedUnreads")+ expect(popover).toContain("const hasMentions = hasProjectedMentions")+ expect(popover).not.toMatch(/hasProjectedUnreads\s*\?\?/)+ expect(popover).not.toMatch(/hasProjectedMentions\s*\?\?/)++ const surface = source(+ "src/web/src/components/community/shell/community-inbox-surface.tsx",+ )+ expect(surface).toContain("hasUnread: boolean")+ })+})diff --git a/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts b/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.tsindex 0d45355ad..7743f2f76 100644--- a/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts+++ b/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts@@ -17,31 +17,63 @@ import {proxyCommunityWebSockets,} from "./_fixtures/community-ws-proxy"-type CapturedReadStateEvent = CapturedCommunityFrame & {- type: "community:read_state.advanced" | "community:inbox.changed"+type CapturedReadStateAdvancedEvent = CapturedCommunityFrame & {+ type: "community:read_state.advanced"revision: numberinboxChanged: boolean}-function isCapturedReadStateEvent(event: CapturedCommunityFrame): event is CapturedReadStateEvent {+type CapturedInboxChangedEvent = CapturedCommunityFrame & {+ type: "community:inbox.changed"+ revision: number+ inboxChanged: boolean+ reason: "read_all" | "mention_read_all" | "mention_dismiss" | "notification_policy"+}++function isCapturedReadStateAdvancedEvent(+ event: CapturedCommunityFrame,+): event is CapturedReadStateAdvancedEvent {+ return (+ event.type === "community:read_state.advanced"+ && typeof event.revision === "number"+ && typeof event.inboxChanged === "boolean"+ )+}++function isCapturedInboxChangedEvent(+ event: CapturedCommunityFrame,+): event is CapturedInboxChangedEvent {return (- (event.type === "community:read_state.advanced" || event.type === "community:inbox.changed")+ event.type === "community:inbox.changed"&& typeof event.revision === "number"&& typeof event.inboxChanged === "boolean"+ && (+ event.reason === "read_all"+ || event.reason === "mention_read_all"+ || event.reason === "mention_dismiss"+ || event.reason === "notification_policy"+ ))}function readStateEventsSince(frames: CapturedCommunityFrame[],start: number,-): CapturedReadStateEvent[] {+): CapturedReadStateAdvancedEvent[] {return frames.slice(start).flatMap((frame) => communityFrameEvents(frame))- .filter((event): event is CapturedReadStateEvent => (- isCapturedReadStateEvent(event)- && event.type === "community:read_state.advanced"- ))+ .filter(isCapturedReadStateAdvancedEvent)+}++function inboxChangedEventsSince(+ frames: CapturedCommunityFrame[],+ start: number,+): CapturedInboxChangedEvent[] {+ return frames+ .slice(start)+ .flatMap((frame) => communityFrameEvents(frame))+ .filter(isCapturedInboxChangedEvent)}function unreadBumpsSince(@@ -272,14 +304,8 @@ test("one human account converges read state across two browser profiles", asyncawait expect(deviceA.page.getByText("Caught up", { exact: true })).toBeVisible({ timeout: 20_000 })await expect(deviceB.page.getByText("Caught up", { exact: true })).toBeVisible({ timeout: 20_000 })- const readAllEvents = (frames: typeof proxyA.frames, start: number) => frames- .slice(start)- .flatMap((frame) => communityFrameEvents(frame))- .filter((event): event is CapturedReadStateEvent => (- isCapturedReadStateEvent(event)- && event.type === "community:inbox.changed"- && event.reason === "read_all"- ))+ const readAllEvents = (frames: typeof proxyA.frames, start: number) =>+ inboxChangedEventsSince(frames, start).filter((event) => event.reason === "read_all")await expect.poll(() => readAllEvents(proxyA.frames, readAllFrameStarts[0]!).length, {timeout: 20_000,}).toBe(changedReadAllResults.length)@@ -782,16 +808,26 @@ test("human author-send replaces both profiles while notification policy preservexpect(notificationStatus).toBe(200)for (const [proxy, start] of [[proxyA, notificationStarts[0]], [proxyB, notificationStarts[1]]] as const) {- await expect.poll(() => readStateEventsSince(proxy.frames, start!).length, {+ await expect.poll(() => inboxChangedEventsSince(proxy.frames, start!).filter(+ (event) => event.reason === "notification_policy",+ ).length, {timeout: 20_000,}).toBe(1)- const event = readStateEventsSince(proxy.frames, start!)[0]!+ const event = inboxChangedEventsSince(proxy.frames, start!)+ .find((candidate) => candidate.reason === "notification_policy")!+ expect(event).toMatchObject({+ type: "community:inbox.changed",+ reason: "notification_policy",+ inboxChanged: true,+ })expect(event.revision).toBeGreaterThan(authorEvents[0].revision)expect("readStates" in event).toBe(false)}const notificationEvents = [- readStateEventsSince(proxyA.frames, notificationStarts[0]!)[0]!,- readStateEventsSince(proxyB.frames, notificationStarts[1]!)[0]!,+ inboxChangedEventsSince(proxyA.frames, notificationStarts[0]!)+ .find((event) => event.reason === "notification_policy")!,+ inboxChangedEventsSince(proxyB.frames, notificationStarts[1]!)+ .find((event) => event.reason === "notification_policy")!,]expect(notificationEvents[0].revision).toBe(notificationEvents[1].revision)await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(notificationChannelId))).toHaveCount(0)@@ -816,10 +852,28 @@ test("human author-send replaces both profiles while notification policy preservexpect(restoreStatus).toBe(200)for (const [proxy, start] of [[proxyA, restoreStarts[0]], [proxyB, restoreStarts[1]]] as const) {- await expect.poll(() => readStateEventsSince(proxy.frames, start!).length, {+ await expect.poll(() => inboxChangedEventsSince(proxy.frames, start!).filter(+ (event) => event.reason === "notification_policy",+ ).length, {timeout: 20_000,}).toBe(1)+ const event = inboxChangedEventsSince(proxy.frames, start!)+ .find((candidate) => candidate.reason === "notification_policy")!+ expect(event).toMatchObject({+ type: "community:inbox.changed",+ reason: "notification_policy",+ inboxChanged: true,+ })+ expect(event.revision).toBeGreaterThan(notificationEvents[0].revision)+ expect("readStates" in event).toBe(false)}+ const restoreEvents = [+ inboxChangedEventsSince(proxyA.frames, restoreStarts[0]!)+ .find((event) => event.reason === "notification_policy")!,+ inboxChangedEventsSince(proxyB.frames, restoreStarts[1]!)+ .find((event) => event.reason === "notification_policy")!,+ ]+ expect(restoreEvents[0].revision).toBe(restoreEvents[1].revision)await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(notificationChannelId))).toBeVisible()const restoredSnapshot = await (await deviceB.page.request.get("/api/community/users/me/read-state",diff --git a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.tsindex bbe35f0fa..854317039 100644--- a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts+++ b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts@@ -217,6 +217,94 @@ async function expectRailReplacementDoesNotBlockMessages({test.describe.serial("account unread projection", () => {test.setTimeout(180_000)+ test("one mention source disappears from Unreads, Mentions, and every dot in the same frame", async ({ asUser }) => {+ const stamp = Date.now()+ const serverId = await seedServer("alice", `Projection mention ${stamp}`)+ const channelName = `mention-${stamp}`+ const channelId = await seedChannel("alice", serverId, channelName)+ await seedJoinServer("alice", "bob", serverId)+ const bobInfo = await memberInfo("alice", serverId, userId("bob"))++ const bob = await asUser("bob")+ for (const path of [+ "/api/community/users/me/inbox/mentions/read-all",+ "/api/community/users/me/inbox/unreads/read-all",+ "/api/community/users/me/inbox/dms/read-all",+ ]) {+ expect((await bob.page.request.post(path)).ok()).toBe(true)+ }+ const observerGate = await installReadObserverGate(bob.page)+ const proxy = await proxyCommunityWebSockets(bob.context)+ await gotoAfterUserWsAuth(bob.page, "/c/me/friends")+ await expect(bob.page.getByTestId(tid.serverIcon(serverId))).toBeVisible({ timeout: 30_000 })++ const alice = await asUser("alice")+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}`)+ const mentionText = `Canonical mention ${stamp}`+ const frameStart = proxy.frames.length+ const response = alice.page.waitForResponse((candidate) => (+ candidate.request().method() === "POST"+ && new URL(candidate.url()).pathname === `/api/community/channels/${channelId}/messages`+ ))+ const editable = composerEditable(alice.page)+ await editable.click()+ await editable.pressSequentially(`@${bobInfo.name.slice(0, 3)}`)+ await alice.page.getByTestId(tid.mentionOption(bobInfo.id)).click()+ await editable.pressSequentially(` ${mentionText}`)+ await alice.page.keyboard.press("Enter")+ const messageResponse = await response+ expect(messageResponse.status()).toBe(201)+ const messageId = (await messageResponse.json() as { message: { id: string } }).message.id+ await expect.poll(() => {+ const events = proxy.frames.slice(frameStart).flatMap(communityFrameEvents)+ return events.some((event) => (+ event.type === "community:message.create"+ && event.message?.id === messageId+ )) && events.some((event) => (+ event.type === "community:unread.bump"+ && event.channelId === channelId+ )) && events.some((event) => (+ event.type === "community:mention.create"+ && event.messageId === messageId+ ))+ }, { timeout: 20_000 }).toBe(true)++ const inboxTrigger = bob.page.getByTestId(tid.inboxTrigger)+ await expect(inboxTrigger.locator("span.bg-primary")).toHaveCount(1)+ await inboxTrigger.click()+ await expect(bob.page.getByTestId(tid.inboxUnreadChannel(channelId))).toBeVisible()+ await bob.page.getByRole("tab", { name: "Mentions" }).click()+ await expect(bob.page.getByText(mentionText, { exact: false })).toBeVisible()+ await bob.page.getByRole("tab", { name: "Unreads" }).click()++ await observerGate.block()+ await bob.page.getByTestId(tid.inboxUnreadChannel(channelId)).click()+ await expect(bob.page).toHaveURL(`/c/channels/${serverId}/${channelId}`)+ await expect(bob.page.getByText(mentionText, { exact: false })).toBeVisible({ timeout: 20_000 })+ await expect.poll(observerGate.pending).toBeGreaterThan(0)+ await expect(inboxTrigger.locator("span.bg-primary")).toHaveCount(0)+ await expectNoUnreadDot(bob.page.getByTestId(tid.channelRow(channelId)))+ await expect.poll(async () => bob.page+ .getByTestId(tid.serverRailIndicator(serverId))+ .evaluate((element) => element.getBoundingClientRect().height)).toBe(40)+ await expect(bob.page.getByTestId(tid.railUnreadBadge(serverId))).toHaveCount(0)++ await inboxTrigger.click()+ await expect(bob.page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0)+ await expect(bob.page.getByRole("tab", { name: "Unreads" }).locator("span.bg-primary")).toHaveCount(0)+ await bob.page.getByRole("tab", { name: "Mentions" }).click()+ const inboxPanel = bob.page.getByTestId(tid.inboxTabList).locator("xpath=..")+ await expect(inboxPanel.getByText(mentionText, { exact: false })).toHaveCount(0)+ await expect(bob.page.getByRole("tab", { name: "Mentions" }).locator("span.bg-primary")).toHaveCount(0)++ const readResponse = bob.page.waitForResponse((candidate) => (+ candidate.request().method() === "PUT"+ && new URL(candidate.url()).pathname === `/api/community/channels/${channelId}/read`+ ))+ await observerGate.release()+ expect((await readResponse).status()).toBe(200)+ })+test("one committed bundle projects every surface and only a visible row clears it", async ({ asUser }, testInfo) => {const stamp = Date.now()const foregroundServer = await seedServer("alice", `Projection foreground ${stamp}`)diff --git a/src/ws-do/src/routes/message-delivery.test.ts b/src/ws-do/src/routes/message-delivery.test.tsindex 7db112554..b3cdc7065 100644--- a/src/ws-do/src/routes/message-delivery.test.ts+++ b/src/ws-do/src/routes/message-delivery.test.ts@@ -1,7 +1,9 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import {COMMUNITY_DELIVERY_OPERATION_ID_HEADER,+ MESSAGE_DELIVERY_MAX_EVENTS_PER_USER,deriveCommunityDeliveryOperationId,+ type MessageDeliveryBatch,} from "@alook/shared"import { createCommunityDeliveryReceipt } from "../community-delivery-receipt"import { INTERNAL_USER_TARGET_HEADER } from "../internal-user-broadcast"@@ -49,7 +51,7 @@ const batch = {type InternalBundleBody = {operationId: stringoperationDigest: string- events: Array<{ type: string }>+ events: Array<{ type: string; [key: string]: unknown }>}async function successfulReceipt(request: Request): Promise<Response> {@@ -63,7 +65,7 @@ async function successfulReceipt(request: Request): Promise<Response> {}))}-async function deliveryRequest(value: typeof batch = batch): Promise<Request> {+async function deliveryRequest(value: MessageDeliveryBatch = batch): Promise<Request> {return new Request("http://localhost/broadcast/community/message-delivery", {method: "POST",headers: {@@ -122,11 +124,35 @@ describe("message delivery route", () => {"community:mention.create","community:channel.child_update",])- expect(byUser.get("mention-only")?.events.map((event) => event.type)).toEqual(["community:mention.create"])+ expect(byUser.get("mention-only")?.events.map((event) => event.type)).toEqual([+ "community:unread.bump",+ "community:mention.create",+ ])+ expect(byUser.get("mention-only")?.events[0]).toMatchObject({+ channelId: "thread-1",+ serverId: "server-1",+ railChannelId: "forum-1",+ isMention: true,+ })+ // Exact legacy strict shape: scope travels on the pre-existing bump so an+ // already-open client running the previous decoder accepts the whole batch.+ expect(byUser.get("mention-only")?.events[1]).toEqual({+ type: "community:mention.create",+ userId: "mention-only",+ messageId: "message-1",+ channelId: "thread-1",+ authorName: "Alice",+ })+ expect(byUser.get("overlap")?.events.filter((event) => (+ event.type === "community:unread.bump"+ ))).toHaveLength(1)expect(byUser.get("parent-only")?.events.map((event) => event.type)).toEqual(["community:channel.child_update"])expect(new Set(calls.map((call) => call.body.operationId))).toEqual(new Set([await deriveCommunityDeliveryOperationId("message-1"),]))+ expect(calls.every((call) => (+ call.body.events.length <= MESSAGE_DELIVERY_MAX_EVENTS_PER_USER+ ))).toBe(true)expect(byUser.get("author")?.operationDigest).not.toBe(byUser.get("overlap")?.operationDigest)})@@ -145,34 +171,74 @@ describe("message delivery route", () => {})it("keeps the operation ID and per-user digest stable after an accepted enqueue response is lost", async () => {- const overlapBodies: InternalBundleBody[] = []- let overlapAttempts = 0+ const mentionOnlyBodies: InternalBundleBody[] = []+ let mentionOnlyAttempts = 0doMock.stubFetch.mockImplementation(async (request: Request) => {const userId = decodeURIComponent(request.headers.get(INTERNAL_USER_TARGET_HEADER)!)- if (userId !== "overlap") return successfulReceipt(request)+ if (userId !== "mention-only") return successfulReceipt(request)const body = await request.clone().json() as InternalBundleBody- overlapBodies.push(body)- overlapAttempts += 1- if (overlapAttempts === 1) return new Response("")+ mentionOnlyBodies.push(body)+ mentionOnlyAttempts += 1+ if (mentionOnlyAttempts === 1) return new Response("")return successfulReceipt(request)})- const first = await handler.fetch(await deliveryRequest(), env as never)- expect(first.status).toBe(207)- await expect(first.json()).resolves.toEqual({ failedUserIds: ["overlap"] })-const retryBatch = {...batch,- contentUserIds: ["overlap"],- unreadMentionUserIds: ["overlap"],- mentionUserIds: ["overlap"],+ contentUserIds: [],+ unreadMentionUserIds: [],+ mentionUserIds: ["mention-only"],memberAdded: undefined,- parentProjectionUserIds: ["overlap"],+ parentProjectionUserIds: ["mention-only"],}+ const first = await handler.fetch(await deliveryRequest(retryBatch), env as never)+ expect(first.status).toBe(207)+ await expect(first.json()).resolves.toEqual({ failedUserIds: ["mention-only"] })+const retry = await handler.fetch(await deliveryRequest(retryBatch), env as never)expect(retry.status).toBe(200)- expect(overlapBodies).toHaveLength(2)- expect(overlapBodies[1]).toEqual(overlapBodies[0])+ expect(mentionOnlyBodies).toHaveLength(2)+ expect(mentionOnlyBodies[1]).toEqual(mentionOnlyBodies[0])+ expect(mentionOnlyBodies[0]?.events).toHaveLength(3)+ })++ it("keeps a mention-only DM scoped as a DM in the legacy-compatible batch", async () => {+ doMock.stubFetch.mockImplementation(successfulReceipt)+ const dmBatch = {+ ...batch,+ messageEvent: {+ ...batch.messageEvent,+ channelId: "dm-1",+ serverId: undefined,+ parentChannelId: undefined,+ },+ contentUserIds: [],+ unreadMentionUserIds: [],+ mentionUserIds: ["mention-only"],+ memberAdded: undefined,+ parentProjection: undefined,+ parentProjectionUserIds: undefined,+ }++ const response = await handler.fetch(await deliveryRequest(dmBatch), env as never)+ expect(response.status).toBe(200)+ const request = doMock.stubFetch.mock.calls[0]?.[0] as Request+ const body = await request.clone().json() as InternalBundleBody+ expect(body.events).toEqual([+ {+ type: "community:unread.bump",+ userId: "mention-only",+ channelId: "dm-1",+ isMention: true,+ },+ {+ type: "community:mention.create",+ userId: "mention-only",+ messageId: "message-1",+ channelId: "dm-1",+ authorName: "Alice",+ },+ ])})it("accepts only the operation ID derived from the committed message", async () => {diff --git a/src/ws-do/src/routes/message-delivery.ts b/src/ws-do/src/routes/message-delivery.tsindex f57a90acb..4e08f535a 100644--- a/src/ws-do/src/routes/message-delivery.ts+++ b/src/ws-do/src/routes/message-delivery.ts@@ -125,7 +125,24 @@ export async function handleMessageDelivery(isMention: true,})}+ const unreadMentionUsers = new Set(batch.unreadMentionUserIds)for (const userId of batch.mentionUserIds) {+ // Keep mention.create's production strict shape rollout-safe. A user who+ // only receives attention (for example through a visible forum parent)+ // first gets the existing scoped bump so both old and new clients decode+ // the batch and the new projection knows its server/rail scope.+ if (!unreadMentionUsers.has(userId)) {+ addEvent(bundles, userId, {+ type: WS_EVENTS.UNREAD_BUMP,+ userId,+ channelId: batch.messageEvent.channelId,+ ...(batch.messageEvent.serverId ? { serverId: batch.messageEvent.serverId } : {}),+ ...(batch.messageEvent.serverId+ ? { railChannelId: batch.messageEvent.parentChannelId ?? batch.messageEvent.channelId }+ : {}),+ isMention: true,+ })+ }addEvent(bundles, userId, {type: WS_EVENTS.MENTION_CREATE,userId,