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
feat(web): add actionable friend requests to inbox (#775)
Gener6f47caeedbbb
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjsindex 9f6053eb2..1fba41bcb 100644--- a/scripts/ci/e2e-shards.mjs+++ b/scripts/ci/e2e-shards.mjs@@ -77,6 +77,7 @@ export const SPEC_SECONDS = {"54-authenticated-context-menu-policy.spec.ts": 13.721,"54-blog-multizone.spec.ts": 5.485,"55-message-scroll-characterization.spec.ts": 109.548,+ "56-inbox-friend-requests.spec.ts": 60,"56-remote-image-state-contract.spec.ts": 3.122,"57-server-delete-navigation-races.spec.ts": 55,}diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.tsindex af28502cd..3f20cfdcc 100644--- a/scripts/ci/e2e-shards.test.ts+++ b/scripts/ci/e2e-shards.test.ts@@ -75,15 +75,17 @@ describe("planE2eShards", () => {expect(first).toEqual(second)expect(Object.keys(SPEC_SECONDS).sort()).toEqual(specs)- expect(first).toHaveLength(9)+ expect(first).toHaveLength(10)expect([...assigned].sort()).toEqual(specs)expect(new Set(assigned).size).toBe(specs.length)expect(SPEC_SECONDS["55-message-scroll-characterization.spec.ts"]).toBe(109.548)expect(specSeconds).toEqual([- 159.424, 161.016, 162.097, 159.838, 161.875, 161.643, 159.966, 161.68, 159.89,+ 150.249, 150.644, 151.022, 150.534, 151.049,+ 150.933, 150.119, 151.048, 150.765, 151.066,])expect(predictedSeconds).toEqual([- 234.424, 236.016, 237.097, 234.838, 236.875, 236.643, 234.966, 236.68, 234.89,+ 225.249, 225.644, 226.022, 225.534, 226.049,+ 225.933, 225.119, 226.048, 225.765, 226.066,])expect(first.every((shard) => (shard.fixed_setup_seconds === E2E_FIXED_SETUP_SECONDSdiff --git a/src/shared/src/db/queries/community/friendship.ts b/src/shared/src/db/queries/community/friendship.tsindex 820fdcf3f..1d50111eb 100644--- a/src/shared/src/db/queries/community/friendship.ts+++ b/src/shared/src/db/queries/community/friendship.ts@@ -1,4 +1,4 @@-import { eq, and, or, isNull, inArray } from "drizzle-orm";+import { eq, and, or, isNull, inArray, desc } from "drizzle-orm";import {communityFriendship,communityUserProfile,@@ -1043,6 +1043,33 @@ export async function listPending(db: Database, userId: string) {return merged;}+/**+ * Incoming friend requests the viewer can act on immediately. This is kept+ * separate from `listPending`: Inbox must not perform the own-bot lookup or+ * include outgoing and owner-gated rows from the Friends aggregate.+ */+export async function listActionableIncomingRequests(db: Database, userId: string) {+ return db+ .select({+ id: communityFriendship.id,+ userId: user.id,+ name: user.name,+ image: user.image,+ avatarVersion: user.avatarVersion,+ createdAt: communityFriendship.createdAt,+ })+ .from(communityFriendship)+ .innerJoin(user, eq(user.id, communityFriendship.requesterId))+ .where(+ and(+ eq(communityFriendship.addresseeId, userId),+ eq(communityFriendship.status, "pending"),+ isNull(communityFriendship.needsOwnerApproval)+ )+ )+ .orderBy(desc(communityFriendship.createdAt), desc(communityFriendship.id));+}+// ─── Owner decision (approve / deny) ─────────────────────────────────────────export type OwnerDecisionResult =diff --git a/src/shared/test/queries/community-friendship-actionable-incoming.test.ts b/src/shared/test/queries/community-friendship-actionable-incoming.test.tsnew file mode 100644index 000000000..1d5983340--- /dev/null+++ b/src/shared/test/queries/community-friendship-actionable-incoming.test.ts@@ -0,0 +1,91 @@+import Sqlite from "better-sqlite3"+import { drizzle } from "drizzle-orm/better-sqlite3"+import { afterEach, beforeEach, describe, expect, it } from "vitest"+import type { Database } from "../../src/db"+import { listActionableIncomingRequests } from "../../src/db/queries/community/friendship"++describe("listActionableIncomingRequests", () => {+ let sqlite: Sqlite.Database+ let db: Database++ beforeEach(() => {+ sqlite = new Sqlite(":memory:")+ sqlite.exec(`+ CREATE TABLE user (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ image TEXT,+ avatarVersion INTEGER NOT NULL DEFAULT 0+ );+ CREATE TABLE community_friendship (+ id TEXT PRIMARY KEY,+ requester_id TEXT NOT NULL,+ addressee_id TEXT NOT NULL,+ status TEXT NOT NULL,+ needs_owner_approval TEXT,+ blocker_id TEXT,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ resolved_at TEXT+ );+ `)+ sqlite.prepare("INSERT INTO user (id, name, image, avatarVersion) VALUES (?, ?, ?, ?)")+ .run("viewer", "Viewer", null, 0)+ for (const [id, name, version] of [+ ["newer", "Newer", 2],+ ["tie-z", "Tie Z", 3],+ ["tie-a", "Tie A", 4],+ ["outgoing", "Outgoing", 5],+ ["gated", "Gated", 6],+ ["terminal", "Terminal", 7],+ ] as const) {+ sqlite.prepare("INSERT INTO user (id, name, image, avatarVersion) VALUES (?, ?, ?, ?)")+ .run(id, name, null, version)+ }+ const insert = sqlite.prepare(`+ INSERT INTO community_friendship+ (id, requester_id, addressee_id, status, needs_owner_approval, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?)+ `)+ insert.run("fr_newer", "newer", "viewer", "pending", null, "2026-09-12T02:00:00Z", "2026-09-12T02:00:00Z")+ insert.run("fr_z", "tie-z", "viewer", "pending", null, "2026-09-12T01:00:00Z", "2026-09-12T01:00:00Z")+ insert.run("fr_a", "tie-a", "viewer", "pending", null, "2026-09-12T01:00:00Z", "2026-09-12T01:00:00Z")+ insert.run("fr_out", "viewer", "outgoing", "pending", null, "2026-09-12T03:00:00Z", "2026-09-12T03:00:00Z")+ insert.run("fr_gated", "gated", "viewer", "pending", "viewer", "2026-09-12T03:00:00Z", "2026-09-12T03:00:00Z")+ for (const status of ["accepted", "denied", "cancelled", "superseded", "blocked"]) {+ insert.run(`fr_${status}`, "terminal", "viewer", status, null, "2026-09-12T04:00:00Z", "2026-09-12T04:00:00Z")+ }+ db = drizzle(sqlite) as unknown as Database+ })++ afterEach(() => sqlite.close())++ it("returns only ungated incoming pending rows in deterministic newest-first order", async () => {+ await expect(listActionableIncomingRequests(db, "viewer")).resolves.toEqual([+ {+ id: "fr_newer",+ userId: "newer",+ name: "Newer",+ image: null,+ avatarVersion: 2,+ createdAt: "2026-09-12T02:00:00Z",+ },+ {+ id: "fr_z",+ userId: "tie-z",+ name: "Tie Z",+ image: null,+ avatarVersion: 3,+ createdAt: "2026-09-12T01:00:00Z",+ },+ {+ id: "fr_a",+ userId: "tie-a",+ name: "Tie A",+ image: null,+ avatarVersion: 4,+ createdAt: "2026-09-12T01:00:00Z",+ },+ ])+ })+})diff --git a/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts b/src/web/src/app/api/community/users/me/inbox/unreads/route.test.tsindex 2f7426e40..4bd457735 100644--- a/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts+++ b/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts@@ -7,6 +7,7 @@ const mockListThreadOpenersByChildIds = vi.fn()const mockListEligibleUnreadDms = vi.fn()const mockListVisibleChannelIds = vi.fn()const mockGetChannelsByIds = vi.fn()+const mockListActionableIncomingRequests = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),@@ -29,6 +30,9 @@ vi.mock("@alook/shared", async () => {listVisibleChannelIdsForUser: (...args: unknown[]) => mockListVisibleChannelIds(...args),getChannelsByIds: (...args: unknown[]) => mockGetChannelsByIds(...args),},+ communityFriendship: {+ listActionableIncomingRequests: (...args: unknown[]) => mockListActionableIncomingRequests(...args),+ },},}})@@ -115,6 +119,70 @@ describe("GET /api/community/users/me/inbox/unreads", () => {mockListThreadOpenersByChildIds.mockResolvedValue([])mockListVisibleChannelIds.mockResolvedValue([])mockGetChannelsByIds.mockResolvedValue([])+ mockListActionableIncomingRequests.mockResolvedValue([])+ })++ it("returns actionable friend requests without consuming the message limit", async () => {+ mockListEligibleUnreadChannels.mockResolvedValue([+ row({ channelId: "c1", lastMessageAt: "2026-06-25T12:00:00Z" }),+ row({ channelId: "c2", lastMessageAt: "2026-06-25T11:00:00Z" }),+ ])+ mockListActionableIncomingRequests.mockResolvedValue([+ {+ id: "fr_2",+ userId: "u2",+ name: "Ada",+ image: null,+ avatarVersion: 3,+ createdAt: "2026-06-25T13:00:00Z",+ },+ {+ id: "fr_1",+ userId: "u3",+ name: "Grace",+ image: null,+ avatarVersion: 4,+ createdAt: "2026-06-25T12:30:00Z",+ },+ ])++ const response = await GET(new NextRequest(+ "http://localhost/api/community/users/me/inbox/unreads?limit=1",+ ))+ const body = await response.json()++ expect(body.friendRequests).toEqual([+ expect.objectContaining({ id: "fr_2", userId: "u2", name: "Ada", avatarVersion: 3 }),+ expect.objectContaining({ id: "fr_1", userId: "u3", name: "Grace", avatarVersion: 4 }),+ ])+ expect(body.servers[0].channels).toHaveLength(1)+ expect(body.limit).toBe(1)+ expect(body.truncated).toBe(true)+ })++ it("fails closed with an explicit empty friend-request list on retry exhaustion", async () => {+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {})+ try {+ mockListActionableIncomingRequests.mockRejectedValue(+ new Error("D1_ERROR: database is locked"),+ )++ const response = await GET(new NextRequest(+ "http://localhost/api/community/users/me/inbox/unreads?limit=7",+ ))++ expect(response.status).toBe(200)+ expect(await response.json()).toEqual({+ friendRequests: [],+ servers: [],+ dms: [],+ limit: 7,+ truncated: false,+ stale: true,+ })+ } finally {+ logSpy.mockRestore()+ }})it("groups channels by server", async () => {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 c18604dd8..080912c7a 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@@ -28,13 +28,18 @@ export const GET = withAuth(async (req, ctx) => {type UnreadDmRow = Awaited<ReturnType<typeof queries.communityInbox.listEligibleUnreadDms>>[number]type ForumOpenerRow = Awaited<ReturnType<typeof queries.communityInbox.listUnreadForumOpeners>>[number]type ThreadOpenerRow = Awaited<ReturnType<typeof queries.communityInbox.listThreadOpenersByChildIds>>[number]+ type FriendRequestRow = Awaited<ReturnType<typeof queries.communityFriendship.listActionableIncomingRequests>>[number]const { value: fetched, stale } = await readOrStale<{unread: UnreadRow[]unreadDms: UnreadDmRow[]threadOpeners: Array<ThreadOpenerRow>+ friendRequests: FriendRequestRow[]}>(async () => {- const visibleChannelIds = await queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId)+ const [visibleChannelIds, friendRequests] = await Promise.all([+ queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId),+ queries.communityFriendship.listActionableIncomingRequests(db, ctx.userId),+ ])const [unread, unreadDms] = await Promise.all([queries.communityInbox.listEligibleUnreadChannels(db, ctx.userId, visibleChannelIds),queries.communityInbox.listEligibleUnreadDms(db, ctx.userId),@@ -88,15 +93,15 @@ export const GET = withAuth(async (req, ctx) => {row.type !== "forum" ||forumParentsWithUnread.has(row.channelId),)- return { unread: withoutPhantomForumParents, unreadDms, threadOpeners }+ return { unread: withoutPhantomForumParents, unreadDms, threadOpeners, friendRequests }},- { unread: [], unreadDms: [], threadOpeners: [] },+ { unread: [], unreadDms: [], threadOpeners: [], friendRequests: [] },{ route: "community/inbox/unreads" },)if (stale) {- return writeJSON({ servers: [], dms: [], limit, truncated: false, stale: true })+ return writeJSON({ friendRequests: [], servers: [], dms: [], limit, truncated: false, stale: true })}- const { unread, unreadDms, threadOpeners } = fetched+ const { unread, unreadDms, threadOpeners, friendRequests: friendRequestRows } = fetched// Split unread rows into top-level channels and child threads.// A child nests under its `parentChannelId`; a parent surfaces in the tree@@ -378,5 +383,18 @@ export const GET = withAuth(async (req, ctx) => {})).sort((a, b) => (a.lastMessageAt < b.lastMessageAt ? 1 : -1))- return writeJSON({ servers, dms, limit, truncated })+ const friendRequests = friendRequestRows.map((request) => ({+ id: request.id,+ userId: request.userId,+ name: request.name,+ avatar: canonicalUserImage(+ request.userId,+ request.image,+ request.avatarVersion,+ ) ?? avatarInitial(request.name),+ avatarVersion: request.avatarVersion,+ createdAt: request.createdAt,+ }))++ return writeJSON({ friendRequests, servers, dms, limit, truncated })})diff --git a/src/web/src/app/c/me/friends/page.tsx b/src/web/src/app/c/me/friends/page.tsxindex 07ecc79cc..dddaba1d1 100644--- a/src/web/src/app/c/me/friends/page.tsx+++ b/src/web/src/app/c/me/friends/page.tsx@@ -3,6 +3,7 @@import { useBreakpoint } from "@/hooks/use-mobile"import { FriendsPage } from "@/components/community/social/friends-page"import { useMemo } from "react"+import { useRouter, useSearchParams } from "next/navigation"import { useFriends } from "@/hooks/community/use-friends"import { useUiHandlers } from "@/stores/community"import { useCommunityWsStore } from "@/stores/community/ws"@@ -22,6 +23,9 @@ import { toastApiError } from "@/lib/api/client"export default function MeFriendsPage() {const bp = useBreakpoint()+ const router = useRouter()+ const searchParams = useSearchParams()+ const activeTab = searchParams.get("tab") === "new" ? "new" : "all"const { friends: rawFriends, pending, blocked, isLoading } = useFriends()const uiHandlers = useUiHandlers()const profilesByUserId = useCommunityWsStore((s) => s.profilesByUserId)@@ -59,22 +63,31 @@ export default function MeFriendsPage() {pending={pending}blocked={blocked}loading={isLoading}+ activeTab={activeTab}+ onActiveTabChange={(tab) => {+ router.replace(tab === "new" ? "/c/me/friends?tab=new" : "/c/me/friends")+ }}+ onOpenProfile={(name, event, discriminator, userId) => {+ uiHandlers.openProfile?.(name, event, discriminator, userId)+ }}onBack={bp === "mobile" ? () => uiHandlers.goBackMobile?.() : undefined}- onAccept={(id) =>- acceptFriendRequest.mutate(- { friendshipId: id },- {- onSuccess: () => toast("Friend request accepted"),- onError: (e) => toastApiError(e, "Failed to accept request"),- },- )- }- onReject={(id) =>- rejectFriendRequest.mutate(- { friendshipId: id },- { onError: (e) => toastApiError(e, "Failed to reject request") },- )- }+ onAccept={async (id) => {+ try {+ await acceptFriendRequest.mutateAsync({ friendshipId: id })+ toast("Friend request accepted")+ } catch (error) {+ toastApiError(error, "Failed to accept request")+ throw error+ }+ }}+ onReject={async (id) => {+ try {+ await rejectFriendRequest.mutateAsync({ friendshipId: id })+ } catch (error) {+ toastApiError(error, "Failed to reject request")+ throw error+ }+ }}onCancelRequest={({ id }) =>// Unified after migration 0065 — outgoing pendings (own or the owner's// bots') are real community_friendship rows cancelled via DELETE.diff --git a/src/web/src/app/c/me/layout.route-memory.dom.test.ts b/src/web/src/app/c/me/layout.route-memory.dom.test.tsindex b8abc5fba..683d33b66 100644--- a/src/web/src/app/c/me/layout.route-memory.dom.test.ts+++ b/src/web/src/app/c/me/layout.route-memory.dom.test.ts@@ -1,6 +1,9 @@import { createElement } from "react"+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"import { beforeEach, describe, expect, it, vi } from "vitest"-import { render } from "@/test/react-dom-harness"+import { act, render } from "@/test/react-dom-harness"+import { communityKeys } from "@/lib/query-keys"+import { getFriendRequestActionController } from "@/hooks/community/use-friend-request-action-state"const mocks = vi.hoisted(() => ({pathname: "/c/me/friends",@@ -13,6 +16,14 @@ const mocks = vi.hoisted(() => ({clearLastMeLocation: vi.fn(),commitLastCommunityRoute: vi.fn(),consumeColdEntryFailure: vi.fn(() => false),+ pending: [] as Array<{+ id: string+ userId: string+ name: string+ avatar: string+ avatarVersion: number+ kind: "incoming"+ }>,}))vi.mock("next/navigation", () => ({@@ -25,7 +36,13 @@ vi.mock("@/contexts/community/current-user", () => ({useCurrentUser: () => ({ id: "viewer-1" }),}))vi.mock("@/components/community/shell/shell-frame", () => ({- ShellFrame: ({ children }: { children: React.ReactNode }) => createElement("shell-frame", null, children),+ ShellFrame: ({+ children,+ sidebar,+ }: {+ children: React.ReactNode+ sidebar?: () => React.ReactNode+ }) => createElement("shell-frame", null, sidebar?.(), children),}))vi.mock("@/components/community/shell/community-pending-frame", () => ({CommunityPendingFrame: (props: Record<string, unknown>) => createElement("pending-frame", props),@@ -34,7 +51,13 @@ vi.mock("@/components/community/channels/dm-route-error-frame", () => ({DmRouteErrorFrame: (props: Record<string, unknown>) => createElement("error-frame", props),}))vi.mock("@/components/community/channels/dm-sidebar", () => ({- DmSidebar: () => null,+ DmSidebar: ({ friendRequestCount }: { friendRequestCount?: number }) => createElement(+ "output",+ {+ "data-testid": "dm-sidebar",+ "data-friend-request-count": friendRequestCount ?? 0,+ },+ ),}))vi.mock("@/stores/community", () => {const state = {@@ -54,7 +77,7 @@ vi.mock("@/hooks/community/use-dm-route-verification", () => ({useDmRouteVerification: () => ({ status: mocks.dmStatus, retry: vi.fn(), retrying: false }),}))vi.mock("@/hooks/community/use-friends", () => ({- useFriends: () => ({ blocked: [] }),+ useFriends: () => ({ blocked: [], pending: mocks.pending }),useFriendsPresence: vi.fn(),}))vi.mock("@/stores/community/ws", () => ({@@ -86,8 +109,12 @@ vi.mock("@/lib/community/last-community-route", () => ({import MeLayout from "./layout"-function renderLayout() {- return render(createElement(MeLayout, null, createElement("div")))+function renderLayout(queryClient = new QueryClient()) {+ return render(createElement(+ QueryClientProvider,+ { client: queryClient },+ createElement(MeLayout, null, createElement("div")),+ ))}describe("MeLayout route memory", () => {@@ -103,6 +130,7 @@ describe("MeLayout route memory", () => {mocks.commitLastCommunityRoute.mockClear()mocks.consumeColdEntryFailure.mockReset()mocks.consumeColdEntryFailure.mockReturnValue(false)+ mocks.pending = []})it("commits a verified Me leaf for the active account", () => {@@ -147,4 +175,51 @@ describe("MeLayout route memory", () => {renderLayout()expect(mocks.replace).toHaveBeenCalledWith("/c/me")})++ it("keeps the Friends shortcut count on the shared terminal projection through failed refreshes", async () => {+ const request = {+ id: "friendship-a",+ userId: "user-a",+ name: "A",+ avatar: "A",+ avatarVersion: 1,+ kind: "incoming" as const,+ }+ mocks.pending = [request]+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ queryClient.setQueryData(communityKeys.friends(), {+ friends: [],+ blocked: [],+ pending: [request],+ })+ queryClient.setQueryData(communityKeys.inboxUnreads(), {+ friendRequests: [{ ...request, createdAt: "2026-09-12T00:00:00.000Z" }],+ servers: [],+ dms: [],+ })+ getFriendRequestActionController(queryClient).publishTerminal(request.id)++ const rendered = renderLayout(queryClient)+ await act(async () => {+ await Promise.allSettled([+ queryClient.fetchQuery({+ queryKey: communityKeys.friends(),+ queryFn: async () => { throw new Error("friends refresh failed") },+ staleTime: 0,+ }),+ queryClient.fetchQuery({+ queryKey: communityKeys.inboxUnreads(),+ queryFn: async () => { throw new Error("inbox refresh failed") },+ staleTime: 0,+ }),+ ])+ })++ expect(rendered.getByTestId("dm-sidebar")).toHaveAttribute(+ "data-friend-request-count",+ "0",+ )+ })})diff --git a/src/web/src/app/c/me/layout.tsx b/src/web/src/app/c/me/layout.tsxindex df96cec86..b96efd381 100644--- a/src/web/src/app/c/me/layout.tsx+++ b/src/web/src/app/c/me/layout.tsx@@ -15,6 +15,8 @@ import { useCommunityStore, useCurrentChannelId } from "@/stores/community"import { useDms } from "@/hooks/community/use-dms"import { useDmRouteVerification } from "@/hooks/community/use-dm-route-verification"import { useFriends, useFriendsPresence } from "@/hooks/community/use-friends"+import { actionableIncomingRequests } from "@/lib/community/friend-requests"+import { useFriendRequestActionState } from "@/hooks/community/use-friend-request-action-state"import { useCommunityWsStore } from "@/stores/community/ws"import { readCommunityProfile } from "@/lib/community/profile-read"import { useCurrentUser } from "@/contexts/community/current-user"@@ -67,7 +69,15 @@ export default function MeLayout({ children }: { children: ReactNode }) {}),[profilesByUserId, rawDms],)- const { blocked } = useFriends()+ const { blocked, pending } = useFriends()+ const incomingFriendRequests = useMemo(+ () => actionableIncomingRequests(pending),+ [pending],+ )+ const friendRequestCount = useFriendRequestActionState({+ rows: incomingFriendRequests,+ surface: "friends",+ }).items.lengthconst currentChannelId = useCurrentChannelId()const cancelPendingNavigation = useCallback(() => {useCommunityStore.getState().uiHandlers.cancelPendingNavigation?.()@@ -149,6 +159,7 @@ export default function MeLayout({ children }: { children: ReactNode }) {onPickDm={enterDm}onPrefetchDm={prefetchDm}onShowFriends={onShowFriends}+ friendRequestCount={friendRequestCount}onPrefetchFriends={prefetchFriends}onShowMachines={onShowMachines}onPrefetchMachines={prefetchMachines}@@ -158,7 +169,7 @@ export default function MeLayout({ children }: { children: ReactNode }) {machinesActive={machinesActive}botsActive={botsActive}/>- ), [dms, currentChannelId, dmsLoading, blockedUserIds, enterDm, prefetchDm, onShowFriends, prefetchFriends, onShowMachines, prefetchMachines, onShowBots, prefetchBots, friendsActive, machinesActive, botsActive])+ ), [dms, currentChannelId, dmsLoading, blockedUserIds, enterDm, prefetchDm, onShowFriends, friendRequestCount, prefetchFriends, onShowMachines, prefetchMachines, onShowBots, prefetchBots, friendsActive, machinesActive, botsActive])return (<ShellFramediff --git a/src/web/src/components/community/channels/dm-sidebar.prefetch.dom.test.ts b/src/web/src/components/community/channels/dm-sidebar.prefetch.dom.test.tsindex 1dee39a1d..6e2fe19fb 100644--- a/src/web/src/components/community/channels/dm-sidebar.prefetch.dom.test.ts+++ b/src/web/src/components/community/channels/dm-sidebar.prefetch.dom.test.ts@@ -5,6 +5,26 @@ import { fireEvent, render } from "@/test/react-dom-harness"import { DmSidebar, DmSidebarSkeleton } from "./dm-sidebar"describe("DmSidebar navigation intent", () => {+ it.each([+ [0, null],+ [1, "1"],+ [99, "99"],+ [100, "99+"],+ ] as const)("renders the Friends request badge for %i as %s", (count, label) => {+ const renderer = render(createElement(DmSidebar, {+ dms: [],+ activeDm: null,+ friendRequestCount: count,+ onPickDm: vi.fn(),+ onShowFriends: vi.fn(),+ }))+ const badge = renderer.queryByTestId(tid.friendsShortcutBadge)+ if (label === null) expect(badge).toBeNull()+ else expect(badge).toHaveTextContent(label)+ expect(renderer.getByRole("button", { name: count ? `Friends, ${count} new requests` : "Friends" }))+ .toBeInTheDocument()+ })+it("keeps the pending DM sidebar inert and accessible", () => {const renderer = render(createElement(DmSidebarSkeleton))const aside = renderer.getByTestId(tid.dmSidebarPending)diff --git a/src/web/src/components/community/channels/dm-sidebar.tsx b/src/web/src/components/community/channels/dm-sidebar.tsxindex 17f3fb599..8c2ede348 100644--- a/src/web/src/components/community/channels/dm-sidebar.tsx+++ b/src/web/src/components/community/channels/dm-sidebar.tsx@@ -7,11 +7,13 @@ import { Skeleton } from "@/components/ui/skeleton"import { tid } from "@/lib/community/testids"import type { DM } from "@/lib/community/models/people"import { selectUnreadPresentation } from "@/hooks/community/unread-presentation"+import { compactRequestCount } from "@/lib/community/friend-requests"export const DmSidebar = memo(function DmSidebar({dms, activeDm, blockedUserIds, loading, onPickDm, onShowFriends, onShowMachines, onShowBots,onPrefetchDm, onPrefetchFriends, onPrefetchMachines, onPrefetchBots,friendsActive, machinesActive, botsActive,+ friendRequestCount = 0,}: {dms: DM[]activeDm: string | null@@ -26,14 +28,17 @@ export const DmSidebar = memo(function DmSidebar({onShowBots?: () => voidonPrefetchBots?: () => voidfriendsActive?: boolean+ friendRequestCount?: numbermachinesActive?: booleanbotsActive?: boolean}) {const isFriendsActive = friendsActive ?? (activeDm === null && !machinesActive && !botsActive)+ const requestCount = compactRequestCount(friendRequestCount)return (<aside className="flex min-h-0 min-w-0 flex-1 flex-col"><div data-slot="dm-sidebar-shortcuts" className="shrink-0 px-2 pt-4"><button+ aria-label={requestCount ? `Friends, ${friendRequestCount} new requests` : "Friends"}onClick={onShowFriends}onPointerEnter={onPrefetchFriends}onFocus={onPrefetchFriends}@@ -43,6 +48,14 @@ export const DmSidebar = memo(function DmSidebar({].join(" ")}><Users className="size-5" /> Friends+ {requestCount && (+ <span+ data-testid={tid.friendsShortcutBadge}+ className="ml-auto grid h-5 min-w-5 place-items-center rounded-full bg-primary px-1 text-xs font-semibold text-primary-foreground"+ >+ {requestCount}+ </span>+ )}</button>{onShowMachines && (<buttondiff --git a/src/web/src/components/community/shell/community-friend-pending-provider-order.test.ts b/src/web/src/components/community/shell/community-friend-pending-provider-order.test.tsnew file mode 100644index 000000000..63942325e--- /dev/null+++ b/src/web/src/components/community/shell/community-friend-pending-provider-order.test.ts@@ -0,0 +1,59 @@+import { createElement, type ReactNode } from "react"+import { renderToStaticMarkup } from "react-dom/server"+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"+import { describe, expect, it, vi } from "vitest"++vi.mock("@/components/community/billing/billing-plan.module.css", () => ({+ default: new Proxy({}, { get: (_target, key) => String(key) }),+}))+vi.mock("@/components/community/shell/community-shell-layout", () => ({+ CommunityShellLayout: ({ main }: { main: ReactNode }) => main,+}))++import FriendsLoading from "@/app/c/me/friends/loading"+import { CommunityPendingFrame } from "./community-pending-frame"+import { CommunitySessionPendingFrame } from "./community-session-pending-frame"++function prerender(node: ReactNode, withQueryProvider: boolean) {+ const tree = withQueryProvider+ ? createElement(+ QueryClientProvider,+ { client: new QueryClient() },+ node,+ )+ : node++ return renderToStaticMarkup(tree)+}++describe("friends pending QueryClient provider order", () => {+ it.each([+ {+ name: "the pre-auth community session frame",+ render: () => createElement(CommunitySessionPendingFrame, {+ pathname: "/c/me/friends",+ }),+ withQueryProvider: false,+ },+ {+ name: "the friends route loading boundary",+ render: () => createElement(FriendsLoading),+ withQueryProvider: false,+ },+ {+ name: "the authenticated shared pending frame",+ render: () => createElement(CommunityPendingFrame, {+ href: "/c/me/friends",+ }),+ withQueryProvider: true,+ },+ ])("prerenders $name without requiring a misplaced provider", ({+ render,+ withQueryProvider,+ }) => {+ const html = prerender(render(), withQueryProvider)++ expect(html).toContain('aria-label="Loading friends"')+ expect(html).toContain('data-testid="community-pending-main-friends"')+ })+})diff --git a/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts b/src/web/src/components/community/shell/community-inbox-popover.dom.test.tsindex ef9a955bf..28b77e00e 100644--- a/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts+++ b/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts@@ -212,6 +212,111 @@ describe("InboxPopover thread opener rows", () => {})})+describe("InboxPopover friend requests", () => {+ const friendRequest = {+ row: {+ id: "fr_1",+ userId: "u_friend",+ name: "Ada",+ avatar: "A",+ avatarVersion: 1,+ createdAt: "2026-09-12T01:00:00Z",+ },+ }++ it("renders requests before DMs and servers with sibling navigation/actions", () => {+ const onOpenFriendRequests = vi.fn()+ const onAcceptFriendRequest = vi.fn()+ const renderer = render(React.createElement(InboxPopover, {+ friendRequests: [friendRequest],+ unreads: unreadFixture(),+ unreadDms: [{+ channelId: "dm1",+ otherUserId: "u2",+ otherUserName: "Grace",+ otherUserDiscriminator: "0001",+ otherUserAvatar: "G",+ otherUserAvatarVersion: 1,+ lastMessageAt: "2026-09-12T00:00:00Z",+ }],+ mentions: [],+ marked: [],+ hasProjectedUnreads: true,+ hasProjectedMentions: false,+ onOpenFriendRequests,+ onAcceptFriendRequest,+ onOpenThread: vi.fn(),+ }))+ const text = renderer.container.textContent ?? ""+ expect(text.indexOf("Friend requests — 1")).toBeLessThan(text.indexOf("Direct Messages"))+ expect(text.indexOf("Direct Messages")).toBeLessThan(text.indexOf("Server"))++ const open = renderer.getByTestId(tid.inboxFriendRequestOpen("fr_1"))+ const accept = renderer.getByTestId(tid.inboxFriendRequestAccept("fr_1"))+ expect(open.contains(accept)).toBe(false)+ fireEvent.click(accept)+ expect(onAcceptFriendRequest).toHaveBeenCalledWith(friendRequest)+ expect(onOpenFriendRequests).not.toHaveBeenCalled()+ fireEvent.click(open)+ expect(onOpenFriendRequests).toHaveBeenCalledTimes(1)+ })++ it("keeps request-only state out of Caught up while Mark all stays disabled", () => {+ const renderer = render(React.createElement(InboxPopover, {+ friendRequests: [friendRequest],+ unreads: [],+ unreadDms: [],+ mentions: [],+ marked: [],+ hasProjectedUnreads: false,+ hasProjectedMentions: false,+ onMarkAllRead: vi.fn(),+ }))+ expect(renderer.queryByText("Caught up")).toBeNull()+ expect(renderer.getByRole("button", { name: "Mark all read" })).toBeDisabled()+ })++ it("renders a pending tombstone and an accessible retryable error", () => {+ const onRetryFriendRequest = vi.fn()+ const renderer = render(React.createElement(InboxPopover, {+ friendRequests: [{+ ...friendRequest,+ action: "accept",+ status: "error",+ error: "Couldn’t accept this request. Try again.",+ }],+ unreads: [],+ unreadDms: [],+ mentions: [],+ marked: [],+ hasProjectedUnreads: false,+ hasProjectedMentions: false,+ onRetryFriendRequest,+ }))+ expect(renderer.getByRole("status").textContent).toContain("Couldn’t accept")+ fireEvent.click(renderer.getByRole("button", { name: "Retry" }))+ expect(onRetryFriendRequest).toHaveBeenCalledTimes(1)+ })++ it("announces row-local pending state and locks only that request", () => {+ const renderer = render(React.createElement(InboxPopover, {+ friendRequests: [{ ...friendRequest, action: "accept", status: "pending" }],+ unreads: [],+ unreadDms: [],+ mentions: [],+ marked: [],+ hasProjectedUnreads: false,+ hasProjectedMentions: false,+ }))+ expect(renderer.getByTestId(tid.inboxFriendRequest("fr_1"))).toHaveAttribute(+ "aria-busy",+ "true",+ )+ expect(renderer.getByTestId(tid.inboxFriendRequestAccept("fr_1"))).toBeDisabled()+ expect(renderer.getByTestId(tid.inboxFriendRequestReject("fr_1"))).toBeDisabled()+ })+})+describe("InboxPopover DM rows", () => {it("passes the complete DM summary to the open callback", () => {const dm: UnreadDm = {diff --git a/src/web/src/components/community/shell/community-inbox-popover.tsx b/src/web/src/components/community/shell/community-inbox-popover.tsxindex 1e41f47f3..053d05cec 100644--- a/src/web/src/components/community/shell/community-inbox-popover.tsx+++ b/src/web/src/components/community/shell/community-inbox-popover.tsx@@ -1,14 +1,16 @@-import { Bookmark, ChevronRight, Inbox, MoreHorizontal, Trash2 } from "lucide-react"+import { Bookmark, Check, ChevronRight, Inbox, LoaderCircle, MoreHorizontal, Trash2, X } from "lucide-react"import { stripInlineMarkup } from "@alook/shared"import { EntityIcon } from "../entity-icon"import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"import { Skeleton } from "@/components/ui/skeleton"+import { Button } from "@/components/ui/button"import { Avatar } from "../avatar"import { ChannelIcon } from "../channels/channel-icon"import { EmptyState } from "../empty-state"import { formatRelativeTime } from "@/lib/community/format-time"-import type { Marked, Mention, UnreadDm, UnreadServer } from "@/lib/community/models/inbox"+import type { InboxFriendRequest, Marked, Mention, UnreadDm, UnreadServer } from "@/lib/community/models/inbox"+import type { ActionableFriendRequest } from "@/hooks/community/use-friend-request-action-state"import {inboxChannelRowTarget,inboxDmRowTarget,@@ -116,10 +118,15 @@ function MentionBadge({ count }: { count: number }) {)}-function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenThread, onOpenDm, isProjected, profilesByUserId, getScrollOffset, onScrollOffsetChange }: {+function UnreadsTab({ friendRequests, servers, dms, loading, onOpenFriendRequests, onAcceptFriendRequest, onRejectFriendRequest, onRetryFriendRequest, onOpenChannel, onOpenThread, onOpenDm, isProjected, profilesByUserId, getScrollOffset, onScrollOffsetChange }: {+ friendRequests: Array<ActionableFriendRequest<InboxFriendRequest>>servers: UnreadServer[]dms: UnreadDm[]loading?: boolean+ onOpenFriendRequests?: () => void+ onAcceptFriendRequest?: (request: ActionableFriendRequest<InboxFriendRequest>) => void+ onRejectFriendRequest?: (request: ActionableFriendRequest<InboxFriendRequest>) => void+ onRetryFriendRequest?: (request: ActionableFriendRequest<InboxFriendRequest>) => voidonOpenChannel?: (server: UnreadServer,channel: UnreadChannel,@@ -146,11 +153,82 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenThread, onOpen}}).filter((group) => group.directVisible || group.children.length > 0),})).filter((group) => group.channels.length > 0)- const nothingUnread = visibleServers.length === 0 && visibleDms.length === 0+ const nothingUnread = friendRequests.length === 0 && visibleServers.length === 0 && visibleDms.length === 0return (<InboxScrollBody tab="unreads" getScrollOffset={getScrollOffset} onScrollOffsetChange={onScrollOffsetChange}>{loading && nothingUnread && <InboxUnreadsSkeleton />}{!loading && nothingUnread && <EmptyState icon={Inbox} label="Caught up" />}+ {friendRequests.length > 0 && (+ <div className="mb-3">+ <div className="px-2 pb-1 text-xs font-semibold text-muted-foreground">+ Friend requests — {friendRequests.length}+ </div>+ {friendRequests.map((item) => {+ const request = item.row+ const profile = readCommunityProfile(+ profilesByUserId.get(request.userId),+ request.userId,+ )+ const pending = item.status === "pending"+ return (+ <div+ key={request.id}+ data-testid={tid.inboxFriendRequest(request.id)}+ aria-busy={pending || undefined}+ className="rounded-md px-2 py-2 hover:bg-accent"+ >+ <div className="flex items-center gap-2">+ <button+ data-testid={tid.inboxFriendRequestOpen(request.id)}+ onClick={onOpenFriendRequests}+ className="flex min-h-11 min-w-0 flex-1 items-center gap-2 rounded-md text-left text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring sm:min-h-0"+ >+ <Avatar label={profile.avatar} seed={request.userId} size={28} />+ <span className="min-w-0 flex-1">+ <span className="block truncate font-medium">{profile.name}</span>+ <span className="block truncate text-xs text-muted-foreground">sent you a friend request</span>+ </span>+ </button>+ <div className="flex shrink-0 gap-1">+ <Button+ data-testid={tid.inboxFriendRequestAccept(request.id)}+ variant="secondary"+ size="icon"+ disabled={pending}+ onClick={() => onAcceptFriendRequest?.(item)}+ aria-label={`Accept ${profile.name}'s friend request`}+ className="size-11 rounded-full text-status-online sm:size-8"+ >+ {pending && item.action === "accept"+ ? <LoaderCircle className="size-4 animate-spin" />+ : <Check className="size-4" />}+ </Button>+ <Button+ data-testid={tid.inboxFriendRequestReject(request.id)}+ variant="secondary"+ size="icon"+ disabled={pending}+ onClick={() => onRejectFriendRequest?.(item)}+ aria-label={`Reject ${profile.name}'s friend request`}+ className="size-11 rounded-full text-destructive sm:size-8"+ >+ {pending && item.action === "reject"+ ? <LoaderCircle className="size-4 animate-spin" />+ : <X className="size-4" />}+ </Button>+ </div>+ </div>+ {item.error && (+ <div role="status" aria-live="polite" className="mt-1 flex items-center justify-end gap-2 text-xs text-destructive">+ <span>{item.error}</span>+ <button className="min-h-11 min-w-11 font-medium underline sm:min-h-0 sm:min-w-0" onClick={() => onRetryFriendRequest?.(item)}>Retry</button>+ </div>+ )}+ </div>+ )+ })}+ </div>+ )}{visibleDms.length > 0 && (<div className="mb-3"><div className="px-2 pb-1 text-xs font-semibold text-muted-foreground">Direct Messages</div>@@ -323,6 +401,7 @@ function MarkedTab({ marked, loading, onOpenMarked, onUnmark, profilesByUserId,}export function InboxPopover({+ friendRequests = [],unreads,unreadDms,mentions,@@ -331,6 +410,11 @@ export function InboxPopover({loading,hasProjectedUnreads,hasProjectedMentions,+ hasOutstandingFriendRequest = friendRequests.length > 0,+ onOpenFriendRequests,+ onAcceptFriendRequest,+ onRejectFriendRequest,+ onRetryFriendRequest,onOpenChannel,onOpenThread,onOpenForumThread,@@ -348,6 +432,7 @@ export function InboxPopover({onScrollOffsetChange,surface = "desktop",}: {+ friendRequests?: Array<ActionableFriendRequest<InboxFriendRequest>>unreads: UnreadServer[]unreadDms: UnreadDm[]mentions: Mention[]@@ -356,6 +441,11 @@ export function InboxPopover({loading?: booleanhasProjectedUnreads: booleanhasProjectedMentions: boolean+ hasOutstandingFriendRequest?: boolean+ onOpenFriendRequests?: () => void+ onAcceptFriendRequest?: (request: ActionableFriendRequest<InboxFriendRequest>) => void+ onRejectFriendRequest?: (request: ActionableFriendRequest<InboxFriendRequest>) => void+ onRetryFriendRequest?: (request: ActionableFriendRequest<InboxFriendRequest>) => voidonOpenChannel?: (server: UnreadServer,channel: UnreadChannel,@@ -388,12 +478,12 @@ export function InboxPopover({const hasUnreads = hasProjectedUnreadsconst hasMentions = hasProjectedMentionsconst showUnreadDot = selectUnreadPresentation({- accountUnread: hasUnreads,+ accountUnread: hasUnreads || hasOutstandingFriendRequest,}).showDotconst showMentionDot = selectUnreadPresentation({accountUnread: hasMentions,}).showDot- const hasAnything = hasUnreads || hasMentions+ const hasMessageUnread = hasUnreads || hasMentionsreturn (<TabsdefaultValue="unreads"@@ -411,7 +501,7 @@ export function InboxPopover({{onMarkAllRead && (<buttononClick={onMarkAllRead}- disabled={!hasAnything}+ disabled={!hasMessageUnread}className="text-xs text-primary hover:underline disabled:cursor-not-allowed disabled:text-muted-foreground disabled:no-underline">Mark all read@@ -435,9 +525,14 @@ export function InboxPopover({</TabsList><TabsContent value="unreads" className="min-h-0 flex-1"><UnreadsTab+ friendRequests={friendRequests}servers={unreads}dms={unreadDms}loading={loading}+ onOpenFriendRequests={onOpenFriendRequests}+ onAcceptFriendRequest={onAcceptFriendRequest}+ onRejectFriendRequest={onRejectFriendRequest}+ onRetryFriendRequest={onRetryFriendRequest}onOpenChannel={onOpenChannel}onOpenThread={onOpenThread ?? onOpenForumThread ?? (() => {})}onOpenDm={onOpenDm}diff --git a/src/web/src/components/community/shell/community-pending-frame.dom.test.ts b/src/web/src/components/community/shell/community-pending-frame.dom.test.tsindex 312d80617..2dd85a636 100644--- a/src/web/src/components/community/shell/community-pending-frame.dom.test.ts+++ b/src/web/src/components/community/shell/community-pending-frame.dom.test.ts@@ -14,10 +14,10 @@ vi.mock("@/components/community/bots/bot-list-view", () => ({"data-reserve-back-slot": String(Boolean(reserveBackSlot)),}),}))-vi.mock("@/components/community/social/friends-page", () => ({- FriendsPage: (props: Record<string, unknown>) => createElement("div", {+vi.mock("@/components/community/social/friends-page-skeleton", () => ({+ FriendsPageSkeleton: ({ reserveBackSlot }: { reserveBackSlot?: boolean }) => createElement("div", {"data-testid": "friends-skeleton",- "data-props": JSON.stringify(props),+ "data-reserve-back-slot": String(Boolean(reserveBackSlot)),}),}))vi.mock("@/components/community/channels/dm-loading-frame", () => ({@@ -86,13 +86,8 @@ describe("CommunityPendingFrame", () => {rendered.unmount()renderFrame("/c/me/friends#new")- expect(JSON.parse(screen.getByTestId("friends-skeleton").dataset.props!)).toMatchObject({- friends: [],- pending: [],- blocked: [],- loading: true,- reserveBackSlot: true,- })+ expect(screen.getByTestId("friends-skeleton"))+ .toHaveAttribute("data-reserve-back-slot", "true")})it("separates neutral Me from DM and channel mobile Back geometry", () => {diff --git a/src/web/src/components/community/shell/community-pending-frame.tsx b/src/web/src/components/community/shell/community-pending-frame.tsxindex 5f6e92beb..233baf08b 100644--- a/src/web/src/components/community/shell/community-pending-frame.tsx+++ b/src/web/src/components/community/shell/community-pending-frame.tsx@@ -5,7 +5,7 @@ import { BotListSkeleton } from "@/components/community/bots/bot-list-view"import { ConversationResolutionPendingFrame } from "@/components/community/channels/conversation-resolution-pending-frame"import { DmLoadingFrame } from "@/components/community/channels/dm-loading-frame"import { MachineListSkeleton } from "@/components/community/machines/machine-list"-import { FriendsPage } from "@/components/community/social/friends-page"+import { FriendsPageSkeleton } from "@/components/community/social/friends-page-skeleton"import { ServerLandingPendingFrame } from "./server-landing-pending-frame"import { UnresolvedMainSkeleton } from "./unresolved-main-skeleton"import {@@ -59,15 +59,7 @@ export function CommunityPendingFrame({content = <BotListSkeleton reserveBackSlot={reserveMeBackSlot} />breakcase "friends":- content = (- <FriendsPage- friends={[]}- pending={[]}- blocked={[]}- loading- reserveBackSlot={reserveMeBackSlot}- />- )+ content = <FriendsPageSkeleton reserveBackSlot={reserveMeBackSlot} />breakcase "dm":content = <DmLoadingFrame reserveBackSlot={reserveMeBackSlot} />diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.tsindex b5a3258a9..c33c776dc 100644--- a/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts@@ -1,4 +1,5 @@import { createElement } from "react"+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"import { act, render as rtlRender } from "@/test/react-dom-harness"import { beforeEach, describe, expect, it, vi } from "vitest"import type { DmCache } from "@/lib/community/dm-cache"@@ -11,6 +12,8 @@ const mocks = vi.hoisted(() => ({markAll: vi.fn(),deleteMention: vi.fn(),unmark: vi.fn(),+ accept: vi.fn(),+ reject: vi.fn(),verifyDm: vi.fn(),armOpener: vi.fn(),clearOpener: vi.fn(),@@ -66,8 +69,22 @@ const mention: Mention = {}vi.mock("@/hooks/community/use-inbox", () => ({- useInboxUnreads: () => ({ servers: [server], dms: [unreadDm], isLoading: false }),- useInboxMentions: () => ({ mentions: [mention], isLoading: false }),+ useInboxUnreads: () => ({+ friendRequests: [{+ id: "fr_1",+ userId: "requester",+ name: "Ada",+ avatar: "A",+ avatarVersion: 1,+ createdAt: "2026-09-12T01:00:00Z",+ }],+ servers: [server],+ dms: [unreadDm],+ isLoading: false,+ hasProjectedUnread: false,+ hasOutstandingFriendRequest: true,+ }),+ useInboxMentions: () => ({ mentions: [mention], isLoading: false, hasProjectedMention: false }),useInboxMarked: (enabled: boolean) => {mocks.markedEnabled.push(enabled)return { marked: [], isLoading: false }@@ -89,6 +106,8 @@ vi.mock("@/hooks/community/mutations", () => ({useMarkAllInboxRead: () => ({ mutate: mocks.markAll }),useDeleteMention: () => ({ mutate: mocks.deleteMention }),useUnmarkMessage: () => ({ mutate: mocks.unmark }),+ useAcceptFriendRequest: () => ({ mutateAsync: mocks.accept }),+ useRejectFriendRequest: () => ({ mutateAsync: mocks.reject }),}))vi.mock("@/hooks/community/use-dm-route-verification", () => ({startDmRouteVerification: (...args: unknown[]) => mocks.verifyDm(...args),@@ -144,18 +163,23 @@ async function renderController(}const cancelPendingNavigation = vi.fn(() => { order.push("cancel") })let current!: Result+ const actionQueryClient = new QueryClient()await act(async () => {- rtlRender(createElement(Capture, {- options: {- router,- queryClient,- cancelPendingNavigation,- publishedHref: "/c/channels/s1",- navigationPending: false,- pendingHref: null,- } as never,- onResult: (result) => { current = result },- }))+ rtlRender(createElement(+ QueryClientProvider,+ { client: actionQueryClient },+ createElement(Capture, {+ options: {+ router,+ queryClient,+ cancelPendingNavigation,+ publishedHref: "/c/channels/s1",+ navigationPending: false,+ pendingHref: null,+ } as never,+ onResult: (result) => { current = result },+ }),+ ))})return {get current() { return current },@@ -173,6 +197,8 @@ describe("useShellInboxController", () => {mocks.markAll,mocks.deleteMention,mocks.unmark,+ mocks.accept,+ mocks.reject,mocks.verifyDm,mocks.armOpener,mocks.clearOpener,@@ -208,6 +234,52 @@ describe("useShellInboxController", () => {return Promise.resolve("present")})mocks.warmup.mockReturnValue(99)+ mocks.accept.mockResolvedValue(undefined)+ mocks.reject.mockResolvedValue(undefined)+ })++ it("includes friend requests in the global dot while keeping navigation and actions read-neutral", async () => {+ const hook = await renderController()+ expect(hook.current.hasUnread).toBe(true)+ expect(hook.current.popoverProps.hasProjectedUnreads).toBe(false)+ expect(hook.current.popoverProps.friendRequests).toHaveLength(1)++ hook.current.popoverProps.onOpenFriendRequests?.()+ expect(hook.pushed).toEqual(["/c/me/friends?tab=new"])+ expect(mocks.begin).not.toHaveBeenCalled()++ const item = hook.current.popoverProps.friendRequests?.[0]+ expect(item).toBeDefined()+ await act(async () => hook.current.popoverProps.onAcceptFriendRequest?.(item!))+ expect(mocks.accept).toHaveBeenCalledWith({ friendshipId: "fr_1" })+ expect(mocks.reject).not.toHaveBeenCalled()+ })++ it("routes a rejected request through its keyed retry", async () => {+ mocks.reject+ .mockRejectedValueOnce(new Error("offline"))+ .mockResolvedValueOnce(undefined)+ const hook = await renderController()+ const item = hook.current.popoverProps.friendRequests?.[0]+ expect(item).toBeDefined()++ await act(async () => hook.current.popoverProps.onRejectFriendRequest?.(item!))+ const failed = hook.current.popoverProps.friendRequests?.[0]+ expect(failed).toMatchObject({ action: "reject", status: "error" })+ await act(async () => hook.current.popoverProps.onRetryFriendRequest?.(failed!))++ expect(mocks.reject).toHaveBeenCalledTimes(2)+ expect(mocks.reject).toHaveBeenNthCalledWith(1, { friendshipId: "fr_1" })+ expect(mocks.reject).toHaveBeenNthCalledWith(2, { friendshipId: "fr_1" })+ })++ it("reopens Inbox when friend-request navigation throws", async () => {+ const hook = await renderController(undefined, () => { throw new Error("push failed") })+ order.length = 0++ expect(() => hook.current.popoverProps.onOpenFriendRequests?.()).toThrow("push failed")+ expect(order).toEqual(["close", "cancel", "push", "cancel", "reopen"])+ expect(mocks.onOpenChange).toHaveBeenCalledWith(true)})it("keeps Marked lazy and latches it after first selection", async () => {diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.tsindex 0e661279a..e171633ee 100644--- a/src/web/src/components/community/shell/use-shell-inbox-controller.ts+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.ts@@ -18,9 +18,12 @@ import {} from "@/hooks/community/inbox-read-reservation"import {useMarkAllInboxRead,+ useAcceptFriendRequest,+ useRejectFriendRequest,useDeleteMention,useUnmarkMessage,} from "@/hooks/community/mutations"+import { useFriendRequestActionState } from "@/hooks/community/use-friend-request-action-state"import type { InboxPopover } from "./community-inbox-popover"import type { InboxTab } from "./community-inbox-popover"import type { QueryClient } from "@tanstack/react-query"@@ -78,6 +81,8 @@ export function useShellInboxController({const { mutate: unmarkMessageMutate } = useUnmarkMessage()const markAllInboxRead = useMarkAllInboxRead()const deleteMention = useDeleteMention()+ const acceptFriendRequest = useAcceptFriendRequest()+ const rejectFriendRequest = useRejectFriendRequest()const inbox = useInboxAutoCollapse({queryClient,publishedHref,@@ -94,6 +99,20 @@ export function useShellInboxController({const setScrollOffset = useCallback((tab: InboxTab, scrollTop: number) => {scrollOffsetsRef.current[tab] = scrollTop}, [])+ const acceptRequest = useCallback(+ (friendshipId: string) => acceptFriendRequest.mutateAsync({ friendshipId }),+ [acceptFriendRequest],+ )+ const rejectRequest = useCallback(+ (friendshipId: string) => rejectFriendRequest.mutateAsync({ friendshipId }),+ [rejectFriendRequest],+ )+ const friendRequestActions = useFriendRequestActionState({+ rows: inboxUnreads.friendRequests,+ onAccept: acceptRequest,+ onReject: rejectRequest,+ surface: "inbox",+ })const pushProjected = useCallback((target: InboxRowTarget,@@ -257,7 +276,20 @@ export function useShellInboxController({})}, [pushProjected])+ const openFriendRequests = useCallback(() => {+ const previousOpen = inbox.closeWithoutProjection()+ cancelPendingNavigation()+ try {+ pushInboxHref("/c/me/friends?tab=new")+ } catch (error) {+ cancelPendingNavigation()+ inbox.onOpenChange(previousOpen)+ throw error+ }+ }, [cancelPendingNavigation, inbox, pushInboxHref])+const popoverProps: ComponentProps<typeof InboxPopover> = {+ friendRequests: friendRequestActions.items,unreads: unreadFeed,unreadDms,mentions,@@ -271,6 +303,10 @@ export function useShellInboxController({onOpenDm: openDm,onOpenMention: openMention,onOpenMarked: openMarked,+ onOpenFriendRequests: openFriendRequests,+ onAcceptFriendRequest: (item) => { void friendRequestActions.act(item, "accept") },+ onRejectFriendRequest: (item) => { void friendRequestActions.act(item, "reject") },+ onRetryFriendRequest: (item) => { void friendRequestActions.retry(item) },activeTab,onActiveTabChange: changeActiveTab,onMarkedTabSelected: () => setMarkedTabOpened(true),@@ -285,7 +321,9 @@ export function useShellInboxController({return {popoverProps,hasUnread:- inboxUnreads.hasProjectedUnread || inboxMentions.hasProjectedMention,+ inboxUnreads.hasProjectedUnread+ || inboxMentions.hasProjectedMention+ || friendRequestActions.items.length > 0,open: inbox.open,onOpenChange: inbox.onOpenChange,}diff --git a/src/web/src/components/community/social/friends-page-skeleton.tsx b/src/web/src/components/community/social/friends-page-skeleton.tsxnew file mode 100644index 000000000..46abbfd88--- /dev/null+++ b/src/web/src/components/community/social/friends-page-skeleton.tsx@@ -0,0 +1,64 @@+import { Skeleton } from "@/components/ui/skeleton"++export function FriendsPageSkeleton({+ reserveBackSlot = false,+}: {+ reserveBackSlot?: boolean+}) {+ return (+ <div+ aria-busy="true"+ aria-label="Loading friends"+ className="flex min-h-0 min-w-0 flex-1 flex-col gap-2"+ >+ <header className="flex h-12 shrink-0 items-center gap-2 border-b border-border/40 px-4">+ {reserveBackSlot && (+ <Skeleton data-slot="loading-back-placeholder" aria-hidden className="size-8 shrink-0 rounded-md" />+ )}+ <div aria-hidden className="inline-flex h-8 items-center gap-1 p-0.75 text-muted-foreground">+ <span className="inline-flex h-[calc(100%-1px)] items-center px-2 py-1 text-sm font-medium">All</span>+ <span className="inline-flex h-[calc(100%-1px)] items-center px-2 py-1 text-sm font-medium">New</span>+ </div>+ </header>+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto thin-scrollbar p-4">+ <Skeleton className="mb-4 h-11 w-full rounded-md" />+ <div className="flex min-h-0 flex-col">+ <div className="mb-2 text-xs font-semibold text-muted-foreground">All friends — …</div>+ <FriendRowsSkeleton />+ </div>+ <div className="mt-8 flex min-h-0 flex-col">+ <div className="mb-2 text-xs font-semibold text-muted-foreground">Blocked — …</div>+ <FriendRowsSkeleton withActions />+ </div>+ </div>+ <span className="sr-only">Loading friends</span>+ </div>+ )+}++// Skeleton rows for the friends/pending/blocked sections. `withActions` reserves+// the trailing action-button slot so pending/blocked rows don't reflow into+// the friend-row footprint and back.+export function FriendRowsSkeleton({ withActions = false }: { withActions?: boolean }) {+ return (+ <div className="flex flex-col gap-1">+ {Array.from({ length: 5 }).map((_, i) => (+ <div key={i} className="flex items-center gap-3 rounded-md px-2 py-2">+ <Skeleton className="size-8 shrink-0 rounded-full" />+ <div className="flex min-w-0 flex-1 flex-col gap-2">+ <Skeleton className="h-3.5 w-2/5 rounded" />+ <Skeleton className="h-3 w-3/5 rounded" />+ </div>+ {withActions ? (+ <div className="flex gap-2">+ <Skeleton className="size-8 shrink-0 rounded-full" />+ <Skeleton className="size-8 shrink-0 rounded-full" />+ </div>+ ) : (+ <Skeleton className="size-8 shrink-0 rounded-full" />+ )}+ </div>+ ))}+ </div>+ )+}diff --git a/src/web/src/components/community/social/friends-page.dom.test.tsx b/src/web/src/components/community/social/friends-page.dom.test.tsxnew file mode 100644index 000000000..864d9790d--- /dev/null+++ b/src/web/src/components/community/social/friends-page.dom.test.tsx@@ -0,0 +1,105 @@+import React from "react"+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"+import { fireEvent, render, waitFor } from "@/test/react-dom-harness"+import { beforeEach, describe, expect, it, vi } from "vitest"+import { FriendsPage } from "./friends-page"+import { tid } from "@/lib/community/testids"++const mocks = vi.hoisted(() => ({ tabs: vi.fn() }))++vi.mock("@/components/ui/tabs", () => ({+ Tabs: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) => {+ mocks.tabs(props)+ return React.createElement("tabs-root", null, children)+ },+ TabsList: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) => React.createElement("tabs-list", props, children),+ TabsTrigger: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) => React.createElement("tabs-trigger", props, children),+ TabsContent: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) => React.createElement("tabs-content", props, children),+}))++const pending = [+ { id: "fr_1", userId: "u1", name: "Ada", avatar: "A", avatarVersion: 1, kind: "incoming" as const, needsOwnerApproval: null },+ { id: "fr_gated", userId: "u2", name: "Bot", avatar: "B", avatarVersion: 1, kind: "incoming" as const, needsOwnerApproval: "owner" },+ { id: "fr_out", userId: "u3", name: "Grace", avatar: "G", avatarVersion: 1, kind: "outgoing" as const, needsOwnerApproval: null },+]++beforeEach(() => mocks.tabs.mockClear())++function renderPage(page: React.ReactElement) {+ return render(+ <QueryClientProvider client={new QueryClient()}>{page}</QueryClientProvider>,+ )+}++describe("FriendsPage actionable requests", () => {+ it("keeps the real Back control during a warm-data refresh", () => {+ const renderer = renderPage(<FriendsPage+ friends={[{+ id: "friend_1",+ userId: "user_1",+ name: "Alice",+ discriminator: "0001",+ avatar: "A",+ avatarVersion: 0,+ status: "online",+ sub: "",+ }]}+ pending={[]}+ blocked={[]}+ loading+ onBack={vi.fn()}+ />)++ expect(renderer.getByRole("button", { name: "Back" })).toBeInTheDocument()+ })++ it("uses the URL-owned tab and counts only actionable incoming rows", () => {+ const onActiveTabChange = vi.fn()+ const renderer = renderPage(<FriendsPage+ friends={[]}+ pending={pending}+ blocked={[]}+ activeTab="new"+ onActiveTabChange={onActiveTabChange}+ />)++ expect(mocks.tabs).toHaveBeenLastCalledWith(expect.objectContaining({ value: "new" }))+ const tabsProps = mocks.tabs.mock.calls.at(-1)?.[0] as { onValueChange: (value: string) => void }+ tabsProps.onValueChange("all")+ expect(onActiveTabChange).toHaveBeenCalledWith("all")+ expect(renderer.getByTestId(tid.friendsNewBadge)).toHaveTextContent("1")+ expect(renderer.getByText("Incoming — 1")).toBeInTheDocument()+ })++ it("keeps navigation and actions as siblings, and an action never navigates", async () => {+ let resolve!: () => void+ const onAccept = vi.fn(() => new Promise<void>((next) => { resolve = next }))+ const onOpenProfile = vi.fn()+ const renderer = renderPage(<FriendsPage+ friends={[]}+ pending={pending}+ blocked={[]}+ activeTab="new"+ onAccept={onAccept}+ onOpenProfile={onOpenProfile}+ />)+ const open = renderer.getByText("Ada").closest("button")!+ const accept = renderer.getByRole("button", { name: "Accept Ada's friend request" })+ expect(open.contains(accept)).toBe(false)+ fireEvent.click(open)+ expect(onOpenProfile).toHaveBeenCalledWith("Ada", expect.anything(), undefined, "u1")+ onOpenProfile.mockClear()++ fireEvent.click(accept)+ expect(onAccept).toHaveBeenCalledWith("fr_1")+ expect(onOpenProfile).not.toHaveBeenCalled()+ await waitFor(() => expect(accept).toBeDisabled())+ expect(open.closest("[aria-busy='true']")).not.toBeNull()++ resolve()+ await waitFor(() => expect(renderer.queryByRole(+ "button",+ { name: "Accept Ada's friend request" },+ )).toBeNull())+ })+})diff --git a/src/web/src/components/community/social/friends-page.skeleton.test.ts b/src/web/src/components/community/social/friends-page.skeleton.test.tsindex 8e87a1564..4b466b1f9 100644--- a/src/web/src/components/community/social/friends-page.skeleton.test.ts+++ b/src/web/src/components/community/social/friends-page.skeleton.test.ts@@ -1,17 +1,15 @@import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"-import { describe, expect, it, vi } from "vitest"-import { FriendsPage } from "./friends-page"+import { describe, expect, it } from "vitest"+import { FriendsPageSkeleton } from "./friends-page-skeleton"++function renderFriendsPageSkeleton(reserveBackSlot: boolean) {+ return renderToStaticMarkup(createElement(FriendsPageSkeleton, { reserveBackSlot }))+}describe("FriendsPage loading header", () => {it("keeps Back geometry inert until the real page is loaded", () => {- const html = renderToStaticMarkup(createElement(FriendsPage, {- friends: [],- pending: [],- blocked: [],- loading: true,- onBack: vi.fn(),- }))+ const html = renderFriendsPageSkeleton(true)expect(html).toContain('data-slot="loading-back-placeholder"')expect(html).not.toContain("<button")@@ -19,22 +17,10 @@ describe("FriendsPage loading header", () => {expect(html).not.toContain('aria-label="Back"')})- it("keeps the real Back control during a warm-data refresh", () => {- const html = renderToStaticMarkup(createElement(FriendsPage, {- friends: [{- id: "friend_1",- userId: "user_1",- name: "Alice",- discriminator: "0001",- avatar: "A",- status: "online",- }],- pending: [],- blocked: [],- loading: true,- onBack: vi.fn(),- }))+ it("omits Back geometry when the route does not reserve it", () => {+ const html = renderFriendsPageSkeleton(false)- expect(html).toContain('aria-label="Back"')+ expect(html).not.toContain('data-slot="loading-back-placeholder"')+ expect(html).not.toContain("<button")})})diff --git a/src/web/src/components/community/social/friends-page.tsx b/src/web/src/components/community/social/friends-page.tsxindex d9ceb3938..cb594573b 100644--- a/src/web/src/components/community/social/friends-page.tsx+++ b/src/web/src/components/community/social/friends-page.tsx@@ -2,23 +2,26 @@import { useState, useEffect, useMemo, useRef } from "react"import type React from "react"-import { Users, MessagesSquare, ChevronLeft, Check, X, AtSign, UserMinus, Ban, UserPlus, Search } from "lucide-react"+import { Users, MessagesSquare, ChevronLeft, Check, LoaderCircle, X, AtSign, UserMinus, Ban, UserPlus, Search } from "lucide-react"import { toastApiError } from "@/lib/api/client"import { apiFetchProfiles } from "@/lib/community/profile-seed"import { Button } from "@/components/ui/button"import { Input } from "@/components/ui/input"import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuSeparator } from "@/components/ui/context-menu"-import { Skeleton } from "@/components/ui/skeleton"import { Avatar } from "../avatar"import { avatarInitial } from "@/lib/community/avatar"import { EmptyState } from "../empty-state"+import { FriendRowsSkeleton, FriendsPageSkeleton } from "./friends-page-skeleton"import { hasStatus } from "./status-presets"import type { Friend, PendingRequest, BlockedUser } from "@/lib/community/models/people"import type { OpenProfile } from "@/components/community/social/profile-types"import { isSelfBotFriendship, isPresenceOffline, MIN_SEARCH_LENGTH } from "@alook/shared"import { useCommunityWsStore } from "@/stores/community/ws"import { readCommunityProfile } from "@/lib/community/profile-read"+import { actionableIncomingRequests, compactRequestCount } from "@/lib/community/friend-requests"+import { useFriendRequestActionState } from "@/hooks/community/use-friend-request-action-state"+import { tid } from "@/lib/community/testids"function FriendSection({ title, count, emptyLabel, children }: {title: string@@ -37,6 +40,7 @@ function FriendSection({ title, count, emptyLabel, children }: {// Friends page (@me, no DM selected) — All (friends + blocked) / New (add friend + pending).export function FriendsPage({friends, pending, blocked, loading, onBack, reserveBackSlot = false,+ activeTab, onActiveTabChange, onOpenProfile,onAccept, onReject, onCancelRequest, onUnblock, onSendRequest, onRemoveFriend, onBlock, onDm,}: {friends: Friend[]@@ -46,8 +50,10 @@ export function FriendsPage({onBack?: () => voidreserveBackSlot?: booleanonOpenProfile?: OpenProfile- onAccept?: (id: string) => void- onReject?: (id: string) => void+ activeTab?: "all" | "new"+ onActiveTabChange?: (tab: "all" | "new") => void+ onAccept?: (id: string) => Promise<unknown>+ onReject?: (id: string) => Promise<unknown>onCancelRequest?: (req: { id: string }) => voidonUnblock?: (id: string) => voidonSendRequest?: (target: { userId: string; username: string }) => void@@ -83,8 +89,15 @@ export function FriendsPage({return m}, [friends, pending, blocked])- const incoming = useMemo(() => pending.filter((p) => p.kind === "incoming"), [pending])+ const incoming = useMemo(() => actionableIncomingRequests(pending), [pending])const outgoing = useMemo(() => pending.filter((p) => p.kind === "outgoing"), [pending])+ const incomingActions = useFriendRequestActionState({+ rows: incoming,+ onAccept,+ onReject,+ surface: "friends",+ })+ const incomingCount = compactRequestCount(incomingActions.items.length)useEffect(() => {if (debounceRef.current) clearTimeout(debounceRef.current)@@ -126,35 +139,7 @@ export function FriendsPage({}, [addValue])if (loading && friends.length === 0 && pending.length === 0 && blocked.length === 0) {- return (- <div- aria-busy="true"- aria-label="Loading friends"- className="flex min-h-0 min-w-0 flex-1 flex-col gap-2"- >- <header className="flex h-12 shrink-0 items-center gap-2 border-b border-border/40 px-4">- {(reserveBackSlot || Boolean(onBack)) && (- <Skeleton data-slot="loading-back-placeholder" aria-hidden className="size-8 shrink-0 rounded-md" />- )}- <div aria-hidden className="inline-flex h-8 items-center gap-1 p-0.75 text-muted-foreground">- <span className="inline-flex h-[calc(100%-1px)] items-center px-2 py-1 text-sm font-medium">All</span>- <span className="inline-flex h-[calc(100%-1px)] items-center px-2 py-1 text-sm font-medium">New</span>- </div>- </header>- <div className="flex min-h-0 flex-1 flex-col overflow-y-auto thin-scrollbar p-4">- <Skeleton className="mb-4 h-11 w-full rounded-md" />- <div className="flex min-h-0 flex-col">- <div className="mb-2 text-xs font-semibold text-muted-foreground">All friends — …</div>- <FriendRowsSkeleton />- </div>- <div className="mt-8 flex min-h-0 flex-col">- <div className="mb-2 text-xs font-semibold text-muted-foreground">Blocked — …</div>- <FriendRowsSkeleton withActions />- </div>- </div>- <span className="sr-only">Loading friends</span>- </div>- )+ return <FriendsPageSkeleton reserveBackSlot={reserveBackSlot || Boolean(onBack)} />}const sendRequest = (u: { id: string; name: string; discriminator: string }) => {@@ -206,14 +191,31 @@ export function FriendsPage({}return (- <Tabs defaultValue="all" className="min-h-0 flex-1">+ <Tabs+ defaultValue="all"+ value={activeTab}+ onValueChange={(value) => onActiveTabChange?.(value as "all" | "new")}+ className="min-h-0 flex-1"+ ><header className="flex h-12 shrink-0 items-center gap-2 border-b border-border/40 px-4">{onBack && (<Button variant="ghost" size="icon-sm" onClick={onBack} className="text-muted-foreground hover:text-foreground" aria-label="Back"><ChevronLeft className="size-5" /></Button>)}<TabsList variant="line"><TabsTrigger value="all">All</TabsTrigger>- <TabsTrigger value="new">New</TabsTrigger>+ <TabsTrigger value="new">+ <span className="inline-flex items-center gap-1.5">+ New+ {incomingCount && (+ <span+ data-testid={tid.friendsNewBadge}+ className="grid h-5 min-w-5 place-items-center rounded-full bg-primary px-1 text-xs font-semibold text-primary-foreground"+ >+ {incomingCount}+ </span>+ )}+ </span>+ </TabsTrigger></TabsList></header>@@ -320,26 +322,51 @@ export function FriendsPage({</div>) : (<>- {incoming.length > 0 && (+ {incomingActions.items.length > 0 && (<div>- <div className="mb-2 text-xs font-semibold text-muted-foreground">Incoming — {incoming.length}</div>+ <div className="mb-2 text-xs font-semibold text-muted-foreground">Incoming — {incomingActions.items.length}</div><div className="flex flex-col gap-1">- {incoming.map((p) => (- <div key={p.id} className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent">- <Avatar label={p.avatar} seed={p.userId} size={32} />- <div className="min-w-0 flex-1 truncate text-sm font-medium">{p.name}</div>- <div className="flex gap-2">- <Button variant="secondary" size="icon-sm" onClick={() => onAccept?.(p.id)} className="rounded-full text-status-online" aria-label="Accept"><Check className="size-4" /></Button>- <Button variant="secondary" size="icon-sm" onClick={() => onReject?.(p.id)} className="rounded-full text-destructive" aria-label="Reject"><X className="size-4" /></Button>+ {incomingActions.items.map((item) => {+ const p = item.row+ const actionPending = item.status === "pending"+ return (+ <div+ key={p.id}+ aria-busy={actionPending || undefined}+ className="rounded-md px-2 py-2 hover:bg-accent"+ >+ <div className="flex items-center gap-3">+ <button+ className="flex min-h-11 min-w-0 flex-1 items-center gap-3 rounded-md text-left outline-none focus-visible:ring-2 focus-visible:ring-ring sm:min-h-0"+ onClick={(event) => onOpenProfile?.(p.name, event, undefined, p.userId)}+ >+ <Avatar label={p.avatar} seed={p.userId} size={32} />+ <span className="min-w-0 flex-1 truncate text-sm font-medium">{p.name}</span>+ </button>+ <div className="flex gap-2">+ <Button variant="secondary" size="icon" disabled={actionPending} onClick={() => { void incomingActions.act(item, "accept") }} className="size-11 rounded-full text-status-online sm:size-8" aria-label={`Accept ${p.name}'s friend request`}>+ {actionPending && item.action === "accept" ? <LoaderCircle className="size-4 animate-spin" /> : <Check className="size-4" />}+ </Button>+ <Button variant="secondary" size="icon" disabled={actionPending} onClick={() => { void incomingActions.act(item, "reject") }} className="size-11 rounded-full text-destructive sm:size-8" aria-label={`Reject ${p.name}'s friend request`}>+ {actionPending && item.action === "reject" ? <LoaderCircle className="size-4 animate-spin" /> : <X className="size-4" />}+ </Button>+ </div></div>+ {item.error && (+ <div role="status" aria-live="polite" className="mt-1 flex items-center justify-end gap-2 text-xs text-destructive">+ <span>{item.error}</span>+ <button className="min-h-11 min-w-11 font-medium underline sm:min-h-0 sm:min-w-0" onClick={() => { void incomingActions.retry(item) }}>Retry</button>+ </div>+ )}</div>- ))}+ )+ })}</div></div>)}{outgoing.length > 0 && (- <div className={incoming.length > 0 ? "mt-8" : ""}>+ <div className={incomingActions.items.length > 0 ? "mt-8" : ""}><div className="mb-2 text-xs font-semibold text-muted-foreground">Outgoing — {outgoing.length}</div><div className="flex flex-col gap-1">{outgoing.map((p) => (@@ -362,30 +389,3 @@ export function FriendsPage({</Tabs>)}--// Skeleton rows for the friends/pending/blocked sections. `withActions` reserves-// the trailing action-button slot so pending/blocked rows don't reflow into-// the friend-row footprint and back.-function FriendRowsSkeleton({ withActions = false }: { withActions?: boolean }) {- return (- <div className="flex flex-col gap-1">- {Array.from({ length: 5 }).map((_, i) => (- <div key={i} className="flex items-center gap-3 rounded-md px-2 py-2">- <Skeleton className="size-8 shrink-0 rounded-full" />- <div className="flex min-w-0 flex-1 flex-col gap-2">- <Skeleton className="h-3.5 w-2/5 rounded" />- <Skeleton className="h-3 w-3/5 rounded" />- </div>- {withActions ? (- <div className="flex gap-2">- <Skeleton className="size-8 shrink-0 rounded-full" />- <Skeleton className="size-8 shrink-0 rounded-full" />- </div>- ) : (- <Skeleton className="size-8 shrink-0 rounded-full" />- )}- </div>- ))}- </div>- )-}diff --git a/src/web/src/hooks/community/community-ws/invalidation-projections.ts b/src/web/src/hooks/community/community-ws/invalidation-projections.tsindex db32fbc38..5c3a82de1 100644--- a/src/web/src/hooks/community/community-ws/invalidation-projections.ts+++ b/src/web/src/hooks/community/community-ws/invalidation-projections.ts@@ -90,6 +90,15 @@ export function invalidateInbox(projection.invalidate("inbox", { queryKey: communityKeys.inbox() })}+export function invalidateInboxUnreads(+ projection: CommunityWsProjectionTransaction,+) {+ projection.invalidate("inbox-unreads", {+ queryKey: communityKeys.inboxUnreads(),+ exact: true,+ })+}+export function invalidateDms(projection: CommunityWsProjectionTransaction,) {diff --git a/src/web/src/hooks/community/community-ws/reconnect.test.ts b/src/web/src/hooks/community/community-ws/reconnect.test.tsindex 685b1892e..01874fff3 100644--- a/src/web/src/hooks/community/community-ws/reconnect.test.ts+++ b/src/web/src/hooks/community/community-ws/reconnect.test.ts@@ -601,6 +601,47 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {expect(summary).toMatchObject({ policyCount: 14, successCount: 14, failureCount: 0 })})+ it("actively refetches cached Friends and Inbox unreads after a socket gap", async () => {+ const { reconcileCommunityWsReconnect } = await import("./reconnect")+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },+ })+ let version = 1+ const friendsQuery = vi.fn(async () => ({ version }))+ const inboxQuery = vi.fn(async () => ({ version }))+ const friendsKey = communityKeys.friends()+ const inboxKey = communityKeys.inboxUnreads()+ await Promise.all([+ queryClient.fetchQuery({ queryKey: friendsKey, queryFn: friendsQuery }),+ queryClient.fetchQuery({ queryKey: inboxKey, queryFn: inboxQuery }),+ ])+ const friendsObserver = new QueryObserver(queryClient, {+ queryKey: friendsKey,+ queryFn: friendsQuery,+ staleTime: Infinity,+ })+ const inboxObserver = new QueryObserver(queryClient, {+ queryKey: inboxKey,+ queryFn: inboxQuery,+ staleTime: Infinity,+ })+ const unsubscribeFriends = friendsObserver.subscribe(() => undefined)+ const unsubscribeInbox = inboxObserver.subscribe(() => undefined)++ try {+ version = 2+ await reconcileCommunityWsReconnect(queryClient)++ expect(friendsQuery).toHaveBeenCalledTimes(2)+ expect(inboxQuery).toHaveBeenCalledTimes(2)+ expect(queryClient.getQueryData(friendsKey)).toEqual({ version: 2 })+ expect(queryClient.getQueryData(inboxKey)).toEqual({ version: 2 })+ } finally {+ unsubscribeFriends()+ unsubscribeInbox()+ }+ })+it("resets presence and status overlays before authoritative invalidation starts", async () => {const { reconcileCommunityWsReconnect } = await import("./reconnect")const { useCommunityWsStore } = await import("@/stores/community/ws")diff --git a/src/web/src/hooks/community/community-ws/registry.test.ts b/src/web/src/hooks/community/community-ws/registry.test.tsindex 48f5abe1a..8e3834faf 100644--- a/src/web/src/hooks/community/community-ws/registry.test.ts+++ b/src/web/src/hooks/community/community-ws/registry.test.ts@@ -113,6 +113,16 @@ describe("community WebSocket registry", () => {expect(communityWsRegistry[type].reconnectPolicies).toContain("all-cached-servers")})+ it.each([+ "community:friend.request",+ "community:friend.accept",+ "community:friend.reject",+ "community:friend.remove",+ "community:friend.block",+ ] as const)("assigns %s to Friends and Inbox reconnect reconciliation", (type) => {+ expect(communityWsRegistry[type].reconnectPolicies).toEqual(["friends", "inbox-dms"])+ })+it.each([["community:message.create", "handleMessageCreate"],["community:typing.start", "handleTypingStart"],diff --git a/src/web/src/hooks/community/community-ws/registry.ts b/src/web/src/hooks/community/community-ws/registry.tsindex 59bbf8f02..72387d09c 100644--- a/src/web/src/hooks/community/community-ws/registry.ts+++ b/src/web/src/hooks/community/community-ws/registry.ts@@ -85,11 +85,11 @@ export const communityWsRegistry = {"community:member.join": { handler: handleMemberJoin, reconnectPolicies: ["all-cached-servers"] },"community:member.leave": { handler: handleMemberLeave, reconnectPolicies: ["all-cached-servers"] },"community:member.update": { handler: handleMemberUpdate, reconnectPolicies: ["all-cached-servers"] },- "community:friend.request": { handler: handleFriendEvent, reconnectPolicies: ["friends"] },- "community:friend.accept": { handler: handleFriendEvent, reconnectPolicies: ["friends"] },- "community:friend.reject": { handler: handleFriendEvent, reconnectPolicies: ["friends"] },- "community:friend.remove": { handler: handleFriendEvent, reconnectPolicies: ["friends"] },- "community:friend.block": { handler: handleFriendEvent, reconnectPolicies: ["friends"] },+ "community:friend.request": { handler: handleFriendEvent, reconnectPolicies: ["friends", "inbox-dms"] },+ "community:friend.accept": { handler: handleFriendEvent, reconnectPolicies: ["friends", "inbox-dms"] },+ "community:friend.reject": { handler: handleFriendEvent, reconnectPolicies: ["friends", "inbox-dms"] },+ "community:friend.remove": { handler: handleFriendEvent, reconnectPolicies: ["friends", "inbox-dms"] },+ "community:friend.block": { handler: handleFriendEvent, reconnectPolicies: ["friends", "inbox-dms"] },"community:invite.create": { handler: handleInviteCreate, reconnectPolicies: ["all-cached-servers"] },"community:mention.create": { handler: handleMentionCreate, reconnectPolicies: ["inbox-dms"] },"community:unread.bump": { handler: handleUnreadBump, reconnectPolicies: ["inbox-dms", "all-cached-servers"] },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 d9bbfcdaa..3e44ef06a 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@@ -1,7 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import type {CommunityFriendBlock,- CommunityFriendRequest,CommunityMentionCreate,CommunityWsEvent,} from "@alook/shared"@@ -190,10 +189,8 @@ describe("useCommunityWs — account unread projection", () => {})describe("useCommunityWs — friend + mention → invalidate", () => {- it("friend.request invalidates communityKeys.friends()", async () => {- await mountHook()- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")- const event: CommunityFriendRequest = {+ it.each<CommunityWsEvent>([+ {type: "community:friend.request",friendship: {id: "f_1",@@ -202,11 +199,25 @@ describe("useCommunityWs — friend + mention → invalidate", () => {status: "pending",createdAt: "2026-07-03T00:00:00.000Z",},- }+ },+ { type: "community:friend.accept", friendshipId: "f_1" },+ { type: "community:friend.reject", friendshipId: "f_1" },+ { type: "community:friend.remove", friendshipId: "f_1" },+ { type: "community:friend.block", userId: "u_a" },+ ])("$type invalidates Friends and exact Inbox unreads once", async (event) => {+ await mountHook()+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")capturedOnMessage!(event)- expect(spy.mock.calls.some((call) => (- (call[0]?.queryKey as unknown[] | undefined)?.includes("friends")- ))).toBe(true)+ await vi.waitFor(() => expect(spy).toHaveBeenCalledTimes(2))+ const friendCalls = spy.mock.calls.filter((call) => (+ JSON.stringify(call[0]?.queryKey) === JSON.stringify(communityKeys.friends())+ ))+ const inboxCalls = spy.mock.calls.filter((call) => (+ JSON.stringify(call[0]?.queryKey) === JSON.stringify(communityKeys.inboxUnreads())+ ))+ expect(friendCalls).toHaveLength(1)+ expect(inboxCalls).toHaveLength(1)+ expect(inboxCalls[0]?.[0]).toMatchObject({ exact: true })})it("friend.block evicts cached DM reactor identities", async () => {diff --git a/src/web/src/hooks/community/community-ws/social-events.ts b/src/web/src/hooks/community/community-ws/social-events.tsindex 6b3993b62..6c626d617 100644--- a/src/web/src/hooks/community/community-ws/social-events.ts+++ b/src/web/src/hooks/community/community-ws/social-events.ts@@ -12,6 +12,7 @@ import type {import type { SocialEventContext } from "@/hooks/community/community-ws/handler-context"import {invalidateFriends,+ invalidateInboxUnreads,invalidateServersList,} from "./invalidation-projections"import {@@ -21,6 +22,8 @@ import {import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"import { removeDmReactionDetails } from "./reaction-details-invalidation"import { reconcileNotificationSettings } from "@/hooks/community/use-notification-settings"+import { getFriendRequestActionController } from "@/hooks/community/use-friend-request-action-state"+import { communityKeys } from "@/lib/query-keys"export function handleReadStateAdvanced(event: CommunityReadStateAdvanced,@@ -102,7 +105,27 @@ export function handleFriendEvent(event: FriendEvent,{ projection, queryClient }: SocialEventContext,) {- invalidateFriends(projection)+ if (event.type === "community:friend.request") {+ invalidateFriends(projection)+ invalidateInboxUnreads(projection)+ } else {+ projection.project(() => {+ const controller = getFriendRequestActionController(queryClient)+ if (event.type === "community:friend.block") {+ controller.publishTerminalForUser(event.userId)+ } else {+ controller.publishTerminal(event.friendshipId)+ }+ })+ projection.fence("friends", {+ queryKey: communityKeys.friends(),+ exact: true,+ })+ projection.fence("inbox-unreads", {+ queryKey: communityKeys.inboxUnreads(),+ exact: true,+ })+ }if (event.type === "community:friend.block") removeDmReactionDetails(queryClient)}diff --git a/src/web/src/hooks/community/friend-request-action-order.red.dom.test.tsx b/src/web/src/hooks/community/friend-request-action-order.red.dom.test.tsxnew file mode 100644index 000000000..9b7479329--- /dev/null+++ b/src/web/src/hooks/community/friend-request-action-order.red.dom.test.tsx@@ -0,0 +1,692 @@+import { useCallback, useLayoutEffect, type MutableRefObject } from "react"+import {+ QueryClient,+ QueryClientProvider,+ useQuery,+} from "@tanstack/react-query"+import { act, render, waitFor } from "@/test/react-dom-harness"+import { beforeEach, describe, expect, it, vi } from "vitest"+import { communityKeys } from "@/lib/query-keys"+import type { PendingRequest } from "@/lib/community/models/people"+import type { InboxFriendRequest } from "@/lib/community/models/inbox"+import { useCommunityWsStore } from "@/stores/community/ws"+import { useAcceptFriendRequest } from "./mutations/friends"+import { handleFriendEvent } from "./community-ws/social-events"+import {+ runCommunityWsProjectionTransaction,+ type CommunityWsProjectionTransaction,+} from "./community-ws/projection-transaction"+import type { SocialEventContext } from "./community-ws/handler-context"+import {+ friendsQueryFn,+ type FriendsResponse,+} from "./use-friends"+import {+ inboxUnreadsQueryFn,+ type UnreadsResponse,+} from "./use-inbox"+import {+ useFriendRequestActionState,+ type ActionableFriendRequest,+} from "./use-friend-request-action-state"++const apiFetchMock = vi.fn()+vi.mock("@/lib/api/client", () => ({+ apiFetch: (...args: unknown[]) => apiFetchMock(...args),+}))++type Deferred<T> = {+ promise: Promise<T>+ resolve: (value: T) => void+ reject: (reason?: unknown) => void+}++function deferred<T>(): Deferred<T> {+ let resolve!: (value: T) => void+ let reject!: (reason?: unknown) => void+ const promise = new Promise<T>((next, fail) => {+ resolve = next+ reject = fail+ })+ return { promise, resolve, reject }+}++const pendingRows: PendingRequest[] = [+ { id: "a", userId: "ua", name: "A", avatar: "A", avatarVersion: 1, kind: "incoming" },+ { id: "b", userId: "ub", name: "B", avatar: "B", avatarVersion: 1, kind: "incoming" },+]++const inboxRows: InboxFriendRequest[] = [+ { id: "a", userId: "ua", name: "A", avatar: "A", avatarVersion: 1, createdAt: "2" },+ { id: "b", userId: "ub", name: "B", avatar: "B", avatarVersion: 1, createdAt: "1" },+]++function friendsData(ids: readonly string[]): FriendsResponse {+ return {+ friends: [],+ blocked: [],+ pending: pendingRows.filter((row) => ids.includes(row.id)),+ }+}++function inboxData(ids: readonly string[]): UnreadsResponse {+ return {+ friendRequests: inboxRows.filter((row) => ids.includes(row.id)),+ servers: [],+ dms: [],+ }+}++type Transport = {+ action: (id: string) => Promise<unknown>+ readFriends: () => Promise<readonly string[]>+ readInbox: () => Promise<readonly string[]>+}++function installTransport(transport: Transport) {+ apiFetchMock.mockImplementation(async (path: string) => {+ const action = path.match(/^\/api\/community\/friends\/([^/]+)\/(accept|reject)$/)+ if (action) return transport.action(action[1]!)+ if (path === "/api/community/friends/accepted") return { friends: [] }+ if (path === "/api/community/friends/blocked") return { blocked: [] }+ if (path === "/api/community/friends/pending") {+ const ids = await transport.readFriends()+ return { pending: pendingRows.filter((row) => ids.includes(row.id)) }+ }+ if (path === "/api/community/users/me/inbox/unreads") {+ return inboxData(await transport.readInbox())+ }+ throw new Error(`unexpected API path ${path}`)+ })+}++type Surface = "inbox" | "friends"+type Paint = {+ inbox: string[]+ friends: string[]+ inboxCount: number+ friendsCount: number+ shortcutCount: number+ dot: boolean+}+type Controls = {+ act: (surface: Surface, id: string) => Promise<void>+ retry: (surface: Surface, id: string) => Promise<void>+}++function TestSurfaces({+ controlsRef,+ onPaint,+}: {+ controlsRef: MutableRefObject<Controls | null>+ onPaint?: (paint: Paint) => void+}) {+ const friends = useQuery({+ queryKey: communityKeys.friends(),+ queryFn: friendsQueryFn,+ enabled: false,+ })+ const inbox = useQuery({+ queryKey: communityKeys.inboxUnreads(),+ queryFn: inboxUnreadsQueryFn,+ enabled: false,+ })+ const mutation = useAcceptFriendRequest()+ const onAccept = useCallback(+ (id: string) => mutation.mutateAsync({ friendshipId: id }),+ [mutation],+ )+ const inboxActions = useFriendRequestActionState({+ rows: inbox.data?.friendRequests ?? [],+ onAccept,+ surface: "inbox",+ })+ const friendsActions = useFriendRequestActionState({+ rows: friends.data?.pending ?? [],+ onAccept,+ surface: "friends",+ })+ const shortcutActions = useFriendRequestActionState({+ rows: friends.data?.pending ?? [],+ surface: "friends",+ })++ const find = <T extends { id: string }>(+ items: Array<ActionableFriendRequest<T>>,+ id: string,+ ) => {+ const item = items.find((candidate) => candidate.row.id === id)+ if (!item) throw new Error(`missing ${id}`)+ return item+ }+ useLayoutEffect(() => {+ controlsRef.current = {+ act: (surface, id) => {+ if (surface === "inbox") {+ return inboxActions.act(find(inboxActions.items, id), "accept")+ }+ return friendsActions.act(find(friendsActions.items, id), "accept")+ },+ retry: (surface, id) => {+ if (surface === "inbox") {+ return inboxActions.retry(find(inboxActions.items, id))+ }+ return friendsActions.retry(find(friendsActions.items, id))+ },+ }+ })++ const paint: Paint = {+ inbox: inboxActions.items.map((item) => `${item.row.id}:${item.status ?? "idle"}`),+ friends: friendsActions.items.map((item) => `${item.row.id}:${item.status ?? "idle"}`),+ inboxCount: inboxActions.items.length,+ friendsCount: friendsActions.items.length,+ shortcutCount: shortcutActions.items.length,+ dot: inboxActions.items.length > 0,+ }+ useLayoutEffect(() => {+ onPaint?.(paint)+ })++ const rows = (+ surface: Surface,+ items: readonly ActionableFriendRequest<{ id: string }>[],+ ) => items.map((item) => (+ <div+ key={item.row.id}+ data-testid={`${surface}-row-${item.row.id}`}+ data-status={item.status ?? "idle"}+ >+ {item.error ? <button data-testid={`${surface}-retry-${item.row.id}`}>Retry</button> : null}+ </div>+ ))++ return (+ <>+ <output+ data-testid="projection"+ data-inbox-count={paint.inboxCount}+ data-friends-count={paint.friendsCount}+ data-shortcut-count={paint.shortcutCount}+ data-dot={paint.dot ? "on" : "off"}+ />+ <section data-testid="inbox-surface">{rows("inbox", inboxActions.items)}</section>+ <section data-testid="friends-surface">{rows("friends", friendsActions.items)}</section>+ </>+ )+}++function createClient(ids: readonly string[] = ["a", "b"]) {+ const client = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ })+ client.setQueryData(communityKeys.friends(), friendsData(ids), { updatedAt: 1 })+ client.setQueryData(communityKeys.inboxUnreads(), inboxData(ids), { updatedAt: 1 })+ return client+}++function mount(client: QueryClient, onPaint?: (paint: Paint) => void) {+ const controls = { current: null } as MutableRefObject<Controls | null>+ const rendered = render(+ <QueryClientProvider client={client}>+ <TestSurfaces controlsRef={controls} onPaint={onPaint} />+ </QueryClientProvider>,+ )+ return { controls, rendered }+}++async function fetchFriends(client: QueryClient) {+ return client.fetchQuery({+ queryKey: communityKeys.friends(),+ queryFn: friendsQueryFn,+ staleTime: 0,+ })+}++async function fetchInbox(client: QueryClient) {+ return client.fetchQuery({+ queryKey: communityKeys.inboxUnreads(),+ queryFn: inboxUnreadsQueryFn,+ staleTime: 0,+ })+}++beforeEach(() => {+ apiFetchMock.mockReset()+ useCommunityWsStore.getState().reset()+ useCommunityWsStore.getState().activateProfileAccount("viewer")+})++describe("friend-request action authority RED", () => {+ it("does not recreate A when fresh terminal absence precedes mutation rejection", async () => {+ const gate = deferred<unknown>()+ installTransport({+ action: () => gate.promise,+ readFriends: async () => [],+ readInbox: async () => [],+ })+ const client = createClient(["a"])+ const { controls, rendered } = mount(client)+ let request!: Promise<void>+ act(() => { request = controls.current!.act("inbox", "a") })+ await act(async () => { await Promise.all([fetchFriends(client), fetchInbox(client)]) })+ await act(async () => {+ gate.reject(new Error("ambiguous failure"))+ await request+ })++ expect(rendered.queryByTestId("inbox-row-a")).toBeNull()+ expect(rendered.queryByTestId("friends-row-a")).toBeNull()+ expect(rendered.getByTestId("projection")).toHaveAttribute("data-dot", "off")+ })++ it("keeps Retry across failed refresh, then clears every projection on later fresh absence", async () => {+ let stale = true+ installTransport({+ action: async () => { throw new Error("offline") },+ readFriends: async () => {+ if (stale) throw new Error("stale friends")+ return []+ },+ readInbox: async () => {+ if (stale) throw new Error("stale inbox")+ return []+ },+ })+ const client = createClient(["a"])+ const { controls, rendered } = mount(client)+ await act(async () => { await controls.current!.act("inbox", "a") })+ expect(rendered.getByTestId("inbox-row-a")).toHaveAttribute("data-status", "error")++ await act(async () => {+ await Promise.allSettled([fetchFriends(client), fetchInbox(client)])+ })+ expect(rendered.getByTestId("inbox-row-a")).toHaveAttribute("data-status", "error")++ stale = false+ await act(async () => { await fetchInbox(client) })+ expect(rendered.queryByTestId("inbox-row-a")).toBeNull()+ expect(rendered.queryByTestId("friends-row-a")).toBeNull()+ const projection = rendered.getByTestId("projection")+ expect(projection).toHaveAttribute("data-inbox-count", "0")+ expect(projection).toHaveAttribute("data-friends-count", "0")+ expect(projection).toHaveAttribute("data-shortcut-count", "0")+ expect(projection).toHaveAttribute("data-dot", "off")+ })++ it("publishes terminal absence to all three counts and the dot before the next paint", async () => {+ const inboxRead = deferred<readonly string[]>()+ installTransport({+ action: async () => { throw new Error("offline") },+ readFriends: async () => ["a"],+ readInbox: () => inboxRead.promise,+ })+ const paints: Paint[] = []+ const client = createClient(["a"])+ const { controls, rendered } = mount(client, (paint) => paints.push(paint))+ await act(async () => { await controls.current!.act("inbox", "a") })+ const read = fetchInbox(client)+ await waitFor(() => expect(apiFetchMock.mock.calls.some(+ ([path]) => path === "/api/community/users/me/inbox/unreads",+ )).toBe(true))+ paints.length = 0+ await act(async () => {+ inboxRead.resolve([])+ await read+ })++ expect(paints).not.toContainEqual(expect.objectContaining({+ inboxCount: 0,+ friendsCount: 1,+ }))+ expect(paints).not.toContainEqual(expect.objectContaining({+ inboxCount: 1,+ friendsCount: 0,+ }))+ expect(paints.length).toBeGreaterThan(0)+ expect(paints.every((paint) => (+ paint.inboxCount === 0+ && paint.friendsCount === 0+ && paint.shortcutCount === 0+ && !paint.dot+ ))).toBe(true)+ const projection = rendered.getByTestId("projection")+ expect(projection).toHaveAttribute("data-inbox-count", "0")+ expect(projection).toHaveAttribute("data-friends-count", "0")+ expect(projection).toHaveAttribute("data-shortcut-count", "0")+ expect(projection).toHaveAttribute("data-dot", "off")+ })++ it("keeps a terminal-event fence through stale sibling data and failed follow-up reads", async () => {+ installTransport({+ action: async () => { throw new Error("offline") },+ readFriends: async () => { throw new Error("friends refresh failed") },+ readInbox: async () => { throw new Error("inbox refresh failed") },+ })+ const paints: Paint[] = []+ const client = createClient(["a"])+ const { controls, rendered } = mount(client, (paint) => paints.push(paint))+ await act(async () => { await controls.current!.act("inbox", "a") })+ paints.length = 0++ act(() => {+ runCommunityWsProjectionTransaction(client, (projection) => {+ handleFriendEvent(+ { type: "community:friend.remove", friendshipId: "a" },+ {+ deliveryMode: "single",+ queryClient: client,+ sub: {},+ viewerUserIdRef: { current: "viewer" },+ projection,+ scheduleInboxInvalidate: vi.fn(),+ } satisfies SocialEventContext,+ )+ })+ })++ expect(rendered.queryByTestId("inbox-row-a")).toBeNull()+ expect(rendered.queryByTestId("friends-row-a")).toBeNull()+ expect(paints.every((paint) => (+ paint.inboxCount === 0+ && paint.friendsCount === 0+ && paint.shortcutCount === 0+ && !paint.dot+ ))).toBe(true)++ await act(async () => {+ await Promise.allSettled([fetchFriends(client), fetchInbox(client)])+ })+ expect(rendered.queryByTestId("inbox-row-a")).toBeNull()+ expect(rendered.queryByTestId("friends-row-a")).toBeNull()+ })++ it("suppresses a late unknown request for a blocked user until both fresh surfaces prove absence", async () => {+ let mode: "failed" | "absent" = "failed"+ installTransport({+ action: async () => undefined,+ readFriends: async () => {+ if (mode === "failed") throw new Error("friends refresh failed")+ return []+ },+ readInbox: async () => {+ if (mode === "failed") throw new Error("inbox refresh failed")+ return []+ },+ })+ const paints: Paint[] = []+ const client = createClient([])+ const { rendered } = mount(client, (paint) => paints.push(paint))++ const projection = {+ project: <T,>(effect: () => T) => effect(),+ invalidate: vi.fn(),+ fence: vi.fn(),+ } satisfies CommunityWsProjectionTransaction+ act(() => {+ handleFriendEvent(+ { type: "community:friend.block", userId: "ua" },+ {+ deliveryMode: "single",+ queryClient: client,+ sub: {},+ viewerUserIdRef: { current: "viewer" },+ projection,+ scheduleInboxInvalidate: vi.fn(),+ } satisfies SocialEventContext,+ )+ client.setQueryData(communityKeys.friends(), friendsData(["a"]))+ client.setQueryData(communityKeys.inboxUnreads(), inboxData(["a"]))+ })++ await act(async () => {+ await Promise.allSettled([fetchFriends(client), fetchInbox(client)])+ })+ expect(rendered.queryByTestId("inbox-row-a")).toBeNull()+ expect(rendered.queryByTestId("friends-row-a")).toBeNull()+ expect(paints.every((paint) => (+ paint.inboxCount === 0+ && paint.friendsCount === 0+ && paint.shortcutCount === 0+ && !paint.dot+ ))).toBe(true)++ mode = "absent"+ await act(async () => {+ await Promise.all([+ client.invalidateQueries({+ queryKey: communityKeys.friends(),+ exact: true,+ refetchType: "none",+ }),+ client.invalidateQueries({+ queryKey: communityKeys.inboxUnreads(),+ exact: true,+ refetchType: "none",+ }),+ ])+ await Promise.all([fetchFriends(client), fetchInbox(client)])+ })+ expect(rendered.queryByTestId("inbox-row-a")).toBeNull()+ expect(rendered.queryByTestId("friends-row-a")).toBeNull()++ await act(async () => {+ client.setQueryData(communityKeys.friends(), friendsData(["a"]))+ client.setQueryData(communityKeys.inboxUnreads(), inboxData(["a"]))+ })+ await waitFor(() => {+ expect(rendered.getByTestId("inbox-row-a")).toBeInTheDocument()+ expect(rendered.getByTestId("friends-row-a")).toBeInTheDocument()+ })+ expect(rendered.getByTestId("projection")).toHaveAttribute("data-shortcut-count", "1")+ })++ it("keeps pre-terminal exact-key reads from committing after both post-terminal absences", async () => {+ const oldFriends = deferred<readonly string[]>()+ const oldInbox = deferred<readonly string[]>()+ let postTerminal = false+ installTransport({+ action: async () => undefined,+ readFriends: () => postTerminal ? Promise.resolve([]) : oldFriends.promise,+ readInbox: () => postTerminal ? Promise.resolve([]) : oldInbox.promise,+ })+ const client = createClient(["a"])+ const preTerminalReads = [fetchFriends(client), fetchInbox(client)]+ await waitFor(() => expect(apiFetchMock.mock.calls.some(+ ([path]) => path === "/api/community/users/me/inbox/unreads",+ )).toBe(true))+ await Promise.all([+ client.cancelQueries({ queryKey: communityKeys.friends(), exact: true }),+ client.cancelQueries({ queryKey: communityKeys.inboxUnreads(), exact: true }),+ ])+ postTerminal = true+ await Promise.all([fetchFriends(client), fetchInbox(client)])++ oldFriends.resolve(["a"])+ oldInbox.resolve(["a"])+ await Promise.allSettled(preTerminalReads)++ expect(client.getQueryData<FriendsResponse>(communityKeys.friends())?.pending).toEqual([])+ expect(client.getQueryData<UnreadsResponse>(communityKeys.inboxUnreads())?.friendRequests).toEqual([])+ })+})++describe("friend-request shared owner RED", () => {+ it.each<Surface>(["inbox", "friends"])(+ "shows one pending A on both surfaces when the action starts from %s",+ async (origin) => {+ const gate = deferred<unknown>()+ installTransport({+ action: () => gate.promise,+ readFriends: async () => ["a", "b"],+ readInbox: async () => ["a", "b"],+ })+ const client = createClient()+ const { controls, rendered } = mount(client)+ let request!: Promise<void>+ act(() => { request = controls.current!.act(origin, "a") })+ try {+ await waitFor(() => {+ expect(rendered.getByTestId("inbox-row-a")).toHaveAttribute("data-status", "pending")+ expect(rendered.getByTestId("friends-row-a")).toHaveAttribute("data-status", "pending")+ })+ expect(rendered.getByTestId("inbox-row-b")).toHaveAttribute("data-status", "idle")+ expect(rendered.getByTestId("friends-row-b")).toHaveAttribute("data-status", "idle")+ } finally {+ gate.resolve(undefined)+ await act(async () => { await request })+ }+ },+ )++ it("inherits both surface rows when Retry starts with both cache envelopes absent", async () => {+ const retryGate = deferred<unknown>()+ let attempts = 0+ installTransport({+ action: async () => {+ attempts += 1+ if (attempts === 1) throw new Error("offline")+ return retryGate.promise+ },+ readFriends: async () => ["a"],+ readInbox: async () => ["a"],+ })+ const client = createClient(["a"])+ const { controls, rendered } = mount(client)+ await act(async () => { await controls.current!.act("inbox", "a") })+ act(() => {+ client.removeQueries({ queryKey: communityKeys.friends(), exact: true })+ client.removeQueries({ queryKey: communityKeys.inboxUnreads(), exact: true })+ })++ let retry!: Promise<void>+ act(() => { retry = controls.current!.retry("inbox", "a") })+ try {+ await waitFor(() => {+ expect(rendered.getByTestId("inbox-row-a")).toHaveAttribute("data-status", "pending")+ expect(rendered.getByTestId("friends-row-a")).toHaveAttribute("data-status", "pending")+ })+ expect(client.getQueryData(communityKeys.friends())).toBeUndefined()+ expect(client.getQueryData(communityKeys.inboxUnreads())).toBeUndefined()+ } finally {+ retryGate.resolve(undefined)+ await act(async () => { await retry })+ }+ })++ it("coalesces same-frame duplicate pending actions across both surfaces", async () => {+ const gate = deferred<unknown>()+ let calls = 0+ installTransport({+ action: () => {+ calls += 1+ return gate.promise+ },+ readFriends: async () => ["a"],+ readInbox: async () => ["a"],+ })+ const client = createClient(["a"])+ const { controls } = mount(client)+ let inboxRequest!: Promise<void>+ let friendsRequest!: Promise<void>+ act(() => {+ inboxRequest = controls.current!.act("inbox", "a")+ friendsRequest = controls.current!.act("friends", "a")+ })+ try {+ await waitFor(() => expect(calls).toBeGreaterThan(0))+ expect(calls).toBe(1)+ } finally {+ gate.resolve(undefined)+ await act(async () => { await Promise.all([inboxRequest, friendsRequest]) })+ }+ })++ it("permits only one generation increment when Retry is invoked twice in one frame", async () => {+ const retryGate = deferred<unknown>()+ let calls = 0+ installTransport({+ action: async () => {+ calls += 1+ if (calls === 1) throw new Error("offline")+ return retryGate.promise+ },+ readFriends: async () => ["a"],+ readInbox: async () => ["a"],+ })+ const client = createClient(["a"])+ const { controls } = mount(client)+ await act(async () => { await controls.current!.act("inbox", "a") })+ let first!: Promise<void>+ let second!: Promise<void>+ act(() => {+ first = controls.current!.retry("inbox", "a")+ second = controls.current!.retry("inbox", "a")+ })+ try {+ await waitFor(() => expect(calls).toBeGreaterThan(1))+ expect(calls).toBe(2)+ } finally {+ retryGate.resolve(undefined)+ await act(async () => { await Promise.all([first, second]) })+ }+ })++ it.each([+ { terminalId: "a", failedId: "b", order: "terminal-first" },+ { terminalId: "a", failedId: "b", order: "failure-first" },+ { terminalId: "b", failedId: "a", order: "terminal-first" },+ { terminalId: "b", failedId: "a", order: "failure-first" },+ ] as const)(+ "suppresses $terminalId and keeps only $failedId retryable with $order completion",+ async ({ terminalId, failedId, order }) => {+ const actions = new Map([+ ["a", deferred<unknown>()],+ ["b", deferred<unknown>()],+ ])+ installTransport({+ action: (id) => actions.get(id)!.promise,+ readFriends: async () => [failedId],+ readInbox: async () => [failedId],+ })+ const client = createClient()+ const { controls, rendered } = mount(client)+ let actionA!: Promise<void>+ let actionB!: Promise<void>+ act(() => {+ actionA = controls.current!.act("inbox", "a")+ actionB = controls.current!.act("inbox", "b")+ })++ if (order === "terminal-first") {+ await act(async () => { await Promise.all([fetchFriends(client), fetchInbox(client)]) })+ await act(async () => {+ actions.get(terminalId)!.reject(new Error(`ambiguous ${terminalId}`))+ await (terminalId === "a" ? actionA : actionB)+ })+ await act(async () => {+ actions.get(failedId)!.reject(new Error(`failed ${failedId}`))+ await (failedId === "a" ? actionA : actionB)+ })+ } else {+ await act(async () => {+ actions.get(failedId)!.reject(new Error(`failed ${failedId}`))+ await (failedId === "a" ? actionA : actionB)+ })+ await act(async () => { await Promise.all([fetchFriends(client), fetchInbox(client)]) })+ await act(async () => {+ actions.get(terminalId)!.reject(new Error(`ambiguous ${terminalId}`))+ await (terminalId === "a" ? actionA : actionB)+ })+ }++ expect(rendered.queryByTestId(`inbox-row-${terminalId}`)).toBeNull()+ expect(rendered.queryByTestId(`friends-row-${terminalId}`)).toBeNull()+ expect(rendered.getByTestId(`inbox-row-${failedId}`)).toHaveAttribute("data-status", "error")+ expect(rendered.getByTestId(`friends-row-${failedId}`)).toHaveAttribute("data-status", "error")+ },+ )+})diff --git a/src/web/src/hooks/community/mutations/friends.test.ts b/src/web/src/hooks/community/mutations/friends.test.tsindex 7f725a988..02ff54d60 100644--- a/src/web/src/hooks/community/mutations/friends.test.ts+++ b/src/web/src/hooks/community/mutations/friends.test.ts@@ -22,6 +22,7 @@ type MutConfig<Args, Ctx> = {onMutate?: (args: Args) => Promise<Ctx> | CtxonSuccess?: (data: unknown, args: Args, ctx: Ctx) => unknownonError?: (err: unknown, args: Args, ctx: Ctx) => unknown+ onSettled?: (data: unknown, err: unknown, args: Args, ctx: Ctx) => unknown}let capturedConfig: MutConfig<unknown, unknown> | null = nulllet capturedQc: QueryClient@@ -42,10 +43,12 @@ async function runMutation<Args>(args: Args) {const ctx = cfg.onMutate ? await cfg.onMutate(args) : undefinedtry {const data = cfg.mutationFn ? await cfg.mutationFn(args) : undefined- cfg.onSuccess?.(data, args, ctx)+ await cfg.onSuccess?.(data, args, ctx)+ await cfg.onSettled?.(data, null, args, ctx)return { data, ctx }} catch (err) {- cfg.onError?.(err, args, ctx)+ await cfg.onError?.(err, args, ctx)+ await cfg.onSettled?.(undefined, err, args, ctx)throw err}}@@ -100,6 +103,168 @@ describe("useAcceptFriendRequest — rollback", () => {const cache = capturedQc.getQueryData<{ pending: { id: string }[] }>(communityKeys.friends())expect(cache?.pending).toHaveLength(1)})++ it("optimistically removes and compensates the same id in both cache grains", async () => {+ capturedQc.setQueryData(communityKeys.friends(), {+ friends: [],+ blocked: [],+ pending: [+ { id: "f_1", userId: "u_1", name: "One", avatar: "1", avatarVersion: 1, kind: "incoming" },+ { id: "f_2", userId: "u_2", name: "Two", avatar: "2", avatarVersion: 2, kind: "incoming" },+ ],+ })+ capturedQc.setQueryData(communityKeys.inboxUnreads(), {+ friendRequests: [+ { id: "f_1", userId: "u_1", name: "One", avatar: "1", avatarVersion: 1, createdAt: "2" },+ { id: "f_2", userId: "u_2", name: "Two", avatar: "2", avatarVersion: 2, createdAt: "1" },+ ],+ servers: [],+ dms: [],+ })+ const mod = await load()+ mod.useAcceptFriendRequest()+ const cfg = capturedConfig as MutConfig<{ friendshipId: string }, unknown>+ const cancelSpy = vi.spyOn(capturedQc, "cancelQueries")+ const context = await cfg.onMutate?.({ friendshipId: "f_1" })++ expect(cancelSpy.mock.calls.map((call) => call[0])).toEqual([+ { queryKey: communityKeys.friends(), exact: true },+ { queryKey: communityKeys.inboxUnreads(), exact: true },+ ])+ expect(capturedQc.getQueryData<{ pending: { id: string }[] }>(communityKeys.friends())?.pending)+ .toEqual([expect.objectContaining({ id: "f_2" })])+ expect(capturedQc.getQueryData<{ friendRequests: { id: string }[] }>(communityKeys.inboxUnreads())?.friendRequests)+ .toEqual([expect.objectContaining({ id: "f_2" })])++ await cfg.onError?.(new Error("boom"), { friendshipId: "f_1" }, context)+ expect(capturedQc.getQueryData<{ pending: { id: string }[] }>(communityKeys.friends())?.pending.map((row) => row.id))+ .toEqual(["f_1", "f_2"])+ expect(capturedQc.getQueryData<{ friendRequests: { id: string }[] }>(communityKeys.inboxUnreads())?.friendRequests.map((row) => row.id))+ .toEqual(["f_1", "f_2"])+ })++ it.each([+ { successfulId: "a", failedId: "b", order: "failed-first" },+ { successfulId: "a", failedId: "b", order: "success-first" },+ { successfulId: "b", failedId: "a", order: "failed-first" },+ { successfulId: "b", failedId: "a", order: "success-first" },+ ])(+ "does not resurrect $successfulId when $failedId compensates $order",+ async ({ successfulId, failedId, order }) => {+ capturedQc.setQueryData(communityKeys.friends(), {+ friends: [],+ blocked: [],+ pending: [+ { id: "a", userId: "ua", name: "A", avatar: "A", avatarVersion: 1, kind: "incoming" },+ { id: "b", userId: "ub", name: "B", avatar: "B", avatarVersion: 1, kind: "incoming" },+ ],+ })+ capturedQc.setQueryData(communityKeys.inboxUnreads(), {+ friendRequests: [+ { id: "a", userId: "ua", name: "A", avatar: "A", avatarVersion: 1, createdAt: "2" },+ { id: "b", userId: "ub", name: "B", avatar: "B", avatarVersion: 1, createdAt: "1" },+ ],+ servers: [],+ dms: [],+ })+ const mod = await load()+ mod.useRejectFriendRequest()+ const cfg = capturedConfig as MutConfig<{ friendshipId: string }, unknown>+ const contextA = await cfg.onMutate?.({ friendshipId: "a" })+ const contextB = await cfg.onMutate?.({ friendshipId: "b" })+ const contexts = { a: contextA, b: contextB }+ const fail = () => cfg.onError?.(+ new Error(`${failedId} failed`),+ { friendshipId: failedId },+ contexts[failedId as "a" | "b"],+ )+ const settle = () => cfg.onSettled?.(+ undefined,+ null,+ { friendshipId: successfulId },+ contexts[successfulId as "a" | "b"],+ )+ if (order === "failed-first") {+ await fail()+ await settle()+ } else {+ await settle()+ await fail()+ }++ expect(capturedQc.getQueryData<{ pending: { id: string }[] }>(communityKeys.friends())?.pending.map((row) => row.id))+ .toEqual([failedId])+ expect(capturedQc.getQueryData<{ friendRequests: { id: string }[] }>(communityKeys.inboxUnreads())?.friendRequests.map((row) => row.id))+ .toEqual([failedId])+ },+ )++ it("preserves unrelated current-cache changes and never reconstructs an absent envelope", async () => {+ capturedQc.setQueryData(communityKeys.friends(), {+ friends: [],+ blocked: [],+ pending: [{ id: "a", userId: "ua", name: "A", avatar: "A", avatarVersion: 1, kind: "incoming" }],+ })+ const mod = await load()+ mod.useAcceptFriendRequest()+ const cfg = capturedConfig as MutConfig<{ friendshipId: string }, unknown>+ const context = await cfg.onMutate?.({ friendshipId: "a" })+ capturedQc.setQueryData(communityKeys.friends(), {+ friends: [],+ blocked: [],+ pending: [{ id: "c", userId: "uc", name: "C", avatar: "C", avatarVersion: 1, kind: "incoming" }],+ })+ await cfg.onError?.(new Error("failed"), { friendshipId: "a" }, context)++ expect(capturedQc.getQueryData<{ pending: { id: string }[] }>(communityKeys.friends())?.pending.map((row) => row.id))+ .toEqual(["a", "c"])+ expect(capturedQc.getQueryData(communityKeys.inboxUnreads())).toBeUndefined()+ })++ it("never reconstructs an absent Friends envelope while compensating Inbox", async () => {+ capturedQc.setQueryData(communityKeys.inboxUnreads(), {+ friendRequests: [{+ id: "a",+ userId: "ua",+ name: "A",+ avatar: "A",+ avatarVersion: 1,+ createdAt: "2026-09-12T01:00:00Z",+ }],+ servers: [],+ dms: [],+ })+ const mod = await load()+ mod.useAcceptFriendRequest()+ const cfg = capturedConfig as MutConfig<{ friendshipId: string }, unknown>+ const context = await cfg.onMutate?.({ friendshipId: "a" })+ await cfg.onError?.(new Error("failed"), { friendshipId: "a" }, context)++ expect(capturedQc.getQueryData(communityKeys.friends())).toBeUndefined()+ expect(capturedQc.getQueryData<{ friendRequests: { id: string }[] }>(+ communityKeys.inboxUnreads(),+ )?.friendRequests.map((row) => row.id)).toEqual(["a"])+ })++ it("awaits settled invalidation of Friends and exact Inbox unreads", async () => {+ apiFetchMock.mockResolvedValueOnce(undefined)+ const mod = await load()+ mod.useAcceptFriendRequest()+ const gates: Array<() => void> = []+ const spy = vi.spyOn(capturedQc, "invalidateQueries").mockImplementation(() => (+ new Promise<void>((resolve) => gates.push(resolve))+ ))+ let settled = false+ const mutation = runMutation({ friendshipId: "f_1" }).then(() => { settled = true })+ await vi.waitFor(() => expect(spy).toHaveBeenCalledTimes(2))+ expect(settled).toBe(false)+ gates.splice(0).forEach((resolve) => resolve())+ await mutation+ expect(spy.mock.calls.map((call) => call[0])).toEqual([+ { queryKey: communityKeys.friends(), exact: true },+ { queryKey: communityKeys.inboxUnreads(), exact: true },+ ])+ })})describe("useCancelBotFriendRequest — optimistic + rollback", () => {@@ -150,6 +315,18 @@ describe("useRemoveFriend — optimistic + rollback", () => {const cache = capturedQc.getQueryData<{ friends: { id: string }[] }>(communityKeys.friends())expect(cache?.friends).toHaveLength(1)})++ it("keeps an absent cache absent and invalidates Friends on success", async () => {+ apiFetchMock.mockResolvedValueOnce(undefined)+ const mod = await load()+ mod.useRemoveFriend()+ const spy = vi.spyOn(capturedQc, "invalidateQueries")++ await runMutation({ friendshipId: "missing" })++ expect(capturedQc.getQueryData(communityKeys.friends())).toBeUndefined()+ expect(spy).toHaveBeenCalledWith({ queryKey: communityKeys.friends() })+ })})describe("useBlockUser — invalidates friends", () => {diff --git a/src/web/src/hooks/community/mutations/friends.ts b/src/web/src/hooks/community/mutations/friends.tsindex 882b43780..80c58c676 100644--- a/src/web/src/hooks/community/mutations/friends.ts+++ b/src/web/src/hooks/community/mutations/friends.ts@@ -4,6 +4,13 @@ import { useMutation, useQueryClient } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import type { FriendsResponse } from "@/hooks/community/use-friends"+import type { UnreadsResponse } from "@/hooks/community/use-inbox"+import type { PendingRequest } from "@/lib/community/models/people"+import type { InboxFriendRequest } from "@/lib/community/models/inbox"+import {+ getFriendRequestActionController,+ type FriendRequestAction,+} from "@/hooks/community/use-friend-request-action-state"/*** Friend-scoped mutations. All six live on one query key@@ -36,63 +43,147 @@ export function useSendFriendRequest() {})}-// ── Accept / reject / remove — all decorate the pending list ───────────────+// ── Accept / reject ────────────────────────────────────────────────────────export type FriendActionArgs = { friendshipId: string }-function useFriendListMutation(+type CapturedRow<T> = { row: T; index: number }+type FriendRequestMutationContext = {+ friends?: CapturedRow<PendingRequest>+ generation: number+ inbox?: CapturedRow<InboxFriendRequest>+}++function captureRow<T extends { id: string }>(+ rows: readonly T[],+ id: string,+): CapturedRow<T> | undefined {+ const index = rows.findIndex((row) => row.id === id)+ return index < 0 ? undefined : { row: rows[index]!, index }+}++function reinsertRow<T extends { id: string }>(+ rows: readonly T[],+ captured: CapturedRow<T> | undefined,+): T[] {+ if (!captured || rows.some((row) => row.id === captured.row.id)) return [...rows]+ const next = [...rows]+ next.splice(Math.min(captured.index, next.length), 0, captured.row)+ return next+}++function useFriendRequestMutation(+ action: FriendRequestAction,buildFetch: (id: string) => Promise<unknown>,- patchOptimistic: (prev: FriendsResponse | undefined, id: string) => FriendsResponse | undefined,) {const queryClient = useQueryClient()- return useMutation<void, Error, FriendActionArgs, { snapshot: FriendsResponse | undefined }>({+ const controller = getFriendRequestActionController(queryClient)+ return useMutation<void, Error, FriendActionArgs, FriendRequestMutationContext>({mutationFn: async ({ friendshipId }) => {await buildFetch(friendshipId)},- onMutate: async (args) => {- const key = communityKeys.friends()- await queryClient.cancelQueries({ queryKey: key })- const snapshot = queryClient.getQueryData<FriendsResponse>(key)- queryClient.setQueryData<FriendsResponse | undefined>(key, (prev) =>- patchOptimistic(prev, args.friendshipId),+ onMutate: async ({ friendshipId }) => {+ const generation = controller.claimMutation(friendshipId, action)+ const friendsKey = communityKeys.friends()+ const inboxKey = communityKeys.inboxUnreads()+ await Promise.all([+ queryClient.cancelQueries({ queryKey: friendsKey, exact: true }),+ queryClient.cancelQueries({ queryKey: inboxKey, exact: true }),+ ])+ const friends = queryClient.getQueryData<FriendsResponse>(friendsKey)+ const inbox = queryClient.getQueryData<UnreadsResponse>(inboxKey)+ const context = {+ friends: captureRow(friends?.pending ?? [], friendshipId),+ generation,+ inbox: captureRow(inbox?.friendRequests ?? [], friendshipId),+ }+ queryClient.setQueryData<FriendsResponse | undefined>(friendsKey, (current) =>+ current+ ? { ...current, pending: current.pending.filter((row) => row.id !== friendshipId) }+ : current,)- return { snapshot }+ queryClient.setQueryData<UnreadsResponse | undefined>(inboxKey, (current) =>+ current+ ? {+ ...current,+ friendRequests: (current.friendRequests ?? []).filter((row) => row.id !== friendshipId),+ }+ : current,+ )+ return context},- onError: (_err, _args, ctx) => {- if (ctx?.snapshot) queryClient.setQueryData(communityKeys.friends(), ctx.snapshot)+ onSuccess: async (_data, { friendshipId }, context) => {+ if (!context) return+ await controller.publishTerminalAndFence(friendshipId, context.generation)},- onSuccess: () => {- // Reconcile once — the accepted friendship needs the "accepted" row from- // the server. Invalidation refetches. If the WS event arrives first, the- // reconciliation table also invalidates; either way, the final render is- // the same.- void queryClient.invalidateQueries({ queryKey: communityKeys.friends() })+ onError: (_error, { friendshipId }, context) => {+ if (!context) return+ if (!controller.isCompensatable(friendshipId, context.generation)) return+ queryClient.setQueryData<FriendsResponse | undefined>(communityKeys.friends(), (current) =>+ current+ ? { ...current, pending: reinsertRow(current.pending, context?.friends) }+ : current,+ )+ queryClient.setQueryData<UnreadsResponse | undefined>(communityKeys.inboxUnreads(), (current) =>+ current+ ? { ...current, friendRequests: reinsertRow(current.friendRequests ?? [], context?.inbox) }+ : current,+ )+ controller.publishError(friendshipId, context.generation)+ },+ onSettled: async (_data, _error, { friendshipId }, context) => {+ try {+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: communityKeys.friends(), exact: true }),+ queryClient.invalidateQueries({ queryKey: communityKeys.inboxUnreads(), exact: true }),+ ])+ } finally {+ if (context) controller.settleGeneration(friendshipId, context.generation)+ }},})}export function useAcceptFriendRequest() {- return useFriendListMutation(+ return useFriendRequestMutation(+ "accept",(id) => apiFetch(`/api/community/friends/${id}/accept`, { method: "POST" }),- (prev, id) =>- prev ? { ...prev, pending: prev.pending.filter((p) => p.id !== id) } : prev,)}export function useRejectFriendRequest() {- return useFriendListMutation(+ return useFriendRequestMutation(+ "reject",(id) => apiFetch(`/api/community/friends/${id}/reject`, { method: "POST" }),- (prev, id) =>- prev ? { ...prev, pending: prev.pending.filter((p) => p.id !== id) } : prev,)}+// ── Remove friend ──────────────────────────────────────────────────────────+export function useRemoveFriend() {- return useFriendListMutation(- (id) => apiFetch(`/api/community/friends/${id}`, { method: "DELETE" }),- (prev, id) =>- prev ? { ...prev, friends: prev.friends.filter((f) => f.id !== id) } : prev,- )+ const queryClient = useQueryClient()+ return useMutation<void, Error, FriendActionArgs, { snapshot: FriendsResponse | undefined }>({+ mutationFn: async ({ friendshipId }) => {+ await apiFetch(`/api/community/friends/${friendshipId}`, { method: "DELETE" })+ },+ onMutate: async ({ friendshipId }) => {+ const key = communityKeys.friends()+ await queryClient.cancelQueries({ queryKey: key })+ const snapshot = queryClient.getQueryData<FriendsResponse>(key)+ queryClient.setQueryData<FriendsResponse | undefined>(key, (current) =>+ current+ ? { ...current, friends: current.friends.filter((friend) => friend.id !== friendshipId) }+ : current,+ )+ return { snapshot }+ },+ onError: (_error, _args, context) => {+ if (context?.snapshot) queryClient.setQueryData(communityKeys.friends(), context.snapshot)+ },+ onSuccess: () => {+ void queryClient.invalidateQueries({ queryKey: communityKeys.friends() })+ },+ })}// ── Cancel outgoing pending (unified) ──────────────────────────────────────diff --git a/src/web/src/hooks/community/use-friend-request-action-state.dom.test.ts b/src/web/src/hooks/community/use-friend-request-action-state.dom.test.tsnew file mode 100644index 000000000..29f179987--- /dev/null+++ b/src/web/src/hooks/community/use-friend-request-action-state.dom.test.ts@@ -0,0 +1,206 @@+import { createElement, type PropsWithChildren } from "react"+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"+import { act, renderHook, waitFor } from "@/test/react-dom-harness"+import { describe, expect, it, vi } from "vitest"+import {+ getFriendRequestActionController,+ useFriendRequestActionState,+} from "./use-friend-request-action-state"+import { communityKeys } from "@/lib/query-keys"++type Row = { id: string; name: string }+const rows: Row[] = [+ { id: "a", name: "A" },+ { id: "b", name: "B" },+]++function createQueryWrapper() {+ const queryClient = new QueryClient()+ return function QueryWrapper({ children }: PropsWithChildren) {+ return createElement(QueryClientProvider, { client: queryClient }, children)+ }+}++describe("useFriendRequestActionState", () => {+ it("keeps an optimistically removed row visible and locks only that id", async () => {+ let resolve!: () => void+ const onAccept = vi.fn(() => new Promise<void>((next) => { resolve = next }))+ const rendered = renderHook(+ ({ currentRows }) => useFriendRequestActionState({+ rows: currentRows,+ onAccept,+ surface: "friends",+ }),+ { initialProps: { currentRows: rows }, wrapper: createQueryWrapper() },+ )+ let pending!: Promise<void>+ act(() => {+ pending = rendered.result.current.act(rendered.result.current.items[0]!, "accept")+ })+ rendered.rerender({ currentRows: [rows[1]!] })++ expect(rendered.result.current.items.map((item) => item.row.id)).toEqual(["a", "b"])+ expect(rendered.result.current.items[0]?.status).toBe("pending")+ expect(rendered.result.current.items[1]?.status).toBeUndefined()++ resolve()+ await act(async () => { await pending })+ expect(rendered.result.current.items.map((item) => item.row.id)).toEqual(["b"])+ })++ it("keeps a keyed live error and retries the same action independently", async () => {+ const onReject = vi.fn()+ .mockRejectedValueOnce(new Error("offline"))+ .mockResolvedValueOnce(undefined)+ const rendered = renderHook(+ ({ currentRows }) => useFriendRequestActionState({+ rows: currentRows,+ onReject,+ surface: "friends",+ }),+ { initialProps: { currentRows: rows }, wrapper: createQueryWrapper() },+ )++ await act(async () => {+ await rendered.result.current.act(rendered.result.current.items[0]!, "reject")+ })+ rendered.rerender({ currentRows: [rows[1]!] })+ expect(rendered.result.current.items[0]).toMatchObject({+ row: rows[0],+ action: "reject",+ status: "error",+ })+ expect(rendered.result.current.items[0]?.error).toContain("Try again")+ expect(rendered.result.current.items[1]?.status).toBeUndefined()++ await act(async () => {+ await rendered.result.current.retry(rendered.result.current.items[0]!)+ })+ await waitFor(() => {+ expect(rendered.result.current.items.map((item) => item.row.id)).toEqual(["b"])+ })+ expect(onReject).toHaveBeenCalledTimes(2)+ })++ it("tracks two pending ids without sharing action state", async () => {+ const resolvers = new Map<string, () => void>()+ const onAccept = vi.fn((id: string) => new Promise<void>((resolve) => {+ resolvers.set(id, resolve)+ }))+ const rendered = renderHook(+ () => useFriendRequestActionState({ rows, onAccept, surface: "friends" }),+ { wrapper: createQueryWrapper() },+ )+ let first!: Promise<void>+ let second!: Promise<void>+ act(() => {+ first = rendered.result.current.act(rendered.result.current.items[0]!, "accept")+ second = rendered.result.current.act(rendered.result.current.items[1]!, "accept")+ })+ expect(rendered.result.current.items.map((item) => item.status)).toEqual(["pending", "pending"])++ resolvers.get("b")?.()+ await act(async () => { await second })+ expect(rendered.result.current.items[0]?.status).toBe("pending")+ expect(rendered.result.current.items[1]?.status).toBeUndefined()+ resolvers.get("a")?.()+ await act(async () => { await first })+ })++ it("fans a user terminal out across snapshots and caches", async () => {+ const queryClient = new QueryClient()+ const snapshot = { id: "snapshot", userId: "u1" }+ const cached = { id: "cached", userId: "u1" }+ const alreadyTerminal = { id: "terminal", userId: "u1" }+ queryClient.setQueryData(communityKeys.friends(), { pending: [snapshot] })+ queryClient.setQueryData(communityKeys.inboxUnreads(), {+ friendRequests: [cached, alreadyTerminal],+ })+ const controller = getFriendRequestActionController(queryClient)+ controller.claimMutation(snapshot.id, "accept")+ controller.publishTerminal(alreadyTerminal.id)++ controller.publishTerminalForUser("u1")++ expect(controller.project("friends", [snapshot])).toEqual([])+ expect(controller.project("inbox", [cached, alreadyTerminal])).toEqual([])++ const late = { id: "late", userId: "u1" }+ queryClient.setQueryData(communityKeys.inboxUnreads(), { friendRequests: [late] })+ controller.claimMutation(late.id, "reject")+ expect(controller.project("inbox", [])).toEqual([])+ const mutation = vi.fn()+ await controller.start({+ action: "reject",+ index: 0,+ mutation,+ retry: false,+ row: late,+ surface: "inbox",+ })+ expect(mutation).not.toHaveBeenCalled()+ })++ it("collects a settled terminal only after two absent authority proofs", async () => {+ const queryClient = new QueryClient()+ const row = { id: "a", userId: "u1" }+ queryClient.setQueryData(communityKeys.friends(), { pending: [row] })+ queryClient.setQueryData(communityKeys.inboxUnreads(), { friendRequests: [row] })+ const controller = getFriendRequestActionController(queryClient)+ const generation = controller.claimMutation(row.id, "accept")+ await controller.publishTerminalAndFence(row.id, generation)++ let friendRows = [row]+ await queryClient.fetchQuery({+ queryKey: communityKeys.friends(),+ queryFn: async () => ({ pending: friendRows }),+ })+ friendRows = []+ await queryClient.refetchQueries({ queryKey: communityKeys.friends(), exact: true })+ await queryClient.fetchQuery({+ queryKey: communityKeys.inboxUnreads(),+ queryFn: async () => ({ friendRequests: [] }),+ })++ queryClient.setQueryData(communityKeys.friends(), { pending: [row] })+ controller.settleGeneration(row.id, generation)+ expect(controller.project("friends", [row])).toEqual([])++ queryClient.setQueryData(communityKeys.friends(), { pending: [] })+ queryClient.setQueryData(communityKeys.inboxUnreads(), { friendRequests: [row] })+ controller.settleGeneration(row.id, generation)+ expect(controller.project("friends", [row])).toEqual([])++ queryClient.setQueryData(communityKeys.inboxUnreads(), { friendRequests: [] })+ controller.settleGeneration(row.id, generation)+ expect(controller.project("friends", [row])).toEqual([{ row }])+ })++ it("keeps a user fence until both surfaces prove absence with no cached row", async () => {+ const queryClient = new QueryClient()+ const controller = getFriendRequestActionController(queryClient)+ queryClient.setQueryData(["unrelated"], {})+ controller.publishTerminalForUser("ghost")++ await queryClient.fetchQuery({+ queryKey: communityKeys.inboxUnreads(),+ queryFn: async () => ({ friendRequests: [] }),+ })+ const row = { id: "late", userId: "ghost" }+ queryClient.setQueryData(communityKeys.inboxUnreads(), { friendRequests: [row] })+ await queryClient.fetchQuery({+ queryKey: communityKeys.friends(),+ queryFn: async () => ({ pending: [] }),+ })+ expect(controller.project("friends", [row])).toEqual([])++ queryClient.setQueryData(communityKeys.inboxUnreads(), { friendRequests: [] })+ queryClient.setQueryData(communityKeys.friends(), { pending: [row] })+ await queryClient.refetchQueries({ queryKey: communityKeys.inboxUnreads(), exact: true })+ expect(controller.project("friends", [row])).toEqual([])++ queryClient.setQueryData(communityKeys.friends(), { pending: [] })+ await queryClient.refetchQueries({ queryKey: communityKeys.inboxUnreads(), exact: true })+ expect(controller.project("friends", [row])).toEqual([{ row }])+ })+})diff --git a/src/web/src/hooks/community/use-friend-request-action-state.ts b/src/web/src/hooks/community/use-friend-request-action-state.tsnew file mode 100644index 000000000..212450471--- /dev/null+++ b/src/web/src/hooks/community/use-friend-request-action-state.ts@@ -0,0 +1,470 @@+"use client"++import {+ useCallback,+ useSyncExternalStore,+} from "react"+import {+ hashKey,+ useQueryClient,+ type QueryClient,+ type QueryCacheNotifyEvent,+} from "@tanstack/react-query"+import { communityKeys } from "@/lib/query-keys"++export type FriendRequestAction = "accept" | "reject"+type FriendRequestActionStatus = "pending" | "error"+export type FriendRequestSurface = "inbox" | "friends"++type FriendRequestRow = {+ id: string+ userId?: string+}++type CapturedRow = {+ row: FriendRequestRow+ index: number+}++type ActionEntry = {+ action: FriendRequestAction+ baselineEpoch: number+ generation: number+ promise?: Promise<void>+ settled: boolean+ snapshots: Partial<Record<FriendRequestSurface, CapturedRow>>+ status: FriendRequestActionStatus+}++type TerminalFence = {+ cancellation?: Promise<void>+ epoch: number+ proofs: Set<FriendRequestSurface>+}++type UserTerminalFence = {+ epoch: number+ proofs: Set<FriendRequestSurface>+}++type FriendsEnvelope = {+ pending?: readonly FriendRequestRow[]+}++type InboxEnvelope = {+ friendRequests?: readonly FriendRequestRow[]+}++export type ActionableFriendRequest<T> = {+ row: T+ action?: FriendRequestAction+ status?: FriendRequestActionStatus+ error?: string+}++const controllers = new WeakMap<QueryClient, FriendRequestActionController>()+const friendsHash = hashKey(communityKeys.friends())+const inboxHash = hashKey(communityKeys.inboxUnreads())++function captureRow<T extends FriendRequestRow>(+ rows: readonly T[],+ id: string,+): CapturedRow | undefined {+ const index = rows.findIndex((row) => row.id === id)+ return index < 0 ? undefined : { row: rows[index]!, index }+}++function rowsFromEnvelope(+ surface: FriendRequestSurface,+ data: unknown,+): readonly FriendRequestRow[] {+ if (!data || typeof data !== "object") return []+ if (surface === "friends") {+ return (data as FriendsEnvelope).pending ?? []+ }+ return (data as InboxEnvelope).friendRequests ?? []+}++function surfaceForHash(queryHash: string): FriendRequestSurface | undefined {+ if (queryHash === friendsHash) return "friends"+ if (queryHash === inboxHash) return "inbox"+ return undefined+}++class FriendRequestActionController {+ private readonly actions = new Map<string, ActionEntry>()+ private readonly listeners = new Set<() => void>()+ private readonly readStarts = new Map<string, number>()+ private readonly terminals = new Map<string, TerminalFence>()+ private readonly userTerminals = new Map<string, UserTerminalFence>()+ private clock = 0+ private version = 0++ constructor(private readonly queryClient: QueryClient) {+ queryClient.getQueryCache().subscribe((event) => this.onQueryEvent(event))+ }++ subscribe = (listener: () => void) => {+ this.listeners.add(listener)+ return () => this.listeners.delete(listener)+ }++ getSnapshot = () => this.version++ private publish() {+ this.version += 1+ for (const listener of this.listeners) listener()+ }++ private captureCaches(id: string) {+ const friends = this.queryClient.getQueryData<FriendsEnvelope>(communityKeys.friends())+ const inbox = this.queryClient.getQueryData<InboxEnvelope>(communityKeys.inboxUnreads())+ return {+ friends: captureRow(friends?.pending ?? [], id),+ inbox: captureRow(inbox?.friendRequests ?? [], id),+ }+ }++ private refreshSnapshots(entry: ActionEntry, id: string) {+ const captured = this.captureCaches(id)+ if (captured.friends) entry.snapshots.friends = captured.friends+ if (captured.inbox) entry.snapshots.inbox = captured.inbox+ }++ claimMutation(id: string, action: FriendRequestAction) {+ const current = this.actions.get(id)+ if (current?.status === "pending") {+ this.refreshSnapshots(current, id)+ return current.generation+ }+ if (this.terminals.has(id)) return current?.generation ?? 0+ const entry: ActionEntry = {+ action,+ baselineEpoch: ++this.clock,+ generation: (current?.generation ?? 0) + 1,+ settled: false,+ snapshots: current?.snapshots ?? {},+ status: "pending",+ }+ this.refreshSnapshots(entry, id)+ this.actions.set(id, entry)+ this.publish()+ return entry.generation+ }++ isCompensatable(id: string, generation: number) {+ const entry = this.actions.get(id)+ return Boolean(+ entry+ && entry.generation === generation+ && !this.terminals.has(id),+ )+ }++ publishError(id: string, generation: number) {+ const entry = this.actions.get(id)+ if (+ !entry+ || entry.generation !== generation+ || this.terminals.has(id)+ || entry.status === "error"+ ) return false+ entry.status = "error"+ entry.promise = undefined+ this.publish()+ return true+ }++ publishTerminal(id: string, generation?: number) {+ const entry = this.actions.get(id)+ if (generation !== undefined && entry?.generation !== generation) return false+ if (this.terminals.has(id)) return true+ this.terminals.set(id, { epoch: ++this.clock, proofs: new Set() })+ this.publish()+ return true+ }++ publishTerminalForUser(userId: string) {+ const existingUserFence = this.userTerminals.get(userId)+ const epoch = existingUserFence?.epoch ?? ++this.clock+ let changed = false+ if (!existingUserFence) {+ this.userTerminals.set(userId, { epoch, proofs: new Set() })+ changed = true+ }+ const ids = new Set<string>()+ for (const [id, entry] of this.actions) {+ if (Object.values(entry.snapshots).some((snapshot) => snapshot?.row.userId === userId)) {+ ids.add(id)+ }+ }+ const caches = this.captureRowsBySurface()+ for (const row of [...caches.friends, ...caches.inbox]) {+ if (row.userId === userId) ids.add(row.id)+ }+ for (const id of ids) {+ if (this.terminals.has(id)) continue+ this.terminals.set(id, { epoch, proofs: new Set() })+ changed = true+ }+ if (changed) this.publish()+ }++ async fenceReads() {+ await Promise.all([+ this.queryClient.cancelQueries({ queryKey: communityKeys.friends(), exact: true }),+ this.queryClient.cancelQueries({ queryKey: communityKeys.inboxUnreads(), exact: true }),+ ])+ }++ async publishTerminalAndFence(id: string, generation: number) {+ if (!this.publishTerminal(id, generation)) return false+ const fence = this.terminals.get(id)!+ fence.cancellation ??= this.fenceReads()+ await fence.cancellation+ return true+ }++ settleGeneration(id: string, generation: number) {+ const entry = this.actions.get(id)+ if (!entry || entry.generation !== generation) return+ entry.settled = true+ this.collectTerminal(id)+ }++ private captureRowsBySurface() {+ const friends = this.queryClient.getQueryData<FriendsEnvelope>(communityKeys.friends())+ const inbox = this.queryClient.getQueryData<InboxEnvelope>(communityKeys.inboxUnreads())+ return {+ friends: friends?.pending ?? [],+ inbox: inbox?.friendRequests ?? [],+ }+ }++ private collectTerminal(id: string) {+ const fence = this.terminals.get(id)+ if (!fence || fence.proofs.size !== 2) return+ const entry = this.actions.get(id)+ if (entry && !entry.settled) return+ const rows = this.captureRowsBySurface()+ if (+ rows.friends.some((row) => row.id === id)+ || rows.inbox.some((row) => row.id === id)+ ) return+ this.terminals.delete(id)+ this.actions.delete(id)+ this.publish()+ }++ private collectUserTerminal(userId: string) {+ const fence = this.userTerminals.get(userId)+ if (!fence || fence.proofs.size !== 2) return+ const rows = this.captureRowsBySurface()+ if (+ rows.friends.some((row) => row.userId === userId)+ || rows.inbox.some((row) => row.userId === userId)+ ) return+ this.userTerminals.delete(userId)+ this.publish()+ }++ private onQueryEvent(event: QueryCacheNotifyEvent) {+ if (event.type !== "updated") return+ const surface = surfaceForHash(event.query.queryHash)+ if (!surface) return+ if (event.action.type === "fetch") {+ this.readStarts.set(event.query.queryHash, ++this.clock)+ return+ }+ if (event.action.type !== "success" || event.action.manual) return+ const startEpoch = this.readStarts.get(event.query.queryHash)+ if (startEpoch === undefined) return+ const rows = rowsFromEnvelope(surface, event.action.data)+ const rowsById = new Map(rows.map((row, index) => [row.id, { row, index }]))+ const knownIds = new Set([...this.actions.keys(), ...this.terminals.keys()])+ let snapshotsChanged = false++ for (const [userId, fence] of this.userTerminals) {+ if (startEpoch <= fence.epoch) continue+ if (rows.some((row) => row.userId === userId)) fence.proofs.delete(surface)+ else fence.proofs.add(surface)+ this.collectUserTerminal(userId)+ }++ for (const id of knownIds) {+ const row = rowsById.get(id)+ const fence = this.terminals.get(id)+ if (fence) {+ if (startEpoch > fence.epoch) {+ if (row) fence.proofs.delete(surface)+ else fence.proofs.add(surface)+ this.collectTerminal(id)+ }+ continue+ }+ const entry = this.actions.get(id)+ if (!entry) continue+ if (row) {+ entry.snapshots[surface] = row+ snapshotsChanged = true+ } else if (startEpoch > entry.baselineEpoch) {+ void this.publishTerminalAndFence(id, entry.generation)+ }+ }+ if (snapshotsChanged) this.publish()+ }++ project<T extends FriendRequestRow>(+ surface: FriendRequestSurface,+ rows: readonly T[],+ ): Array<ActionableFriendRequest<T>> {+ const merged: Array<ActionableFriendRequest<T>> = []+ const present = new Set<string>()+ for (const row of rows) {+ if (+ this.terminals.has(row.id)+ || (row.userId !== undefined && this.userTerminals.has(row.userId))+ ) continue+ present.add(row.id)+ const entry = this.actions.get(row.id)+ merged.push(this.toItem(row, entry))+ }+ for (const [id, entry] of this.actions) {+ if (present.has(id) || this.terminals.has(id)) continue+ const snapshot = entry.snapshots[surface]+ if (!snapshot) continue+ if (+ snapshot.row.userId !== undefined+ && this.userTerminals.has(snapshot.row.userId)+ ) continue+ merged.splice(Math.min(snapshot.index, merged.length), 0, this.toItem(+ snapshot.row as T,+ entry,+ ))+ }+ return merged+ }++ private toItem<T extends FriendRequestRow>(+ row: T,+ entry: ActionEntry | undefined,+ ): ActionableFriendRequest<T> {+ return {+ row,+ action: entry?.action,+ status: entry?.status,+ ...(entry?.status === "error"+ ? { error: `Couldn’t ${entry.action} this request. Try again.` }+ : {}),+ }+ }++ start<T extends FriendRequestRow>({+ action,+ index,+ mutation,+ retry,+ row,+ surface,+ }: {+ action: FriendRequestAction+ index: number+ mutation: (id: string) => Promise<unknown>+ retry: boolean+ row: T+ surface: FriendRequestSurface+ }) {+ if (+ this.terminals.has(row.id)+ || (row.userId !== undefined && this.userTerminals.has(row.userId))+ ) return Promise.resolve()+ const current = this.actions.get(row.id)+ if (current?.status === "pending" && current.promise) return current.promise+ if (retry && current?.status !== "error") return Promise.resolve()++ const entry: ActionEntry = {+ action,+ baselineEpoch: ++this.clock,+ generation: (current?.generation ?? 0) + 1,+ settled: false,+ snapshots: current?.snapshots ?? {},+ status: "pending",+ }+ this.refreshSnapshots(entry, row.id)+ entry.snapshots[surface] = { row, index }+ this.actions.set(row.id, entry)+ this.publish()++ const task = (async () => {+ try {+ await mutation(row.id)+ await this.publishTerminalAndFence(row.id, entry.generation)+ } catch {+ this.publishError(row.id, entry.generation)+ } finally {+ this.settleGeneration(row.id, entry.generation)+ }+ })()+ entry.promise = task+ return task+ }+}++export function getFriendRequestActionController(queryClient: QueryClient) {+ let controller = controllers.get(queryClient)+ if (!controller) {+ controller = new FriendRequestActionController(queryClient)+ controllers.set(queryClient, controller)+ }+ return controller+}++export function useFriendRequestActionState<T extends FriendRequestRow>({+ rows,+ onAccept,+ onReject,+ surface,+}: {+ rows: readonly T[]+ onAccept?: (id: string) => Promise<unknown>+ onReject?: (id: string) => Promise<unknown>+ surface: FriendRequestSurface+}) {+ const queryClient = useQueryClient()+ const controller = getFriendRequestActionController(queryClient)+ useSyncExternalStore(+ controller.subscribe,+ controller.getSnapshot,+ controller.getSnapshot,+ )+ const items = controller.project(surface, rows)++ const run = useCallback((+ item: ActionableFriendRequest<T>,+ action: FriendRequestAction,+ retry: boolean,+ ) => {+ const mutation = action === "accept" ? onAccept : onReject+ if (!mutation) return Promise.resolve()+ const index = items.findIndex((candidate) => candidate.row.id === item.row.id)+ return controller.start({+ action,+ index: Math.max(index, 0),+ mutation,+ retry,+ row: item.row,+ surface,+ })+ }, [controller, items, onAccept, onReject, surface])++ const act = useCallback((+ item: ActionableFriendRequest<T>,+ action: FriendRequestAction,+ ) => run(item, action, false), [run])++ const retry = useCallback((item: ActionableFriendRequest<T>) => (+ item.action ? run(item, item.action, true) : Promise.resolve()+ ), [run])++ return { items, act, retry }+}diff --git a/src/web/src/hooks/community/use-inbox.dom.test.ts b/src/web/src/hooks/community/use-inbox.dom.test.tsindex 06da2cdb8..75675b06c 100644--- a/src/web/src/hooks/community/use-inbox.dom.test.ts+++ b/src/web/src/hooks/community/use-inbox.dom.test.ts@@ -3,6 +3,7 @@ import { act, render as rtlRender } from "@/test/react-dom-harness"import { describe, it, expect, vi, beforeEach } from "vitest"import { QueryClient, QueryClientProvider } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"+import { useCommunityWsStore } from "@/stores/community/ws"import {disposeInboxReadReservation,inboxChannelRowTarget,@@ -20,6 +21,109 @@ beforeEach(() => {})describe("useInboxUnreads / inboxUnreadsQueryFn", () => {+ it("passes friend requests through, seeds their profile, and exposes the outstanding boolean", async () => {+ useCommunityWsStore.getState().reset()+ useCommunityWsStore.getState().activateProfileAccount("viewer")+ apiFetchMock.mockResolvedValueOnce({+ friendRequests: [{+ id: "fr_1",+ userId: "requester",+ name: "Ada",+ avatar: "avatar-url",+ avatarVersion: 7,+ createdAt: "2026-09-12T01:00:00Z",+ }],+ servers: [],+ dms: [],+ truncated: false,+ })+ const { useInboxUnreads } = await import("./use-inbox")+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ let latest: ReturnType<typeof useInboxUnreads> | undefined+ function Harness() {+ latest = useInboxUnreads()+ return null+ }+ const renderer = rtlRender(React.createElement(+ QueryClientProvider,+ { client: qc },+ React.createElement(Harness),+ ))++ await vi.waitFor(() => expect(latest?.friendRequests).toHaveLength(1))+ expect(latest?.hasOutstandingFriendRequest).toBe(true)+ expect(useCommunityWsStore.getState().profilesByUserId.get("requester")).toMatchObject({+ name: "Ada",+ avatar: "avatar-url",+ avatarVersion: 7,+ })+ expect(latest?.hasProjectedUnread).toBe(false)+ await act(async () => renderer.unmount())+ })++ it("seeds a DM peer profile while reading Inbox unreads", async () => {+ useCommunityWsStore.getState().reset()+ useCommunityWsStore.getState().activateProfileAccount("viewer")+ apiFetchMock.mockResolvedValueOnce({+ friendRequests: [],+ servers: [],+ dms: [{+ channelId: "dm_1",+ otherUserId: "peer",+ otherUserName: "Grace",+ otherUserDiscriminator: "0007",+ otherUserAvatar: "peer-avatar",+ otherUserAvatarVersion: 8,+ lastMessageAt: "2026-09-12T01:01:00Z",+ }],+ truncated: false,+ })+ const { inboxUnreadsQueryFn } = await import("./use-inbox")++ await inboxUnreadsQueryFn()++ expect(useCommunityWsStore.getState().profilesByUserId.get("peer")).toMatchObject({+ name: "Grace",+ discriminator: "0007",+ avatar: "peer-avatar",+ avatarVersion: 8,+ })+ })++ it("keeps last-good friend requests and their boolean after a stale refetch", async () => {+ const request = {+ id: "fr_1",+ userId: "requester",+ name: "Ada",+ avatar: "A",+ avatarVersion: 1,+ createdAt: "2026-09-12T01:00:00Z",+ }+ apiFetchMock+ .mockResolvedValueOnce({ friendRequests: [request], servers: [], dms: [], truncated: false })+ .mockResolvedValueOnce({ friendRequests: [], servers: [], dms: [], truncated: false, stale: true })+ const { useInboxUnreads } = await import("./use-inbox")+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ let latest: ReturnType<typeof useInboxUnreads> | undefined+ function Harness() {+ latest = useInboxUnreads()+ return null+ }+ const renderer = rtlRender(React.createElement(+ QueryClientProvider,+ { client: qc },+ React.createElement(Harness),+ ))+ await vi.waitFor(() => expect(latest?.friendRequests).toEqual([request]))+ await qc.invalidateQueries({ queryKey: communityKeys.inboxUnreads(), exact: true })+ await vi.waitFor(() => expect(latest?.isError).toBe(true))++ expect(latest?.friendRequests).toEqual([request])+ expect(latest?.hasOutstandingFriendRequest).toBe(true)+ expect(latest?.hasProjectedUnread).toBe(false)+ await act(async () => renderer.unmount())+ })+it("supports direct reads without a query context", async () => {apiFetchMock.mockResolvedValueOnce({ servers: [], dms: [] })const { inboxUnreadsQueryFn } = await import("./use-inbox")diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.tsindex 92633b09e..52c73f2ae 100644--- a/src/web/src/hooks/community/use-inbox.ts+++ b/src/web/src/hooks/community/use-inbox.ts@@ -5,7 +5,7 @@ import { useQuery, useQueryClient, keepPreviousData, type UseQueryResult } fromimport { apiFetch } from "@/lib/api/client"import { apiFetchProfiles, messageProfilePatches } from "@/lib/community/profile-seed"import { communityKeys } from "@/lib/query-keys"-import type { UnreadServer, UnreadDm, Mention, Marked } from "@/lib/community/models/inbox"+import type { UnreadServer, UnreadDm, InboxFriendRequest, Mention, Marked } from "@/lib/community/models/inbox"import {inboxMentionRowTarget,reserveInboxUnreadsResponse,@@ -33,6 +33,7 @@ function throwIfStale<T extends { stale?: boolean }>(v: T): T {// Frozen empty fallbacks — see `use-servers.ts` for the rationale.const EMPTY_UNREADS: readonly UnreadServer[] = Object.freeze([])const EMPTY_DMS: readonly UnreadDm[] = Object.freeze([])+const EMPTY_FRIEND_REQUESTS: readonly InboxFriendRequest[] = Object.freeze([])const EMPTY_MENTIONS: readonly Mention[] = Object.freeze([])const EMPTY_MARKED: readonly Marked[] = Object.freeze([])@@ -67,6 +68,7 @@ type ProjectedMention = Mention & {*/export type UnreadsResponse = {+ friendRequests: InboxFriendRequest[]servers: ProjectedUnreadServer[]dms: UnreadDm[]limit?: number@@ -77,17 +79,29 @@ const inboxUnreadsTransportFn = ({ signal }: { signal?: AbortSignal } = {}) =>apiFetchProfiles<UnreadsResponse & { stale?: boolean }>("/api/community/users/me/inbox/unreads",(data) => {- return data.dms.map((dm) => ({- id: dm.otherUserId,- identityAbout: {- name: dm.otherUserName,- discriminator: dm.otherUserDiscriminator,- },- avatar: {- avatar: dm.otherUserAvatar,- avatarVersion: dm.otherUserAvatarVersion,- },- }))+ return [+ ...(data.friendRequests ?? []).map((request) => ({+ id: request.userId,+ identityAbout: { name: request.name },+ ...(request.avatarVersion === null ? {} : {+ avatar: {+ avatar: request.avatar,+ avatarVersion: request.avatarVersion,+ },+ }),+ })),+ ...data.dms.map((dm) => ({+ id: dm.otherUserId,+ identityAbout: {+ name: dm.otherUserName,+ discriminator: dm.otherUserDiscriminator,+ },+ avatar: {+ avatar: dm.otherUserAvatar,+ avatarVersion: dm.otherUserAvatarVersion,+ },+ })),+ ]},{ signal },)@@ -173,9 +187,11 @@ export const inboxUnreadsProjectedQueryFn = (}export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {+ friendRequests: InboxFriendRequest[]servers: UnreadServer[]dms: UnreadDm[]hasProjectedUnread: boolean+ hasOutstandingFriendRequest: boolean} {const queryClient = useQueryClient()const unreadProjection = useMemo(@@ -298,6 +314,7 @@ export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {}, [channelExclusion, dmExclusion, query.data, unreadProjection, unreadVersion])return {...query,+ friendRequests: query.data?.friendRequests ?? (EMPTY_FRIEND_REQUESTS as InboxFriendRequest[]),servers: projected.servers ?? (EMPTY_UNREADS as UnreadServer[]),dms: projected.dms ?? (EMPTY_DMS as UnreadDm[]),hasProjectedUnread:@@ -305,6 +322,7 @@ export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {|| projected.dms.length > 0|| unreadProjection.hasPending("inbox-unreads", "channels", channelExclusion)|| unreadProjection.hasPending("inbox-unreads", "dms", dmExclusion),+ hasOutstandingFriendRequest: (query.data?.friendRequests?.length ?? 0) > 0,}}diff --git a/src/web/src/lib/community/friend-requests.test.ts b/src/web/src/lib/community/friend-requests.test.tsnew file mode 100644index 000000000..bba3be9f8--- /dev/null+++ b/src/web/src/lib/community/friend-requests.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from "vitest"+import { actionableIncomingRequests, compactRequestCount } from "./friend-requests"+import type { PendingRequest } from "./models/people"++const request = (+ id: string,+ kind: PendingRequest["kind"],+ needsOwnerApproval: string | null | undefined,+): PendingRequest => ({+ id,+ userId: `user-${id}`,+ name: id,+ avatar: id,+ avatarVersion: 0,+ kind,+ needsOwnerApproval,+})++describe("actionableIncomingRequests", () => {+ it("treats an absent legacy response field as an empty list", () => {+ expect(actionableIncomingRequests(undefined)).toEqual([])+ })++ it("keeps only incoming rows without an owner gate", () => {+ expect(actionableIncomingRequests([+ request("incoming-null", "incoming", null),+ request("incoming-legacy", "incoming", undefined),+ request("incoming-gated", "incoming", "owner"),+ request("outgoing", "outgoing", null),+ ]).map((row) => row.id)).toEqual(["incoming-null", "incoming-legacy"])+ })+})++describe("compactRequestCount", () => {+ it.each([+ [0, null],+ [1, "1"],+ [99, "99"],+ [100, "99+"],+ ])("formats %i as %s", (count, expected) => {+ expect(compactRequestCount(count)).toBe(expected)+ })+})diff --git a/src/web/src/lib/community/friend-requests.ts b/src/web/src/lib/community/friend-requests.tsnew file mode 100644index 000000000..cb816904f--- /dev/null+++ b/src/web/src/lib/community/friend-requests.ts@@ -0,0 +1,14 @@+import type { PendingRequest } from "./models/people"++export function actionableIncomingRequests(+ pending: readonly PendingRequest[] | null | undefined,+): PendingRequest[] {+ return (pending ?? []).filter(+ (request) => request.kind === "incoming" && request.needsOwnerApproval == null,+ )+}++export function compactRequestCount(count: number): string | null {+ if (count <= 0) return null+ return count > 99 ? "99+" : String(count)+}diff --git a/src/web/src/lib/community/models/inbox.ts b/src/web/src/lib/community/models/inbox.tsindex 34da4a2a0..0d5fb4e3a 100644--- a/src/web/src/lib/community/models/inbox.ts+++ b/src/web/src/lib/community/models/inbox.ts@@ -93,3 +93,12 @@ export type UnreadDm = {lastMessageAt: stringlastUnreadSeq?: number}++export type InboxFriendRequest = {+ id: string+ userId: string+ name: string+ avatar: string+ avatarVersion: number | null+ createdAt: string+}diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.tsindex 491c70a20..dadecce7c 100644--- a/src/web/src/lib/community/testids.ts+++ b/src/web/src/lib/community/testids.ts@@ -232,6 +232,12 @@ export const tid = {inboxUnreadChannel: (id: string) => `community-inbox-unread-channel-${id}`,inboxUnreadChild: (id: string) => `community-inbox-unread-child-${id}`,inboxUnreadDm: (id: string) => `community-inbox-unread-dm-${id}`,+ inboxFriendRequest: (id: string) => `community-inbox-friend-request-${id}`,+ inboxFriendRequestOpen: (id: string) => `community-inbox-friend-request-open-${id}`,+ inboxFriendRequestAccept: (id: string) => `community-inbox-friend-request-accept-${id}`,+ inboxFriendRequestReject: (id: string) => `community-inbox-friend-request-reject-${id}`,+ friendsShortcutBadge: "community-friends-shortcut-badge",+ friendsNewBadge: "community-friends-new-badge",userBar: "community-user-bar",userBarName: "community-user-bar-name",userBarExtension: "community-user-bar-extension",diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.tsindex 8c6576713..1556b14b6 100644--- a/src/web/src/lib/use-user-ws.test.ts+++ b/src/web/src/lib/use-user-ws.test.ts@@ -1000,6 +1000,73 @@ describe("useUserWs", () => {expect(mockFetch).toHaveBeenCalledTimes(fetchCount)})+ it("reconciles one offline event gap after exact retained-socket validation", async () => {+ setupTokenFetch()+ const onMessage = vi.fn()+ const onReconnect = vi.fn()+ await mountHook(onMessage, { onReconnect, requestDaemonStatusOnAuth: false })+ const ws = MockWebSocket.instances[0]!+ ws.simulateOpen()+ ws.simulateMessage({ type: "auth.ok" })++ vi.setSystemTime(new Date("2026-09-12T00:00:00.000Z"))+ mockNavigator.onLine = false+ mockWindow.dispatch("offline")+ ws.simulateMessage({ type: "task.updated", taskId: "missed-offline" })+ expect(onMessage).not.toHaveBeenCalled()++ vi.setSystemTime(new Date("2026-09-12T00:00:02.500Z"))+ mockNavigator.onLine = true+ mockWindow.dispatch("online")+ const [{ nonce }] = connectionPings(ws)+ ws.simulateMessage({ type: "connection.pong", nonce })++ expect(onReconnect).toHaveBeenCalledOnce()+ expect(onReconnect).toHaveBeenCalledWith({ reconnectDurationMs: 2_500 })++ ws.simulateMessage({ type: "connection.pong", nonce })+ dispatchWindowFocus()+ const nextNonce = connectionPings(ws).at(-1)!.nonce+ expect(nextNonce).not.toBe(nonce)+ ws.simulateMessage({ type: "connection.pong", nonce })+ ws.simulateMessage({ type: "connection.pong", nonce: nextNonce })+ expect(onReconnect).toHaveBeenCalledOnce()+ })++ it("defers offline gap reconciliation to replacement auth after validation failure", async () => {+ setupTokenFetch()+ const onReconnect = vi.fn()+ const mod = await mountHook(vi.fn(), { onReconnect, requestDaemonStatusOnAuth: false })+ const first = MockWebSocket.instances[0]!+ first.simulateOpen()+ first.simulateMessage({ type: "auth.ok" })++ vi.setSystemTime(new Date("2026-09-12T00:00:00.000Z"))+ mockNavigator.onLine = false+ mockWindow.dispatch("offline")+ vi.setSystemTime(new Date("2026-09-12T00:00:01.000Z"))+ mockNavigator.onLine = true+ mockWindow.dispatch("online")+ const [{ nonce }] = connectionPings(first)++ await vi.advanceTimersByTimeAsync(mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS)+ await flushPromises()+ expect(first.closed).toBe(true)+ expect(onReconnect).not.toHaveBeenCalled()++ first.simulateMessage({ type: "connection.pong", nonce })+ const replacement = MockWebSocket.instances.at(-1)!+ expect(replacement).not.toBe(first)+ replacement.simulateOpen()+ replacement.simulateMessage({ type: "auth.ok" })+ replacement.simulateMessage({ type: "auth.ok" })++ expect(onReconnect).toHaveBeenCalledOnce()+ expect(onReconnect).toHaveBeenCalledWith({+ reconnectDurationMs: 1_000 + mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS,+ })+ })+it("applies offline cleanup after send observes the browser offline before the event", async () => {setupTokenFetch()const onConnectionStateChange = vi.fn()diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.tsindex e18d0bc7d..c2e9c99c9 100644--- a/src/web/src/lib/use-user-ws.ts+++ b/src/web/src/lib/use-user-ws.ts@@ -669,12 +669,21 @@ export function useUserWs(&& pending.nonce === msg.nonce&& authenticatedGenerationRef.current === generation) {+ const disconnectedAt = disconnectedAtRef.currentclearConnectionValidation("success")publishConnectionPhase("authenticated")if (isOffline()|| !ownsAuthenticatedConnection(ws, generation)) return+ if (disconnectedAt !== null) {+ disconnectedAtRef.current = null+ runLifecycleCallback("reconnect", () =>+ onReconnectRef.current?.({+ reconnectDurationMs: Math.max(0, Date.now() - disconnectedAt),+ }))+ if (isOffline() || !ownsAuthenticatedConnection(ws, generation)) return+ }startHeartbeat(ws, generation)}return@@ -857,7 +866,9 @@ export function useUserWs(const retainAuthenticatedSocket = ws? ownsAuthenticatedConnection(ws, generation): false- if (!retainAuthenticatedSocket) {+ if (retainAuthenticatedSocket) {+ disconnectedAtRef.current ??= Date.now()+ } else {connectionGenerationRef.current += 1retireSocket(true, "offline")}diff --git a/src/web/src/test/e2e-ui/56-inbox-friend-requests.spec.ts b/src/web/src/test/e2e-ui/56-inbox-friend-requests.spec.tsnew file mode 100644index 000000000..fc67b8e6e--- /dev/null+++ b/src/web/src/test/e2e-ui/56-inbox-friend-requests.spec.ts@@ -0,0 +1,399 @@+import type { Locator, Page } from "@playwright/test"+import { expect, test, userId, userName } from "./_fixtures/community-fixture"+import { gotoAfterUserWsAuth } from "./_fixtures/actions"+import {+ seedCancelFriendRequest,+ seedChannel,+ seedDm,+ seedDmMessage,+ seedJoinServer,+ seedMessage,+ seedPendingFriendRequest,+ seedServer,+} from "./_fixtures/seed"+import { tid } from "./_fixtures/testids"++async function expectInboxDot(page: Page) {+ await expect(page.getByTestId(tid.inboxTrigger).locator("span.bg-primary")).toHaveCount(1)+}++async function expectNoInboxDot(page: Page) {+ await expect(page.getByTestId(tid.inboxTrigger).locator("span.bg-primary")).toHaveCount(0)+}++async function clearMessageInbox(page: Page) {+ 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 page.request.post(path)).ok()).toBe(true)+ }+}++async function clientRect(locator: Locator) {+ return locator.evaluate((element) => {+ const { width, height } = element.getBoundingClientRect()+ return { width, height }+ })+}++async function siblingActionStructure(+ navigation: Locator,+ acceptName: string,+ rejectName: string,+) {+ return navigation.evaluate((node, names) => {+ const layout = node.parentElement+ const row = layout?.parentElement+ const buttons = Array.from(row?.querySelectorAll("button") ?? [])+ const accept = buttons.find((button) => button.getAttribute("aria-label") === names.acceptName)+ const reject = buttons.find((button) => button.getAttribute("aria-label") === names.rejectName)+ return {+ actionsAreSiblings: accept?.parentElement?.parentElement === layout+ && reject?.parentElement?.parentElement === layout,+ navigationContainsAction: Boolean(accept && node.contains(accept))+ || Boolean(reject && node.contains(reject)),+ nestedInteractiveCount: row?.querySelectorAll("button button").length ?? -1,+ }+ }, { acceptName, rejectName })+}++function expectMinimumRect(+ label: string,+ rect: { width: number; height: number },+ minimum: number,+) {+ expect.soft(rect.width, `${label} width`).toBeGreaterThanOrEqual(minimum)+ expect.soft(rect.height, `${label} height`).toBeGreaterThanOrEqual(minimum)+}++async function expectExactRect(+ label: string,+ locator: Locator,+ size: number,+) {+ await expect.poll(+ () => clientRect(locator),+ { message: `${label} stable rect` },+ ).toEqual({ width: size, height: size })+}++test.describe.serial("actionable Inbox friend requests", () => {+ test.setTimeout(120_000)++ test("fans out live, survives opening, and owns the Friends New URL", async ({ asUser }) => {+ const bob = await asUser("bob")+ await bob.page.setViewportSize({ width: 1280, height: 900 })+ await clearMessageInbox(bob.page)+ await gotoAfterUserWsAuth(bob.page, "/c/me/friends")++ const friendshipId = await seedPendingFriendRequest("alice", "bob", userId("bob"))+ try {+ await expect(bob.page.getByTestId(tid.friendsShortcutBadge)).toHaveText("1")+ await expect(bob.page.getByTestId(tid.friendsNewBadge)).toHaveText("1")+ await expectInboxDot(bob.page)++ const trigger = bob.page.getByTestId(tid.inboxTrigger)+ await trigger.click()+ const row = bob.page.getByTestId(tid.inboxFriendRequest(friendshipId))+ await expect(row).toBeVisible()+ await expect(bob.page.getByText("Friend requests — 1", { exact: true })).toBeVisible()+ await expect(bob.page.getByText("Caught up", { exact: true })).toHaveCount(0)+ await expect(bob.page.getByRole("button", { name: "Mark all read" })).toBeDisabled()++ await trigger.click()+ await expectInboxDot(bob.page)+ await trigger.click()+ await expect(row).toBeVisible()++ const open = bob.page.getByTestId(tid.inboxFriendRequestOpen(friendshipId))+ const accept = bob.page.getByTestId(tid.inboxFriendRequestAccept(friendshipId))+ const reject = bob.page.getByTestId(tid.inboxFriendRequestReject(friendshipId))+ expect(await open.evaluate((node, actionIds) => (+ actionIds.every((id) => !node.contains(document.querySelector(`[data-testid='${id}']`)))+ ), [tid.inboxFriendRequestAccept(friendshipId), tid.inboxFriendRequestReject(friendshipId)])).toBe(true)+ await expect(accept).toHaveAccessibleName(/Accept .+ friend request/)+ await expect(reject).toHaveAccessibleName(/Reject .+ friend request/)++ await open.click()+ await expect(bob.page).toHaveURL(/\/c\/me\/friends\?tab=new$/)+ await expect(bob.page.getByRole("tab", { name: /New/ })).toHaveAttribute("aria-selected", "true")+ } finally {+ await seedCancelFriendRequest("alice", friendshipId)+ }+ })++ test("keeps requests above DM/server unread and Mark all is message-only", async ({ asUser }) => {+ const stamp = Date.now()+ const serverName = `Friend request mix ${stamp}`+ const serverId = await seedServer("alice", serverName)+ const channelId = await seedChannel("alice", serverId, `friend-mix-${stamp}`)+ await seedJoinServer("alice", "bob", serverId)+ const dmId = await seedDm("alice", userId("bob"))++ const bob = await asUser("bob")+ await clearMessageInbox(bob.page)+ await gotoAfterUserWsAuth(bob.page, "/c/me/friends")+ const friendshipId = await seedPendingFriendRequest("carol", "bob", userId("bob"))+ try {+ await seedMessage("alice", channelId, `Friend request channel unread ${stamp}`)+ await seedDmMessage("alice", dmId, `Friend request DM unread ${stamp}`)++ await expectInboxDot(bob.page)+ await bob.page.getByTestId(tid.inboxTrigger).click()+ const requestRow = bob.page.getByTestId(tid.inboxFriendRequest(friendshipId))+ const dmRow = bob.page.getByTestId(tid.inboxUnreadDm(dmId))+ const serverRow = bob.page.getByTestId(tid.inboxUnreadChannel(channelId))+ await expect(requestRow).toBeVisible()+ await expect(dmRow).toBeVisible()+ await expect(serverRow).toBeVisible()++ const [requestBox, dmBox, serverBox] = await Promise.all([+ requestRow.boundingBox(),+ dmRow.boundingBox(),+ serverRow.boundingBox(),+ ])+ expect(requestBox).not.toBeNull()+ expect(dmBox).not.toBeNull()+ expect(serverBox).not.toBeNull()+ expect(requestBox!.y).toBeLessThan(dmBox!.y)+ expect(dmBox!.y).toBeLessThan(serverBox!.y)++ await bob.page.getByRole("button", { name: "Mark all read" }).click()+ await expect(requestRow).toBeVisible()+ await expect(dmRow).toHaveCount(0)+ await expect(serverRow).toHaveCount(0)+ await expect(bob.page.getByRole("button", { name: "Mark all read" })).toBeDisabled()+ await expectInboxDot(bob.page)+ } finally {+ await seedCancelFriendRequest("carol", friendshipId)+ }+ })++ test("a failed action keeps its keyed row while another request remains usable", async ({ asUser }) => {+ const firstId = await seedPendingFriendRequest("alice", "bob", userId("bob"))+ const secondId = await seedPendingFriendRequest("carol", "bob", userId("bob"))+ const bob = await asUser("bob")+ let releaseFailure!: () => void+ let markFirstAttempt!: () => void+ const failureGate = new Promise<void>((resolve) => { releaseFailure = resolve })+ const firstAttempt = new Promise<void>((resolve) => { markFirstAttempt = resolve })+ let attempts = 0+ await bob.page.route(`**/api/community/friends/${firstId}/accept`, async (route) => {+ attempts += 1+ if (attempts === 1) {+ markFirstAttempt()+ await failureGate+ await route.fulfill({ status: 503, json: { error: "forced retry" } })+ return+ }+ await route.continue()+ })++ try {+ await clearMessageInbox(bob.page)+ await gotoAfterUserWsAuth(bob.page, "/c/me/friends")+ await expect(bob.page.getByTestId(tid.friendsShortcutBadge)).toHaveText("2")+ await expect(bob.page.getByTestId(tid.friendsNewBadge)).toHaveText("2")+ await bob.page.getByTestId(tid.inboxTrigger).click()++ const firstRow = bob.page.getByTestId(tid.inboxFriendRequest(firstId))+ const secondRow = bob.page.getByTestId(tid.inboxFriendRequest(secondId))+ const firstAccept = bob.page.getByTestId(tid.inboxFriendRequestAccept(firstId))+ const secondReject = bob.page.getByTestId(tid.inboxFriendRequestReject(secondId))+ await firstAccept.click()+ await firstAttempt+ await expect(firstRow).toHaveAttribute("aria-busy", "true")+ await expect(firstAccept).toBeDisabled()+ await expect(secondReject).toBeEnabled()+ await expect(bob.page).toHaveURL(/\/c\/me\/friends$/)++ releaseFailure()+ await expect(firstRow.getByRole("status")).toContainText("Couldn’t accept")+ await expect(firstRow.getByRole("button", { name: "Retry" })).toBeVisible()+ await expect(bob.page.getByText("Friend requests — 2", { exact: true })).toBeVisible()+ await expect(bob.page.getByTestId(tid.friendsShortcutBadge)).toHaveText("2")++ await firstRow.getByRole("button", { name: "Retry" }).click()+ await expect(firstRow).toHaveCount(0)+ await expect(bob.page.getByText("Friend requests — 1", { exact: true })).toBeVisible()+ await expect(bob.page.getByTestId(tid.friendsShortcutBadge)).toHaveText("1")+ await expect(bob.page.getByTestId(tid.friendsNewBadge)).toHaveText("1")++ await secondReject.focus()+ await expect(secondReject).toBeFocused()+ await secondReject.press("Enter")+ await expect(secondRow).toHaveCount(0)+ await expect(bob.page.getByTestId(tid.friendsShortcutBadge)).toHaveCount(0)+ await expect(bob.page.getByTestId(tid.friendsNewBadge)).toHaveCount(0)+ await expectNoInboxDot(bob.page)++ await bob.page.getByTestId(tid.inboxTrigger).click()+ await bob.page.getByRole("button", { name: "Friends", exact: true }).click()+ const accepted = await bob.page.request.get("/api/community/friends/accepted")+ expect(accepted.ok()).toBe(true)+ const acceptedBody = await accepted.json() as { friends: Array<{ userId: string; name: string }> }+ const alice = acceptedBody.friends.find((friend) => friend.userId === userId("alice"))+ expect(alice).toBeDefined()+ await expect(bob.page.getByText(alice!.name, { exact: true }).first()).toBeVisible()+ } finally {+ releaseFailure()+ await bob.page.unroute(`**/api/community/friends/${firstId}/accept`)+ await seedCancelFriendRequest("alice", firstId)+ await seedCancelFriendRequest("carol", secondId)+ }+ })++ test("reconnect reconciles a request cancelled while its event was missed", async ({ asUser }) => {+ const bob = await asUser("bob")+ await gotoAfterUserWsAuth(bob.page, "/c/me/friends")+ const friendshipId = await seedPendingFriendRequest("dave", "bob", userId("bob"))+ const row = bob.page.getByTestId(tid.inboxFriendRequest(friendshipId))++ try {+ await bob.page.getByTestId(tid.inboxTrigger).click()+ await expect(row).toBeVisible()+ await bob.context.setOffline(true)+ await seedCancelFriendRequest("dave", friendshipId)+ await expect(row).toBeVisible()+ await bob.context.setOffline(false)+ await expect(row).toHaveCount(0, { timeout: 30_000 })+ } finally {+ await bob.context.setOffline(false)+ await seedCancelFriendRequest("dave", friendshipId)+ }+ })++ test("mobile actions keep 44px targets, readable labels, focus, and row-local busy state", async ({ asUser }) => {+ const stamp = Date.now()+ const serverId = await seedServer("alice", `Friend request mobile ${stamp}`)+ await seedChannel("alice", serverId, `friend-mobile-${stamp}`)+ await seedJoinServer("alice", "bob", serverId)+ const bob = await asUser("bob")+ await bob.page.setViewportSize({ width: 390, height: 844 })+ await clearMessageInbox(bob.page)+ await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}`)+ const inboxTrigger = bob.page.getByTestId(tid.inboxTrigger)+ await expect(inboxTrigger).toBeVisible()+ const startingUrl = bob.page.url()+ const friendshipId = await seedPendingFriendRequest("alice", "bob", userId("bob"))++ try {+ await inboxTrigger.click()+ const inboxSurface = bob.page.getByTestId(tid.userBarExtension)+ await expect(inboxSurface).toBeVisible()+ await expect(inboxSurface).toHaveAttribute("data-extension", "inbox")+ const row = bob.page.getByTestId(tid.inboxFriendRequest(friendshipId))+ const accept = bob.page.getByTestId(tid.inboxFriendRequestAccept(friendshipId))+ const reject = bob.page.getByTestId(tid.inboxFriendRequestReject(friendshipId))+ await expect(accept).toHaveAccessibleName(/Accept .+ friend request/)+ await expect(reject).toHaveAccessibleName(/Reject .+ friend request/)+ for (const action of [accept, reject]) {+ const box = await action.boundingBox()+ expect(box).not.toBeNull()+ expect(box!.width).toBeGreaterThanOrEqual(44)+ expect(box!.height).toBeGreaterThanOrEqual(44)+ }++ await reject.focus()+ await expect(reject).toBeFocused()+ const response = bob.page.waitForResponse((candidate) => (+ candidate.request().method() === "POST"+ && new URL(candidate.url()).pathname === `/api/community/friends/${friendshipId}/reject`+ ))+ await reject.press("Enter")+ expect((await response).status()).toBe(200)+ await expect(row).toHaveCount(0)+ expect(bob.page.url()).toBe(startingUrl)+ } finally {+ await seedCancelFriendRequest("alice", friendshipId)+ }+ })++ test("locks 390px navigation and retry targets plus 640px action geometry on both surfaces", async ({ asUser }) => {+ const stamp = Date.now()+ const serverId = await seedServer("alice", `Friend request geometry ${stamp}`)+ await seedChannel("alice", serverId, `friend-geometry-${stamp}`)+ await seedJoinServer("alice", "bob", serverId)+ const inboxRequestId = await seedPendingFriendRequest("alice", "bob", userId("bob"))+ const friendsRequestId = await seedPendingFriendRequest("carol", "bob", userId("bob"))+ const bob = await asUser("bob")+ const inboxAcceptPath = `/api/community/friends/${inboxRequestId}/accept`+ const friendsAcceptPath = `/api/community/friends/${friendsRequestId}/accept`+ await bob.page.route(`**${inboxAcceptPath}`, async (route) => {+ await route.fulfill({ status: 503, json: { error: "forced inbox geometry retry" } })+ })+ await bob.page.route(`**${friendsAcceptPath}`, async (route) => {+ await route.fulfill({ status: 503, json: { error: "forced friends geometry retry" } })+ })++ try {+ await bob.page.setViewportSize({ width: 390, height: 844 })+ await clearMessageInbox(bob.page)+ await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}`)++ const inboxTrigger = bob.page.getByTestId(tid.inboxTrigger)+ await inboxTrigger.click()+ const inboxRow = bob.page.getByTestId(tid.inboxFriendRequest(inboxRequestId))+ await expect(inboxRow).toBeVisible()+ const inboxNavigation = bob.page.getByTestId(tid.inboxFriendRequestOpen(inboxRequestId))+ const inboxAccept = bob.page.getByTestId(tid.inboxFriendRequestAccept(inboxRequestId))+ const inboxReject = bob.page.getByTestId(tid.inboxFriendRequestReject(inboxRequestId))+ const inboxAcceptName = `Accept ${userName("alice")}'s friend request`+ const inboxRejectName = `Reject ${userName("alice")}'s friend request`+ const inboxStructure = await siblingActionStructure(inboxNavigation, inboxAcceptName, inboxRejectName)+ expect.soft(inboxStructure.actionsAreSiblings, "Inbox navigation/action groups are siblings").toBe(true)+ expect.soft(inboxStructure.navigationContainsAction, "Inbox navigation has no nested action").toBe(false)+ expect.soft(inboxStructure.nestedInteractiveCount, "Inbox row has no nested interactive control").toBe(0)+ expectMinimumRect("390px Inbox navigation", await clientRect(inboxNavigation), 44)+ expectMinimumRect("390px Inbox Accept", await clientRect(inboxAccept), 44)+ expectMinimumRect("390px Inbox Reject", await clientRect(inboxReject), 44)++ await inboxAccept.click()+ const inboxRetry = inboxRow.getByRole("button", { name: "Retry" })+ await expect(inboxRetry).toBeVisible()+ expectMinimumRect("390px Inbox Retry", await clientRect(inboxRetry), 44)++ await inboxNavigation.click()+ await expect(bob.page).toHaveURL(/\/c\/me\/friends\?tab=new$/)+ const friendsName = userName("carol")+ const friendsNavigation = bob.page.getByRole("button", { name: friendsName, exact: true })+ const friendsRow = friendsNavigation.locator("..").locator("..")+ const friendsAcceptName = `Accept ${friendsName}'s friend request`+ const friendsRejectName = `Reject ${friendsName}'s friend request`+ const friendsAccept = friendsRow.getByRole("button", { name: friendsAcceptName })+ const friendsReject = friendsRow.getByRole("button", { name: friendsRejectName })+ await expect(friendsNavigation).toBeVisible()+ const friendsStructure = await siblingActionStructure(friendsNavigation, friendsAcceptName, friendsRejectName)+ expect.soft(friendsStructure.actionsAreSiblings, "Friends navigation/action groups are siblings").toBe(true)+ expect.soft(friendsStructure.navigationContainsAction, "Friends navigation has no nested action").toBe(false)+ expect.soft(friendsStructure.nestedInteractiveCount, "Friends row has no nested interactive control").toBe(0)+ expectMinimumRect("390px Friends profile navigation", await clientRect(friendsNavigation), 44)+ expectMinimumRect("390px Friends Accept", await clientRect(friendsAccept), 44)+ expectMinimumRect("390px Friends Reject", await clientRect(friendsReject), 44)++ await friendsAccept.click()+ const friendsRetry = friendsRow.getByRole("button", { name: "Retry" })+ await expect(friendsRetry).toBeVisible()+ expectMinimumRect("390px Friends Retry", await clientRect(friendsRetry), 44)++ await bob.page.setViewportSize({ width: 640, height: 900 })+ await bob.page.evaluate(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())))+ await expectExactRect("640px Friends Accept", friendsAccept, 32)+ await expectExactRect("640px Friends Reject", friendsReject, 32)++ await inboxTrigger.click()+ await expect(inboxRow).toBeVisible()+ await expectExactRect("640px Inbox Accept", inboxAccept, 32)+ await expectExactRect("640px Inbox Reject", inboxReject, 32)+ } finally {+ if (!bob.page.isClosed()) {+ await bob.page.unroute(`**${inboxAcceptPath}`)+ await bob.page.unroute(`**${friendsAcceptPath}`)+ }+ await seedCancelFriendRequest("alice", inboxRequestId)+ await seedCancelFriendRequest("carol", friendsRequestId)+ }+ })+})diff --git a/src/web/src/test/e2e-ui/_fixtures/seed.ts b/src/web/src/test/e2e-ui/_fixtures/seed.tsindex 02aff5667..8e51bbd6f 100644--- a/src/web/src/test/e2e-ui/_fixtures/seed.ts+++ b/src/web/src/test/e2e-ui/_fixtures/seed.ts@@ -1,5 +1,5 @@import { WEB_URL } from "../_setup/paths"-import { sessionCookie } from "./community-fixture"+import { sessionCookie, userId } from "./community-fixture"import type { UserKey } from "../_setup/users"import { isRetryableSeedStatus, retrySeedRequest, seedRetryDelayMs } from "./seed-retry"@@ -124,6 +124,84 @@ async function findFriendshipId(requester: UserKey, targetUserId: string): Promireturn data.friends.find((f) => f.userId === targetUserId)?.id}+type SeedRelationship = {+ id: string+ userId: string+ kind?: "incoming" | "outgoing"+}++async function listSeedRelationships(key: UserKey): Promise<{+ accepted: SeedRelationship[]+ pending: SeedRelationship[]+}> {+ const headers = { Cookie: sessionCookie(key), Origin: WEB_URL }+ const [accepted, pending] = await Promise.all([+ retrySeedRequest(() => fetch(`${WEB_URL}/api/community/friends/accepted`, { headers })),+ retrySeedRequest(() => fetch(`${WEB_URL}/api/community/friends/pending`, { headers })),+ ])+ if (!accepted.ok) throw new Error(`listSeedRelationships accepted failed (${accepted.status})`)+ if (!pending.ok) throw new Error(`listSeedRelationships pending failed (${pending.status})`)+ return {+ accepted: ((await accepted.json()) as { friends: SeedRelationship[] }).friends,+ pending: ((await pending.json()) as { pending: SeedRelationship[] }).pending,+ }+}++async function deleteSeedRelationship(key: UserKey, id: string): Promise<Response> {+ return retrySeedRequest(() => fetch(`${WEB_URL}/api/community/friends/${id}`, {+ method: "DELETE",+ headers: { Cookie: sessionCookie(key), Origin: WEB_URL },+ }))+}++// Normalize a human-to-human pair to one actionable pending request. This uses+// only the public HTTP routes and is repeatable after an earlier E2E spec (or a+// Playwright retry) left the pair accepted, blocked, or pending in either+// direction.+export async function seedPendingFriendRequest(+ requester: UserKey,+ addressee: UserKey,+ targetUserId: string,+): Promise<string> {+ await Promise.all([+ post(requester, `/api/community/users/${targetUserId}/unblock`),+ post(addressee, `/api/community/users/${userId(requester)}/unblock`),+ ])++ const relationships = await listSeedRelationships(requester)+ const accepted = relationships.accepted.find((row) => row.userId === targetUserId)+ if (accepted) {+ const response = await deleteSeedRelationship(requester, accepted.id)+ if (!response.ok) throw new Error(`seedPendingFriendRequest remove failed (${response.status})`)+ }+ const pending = relationships.pending.find((row) => row.userId === targetUserId)+ if (pending) {+ const response = pending.kind === "outgoing"+ ? await deleteSeedRelationship(requester, pending.id)+ : await post(requester, `/api/community/friends/${pending.id}/reject`)+ if (!response.ok) throw new Error(`seedPendingFriendRequest clear pending failed (${response.status})`)+ }++ const response = await retrySeedRequest(() => postRaw(+ requester,+ "/api/community/friends/request",+ { userId: targetUserId },+ ))+ if (!response.ok) throw new Error(`seedPendingFriendRequest request failed (${response.status})`)+ const body = (await response.json()) as { id?: string; friendship?: { id: string } | null }+ const id = body.id ?? body.friendship?.id+ if (!id) throw new Error("seedPendingFriendRequest: no friendship id in response")+ return id+}++// Withdraw a pending request through the same route used by the product. A+// terminal/missing row is already cancelled for fixture-cleanup purposes.+export async function seedCancelFriendRequest(requester: UserKey, friendshipId: string): Promise<void> {+ const response = await deleteSeedRelationship(requester, friendshipId)+ if (response.ok || response.status === 400 || response.status === 404) return+ throw new Error(`seedCancelFriendRequest failed (${response.status})`)+}+// Full friend handshake: requester sends, addressee accepts (accept is// addressee-only, hence two keys). Returns the friendship id. Idempotent on a// Playwright retry: if the pair is already friends the request 409s, so we