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
refactor(community): drop Inbox "For You" tab, keep Unreads + Mentions
Gener87d4ce9aab02
diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.tsindex 0efa667c2..4924584f8 100644--- a/src/shared/src/db/community-schema.ts+++ b/src/shared/src/db/community-schema.ts@@ -458,23 +458,3 @@ export const communityBotApprovalRequest = sqliteTable((t) => [index("idx_community_bot_approval_bot").on(t.botId, t.status)]);-// 21. community_inbox_dismissal-// Tracks which "For You" inbox events the user has hard-dismissed.-// eventKey is opaque, formed like "mention:<messageId>" / "reply:<messageId>" /-// "thread:<channelId>". Once dismissed, the corresponding event is filtered out-// of /api/community/inbox/foryou permanently.-export const communityInboxDismissal = sqliteTable(- "community_inbox_dismissal",- {- id: text("id").primaryKey().$defaultFn(() => nanoid()),- userId: text("user_id")- .notNull()- .references(() => user.id, { onDelete: "cascade" }),- eventKey: text("event_key").notNull(),- dismissedAt: text("dismissed_at").notNull().$defaultFn(() => new Date().toISOString()),- },- (t) => [- unique("uq_inbox_dismissal_user_event").on(t.userId, t.eventKey),- index("idx_inbox_dismissal_user").on(t.userId),- ]-);diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.tsindex 11677acb8..3e30fbd53 100644--- a/src/shared/src/db/queries/community/inbox.ts+++ b/src/shared/src/db/queries/community/inbox.ts@@ -1,42 +1,12 @@-import { and, desc, eq, inArray, isNotNull, isNull } from "drizzle-orm";+import { and, eq, isNotNull, isNull } from "drizzle-orm";import {communityChannel,- communityInboxDismissal,- communityMention,- communityMessage,communityReadState,communityServer,communityServerMember,} from "../../community-schema";-import { user } from "../../schema";import type { Database } from "../../index";-const FOR_YOU_LIMIT_DEFAULT = 50;-// Cap the number of "I participated in this thread" channels we scan per-// user. Without this, a power user who has chimed in on hundreds of threads-// would join + return all of them every time the For You feed is refetched.-// 30 keeps the work bounded while still covering everything a user is-// realistically still tracking.-const THREAD_PARTICIPATION_LIMIT = 30;-const PREVIEW_LEN = 140;--export type ForYouKind = "mention" | "reply" | "thread";--export interface ForYouEventRow {- eventKey: string;- kind: ForYouKind;- serverId: string;- serverName: string;- channelId: string;- channelName: string;- messageId: string;- authorId: string;- authorName: string;- authorAvatar: string;- preview: string;- createdAt: string;-}-export interface UnreadChannelRow {channelId: string;channelName: string;@@ -46,204 +16,6 @@ export interface UnreadChannelRow {lastReadAt: string | null;}-function buildEventKey(kind: ForYouKind, id: string): string {- return `${kind}:${id}`;-}--function previewOf(content: string): string {- const trimmed = content.trim();- return trimmed.length > PREVIEW_LEN ? `${trimmed.slice(0, PREVIEW_LEN)}…` : trimmed;-}--// ──────────────────────────────────────────────────────────────────────────────-// For You-// ──────────────────────────────────────────────────────────────────────────────--export async function listForYouEvents(- db: Database,- userId: string,- opts: { limit?: number } = {}-): Promise<ForYouEventRow[]> {- const limit = opts.limit ?? FOR_YOU_LIMIT_DEFAULT;-- // 1. Unread mention rows — kind is "mention" or "reply", carried straight through.- const mentionRows = await db- .select({- kind: communityMention.kind,- messageId: communityMessage.id,- channelId: communityMessage.channelId,- authorId: communityMessage.authorId,- authorName: user.name,- authorEmail: user.email,- authorImage: user.image,- content: communityMessage.content,- createdAt: communityMessage.createdAt,- })- .from(communityMention)- .innerJoin(communityMessage, eq(communityMention.messageId, communityMessage.id))- .innerJoin(user, eq(communityMessage.authorId, user.id))- .where(- and(- eq(communityMention.userId, userId),- eq(communityMention.read, 0),- isNotNull(communityMessage.channelId)- )- );-- // 3. Threads I participate in that have new messages.- // Participation = I authored a message in a child channel (parentChannelId- // IS NOT NULL). We rank by the thread's last activity so a long-time user- // with hundreds of past threads still sees only the most relevant ones.- const participatedThreadsRaw = await db- .selectDistinct({- channelId: communityMessage.channelId,- lastMessageAt: communityChannel.lastMessageAt,- })- .from(communityMessage)- .innerJoin(communityChannel, eq(communityMessage.channelId, communityChannel.id))- .where(- and(- eq(communityMessage.authorId, userId),- isNotNull(communityChannel.parentChannelId),- isNotNull(communityChannel.lastMessageAt)- )- )- .orderBy(desc(communityChannel.lastMessageAt))- .limit(THREAD_PARTICIPATION_LIMIT);- const threadChannelIds = participatedThreadsRaw- .map((r) => r.channelId)- .filter((id): id is string => !!id);-- let threadRows: Array<{- channelId: string;- serverId: string;- channelName: string;- lastMessageAt: string | null;- lastReadAt: string | null;- }> = [];- if (threadChannelIds.length > 0) {- const raw = await db- .select({- channelId: communityChannel.id,- serverId: communityChannel.serverId,- channelName: communityChannel.name,- lastMessageAt: communityChannel.lastMessageAt,- lastReadAt: communityReadState.lastReadAt,- })- .from(communityChannel)- .leftJoin(- communityReadState,- and(- eq(communityReadState.channelId, communityChannel.id),- eq(communityReadState.userId, userId)- )- )- .where(inArray(communityChannel.id, threadChannelIds));- threadRows = raw.filter(- (r) =>- r.lastMessageAt &&- (!r.lastReadAt || r.lastMessageAt > r.lastReadAt)- ) as typeof threadRows;- }-- // Collect all unique channelIds and serverIds for batch hydration- const allChannelIds = new Set<string>();- for (const r of mentionRows) if (r.channelId) allChannelIds.add(r.channelId);- for (const r of threadRows) allChannelIds.add(r.channelId);-- let channelById = new Map<string, { id: string; name: string; serverId: string }>();- if (allChannelIds.size > 0) {- const channels = await db- .select({- id: communityChannel.id,- name: communityChannel.name,- serverId: communityChannel.serverId,- })- .from(communityChannel)- .where(inArray(communityChannel.id, Array.from(allChannelIds)));- channelById = new Map(channels.map((c) => [c.id, c]));- }-- const allServerIds = new Set<string>();- for (const c of channelById.values()) allServerIds.add(c.serverId);-- let serverById = new Map<string, { id: string; name: string }>();- if (allServerIds.size > 0) {- const servers = await db- .select({ id: communityServer.id, name: communityServer.name })- .from(communityServer)- .where(inArray(communityServer.id, Array.from(allServerIds)));- serverById = new Map(servers.map((s) => [s.id, s]));- }-- // Build event list. mention.kind drives whether this is a "mention" or- // "reply" event — both come from the mention table now.- const events: ForYouEventRow[] = [];-- for (const r of mentionRows) {- const ch = r.channelId ? channelById.get(r.channelId) : null;- const srv = ch ? serverById.get(ch.serverId) : null;- if (!ch || !srv) continue;- const kind: ForYouKind = r.kind === "reply" ? "reply" : "mention";- events.push({- eventKey: buildEventKey(kind, r.messageId),- kind,- serverId: srv.id,- serverName: srv.name,- channelId: ch.id,- channelName: ch.name,- messageId: r.messageId,- authorId: r.authorId,- authorName: r.authorName ?? r.authorEmail ?? "Unknown",- authorAvatar: r.authorImage ?? (r.authorName ?? "?").charAt(0).toUpperCase(),- preview: previewOf(r.content ?? ""),- createdAt: r.createdAt,- });- }-- for (const r of threadRows) {- const srv = serverById.get(r.serverId);- if (!srv) continue;- events.push({- eventKey: buildEventKey("thread", r.channelId),- kind: "thread",- serverId: srv.id,- serverName: srv.name,- channelId: r.channelId,- channelName: r.channelName,- messageId: r.channelId, // thread doesn't anchor to one message; reuse channelId for click target- authorId: "",- authorName: "",- authorAvatar: "",- preview: "",- createdAt: r.lastMessageAt!,- });- }-- // Filter out dismissed eventKeys- const allKeys = events.map((e) => e.eventKey);- if (allKeys.length > 0) {- const dismissed = await db- .select({ eventKey: communityInboxDismissal.eventKey })- .from(communityInboxDismissal)- .where(- and(- eq(communityInboxDismissal.userId, userId),- inArray(communityInboxDismissal.eventKey, allKeys)- )- );- const dismissedSet = new Set(dismissed.map((r) => r.eventKey));- return events- .filter((e) => !dismissedSet.has(e.eventKey))- .sort((a, b) => (a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0))- .slice(0, limit);- }-- return events- .sort((a, b) => (a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0))- .slice(0, limit);-}-// ──────────────────────────────────────────────────────────────────────────────// Unreads// ──────────────────────────────────────────────────────────────────────────────@@ -301,82 +73,3 @@ export async function listUnreadChannels(lastReadAt: r.lastReadAt,}));}--// ──────────────────────────────────────────────────────────────────────────────-// Dismissals-// ──────────────────────────────────────────────────────────────────────────────--export async function dismissEvent(- db: Database,- userId: string,- eventKey: string-): Promise<void> {- await db- .insert(communityInboxDismissal)- .values({- userId,- eventKey,- dismissedAt: new Date().toISOString(),- })- .onConflictDoNothing({- target: [communityInboxDismissal.userId, communityInboxDismissal.eventKey],- });-}--export async function dismissEvents(- db: Database,- userId: string,- eventKeys: string[]-): Promise<void> {- if (eventKeys.length === 0) return;- const now = new Date().toISOString();- await db- .insert(communityInboxDismissal)- .values(eventKeys.map((eventKey) => ({ userId, eventKey, dismissedAt: now })))- .onConflictDoNothing({- target: [communityInboxDismissal.userId, communityInboxDismissal.eventKey],- });-}--export async function listDismissals(db: Database, userId: string) {- return db- .select()- .from(communityInboxDismissal)- .where(eq(communityInboxDismissal.userId, userId));-}--/**- * When the user opens a channel, dismiss the thread For You event for it.- * Mention/reply events are handled by markChannelMentionsRead — they drop- * out of For You as soon as their mention row is marked read.- */-export async function dismissForYouForChannel(- db: Database,- userId: string,- channelId: string-): Promise<void> {- await dismissEvents(db, userId, [`thread:${channelId}`]);-}--/**- * Batch-friendly builder variant of {@link dismissForYouForChannel}. Returns- * the INSERT builder directly so it can be composed into `db.batch([...])`.- * The `ON CONFLICT DO NOTHING` target matches the `uq_inbox_dismissal_user_event`- * unique index (userId, eventKey).- */-export function dismissForYouForChannelBuilder(- db: Database,- userId: string,- channelId: string-) {- return db- .insert(communityInboxDismissal)- .values({- userId,- eventKey: `thread:${channelId}`,- dismissedAt: new Date().toISOString(),- })- .onConflictDoNothing({- target: [communityInboxDismissal.userId, communityInboxDismissal.eventKey],- });-}diff --git a/src/shared/test/queries/community-inbox.test.ts b/src/shared/test/queries/community-inbox.test.tsindex 0c16242db..101a5644a 100644--- a/src/shared/test/queries/community-inbox.test.ts+++ b/src/shared/test/queries/community-inbox.test.ts@@ -6,71 +6,9 @@ import * as inboxQueries from "../../src/db/queries/community/inbox";// also surfaces accidental query syntax regressions at typecheck time.describe("community/inbox exports", () => {- it("exports listForYouEvents", () => {- expect(typeof inboxQueries.listForYouEvents).toBe("function");- });it("exports listUnreadChannels", () => {expect(typeof inboxQueries.listUnreadChannels).toBe("function");});- it("exports dismissEvent", () => {- expect(typeof inboxQueries.dismissEvent).toBe("function");- });- it("exports dismissEvents", () => {- expect(typeof inboxQueries.dismissEvents).toBe("function");- });- it("exports listDismissals", () => {- expect(typeof inboxQueries.listDismissals).toBe("function");- });-});--describe("dismissForYouForChannelBuilder", () => {- function createInsertBuilderMock() {- const chain: any = {};- chain.insert = vi.fn(() => chain);- chain.values = vi.fn(() => chain);- chain.onConflictDoNothing = vi.fn(() => ({ __builder: "insert-dismissal" }));- return chain;- }-- it("exports the builder function", () => {- expect(typeof inboxQueries.dismissForYouForChannelBuilder).toBe("function");- });-- it("returns a builder synchronously (usable in db.batch)", () => {- const db = createInsertBuilderMock();- const result = inboxQueries.dismissForYouForChannelBuilder(db, "u_1", "c_1");- expect(result).toBeDefined();- expect(result).not.toBeInstanceOf(Promise);- expect(db.insert).toHaveBeenCalledTimes(1);- expect(db.onConflictDoNothing).toHaveBeenCalledTimes(1);- });-- it("uses the thread:<channelId> event key shape", () => {- const db = createInsertBuilderMock();- inboxQueries.dismissForYouForChannelBuilder(db, "u_1", "c_1");- const valuesArg = db.values.mock.calls[0][0];- expect(valuesArg).toMatchObject({- userId: "u_1",- eventKey: "thread:c_1",- });- expect(typeof valuesArg.dismissedAt).toBe("string");- });-});--describe("dismissEvents short-circuit", () => {- it("returns without touching db when keys empty", async () => {- let called = false;- const fakeDb = {- insert() {- called = true;- return this;- },- values() { return this; },- onConflictDoNothing() { return Promise.resolve(); },- } as unknown as Parameters<typeof inboxQueries.dismissEvents>[0];- await inboxQueries.dismissEvents(fakeDb, "u1", []);- expect(called).toBe(false);- });});/**diff --git a/src/web/migrations/0054_drop_community_inbox_dismissal.sql b/src/web/migrations/0054_drop_community_inbox_dismissal.sqlnew file mode 100644index 000000000..ac8adcd7d--- /dev/null+++ b/src/web/migrations/0054_drop_community_inbox_dismissal.sql@@ -0,0 +1,8 @@+-- Migration: drop community_inbox_dismissal+-- The Inbox "For You" tab is removed; the dismissal table is no longer read+-- or written by any code path. Indexes drop implicitly with the table under+-- SQLite, but we drop them explicitly first to make the intent obvious.++DROP INDEX IF EXISTS idx_inbox_dismissal_user;+DROP INDEX IF EXISTS uq_inbox_dismissal_user_event;+DROP TABLE IF EXISTS community_inbox_dismissal;diff --git a/src/web/src/app/api/community/channels/[id]/read/route.test.ts b/src/web/src/app/api/community/channels/[id]/read/route.test.tsindex 42d8d980e..cc8e2bdad 100644--- a/src/web/src/app/api/community/channels/[id]/read/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/read/route.test.ts@@ -11,7 +11,6 @@ const mockGetMessage = vi.fn()const mockGetLatestMessage = vi.fn()const mockMarkReadToMessageBuilder = vi.fn()const mockMarkChannelMentionsReadBuilder = vi.fn()-const mockDismissForYouForChannelBuilder = vi.fn()const mockBatch = vi.fn()vi.mock("@/lib/db", () => ({@@ -38,10 +37,6 @@ vi.mock("@alook/shared", async () => {markChannelMentionsReadBuilder: (...a: unknown[]) =>mockMarkChannelMentionsReadBuilder(...a),},- communityInbox: {- dismissForYouForChannelBuilder: (...a: unknown[]) =>- mockDismissForYouForChannelBuilder(...a),- },},}})@@ -80,13 +75,10 @@ describe("PUT /api/community/channels/[id]/read", () => {mockMarkChannelMentionsReadBuilder.mockReturnValue({__builder: "markChannelMentionsRead",})- mockDismissForYouForChannelBuilder.mockReturnValue({- __builder: "dismissForYouForChannel",- })mockBatch.mockResolvedValue(undefined)})- it("no-body call on non-empty channel: uses latest message and issues one batch with all three builders", async () => {+ it("no-body call on non-empty channel: uses latest message and issues one batch with both builders", async () => {mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1" })mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })mockGetLatestMessage.mockResolvedValue({@@ -104,14 +96,13 @@ describe("PUT /api/community/channels/[id]/read", () => {message: { id: "m_latest", createdAt: "2026-07-05T10:00:00.000Z" },})- // Exactly one batch call carrying all three statements in order.+ // Exactly one batch call carrying both statements in order.expect(mockBatch).toHaveBeenCalledTimes(1)const batchArg = mockBatch.mock.calls[0]![0]expect(Array.isArray(batchArg)).toBe(true)- expect(batchArg).toHaveLength(3)+ expect(batchArg).toHaveLength(2)expect(batchArg[0]).toEqual({ __builder: "markReadToMessage" })expect(batchArg[1]).toEqual({ __builder: "markChannelMentionsRead" })- expect(batchArg[2]).toEqual({ __builder: "dismissForYouForChannel" })})it("no-body call on EMPTY channel: no writes at all, returns 200 { ok: true }", async () => {@@ -128,7 +119,6 @@ describe("PUT /api/community/channels/[id]/read", () => {expect(mockMarkReadToMessageBuilder).not.toHaveBeenCalled()expect(mockMarkChannelMentionsReadBuilder).not.toHaveBeenCalled()- expect(mockDismissForYouForChannelBuilder).not.toHaveBeenCalled()expect(mockBatch).not.toHaveBeenCalled()})@@ -166,7 +156,6 @@ describe("PUT /api/community/channels/[id]/read", () => {expect(mockGetChannelForMember).not.toHaveBeenCalled()expect(mockMarkReadToMessageBuilder).not.toHaveBeenCalled()expect(mockMarkChannelMentionsReadBuilder).not.toHaveBeenCalled()- expect(mockDismissForYouForChannelBuilder).not.toHaveBeenCalled()expect(mockBatch).not.toHaveBeenCalled()})@@ -179,7 +168,6 @@ describe("PUT /api/community/channels/[id]/read", () => {expect(res.status).toBe(403)expect(mockMarkReadToMessageBuilder).not.toHaveBeenCalled()expect(mockMarkChannelMentionsReadBuilder).not.toHaveBeenCalled()- expect(mockDismissForYouForChannelBuilder).not.toHaveBeenCalled()expect(mockBatch).not.toHaveBeenCalled()})diff --git a/src/web/src/app/api/community/channels/[id]/read/route.ts b/src/web/src/app/api/community/channels/[id]/read/route.tsindex 2cdf64bcc..ced3d81e9 100644--- a/src/web/src/app/api/community/channels/[id]/read/route.ts+++ b/src/web/src/app/api/community/channels/[id]/read/route.ts@@ -20,10 +20,9 @@ import { requireChannelMember } from "@/lib/community/permissions"* message belongs to another channel (400) — protects against confused-* deputy watermark advances.*- * Mention clear + for-you dismiss still fire in one D1 batch on non-empty- * channels. On an empty channel we short-circuit before writing anything —- * there are no mentions / for-you entries to clear on a channel with no- * messages.+ * Mention clear still fires in one D1 batch on non-empty channels. On an+ * empty channel we short-circuit before writing anything — there are no+ * mentions to clear on a channel with no messages.*/export const PUT = withAuth(async (req: NextRequest, ctx) => {const channelId = ctx.params?.id@@ -76,9 +75,9 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {if (!target) return writeJSON({ ok: true })}- // Fire all three writes in one D1 batch so partial failure can't leave the- // inbox inconsistent (mark-read succeeded but the mention/for-you dismissal- // didn't, or vice versa). D1 batches are atomic per SQLite guarantees.+ // Fire both writes in one D1 batch so partial failure can't leave the+ // inbox inconsistent (mark-read succeeded but the mention clear didn't, or+ // vice versa). D1 batches are atomic per SQLite guarantees.await db.batch([queries.communityReadState.markReadToMessageBuilder(db, {userId: ctx.userId,@@ -86,7 +85,6 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {message: target,}),queries.communityMention.markChannelMentionsReadBuilder(db, ctx.userId, channelId),- queries.communityInbox.dismissForYouForChannelBuilder(db, ctx.userId, channelId),])return writeJSON({ ok: true })diff --git a/src/web/src/app/api/community/inbox/foryou/dismiss/route.test.ts b/src/web/src/app/api/community/inbox/foryou/dismiss/route.test.tsdeleted file mode 100644index ee7229723..000000000--- a/src/web/src/app/api/community/inbox/foryou/dismiss/route.test.ts+++ /dev/null@@ -1,81 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--const mockDismissEvents = vi.fn()--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}))--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- communityInbox: {- dismissEvents: (...args: unknown[]) => mockDismissEvents(...args),- },- },-}))--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params- return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })- }),-}))--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server")- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- }-})--import { POST } from "./route"--function postBody(body: unknown): NextRequest {- return new NextRequest("http://localhost/api/community/inbox/foryou/dismiss", {- method: "POST",- body: JSON.stringify(body),- })-}--describe("POST /api/community/inbox/foryou/dismiss", () => {- beforeEach(() => vi.clearAllMocks())-- it("dismisses a single eventKey", async () => {- mockDismissEvents.mockResolvedValue(undefined)- const res = await POST(postBody({ eventKey: "mention:abc" }))- expect(res.status).toBe(200)- expect(mockDismissEvents).toHaveBeenCalledWith({}, "u1", ["mention:abc"])- })-- it("dismisses multiple eventKeys", async () => {- mockDismissEvents.mockResolvedValue(undefined)- const res = await POST(postBody({ eventKeys: ["mention:a", "reply:b", "thread:c"] }))- expect(res.status).toBe(200)- expect(mockDismissEvents).toHaveBeenCalledWith({}, "u1", ["mention:a", "reply:b", "thread:c"])- })-- it("400 when no keys provided", async () => {- const res = await POST(postBody({}))- expect(res.status).toBe(400)- expect(mockDismissEvents).not.toHaveBeenCalled()- })-- it("400 when an eventKey has an unknown prefix", async () => {- const res = await POST(postBody({ eventKey: "foo:bar" }))- expect(res.status).toBe(400)- expect(mockDismissEvents).not.toHaveBeenCalled()- })-- it("400 when body is not JSON", async () => {- const res = await POST(new NextRequest("http://localhost/api/community/inbox/foryou/dismiss", {- method: "POST",- body: "not json",- }))- expect(res.status).toBe(400)- })-})diff --git a/src/web/src/app/api/community/inbox/foryou/dismiss/route.ts b/src/web/src/app/api/community/inbox/foryou/dismiss/route.tsdeleted file mode 100644index 916c6240d..000000000--- a/src/web/src/app/api/community/inbox/foryou/dismiss/route.ts+++ /dev/null@@ -1,27 +0,0 @@-import { NextRequest } from "next/server"-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"--const VALID_PREFIXES = ["mention:", "reply:", "thread:"]--export const POST = withAuth(async (req: NextRequest, ctx) => {- let body: { eventKey?: string; eventKeys?: string[] }- try {- body = await req.json()- } catch {- return writeError("invalid request body", 400)- }-- const keys = body.eventKeys ?? (body.eventKey ? [body.eventKey] : [])- if (keys.length === 0) return writeError("provide eventKey or eventKeys", 400)-- const invalid = keys.find((k) => !VALID_PREFIXES.some((p) => k.startsWith(p)))- if (invalid) return writeError(`invalid eventKey: ${invalid}`, 400)-- const db = getDb(ctx.env.DB)- await queries.communityInbox.dismissEvents(db, ctx.userId, keys)-- return writeJSON({ ok: true })-})diff --git a/src/web/src/app/api/community/inbox/foryou/route.test.ts b/src/web/src/app/api/community/inbox/foryou/route.test.tsdeleted file mode 100644index b8016440e..000000000--- a/src/web/src/app/api/community/inbox/foryou/route.test.ts+++ /dev/null@@ -1,91 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--const mockListForYouEvents = vi.fn()--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}))--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- queries: {- communityInbox: {- listForYouEvents: (...args: unknown[]) => mockListForYouEvents(...args),- },- },- }-})--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params- return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })- }),-}))--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server")- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- }-})--import { GET } from "./route"--describe("GET /api/community/inbox/foryou", () => {- beforeEach(() => vi.clearAllMocks())-- it("returns events from the query", async () => {- const event = {- eventKey: "mention:m1",- kind: "mention",- serverId: "s1",- serverName: "Server 1",- channelId: "c1",- channelName: "general",- messageId: "m1",- authorId: "u2",- authorName: "Alice",- authorAvatar: "A",- preview: "hi",- createdAt: "2026-06-25T10:00:00Z",- }- mockListForYouEvents.mockResolvedValue([event])-- const res = await GET(new NextRequest("http://localhost/api/community/inbox/foryou"))- const body = await res.json()-- expect(res.status).toBe(200)- expect(body.events).toEqual([event])- expect(body.limit).toBeGreaterThan(0)- expect(mockListForYouEvents).toHaveBeenCalledWith({}, "u1", { limit: body.limit })- })-- it("returns empty events array when none", async () => {- mockListForYouEvents.mockResolvedValue([])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/foryou"))- const body = await res.json()- expect(body.events).toEqual([])- })-- it("honours the limit query param when within bounds", async () => {- mockListForYouEvents.mockResolvedValue([])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/foryou?limit=25"))- const body = await res.json()- expect(body.limit).toBe(25)- expect(mockListForYouEvents).toHaveBeenCalledWith({}, "u1", { limit: 25 })- })-- it("clamps an over-cap limit to MAX_INBOX_PAGE_SIZE", async () => {- mockListForYouEvents.mockResolvedValue([])- const res = await GET(new NextRequest("http://localhost/api/community/inbox/foryou?limit=99999"))- const body = await res.json()- expect(body.limit).toBe(200) // MAX_INBOX_PAGE_SIZE- })-})diff --git a/src/web/src/app/api/community/inbox/foryou/route.ts b/src/web/src/app/api/community/inbox/foryou/route.tsdeleted file mode 100644index a3b30475b..000000000--- a/src/web/src/app/api/community/inbox/foryou/route.ts+++ /dev/null@@ -1,21 +0,0 @@-import {- queries,- DEFAULT_INBOX_PAGE_SIZE,- MAX_INBOX_PAGE_SIZE,-} from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON } from "@/lib/middleware/helpers"-import { parseBoundedInt } from "@/lib/community/messages"--export const GET = withAuth(async (req, ctx) => {- const db = getDb(ctx.env.DB)- const url = new URL(req.url)- const limit = parseBoundedInt(- url.searchParams.get("limit"),- DEFAULT_INBOX_PAGE_SIZE,- MAX_INBOX_PAGE_SIZE,- )- const events = await queries.communityInbox.listForYouEvents(db, ctx.userId, { limit })- return writeJSON({ events, limit })-})diff --git a/src/web/src/app/community/preview/_mock.ts b/src/web/src/app/community/preview/_mock.tsindex cd784305f..ed4b05c32 100644--- a/src/web/src/app/community/preview/_mock.ts+++ b/src/web/src/app/community/preview/_mock.ts@@ -27,7 +27,6 @@ import type {InviteRow,AuditEntry,Mention,- ForYouEvent,UnreadServer,} from "@/components/community/_types"@@ -329,49 +328,6 @@ export const MENTIONS: Mention[] = [},]-// "For You" events — direct hits (mentions, replies, thread updates)-export const FOR_YOU_FEED: ForYouEvent[] = [- {- eventKey: "mention:mn_m1",- kind: "mention",- serverId: "sv_alook",- serverName: "Alook",- channelId: "ch_general",- channelName: "general",- messageId: "mn_m1",- authorName: "Gus",- authorAvatar: "Gu",- preview: "thanks @Gener — can you cross-post this in #general?",- createdAt: "2026-06-25T09:48:00Z",- },- {- eventKey: "reply:r_m1",- kind: "reply",- serverId: "sv_alook",- serverName: "Alook",- channelId: "ch_general",- channelName: "general",- messageId: "r_m1",- authorName: "Lindsay",- authorAvatar: "L",- preview: "got it — that approach works for me",- createdAt: "2026-06-25T09:20:00Z",- },- {- eventKey: "thread:ch_thread_42",- kind: "thread",- serverId: "sv_cf",- serverName: "Cloudflare",- channelId: "ch_thread_42",- channelName: "workers-routing",- messageId: "ch_thread_42",- authorName: "",- authorAvatar: "",- preview: "",- createdAt: "2026-06-25T08:00:00Z",- },-]-// Unreads grouped by server — channel-levelexport const UNREAD_SERVERS: UnreadServer[] = [{diff --git a/src/web/src/app/community/preview/page.tsx b/src/web/src/app/community/preview/page.tsxindex 9355e92a7..c3f0d1572 100644--- a/src/web/src/app/community/preview/page.tsx+++ b/src/web/src/app/community/preview/page.tsx@@ -26,7 +26,7 @@ import { Dialog, DialogContent } from "@/components/ui/dialog"import {SERVERS, CATEGORIES, MESSAGES, NEW_DIVIDER_BEFORE, PINNED, SEARCH_RESULTS,THREADS, THREAD_MESSAGES, FORUM_POSTS, FORUM_TAGS, MEMBERS, FRIENDS, PENDING, BLOCKED, DMS, DM_MESSAGES,- PROFILES, INVITES, AUDIT_LOG, MENTIONS, FOR_YOU_FEED, UNREAD_SERVERS, MOCK_FOLDERS,+ PROFILES, INVITES, AUDIT_LOG, MENTIONS, UNREAD_SERVERS, MOCK_FOLDERS,} from "./_mock"import type { RightPanel, MobileZone, View, SettingsSection, Msg, PendingRequest, BlockedUser, ForumPost, Profile, Thread, Role, DM, Member } from "@/components/community/_types"import { useBreakpoint } from "@/hooks/use-mobile"@@ -99,7 +99,6 @@ export default function CommunityPreview() {const [searchQuery] = useState("")// image attachment being previewed in the lightboxconst [preview, setPreview] = useState<string | null>(null)- const [forYouFeed, setForYouFeed] = useState(FOR_YOU_FEED)const [unreadFeed] = useState(UNREAD_SERVERS)// open an inbox event → jump to its server + channel@@ -115,16 +114,13 @@ export default function CommunityPreview() {appName: "Alook",inbox: (<InboxPopover- forYou={forYouFeed}unreads={unreadFeed}mentions={MENTIONS}- onOpenEvent={(e) => openServerChannel(e.serverId, e.channelId)}onOpenChannel={openServerChannel}- onDismissEvent={(eventKey) => setForYouFeed((prev) => prev.filter((e) => e.eventKey !== eventKey))}- onMarkAllRead={() => setForYouFeed([])}+ onMarkAllRead={() => {}}/>),- hasUnread: forYouFeed.length > 0 || unreadFeed.length > 0 || MENTIONS.length > 0,+ hasUnread: unreadFeed.length > 0 || MENTIONS.length > 0,}// open a profile card near the click point (desktop popover / mobile sheet).diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.tsindex 82d6bd44d..d3d694338 100644--- a/src/web/src/components/community/_types.ts+++ b/src/web/src/components/community/_types.ts@@ -224,24 +224,6 @@ export type Mention = {m: Msg}-// "For You" — a single event the user should see.-// eventKey is opaque: "mention:<msgId>" | "reply:<msgId>" | "thread:<channelId>".-export type ForYouKind = "mention" | "reply" | "thread"--export type ForYouEvent = {- eventKey: string- kind: ForYouKind- serverId: string- serverName: string- channelId: string- channelName: string- messageId: string- authorName: string- authorAvatar: string- preview: string- createdAt: string-}-// "Unreads" — channels with unread messages, grouped by server.export type UnreadServer = {serverId: stringdiff --git a/src/web/src/components/community/community-inbox-popover.tsx b/src/web/src/components/community/community-inbox-popover.tsxindex fd33e6fe8..3245b0328 100644--- a/src/web/src/components/community/community-inbox-popover.tsx+++ b/src/web/src/components/community/community-inbox-popover.tsx@@ -1,76 +1,10 @@-import type React from "react"-import { AtSign, ChevronRight, Hash, Inbox, MessagesSquare, MoreHorizontal, Reply, Trash2 } from "lucide-react"+import { ChevronRight, Hash, Inbox, MoreHorizontal, Trash2 } from "lucide-react"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 { Avatar } from "./avatar"import { EmptyState } from "./empty-state"-import { formatRelativeTime } from "./format-time"-import type { ForYouEvent, ForYouKind, Mention, UnreadServer } from "./_types"--function KindIcon({ kind }: { kind: ForYouKind }) {- const cls = "size-4 text-muted-foreground"- if (kind === "mention") return <AtSign className={cls} />- if (kind === "reply") return <Reply className={cls} />- return <MessagesSquare className={cls} />-}--function kindLabel(e: ForYouEvent): React.ReactNode {- if (e.kind === "mention") return <><span className="font-medium">{e.authorName}</span> mentioned you</>- if (e.kind === "reply") return <><span className="font-medium">{e.authorName}</span> replied to you</>- return <>New activity in thread</>-}--function ForYouTab({ events, loading, onOpenEvent, onDismissEvent }: {- events: ForYouEvent[]- loading?: boolean- onOpenEvent?: (e: ForYouEvent) => void- onDismissEvent?: (eventKey: string) => void-}) {- return (- <div className="h-full overflow-y-auto thin-scrollbar p-3">- {loading && events.length === 0 && <InboxRowsSkeleton />}- {!loading && events.length === 0 && <EmptyState icon={Inbox} label="Nothing for you right now" />}- {events.map((e) => (- <div key={e.eventKey} className="group flex w-full items-start gap-3 rounded-md p-2 text-left hover:bg-accent">- <button onClick={() => onOpenEvent?.(e)} className="flex min-w-0 flex-1 items-start gap-3 text-left">- {e.kind === "thread" ? (- <div className="grid size-9 shrink-0 place-items-center rounded-full bg-muted">- <MessagesSquare className="size-4 text-muted-foreground" />- </div>- ) : (- <Avatar label={e.authorAvatar || "?"} size={36} />- )}- <div className="min-w-0 flex-1">- <div className="flex items-center gap-2">- <KindIcon kind={e.kind} />- <div className="truncate text-sm">{kindLabel(e)}</div>- </div>- <div className="truncate text-xs text-muted-foreground">- in <span className="font-medium">{e.serverName}</span> · #{e.channelName}- </div>- {e.preview && <div className="mt-1 truncate text-sm text-muted-foreground">{e.preview}</div>}- <div className="mt-1 text-xs text-muted-foreground" suppressHydrationWarning>{formatRelativeTime(e.createdAt)}</div>- </div>- </button>- {onDismissEvent && (- <DropdownMenu>- <DropdownMenuTrigger render={<button className="mt-1 grid size-6 shrink-0 place-items-center rounded-md text-muted-foreground opacity-0 hover:bg-accent hover:text-foreground group-hover:opacity-100" aria-label="More" />}>- <MoreHorizontal className="size-4" />- </DropdownMenuTrigger>- <DropdownMenuContent align="end" sideOffset={4} className="w-36">- <DropdownMenuItem onClick={() => onDismissEvent(e.eventKey)}>- <Trash2 className="size-4" />- Remove- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- )}- </div>- ))}- </div>- )-}+import type { Mention, UnreadServer } from "./_types"function UnreadsTab({ servers, loading, onOpenChannel }: {servers: UnreadServer[]@@ -146,31 +80,25 @@ function MentionsTab({ mentions, loading, onOpenMention, onDeleteMention }: {}export function InboxPopover({- forYou,unreads,mentions,loading,- onOpenEvent,onOpenChannel,onOpenMention,- onDismissEvent,onDeleteMention,onMarkAllRead,}: {- forYou: ForYouEvent[]unreads: UnreadServer[]mentions: Mention[]loading?: boolean- onOpenEvent?: (e: ForYouEvent) => voidonOpenChannel?: (serverId: string, channelId: string) => voidonOpenMention?: (m: Mention) => void- onDismissEvent?: (eventKey: string) => voidonDeleteMention?: (id: string) => voidonMarkAllRead?: () => void}) {- const hasAnything = forYou.length > 0 || unreads.length > 0 || mentions.length > 0+ const hasAnything = unreads.length > 0 || mentions.length > 0return (- <Tabs defaultValue="foryou" className="flex h-112 flex-col">+ <Tabs defaultValue="unreads" className="flex h-112 flex-col"><div className="flex items-center gap-2 px-3 pt-4"><Inbox className="size-5" /><h2 className="flex-1 text-lg font-semibold">Inbox</h2>@@ -185,12 +113,6 @@ export function InboxPopover({)}</div><TabsList variant="line" className="mt-3 w-full border-b border-border px-3">- <TabsTrigger value="foryou">- <span className="inline-flex items-center gap-2">- For You- {forYou.length > 0 && <span className="size-1.5 rounded-full bg-primary" />}- </span>- </TabsTrigger><TabsTrigger value="unreads"><span className="inline-flex items-center gap-2">Unreads@@ -204,9 +126,6 @@ export function InboxPopover({</span></TabsTrigger></TabsList>- <TabsContent value="foryou" className="min-h-0 flex-1">- <ForYouTab events={forYou} loading={loading} onOpenEvent={onOpenEvent} onDismissEvent={onDismissEvent} />- </TabsContent><TabsContent value="unreads" className="min-h-0 flex-1"><UnreadsTab servers={unreads} loading={loading} onOpenChannel={onOpenChannel} /></TabsContent>@@ -217,10 +136,9 @@ export function InboxPopover({)}-// Skeleton rows shared by ForYou + Mentions — both render an avatar + two-// text lines per item, so a single shape covers them. Reserves the same gap-// as <ForYouTab> / <MentionsTab> rows so the popover doesn't reflow when data-// lands.+// Skeleton rows for Mentions — avatar + two text lines per item. Reserves+// the same gap as <MentionsTab> rows so the popover doesn't reflow when+// data lands.function InboxRowsSkeleton() {return (<div className="flex flex-col gap-1">diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsxindex 0426c6733..09f644429 100644--- a/src/web/src/components/community/shell-frame.tsx+++ b/src/web/src/components/community/shell-frame.tsx@@ -24,7 +24,7 @@ import { useServers } from "@/hooks/community/use-servers"import { useFolders } from "@/hooks/community/use-folders"import { useFriends } from "@/hooks/community/use-friends"import { useServerMembers } from "@/hooks/community/use-server-members"-import { useInboxForYou, useInboxUnreads, useInboxMentions } from "@/hooks/community/use-inbox"+import { useInboxUnreads, useInboxMentions } from "@/hooks/community/use-inbox"import {useCreateServer,useJoinServer,@@ -37,7 +37,6 @@ import {useCreateServerFolderWith,useCreateOrGetDm,useMarkAllInboxRead,- useDismissForYouEvent,useDeleteMention,useUpdateProfile,useSendDmMessage,@@ -91,15 +90,12 @@ export function ShellFrame({const membersHook = useServerMembers(currentServerId)const members = membersHook.members- // Inbox trio — the shell reads all three to drive the bell badge.- const inboxForYou = useInboxForYou()+ // Inbox pair — the shell reads both to drive the bell badge.const inboxUnreads = useInboxUnreads()const inboxMentions = useInboxMentions()- const forYouFeed = inboxForYou.eventsconst unreadFeed = inboxUnreads.serversconst mentions = inboxMentions.mentions- const inboxLoading =- inboxForYou.isLoading || inboxUnreads.isLoading || inboxMentions.isLoading+ const inboxLoading = inboxUnreads.isLoading || inboxMentions.isLoading// Mutations wired through the shell.const createServer = useCreateServer()@@ -114,7 +110,6 @@ export function ShellFrame({const createOrGetDm = useCreateOrGetDm()const sendDmMessage = useSendDmMessage()const markAllInboxRead = useMarkAllInboxRead()- const dismissForYouEvent = useDismissForYouEvent()const deleteMention = useDeleteMention()const updateProfile = useUpdateProfile()@@ -390,24 +385,19 @@ export function ShellFrame({const inboxElement = (<InboxPopover- forYou={forYouFeed}unreads={unreadFeed}mentions={mentions}loading={inboxLoading}- onOpenEvent={(e) => openServerChannel(e.serverId, e.channelId)}onOpenChannel={openServerChannel}onOpenMention={(mention) => {if (mention.serverId && mention.channelId) openServerChannel(mention.serverId, mention.channelId)}}onMarkAllRead={() => { markAllInboxRead.mutate() }}- onDismissEvent={(eventKey) => { dismissForYouEvent.mutate({ eventKey }) }}onDeleteMention={(id) => deleteMention.mutate({ mentionId: id })}/>)const inboxHasUnread =- (forYouFeed?.length ?? 0) > 0 ||- (unreadFeed?.length ?? 0) > 0 ||- (mentions?.length ?? 0) > 0+ (unreadFeed?.length ?? 0) > 0 || (mentions?.length ?? 0) > 0const userSettingsDialog = (<Dialog open={editingProfile} onOpenChange={(o) => { if (!o) setEditingProfile(false) }}>diff --git a/src/web/src/hooks/community/mutations/messages.test.ts b/src/web/src/hooks/community/mutations/messages.test.tsindex c04518b0c..c0577a43c 100644--- a/src/web/src/hooks/community/mutations/messages.test.ts+++ b/src/web/src/hooks/community/mutations/messages.test.ts@@ -731,60 +731,28 @@ describe("useMarkDmRead — rollback", () => {})})-// ── useMarkAllInboxRead — eventKeys captured pre-clear ───────────────────--describe("useMarkAllInboxRead — captures eventKeys BEFORE optimistic clear", () => {- // Regression: the old implementation read the for-you cache inside- // `mutationFn`, which runs AFTER `onMutate` per TanStack ordering. Since- // `onMutate` wiped the cache to `{ events: [] }`, `mutationFn` always saw- // an empty list and skipped the dismiss POST. The fix uses a ref- // populated in `onMutate`.- it("dismisses each for-you eventKey with a POST containing the pre-clear keys", async () => {- capturedQc.setQueryData(communityKeys.inboxForYou(), {- events: [- { eventKey: "mention:m_1" },- { eventKey: "reply:r_2" },- { eventKey: "reaction:x_3" },- ],- })+// ── useMarkAllInboxRead ───────────────────────────────────────────────────++describe("useMarkAllInboxRead", () => {+ it("fires exactly two POSTs — mentions read-all + unreads read-all", async () => {capturedQc.setQueryData(communityKeys.inboxUnreads(), { servers: [] })capturedQc.setQueryData(communityKeys.inboxMentions(), { mentions: [] })apiFetchMock.mockResolvedValue(undefined)const mod = await loadMod()mod.useMarkAllInboxRead()await runMutation<void>(undefined as unknown as void)- // Three POSTs — mentions read-all, unreads read-all, foryou dismiss.- const posts = apiFetchMock.mock.calls.filter(- (c) => (c[1] as { method?: string })?.method === "POST",- )- expect(posts).toHaveLength(3)- const dismiss = posts.find((c) => (c[0] as string).endsWith("/foryou/dismiss"))- expect(dismiss).toBeDefined()- const body = JSON.parse((dismiss![1] as { body: string }).body)- expect(body).toEqual({ eventKeys: ["mention:m_1", "reply:r_2", "reaction:x_3"] })- })-- it("skips the dismiss POST when there are no for-you events", async () => {- capturedQc.setQueryData(communityKeys.inboxForYou(), { events: [] })- apiFetchMock.mockResolvedValue(undefined)- const mod = await loadMod()- mod.useMarkAllInboxRead()- await runMutation<void>(undefined as unknown as void)- const dismissCalls = apiFetchMock.mock.calls.filter((c) =>- (c[0] as string).endsWith("/foryou/dismiss"),- )- expect(dismissCalls).toHaveLength(0)- // Mentions + unreads read-all still fire.const posts = apiFetchMock.mock.calls.filter((c) => (c[1] as { method?: string })?.method === "POST",)expect(posts).toHaveLength(2)+ const paths = posts.map((c) => c[0] as string).sort()+ expect(paths).toEqual([+ "/api/community/inbox/mentions/read-all",+ "/api/community/inbox/unreads/read-all",+ ])})- it("still clears all three inbox caches optimistically", async () => {- capturedQc.setQueryData(communityKeys.inboxForYou(), {- events: [{ eventKey: "mention:m_1" }],- })+ it("clears both inbox caches optimistically", async () => {capturedQc.setQueryData(communityKeys.inboxUnreads(), {servers: [{ serverId: "s_1", serverName: "s", channels: [{ channelId: "ch_1" }] }],})@@ -795,7 +763,6 @@ describe("useMarkAllInboxRead — captures eventKeys BEFORE optimistic clear", (const mod = await loadMod()mod.useMarkAllInboxRead()await runMutation<void>(undefined as unknown as void)- expect(capturedQc.getQueryData(communityKeys.inboxForYou())).toEqual({ events: [] })expect(capturedQc.getQueryData(communityKeys.inboxUnreads())).toEqual({ servers: [] })expect(capturedQc.getQueryData(communityKeys.inboxMentions())).toEqual({ mentions: [] })})@@ -803,7 +770,6 @@ describe("useMarkAllInboxRead — captures eventKeys BEFORE optimistic clear", (it("onSuccess invalidates communityKeys.servers() so every rail badge drops to 0", async () => {// Mark-all-read clears every unread mention row on the server — the rail// aggregate must refresh across all servers, not just the inbox feeds.- capturedQc.setQueryData(communityKeys.inboxForYou(), { events: [] })apiFetchMock.mockResolvedValue(undefined)const mod = await loadMod()mod.useMarkAllInboxRead()@@ -817,24 +783,6 @@ describe("useMarkAllInboxRead — captures eventKeys BEFORE optimistic clear", (})})-// ── useDismissForYouEvent — rollback ─────────────────────────────────────--describe("useDismissForYouEvent — rollback", () => {- it("restores the event on failure", async () => {- capturedQc.setQueryData(communityKeys.inboxForYou(), {- events: [{ eventKey: "mention:m_1", kind: "mention" }],- })- apiFetchMock.mockRejectedValueOnce(new Error("boom"))- const mod = await loadMod()- mod.useDismissForYouEvent()- await runMutation({ eventKey: "mention:m_1" }).catch(() => {})- const cache = capturedQc.getQueryData<{ events: { eventKey: string }[] }>(- communityKeys.inboxForYou(),- )- expect(cache?.events).toHaveLength(1)- })-})-// ── useDeleteMention — rollback ──────────────────────────────────────────describe("useDeleteMention — rollback", () => {diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.tsindex 074a48ef9..14f36b453 100644--- a/src/web/src/hooks/community/mutations/messages.ts+++ b/src/web/src/hooks/community/mutations/messages.ts@@ -1,6 +1,5 @@"use client"-import { useRef } from "react"import {useMutation,useQueryClient,@@ -833,34 +832,14 @@ export function useMarkDmRead() {export function useMarkAllInboxRead() {const queryClient = useQueryClient()- // TanStack Query calls `onMutate` before `mutationFn`, so the optimistic- // clear below wipes the for-you cache before `mutationFn` can read the- // eventKeys. Capture the pre-clear eventKeys in `onMutate` via a ref, and- // read them back in `mutationFn`. Ref (not module state) so parallel calls- // from different hook instances don't stomp each other.- const eventKeysRef = useRef<string[]>([])return useMutation<void, Error, void>({mutationFn: async () => {- const eventKeys = eventKeysRef.currentawait Promise.all([apiFetch("/api/community/inbox/mentions/read-all", { method: "POST" }),apiFetch("/api/community/inbox/unreads/read-all", { method: "POST" }),- eventKeys.length > 0- ? apiFetch("/api/community/inbox/foryou/dismiss", {- method: "POST",- body: JSON.stringify({ eventKeys }),- })- : Promise.resolve(),])},onMutate: async () => {- // Snapshot the for-you eventKeys BEFORE the optimistic clear — the- // dismiss POST needs them and `mutationFn` runs after this hook.- const forYou = queryClient.getQueryData<{ events: { eventKey: string }[] }>(- communityKeys.inboxForYou(),- )- eventKeysRef.current = forYou?.events.map((e) => e.eventKey) ?? []- queryClient.setQueryData(communityKeys.inboxForYou(), { events: [] })queryClient.setQueryData(communityKeys.inboxUnreads(), { servers: [] })queryClient.setQueryData(communityKeys.inboxMentions(), { mentions: [] })},@@ -871,39 +850,14 @@ export function useMarkAllInboxRead() {},onError: () => {void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })- // A partial write is possible (one of the three POSTs may have- // succeeded before another failed) — refresh the rail badges too so- // the UI reflects whatever landed on the server.+ // A partial write is possible (one of the two POSTs may have succeeded+ // before the other failed) — refresh the rail badges too so the UI+ // reflects whatever landed on the server.void queryClient.invalidateQueries({ queryKey: communityKeys.servers() })},})}-export type DismissForYouArgs = { eventKey: string }--export function useDismissForYouEvent() {- const queryClient = useQueryClient()- return useMutation<void, Error, DismissForYouArgs, { snapshot: unknown }>({- mutationFn: async ({ eventKey }) => {- await apiFetch("/api/community/inbox/foryou/dismiss", {- method: "POST",- body: JSON.stringify({ eventKeys: [eventKey] }),- })- },- onMutate: async (args) => {- const key = communityKeys.inboxForYou()- const snapshot = queryClient.getQueryData(key)- queryClient.setQueryData(key, (prev: { events: { eventKey: string }[] } | undefined) =>- prev ? { ...prev, events: prev.events.filter((e) => e.eventKey !== args.eventKey) } : prev,- )- return { snapshot }- },- onError: (_err, _args, ctx) => {- if (ctx?.snapshot) queryClient.setQueryData(communityKeys.inboxForYou(), ctx.snapshot)- },- })-}-export type DeleteMentionArgs = { mentionId: string }export function useDeleteMention() {diff --git a/src/web/src/hooks/community/use-inbox.test.ts b/src/web/src/hooks/community/use-inbox.test.tsindex 52d500478..d3665e19c 100644--- a/src/web/src/hooks/community/use-inbox.test.ts+++ b/src/web/src/hooks/community/use-inbox.test.ts@@ -11,18 +11,6 @@ beforeEach(() => {apiFetchMock.mockReset()})-describe("useInboxForYou / inboxForYouQueryFn", () => {- it("fetches /inbox/foryou and populates queryClient at communityKeys.inboxForYou()", async () => {- apiFetchMock.mockResolvedValueOnce({ events: [] })- const { inboxForYouQueryFn } = await import("./use-inbox")- const qc = new QueryClient()- const key = communityKeys.inboxForYou()- await qc.fetchQuery({ queryKey: key, queryFn: inboxForYouQueryFn })- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/inbox/foryou")- expect(qc.getQueryData(key)).toEqual({ events: [] })- })-})-describe("useInboxUnreads / inboxUnreadsQueryFn", () => {it("fetches /inbox/unreads and populates queryClient at communityKeys.inboxUnreads()", async () => {apiFetchMock.mockResolvedValueOnce({ servers: [] })@@ -47,30 +35,24 @@ describe("useInboxMentions / inboxMentionsQueryFn", () => {})})-// The plan pins this invariant: `invalidateQueries({ queryKey: inbox() })`-// must refresh all three feeds. Step 3's WS reconciliation depends on this-// working, so we test it here — losing this behaviour would silently regress-// mention/unread refreshing.+// WS reconciliation invalidates the shared `inbox()` prefix — both feeds must+// pick it up, otherwise mentions or unread refreshes would silently drop.describe("communityKeys.inbox() prefix invalidation", () => {- it("invalidates all three inbox queries in a single call", async () => {+ it("invalidates both inbox queries in a single call", async () => {apiFetchMock- .mockResolvedValueOnce({ events: [] }).mockResolvedValueOnce({ servers: [] }).mockResolvedValueOnce({ mentions: [] })- const { inboxForYouQueryFn, inboxUnreadsQueryFn, inboxMentionsQueryFn } = await import(+ const { inboxUnreadsQueryFn, inboxMentionsQueryFn } = await import("./use-inbox")const qc = new QueryClient()- const forYouKey = communityKeys.inboxForYou()const unreadsKey = communityKeys.inboxUnreads()const mentionsKey = communityKeys.inboxMentions()- await qc.fetchQuery({ queryKey: forYouKey, queryFn: inboxForYouQueryFn })await qc.fetchQuery({ queryKey: unreadsKey, queryFn: inboxUnreadsQueryFn })await qc.fetchQuery({ queryKey: mentionsKey, queryFn: inboxMentionsQueryFn })await qc.invalidateQueries({ queryKey: communityKeys.inbox() })- expect(qc.getQueryState(forYouKey)?.isInvalidated).toBe(true)expect(qc.getQueryState(unreadsKey)?.isInvalidated).toBe(true)expect(qc.getQueryState(mentionsKey)?.isInvalidated).toBe(true)})diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.tsindex 4c73f518d..18a54d6c6 100644--- a/src/web/src/hooks/community/use-inbox.ts+++ b/src/web/src/hooks/community/use-inbox.ts@@ -3,44 +3,25 @@import { useQuery, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"-import type { ForYouEvent, UnreadServer, Mention } from "@/components/community/_types"+import type { UnreadServer, Mention } from "@/components/community/_types"// Frozen empty fallbacks — see `use-servers.ts` for the rationale.-const EMPTY_FORYOU: readonly ForYouEvent[] = Object.freeze([])const EMPTY_UNREADS: readonly UnreadServer[] = Object.freeze([])const EMPTY_MENTIONS: readonly Mention[] = Object.freeze([])/**- * The inbox popover shows three sibling feeds. Each has its own endpoint and+ * The inbox popover shows two sibling feeds. Each has its own endpoint and* its own query key nested under `communityKeys.inbox()` so a single* `invalidateQueries({ queryKey: communityKeys.inbox() })` — the WS-side- * pattern for cross-slice reconciliation — refreshes all three in one batch.+ * pattern for cross-slice reconciliation — refreshes both in one batch.*- * Rules the plan pins on this prefix (Step 3 depends on it):- * - `communityKeys.inboxForYou()`, `communityKeys.inboxUnreads()`, and- * `communityKeys.inboxMentions()` all extend `communityKeys.inbox()`.+ * Rules the plan pins on this prefix:+ * - `communityKeys.inboxUnreads()` and `communityKeys.inboxMentions()` both+ * extend `communityKeys.inbox()`.* - The hooks stay separate so consumers subscribe granularly (one feed's- * refresh doesn't re-render another).+ * refresh doesn't re-render the other).*/-export type ForYouResponse = { events: ForYouEvent[]; limit?: number }--export const inboxForYouQueryFn = () =>- apiFetch<ForYouResponse>("/api/community/inbox/foryou")--export function useInboxForYou(): UseQueryResult<ForYouResponse> & {- events: ForYouEvent[]-} {- const query = useQuery({- queryKey: communityKeys.inboxForYou(),- queryFn: inboxForYouQueryFn,- })- return {- ...query,- events: query.data?.events ?? (EMPTY_FORYOU as ForYouEvent[]),- }-}-export type UnreadsResponse = { servers: UnreadServer[] }export const inboxUnreadsQueryFn = () =>diff --git a/src/web/src/lib/query-keys.test.ts b/src/web/src/lib/query-keys.test.tsindex 89ad30a69..9bb845500 100644--- a/src/web/src/lib/query-keys.test.ts+++ b/src/web/src/lib/query-keys.test.ts@@ -83,7 +83,6 @@ describe("communityKeys", () => {const inbox = communityKeys.inbox()expect(inbox).toEqual(["community", "inbox"])expect(communityKeys.inboxUnreads()).toEqual([...inbox, "unreads"])- expect(communityKeys.inboxForYou()).toEqual([...inbox, "foryou"])expect(communityKeys.inboxMentions()).toEqual([...inbox, "mentions"])})diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.tsindex dd9357ad0..094b9eb7a 100644--- a/src/web/src/lib/query-keys.ts+++ b/src/web/src/lib/query-keys.ts@@ -5,8 +5,8 @@* - Every key is `as const` so its literal-tuple type is preserved for* `queryClient.setQueryData` / `invalidateQueries` inference.* - Every key derived from a parent extends the parent's tuple, so- * `invalidateQueries({ queryKey: communityKeys.inbox() })` invalidates all- * three inbox feeds under it, `invalidateQueries({ queryKey: communityKeys.server(id) })`+ * `invalidateQueries({ queryKey: communityKeys.inbox() })` invalidates both+ * inbox feeds under it, `invalidateQueries({ queryKey: communityKeys.server(id) })`* invalidates every subkey of that server, and so on.* - Parameterisation matches the underlying route params. Message list keys* include an optional cursor so pagination pages nest under a stable@@ -71,7 +71,6 @@ export const communityKeys = {// ── Inbox ───────────────────────────────────────────────────────────────inbox: () => [...communityKeys.all, "inbox"] as const,inboxUnreads: () => [...communityKeys.inbox(), "unreads"] as const,- inboxForYou: () => [...communityKeys.inbox(), "foryou"] as const,inboxMentions: () => [...communityKeys.inbox(), "mentions"] as const,// ── Social ──────────────────────────────────────────────────────────────