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(web): unify inbox attention read model (#840)
Generd8b94af9f58b
diff --git a/src/shared/src/community-attention.test.ts b/src/shared/src/community-attention.test.tsindex 710e3a5fe..a7f2df718 100644--- a/src/shared/src/community-attention.test.ts+++ b/src/shared/src/community-attention.test.ts@@ -25,6 +25,120 @@ const item = {createdAt: "2026-09-27T00:00:00.000Z",}+const included = {+ servers: [{ id: "s1", name: "One", discriminator: "0001" }],+ channels: [{+ id: "c1",+ serverId: "s1",+ name: "general",+ type: "text" as const,+ parentChannelId: null,+ parentMessageId: null,+ creatorId: "u1",+ archived: false,+ lastMessageAt: "2026-09-27T00:00:00.000Z",+ }],+ dms: [],+ profiles: [{+ userId: "u2",+ name: "Alice",+ discriminator: "0002",+ avatar: "",+ avatarVersion: 1,+ }],+ messages: [{+ id: "m7",+ channelId: "c1",+ type: "chat" as const,+ authorId: "u2",+ authorName: "Alice",+ seq: 7,+ createdAt: "2026-09-27T00:00:00.000Z",+ content: "hello",+ }],+}++function childThreadSnapshot() {+ return {+ scopes: [{+ ...scope,+ scopeId: "post",+ channelId: "post",+ parentChannelId: "forum",+ }],+ items: [],+ limit: 100,+ truncated: false,+ included: {+ servers: included.servers,+ channels: [{+ ...included.channels[0],+ id: "forum",+ name: "Ideas",+ type: "forum" as const,+ }, {+ ...included.channels[0],+ id: "post",+ name: "Launch",+ type: "thread" as const,+ parentChannelId: "forum",+ parentMessageId: "opener",+ openerSeq: 7,+ openerUnread: false,+ }],+ dms: [],+ profiles: [],+ messages: [{+ id: "opener",+ channelId: "forum",+ type: "chat" as const,+ seq: 7,+ createdAt: "2026-09-27T00:00:00.000Z",+ content: "Launch",+ }],+ },+ }+}++function dmSnapshot() {+ return {+ scopes: [{+ ...scope,+ scopeId: "dm",+ channelId: "dm",+ serverId: null,+ parentChannelId: null,+ attentionCount: 0,+ lastAttentionSeq: null,+ }],+ items: [],+ limit: 100,+ truncated: false,+ included: {+ servers: [],+ channels: [],+ dms: [{+ id: "dm",+ userId: "peer",+ name: "Peer",+ discriminator: "0002",+ avatar: "P",+ avatarVersion: 1,+ lastMessageAt: "2026-09-27T00:00:00.000Z",+ lastUnreadSeq: 7,+ }],+ profiles: [{+ userId: "peer",+ name: "Peer",+ discriminator: "0002",+ avatar: "P",+ avatarVersion: 1,+ }],+ messages: [],+ },+ }+}+describe("account attention wire schemas", () => {it("rejects invalid attention-item reference shapes", () => {expect(AttentionItemSchema.safeParse({@@ -36,14 +150,30 @@ describe("account attention wire schemas", () => {scopeId: null,messageId: null,}).success).toBe(false)+ expect(AttentionItemSchema.safeParse({+ id: "friend_request:f1",+ kind: "friend_request",+ sourceId: "f1",+ scopeId: null,+ messageId: null,+ actorUserId: "u2",+ childChannelId: "post",+ createdAt: item.createdAt,+ }).success).toBe(false)+ expect(AttentionItemSchema.safeParse({ ...item, actorUserId: null }).success).toBe(false)+ expect(AttentionItemSchema.safeParse({+ ...item,+ childChannelId: "post",+ }).success).toBe(false)})- it("accepts ref-only snapshots and the existing reply kind", () => {+ it("accepts self-contained snapshots and the existing reply kind", () => {expect(AccountAttentionSnapshotSchema.parse({scopes: [scope],items: [item, { ...item, id: "mention:a2", sourceId: "a2", kind: "reply" }],limit: 100,truncated: false,+ included,}).items).toHaveLength(2)})@@ -53,6 +183,7 @@ describe("account attention wire schemas", () => {items: [{ ...item, actorName: "Alice", content: "hello" }],limit: 100,truncated: false,+ included,}).success).toBe(false)})@@ -62,12 +193,174 @@ describe("account attention wire schemas", () => {items: [item, item],limit: 100,truncated: false,+ included,+ }).success).toBe(false)+ expect(AccountAttentionSnapshotSchema.safeParse({+ scopes: [],+ items: [item],+ limit: 100,+ truncated: false,+ included,+ }).success).toBe(false)+ })++ it("rejects a scope whose canonical owner graph is incomplete", () => {+ expect(AccountAttentionSnapshotSchema.safeParse({+ scopes: [scope],+ items: [item],+ limit: 100,+ truncated: false,+ included: { ...included, servers: [] },}).success).toBe(false)+ })++ it("validates every child-thread parent and opener edge", () => {+ const valid = childThreadSnapshot()+ expect(AccountAttentionSnapshotSchema.safeParse(valid).success).toBe(true)++ const broken = [+ (candidate: ReturnType<typeof childThreadSnapshot>) => {+ candidate.included.channels[1]!.parentChannelId = null+ },+ (candidate: ReturnType<typeof childThreadSnapshot>) => {+ candidate.included.channels.splice(0, 1)+ },+ (candidate: ReturnType<typeof childThreadSnapshot>) => {+ candidate.included.channels[0]!.serverId = "other-server"+ },+ (candidate: ReturnType<typeof childThreadSnapshot>) => {+ candidate.included.channels[1]!.parentMessageId = null+ },+ (candidate: ReturnType<typeof childThreadSnapshot>) => {+ candidate.included.messages[0]!.channelId = "post"+ },+ (candidate: ReturnType<typeof childThreadSnapshot>) => {+ Object.assign(candidate.included.channels[1]!, { openerSeq: 6 })+ },+ (candidate: ReturnType<typeof childThreadSnapshot>) => {+ Reflect.deleteProperty(candidate.included.channels[1]!, "openerUnread")+ },+ ]+ for (const mutate of broken) {+ const candidate = structuredClone(valid)+ mutate(candidate)+ expect(AccountAttentionSnapshotSchema.safeParse(candidate).success).toBe(false)+ }++ const topLevelMismatch = childThreadSnapshot()+ Object.assign(topLevelMismatch.scopes[0]!, { parentChannelId: null })+ expect(AccountAttentionSnapshotSchema.safeParse(topLevelMismatch).success).toBe(false)+ })++ it("requires a DM scope to carry both its DM and profile owners", () => {+ const valid = dmSnapshot()+ expect(AccountAttentionSnapshotSchema.safeParse(valid).success).toBe(true)++ const missingDm = dmSnapshot()+ missingDm.included.dms = []+ expect(AccountAttentionSnapshotSchema.safeParse(missingDm).success).toBe(false)++ const missingProfile = dmSnapshot()+ missingProfile.included.profiles = []+ expect(AccountAttentionSnapshotSchema.safeParse(missingProfile).success).toBe(false)+ })++ it("rejects friend and message items without their canonical owners", () => {expect(AccountAttentionSnapshotSchema.safeParse({scopes: [],+ items: [{+ id: "friend_request:f1",+ kind: "friend_request",+ sourceId: "f1",+ scopeId: null,+ messageId: null,+ actorUserId: "missing",+ createdAt: item.createdAt,+ }],+ limit: 100,+ truncated: false,+ included: { ...included, profiles: [] },+ }).success).toBe(false)++ expect(AccountAttentionSnapshotSchema.safeParse({+ scopes: [scope],+ items: [{ ...item, scopeId: null }],+ limit: 100,+ truncated: false,+ included,+ }).success).toBe(false)++ expect(AccountAttentionSnapshotSchema.safeParse({+ scopes: [scope],items: [item],limit: 100,truncated: false,+ included: {+ ...included,+ messages: [{ ...included.messages[0], channelId: "other" }],+ },+ }).success).toBe(false)+ })++ it("requires exact forum-post parent, child, opener, and read-target refs", () => {+ const forumScope = { ...scope, scopeId: "forum", channelId: "forum" }+ const forumIncluded = {+ ...included,+ channels: [{+ ...included.channels[0],+ id: "forum",+ name: "ideas",+ type: "forum" as const,+ }, {+ ...included.channels[0],+ id: "post",+ name: "Launch",+ type: "thread" as const,+ parentChannelId: "forum",+ parentMessageId: "opener",+ }],+ messages: [{+ id: "opener",+ channelId: "forum",+ type: "chat" as const,+ seq: 7,+ createdAt: "2026-09-27T00:00:00.000Z",+ content: "Launch",+ }],+ }+ const forumPost = {+ id: "forum_post:post",+ kind: "forum_post" as const,+ sourceId: "post",+ scopeId: "forum",+ messageId: "opener",+ actorUserId: null,+ childChannelId: "post",+ openerSeq: 7,+ readTarget: { channelId: "forum", seq: 7 },+ createdAt: "2026-09-27T00:00:00.000Z",+ }++ expect(AccountAttentionSnapshotSchema.safeParse({+ scopes: [forumScope],+ items: [forumPost],+ limit: 100,+ truncated: false,+ included: forumIncluded,+ }).success).toBe(true)+ expect(AccountAttentionSnapshotSchema.safeParse({+ scopes: [forumScope],+ items: [{ ...forumPost, readTarget: { channelId: "forum", seq: 6 } }],+ limit: 100,+ truncated: false,+ included: forumIncluded,+ }).success).toBe(false)+ expect(AccountAttentionSnapshotSchema.safeParse({+ scopes: [forumScope],+ items: [{ ...forumPost, readTarget: { channelId: "wrong", seq: 7 } }],+ limit: 100,+ truncated: false,+ included: forumIncluded,}).success).toBe(false)})})diff --git a/src/shared/src/community-attention.ts b/src/shared/src/community-attention.tsindex e4a538fa8..38353b182 100644--- a/src/shared/src/community-attention.ts+++ b/src/shared/src/community-attention.ts@@ -15,27 +15,108 @@ export const AttentionScopeSchema = z.strictObject({export const AttentionItemSchema = z.strictObject({id,- kind: z.enum(["mention", "reply", "friend_request"]),+ kind: z.enum(["mention", "reply", "friend_request", "forum_post"]),sourceId: id,scopeId: id.nullable().optional(),messageId: id.nullable().optional(),- actorUserId: id,+ actorUserId: id.nullable().optional(),createdAt: z.string(),+ childChannelId: id.optional(),+ openerSeq: z.number().int().nonnegative().optional(),+ readTarget: z.strictObject({+ channelId: id,+ seq: z.number().int().nonnegative(),+ }).optional(),}).superRefine((item, ctx) => {if (item.kind === "friend_request") {- if (item.scopeId != null || item.messageId != null) {+ if (!item.actorUserId || item.scopeId != null || item.messageId != null) {ctx.addIssue({ code: "custom", message: "friend request cannot reference a scope or message" })}+ if (item.childChannelId || item.openerSeq !== undefined || item.readTarget) {+ ctx.addIssue({ code: "custom", message: "friend request cannot carry forum presentation refs" })+ }return}if (!item.scopeId || !item.messageId) {ctx.addIssue({ code: "custom", message: "message attention requires scope and message refs" })}+ if (item.kind === "forum_post") {+ if (+ item.actorUserId != null+ || !item.childChannelId+ || item.openerSeq === undefined+ || !item.readTarget+ || item.sourceId !== item.childChannelId+ || item.readTarget.seq !== item.openerSeq+ ) {+ ctx.addIssue({ code: "custom", message: "forum post requires exact child, opener, and read-target refs" })+ }+ return+ }+ if (!item.actorUserId) {+ ctx.addIssue({ code: "custom", message: "message attention requires an actor" })+ }+ if (item.childChannelId || item.openerSeq !== undefined || item.readTarget) {+ ctx.addIssue({ code: "custom", message: "mention or reply cannot carry forum presentation refs" })+ }+})++export const AttentionIncludedServerSchema = z.strictObject({+ id,+ name: z.string(),+ discriminator: z.string(),+})++export const AttentionIncludedChannelSchema = z.strictObject({+ id,+ serverId: id,+ name: z.string(),+ type: z.enum(["text", "forum", "thread"]),+ parentChannelId: id.nullable(),+ parentMessageId: id.nullable(),+ creatorId: id.nullable(),+ archived: z.boolean(),+ lastMessageAt: z.string().nullable(),+ openerSeq: z.number().int().nonnegative().optional(),+ openerUnread: z.boolean().optional(),+})++export const AttentionIncludedDmSchema = z.strictObject({+ id,+ userId: id,+ name: z.string(),+ discriminator: z.string(),+ avatar: z.string(),+ avatarVersion: z.number().int().nonnegative(),+ lastMessageAt: z.string(),+ lastUnreadSeq: z.number().int().nonnegative(),+})++export const AttentionIncludedProfileSchema = z.strictObject({+ userId: id,+ name: z.string(),+ discriminator: z.string(),+ avatar: z.string(),+ avatarVersion: z.number().int().nonnegative(),+})++export const AttentionIncludedMessageSchema = z.strictObject({+ id,+ channelId: id,+ type: z.enum(["chat", "system"]),+ authorId: id.optional(),+ authorName: z.string().optional(),+ seq: z.number().int().nonnegative(),+ createdAt: z.string(),+ content: z.string(),})export const AttentionIncludedSchema = z.strictObject({- profiles: z.array(z.unknown()).optional(),- messages: z.array(z.unknown()).optional(),+ servers: z.array(AttentionIncludedServerSchema),+ channels: z.array(AttentionIncludedChannelSchema),+ dms: z.array(AttentionIncludedDmSchema),+ profiles: z.array(AttentionIncludedProfileSchema),+ messages: z.array(AttentionIncludedMessageSchema),})export const AccountAttentionSnapshotSchema = z.strictObject({@@ -43,7 +124,7 @@ export const AccountAttentionSnapshotSchema = z.strictObject({items: z.array(AttentionItemSchema),limit: z.number().int().positive(),truncated: z.boolean(),- included: AttentionIncludedSchema.optional(),+ included: AttentionIncludedSchema,}).superRefine((snapshot, ctx) => {const scopeIds = new Set<string>()for (const scope of snapshot.scopes) {@@ -53,6 +134,56 @@ export const AccountAttentionSnapshotSchema = z.strictObject({scopeIds.add(scope.scopeId)}const itemIds = new Set<string>()+ const serverById = new Map(snapshot.included.servers.map((server) => [server.id, server]))+ const channelById = new Map(snapshot.included.channels.map((channel) => [channel.id, channel]))+ const dmById = new Map(snapshot.included.dms.map((dm) => [dm.id, dm]))+ const profileById = new Map(snapshot.included.profiles.map((profile) => [profile.userId, profile]))+ const messageById = new Map(snapshot.included.messages.map((message) => [message.id, message]))+ const rejectDuplicates = (values: string[], kind: string) => {+ const seen = new Set<string>()+ for (const value of values) {+ if (seen.has(value)) ctx.addIssue({ code: "custom", message: `duplicate included ${kind}: ${value}` })+ seen.add(value)+ }+ }+ rejectDuplicates(snapshot.included.servers.map((server) => server.id), "server")+ rejectDuplicates(snapshot.included.channels.map((channel) => channel.id), "channel")+ rejectDuplicates(snapshot.included.dms.map((dm) => dm.id), "dm")+ rejectDuplicates(snapshot.included.profiles.map((profile) => profile.userId), "profile")+ rejectDuplicates(snapshot.included.messages.map((message) => message.id), "message")+ for (const scope of snapshot.scopes) {+ if (scope.serverId) {+ const channel = channelById.get(scope.channelId)+ if (!serverById.has(scope.serverId) || !channel || channel.serverId !== scope.serverId) {+ ctx.addIssue({ code: "custom", message: `attention scope references missing owner: ${scope.scopeId}` })+ continue+ }+ if (scope.parentChannelId) {+ const parent = channelById.get(scope.parentChannelId)+ const opener = channel.parentMessageId+ ? messageById.get(channel.parentMessageId)+ : undefined+ if (+ channel.parentChannelId !== scope.parentChannelId+ || !parent+ || parent.serverId !== scope.serverId+ || !opener+ || opener.channelId !== parent.id+ || channel.openerSeq !== opener.seq+ || channel.openerUnread === undefined+ ) {+ ctx.addIssue({ code: "custom", message: `attention scope references missing parent: ${scope.scopeId}` })+ }+ } else if (channel.parentChannelId !== null) {+ ctx.addIssue({ code: "custom", message: `attention scope parent mismatch: ${scope.scopeId}` })+ }+ } else {+ const dm = dmById.get(scope.channelId)+ if (!dm || !profileById.has(dm.userId)) {+ ctx.addIssue({ code: "custom", message: `attention scope references missing DM owner: ${scope.scopeId}` })+ }+ }+ }for (const item of snapshot.items) {if (itemIds.has(item.id)) {ctx.addIssue({ code: "custom", message: `duplicate attention item: ${item.id}` })@@ -61,6 +192,44 @@ export const AccountAttentionSnapshotSchema = z.strictObject({if (item.scopeId && !scopeIds.has(item.scopeId)) {ctx.addIssue({ code: "custom", message: `attention item references missing scope: ${item.scopeId}` })}+ if (item.kind === "friend_request") {+ if (!item.actorUserId || !profileById.has(item.actorUserId)) {+ ctx.addIssue({ code: "custom", message: `friend request references missing profile: ${item.id}` })+ }+ continue+ }+ const scope = item.scopeId+ ? snapshot.scopes.find((candidate) => candidate.scopeId === item.scopeId)+ : undefined+ const message = item.messageId ? messageById.get(item.messageId) : undefined+ if (!scope || !message) {+ ctx.addIssue({ code: "custom", message: `attention item references missing message: ${item.id}` })+ continue+ }+ if (item.kind === "forum_post") {+ const parent = channelById.get(scope.channelId)+ const child = item.childChannelId ? channelById.get(item.childChannelId) : undefined+ if (+ !scope.serverId+ || parent?.type !== "forum"+ || child?.type !== "thread"+ || child.parentChannelId !== parent.id+ || child.parentMessageId !== message.id+ || message.channelId !== parent.id+ || message.seq !== item.openerSeq+ || item.readTarget?.channelId !== parent.id+ ) {+ ctx.addIssue({ code: "custom", message: `forum post references incomplete presentation owners: ${item.id}` })+ }+ continue+ }+ if (+ message.channelId !== scope.channelId+ || !item.actorUserId+ || !profileById.has(item.actorUserId)+ ) {+ ctx.addIssue({ code: "custom", message: `message attention references incomplete owners: ${item.id}` })+ }}})diff --git a/src/shared/src/db/queries/community/attention.test.ts b/src/shared/src/db/queries/community/attention.test.tsindex 9ac03996b..64fb9850b 100644--- a/src/shared/src/db/queries/community/attention.test.ts+++ b/src/shared/src/db/queries/community/attention.test.ts@@ -7,12 +7,21 @@ const mocks = vi.hoisted(() => ({listActionableIncomingRequests: vi.fn(),listUnreadMentionScopes: vi.fn(),listUnreadMentions: vi.fn(),+ getChannelsByIds: vi.fn(),+ getServersByIds: vi.fn(),+ listUnreadForumOpeners: vi.fn(),+ listThreadOpenersByChildIds: vi.fn(),}))-vi.mock("./channel", () => ({ listVisibleChannelIdsForUser: mocks.listVisibleChannelIdsForUser }))+vi.mock("./channel", () => ({+ listVisibleChannelIdsForUser: mocks.listVisibleChannelIdsForUser,+ getChannelsByIds: mocks.getChannelsByIds,+}))vi.mock("./inbox", () => ({listEligibleUnreadChannels: mocks.listEligibleUnreadChannels,listEligibleUnreadDms: mocks.listEligibleUnreadDms,+ listUnreadForumOpeners: mocks.listUnreadForumOpeners,+ listThreadOpenersByChildIds: mocks.listThreadOpenersByChildIds,}))vi.mock("./friendship", () => ({listActionableIncomingRequests: mocks.listActionableIncomingRequests,@@ -21,6 +30,7 @@ vi.mock("./mention", () => ({listUnreadMentionScopes: mocks.listUnreadMentionScopes,listUnreadMentions: mocks.listUnreadMentions,}))+vi.mock("./server", () => ({ getServersByIds: mocks.getServersByIds }))import { DEFAULT_ATTENTION_ITEM_LIMIT, getAccountAttentionSnapshot } from "./attention"@@ -28,10 +38,23 @@ beforeEach(() => {vi.clearAllMocks()mocks.listVisibleChannelIdsForUser.mockResolvedValue([])mocks.listEligibleUnreadChannels.mockResolvedValue([])- mocks.listEligibleUnreadDms.mockResolvedValue([{ channelId: "dm_1", lastUnreadSeq: 4 }])+ mocks.listEligibleUnreadDms.mockResolvedValue([{+ channelId: "dm_1",+ otherUserId: "user_2",+ otherUserName: "Peer",+ otherUserDiscriminator: "0002",+ otherUserImage: null,+ otherUserAvatarVersion: 1,+ lastMessageAt: "2026-09-27T00:00:00.000Z",+ lastUnreadSeq: 4,+ }])mocks.listActionableIncomingRequests.mockResolvedValue([])mocks.listUnreadMentionScopes.mockResolvedValue([])mocks.listUnreadMentions.mockResolvedValue([])+ mocks.getChannelsByIds.mockResolvedValue([])+ mocks.getServersByIds.mockResolvedValue([])+ mocks.listUnreadForumOpeners.mockResolvedValue([])+ mocks.listThreadOpenersByChildIds.mockResolvedValue([])})describe("getAccountAttentionSnapshot", () => {@@ -49,5 +72,114 @@ describe("getAccountAttentionSnapshot", () => {lastAttentionSeq: null,attentionCount: 0,}])+ expect(snapshot.included.dms).toEqual([expect.objectContaining({+ id: "dm_1",+ userId: "user_2",+ })])+ })++ it("skips channel rows that cannot become canonical owners", async () => {+ mocks.listEligibleUnreadDms.mockResolvedValue([])+ mocks.listEligibleUnreadChannels.mockResolvedValue([{+ channelId: "c1",+ serverId: "s1",+ parentChannelId: null,+ type: "text",+ lastUnreadSeq: 4,+ }])+ mocks.getChannelsByIds.mockResolvedValue([{+ id: "c1",+ serverId: "s1",+ name: null,+ type: "text",+ parentChannelId: null,+ parentMessageId: null,+ }])+ mocks.getServersByIds.mockResolvedValue([{+ id: "s1", name: "Server", discriminator: "0001",+ }])++ const snapshot = await getAccountAttentionSnapshot({} as never, "user_1")++ expect(snapshot.included.channels).toEqual([])+ expect(snapshot.scopes).toEqual([])+ })++ it("drops a scope whose canonical channel belongs to another server", async () => {+ mocks.listEligibleUnreadDms.mockResolvedValue([])+ mocks.listEligibleUnreadChannels.mockResolvedValue([{+ channelId: "c1",+ serverId: "s1",+ parentChannelId: null,+ type: "text",+ lastUnreadSeq: 4,+ }])+ mocks.getChannelsByIds.mockResolvedValue([{+ id: "c1",+ serverId: "s2",+ name: "General",+ type: "text",+ parentChannelId: null,+ parentMessageId: null,+ creatorId: null,+ archived: false,+ lastMessageAt: null,+ }])+ mocks.getServersByIds.mockResolvedValue([{+ id: "s2", name: "Other", discriminator: "0002",+ }])++ const snapshot = await getAccountAttentionSnapshot({} as never, "user_1")++ expect(snapshot.included.channels).toHaveLength(1)+ expect(snapshot.scopes).toEqual([])+ })++ it("drops a forum presentation whose child does not own the opener", async () => {+ mocks.listEligibleUnreadDms.mockResolvedValue([])+ mocks.listEligibleUnreadChannels.mockResolvedValue([{+ channelId: "forum",+ serverId: "s1",+ parentChannelId: null,+ type: "forum",+ lastUnreadSeq: 7,+ }])+ mocks.listUnreadForumOpeners.mockResolvedValue([{+ forumChannelId: "forum",+ openerMessageId: "opener",+ childChannelId: "post",+ title: "Launch",+ createdAt: "2026-09-27T00:00:00.000Z",+ openerSeq: 7,+ }])+ mocks.getChannelsByIds.mockResolvedValue([{+ id: "forum",+ serverId: "s1",+ name: "Ideas",+ type: "forum",+ parentChannelId: null,+ parentMessageId: null,+ creatorId: null,+ archived: false,+ lastMessageAt: null,+ }, {+ id: "post",+ serverId: "s1",+ name: "Launch",+ type: "thread",+ parentChannelId: "forum",+ parentMessageId: "different-opener",+ creatorId: null,+ archived: false,+ lastMessageAt: null,+ }])+ mocks.getServersByIds.mockResolvedValue([{+ id: "s1", name: "Server", discriminator: "0001",+ }])++ const snapshot = await getAccountAttentionSnapshot({} as never, "user_1")++ expect(snapshot.scopes).toHaveLength(1)+ expect(snapshot.items.filter((item) => item.kind === "forum_post")).toEqual([])})})diff --git a/src/shared/src/db/queries/community/attention.ts b/src/shared/src/db/queries/community/attention.tsindex c0ad79bcb..1c6074ad6 100644--- a/src/shared/src/db/queries/community/attention.ts+++ b/src/shared/src/db/queries/community/attention.ts@@ -4,14 +4,23 @@ import type {AttentionScope,} from "../../../community-attention"import type { Database } from "../../index"-import { listVisibleChannelIdsForUser } from "./channel"-import { listEligibleUnreadChannels, listEligibleUnreadDms } from "./inbox"+import { getChannelsByIds, listVisibleChannelIdsForUser } from "./channel"+import {+ listEligibleUnreadChannels,+ listEligibleUnreadDms,+ listThreadOpenersByChildIds,+ listUnreadForumOpeners,+} from "./inbox"import { listUnreadMentions, listUnreadMentionScopes } from "./mention"import { listActionableIncomingRequests } from "./friendship"+import { getServersByIds } from "./server"export const DEFAULT_ATTENTION_ITEM_LIMIT = 100export const MAX_ATTENTION_ITEM_LIMIT = 200+type IncludedProfile = AccountAttentionSnapshot["included"]["profiles"][number]+type IncludedMessage = AccountAttentionSnapshot["included"]["messages"][number]+/*** Stateless account-attention projection over the existing inbox facts.* The item cap applies only to mention/reply rows; actionable friend requests@@ -75,7 +84,89 @@ export async function getAccountAttentionSnapshot(attentionCount: row.attentionCount,})}- const scopes = [...scopesById.values()]+ const preliminaryScopes = [...scopesById.values()]++ const forumParentIds = [...new Set(channelRows.flatMap((row) => (+ !row.parentChannelId && row.type === "forum" ? [row.channelId] : []+ )))]+ const unreadChildIds = [...new Set(preliminaryScopes.flatMap((scope) => (+ scope.serverId && scope.parentChannelId ? [scope.channelId] : []+ )))]+ const [allForumOpeners, childThreadOpeners] = await Promise.all([+ listUnreadForumOpeners(db, userId, forumParentIds),+ listThreadOpenersByChildIds(db, userId, unreadChildIds),+ ])+ const displayedForumOpeners = allForumOpeners+ const childThreadOpenerByChildId = new Map(+ childThreadOpeners.map((opener) => [opener.childChannelId, opener]),+ )+ const displayedForumOpenerByChildId = new Map(+ displayedForumOpeners.map((opener) => [opener.childChannelId, opener]),+ )+ const channelOwnerIds = [...new Set([+ ...preliminaryScopes.flatMap((scope) => scope.serverId ? [scope.channelId] : []),+ ...preliminaryScopes.flatMap((scope) => scope.parentChannelId ? [scope.parentChannelId] : []),+ ...displayedForumOpeners.map((opener) => opener.childChannelId),+ ])]+ const channelOwners = await getChannelsByIds(db, channelOwnerIds)+ const includedChannels = channelOwners.flatMap((channel) => {+ if (+ !channel.serverId+ || !channel.name+ || channel.type !== "text" && channel.type !== "forum" && channel.type !== "thread"+ ) return []+ const opener = childThreadOpenerByChildId.get(channel.id)+ ?? displayedForumOpenerByChildId.get(channel.id)+ return [{+ id: channel.id,+ serverId: channel.serverId,+ name: channel.name,+ type: channel.type,+ parentChannelId: channel.parentChannelId ?? null,+ parentMessageId: channel.parentMessageId ?? null,+ creatorId: channel.creatorId ?? null,+ archived: channel.archived === true || channel.archived === 1,+ lastMessageAt: channel.lastMessageAt ?? null,+ ...(opener ? {+ openerSeq: opener.openerSeq,+ openerUnread: "openerUnread" in opener ? opener.openerUnread : true,+ } : {}),+ }]+ })+ const channelOwnerById = new Map(includedChannels.map((channel) => [channel.id, channel]))+ const serverOwnerIds = [...new Set(includedChannels.map((channel) => channel.serverId))]+ const serverOwners = await getServersByIds(db, serverOwnerIds)+ const includedServers = serverOwners.map((server) => ({+ id: server.id,+ name: server.name,+ discriminator: server.discriminator,+ }))+ const serverOwnerById = new Map(includedServers.map((server) => [server.id, server]))+ const includedDms = dmRows.map((row) => ({+ id: row.channelId,+ userId: row.otherUserId,+ name: row.otherUserName,+ discriminator: row.otherUserDiscriminator,+ avatar: row.otherUserImage ?? "",+ avatarVersion: row.otherUserAvatarVersion,+ lastMessageAt: row.lastMessageAt,+ lastUnreadSeq: row.lastUnreadSeq,+ }))+ const dmOwnerById = new Map(includedDms.map((dm) => [dm.id, dm]))+ const scopes = preliminaryScopes.filter((scope) => {+ if (!scope.serverId) return dmOwnerById.has(scope.channelId)+ const channel = channelOwnerById.get(scope.channelId)+ if (!channel || channel.serverId !== scope.serverId || !serverOwnerById.has(scope.serverId)) {+ return false+ }+ if (!scope.parentChannelId) return channel.parentChannelId === null+ const parent = channelOwnerById.get(scope.parentChannelId)+ const opener = childThreadOpenerByChildId.get(scope.channelId)+ return channel.parentChannelId === scope.parentChannelId+ && parent?.serverId === scope.serverId+ && channel.parentMessageId === opener?.openerMessageId+ })+ const survivingScopeIds = new Set(scopes.map((scope) => scope.scopeId))// The aggregate and bounded item reads are independent primary statements.// A mention may be created/deleted between them, so fence the composed@@ -83,7 +174,7 @@ export async function getAccountAttentionSnapshot(// snapshot. A reverse race may leave a scope with no item until reconcile,// which remains schema-valid and preserves its exact aggregate count.const eligibleMentionRows = allMentionRows.filter((row) => (- Boolean(row.message.channelId && scopesById.has(row.message.channelId))+ Boolean(row.message.channelId && survivingScopeIds.has(row.message.channelId))))const displayedMentionRows = eligibleMentionRows.slice(0, limit)const exactMentionCount = mentionScopeRows.reduce(@@ -99,6 +190,31 @@ export async function getAccountAttentionSnapshot(actorUserId: row.author.id,createdAt: row.message.createdAt,}))+ const forumItems: AttentionItem[] = displayedForumOpeners.flatMap((row) => {+ const scope = scopesById.get(row.forumChannelId)+ const parent = channelOwnerById.get(row.forumChannelId)+ const child = channelOwnerById.get(row.childChannelId)+ if (+ !scope+ || !survivingScopeIds.has(scope.scopeId)+ || parent?.type !== "forum"+ || child?.type !== "thread"+ || child.parentChannelId !== parent.id+ || child.parentMessageId !== row.openerMessageId+ ) return []+ return [{+ id: `forum_post:${row.childChannelId}`,+ kind: "forum_post" as const,+ sourceId: row.childChannelId,+ scopeId: scope.scopeId,+ messageId: row.openerMessageId,+ actorUserId: null,+ childChannelId: row.childChannelId,+ openerSeq: row.openerSeq,+ readTarget: { channelId: row.forumChannelId, seq: row.openerSeq },+ createdAt: row.createdAt,+ }]+ })const friendItems: AttentionItem[] = friendRows.map((row) => ({id: `friend_request:${row.id}`,kind: "friend_request",@@ -108,10 +224,10 @@ export async function getAccountAttentionSnapshot(actorUserId: row.userId,createdAt: row.createdAt,}))- const items = [...mentionItems, ...friendItems]+ const items = [...mentionItems, ...forumItems, ...friendItems].sort((left, right) => right.createdAt.localeCompare(left.createdAt) || right.id.localeCompare(left.id))- const includedProfiles = new Map<string, Record<string, unknown>>()+ const includedProfiles = new Map<string, IncludedProfile>()for (const row of friendRows) {includedProfiles.set(row.userId, {userId: row.userId,@@ -130,16 +246,47 @@ export async function getAccountAttentionSnapshot(avatarVersion: row.author.avatarVersion,})}- const includedMessages = displayedMentionRows.map((row) => ({- id: row.message.id,- channelId: row.message.channelId!,- type: row.message.type === "system" ? "system" : "chat",- authorId: row.author.id,- authorName: row.author.name,- seq: row.message.seq,- createdAt: row.message.createdAt,- content: row.message.content ?? "",- }))+ for (const row of dmRows) {+ includedProfiles.set(row.otherUserId, {+ userId: row.otherUserId,+ name: row.otherUserName,+ discriminator: row.otherUserDiscriminator,+ avatar: row.otherUserImage ?? "",+ avatarVersion: row.otherUserAvatarVersion,+ })+ }+ const includedMessages = new Map<string, IncludedMessage>(+ displayedMentionRows.map((row): [string, IncludedMessage] => [row.message.id, {+ id: row.message.id,+ channelId: row.message.channelId!,+ type: row.message.type === "system" ? "system" : "chat",+ authorId: row.author.id,+ authorName: row.author.name,+ seq: row.message.seq,+ createdAt: row.message.createdAt,+ content: row.message.content ?? "",+ }]),+ )+ const openerByMessageId = new Map(+ [...childThreadOpeners, ...displayedForumOpeners.map((row) => ({+ parentChannelId: row.forumChannelId,+ openerMessageId: row.openerMessageId,+ title: row.title,+ createdAt: row.createdAt,+ openerSeq: row.openerSeq,+ }))].map((row) => [row.openerMessageId, row]),+ )+ for (const row of openerByMessageId.values()) {+ if (includedMessages.has(row.openerMessageId)) continue+ includedMessages.set(row.openerMessageId, {+ id: row.openerMessageId,+ channelId: row.parentChannelId,+ type: "chat",+ seq: row.openerSeq,+ createdAt: row.createdAt,+ content: row.title,+ })+ }return {scopes,@@ -147,8 +294,11 @@ export async function getAccountAttentionSnapshot(limit,truncated: exactMentionCount > limit,included: {+ servers: includedServers,+ channels: includedChannels,+ dms: includedDms,profiles: [...includedProfiles.values()],- messages: includedMessages,+ messages: [...includedMessages.values()],},}}diff --git a/src/shared/test/queries/community-attention.test.ts b/src/shared/test/queries/community-attention.test.tsindex 0764b314a..e92ed89ea 100644--- a/src/shared/test/queries/community-attention.test.ts+++ b/src/shared/test/queries/community-attention.test.ts@@ -7,14 +7,21 @@ const mocks = vi.hoisted(() => ({mentions: vi.fn(),mentionScopes: vi.fn(),friends: vi.fn(),+ channelOwners: vi.fn(),+ serverOwners: vi.fn(),+ forumOpeners: vi.fn(),+ threadOpeners: vi.fn(),}))vi.mock("../../src/db/queries/community/channel", () => ({listVisibleChannelIdsForUser: (...args: unknown[]) => mocks.visible(...args),+ getChannelsByIds: (...args: unknown[]) => mocks.channelOwners(...args),}))vi.mock("../../src/db/queries/community/inbox", () => ({listEligibleUnreadChannels: (...args: unknown[]) => mocks.channels(...args),listEligibleUnreadDms: (...args: unknown[]) => mocks.dms(...args),+ listUnreadForumOpeners: (...args: unknown[]) => mocks.forumOpeners(...args),+ listThreadOpenersByChildIds: (...args: unknown[]) => mocks.threadOpeners(...args),}))vi.mock("../../src/db/queries/community/mention", () => ({listUnreadMentions: (...args: unknown[]) => mocks.mentions(...args),@@ -23,6 +30,9 @@ vi.mock("../../src/db/queries/community/mention", () => ({vi.mock("../../src/db/queries/community/friendship", () => ({listActionableIncomingRequests: (...args: unknown[]) => mocks.friends(...args),}))+vi.mock("../../src/db/queries/community/server", () => ({+ getServersByIds: (...args: unknown[]) => mocks.serverOwners(...args),+}))import { getAccountAttentionSnapshot } from "../../src/db/queries/community/attention"import { AccountAttentionSnapshotSchema } from "../../src/community-attention"@@ -40,6 +50,24 @@ describe("account attention snapshot", () => {mentionCount: 9,}])mocks.dms.mockResolvedValue([])+ mocks.channelOwners.mockResolvedValue([{+ id: "c1",+ serverId: "s1",+ name: "general",+ type: "text",+ parentChannelId: null,+ parentMessageId: null,+ creatorId: "owner",+ archived: 0,+ lastMessageAt: "2026-09-27T00:00:02.000Z",+ }])+ mocks.serverOwners.mockResolvedValue([{+ id: "s1",+ name: "One",+ discriminator: "0001",+ }])+ mocks.forumOpeners.mockResolvedValue([])+ mocks.threadOpeners.mockResolvedValue([])mocks.mentionScopes.mockResolvedValue([{channelId: "c1",serverId: "s1",@@ -101,6 +129,37 @@ describe("account attention snapshot", () => {attentionCount: 3,lastAttentionSeq: 7,}])+ mocks.channelOwners.mockResolvedValue([{+ id: "c1",+ serverId: "s1",+ name: "Post",+ type: "thread",+ parentChannelId: "forum1",+ parentMessageId: "opener1",+ creatorId: "owner",+ archived: 0,+ lastMessageAt: "2026-09-27T00:00:02.000Z",+ }, {+ id: "forum1",+ serverId: "s1",+ name: "Ideas",+ type: "forum",+ parentChannelId: null,+ parentMessageId: null,+ creatorId: "owner",+ archived: 0,+ lastMessageAt: "2026-09-27T00:00:00.000Z",+ }])+ mocks.threadOpeners.mockResolvedValue([{+ parentChannelId: "forum1",+ parentType: "forum",+ openerMessageId: "opener1",+ childChannelId: "c1",+ title: "Post",+ createdAt: "2026-09-27T00:00:00.000Z",+ openerSeq: 1,+ openerUnread: false,+ }])const snapshot = await getAccountAttentionSnapshot({} as never, "viewer", 2)expect(snapshot.scopes).toEqual([{@@ -154,4 +213,61 @@ describe("account attention snapshot", () => {expect(snapshot.truncated).toBe(true)expect(() => AccountAttentionSnapshotSchema.parse(snapshot)).not.toThrow()})++ it("emits one explicit presentation unit for each unread forum opener", async () => {+ mocks.channels.mockResolvedValue([{+ channelId: "forum1",+ channelName: "Ideas",+ serverId: "s1",+ serverName: "One",+ type: "forum",+ parentChannelId: null,+ lastMessageAt: "2026-09-27T00:00:02.000Z",+ lastUnreadSeq: 2,+ lastAttentionSeq: null,+ mentionCount: 0,+ }])+ mocks.mentionScopes.mockResolvedValue([])+ mocks.mentions.mockResolvedValue([])+ mocks.friends.mockResolvedValue([])+ mocks.forumOpeners.mockResolvedValue([1, 2].map((seq) => ({+ forumChannelId: "forum1",+ openerMessageId: `opener${seq}`,+ childChannelId: `post${seq}`,+ title: `Post ${seq}`,+ createdAt: `2026-09-27T00:00:0${seq}.000Z`,+ openerSeq: seq,+ })))+ mocks.channelOwners.mockResolvedValue([{+ id: "forum1",+ serverId: "s1",+ name: "Ideas",+ type: "forum",+ parentChannelId: null,+ parentMessageId: null,+ creatorId: "owner",+ archived: 0,+ lastMessageAt: "2026-09-27T00:00:02.000Z",+ }, ...[1, 2].map((seq) => ({+ id: `post${seq}`,+ serverId: "s1",+ name: `Post ${seq}`,+ type: "thread",+ parentChannelId: "forum1",+ parentMessageId: `opener${seq}`,+ creatorId: "owner",+ archived: 0,+ lastMessageAt: `2026-09-27T00:00:0${seq}.000Z`,+ }))])++ const snapshot = await getAccountAttentionSnapshot({} as never, "viewer", 100)+ const posts = snapshot.items.filter((entry) => entry.kind === "forum_post")++ expect(posts).toEqual([+ expect.objectContaining({ sourceId: "post2", openerSeq: 2 }),+ expect.objectContaining({ sourceId: "post1", openerSeq: 1 }),+ ])+ expect(snapshot.items.filter((entry) => entry.kind === "mention")).toEqual([])+ expect(() => AccountAttentionSnapshotSchema.parse(snapshot)).not.toThrow()+ })})diff --git a/src/web/src/app/api/community/users/me/attention/route.test.ts b/src/web/src/app/api/community/users/me/attention/route.test.tsindex c85f77c7f..81c21a4dc 100644--- a/src/web/src/app/api/community/users/me/attention/route.test.ts+++ b/src/web/src/app/api/community/users/me/attention/route.test.ts@@ -45,7 +45,9 @@ describe("GET /api/community/users/me/attention", () => {items: [],limit: 100,truncated: false,- included: { profiles: [], messages: [] },+ included: {+ servers: [], channels: [], dms: [], profiles: [], messages: [],+ },})const response = await GET(new Request("http://localhost/api/community/users/me/attention") as any)@@ -54,4 +56,63 @@ describe("GET /api/community/users/me/attention", () => {expect(mocks.getPrimaryDb).toHaveBeenCalledWith({ binding: "d1" })expect(mocks.snapshot).toHaveBeenCalledWith({ kind: "primary-db" }, "u1", 100)})++ it("returns the same canonical avatar contract for included DMs and profiles", async () => {+ mocks.snapshot.mockResolvedValue({+ scopes: [{+ scopeId: "dm1",+ channelId: "dm1",+ serverId: null,+ parentChannelId: null,+ ordinaryUnread: true,+ lastUnreadSeq: 3,+ lastAttentionSeq: null,+ attentionCount: 0,+ }],+ items: [],+ limit: 100,+ truncated: false,+ included: {+ servers: [],+ channels: [],+ dms: [{+ id: "dm1",+ userId: "u2",+ name: "Alice",+ discriminator: "0002",+ avatar: "/api/community/users/u2/avatar",+ avatarVersion: 7,+ lastMessageAt: "2026-09-28T00:00:00.000Z",+ lastUnreadSeq: 3,+ }],+ profiles: [{+ userId: "u2",+ name: "Alice",+ discriminator: "0002",+ avatar: "/api/community/users/u2/avatar",+ avatarVersion: 7,+ }, {+ userId: "u3",+ name: "Bob",+ discriminator: "0003",+ avatar: "",+ avatarVersion: 0,+ }],+ messages: [],+ },+ })++ const response = await GET(new Request("http://localhost/api/community/users/me/attention") as any)+ const body = await response.json()++ expect(body.included.dms[0].avatar).toBe("/api/community/users/u2/avatar?v=7")+ expect(body.included.profiles).toEqual([+ expect.objectContaining({+ userId: "u2",+ avatar: "/api/community/users/u2/avatar?v=7",+ avatarVersion: 7,+ }),+ expect.objectContaining({ userId: "u3", avatar: "B", avatarVersion: 0 }),+ ])+ })})diff --git a/src/web/src/app/api/community/users/me/attention/route.ts b/src/web/src/app/api/community/users/me/attention/route.tsindex f878961b7..31bc7fb71 100644--- a/src/web/src/app/api/community/users/me/attention/route.ts+++ b/src/web/src/app/api/community/users/me/attention/route.ts@@ -6,10 +6,25 @@ import {readOrStale,} from "@alook/shared"import { getPrimaryDb } from "@/lib/db"+import { avatarInitial } from "@/lib/community/avatar"import { parseBoundedInt } from "@/lib/community/messages"+import { canonicalUserImage } from "@/lib/community/storage"import { withAuth } from "@/lib/middleware/auth"import { writeJSON } from "@/lib/middleware/helpers"+function canonicalizeIncludedAvatar<T extends {+ userId: string+ name: string+ avatar: string+ avatarVersion: number+}>(row: T): T {+ return {+ ...row,+ avatar: canonicalUserImage(row.userId, row.avatar, row.avatarVersion)+ ?? avatarInitial(row.name),+ }+}+export const GET = withAuth(async (request, ctx) => {const db = getPrimaryDb(ctx.env.DB)const url = new URL(request.url)@@ -25,10 +40,24 @@ export const GET = withAuth(async (request, ctx) => {items: [],limit,truncated: false,- included: { profiles: [], messages: [] },+ included: {+ servers: [],+ channels: [],+ dms: [],+ profiles: [],+ messages: [],+ },},{ route: "community/attention" },)- if (stale) return writeJSON({ ...value, stale: true })- return writeJSON(AccountAttentionSnapshotSchema.parse(value))+ const normalized = {+ ...value,+ included: {+ ...value.included,+ dms: value.included.dms.map(canonicalizeIncludedAvatar),+ profiles: value.included.profiles.map(canonicalizeIncludedAvatar),+ },+ }+ if (stale) return writeJSON({ ...normalized, stale: true })+ return writeJSON(AccountAttentionSnapshotSchema.parse(normalized))})diff --git a/src/web/src/app/api/community/users/me/inbox/mentions/route.test.ts b/src/web/src/app/api/community/users/me/inbox/mentions/route.test.tsdeleted file mode 100644index a2e34469f..000000000--- a/src/web/src/app/api/community/users/me/inbox/mentions/route.test.ts+++ /dev/null@@ -1,183 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--const mockListUnreadMentions = vi.fn()-const mockGetChannelsByIds = vi.fn()-const mockGetServersByIds = vi.fn()-const mockListVisibleChannelIds = 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: {- communityMention: {- listUnreadMentions: (...args: unknown[]) => mockListUnreadMentions(...args),- },- communityChannel: {- getChannelsByIds: (...args: unknown[]) => mockGetChannelsByIds(...args),- listVisibleChannelIdsForUser: (...args: unknown[]) => mockListVisibleChannelIds(...args),- },- communityServer: {- getServersByIds: (...args: unknown[]) => mockGetServersByIds(...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/users/me/inbox/mentions", () => {- beforeEach(() => {- vi.clearAllMocks()- mockGetChannelsByIds.mockResolvedValue([])- mockGetServersByIds.mockResolvedValue([])- mockListVisibleChannelIds.mockResolvedValue(["c1"])- })-- it("queries BOTH mention + reply kinds (no kind filter) scoped to visible channels", async () => {- mockListUnreadMentions.mockResolvedValue([])- await GET(new NextRequest("http://localhost/api/community/users/me/inbox/mentions"))- // No `kind` narrowing — both @-mentions and reply notifications surface.- const opts = mockListUnreadMentions.mock.calls[0][2]- expect(opts.kind).toBeUndefined()- expect(opts.visibleChannelIds).toEqual(["c1"])- })-- it("hydrates server + channel names and the mention kind into the response", async () => {- mockListUnreadMentions.mockResolvedValue([- {- mention: { id: "mn1", kind: "mention" },- message: { id: "m1", type: "system", seq: 4, channelId: "c1", content: "@u1 hi", createdAt: "2026-06-25T10:00:00Z" },- author: { id: "u-alice", name: "Alice", email: "[email protected]", image: null },- },- ])- mockGetChannelsByIds.mockResolvedValue([{- id: "c1",- name: "general",- serverId: "s1",- parentChannelId: "forum-1",- }])- mockGetServersByIds.mockResolvedValue([{ id: "s1", name: "Server 1" }])-- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/mentions"))- const body = await res.json()- expect(body.mentions).toHaveLength(1)- expect(body.mentions[0]).toMatchObject({- id: "mn1",- kind: "mention",- server: "Server 1",- serverId: "s1",- channel: "general",- channelId: "c1",- parentChannelId: "forum-1",- // authorId is the beam-avatar seed the inbox popover renders from- // (<Avatar seed={mn.m.authorId}>) — omitting it blanked image-less- // authors' avatars, same bug the pins route had.- m: { id: "m1", type: "system", seq: 4, authorId: "u-alice", authorName: "Alice", content: "@u1 hi" },- })- })-- it("normalizes an ordinary stored message to the canonical chat wire type", async () => {- mockListUnreadMentions.mockResolvedValue([{- mention: { id: "mn-default", kind: "mention" },- message: {- id: "m-default",- type: "default",- seq: 1,- channelId: "c1",- content: "hello",- createdAt: "2026-06-25T10:00:00Z",- },- author: { id: "u-alice", name: "Alice", image: null, avatarVersion: 0 },- }])- mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "general", serverId: "s1" }])- mockGetServersByIds.mockResolvedValue([{ id: "s1", name: "Server 1" }])-- const body = await (await GET(new NextRequest(- "http://localhost/api/community/users/me/inbox/mentions",- ))).json()- expect(body.mentions[0].m).toMatchObject({ id: "m-default", type: "chat" })- })-- it("tags reply-kind rows so the UI can label them 'replied to you'", async () => {- mockListUnreadMentions.mockResolvedValue([- {- mention: { id: "mn2", kind: "reply" },- message: { id: "m2", channelId: "c1", content: "sure", createdAt: "2026-06-25T11:00:00Z" },- author: { name: "Bob", email: "[email protected]", image: null },- },- ])- mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "general", serverId: "s1" }])- mockGetServersByIds.mockResolvedValue([{ id: "s1", name: "Server 1" }])- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/mentions"))- const body = await res.json()- expect(body.mentions[0].kind).toBe("reply")- })-- it("returns empty mentions array when none", async () => {- mockListUnreadMentions.mockResolvedValue([])- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/mentions"))- const body = await res.json()- expect(body.mentions).toEqual([])- })-- it("clamps over-cap limit and forwards it to the query", async () => {- mockListUnreadMentions.mockResolvedValue([])- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/mentions?limit=99999"))- const body = await res.json()- expect(body.limit).toBe(200) // MAX_INBOX_PAGE_SIZE- expect(mockListUnreadMentions).toHaveBeenCalledWith({}, "u1", { limit: 201, visibleChannelIds: ["c1"] })- })-- it("uses limit+1 evidence and reports truncation without returning the sentinel row", async () => {- mockListUnreadMentions.mockResolvedValue([- ...Array.from({ length: 20 }, (_, index) => ({- mention: { id: `mn${index}`, kind: "mention" },- message: {- id: `m${index}`,- seq: index + 1,- channelId: "c1",- content: "hi",- createdAt: `2026-06-25T10:${String(index).padStart(2, "0")}:00Z`,- },- author: { id: "u2", name: "Alice", image: null, avatarVersion: 0 },- })),- {- mention: { id: "sentinel", kind: "mention" },- message: { id: "sentinel-message", seq: 21, channelId: "c1", content: "x", createdAt: "2026-06-25T11:00:00Z" },- author: { id: "u2", name: "Alice", image: null, avatarVersion: 0 },- },- ])- mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "general", serverId: "s1" }])- mockGetServersByIds.mockResolvedValue([{ id: "s1", name: "Server 1" }])-- const body = await (await GET(new NextRequest(- "http://localhost/api/community/users/me/inbox/mentions?limit=20",- ))).json()- expect(body.truncated).toBe(true)- expect(body.mentions).toHaveLength(20)- expect(body.mentions.some((row: { id: string }) => row.id === "sentinel")).toBe(false)- })-})diff --git a/src/web/src/app/api/community/users/me/inbox/mentions/route.ts b/src/web/src/app/api/community/users/me/inbox/mentions/route.tsdeleted file mode 100644index 95fedce7f..000000000--- a/src/web/src/app/api/community/users/me/inbox/mentions/route.ts+++ /dev/null@@ -1,98 +0,0 @@-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON } from "@/lib/middleware/helpers"-import { getDb } from "@/lib/db"-import {- queries,- DEFAULT_INBOX_PAGE_SIZE,- MAX_INBOX_PAGE_SIZE,- readOrStale,-} from "@alook/shared"-import { parseBoundedInt } from "@/lib/community/messages"-import { avatarInitial } from "@/lib/community/avatar"-import { canonicalUserImage } from "@/lib/community/storage"-import { projectMessageWireType } from "@/lib/community/message-wire-type"--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,- )-- // Both `@`-mentions AND reply notifications surface in the Mentions tab now.- // Scope to the viewer's visible channels (scope-first, in-query) so a- // removed-from-private-channel user no longer sees leftover mentions; the- // `inArray(channelId, visibleIds)` also naturally excludes DM reply rows- // (channelId = NULL), which stay out of the Mentions tab by design.- type MentionRow = Awaited<ReturnType<typeof queries.communityMention.listUnreadMentions>>[number]- type ChannelRow = Awaited<ReturnType<typeof queries.communityChannel.getChannelsByIds>>[number]- type ServerRow = Awaited<ReturnType<typeof queries.communityServer.getServersByIds>>[number]- const { value: fetched, stale } = await readOrStale<{- rows: MentionRow[]- channels: ChannelRow[]- servers: ServerRow[]- }>(- async () => {- const visibleChannelIds = await queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId)- const rows = await queries.communityMention.listUnreadMentions(db, ctx.userId, {- limit: limit + 1,- visibleChannelIds,- })- const channelIds = [...new Set(rows.filter((r) => r.message.channelId).map((r) => r.message.channelId!))]- const channels = channelIds.length > 0 ? await queries.communityChannel.getChannelsByIds(db, channelIds) : []- const serverIds = [...new Set(channels.map((ch) => ch.serverId))]- const servers = serverIds.length > 0 ? await queries.communityServer.getServersByIds(db, serverIds) : []- return { rows, channels, servers }- },- { rows: [], channels: [], servers: [] },- { route: "community/inbox/mentions" },- )- if (stale) {- return writeJSON({ mentions: [], limit, stale: true })- }- const { rows: fetchedRows, channels, servers } = fetched- const truncated = fetchedRows.length > limit- const rows = fetchedRows.slice(0, limit)- const channelMap = new Map(channels.map((ch) => [ch.id, ch]))- const serverMap = new Map(servers.map((s) => [s.id, s]))-- const mentions = rows.map((row) => {- const ch = row.message.channelId ? channelMap.get(row.message.channelId) : undefined- const srv = ch ? serverMap.get(ch.serverId) : undefined- return {- id: row.mention.id,- // "mention" (@-mention) vs "reply" — the UI labels them differently- // ("mentioned you" vs "replied to you").- kind: row.mention.kind,- // Missing navigation rows are explicit unavailable states, never a- // visible "Unknown" identity generated by the system.- server: srv ? srv.name : "Server unavailable",- serverId: ch?.serverId,- channel: ch ? ch.name : "Conversation unavailable",- channelId: row.message.channelId,- parentChannelId: ch?.parentChannelId ?? null,- m: {- id: row.message.id,- ...projectMessageWireType(row.message.type),- seq: row.message.seq,- // authorId is the beam-avatar seed the popover renders from- // (<Avatar seed={authorId}>); omitting it left image-less authors with- // a blank avatar — same fix as the pins route.- authorId: row.author.id,- authorName: row.author.name,- authorAvatar: canonicalUserImage(- row.author.id,- row.author.image,- row.author.avatarVersion,- ) ?? avatarInitial(row.author.name),- authorAvatarVersion: row.author.avatarVersion,- content: row.message.content,- createdAt: row.message.createdAt,- },- }- })-- return writeJSON({ mentions, limit, truncated })-})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.tsdeleted file mode 100644index 4bd457735..000000000--- a/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts+++ /dev/null@@ -1,558 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--const mockListEligibleUnreadChannels = vi.fn()-const mockListUnreadForumOpeners = vi.fn()-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: {} } })),-}))--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: {- listEligibleUnreadChannels: (...args: unknown[]) => mockListEligibleUnreadChannels(...args),- listUnreadForumOpeners: (...args: unknown[]) => mockListUnreadForumOpeners(...args),- listThreadOpenersByChildIds: (...args: unknown[]) => mockListThreadOpenersByChildIds(...args),- listEligibleUnreadDms: (...args: unknown[]) => mockListEligibleUnreadDms(...args),- },- communityChannel: {- listVisibleChannelIdsForUser: (...args: unknown[]) => mockListVisibleChannelIds(...args),- getChannelsByIds: (...args: unknown[]) => mockGetChannelsByIds(...args),- },- communityFriendship: {- listActionableIncomingRequests: (...args: unknown[]) => mockListActionableIncomingRequests(...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"--function row(overrides: Partial<{ channelId: string; channelName: string; serverId: string; serverName: string; type: string | null; parentChannelId: string | null; lastMessageAt: string; lastReadAt: string | null; mentionCount: number }>) {- return {- channelId: "c1",- channelName: "general",- serverId: "s1",- serverName: "Server 1",- type: "text" as string | null,- parentChannelId: null,- lastMessageAt: "2026-06-25T10:00:00Z",- lastReadAt: null,- mentionCount: 0,- ...overrides,- }-}--function opener(overrides: Partial<{- forumChannelId: string- openerMessageId: string- childChannelId: string- title: string- createdAt: string- openerSeq: number-}> = {}) {- return {- forumChannelId: "f1",- openerMessageId: "m1",- childChannelId: "p1",- title: "Full opener content",- createdAt: "2026-06-25T10:00:00Z",- openerSeq: 1,- ...overrides,- }-}--function threadOpener(overrides: Partial<{- parentChannelId: string- parentType: string- openerMessageId: string- childChannelId: string- title: string- createdAt: string- openerSeq: number- openerUnread: boolean-}> = {}) {- return {- parentChannelId: "f1",- parentType: "forum",- openerMessageId: "m1",- childChannelId: "p1",- title: "Full opener content",- createdAt: "2026-06-25T10:00:00Z",- openerSeq: 1,- openerUnread: false,- ...overrides,- }-}--describe("GET /api/community/users/me/inbox/unreads", () => {- beforeEach(() => {- vi.clearAllMocks()- mockListEligibleUnreadDms.mockResolvedValue([])- mockListUnreadForumOpeners.mockResolvedValue([])- 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 () => {- mockListEligibleUnreadChannels.mockResolvedValue([- row({ serverId: "s1", channelId: "c1", channelName: "general", lastMessageAt: "2026-06-25T10:00:00Z" }),- row({ serverId: "s1", channelId: "c2", channelName: "releases", lastMessageAt: "2026-06-25T09:00:00Z" }),- row({ serverId: "s2", serverName: "Other", channelId: "c3", channelName: "lounge", lastMessageAt: "2026-06-25T11:00:00Z" }),- ])-- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))- const body = await res.json()-- expect(res.status).toBe(200)- expect(body.servers).toHaveLength(2)- // Most recent server first (s2 latest 11:00 > s1 latest 10:00)- expect(body.servers[0].serverId).toBe("s2")- expect(body.servers[1].serverId).toBe("s1")- // Channels sorted within a server, most recent first- expect(body.servers[1].channels.map((c: { channelId: string }) => c.channelId)).toEqual(["c1", "c2"])- })-- it("uses the mentionCount already aggregated over eligible unread", async () => {- mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "c1", mentionCount: 2 })])- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))- const body = await res.json()- expect(body.servers[0].channels[0].mentionCount).toBe(2)- })-- it("truncates by total channel count when over the limit", async () => {- // 3 channels under one server, limit=2 → only first 2 returned, truncated=true.- mockListEligibleUnreadChannels.mockResolvedValue([- row({ serverId: "s1", channelId: "c1", lastMessageAt: "2026-06-25T12:00:00Z" }),- row({ serverId: "s1", channelId: "c2", lastMessageAt: "2026-06-25T11:00:00Z" }),- row({ serverId: "s1", channelId: "c3", lastMessageAt: "2026-06-25T10:00:00Z" }),- ])-- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads?limit=2"))- const body = await res.json()-- expect(body.limit).toBe(2)- expect(body.truncated).toBe(true)- expect(body.servers[0].channels.map((c: { channelId: string }) => c.channelId)).toEqual(["c1", "c2"])- })-- it("reports truncated=false when total channel count fits the limit", async () => {- mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads?limit=10"))- const body = await res.json()- expect(body.truncated).toBe(false)- })-- it("returns unread DMs sorted most-recent first", async () => {- mockListEligibleUnreadChannels.mockResolvedValue([])- mockListEligibleUnreadDms.mockResolvedValue([- { channelId: "dm_1", otherUserId: "u2", otherUserName: "Alice", otherUserDiscriminator: "1111", otherUserImage: null, lastMessageAt: "2026-06-25T09:00:00Z" },- { channelId: "dm_2", otherUserId: "u3", otherUserName: "Bob", otherUserDiscriminator: "2222", otherUserImage: "https://cdn/b.png", lastMessageAt: "2026-06-25T11:00:00Z" },- ])-- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))- const body = await res.json()-- expect(res.status).toBe(200)- expect(body.dms).toHaveLength(2)- expect(body.dms[0].channelId).toBe("dm_2")- expect(body.dms[0].otherUserDiscriminator).toBe("2222")- expect(body.dms[0].otherUserAvatar).toBe("https://cdn/b.png")- expect(body.dms[1].channelId).toBe("dm_1")- // No cdn image → avatar falls back to the initial letter.- expect(body.dms[1].otherUserAvatar).toBe("A")- })-- it("returns empty dms array when only channels are unread", async () => {- mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])- mockListEligibleUnreadDms.mockResolvedValue([])- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))- const body = await res.json()- expect(body.dms).toEqual([])- expect(body.servers).toHaveLength(1)- })-- it("returns dms alongside servers when both have unreads", async () => {- mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])- mockListEligibleUnreadDms.mockResolvedValue([- { channelId: "dm_1", otherUserId: "u2", otherUserName: "Alice", otherUserDiscriminator: "1111", otherUserImage: null, lastMessageAt: "2026-06-25T12:00:00Z" },- ])- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))- const body = await res.json()- expect(body.servers).toHaveLength(1)- expect(body.dms).toHaveLength(1)- })-- // ── Threads / forum-posts as child sub-rows ────────────────────────────────-- it("nests an unread thread under its parent channel; parent surfaces w/o direct unread", async () => {- // Parent c1 has NO direct unread (not in the unread list); its child thread- // t1 does. The route must batch-resolve the parent's name via getChannelsByIds.- mockListEligibleUnreadChannels.mockResolvedValue([- row({ channelId: "t1", channelName: "budget-2026", parentChannelId: "c1", lastMessageAt: "2026-06-25T10:00:00Z" }),- ])- mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "general", serverId: "s1" }])-- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))- const body = await res.json()-- expect(res.status).toBe(200)- expect(mockGetChannelsByIds).toHaveBeenCalledWith(expect.anything(), ["c1"])- expect(body.servers).toHaveLength(1)- expect(body.servers[0].channels).toHaveLength(1)- const parent = body.servers[0].channels[0]- expect(parent.channelId).toBe("c1")- expect(parent.channelName).toBe("general")- expect(parent.hasDirectUnread).toBe(false)- expect(parent.children.map((c: { channelId: string }) => c.channelId)).toEqual(["t1"])- })-- it("nests a child under a parent that ALSO has a direct unread (no re-resolve)", async () => {- mockListEligibleUnreadChannels.mockResolvedValue([- row({ channelId: "c1", channelName: "general", lastMessageAt: "2026-06-25T10:00:00Z" }),- row({ channelId: "t1", channelName: "budget-2026", parentChannelId: "c1", lastMessageAt: "2026-06-25T11:00:00Z" }),- ])- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))- const body = await res.json()- // Parent was already present → no getChannelsByIds resolve needed.- expect(mockGetChannelsByIds).not.toHaveBeenCalled()- const parent = body.servers[0].channels[0]- expect(parent.channelId).toBe("c1")- expect(parent.children.map((c: { channelId: string }) => c.channelId)).toEqual(["t1"])- })-- it("attributes per-channel mentionCount to the correct child row", async () => {- mockListEligibleUnreadChannels.mockResolvedValue([- row({ channelId: "t1", channelName: "thread", parentChannelId: "c1", mentionCount: 2 }),- ])- mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "general", serverId: "s1" }])- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))- const body = await res.json()- expect(body.servers[0].channels[0].children[0].mentionCount).toBe(2)- })-- it("does not reconstruct channels absent from the eligible unread set", async () => {- mockListEligibleUnreadChannels.mockResolvedValue([])- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))- const body = await res.json()- expect(body.servers).toHaveLength(0)- expect(mockGetChannelsByIds).not.toHaveBeenCalled()- })-- it("counts child rows toward the truncation limit", async () => {- // Parent c1 (weight 1) + 2 children (weight 2) = 3 rows; limit=2 → parent +- // 1 child kept, truncated=true.- mockListEligibleUnreadChannels.mockResolvedValue([- row({ channelId: "c1", channelName: "general", lastMessageAt: "2026-06-25T09:00:00Z" }),- row({ channelId: "t1", channelName: "thread-1", parentChannelId: "c1", lastMessageAt: "2026-06-25T11:00:00Z" }),- row({ channelId: "t2", channelName: "thread-2", parentChannelId: "c1", lastMessageAt: "2026-06-25T10:00:00Z" }),- ])- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads?limit=2"))- const body = await res.json()- expect(body.truncated).toBe(true)- const parent = body.servers[0].channels[0]- expect(parent.channelId).toBe("c1")- // Newest child first, capped to 1.- expect(parent.children.map((c: { channelId: string }) => c.channelId)).toEqual(["t1"])- })-- it("top-level channels carry an empty children array", async () => {- mockListEligibleUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))- const body = await res.json()- expect(body.servers[0].channels[0].children).toEqual([])- expect(mockListThreadOpenersByChildIds).toHaveBeenCalledWith(expect.anything(), "u1", [])- })-- it("enriches only already-eligible text child rows without replacing their names", async () => {- mockListEligibleUnreadChannels.mockResolvedValue([- row({ channelId: "c1", channelName: "general", type: "text" }),- row({ channelId: "t1", channelName: "Chosen thread name", type: "thread", parentChannelId: "c1", lastMessageAt: "2026-06-25T12:00:00Z" }),- row({ channelId: "t2", channelName: "Read opener thread", type: "thread", parentChannelId: "c1", lastMessageAt: "2026-06-25T11:00:00Z" }),- ])- mockListThreadOpenersByChildIds.mockResolvedValue([- threadOpener({ parentChannelId: "c1", parentType: "text", childChannelId: "t1", openerMessageId: "m7", openerSeq: 7, openerUnread: true, title: "Parent message content" }),- threadOpener({ parentChannelId: "c1", parentType: "text", childChannelId: "t2", openerMessageId: "m4", openerSeq: 4, openerUnread: false, title: "Other parent content" }),- ])-- const body = await (await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))).json()- expect(body.servers[0].channels[0].children).toEqual([- expect.objectContaining({- channelId: "t1",- channelName: "Chosen thread name",- parentChannelId: "c1",- openerMessageId: "m7",- openerSeq: 7,- openerUnread: true,- }),- expect.objectContaining({- channelId: "t2",- channelName: "Read opener thread",- parentChannelId: "c1",- openerMessageId: "m4",- openerSeq: 4,- openerUnread: false,- }),- ])- })-- // ── Entity type plumbing (drives the inbox icon) ───────────────────────────-- it("surfaces channel `type` so the inbox can pick the right entity icon", async () => {- mockListEligibleUnreadChannels.mockResolvedValue([- row({ channelId: "c1", channelName: "general", type: "text" }),- row({ channelId: "c2", channelName: "help-forum", type: "forum", lastMessageAt: "2026-06-25T09:00:00Z" }),- ])- mockListUnreadForumOpeners.mockResolvedValue([- opener({ forumChannelId: "c2", childChannelId: "p2", openerMessageId: "m2" }),- ])- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))- const body = await res.json()- const byId = Object.fromEntries(- body.servers[0].channels.map((c: { channelId: string; type?: string }) => [c.channelId, c.type]),- )- expect(byId).toEqual({ c1: "text", c2: "forum" })- })-- it("surfaces child `type` (thread / forum_post) on nested rows", async () => {- mockListEligibleUnreadChannels.mockResolvedValue([- row({ channelId: "c1", channelName: "general", type: "text" }),- row({ channelId: "t1", channelName: "budget", type: "thread", parentChannelId: "c1", lastMessageAt: "2026-06-25T11:00:00Z" }),- ])- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))- const body = await res.json()- const parent = body.servers[0].channels[0]- expect(parent.type).toBe("text")- expect(parent.children[0].type).toBe("thread")- })-- it("carries `type` from getChannelsByIds when the parent is backfilled", async () => {- mockListEligibleUnreadChannels.mockResolvedValue([- row({ channelId: "t1", channelName: "budget", type: "thread", parentChannelId: "c1" }),- ])- mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "help-forum", serverId: "s1", type: "forum" }])- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))- const body = await res.json()- expect(body.servers[0].channels[0].type).toBe("forum")- })-- // ── Per-post forum opener projection ──────────────────────────────────────-- it("queries only visible top-level forum parents with eligible direct unread", async () => {- mockListVisibleChannelIds.mockResolvedValue(["f1", "f2", "text1", "post1"])- mockListEligibleUnreadChannels.mockResolvedValue([- row({ channelId: "f1", channelName: "Forum 1", type: "forum" }),- row({ channelId: "text1", channelName: "Text", type: "text" }),- row({ channelId: "post1", channelName: "Post", type: "thread", parentChannelId: "f1" }),- ])-- await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))-- expect(mockListEligibleUnreadChannels).toHaveBeenCalledWith(expect.anything(), "u1", ["f1", "f2", "text1", "post1"])- expect(mockListUnreadForumOpeners).toHaveBeenCalledWith(expect.anything(), "u1", ["f1"])- })-- it("renders every unread opener as a separately titled child row, newest first", async () => {- mockListEligibleUnreadChannels.mockResolvedValue([- row({ channelId: "f1", channelName: "Forum", type: "forum", lastMessageAt: "2026-06-25T11:00:00Z" }),- ])- mockListUnreadForumOpeners.mockResolvedValue([- opener({ openerMessageId: "m2", childChannelId: "p2", title: "Second full opener", createdAt: "2026-06-25T11:00:00Z", openerSeq: 2 }),- opener({ openerMessageId: "m1", childChannelId: "p1", title: "First full opener", createdAt: "2026-06-25T10:00:00Z", openerSeq: 1 }),- ])-- const body = await (await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))).json()- const children = body.servers[0].channels[0].children- expect(children.map((child: { channelId: string; channelName: string; openerMessageId: string; openerSeq: number; openerUnread: boolean }) => ({- channelId: child.channelId,- title: child.channelName,- openerMessageId: child.openerMessageId,- openerSeq: child.openerSeq,- openerUnread: child.openerUnread,- }))).toEqual([- { channelId: "p2", title: "Second full opener", openerMessageId: "m2", openerSeq: 2, openerUnread: true },- { channelId: "p1", title: "First full opener", openerMessageId: "m1", openerSeq: 1, openerUnread: true },- ])- })-- it("dedupes an unread opener and child replies by childChannelId while retaining the parent target", async () => {- mockListUnreadForumOpeners.mockResolvedValue([- opener({ title: "Canonical opener title", createdAt: "2026-06-25T10:00:00Z", openerSeq: 7 }),- ])- mockListEligibleUnreadChannels.mockResolvedValue([- row({ channelId: "f1", channelName: "Forum", type: "forum", lastMessageAt: "2026-06-25T10:00:00Z" }),- row({ channelId: "p1", channelName: "Derived title", type: "thread", parentChannelId: "f1", lastMessageAt: "2026-06-25T12:00:00Z", mentionCount: 2 }),- ])-- const body = await (await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))).json()- const children = body.servers[0].channels[0].children- expect(children).toHaveLength(1)- expect(children[0]).toMatchObject({- channelId: "p1",- channelName: "Canonical opener title",- openerMessageId: "m1",- openerSeq: 7,- openerUnread: true,- lastMessageAt: "2026-06-25T12:00:00Z",- mentionCount: 2,- })- })-- it("uses canonical opener metadata when only a child reply is unread", async () => {- mockListEligibleUnreadChannels.mockResolvedValue([- row({- channelId: "post_1",- channelName: "stale derived title",- type: "thread",- parentChannelId: "forum_1",- lastMessageAt: "2026-06-25T12:00:00Z",- }),- ])- mockGetChannelsByIds.mockResolvedValue([- { id: "forum_1", name: "Forum", type: "forum", serverId: "s1" },- ])- mockListThreadOpenersByChildIds.mockResolvedValue([- threadOpener({ parentChannelId: "forum_1", childChannelId: "post_1", title: "Full canonical opener" }),- ])-- const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))- const body = await res.json()-- expect(mockListThreadOpenersByChildIds).toHaveBeenCalledWith(expect.anything(), "u1", ["post_1"])- expect(body.servers[0].channels[0].children).toEqual([- expect.objectContaining({- channelId: "post_1",- channelName: "Full canonical opener",- openerMessageId: "m1",- openerSeq: 1,- openerUnread: false,- }),- ])- })-- it("looks up canonical opener metadata only for eligible child ids", async () => {- mockListEligibleUnreadChannels.mockResolvedValue([- row({ channelId: "post_ok", parentChannelId: "forum_ok", type: "thread" }),- ])- await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))- expect(mockListThreadOpenersByChildIds).toHaveBeenCalledWith(expect.anything(), "u1", ["post_ok"])- })-- it("removes a phantom forum parent when no unread opener or child remains", async () => {- mockListEligibleUnreadChannels.mockResolvedValue([- row({ channelId: "f1", channelName: "Forum", type: "forum" }),- ])- mockListUnreadForumOpeners.mockResolvedValue([])-- const body = await (await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))).json()- expect(body.servers).toEqual([])- })-- it("uses opener seq/id as deterministic tie-breaks before child cap truncation", async () => {- mockListEligibleUnreadChannels.mockResolvedValue([- row({ channelId: "f1", channelName: "Forum", type: "forum" }),- ])- mockListUnreadForumOpeners.mockResolvedValue([- opener({ openerMessageId: "m1", childChannelId: "p1", openerSeq: 1 }),- opener({ openerMessageId: "m3", childChannelId: "p3", openerSeq: 3 }),- opener({ openerMessageId: "m2", childChannelId: "p2", openerSeq: 2 }),- ])-- const body = await (await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads?limit=3"))).json()- expect(body.truncated).toBe(true)- // Parent consumes one row; the two newest equal-time openers consume the- // remaining rows in stable seq order.- expect(body.servers[0].channels[0].children.map((child: { channelId: string }) => child.channelId)).toEqual(["p3", "p2"])- })-})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.tsdeleted file mode 100644index 080912c7a..000000000--- a/src/web/src/app/api/community/users/me/inbox/unreads/route.ts+++ /dev/null@@ -1,400 +0,0 @@-import {- queries,- DEFAULT_INBOX_PAGE_SIZE,- MAX_INBOX_PAGE_SIZE,- readOrStale,- withD1Retry,-} 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"-import { avatarInitial } from "@/lib/community/avatar"-import { canonicalUserImage } from "@/lib/community/storage"--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,- )-- // Resolve the viewer's visible channels once (top-level + child threads,- // parent-climbed) and thread the id set into BOTH consumers so neither- // recomputes it. Private threads under an invisible parent are excluded.- type UnreadRow = Awaited<ReturnType<typeof queries.communityInbox.listEligibleUnreadChannels>>[number]- 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, 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),- ])- // Expand only top-level forum parents that already have eligible unread.- // The opener query applies the same current readability, cursor, policy,- // and persisted-attention gate before returning individual post rows.- const forumParentIds = [...new Set(- unread- .filter(- (row) =>- !row.parentChannelId &&- row.type === "forum",- )- .map((row) => row.channelId),- )]- const unreadChildIds = [...new Set(- unread- .filter(- (row) =>- !!row.parentChannelId,- )- .map((row) => row.channelId),- )]- const [directForumOpeners, childThreadOpeners] = await Promise.all([- queries.communityInbox.listUnreadForumOpeners(db, ctx.userId, forumParentIds),- queries.communityInbox.listThreadOpenersByChildIds(db, ctx.userId, unreadChildIds),- ])- const directThreadOpeners: ThreadOpenerRow[] = directForumOpeners.map(- (row: ForumOpenerRow) => ({- parentChannelId: row.forumChannelId,- parentType: "forum",- openerMessageId: row.openerMessageId,- childChannelId: row.childChannelId,- title: row.title,- createdAt: row.createdAt,- openerSeq: row.openerSeq,- openerUnread: true,- }),- )- const threadOpeners = [...new Map(- [...childThreadOpeners, ...directThreadOpeners].map((row) => [row.childChannelId, row]),- ).values()]- const forumParentsWithUnread = new Set([- ...directForumOpeners.map((row) => row.forumChannelId),- ...unread.flatMap((row) => row.parentChannelId ? [row.parentChannelId] : []),- ])- const withoutPhantomForumParents = unread.filter(- (row) =>- row.parentChannelId ||- row.type !== "forum" ||- forumParentsWithUnread.has(row.channelId),- )- return { unread: withoutPhantomForumParents, unreadDms, threadOpeners, friendRequests }- },- { unread: [], unreadDms: [], threadOpeners: [], friendRequests: [] },- { route: "community/inbox/unreads" },- )- if (stale) {- return writeJSON({ friendRequests: [], servers: [], dms: [], limit, truncated: false, stale: true })- }- 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- // even when it has no direct unread of its own (only unread children).- type UnreadChild = {- channelId: string- channelName: string- type: string | null- lastMessageAt: string- mentionCount: number- lastUnreadSeq: number- lastAttentionSeq: number | null- openerMessageId?: string- parentChannelId?: string- openerSeq?: number- openerUnread?: boolean- // Private stable-order fields. They are removed from the response below.- sortSeq: number- sortId: string- }- type ParentNode = {- channelId: string- channelName: string- type: string | null- serverId: string- serverName: string- lastMessageAt: string- mentionCount: number- lastUnreadSeq: number- lastAttentionSeq: number | null- hasDirectUnread: boolean- children: UnreadChild[]- }-- const parents = new Map<string, ParentNode>()- const childrenByParent = new Map<string, Map<string, UnreadChild>>()- const unreadByChannelId = new Map(unread.map((row) => [row.channelId, row]))-- for (const row of unread) {- if (!row.serverId || !row.channelId || !row.serverName || !row.channelName) continue- if (row.parentChannelId) {- const children = childrenByParent.get(row.parentChannelId) ?? new Map<string, UnreadChild>()- children.set(row.channelId, {- channelId: row.channelId,- channelName: row.channelName,- type: row.type,- lastMessageAt: row.lastMessageAt,- mentionCount: row.mentionCount,- lastUnreadSeq: row.lastUnreadSeq,- lastAttentionSeq: row.lastAttentionSeq,- sortSeq: 0,- sortId: row.channelId,- })- childrenByParent.set(row.parentChannelId, children)- } else {- parents.set(row.channelId, {- channelId: row.channelId,- channelName: row.channelName,- type: row.type,- serverId: row.serverId,- serverName: row.serverName,- lastMessageAt: row.lastMessageAt,- mentionCount: row.mentionCount,- lastUnreadSeq: row.lastUnreadSeq,- lastAttentionSeq: row.lastAttentionSeq,- hasDirectUnread: true,- children: [],- })- }- }-- // Enrich already-eligible child rows with their canonical parent opener.- // Forum opener-only rows retain their existing nested presentation; text- // opener-only unread remains represented by its parent channel row.- for (const opener of threadOpeners) {- const parent = parents.get(opener.parentChannelId)- const unreadChild = unreadByChannelId.get(opener.childChannelId)- if (!parent && unreadChild?.parentChannelId !== opener.parentChannelId) continue- const serverId = parent?.serverId ?? unreadChild?.serverId- if (!serverId) continue-- const children = childrenByParent.get(opener.parentChannelId) ?? new Map<string, UnreadChild>()- const existing = children.get(opener.childChannelId)- if (existing) {- if (opener.parentType === "forum") existing.channelName = opener.title- existing.type = existing.type ?? "thread"- existing.parentChannelId = opener.parentChannelId- existing.openerMessageId = opener.openerMessageId- existing.openerSeq = opener.openerSeq- existing.openerUnread = opener.openerUnread- existing.lastUnreadSeq = Math.max(existing.lastUnreadSeq, opener.openerSeq)- if (opener.createdAt >= existing.lastMessageAt) {- existing.lastMessageAt = opener.createdAt- existing.sortSeq = opener.openerSeq- existing.sortId = opener.openerMessageId- }- } else {- if (opener.parentType !== "forum" || !opener.openerUnread) continue- children.set(opener.childChannelId, {- channelId: opener.childChannelId,- channelName: opener.title,- type: "thread",- lastMessageAt: opener.createdAt,- mentionCount: unreadChild?.mentionCount ?? 0,- lastUnreadSeq: Math.max(unreadChild?.lastUnreadSeq ?? 0, opener.openerSeq),- lastAttentionSeq: unreadChild?.lastAttentionSeq ?? null,- parentChannelId: opener.parentChannelId,- openerMessageId: opener.openerMessageId,- openerSeq: opener.openerSeq,- openerUnread: opener.openerUnread,- sortSeq: opener.openerSeq,- sortId: opener.openerMessageId,- })- }- childrenByParent.set(opener.parentChannelId, children)- }-- // Parents that have an unread child but no direct unread aren't in `unread`,- // so their name isn't available — batch-resolve them. `getChannelsByIds` has- // no visibility filter, but that's fine: the child already passed visibility,- // which implies the parent is visible. serverId/serverName come from the- // child rows (they joined `communityServer`).- const missingParentIds = [...childrenByParent.keys()].filter((pid) => !parents.has(pid))- if (missingParentIds.length > 0) {- const resolved = await withD1Retry(- () => queries.communityChannel.getChannelsByIds(db, missingParentIds),- { route: "community/inbox/unreads:missing-parents" },- )- const resolvedById = new Map(resolved.map((c) => [c.id, c]))- for (const pid of missingParentIds) {- const ch = resolvedById.get(pid)- if (!ch) continue- parents.set(pid, {- channelId: pid,- channelName: ch.name,- type: ch.type,- serverId: ch.serverId,- // serverName + a sort timestamp are backfilled from the child rows- // below (those rows carry serverName via the communityServer join).- serverName: "",- lastMessageAt: "",- mentionCount: 0,- lastUnreadSeq: 0,- lastAttentionSeq: null,- hasDirectUnread: false,- children: [],- })- }- }-- // Attach children to their parents. Parent/server policy inheritance was- // already resolved in SQL for each child's eligible message set.- for (const [pid, kids] of childrenByParent) {- const parent = parents.get(pid)- if (!parent) continue // parent muted or unresolved → drop the subtree- parent.children.push(...kids.values())- }-- // Resolved-only parents (unread child, no direct unread) need serverName + a- // sort timestamp. Backfill from the child rows, which carry both.- for (const row of unread) {- if (!row.parentChannelId) continue- const parent = parents.get(row.parentChannelId)- if (!parent || parent.hasDirectUnread) continue- if (!parent.serverName && row.serverName) parent.serverName = row.serverName- if (row.lastMessageAt > parent.lastMessageAt) parent.lastMessageAt = row.lastMessageAt- }-- // Drop any parent that ended up with neither a direct unread nor a surviving- // child (e.g. all children muted), or that never got a serverName.- const grouped = new Map<- string,- { serverId: string; serverName: string; channels: Array<ParentNode & { children: UnreadChild[] }> }- >()- for (const parent of parents.values()) {- if (!parent.hasDirectUnread && parent.children.length === 0) continue- if (!parent.serverName) continue- parent.children.sort(- (a, b) =>- b.lastMessageAt.localeCompare(a.lastMessageAt) ||- b.sortSeq - a.sortSeq ||- b.sortId.localeCompare(a.sortId),- )- let bucket = grouped.get(parent.serverId)- if (!bucket) {- bucket = { serverId: parent.serverId, serverName: parent.serverName, channels: [] }- grouped.set(parent.serverId, bucket)- }- bucket.channels.push(parent)- }-- const allServers = Array.from(grouped.values()).map((g) => ({- serverId: g.serverId,- serverName: g.serverName,- channels: g.channels- .sort(- (a, b) =>- b.lastMessageAt.localeCompare(a.lastMessageAt) ||- b.channelId.localeCompare(a.channelId),- )- .map((c) => ({- channelId: c.channelId,- channelName: c.channelName,- type: c.type ?? undefined,- lastMessageAt: c.lastMessageAt,- mentionCount: c.mentionCount,- lastUnreadSeq: c.lastUnreadSeq,- lastAttentionSeq: c.lastAttentionSeq,- hasDirectUnread: c.hasDirectUnread,- children: c.children.map((k) => ({- channelId: k.channelId,- channelName: k.channelName,- type: k.type ?? undefined,- lastMessageAt: k.lastMessageAt,- mentionCount: k.mentionCount,- lastUnreadSeq: k.lastUnreadSeq,- lastAttentionSeq: k.lastAttentionSeq,- ...(k.parentChannelId ? { parentChannelId: k.parentChannelId } : {}),- ...(k.openerMessageId ? { openerMessageId: k.openerMessageId } : {}),- ...(k.openerSeq !== undefined ? { openerSeq: k.openerSeq } : {}),- ...(k.openerMessageId ? { openerUnread: k.openerUnread === true } : {}),- })),- })),- }))- allServers.sort((a, b) => {- const aLatest = a.channels[0]?.lastMessageAt ?? ""- const bLatest = b.channels[0]?.lastMessageAt ?? ""- return aLatest < bLatest ? 1 : aLatest > bLatest ? -1 : 0- })-- // Cap by total row count — each parent AND each child counts as one row, so a- // single very active server (or one channel with many unread threads) can't- // drown out the rest of the inbox payload.- const nodeWeight = (c: { children: unknown[] }) => 1 + c.children.length- const grandTotal = allServers.reduce((n, s) => n + s.channels.reduce((m, c) => m + nodeWeight(c), 0), 0)- const servers: typeof allServers = []- let total = 0- for (const s of allServers) {- if (total >= limit) break- const keptChannels: typeof s.channels = []- for (const c of s.channels) {- const remaining = limit - total- if (remaining <= 0) break- const weight = nodeWeight(c)- if (weight <= remaining) {- keptChannels.push(c)- total += weight- } else {- // Parent takes one slot; the rest go to children (may be zero).- keptChannels.push({ ...c, children: c.children.slice(0, remaining - 1) })- total = limit- break- }- }- if (keptChannels.length > 0) servers.push({ ...s, channels: keptChannels })- }- const truncated = total < grandTotal-- // DMs are a flat list sorted most-recent first. A DM is a channel-scoped- // notification unit, so `listEligibleUnreadDms` has already applied current- // participation, cursor, policy, and attention. Blocked-user filtering stays- // off intentionally: DM messages- // route gates on `requireDMAccess`; an unread from a blocked user is still- // the viewer's DM and should appear here.- const dms = unreadDms- .map((d) => ({- channelId: d.channelId,- otherUserId: d.otherUserId,- otherUserName: d.otherUserName,- otherUserDiscriminator: d.otherUserDiscriminator,- otherUserAvatar: canonicalUserImage(- d.otherUserId,- d.otherUserImage,- d.otherUserAvatarVersion,- ) ?? avatarInitial(d.otherUserName),- otherUserAvatarVersion: d.otherUserAvatarVersion,- lastMessageAt: d.lastMessageAt,- lastUnreadSeq: d.lastUnreadSeq,- }))- .sort((a, b) => (a.lastMessageAt < b.lastMessageAt ? 1 : -1))-- 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/community-shell.tsx b/src/web/src/app/c/community-shell.tsxindex 4810a6b5e..b92ab9bf1 100644--- a/src/web/src/app/c/community-shell.tsx+++ b/src/web/src/app/c/community-shell.tsx@@ -12,10 +12,7 @@ import {import { useCommunityWs } from "@/hooks/community/use-community-ws"import { useNotificationSettings } from "@/hooks/community/use-notification-settings"import { useNativeSystemNotifications } from "@/hooks/community/use-native-system-notifications"-import {- useAccountAttention,- useAccountAttentionScopeHydration,-} from "@/hooks/community/use-account-attention"+import { useAccountAttention } from "@/hooks/community/use-account-attention"import { PerfTraceBootstrap } from "@/components/perf/perf-trace-bootstrap"import { CommunityOnboardingForm } from "@/components/community/onboarding/community-onboarding-form"import { CommunityWsReconnectBoundary } from "@/components/community/shell/community-ws-reconnect-overlay"@@ -89,7 +86,6 @@ function CommunityBootstrap({ children }: { children: ReactNode }) {useNotificationSettings()useAccountAttention()- useAccountAttentionScopeHydration()useNativeSystemNotifications(currentUser.id)// Wire the WS handler once for the whole community subtree. `viewerUserId`// powers the `me` flag on incoming reactions — passing null would leave thatdiff --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 49dca8a94..35ada92db 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@@ -164,7 +164,7 @@ describe("InboxPopover thread opener rows", () => {)})- it("removes a structural parent after its only child is projected away", () => {+ it("does not let a navigation tombstone hide a new child generation", () => {const unreads = unreadFixture()unreads[0]!.channels[0]!.hasDirectUnread = falseunreads[0]!.channels[0]!.children = unreads[0]!.channels[0]!.children.slice(0, 1)@@ -176,14 +176,13 @@ describe("InboxPopover thread opener rows", () => {hasProjectedUnreads: true,hasProjectedMentions: false,onOpenThread: vi.fn(),- isProjected: (target) => target?.kind === "thread",}))- expect(renderer.queryAllByTestId(tid.inboxUnreadChannel("f1"))).toHaveLength(0)- expect(renderer.queryAllByTestId(tid.inboxUnreadChild("p1"))).toHaveLength(0)+ expect(renderer.queryAllByTestId(tid.inboxUnreadChannel("f1"))).toHaveLength(1)+ expect(renderer.queryAllByTestId(tid.inboxUnreadChild("p1"))).toHaveLength(1)expect(renderer.queryAllByTestId(tid.inboxUnreadChild("t1"))).toHaveLength(0)})- it("retains a projected direct parent as structural while children remain", () => {+ it("renders canonical direct and child truth without tombstone filtering", () => {const onOpenChannel = vi.fn()const unreads = unreadFixture()unreads[0]!.channels[0]!.mentionCount = 2@@ -196,7 +195,6 @@ describe("InboxPopover thread opener rows", () => {hasProjectedMentions: false,onOpenChannel,onOpenThread: vi.fn(),- isProjected: (target) => target?.kind === "channel-direct",}))const parentRows = renderer.queryAllByTestId(tid.inboxUnreadChannel("f1"))const openerRows = renderer.queryAllByTestId(tid.inboxUnreadChild("p1"))@@ -205,12 +203,12 @@ describe("InboxPopover thread opener rows", () => {expect(renderer.queryAllByTestId(tid.inboxUnreadChild("t1"))).toHaveLength(1)expect(textOf(parentRows[0]!)).toContain("Forum")expect(textOf(openerRows[0]!)).toContain("Full authoritative opener content")- expect(textOf(parentRows[0]!)).not.toContain("2")+ expect(textOf(parentRows[0]!)).toContain("2")fireEvent.click(parentRows[0]!)expect(onOpenChannel).toHaveBeenCalledWith(unreads[0],unreads[0]!.channels[0],- false,+ true,)})})@@ -320,6 +318,27 @@ describe("InboxPopover friend requests", () => {})})+describe("InboxPopover attention errors", () => {+ it("shows Retry instead of Caught up on an initial attention failure", () => {+ const onRetryAttention = vi.fn()+ const renderer = render(React.createElement(InboxPopover, {+ unreads: [],+ unreadDms: [],+ mentions: [],+ marked: [],+ attentionError: true,+ onRetryAttention,+ hasProjectedUnreads: false,+ hasProjectedMentions: false,+ }))+ expect(renderer.queryByText("Caught up")).toBeNull()+ expect(renderer.getAllByRole("alert")).toHaveLength(2)+ expect(renderer.getAllByRole("alert")[0]).toHaveTextContent("Couldn\'t load Inbox")+ fireEvent.click(renderer.getAllByRole("button", { name: "Retry" })[0]!)+ expect(onRetryAttention).toHaveBeenCalledTimes(1)+ })+})+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 a85a80a6d..4ee86a64f 100644--- a/src/web/src/components/community/shell/community-inbox-popover.tsx+++ b/src/web/src/components/community/shell/community-inbox-popover.tsx@@ -11,13 +11,6 @@ import { EmptyState } from "../empty-state"import { formatRelativeTime } from "@/lib/community/format-time"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,- inboxMentionRowTarget,- inboxThreadRowTarget,- type InboxRowTarget,-} from "@/hooks/community/inbox-read-reservation"import { selectUnreadPresentation } from "@/hooks/community/unread-presentation"import { tid } from "@/lib/community/testids"import type { CommunityProfile } from "@/lib/community/models/people"@@ -118,11 +111,22 @@ function MentionBadge({ count }: { count: number }) {)}-function UnreadsTab({ friendRequests, servers, dms, loading, onOpenFriendRequests, onAcceptFriendRequest, onRejectFriendRequest, onRetryFriendRequest, onOpenChannel, onOpenThread, onOpenDm, isProjected, profilesByUserId, getScrollOffset, onScrollOffsetChange }: {+function AttentionLoadError({ onRetry }: { onRetry?: () => void }) {+ return (+ <div role="alert" className="flex flex-col items-center gap-2 py-8 text-sm text-muted-foreground">+ <span>Couldn't load Inbox</span>+ {onRetry && <Button variant="secondary" size="sm" onClick={onRetry}>Retry</Button>}+ </div>+ )+}++function UnreadsTab({ friendRequests, servers, dms, loading, error, onRetry, onOpenFriendRequests, onAcceptFriendRequest, onRejectFriendRequest, onRetryFriendRequest, onOpenChannel, onOpenThread, onOpenDm, profilesByUserId, getScrollOffset, onScrollOffsetChange }: {friendRequests: Array<ActionableFriendRequest<InboxFriendRequest>>servers: UnreadServer[]dms: UnreadDm[]loading?: boolean+ error?: boolean+ onRetry?: () => voidonOpenFriendRequests?: () => voidonAcceptFriendRequest?: (request: ActionableFriendRequest<InboxFriendRequest>) => voidonRejectFriendRequest?: (request: ActionableFriendRequest<InboxFriendRequest>) => void@@ -134,22 +138,18 @@ function UnreadsTab({ friendRequests, servers, dms, loading, onOpenFriendRequest) => voidonOpenThread: (server: UnreadServer, parent: UnreadChannel, child: UnreadChild) => voidonOpenDm?: (dm: UnreadDm) => void- isProjected: (target: InboxRowTarget | null) => booleanprofilesByUserId: ReadonlyMap<string, CommunityProfile>getScrollOffset?: (tab: InboxTab) => numberonScrollOffsetChange?: (tab: InboxTab, scrollTop: number) => void}) {- const visibleDms = dms.filter((dm) => !isProjected(inboxDmRowTarget(dm)))+ const visibleDms = dmsconst visibleServers = servers.map((server) => ({server,channels: server.channels.map((channel) => {- const directTarget = inboxChannelRowTarget(server, channel)return {channel,- directVisible: directTarget !== null && !isProjected(directTarget),- children: channel.children.filter((child) => (- !isProjected(inboxThreadRowTarget(server, channel, child))- )),+ directVisible: channel.hasDirectUnread !== false,+ children: channel.children,}}).filter((group) => group.directVisible || group.children.length > 0),})).filter((group) => group.channels.length > 0)@@ -157,7 +157,8 @@ function UnreadsTab({ friendRequests, servers, dms, loading, onOpenFriendRequestreturn (<InboxScrollBody tab="unreads" getScrollOffset={getScrollOffset} onScrollOffsetChange={onScrollOffsetChange}>{loading && nothingUnread && <InboxUnreadsSkeleton />}- {!loading && nothingUnread && <EmptyState icon={Inbox} label="Caught up" />}+ {error && nothingUnread && <AttentionLoadError onRetry={onRetry} />}+ {!loading && !error && 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">@@ -299,23 +300,23 @@ function UnreadsTab({ friendRequests, servers, dms, loading, onOpenFriendRequest)}-function MentionsTab({ mentions, loading, onOpenMention, onDeleteMention, isProjected, profilesByUserId, getScrollOffset, onScrollOffsetChange }: {+function MentionsTab({ mentions, loading, error, onRetry, onOpenMention, onDeleteMention, profilesByUserId, getScrollOffset, onScrollOffsetChange }: {mentions: Mention[]loading?: boolean+ error?: boolean+ onRetry?: () => voidonOpenMention?: (m: Mention) => voidonDeleteMention?: (id: string) => void- isProjected: (target: InboxRowTarget | null) => booleanprofilesByUserId: ReadonlyMap<string, CommunityProfile>getScrollOffset?: (tab: InboxTab) => numberonScrollOffsetChange?: (tab: InboxTab, scrollTop: number) => void}) {- const visibleMentions = mentions.filter((mention) => (- !isProjected(inboxMentionRowTarget(mention))- ))+ const visibleMentions = mentionsreturn (<InboxScrollBody tab="mentions" getScrollOffset={getScrollOffset} onScrollOffsetChange={onScrollOffsetChange}>{loading && visibleMentions.length === 0 && <InboxRowsSkeleton />}- {!loading && visibleMentions.length === 0 && <EmptyState icon={Inbox} label="No mentions" />}+ {error && visibleMentions.length === 0 && <AttentionLoadError onRetry={onRetry} />}+ {!loading && !error && visibleMentions.length === 0 && <EmptyState icon={Inbox} label="No mentions" />}{visibleMentions.map((mn) => {if (mn.pending) {return (@@ -430,6 +431,8 @@ export function InboxPopover({marked,markedLoading,loading,+ attentionError,+ onRetryAttention,hasProjectedUnreads,hasProjectedMentions,hasOutstandingFriendRequest = friendRequests.length > 0,@@ -447,7 +450,6 @@ export function InboxPopover({onUnmark,onMarkedTabSelected,onMarkAllRead,- isProjected = () => false,activeTab,onActiveTabChange,getScrollOffset,@@ -461,6 +463,8 @@ export function InboxPopover({marked: Marked[]markedLoading?: booleanloading?: boolean+ attentionError?: boolean+ onRetryAttention?: () => voidhasProjectedUnreads: booleanhasProjectedMentions: booleanhasOutstandingFriendRequest?: boolean@@ -489,7 +493,6 @@ export function InboxPopover({// the (lazy) marked-feed query only once the viewer actually opens the tab.onMarkedTabSelected?: () => voidonMarkAllRead?: () => void- isProjected?: (target: InboxRowTarget | null) => booleanactiveTab?: InboxTabonActiveTabChange?: (tab: InboxTab) => voidgetScrollOffset?: (tab: InboxTab) => number@@ -551,6 +554,8 @@ export function InboxPopover({servers={unreads}dms={unreadDms}loading={loading}+ error={attentionError}+ onRetry={onRetryAttention}onOpenFriendRequests={onOpenFriendRequests}onAcceptFriendRequest={onAcceptFriendRequest}onRejectFriendRequest={onRejectFriendRequest}@@ -558,14 +563,13 @@ export function InboxPopover({onOpenChannel={onOpenChannel}onOpenThread={onOpenThread ?? onOpenForumThread ?? (() => {})}onOpenDm={onOpenDm}- isProjected={isProjected}profilesByUserId={profilesByUserId}getScrollOffset={getScrollOffset}onScrollOffsetChange={onScrollOffsetChange}/></TabsContent><TabsContent value="mentions" className="min-h-0 flex-1">- <MentionsTab mentions={mentions} loading={loading} onOpenMention={onOpenMention} onDeleteMention={onDeleteMention} isProjected={isProjected} profilesByUserId={profilesByUserId} getScrollOffset={getScrollOffset} onScrollOffsetChange={onScrollOffsetChange} />+ <MentionsTab mentions={mentions} loading={loading} error={attentionError} onRetry={onRetryAttention} onOpenMention={onOpenMention} onDeleteMention={onDeleteMention} profilesByUserId={profilesByUserId} getScrollOffset={getScrollOffset} onScrollOffsetChange={onScrollOffsetChange} /></TabsContent><TabsContent value="marked" className="min-h-0 flex-1"><MarkedTab marked={marked} loading={markedLoading} onOpenMarked={onOpenMarked} onUnmark={onUnmark} profilesByUserId={profilesByUserId} getScrollOffset={getScrollOffset} onScrollOffsetChange={onScrollOffsetChange} />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 a5b93b0cf..d3a5eb7a7 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@@ -9,6 +9,7 @@ import { useShellInboxController } from "./use-shell-inbox-controller"const order: string[] = []const mocks = vi.hoisted(() => ({markedEnabled: [] as boolean[],+ refetchAttention: vi.fn(),markAll: vi.fn(),deleteMention: vi.fn(),unmark: vi.fn(),@@ -69,7 +70,7 @@ const mention: Mention = {}vi.mock("@/hooks/community/use-inbox", () => ({- useInboxUnreads: () => ({+ useInboxAttention: () => ({friendRequests: [{id: "fr_1",userId: "requester",@@ -80,17 +81,14 @@ vi.mock("@/hooks/community/use-inbox", () => ({}],servers: [server],dms: [unreadDm],- isLoading: false,- hasProjectedUnread: false,- hasOutstandingFriendRequest: true,- exactAttentionCount: 7,- pendingChannelIds: [],- }),- useInboxMentions: () => ({mentions: [mention],isLoading: false,- hasProjectedMention: false,- pendingChannelIds: [],+ isInitialError: false,+ hasUnread: true,+ hasMention: true,+ hasOutstandingFriendRequest: true,+ exactAttentionCount: 4,+ refetch: mocks.refetchAttention,}),useInboxMarked: (enabled: boolean) => {mocks.markedEnabled.push(enabled)@@ -202,6 +200,7 @@ describe("useShellInboxController", () => {mocks.markedEnabled.length = 0for (const mock of [mocks.markAll,+ mocks.refetchAttention,mocks.deleteMention,mocks.unmark,mocks.accept,@@ -249,7 +248,7 @@ describe("useShellInboxController", () => {const hook = await renderController()expect(hook.current.hasUnread).toBe(true)expect(hook.current.unreadCount).toBe(4)- expect(hook.current.popoverProps.hasProjectedUnreads).toBe(false)+ expect(hook.current.popoverProps.hasProjectedUnreads).toBe(true)expect(hook.current.popoverProps.friendRequests).toHaveLength(1)hook.current.popoverProps.onOpenFriendRequests?.()@@ -297,6 +296,14 @@ describe("useShellInboxController", () => {expect(mocks.markedEnabled.at(-1)).toBe(true)})+ it("retries the owned attention query from the popover", async () => {+ const hook = await renderController()++ hook.current.popoverProps.onRetryAttention?.()++ expect(mocks.refetchAttention).toHaveBeenCalledTimes(1)+ })+it("retains controlled tab and per-tab scroll offsets without data work", async () => {const hook = await renderController()expect(hook.current.popoverProps.activeTab).toBe("unreads")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 ec4f8d1b0..de13ddfb1 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@@ -5,7 +5,7 @@ import { communityKeys } from "@/lib/query-keys"import { channelHref } from "@/lib/community/community-route"import type { Marked, Mention, UnreadDm, UnreadServer } from "@/lib/community/models/inbox"import { dmSummaryFromInbox, upsertDmSummary, type DmCache } from "@/lib/community/dm-cache"-import { useInboxUnreads, useInboxMentions, useInboxMarked } from "@/hooks/community/use-inbox"+import { useInboxAttention, useInboxMarked } from "@/hooks/community/use-inbox"import { startDmRouteVerification } from "@/hooks/community/use-dm-route-verification"import { useInboxAutoCollapse } from "@/hooks/community/use-inbox-auto-collapse"import {@@ -36,7 +36,6 @@ import { startConversationNavigationWarmup } from "@/lib/community/conversation-import type { ConversationNavigationTarget } from "@/lib/community/conversation-navigation-proof"import { cancelConversationNavigationProof } from "@/lib/community/conversation-navigation-proof"import { publishCommunityDmSummary } from "@/lib/community-db/sync"-import { inboxUnreadCount } from "@/lib/community/inbox-unread-count"type UnreadChannel = UnreadServer["channels"][number]type UnreadChild = UnreadChannel["children"][number]@@ -66,15 +65,11 @@ export function useShellInboxController({if (router.pushImmediate) router.pushImmediate(href)else router.push(href)}, [router])- const inboxUnreads = useInboxUnreads()- const inboxMentions = useInboxMentions()- const unreadFeed = inboxUnreads.servers- const unreadDms = inboxUnreads.dms- const mentions = inboxMentions.mentions- const loading = inboxUnreads.isLoading- || inboxMentions.isLoading- || inboxUnreads.isProjectionPending- || inboxMentions.isProjectionPending+ const attention = useInboxAttention()+ const unreadFeed = attention.servers+ const unreadDms = attention.dms+ const mentions = attention.mentions+ const loading = attention.isLoadingconst [markedTabOpened, setMarkedTabOpened] = useState(false)const [activeTab, setActiveTab] = useState<InboxTab>("unreads")const scrollOffsetsRef = useRef<Record<InboxTab, number>>({@@ -113,7 +108,7 @@ export function useShellInboxController({[rejectFriendRequest],)const friendRequestActions = useFriendRequestActionState({- rows: inboxUnreads.friendRequests,+ rows: attention.friendRequests,onAccept: acceptRequest,onReject: rejectRequest,surface: "inbox",@@ -303,8 +298,10 @@ export function useShellInboxController({marked: inboxMarked.marked,markedLoading: inboxMarked.isLoading,loading,- hasProjectedUnreads: inboxUnreads.hasProjectedUnread,- hasProjectedMentions: inboxMentions.hasProjectedMention,+ attentionError: attention.isInitialError,+ onRetryAttention: () => { void attention.refetch() },+ hasProjectedUnreads: attention.hasUnread,+ hasProjectedMentions: attention.hasMention,onOpenChannel: openServerChannel,onOpenThread: openThread,onOpenDm: openDm,@@ -322,18 +319,8 @@ export function useShellInboxController({onMarkAllRead: () => { markAllInboxRead.mutate() },onDeleteMention: (id) => deleteMention.mutate({ mentionId: id }),onUnmark: (messageId) => unmarkMessageMutate({ messageId }),- isProjected: inbox.isProjected,}- const unreadCount = inboxUnreadCount({- servers: unreadFeed,- dms: unreadDms,- mentions,- pendingChannelIds: [- ...inboxUnreads.pendingChannelIds,- ...inboxMentions.pendingChannelIds,- ],- friendRequestCount: inboxUnreads.friendRequests.length,- })+ const unreadCount = attention.exactAttentionCountreturn {popoverProps,diff --git a/src/web/src/hooks/community/community-ws/bundle-events.test.ts b/src/web/src/hooks/community/community-ws/bundle-events.test.tsindex 71d6f009b..e22304332 100644--- a/src/web/src/hooks/community/community-ws/bundle-events.test.ts+++ b/src/web/src/hooks/community/community-ws/bundle-events.test.ts@@ -102,6 +102,12 @@ function invalidationCount(queryKey: readonly unknown[]): number {JSON.stringify(filters.queryKey) === JSON.stringify(queryKey)).length}+function attentionReconcileCount(): number {+ return vi.mocked(capturedQueryClient.fetchQuery).mock.calls.filter(([options]) => (+ JSON.stringify(options.queryKey) === JSON.stringify(communityKeys.accountAttention())+ )).length+}+describe("useCommunityWs — operation bundles", () => {it("applies archive and null-tag sidebar semantics inside committed batches", async () => {await mountHook()@@ -278,7 +284,7 @@ describe("useCommunityWs — operation bundles", () => {}})- it("skips current raw refresh when a deferred later intent has no owner successor", async () => {+ it("preserves attention reconciliation across deferred read intents", async () => {vi.useFakeTimers()try {useCommunityStore.getState().subscribe({ channelId: "ch-1" })@@ -308,6 +314,7 @@ describe("useCommunityWs — operation bundles", () => {throw new Error(`unexpected API fetch: ${String(url)}`)})vi.spyOn(capturedQueryClient, "invalidateQueries")+ vi.spyOn(capturedQueryClient, "fetchQuery")const lease = registerReadSurface(capturedQueryClient,"viewer-1",@@ -334,15 +341,11 @@ describe("useCommunityWs — operation bundles", () => {releaseFirstRead()await vi.advanceTimersByTimeAsync(499)expect(readCalls).toBe(1)- expect(invalidationCount(communityKeys.inbox())).toBe(0)- expect(invalidationCount(communityKeys.dms())).toBe(0)+ expect(attentionReconcileCount()).toBe(2)await vi.advanceTimersByTimeAsync(1)await vi.waitFor(() => expect(readCalls).toBe(2))- await vi.waitFor(() => {- expect(invalidationCount(communityKeys.inbox())).toBe(1)- expect(invalidationCount(communityKeys.dms())).toBe(1)- })+ expect(attentionReconcileCount()).toBe(3)releaseReadSurface(lease)} finally {vi.useRealTimers()@@ -357,6 +360,7 @@ describe("useCommunityWs — operation bundles", () => {servers: [{ id: "server-1", mentions: 5 }],})vi.spyOn(capturedQueryClient, "invalidateQueries")+ vi.spyOn(capturedQueryClient, "fetchQuery")const frame = await batchFor("message-1", mentionEvents)capturedOnMessage!(frame)@@ -369,17 +373,16 @@ describe("useCommunityWs — operation bundles", () => {// read can cover it. An orphan/sticky bump would deliberately survive.unreadProjection.recordRead("ch-1", 1)expect(unreadProjection.projectUnread("servers", "ch-1", false)).toBe(false)- expect(invalidationCount(communityKeys.inbox())).toBe(0)- expect(invalidationCount(communityKeys.dms())).toBe(0)+ expect(attentionReconcileCount()).toBe(0)expect(invalidationCount(communityKeys.servers())).toBe(1)await vi.advanceTimersByTimeAsync(500)- expect(invalidationCount(communityKeys.inbox())).toBe(1)- expect(invalidationCount(communityKeys.dms())).toBe(0)+ expect(attentionReconcileCount()).toBe(1)const callsAfterFirst = vi.mocked(capturedQueryClient.invalidateQueries).mock.calls.lengthcapturedOnMessage!(frame)await vi.advanceTimersByTimeAsync(500)expect(vi.mocked(capturedQueryClient.invalidateQueries)).toHaveBeenCalledTimes(callsAfterFirst)+ expect(attentionReconcileCount()).toBe(1)const { useCommunityWsStore } = await import("@/stores/community/ws")expect(useCommunityWsStore.getState().seenDeliveryOperations.get(frame.operationId)).toEqual({ digest: frame.operationDigest, completed: true })@@ -473,17 +476,16 @@ describe("useCommunityWs — operation bundles", () => {servers: [{ id: "server-1", mentions: 9 }],})vi.spyOn(capturedQueryClient, "invalidateQueries")+ vi.spyOn(capturedQueryClient, "fetchQuery")capturedOnMessage!(await batchFor("message-late", mentionEvents))expect(capturedQueryClient.getQueryData<{ servers: Array<{ mentions: number }> }>(communityKeys.servers(),)?.servers[0]?.mentions).toBe(9)- expect(invalidationCount(communityKeys.inbox())).toBe(0)- expect(invalidationCount(communityKeys.dms())).toBe(0)+ expect(attentionReconcileCount()).toBe(0)expect(invalidationCount(communityKeys.servers())).toBe(1)await vi.advanceTimersByTimeAsync(500)- expect(invalidationCount(communityKeys.inbox())).toBe(1)- expect(invalidationCount(communityKeys.dms())).toBe(0)+ expect(attentionReconcileCount()).toBe(1)} finally {vi.useRealTimers()}@@ -874,6 +876,7 @@ describe("useCommunityWs — operation bundles", () => {try {await mountHook({ viewerUserId: "viewer-1" })vi.spyOn(capturedQueryClient, "invalidateQueries")+ vi.spyOn(capturedQueryClient, "fetchQuery")const original = await batchFor("bounded-operation", [{...message,message: { ...message.message, id: "bounded-operation" },@@ -894,13 +897,13 @@ describe("useCommunityWs — operation bundles", () => {}await vi.advanceTimersByTimeAsync(500)- expect(invalidationCount(communityKeys.inbox())).toBe(1)+ expect(attentionReconcileCount()).toBe(1)capturedOnMessage!(conflicts[0]!)await vi.advanceTimersByTimeAsync(500)- expect(invalidationCount(communityKeys.inbox())).toBe(2)+ expect(attentionReconcileCount()).toBe(1)capturedOnMessage!(conflicts.at(-1)!)await vi.advanceTimersByTimeAsync(500)- expect(invalidationCount(communityKeys.inbox())).toBe(2)+ expect(attentionReconcileCount()).toBe(1)expect(SEEN_DELIVERY_OPERATION_TRIM_TO).toBeLessThan(SEEN_DELIVERY_OPERATION_MAX)} finally {vi.useRealTimers()diff --git a/src/web/src/hooks/community/community-ws/invalidation-projections.ts b/src/web/src/hooks/community/community-ws/invalidation-projections.tsindex 5c3a82de1..db32fbc38 100644--- a/src/web/src/hooks/community/community-ws/invalidation-projections.ts+++ b/src/web/src/hooks/community/community-ws/invalidation-projections.ts@@ -90,15 +90,6 @@ 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/message-events.test.ts b/src/web/src/hooks/community/community-ws/message-events.test.tsindex 7bc06bc39..3f1f4b921 100644--- a/src/web/src/hooks/community/community-ws/message-events.test.ts+++ b/src/web/src/hooks/community/community-ws/message-events.test.ts@@ -41,8 +41,8 @@ vi.mock("@/hooks/community/community-ws/reconnect-messages", () => ({scheduleFocusedMessageGapRepair: (...args: unknown[]) => scheduleGapRepairMock(...args),}))-beforeEach(() => {- resetCommunityWsHarness()+beforeEach(async () => {+ await resetCommunityWsHarness()scheduleGapRepairMock.mockClear()})afterEach(cleanupCommunityWsHarness)@@ -591,36 +591,44 @@ describe("useCommunityWs — message.create", () => {}})- it("debounces inbox invalidation — 10 real unread signals produce 1 invalidate call", async () => {+ it("coalesces 10 real unread signals into one attention reconcile", async () => {vi.useFakeTimers()try {await mountHook({ viewerUserId: "u_me" })- const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")+ const fetchAttention = vi.spyOn(capturedQueryClient, "fetchQuery")for (let i = 0; i < 10; i++) {capturedOnMessage!(messageCreate("ch_x", `m_${i}`))- capturedOnMessage!({ type: "community:unread.bump", userId: "u_me", channelId: "ch_x", serverId: "s1" })+ capturedOnMessage!({+ type: "community:unread.bump", userId: "u_me", channelId: "ch_x",+ serverId: "s1", isMention: false,+ })}- // Before debounce window, no invalidate.- expect(invalidateSpy).not.toHaveBeenCalled()- // Advance past the debounce window — exactly one invalidate.+ expect(fetchAttention).not.toHaveBeenCalled()await vi.advanceTimersByTimeAsync(500)- const inboxCalls = invalidateSpy.mock.calls.filter((c) => {- const key = c[0]?.queryKey- return Array.isArray(key) && key.includes("inbox")- })- expect(inboxCalls).toHaveLength(1)+ await vi.runAllTicks()+ for (let index = 0; index < 8; index += 1) await Promise.resolve()+ expect(fetchAttention.mock.calls.filter(([options]) => (+ JSON.stringify(options.queryKey) === JSON.stringify(communityKeys.accountAttention())+ ))).toHaveLength(1)} finally {vi.useRealTimers()}})- it("arms one exact focused candidate before scheduling its inbox refresh", async () => {+ it("arms one exact focused candidate before reconciling attention", async () => {vi.useFakeTimers()try {await mountHook({ viewerUserId: "u_me" })const { useCommunityStore } = await import("@/stores/community")useCommunityStore.getState().subscribe({ channelId: "ch_focused" })const order: string[] = []+ const originalFetch = capturedQueryClient.fetchQuery.bind(capturedQueryClient)+ vi.spyOn(capturedQueryClient, "fetchQuery").mockImplementation((options) => {+ if (JSON.stringify(options.queryKey) === JSON.stringify(communityKeys.accountAttention())) {+ order.push("attention-reconcile")+ }+ return originalFetch(options)+ })const lease = registerInboxReadReservationSurface(capturedQueryClient,"ch_focused",@@ -628,23 +636,21 @@ describe("useCommunityWs — message.create", () => {if (candidate) order.push("candidate")},)- const originalInvalidate = capturedQueryClient.invalidateQueries.bind(capturedQueryClient)- vi.spyOn(capturedQueryClient, "invalidateQueries")- .mockImplementation((filters, options) => {- const key = filters.queryKey as unknown[] | undefined- if (Array.isArray(key) && key.includes("inbox")) order.push("inbox-refresh")- return originalInvalidate(filters, options)- })const event = messageCreate("ch_focused", "m_focused")capturedOnMessage!(event)- capturedOnMessage!({ type: "community:unread.bump", userId: "u_me", channelId: event.channelId })+ capturedOnMessage!({+ type: "community:unread.bump", userId: "u_me", channelId: event.channelId,+ serverId: "s1", isMention: false,+ })capturedOnMessage!(event)expect(order).toEqual(["candidate"])await vi.advanceTimersByTimeAsync(500)- await vi.waitFor(() => expect(order).toContain("inbox-refresh"))- expect(order.indexOf("candidate")).toBeLessThan(order.indexOf("inbox-refresh"))+ await vi.runAllTicks()+ for (let index = 0; index < 8; index += 1) await Promise.resolve()+ await vi.waitFor(() => expect(order).toContain("attention-reconcile"))+ expect(order.indexOf("candidate")).toBeLessThan(order.indexOf("attention-reconcile"))releaseInboxReadReservationSurface(lease)} finally {vi.useRealTimers()@@ -712,7 +718,7 @@ describe("useCommunityWs — message.create", () => {releaseInboxReadReservationSurface(lease)})- it("holds a focused refresh until the visible read reconciles authoritatively", async () => {+ it("coalesces attention while a focused read intent is pending", async () => {vi.useFakeTimers()try {const order: string[] = []@@ -740,13 +746,13 @@ describe("useCommunityWs — message.create", () => {useCommunityStore.getState().subscribe({ channelId: "ch_focused" })resetHookMemoization()await mountHook({ viewerUserId: "u_me" })- const originalInvalidate = capturedQueryClient.invalidateQueries.bind(capturedQueryClient)- const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")- .mockImplementation((filters, options) => {- const key = filters.queryKey as unknown[] | undefined- if (Array.isArray(key) && key.includes("inbox")) order.push("inbox-refresh")- return originalInvalidate(filters, options)- })+ const originalFetch = capturedQueryClient.fetchQuery.bind(capturedQueryClient)+ vi.spyOn(capturedQueryClient, "fetchQuery").mockImplementation((options) => {+ if (JSON.stringify(options.queryKey) === JSON.stringify(communityKeys.accountAttention())) {+ order.push("attention-reconcile")+ }+ return originalFetch(options)+ })const lease = registerReadSurface(capturedQueryClient,"u_me",@@ -755,23 +761,21 @@ describe("useCommunityWs — message.create", () => {const event = messageCreate("ch_focused", "m_visible")capturedOnMessage!(event)- capturedOnMessage!({ type: "community:unread.bump", userId: "u_me", channelId: event.channelId })+ capturedOnMessage!({+ type: "community:unread.bump", userId: "u_me", channelId: event.channelId,+ serverId: "s1", isMention: false,+ })expect(submitReadIntent(lease, {kind: "timeline",channelId: "ch_focused",messageId: "m_visible",seq: 1,})).toBe(true)- expect(invalidate).not.toHaveBeenCalled()-await vi.advanceTimersByTimeAsync(500)- await vi.waitFor(() => expect(order).toContain("inbox-refresh"))- expect(order.indexOf("read-put")).toBeLessThan(order.indexOf("inbox-refresh"))- expect(order.indexOf("read-snapshot")).toBeLessThan(order.indexOf("inbox-refresh"))- expect(invalidate.mock.calls.filter(([filters]) => {- const key = filters.queryKey as unknown[] | undefined- return Array.isArray(key) && key.includes("inbox")- })).toHaveLength(1)+ await vi.runAllTicks()+ for (let index = 0; index < 8; index += 1) await Promise.resolve()+ await vi.waitFor(() => expect(order).toContain("attention-reconcile"))+ expect(order.filter((entry) => entry === "attention-reconcile")).toHaveLength(1)releaseReadSurface(lease)} finally {vi.useRealTimers()@@ -1087,7 +1091,7 @@ describe("useCommunityWs — pin.add", () => {})describe("useCommunityWs — DM message.create", () => {- it("writes the focused DM overlay, leaves Query base-only, and invalidates dms()", async () => {+ it("writes the focused DM overlay, leaves Query base-only, and reconciles attention", async () => {vi.useFakeTimers()try {await mountHook({ viewerUserId: "u_me" })@@ -1100,7 +1104,7 @@ describe("useCommunityWs — DM message.create", () => {pages: [{ messages: [], hasMore: false }],pageParams: [null],})- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")+ const fetchAttention = vi.spyOn(capturedQueryClient, "fetchQuery")// A DM is a channel now — its message arrives as `message.create` keyed by// the DM's channel id (which the subscription tracks in `dmConversationId`).const event: CommunityMessageCreate = {@@ -1119,7 +1123,10 @@ describe("useCommunityWs — DM message.create", () => {},}capturedOnMessage!(event)- capturedOnMessage!({ type: "community:unread.bump", userId: "u_me", channelId: event.channelId })+ capturedOnMessage!({+ type: "community:unread.bump", userId: "u_me", channelId: event.channelId,+ isMention: false,+ })const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string; seq?: number }[] }[] }>(communityKeys.dmMessages("dm_1"),)@@ -1128,14 +1135,12 @@ describe("useCommunityWs — DM message.create", () => {expect([...getMessageOverlay({ kind: "dm", id: "dm_1" }).liveById.values()].map((message) => message.id),).toEqual(["dm_m_1"])- // The inbox + `dms()` invalidation is batched behind the inbox debounce.await vi.advanceTimersByTimeAsync(600)- expect(- spy.mock.calls.some((c) => {- const key = c[0]?.queryKey as unknown[] | undefined- return Array.isArray(key) && key.includes("dms")- }),- ).toBe(true)+ await vi.runAllTicks()+ for (let index = 0; index < 8; index += 1) await Promise.resolve()+ expect(fetchAttention.mock.calls.filter(([options]) => (+ JSON.stringify(options.queryKey) === JSON.stringify(communityKeys.accountAttention())+ ))).toHaveLength(1)} finally {vi.useRealTimers()}diff --git a/src/web/src/hooks/community/community-ws/reconnect.test.ts b/src/web/src/hooks/community/community-ws/reconnect.test.tsindex 2f759f13a..05679036e 100644--- a/src/web/src/hooks/community/community-ws/reconnect.test.ts+++ b/src/web/src/hooks/community/community-ws/reconnect.test.ts@@ -113,7 +113,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {)})- it("reactivates the Inbox owner after a Strict Effects cleanup/setup replay", async () => {+ it("reactivates the attention owner after a Strict Effects cleanup/setup replay", async () => {vi.useFakeTimers()await mountHook({ viewerUserId: "u_me" })flushEffects()@@ -122,13 +122,12 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {resetHookMemoization()await mountHook({ viewerUserId: "u_me" })flushEffects()- const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")-capturedOnMessage?.({ type: "community:unread.bump", channelId: "dm_effect_replay", userId: "u_me", isMention: false })await vi.advanceTimersByTimeAsync(500)- expect(invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.inbox() })- expect(invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.dms() })+ expect(getCommunityApiFetchMock().mock.calls.filter(([path]) => (+ path === "/api/community/users/me/attention"+ ))).toHaveLength(1)})it("does not re-arm the Inbox owner when reconnect repair settles after unmount", async () => {@@ -179,7 +178,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {})})- it("reconciles the focused channel's messages + inbox on reconnect, but NOT the read-state snapshot", async () => {+ it("reconciles focused messages + canonical attention on reconnect, but not the read snapshot", async () => {vi.useFakeTimers()const { useCommunityStore } = await import("@/stores/community")useCommunityStore.getState().subscribe({ channelId: "ch_focus" })@@ -190,7 +189,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {expect(capturedOnReconnect).not.toBeNull()await capturedOnReconnect!({ reconnectDurationMs: 0 })- let invalidatedKeys = spy.mock.calls.map(+ const invalidatedKeys = spy.mock.calls.map((c) => c[0]?.queryKey as unknown[] | undefined,)// Focused channel messages use the bounded catch-up path instead of a@@ -238,15 +237,9 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {(k) => Array.isArray(k) && k[0] === "community" && k[1] === "inbox",),).toBe(false)- await vi.advanceTimersByTimeAsync(500)- invalidatedKeys = spy.mock.calls.map(- (c) => c[0]?.queryKey as unknown[] | undefined,- )- expect(- invalidatedKeys.some(- (k) => Array.isArray(k) && k[0] === "community" && k[1] === "inbox",- ),- ).toBe(true)+ await vi.waitFor(() => expect(getCommunityApiFetchMock().mock.calls.filter(([path]) => (+ path === "/api/community/users/me/attention"+ ))).toHaveLength(1))})it("reconciles both visible split panes and drops the hidden parent after owner cleanup", async () => {@@ -612,7 +605,7 @@ 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 () => {+ it("actively refetches cached Friends and canonical attention after a socket gap", async () => {const { reconcileCommunityWsReconnect } = await import("./reconnect")const queryClient = new QueryClient({defaultOptions: { queries: { retry: false, staleTime: Infinity } },@@ -621,7 +614,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {const friendsQuery = vi.fn(async () => ({ version }))const inboxQuery = vi.fn(async () => ({ version }))const friendsKey = communityKeys.friends()- const inboxKey = communityKeys.inboxUnreads()+ const inboxKey = communityKeys.accountAttention()await Promise.all([queryClient.fetchQuery({ queryKey: friendsKey, queryFn: friendsQuery }),queryClient.fetchQuery({ queryKey: inboxKey, queryFn: inboxQuery }),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 f8a713e06..88e8dbe47 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@@ -16,6 +16,7 @@ import {capturedOnMessage,capturedQueryClient,cleanupCommunityWsHarness,+ getCommunityApiFetchMock,messageCreate,mountHook,resetCommunityWsHarness,@@ -279,20 +280,21 @@ describe("useCommunityWs — friend + mention → invalidate", () => {{ 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) => {+ ])("$type invalidates Friends and reconciles canonical attention once", async (event) => {await mountHook()const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")capturedOnMessage!(event)- await vi.waitFor(() => expect(spy).toHaveBeenCalledTimes(2))+ await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledWith(+ "/api/community/users/me/attention",+ expect.objectContaining({ signal: expect.anything() }),+ ))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 })+ expect(getCommunityApiFetchMock().mock.calls.filter(([path]) => (+ path === "/api/community/users/me/attention"+ ))).toHaveLength(1)})it("friend.block evicts cached DM reactor identities", async () => {@@ -332,11 +334,10 @@ describe("useCommunityWs — friend + mention → invalidate", () => {expect(capturedQueryClient.getQueryState(key)).toBeUndefined()})- it("routes mention.create through the debounced Inbox owner", async () => {+ it("coalesces mention.create through the canonical attention owner", async () => {vi.useFakeTimers()try {await mountHook({ viewerUserId: "u_1" })- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")const event: CommunityMentionCreate = {type: "community:mention.create",userId: "u_1",@@ -344,11 +345,10 @@ describe("useCommunityWs — friend + mention → invalidate", () => {authorName: "A",}capturedOnMessage!(event)- expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.inbox() })await vi.advanceTimersByTimeAsync(500)- expect(spy.mock.calls.some((call) => (- (call[0]?.queryKey as unknown[] | undefined)?.includes("inbox")- ))).toBe(true)+ expect(getCommunityApiFetchMock().mock.calls.filter(([path]) => (+ path === "/api/community/users/me/attention"+ ))).toHaveLength(1)} finally {vi.useRealTimers()}diff --git a/src/web/src/hooks/community/community-ws/social-events.ts b/src/web/src/hooks/community/community-ws/social-events.tsindex a61b58506..dcf8f1c28 100644--- a/src/web/src/hooks/community/community-ws/social-events.ts+++ b/src/web/src/hooks/community/community-ws/social-events.ts@@ -13,7 +13,6 @@ import {import type { SocialEventContext } from "@/hooks/community/community-ws/handler-context"import {invalidateFriends,- invalidateInboxUnreads,invalidateServersList,} from "./invalidation-projections"import {@@ -29,11 +28,6 @@ import {resolveDesktopSystemNotificationCandidate,showDesktopSystemNotification,} from "@/lib/community/desktop-system-notification"-import {- projectAttentionFriendEvent,- projectAttentionMentionHint,- projectAttentionUnreadBump,-} from "@/lib/community-db/sync"import { scheduleAccountAttentionReconcile } from "@/hooks/community/use-account-attention"export function handleReadStateAdvanced(@@ -88,12 +82,10 @@ export function handleUnreadBump(queryClient,viewerUserIdRef,unreadBumpEvidence,- scheduleInboxInvalidate,} = contextconst viewerId = viewerUserIdRef.currentif (event.userId === viewerId && viewerId) {const evidence = unreadBumpEvidence?.get(event)- projectAttentionUnreadBump(queryClient, event, evidence)scheduleAccountAttentionReconcile(queryClient)getAccountUnreadProjection(queryClient, viewerId).recordArrival({channelId: event.channelId,@@ -105,7 +97,6 @@ export function handleUnreadBump(})// Use the existing coalesced owner. This is also the sole authority// refresh for legacy/orphan bumps; the ledger itself performs no I/O.- scheduleInboxInvalidate({ inbox: true, dms: !event.serverId })if (evidence && isDesktop()) {void resolveDesktopSystemNotificationCandidate(evidence.messageEvent,@@ -132,11 +123,9 @@ export function handleFriendEvent(event: FriendEvent,{ projection, queryClient }: SocialEventContext,) {- projectAttentionFriendEvent(queryClient, event)scheduleAccountAttentionReconcile(queryClient)if (event.type === "community:friend.request") {invalidateFriends(projection)- invalidateInboxUnreads(projection)} else {projection.project(() => {const controller = getFriendRequestActionController(queryClient)@@ -150,10 +139,6 @@ export function handleFriendEvent(queryKey: communityKeys.friends(),exact: true,})- projection.fence("inbox-unreads", {- queryKey: communityKeys.inboxUnreads(),- exact: true,- })}if (event.type === "community:friend.block") removeDmReactionDetails(queryClient)}@@ -162,7 +147,6 @@ export function handleMentionCreate(event: CommunityMentionCreate,{projection,- scheduleInboxInvalidate,queryClient,viewerUserIdRef,messageEvidenceByChannel,@@ -170,11 +154,10 @@ export function handleMentionCreate() {const viewerId = viewerUserIdRef.currentif (!viewerId || event.userId !== viewerId) return- if (viewerId && event.userId === viewerId && event.channelId) {+ scheduleAccountAttentionReconcile(queryClient)+ if (event.channelId) {const candidate = messageEvidenceByChannel?.get(event.channelId)const evidence = candidate?.messageId === event.messageId ? candidate : undefined- projectAttentionMentionHint(queryClient, event, evidence)- scheduleAccountAttentionReconcile(queryClient)getAccountUnreadProjection(queryClient, viewerId).recordMentionArrival({channelId: event.channelId,messageId: event.messageId,@@ -182,7 +165,6 @@ export function handleMentionCreate(isMention: true,})}- scheduleInboxInvalidate({ inbox: true, dms: false })// The server rail badge counts unread mentions per server; refresh// it on every new mention. `exact: true` is essential: the mention// count lives in the `servers()` LIST query, but members/presence/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.tsxindex 9b7479329..c98fba1ee 100644--- 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.tsx@@ -7,6 +7,7 @@ import {import { act, render, waitFor } from "@/test/react-dom-harness"import { beforeEach, describe, expect, it, vi } from "vitest"import { communityKeys } from "@/lib/query-keys"+import { apiFetch } from "@/lib/api/client"import type { PendingRequest } from "@/lib/community/models/people"import type { InboxFriendRequest } from "@/lib/community/models/inbox"import { useCommunityWsStore } from "@/stores/community/ws"@@ -21,10 +22,6 @@ import {friendsQueryFn,type FriendsResponse,} from "./use-friends"-import {- inboxUnreadsQueryFn,- type UnreadsResponse,-} from "./use-inbox"import {useFriendRequestActionState,type ActionableFriendRequest,@@ -69,14 +66,30 @@ function friendsData(ids: readonly string[]): FriendsResponse {}}-function inboxData(ids: readonly string[]): UnreadsResponse {+type AttentionResponse = {+ items: Array<{+ id: string+ kind: "friend_request"+ sourceId: string+ actorUserId: string+ }>+}++function attentionData(ids: readonly string[]): AttentionResponse {return {- friendRequests: inboxRows.filter((row) => ids.includes(row.id)),- servers: [],- dms: [],+ items: inboxRows.filter((row) => ids.includes(row.id)).map((row) => ({+ id: `friend_request:${row.id}`,+ kind: "friend_request",+ sourceId: row.id,+ actorUserId: row.userId,+ })),}}+const attentionQueryFn = () => apiFetch<AttentionResponse>(+ "/api/community/users/me/attention",+)+type Transport = {action: (id: string) => Promise<unknown>readFriends: () => Promise<readonly string[]>@@ -93,8 +106,8 @@ function installTransport(transport: Transport) {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())+ if (path === "/api/community/users/me/attention") {+ return attentionData(await transport.readInbox())}throw new Error(`unexpected API path ${path}`)})@@ -127,8 +140,8 @@ function TestSurfaces({enabled: false,})const inbox = useQuery({- queryKey: communityKeys.inboxUnreads(),- queryFn: inboxUnreadsQueryFn,+ queryKey: communityKeys.accountAttention(),+ queryFn: attentionQueryFn,enabled: false,})const mutation = useAcceptFriendRequest()@@ -137,7 +150,7 @@ function TestSurfaces({[mutation],)const inboxActions = useFriendRequestActionState({- rows: inbox.data?.friendRequests ?? [],+ rows: inboxRows.filter((row) => inbox.data?.items.some((item) => item.sourceId === row.id)),onAccept,surface: "inbox",})@@ -224,7 +237,7 @@ function createClient(ids: readonly string[] = ["a", "b"]) {},})client.setQueryData(communityKeys.friends(), friendsData(ids), { updatedAt: 1 })- client.setQueryData(communityKeys.inboxUnreads(), inboxData(ids), { updatedAt: 1 })+ client.setQueryData(communityKeys.accountAttention(), attentionData(ids), { updatedAt: 1 })return client}@@ -246,10 +259,10 @@ async function fetchFriends(client: QueryClient) {})}-async function fetchInbox(client: QueryClient) {+async function fetchAttention(client: QueryClient) {return client.fetchQuery({- queryKey: communityKeys.inboxUnreads(),- queryFn: inboxUnreadsQueryFn,+ queryKey: communityKeys.accountAttention(),+ queryFn: attentionQueryFn,staleTime: 0,})}@@ -272,7 +285,7 @@ describe("friend-request action authority RED", () => {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 () => { await Promise.all([fetchFriends(client), fetchAttention(client)]) })await act(async () => {gate.reject(new Error("ambiguous failure"))await request@@ -302,12 +315,12 @@ describe("friend-request action authority RED", () => {expect(rendered.getByTestId("inbox-row-a")).toHaveAttribute("data-status", "error")await act(async () => {- await Promise.allSettled([fetchFriends(client), fetchInbox(client)])+ await Promise.allSettled([fetchFriends(client), fetchAttention(client)])})expect(rendered.getByTestId("inbox-row-a")).toHaveAttribute("data-status", "error")stale = false- await act(async () => { await fetchInbox(client) })+ await act(async () => { await fetchAttention(client) })expect(rendered.queryByTestId("inbox-row-a")).toBeNull()expect(rendered.queryByTestId("friends-row-a")).toBeNull()const projection = rendered.getByTestId("projection")@@ -328,9 +341,9 @@ describe("friend-request action authority RED", () => {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)+ const read = fetchAttention(client)await waitFor(() => expect(apiFetchMock.mock.calls.some(- ([path]) => path === "/api/community/users/me/inbox/unreads",+ ([path]) => path === "/api/community/users/me/attention",)).toBe(true))paints.length = 0await act(async () => {@@ -398,7 +411,7 @@ describe("friend-request action authority RED", () => {))).toBe(true)await act(async () => {- await Promise.allSettled([fetchFriends(client), fetchInbox(client)])+ await Promise.allSettled([fetchFriends(client), fetchAttention(client)])})expect(rendered.queryByTestId("inbox-row-a")).toBeNull()expect(rendered.queryByTestId("friends-row-a")).toBeNull()@@ -439,11 +452,11 @@ describe("friend-request action authority RED", () => {} satisfies SocialEventContext,)client.setQueryData(communityKeys.friends(), friendsData(["a"]))- client.setQueryData(communityKeys.inboxUnreads(), inboxData(["a"]))+ client.setQueryData(communityKeys.accountAttention(), attentionData(["a"]))})await act(async () => {- await Promise.allSettled([fetchFriends(client), fetchInbox(client)])+ await Promise.allSettled([fetchFriends(client), fetchAttention(client)])})expect(rendered.queryByTestId("inbox-row-a")).toBeNull()expect(rendered.queryByTestId("friends-row-a")).toBeNull()@@ -463,19 +476,19 @@ describe("friend-request action authority RED", () => {refetchType: "none",}),client.invalidateQueries({- queryKey: communityKeys.inboxUnreads(),+ queryKey: communityKeys.accountAttention(),exact: true,refetchType: "none",}),])- await Promise.all([fetchFriends(client), fetchInbox(client)])+ await Promise.all([fetchFriends(client), fetchAttention(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"]))+ client.setQueryData(communityKeys.accountAttention(), attentionData(["a"]))})await waitFor(() => {expect(rendered.getByTestId("inbox-row-a")).toBeInTheDocument()@@ -494,23 +507,23 @@ describe("friend-request action authority RED", () => {readInbox: () => postTerminal ? Promise.resolve([]) : oldInbox.promise,})const client = createClient(["a"])- const preTerminalReads = [fetchFriends(client), fetchInbox(client)]+ const preTerminalReads = [fetchFriends(client), fetchAttention(client)]await waitFor(() => expect(apiFetchMock.mock.calls.some(- ([path]) => path === "/api/community/users/me/inbox/unreads",+ ([path]) => path === "/api/community/users/me/attention",)).toBe(true))await Promise.all([client.cancelQueries({ queryKey: communityKeys.friends(), exact: true }),- client.cancelQueries({ queryKey: communityKeys.inboxUnreads(), exact: true }),+ client.cancelQueries({ queryKey: communityKeys.accountAttention(), exact: true }),])postTerminal = true- await Promise.all([fetchFriends(client), fetchInbox(client)])+ await Promise.all([fetchFriends(client), fetchAttention(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([])+ expect(client.getQueryData<AttentionResponse>(communityKeys.accountAttention())?.items).toEqual([])})})@@ -559,7 +572,7 @@ describe("friend-request shared owner RED", () => {await act(async () => { await controls.current!.act("inbox", "a") })act(() => {client.removeQueries({ queryKey: communityKeys.friends(), exact: true })- client.removeQueries({ queryKey: communityKeys.inboxUnreads(), exact: true })+ client.removeQueries({ queryKey: communityKeys.accountAttention(), exact: true })})let retry!: Promise<void>@@ -570,7 +583,7 @@ describe("friend-request shared owner RED", () => {expect(rendered.getByTestId("friends-row-a")).toHaveAttribute("data-status", "pending")})expect(client.getQueryData(communityKeys.friends())).toBeUndefined()- expect(client.getQueryData(communityKeys.inboxUnreads())).toBeUndefined()+ expect(client.getQueryData(communityKeys.accountAttention())).toBeUndefined()} finally {retryGate.resolve(undefined)await act(async () => { await retry })@@ -662,7 +675,7 @@ describe("friend-request shared owner RED", () => {})if (order === "terminal-first") {- await act(async () => { await Promise.all([fetchFriends(client), fetchInbox(client)]) })+ await act(async () => { await Promise.all([fetchFriends(client), fetchAttention(client)]) })await act(async () => {actions.get(terminalId)!.reject(new Error(`ambiguous ${terminalId}`))await (terminalId === "a" ? actionA : actionB)@@ -676,7 +689,7 @@ describe("friend-request shared owner RED", () => {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 () => { await Promise.all([fetchFriends(client), fetchAttention(client)]) })await act(async () => {actions.get(terminalId)!.reject(new Error(`ambiguous ${terminalId}`))await (terminalId === "a" ? actionA : actionB)diff --git a/src/web/src/hooks/community/mutations/friends.test.ts b/src/web/src/hooks/community/mutations/friends.test.tsindex cdc5132ba..569294e9d 100644--- a/src/web/src/hooks/community/mutations/friends.test.ts+++ b/src/web/src/hooks/community/mutations/friends.test.ts@@ -120,6 +120,12 @@ describe("useAcceptFriendRequest — rollback", () => {}],limit: 100,truncated: false,+ included: {+ servers: [], channels: [], dms: [], messages: [],+ profiles: [{+ userId: "u_1", name: "One", discriminator: "0001", avatar: "O", avatarVersion: 1,+ }],+ },}ingestAttentionSnapshot(canonicalRegistry!, canonical)capturedQc.setQueryData(communityKeys.friends(), {@@ -184,7 +190,7 @@ describe("useAcceptFriendRequest — rollback", () => {it("reconciles a failed friend action after an intervening canonical event", async () => {const mod = await load()await installCanonicalRegistry()- const { ingestAttentionSnapshot, projectAttentionUnreadBump } = await import(+ const { ingestAttentionSnapshot, ingestMessages, projectCommunityWsEventToDb } = await import("@/lib/community-db/sync")const canonical = {@@ -196,6 +202,12 @@ describe("useAcceptFriendRequest — rollback", () => {}],limit: 100,truncated: false,+ included: {+ servers: [], channels: [], dms: [], messages: [],+ profiles: [{+ userId: "u_1", name: "One", discriminator: "0001", avatar: "O", avatarVersion: 1,+ }],+ },}ingestAttentionSnapshot(canonicalRegistry!, canonical)capturedQc.setQueryData(communityKeys.friends(), {@@ -209,13 +221,13 @@ describe("useAcceptFriendRequest — rollback", () => {mod.useAcceptFriendRequest()const cfg = capturedConfig as MutConfig<{ friendshipId: string }, unknown>const context = await cfg.onMutate?.({ friendshipId: "f_1" })- projectAttentionUnreadBump(capturedQc, {- type: "community:unread.bump",- userId: "u_me",+ ingestMessages(canonicalRegistry!, "other", [{ id: "event", type: "chat", content: "old" }])+ projectCommunityWsEventToDb(capturedQc, {+ type: "community:message.edited",channelId: "other",- serverId: "s_1",- isMention: false,- }, { seq: 2 })+ messageId: "event",+ content: "new",+ } as never)await cfg.onError?.(new Error("friend action failed"), { friendshipId: "f_1" }, context)@@ -242,7 +254,7 @@ describe("useAcceptFriendRequest — rollback", () => {expect(cache?.pending).toHaveLength(1)})- it("optimistically removes and compensates the same id in both cache grains", async () => {+ it("optimistically removes and compensates the same id in the Friends cache", async () => {capturedQc.setQueryData(communityKeys.friends(), {friends: [],blocked: [],@@ -251,14 +263,6 @@ describe("useAcceptFriendRequest — rollback", () => {{ 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>@@ -267,18 +271,13 @@ describe("useAcceptFriendRequest — rollback", () => {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([@@ -297,14 +296,6 @@ describe("useAcceptFriendRequest — rollback", () => {{ 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>@@ -332,8 +323,6 @@ describe("useAcceptFriendRequest — rollback", () => {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])},)@@ -359,19 +348,7 @@ describe("useAcceptFriendRequest — rollback", () => {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: [],- })+ it("never reconstructs an absent Friends envelope", async () => {const mod = await load()mod.useAcceptFriendRequest()const cfg = capturedConfig as MutConfig<{ friendshipId: string }, unknown>@@ -379,12 +356,9 @@ describe("useAcceptFriendRequest — rollback", () => {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 () => {+ it("awaits settled invalidation of Friends", async () => {apiFetchMock.mockResolvedValueOnce(undefined)const mod = await load()mod.useAcceptFriendRequest()@@ -394,13 +368,12 @@ describe("useAcceptFriendRequest — rollback", () => {))let settled = falseconst mutation = runMutation({ friendshipId: "f_1" }).then(() => { settled = true })- await vi.waitFor(() => expect(spy).toHaveBeenCalledTimes(2))+ await vi.waitFor(() => expect(spy).toHaveBeenCalledTimes(1))expect(settled).toBe(false)gates.splice(0).forEach((resolve) => resolve())await mutationexpect(spy.mock.calls.map((call) => call[0])).toEqual([{ queryKey: communityKeys.friends(), exact: true },- { queryKey: communityKeys.inboxUnreads(), exact: true },])})})diff --git a/src/web/src/hooks/community/mutations/friends.ts b/src/web/src/hooks/community/mutations/friends.tsindex c4e47e17f..5714b5979 100644--- a/src/web/src/hooks/community/mutations/friends.ts+++ b/src/web/src/hooks/community/mutations/friends.ts@@ -4,9 +4,7 @@ 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,@@ -59,7 +57,6 @@ type CapturedRow<T> = { row: T; index: number }type FriendRequestMutationContext = {friends?: CapturedRow<PendingRequest>generation: number- inbox?: CapturedRow<InboxFriendRequest>attention?: AttentionItemsOptimisticSnapshot}@@ -94,17 +91,11 @@ function useFriendRequestMutation(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 }),- ])+ await queryClient.cancelQueries({ queryKey: friendsKey, 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),attention: (() => {const registry = getCommunityDbRegistry(queryClient)return registry@@ -120,14 +111,6 @@ function useFriendRequestMutation(? { ...current, pending: current.pending.filter((row) => row.id !== friendshipId) }: current,)- queryClient.setQueryData<UnreadsResponse | undefined>(inboxKey, (current) =>- current- ? {- ...current,- friendRequests: (current.friendRequests ?? []).filter((row) => row.id !== friendshipId),- }- : current,- )return context},onSuccess: async (_data, { friendshipId }, context) => {@@ -158,19 +141,11 @@ function useFriendRequestMutation(? { ...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 }),- ])+ await queryClient.invalidateQueries({ queryKey: communityKeys.friends(), exact: true })} finally {if (context) controller.settleGeneration(friendshipId, context.generation)}diff --git a/src/web/src/hooks/community/mutations/messages.test.ts b/src/web/src/hooks/community/mutations/messages.test.tsindex cc7014311..95ca6321b 100644--- a/src/web/src/hooks/community/mutations/messages.test.ts+++ b/src/web/src/hooks/community/mutations/messages.test.ts@@ -172,6 +172,27 @@ async function installCanonicalRegistry() {unregisterCanonicalRegistry = collections.registerCommunityDbRegistry(canonicalRegistry)}+function attentionIncluded(overrides: {+ messages?: Array<Record<string, unknown>>+ profiles?: Array<Record<string, unknown>>+} = {}) {+ return {+ servers: [{ id: "s_1", name: "Server", discriminator: "0001" }],+ channels: [{+ id: "channel", serverId: "s_1", name: "Channel", type: "text",+ parentChannelId: null, parentMessageId: null, creatorId: null,+ archived: false, lastMessageAt: null,+ }, {+ id: "ch_1", serverId: "s_1", name: "Channel", type: "text",+ parentChannelId: null, parentMessageId: null, creatorId: null,+ archived: false, lastMessageAt: null,+ }],+ dms: [],+ profiles: overrides.profiles ?? [],+ messages: overrides.messages ?? [],+ }+}+async function seedCanonicalParent(type: "forum" | "text") {if (!canonicalRegistry) throw new Error("canonical test registry is not active")const sync = await import("@/lib/community-db/sync")@@ -1279,7 +1300,7 @@ describe("useMarkAllInboxRead", () => {it("reconciles mark-all after an intervening canonical event declines rollback", async () => {const mod = await loadMod()await installCanonicalRegistry()- const { ingestAttentionSnapshot, projectAttentionUnreadBump } = await import(+ const { ingestAttentionSnapshot, ingestMessages, projectCommunityWsEventToDb } = await import("@/lib/community-db/sync")const canonical = {@@ -1290,6 +1311,7 @@ describe("useMarkAllInboxRead", () => {items: [],limit: 100,truncated: false,+ included: attentionIncluded(),}ingestAttentionSnapshot(canonicalRegistry!, canonical)apiFetchMock.mockImplementation(async (path: string) => {@@ -1299,13 +1321,13 @@ describe("useMarkAllInboxRead", () => {mod.useMarkAllInboxRead()const cfg = capturedConfig as MutConfig<void, unknown>const context = await cfg.onMutate?.(undefined as unknown as void)- projectAttentionUnreadBump(capturedQc, {- type: "community:unread.bump",- userId: "u_me",+ ingestMessages(canonicalRegistry!, "other", [{ id: "event", type: "chat", content: "old" }])+ projectCommunityWsEventToDb(capturedQc, {+ type: "community:message.edited",channelId: "other",- serverId: "s_1",- isMention: false,- }, { seq: 2 })+ messageId: "event",+ content: "new",+ } as never)cfg.onError?.(new Error("account read-all failed"), undefined as unknown as void, context)@@ -1368,6 +1390,15 @@ describe("useDeleteMention — rollback", () => {}],limit: 100,truncated: false,+ included: attentionIncluded({+ profiles: [{+ userId: "u_2", name: "Two", discriminator: "0002", avatar: "T", avatarVersion: 1,+ }],+ messages: [{+ id: "m_1", channelId: "ch_1", authorId: "u_2", content: "hello",+ createdAt: "2026-09-27T00:00:00.000Z", seq: 4, type: "chat",+ }],+ }),}ingestAttentionSnapshot(canonicalRegistry!, canonical)capturedQc.setQueryData(communityKeys.inboxMentions(), {@@ -1393,7 +1424,7 @@ describe("useDeleteMention — rollback", () => {it("reconciles a failed dismissal after an intervening canonical event", async () => {const mod = await loadMod()await installCanonicalRegistry()- const { ingestAttentionSnapshot, projectAttentionUnreadBump } = await import(+ const { ingestAttentionSnapshot, ingestMessages, projectCommunityWsEventToDb } = await import("@/lib/community-db/sync")const canonical = {@@ -1407,6 +1438,15 @@ describe("useDeleteMention — rollback", () => {}],limit: 100,truncated: false,+ included: attentionIncluded({+ profiles: [{+ userId: "u_2", name: "Two", discriminator: "0002", avatar: "T", avatarVersion: 1,+ }],+ messages: [{+ id: "m_1", channelId: "ch_1", authorId: "u_2", content: "hello",+ createdAt: "2026-09-27T00:00:00.000Z", seq: 4, type: "chat",+ }],+ }),}ingestAttentionSnapshot(canonicalRegistry!, canonical)capturedQc.setQueryData(communityKeys.inboxMentions(), {@@ -1419,13 +1459,13 @@ describe("useDeleteMention — rollback", () => {mod.useDeleteMention()const cfg = capturedConfig as MutConfig<{ mentionId: string }, unknown>const context = await cfg.onMutate?.({ mentionId: "men_1" })- projectAttentionUnreadBump(capturedQc, {- type: "community:unread.bump",- userId: "u_me",+ ingestMessages(canonicalRegistry!, "other", [{ id: "event", type: "chat", content: "old" }])+ projectCommunityWsEventToDb(capturedQc, {+ type: "community:message.edited",channelId: "other",- serverId: "s_1",- isMention: false,- }, { seq: 5 })+ messageId: "event",+ content: "new",+ } as never)cfg.onError?.(new Error("dismiss failed"), { mentionId: "men_1" }, context)@@ -1439,6 +1479,8 @@ describe("useDeleteMention — rollback", () => {})it("keeps a same-seq sibling and only decrements badges for direct mentions", async () => {+ const mod = await loadMod()+ await installCanonicalRegistry()const reply = {id: "reply-1",kind: "reply",@@ -1451,10 +1493,29 @@ describe("useDeleteMention — rollback", () => {channelId: "ch_1",m: { id: "msg_1", seq: 4 },}- capturedQc.setQueryData(communityKeys.inboxMentions(), {- mentions: [reply, mention],+ const { ingestAttentionSnapshot, ingestMessages } = await import(+ "@/lib/community-db/sync"+ )+ ingestMessages(canonicalRegistry!, "ch_1", [{+ id: "msg_1", type: "chat", authorId: "u_2", seq: 4,+ }])+ ingestAttentionSnapshot(canonicalRegistry!, {+ scopes: [{+ scopeId: "ch_1", channelId: "ch_1", serverId: "srv_1", parentChannelId: null,+ ordinaryUnread: false, lastUnreadSeq: 4, lastAttentionSeq: 4, attentionCount: 2,+ }],+ items: [reply, mention].map((row) => ({+ id: `mention:${row.id}`,+ kind: row.kind as "mention" | "reply",+ sourceId: row.id,+ scopeId: "ch_1",+ messageId: "msg_1",+ actorUserId: "u_2",+ createdAt: "2026-09-27T00:00:00.000Z",+ })),+ limit: 100,+ truncated: false,})- const mod = await loadMod()const { getActiveAccountUnreadProjection } = await import("@/hooks/community/account-unread-projection")@@ -1475,11 +1536,23 @@ describe("useDeleteMention — rollback", () => {{ mentionId: string },{ token?: unknown; snapshot?: unknown }>+ const cachedAttentionItems = () => capturedQc.getQueryData<Array<{ id: string }>>(+ communityKeys.communityDbCollection("u_me", "attentionItems"),+ ) ?? []+ const cachedAttentionCount = () => capturedQc.getQueryData<Array<{+ scopeId: string+ attentionCount: number+ }>>(communityKeys.communityDbCollection("u_me", "attentionScopes"))+ ?.find((scope) => scope.scopeId === "ch_1")?.attentionCountconst replyContext = await cfg.onMutate?.({ mentionId: reply.id })- expect(capturedQc.getQueryData<{ mentions: Array<{ id: string }> }>(- communityKeys.inboxMentions(),- )?.mentions.map((row) => row.id)).toEqual([mention.id])+ expect(cachedAttentionItems().map((item) => item.id)).toEqual(["mention:mention-1"])+ expect(cachedAttentionCount()).toBe(1)+ await vi.waitFor(() => {+ expect(canonicalRegistry!.collections.attentionItems.get("mention:reply-1")).toBeUndefined()+ expect(canonicalRegistry!.collections.attentionItems.get("mention:mention-1")).toBeDefined()+ expect(canonicalRegistry!.collections.attentionScopes.get("ch_1")?.attentionCount).toBe(1)+ })expect(projection.projectUnread("inbox-mentions", "ch_1", true, 4, "mentions", null, true, mention.id,)).toBe(true)@@ -1488,10 +1561,18 @@ describe("useDeleteMention — rollback", () => {}])).toBe(1)cfg.onError?.(new Error("retry direct"), { mentionId: reply.id }, replyContext)+ expect(cachedAttentionItems().map((item) => item.id).sort()).toEqual([+ "mention:mention-1", "mention:reply-1",+ ])+ expect(cachedAttentionCount()).toBe(2)const mentionContext = await cfg.onMutate?.({ mentionId: mention.id })- expect(capturedQc.getQueryData<{ mentions: Array<{ id: string }> }>(- communityKeys.inboxMentions(),- )?.mentions.map((row) => row.id)).toEqual([reply.id])+ expect(cachedAttentionItems().map((item) => item.id)).toEqual(["mention:reply-1"])+ expect(cachedAttentionCount()).toBe(1)+ await vi.waitFor(() => {+ expect(canonicalRegistry!.collections.attentionItems.get("mention:mention-1")).toBeUndefined()+ expect(canonicalRegistry!.collections.attentionItems.get("mention:reply-1")).toBeDefined()+ expect(canonicalRegistry!.collections.attentionScopes.get("ch_1")?.attentionCount).toBe(1)+ })expect(projection.projectUnread("inbox-mentions", "ch_1", true, 4, "mentions", null, true, reply.id,)).toBe(true)@@ -1499,13 +1580,38 @@ describe("useDeleteMention — rollback", () => {channelId: "ch_1", count: 1, lastSeq: 4,}])).toBe(0)cfg.onError?.(new Error("cleanup"), { mentionId: mention.id }, mentionContext)+ expect(cachedAttentionItems().map((item) => item.id).sort()).toEqual([+ "mention:mention-1", "mention:reply-1",+ ])+ expect(cachedAttentionCount()).toBe(2)+ await vi.waitFor(() => {+ expect(canonicalRegistry!.collections.attentionItems.get("mention:reply-1")).toBeDefined()+ expect(canonicalRegistry!.collections.attentionItems.get("mention:mention-1")).toBeDefined()+ expect(canonicalRegistry!.collections.attentionScopes.get("ch_1")?.attentionCount).toBe(2)+ })})it("hides only the exact attention facet and restores it on failure", async () => {- capturedQc.setQueryData(communityKeys.inboxMentions(), {- mentions: [{ id: "men_1", channelId: "ch_1", m: { id: "msg_1", seq: 4 } }],- })const mod = await loadMod()+ await installCanonicalRegistry()+ const { ingestAttentionSnapshot, ingestMessages } = await import(+ "@/lib/community-db/sync"+ )+ ingestMessages(canonicalRegistry!, "ch_1", [{+ id: "msg_1", type: "chat", authorId: "u_2", seq: 4,+ }])+ ingestAttentionSnapshot(canonicalRegistry!, {+ scopes: [{+ scopeId: "ch_1", channelId: "ch_1", serverId: "srv_1", parentChannelId: null,+ ordinaryUnread: true, lastUnreadSeq: 4, lastAttentionSeq: 4, attentionCount: 1,+ }],+ items: [{+ id: "mention:men_1", kind: "mention", sourceId: "men_1", scopeId: "ch_1",+ messageId: "msg_1", actorUserId: "u_2", createdAt: "2026-09-27T00:00:00.000Z",+ }],+ limit: 100,+ truncated: false,+ })const { getActiveAccountUnreadProjection } = await import("@/hooks/community/account-unread-projection")@@ -1514,6 +1620,7 @@ describe("useDeleteMention — rollback", () => {channelId: "ch_1",serverId: "srv_1",messageId: "msg_1",+ attentionId: "men_1",seq: 4,isMention: true,})@@ -1523,10 +1630,17 @@ describe("useDeleteMention — rollback", () => {{ token?: unknown; snapshot?: unknown }>const context = await cfg.onMutate?.({ mentionId: "men_1" })+ expect(canonicalRegistry!.collections.attentionItems.get("mention:men_1")).toBeUndefined()+ expect(canonicalRegistry!.collections.attentionScopes.get("ch_1")).toMatchObject({+ ordinaryUnread: true,+ attentionCount: 0,+ })expect(projection.projectUnread("inbox-unreads", "ch_1", false)).toBe(true)expect(projection.projectUnread("inbox-mentions", "ch_1", false)).toBe(false)cfg.onError?.(new Error("boom"), { mentionId: "men_1" }, context)+ expect(canonicalRegistry!.collections.attentionItems.get("mention:men_1")).toBeDefined()+ expect(canonicalRegistry!.collections.attentionScopes.get("ch_1")?.attentionCount).toBe(1)expect(projection.projectUnread("inbox-mentions", "ch_1", false)).toBe(true)})diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.tsindex f4e2b6ef5..b7a561f3a 100644--- a/src/web/src/hooks/community/mutations/messages.ts+++ b/src/web/src/hooks/community/mutations/messages.ts@@ -29,7 +29,6 @@ import type { Attachment, MessagesPage, Msg } from "@/lib/community/models/messaimport type { PinsResponse } from "@/hooks/community/use-channel-panels"import type {MarkedResponse,- MentionsResponse,MessageMarkedResponse,} from "@/hooks/community/use-inbox"import {@@ -54,6 +53,7 @@ import {clearAttentionOptimistically,commitAttentionOptimisticSnapshot,commitAttentionItemsOptimisticSnapshot,+ getCanonicalCommunityMessages,removeAttentionItemsOptimistically,restoreAttentionOptimisticDomains,restoreAttentionOptimisticSnapshot,@@ -979,7 +979,6 @@ export function useDeleteMention() {Error,DeleteMentionArgs,{- snapshot: MentionsResponse | undefinedtoken?: AccountUnreadDismissTokenattentionSnapshot?: AttentionItemsOptimisticSnapshot}@@ -991,28 +990,30 @@ export function useDeleteMention() {)},onMutate: async (args) => {- const key = communityKeys.inboxMentions()- const snapshot = queryClient.getQueryData<MentionsResponse>(key)- const row = snapshot?.mentions.find((mention) => mention.id === args.mentionId)- const token = row?.channelId- ? unreadProjection.beginDismissMention({- mentionId: args.mentionId,- channelId: row.channelId,- seq: row.m.seq,- countsServerMention: row.kind !== "reply",- })- : undefined- queryClient.setQueryData(key, (prev: { mentions: { id: string }[] } | undefined) =>- prev ? { ...prev, mentions: prev.mentions.filter((m) => m.id !== args.mentionId) } : prev,- )const registry = getCommunityDbRegistry(queryClient)const attentionSnapshot = registry? removeAttentionItemsOptimistically(registry,- (item) => item.sourceId === args.mentionId && item.kind !== "friend_request",+ (item) => (+ item.sourceId === args.mentionId+ && (item.kind === "mention" || item.kind === "reply")+ ),): undefined- return { snapshot, token, attentionSnapshot }+ const removed = attentionSnapshot?.items[0]+ const message = removed?.messageId+ ? getCanonicalCommunityMessages(queryClient)+ .find((candidate) => candidate.id === removed.messageId)+ : undefined+ const token = removed?.scopeId && message?.seq !== undefined+ ? unreadProjection.beginDismissMention({+ mentionId: args.mentionId,+ channelId: removed.scopeId,+ seq: message.seq,+ countsServerMention: removed.kind === "mention",+ })+ : undefined+ return { token, attentionSnapshot }},onSuccess: (result, _args, context) => {if (context.token) unreadProjection.commitDismissMention(context.token, result?.revision)@@ -1033,7 +1034,6 @@ export function useDeleteMention() {void reconcileAccountAttention(registry).catch(() => undefined)}}- if (ctx?.snapshot) queryClient.setQueryData(communityKeys.inboxMentions(), ctx.snapshot)toastApiError(err, "Failed to remove mention")},})diff --git a/src/web/src/hooks/community/read-coordinator.test.ts b/src/web/src/hooks/community/read-coordinator.test.tsindex 712779212..32837ebd9 100644--- a/src/web/src/hooks/community/read-coordinator.test.ts+++ b/src/web/src/hooks/community/read-coordinator.test.ts@@ -9,7 +9,7 @@ import {import {ingestAttentionSnapshot,ingestMessages,- projectAttentionUnreadBump,+ projectCommunityWsEventToDb,} from "@/lib/community-db/sync"const apiFetch = vi.hoisted(() => vi.fn())@@ -381,7 +381,7 @@ describe("read coordinator", () => {}})- it("reconciles instead of restoring stale attention across an intervening WS fact", async () => {+ it("reconciles instead of restoring stale attention across an intervening canonical fact", async () => {const queryClient = new QueryClient()const registry = createCommunityDbRegistry(queryClient, "user-1")await registry.preload()@@ -410,17 +410,17 @@ describe("read coordinator", () => {const lease = timelineLease(queryClient)submitTimeline(lease, 4)await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)- projectAttentionUnreadBump(queryClient, {- type: "community:unread.bump",- userId: "user-1",- channelId: "channel-1",- serverId: "server-1",- isMention: false,- }, { seq: 5 })+ ingestMessages(registry, "other", [{ id: "event", type: "chat", content: "old" }])+ projectCommunityWsEventToDb(queryClient, {+ type: "community:message.edited",+ channelId: "other",+ messageId: "event",+ content: "new",+ })rejectPut(new ApiError("forbidden", 403))await vi.waitFor(() => expect(reconcileAccountAttention).toHaveBeenCalledWith(registry))- expect(registry.collections.attentionScopes.get("channel-1")?.lastUnreadSeq).toBe(5)+ expect(registry.collections.attentionScopes.get("channel-1")).toBeUndefined()} finally {disposeReadCoordinator(queryClient)unregister()@@ -617,19 +617,19 @@ describe("read coordinator", () => {const ticket = registerInboxProjectionTicket(queryClient, 1, target, vi.fn())activateInboxProjectionTicket(ticket)if (conflict) {- projectAttentionUnreadBump(queryClient, {- type: "community:unread.bump",- userId: "user-1",- channelId: "channel-1",- serverId: "server-1",- isMention: false,- }, { seq: 5 })+ ingestMessages(registry, "other", [{ id: "event", type: "chat", content: "old" }])+ projectCommunityWsEventToDb(queryClient, {+ type: "community:message.edited",+ channelId: "other",+ messageId: "event",+ content: "new",+ })}try {expect(cancelInboxProjectionTicket(ticket)).toBe(true)if (conflict) {- expect(registry.collections.attentionScopes.get("channel-1")?.lastUnreadSeq).toBe(5)+ expect(registry.collections.attentionScopes.get("channel-1")).toBeUndefined()expect(reconcileAccountAttention).toHaveBeenCalledWith(registry)} else {expect(registry.collections.attentionScopes.get("channel-1")?.lastUnreadSeq).toBe(4)diff --git a/src/web/src/hooks/community/use-account-attention.ts b/src/web/src/hooks/community/use-account-attention.tsindex a8d378623..707c3a34b 100644--- a/src/web/src/hooks/community/use-account-attention.ts+++ b/src/web/src/hooks/community/use-account-attention.ts@@ -10,7 +10,6 @@ import { communityKeys } from "@/lib/query-keys"import {useAttentionItems,useAttentionScopes,- useCanonicalChannelsById,} from "@/lib/community-db/projections"import {captureCommunityLiveSnapshotToken,@@ -20,8 +19,6 @@ import {getCommunityDbRegistry,type CommunityDbRegistry,} from "@/lib/community-db/collections"-import { useChannelRefDirectory } from "@/hooks/community/use-channel-ref-directory"-import { useDms } from "@/hooks/community/use-dms"class StaleAttentionReadError extends Error {constructor() {@@ -63,25 +60,6 @@ export function useAccountAttention() {return { ...query, scopes, items }}-/**- * Attention owns only stable structural refs. When those refs arrive before a- * cold route has loaded their canonical owners, enable the existing structural- * directory/DM queries. Their normal publishers hydrate the shared collections- * and every Inbox observer then recomposes without a second attention request.- */-export function useAccountAttentionScopeHydration() {- const scopes = useAttentionScopes()- const channelsById = useCanonicalChannelsById()- const needsServerChannels = scopes.some((scope) => (- Boolean(scope.serverId) && !channelsById.has(scope.channelId)- ))- const needsDms = scopes.some((scope) => (- !scope.serverId && !channelsById.has(scope.channelId)- ))- useChannelRefDirectory(needsServerChannels)- useDms(needsDms)-}-/*** Read-only observer for consumers. The shell owns the sole enabled transport;* every visible attention surface observes that query plus the canonical rows.diff --git a/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.test.ts b/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.test.tsindex c953e4a6a..654b3b177 100644--- a/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.test.ts+++ b/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.test.ts@@ -116,7 +116,7 @@ describe("community read-state lifecycle reconciliation", () => {releaseReadSurface(lease)})- it("schedules the first-auth owner before non-Inbox reconciliation completes", async () => {+ it("schedules the first-auth attention owner before read-state reconciliation completes", async () => {vi.useFakeTimers()await mountHook({ viewerUserId: "viewer-1" })useCommunityWsStore.getState().setPresence("viewer-1", "offline")@@ -124,19 +124,14 @@ describe("community read-state lifecycle reconciliation", () => {getCommunityApiFetchMock().mockReturnValueOnce(new Promise((resolve) => {releaseSnapshot = resolve}))- const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")const authentication = capturedUseUserWsOptions?.onAuthenticated?.()expect(getCommunityApiFetchMock()).toHaveBeenCalledOnce()expect(useCommunityWsStore.getState().presenceByUserId.get("viewer-1")).toBe("online")- await vi.advanceTimersByTimeAsync(500)- expect(invalidate).toHaveBeenCalledWith({- queryKey: communityKeys.inbox(),- })- expect(invalidate).toHaveBeenCalledWith({- queryKey: communityKeys.dms(),- })+ await vi.waitFor(() => expect(getCommunityApiFetchMock().mock.calls.filter(([path]) => (+ path === "/api/community/users/me/attention"+ ))).toHaveLength(1))releaseSnapshot({ revision: 0, readStates: [] })await authentication@@ -151,7 +146,6 @@ describe("community read-state lifecycle reconciliation", () => {vi.useFakeTimers()await mountHook()flushEffects()- const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")const listener = eventType === "visibilitychange"? documentListeners.get(eventType): windowListeners.get(eventType)@@ -160,28 +154,22 @@ describe("community read-state lifecycle reconciliation", () => {await vi.waitFor(() => expect(capturedQueryClient.getQueryData(communityKeys.accountReadStateSnapshot(),)).toEqual({ revision: 0, readStates: [] }))- expect(invalidate).not.toHaveBeenCalledWith({- queryKey: communityKeys.inbox(),- })- await vi.advanceTimersByTimeAsync(500)- expect(invalidate).toHaveBeenCalledWith({- queryKey: communityKeys.inbox(),- })+ await vi.waitFor(() => expect(getCommunityApiFetchMock().mock.calls.filter(([path]) => (+ path === "/api/community/users/me/attention"+ ))).toHaveLength(1))},)- it("contains a visible lifecycle reconciliation failure while the owner still refreshes", async () => {+ it("contains a visible lifecycle reconciliation failure while attention still reconciles", async () => {vi.useFakeTimers()await mountHook()flushEffects()getCommunityApiFetchMock().mockRejectedValueOnce(new Error("snapshot unavailable"))- const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")documentListeners.get("visibilitychange")!()await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledOnce())- await vi.advanceTimersByTimeAsync(500)-- expect(invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.inbox() })- expect(invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.dms() })+ await vi.waitFor(() => expect(getCommunityApiFetchMock().mock.calls.some(([path]) => (+ path === "/api/community/users/me/attention"+ ))).toBe(true))})})diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.tsindex b591f6fc4..30a057ab4 100644--- a/src/web/src/hooks/community/use-community-ws.ts+++ b/src/web/src/hooks/community/use-community-ws.ts@@ -18,6 +18,7 @@ import {dispatchCommunityWsEvents,} from "@/hooks/community/community-ws/registry"import { reconcileAccountReadState } from "@/hooks/community/community-ws/read-state-reconciliation"+import { scheduleAccountAttentionReconcile } from "@/hooks/community/use-account-attention"import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"import { runCommunityWsProjectionTransaction } from "@/hooks/community/community-ws/projection-transaction"import {@@ -510,9 +511,9 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {viewerUserId: viewerUserIdRef.current,})} finally {- scheduleInboxInvalidate({ inbox: true, dms: true })+ scheduleAccountAttentionReconcile(queryClient)}- }, [queryClient, scheduleInboxInvalidate])+ }, [queryClient])const handleAuthenticated = useCallback(async () => {const store = useCommunityWsStore.getState()store.markAccessConnected()@@ -523,10 +524,10 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {const firstAuthentication = !hasAuthenticatedRef.currenthasAuthenticatedRef.current = trueif (firstAuthentication) {- scheduleInboxInvalidate({ inbox: true, dms: true })+ scheduleAccountAttentionReconcile(queryClient)}await reconcileAccountReadState(queryClient, { surfaceMode: "non-inbox" })- }, [queryClient, scheduleInboxInvalidate])+ }, [queryClient])const { send, reconnectNow } = useUserWs(handleMessage, {onReconnect: handleReconnect,onDisconnect: useCommunityWsStore.getState().markAccessDisconnected,@@ -543,7 +544,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {const reconcileVisible = () => {if (document.visibilityState !== "visible") returnif (useCommunityWsStore.getState().accessConnected) {- scheduleInboxInvalidate({ inbox: true, dms: true })+ scheduleAccountAttentionReconcile(queryClient)}void reconcileAccountReadState(queryClient, {surfaceMode: "non-inbox",@@ -555,7 +556,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {document.removeEventListener("visibilitychange", reconcileVisible)window.removeEventListener("pageshow", reconcileVisible)}- }, [queryClient, scheduleInboxInvalidate])+ }, [queryClient])// Publish the send binding so free helpers (`communityWsSendTyping`) can// dispatch without holding a hook reference. Single-instance assumptiondiff --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.tsindex 29f179987..8a0c43b4d 100644--- 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.ts@@ -14,6 +14,16 @@ const rows: Row[] = [{ id: "b", name: "B" },]+function attentionFriendRequests(friendRequests: Array<{ id: string; userId?: string }>) {+ return {+ items: friendRequests.map((row) => ({+ kind: "friend_request",+ sourceId: row.id,+ actorUserId: row.userId ?? null,+ })),+ }+}+function createQueryWrapper() {const queryClient = new QueryClient()return function QueryWrapper({ children }: PropsWithChildren) {@@ -22,6 +32,43 @@ function createQueryWrapper() {}describe("useFriendRequestActionState", () => {+ it("filters non-request and source-less attention items before action projection", () => {+ const queryClient = new QueryClient()+ queryClient.setQueryData(communityKeys.accountAttention(), {+ items: [{+ kind: "mention",+ sourceId: "not-a-request",+ actorUserId: "actor",+ }, {+ kind: "friend_request",+ sourceId: "",+ actorUserId: "actor",+ }],+ })+ const controller = getFriendRequestActionController(queryClient)++ controller.claimMutation("not-a-request", "accept")++ expect(controller.project("inbox", [])).toEqual([])+ })++ it("keeps an actor-less attention request keyed by its request id", () => {+ const queryClient = new QueryClient()+ queryClient.setQueryData(+ communityKeys.accountAttention(),+ attentionFriendRequests([{ id: "actor-less" }]),+ )+ const controller = getFriendRequestActionController(queryClient)++ controller.claimMutation("actor-less", "accept")++ expect(controller.project("inbox", [])).toEqual([{+ row: { id: "actor-less", userId: undefined },+ action: "accept",+ status: "pending",+ }])+ })+it("keeps an optimistically removed row visible and locks only that id", async () => {let resolve!: () => voidconst onAccept = vi.fn(() => new Promise<void>((next) => { resolve = next }))@@ -113,9 +160,10 @@ describe("useFriendRequestActionState", () => {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],- })+ queryClient.setQueryData(+ communityKeys.accountAttention(),+ attentionFriendRequests([cached, alreadyTerminal]),+ )const controller = getFriendRequestActionController(queryClient)controller.claimMutation(snapshot.id, "accept")controller.publishTerminal(alreadyTerminal.id)@@ -126,7 +174,10 @@ describe("useFriendRequestActionState", () => {expect(controller.project("inbox", [cached, alreadyTerminal])).toEqual([])const late = { id: "late", userId: "u1" }- queryClient.setQueryData(communityKeys.inboxUnreads(), { friendRequests: [late] })+ queryClient.setQueryData(+ communityKeys.accountAttention(),+ attentionFriendRequests([late]),+ )controller.claimMutation(late.id, "reject")expect(controller.project("inbox", [])).toEqual([])const mutation = vi.fn()@@ -145,7 +196,7 @@ describe("useFriendRequestActionState", () => {const queryClient = new QueryClient()const row = { id: "a", userId: "u1" }queryClient.setQueryData(communityKeys.friends(), { pending: [row] })- queryClient.setQueryData(communityKeys.inboxUnreads(), { friendRequests: [row] })+ queryClient.setQueryData(communityKeys.accountAttention(), attentionFriendRequests([row]))const controller = getFriendRequestActionController(queryClient)const generation = controller.claimMutation(row.id, "accept")await controller.publishTerminalAndFence(row.id, generation)@@ -158,8 +209,8 @@ describe("useFriendRequestActionState", () => {friendRows = []await queryClient.refetchQueries({ queryKey: communityKeys.friends(), exact: true })await queryClient.fetchQuery({- queryKey: communityKeys.inboxUnreads(),- queryFn: async () => ({ friendRequests: [] }),+ queryKey: communityKeys.accountAttention(),+ queryFn: async () => attentionFriendRequests([]),})queryClient.setQueryData(communityKeys.friends(), { pending: [row] })@@ -167,11 +218,11 @@ describe("useFriendRequestActionState", () => {expect(controller.project("friends", [row])).toEqual([])queryClient.setQueryData(communityKeys.friends(), { pending: [] })- queryClient.setQueryData(communityKeys.inboxUnreads(), { friendRequests: [row] })+ queryClient.setQueryData(communityKeys.accountAttention(), attentionFriendRequests([row]))controller.settleGeneration(row.id, generation)expect(controller.project("friends", [row])).toEqual([])- queryClient.setQueryData(communityKeys.inboxUnreads(), { friendRequests: [] })+ queryClient.setQueryData(communityKeys.accountAttention(), attentionFriendRequests([]))controller.settleGeneration(row.id, generation)expect(controller.project("friends", [row])).toEqual([{ row }])})@@ -183,24 +234,24 @@ describe("useFriendRequestActionState", () => {controller.publishTerminalForUser("ghost")await queryClient.fetchQuery({- queryKey: communityKeys.inboxUnreads(),- queryFn: async () => ({ friendRequests: [] }),+ queryKey: communityKeys.accountAttention(),+ queryFn: async () => attentionFriendRequests([]),})const row = { id: "late", userId: "ghost" }- queryClient.setQueryData(communityKeys.inboxUnreads(), { friendRequests: [row] })+ queryClient.setQueryData(communityKeys.accountAttention(), attentionFriendRequests([row]))await queryClient.fetchQuery({queryKey: communityKeys.friends(),queryFn: async () => ({ pending: [] }),})expect(controller.project("friends", [row])).toEqual([])- queryClient.setQueryData(communityKeys.inboxUnreads(), { friendRequests: [] })+ queryClient.setQueryData(communityKeys.accountAttention(), attentionFriendRequests([]))queryClient.setQueryData(communityKeys.friends(), { pending: [row] })- await queryClient.refetchQueries({ queryKey: communityKeys.inboxUnreads(), exact: true })+ await queryClient.refetchQueries({ queryKey: communityKeys.accountAttention(), exact: true })expect(controller.project("friends", [row])).toEqual([])queryClient.setQueryData(communityKeys.friends(), { pending: [] })- await queryClient.refetchQueries({ queryKey: communityKeys.inboxUnreads(), exact: true })+ await queryClient.refetchQueries({ queryKey: communityKeys.accountAttention(), 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.tsindex 212450471..968f40f47 100644--- a/src/web/src/hooks/community/use-friend-request-action-state.ts+++ b/src/web/src/hooks/community/use-friend-request-action-state.ts@@ -51,8 +51,12 @@ type FriendsEnvelope = {pending?: readonly FriendRequestRow[]}-type InboxEnvelope = {- friendRequests?: readonly FriendRequestRow[]+type AttentionEnvelope = {+ items?: readonly {+ kind?: string+ sourceId?: string+ actorUserId?: string | null+ }[]}export type ActionableFriendRequest<T> = {@@ -64,7 +68,7 @@ export type ActionableFriendRequest<T> = {const controllers = new WeakMap<QueryClient, FriendRequestActionController>()const friendsHash = hashKey(communityKeys.friends())-const inboxHash = hashKey(communityKeys.inboxUnreads())+const inboxHash = hashKey(communityKeys.accountAttention())function captureRow<T extends FriendRequestRow>(rows: readonly T[],@@ -82,7 +86,11 @@ function rowsFromEnvelope(if (surface === "friends") {return (data as FriendsEnvelope).pending ?? []}- return (data as InboxEnvelope).friendRequests ?? []+ return ((data as AttentionEnvelope).items ?? []).flatMap((item) => (+ item.kind === "friend_request" && item.sourceId+ ? [{ id: item.sourceId, userId: item.actorUserId ?? undefined }]+ : []+ ))}function surfaceForHash(queryHash: string): FriendRequestSurface | undefined {@@ -118,10 +126,10 @@ class FriendRequestActionController {private captureCaches(id: string) {const friends = this.queryClient.getQueryData<FriendsEnvelope>(communityKeys.friends())- const inbox = this.queryClient.getQueryData<InboxEnvelope>(communityKeys.inboxUnreads())+ const inbox = this.queryClient.getQueryData<AttentionEnvelope>(communityKeys.accountAttention())return {friends: captureRow(friends?.pending ?? [], id),- inbox: captureRow(inbox?.friendRequests ?? [], id),+ inbox: captureRow(rowsFromEnvelope("inbox", inbox), id),}}@@ -213,7 +221,7 @@ class FriendRequestActionController {async fenceReads() {await Promise.all([this.queryClient.cancelQueries({ queryKey: communityKeys.friends(), exact: true }),- this.queryClient.cancelQueries({ queryKey: communityKeys.inboxUnreads(), exact: true }),+ this.queryClient.cancelQueries({ queryKey: communityKeys.accountAttention(), exact: true }),])}@@ -234,10 +242,10 @@ class FriendRequestActionController {private captureRowsBySurface() {const friends = this.queryClient.getQueryData<FriendsEnvelope>(communityKeys.friends())- const inbox = this.queryClient.getQueryData<InboxEnvelope>(communityKeys.inboxUnreads())+ const inbox = this.queryClient.getQueryData<AttentionEnvelope>(communityKeys.accountAttention())return {friends: friends?.pending ?? [],- inbox: inbox?.friendRequests ?? [],+ inbox: rowsFromEnvelope("inbox", inbox),}}diff --git a/src/web/src/hooks/community/use-inbox.dom.test.ts b/src/web/src/hooks/community/use-inbox.dom.test.tsindex 495b991c3..e03121177 100644--- a/src/web/src/hooks/community/use-inbox.dom.test.ts+++ b/src/web/src/hooks/community/use-inbox.dom.test.ts@@ -1,9 +1,9 @@-import React from "react"-import { act, render as rtlRender } from "@/test/react-dom-harness"-import { describe, it, expect, vi, beforeEach } from "vitest"+import React, { useLayoutEffect } from "react"import { QueryClient, QueryClientProvider } from "@tanstack/react-query"-import { communityKeys } from "@/lib/query-keys"-import { useCommunityWsStore } from "@/stores/community/ws"+import type { AccountAttentionSnapshot } from "@alook/shared"+import type { CommunityProfile } from "@/lib/community/models/people"+import { act, render, renderHook, waitFor } from "@/test/react-dom-harness"+import { beforeEach, describe, expect, it, vi } from "vitest"import {CommunityDbProvider,} from "@/lib/community-db/projections"@@ -12,1471 +12,703 @@ import {registerCommunityDbRegistry,} from "@/lib/community-db/collections"import {- getCanonicalCommunityMessages,- ingestServers,- purgeCommunityServer,+ clearAttentionScopeOptimistically,+ ingestAttentionSnapshot,} from "@/lib/community-db/sync"-import { getAccountUnreadProjection } from "./account-unread-projection"-import {- disposeInboxReadReservation,- inboxChannelRowTarget,- registerInboxReadReservationSurface,- takeInboxReadReservationNegative,-} from "./inbox-read-reservation"+import { useCommunityWsStore } from "@/stores/community/ws"+import { CommunityPreviewProfileOwner } from "@/stores/community/profile-preview"+import { communityKeys } from "@/lib/query-keys"+import { useAccountAttention } from "./use-account-attention"+import { useInboxAttention, useInboxMarked, useMessageMarked } from "./use-inbox"const apiFetchMock = vi.fn()vi.mock("@/lib/api/client", () => ({apiFetch: (...args: unknown[]) => apiFetchMock(...args),}))-beforeEach(() => {- apiFetchMock.mockReset()-})--function deferred<T>() {- let resolve!: (value: T) => void- let reject!: (reason?: unknown) => void- const promise = new Promise<T>((resolvePromise, rejectPromise) => {- resolve = resolvePromise- reject = rejectPromise+function forumSnapshot(): AccountAttentionSnapshot {+ const channel = (+ id: string,+ name: string,+ type: "forum" | "thread",+ parentChannelId: string | null,+ parentMessageId: string | null,+ openerSeq?: number,+ ) => ({+ id,+ serverId: "server",+ name,+ type,+ parentChannelId,+ parentMessageId,+ creatorId: null,+ archived: false,+ lastMessageAt: `2026-09-28T00:00:${openerSeq ?? 30}.000Z`,+ ...(openerSeq === undefined ? {} : { openerSeq, openerUnread: true }),})- return { promise, resolve, reject }+ return {+ scopes: [{+ scopeId: "forum",+ channelId: "forum",+ serverId: "server",+ parentChannelId: null,+ ordinaryUnread: true,+ lastUnreadSeq: 20,+ lastAttentionSeq: null,+ attentionCount: 0,+ }],+ items: [10, 20].map((seq) => ({+ id: `forum_post:child-${seq}`,+ kind: "forum_post" as const,+ sourceId: `child-${seq}`,+ scopeId: "forum",+ messageId: `opener-${seq}`,+ actorUserId: null,+ childChannelId: `child-${seq}`,+ openerSeq: seq,+ readTarget: { channelId: "forum", seq },+ createdAt: `2026-09-28T00:00:${seq}.000Z`,+ })),+ limit: 100,+ truncated: false,+ included: {+ servers: [{ id: "server", name: "Server", discriminator: "0001" }],+ channels: [+ channel("forum", "Forum", "forum", null, null),+ channel("child-10", "Derived A", "thread", "forum", "opener-10", 10),+ channel("child-20", "Derived B", "thread", "forum", "opener-20", 20),+ ],+ dms: [],+ profiles: [],+ messages: [10, 20].map((seq) => ({+ id: `opener-${seq}`,+ channelId: "forum",+ type: "chat" as const,+ seq,+ createdAt: `2026-09-28T00:00:${seq}.000Z`,+ content: `Post ${seq}`,+ })),+ },+ }}-async function mountRailOnlyInbox() {- const message = {- id: "message-rail-only",- seq: 1,- type: "chat" as const,- authorId: "author",- authorName: "Author",- content: "visible before detail loads",- createdAt: "2026-09-25T00:00:00.000Z",- attachments: [{- kind: "file" as const,- name: "evidence.txt",- url: "/evidence.txt",- size: "1 KB",+function truncatedAttentionOnlySnapshot(): AccountAttentionSnapshot {+ return {+ scopes: [{+ scopeId: "channel",+ channelId: "channel",+ serverId: "server",+ parentChannelId: null,+ ordinaryUnread: false,+ lastUnreadSeq: 30,+ lastAttentionSeq: 30,+ attentionCount: 3,}],+ items: [],+ limit: 1,+ truncated: true,+ included: {+ servers: [{ id: "server", name: "Server", discriminator: "0001" }],+ channels: [{+ id: "channel",+ serverId: "server",+ name: "Attention only",+ type: "text",+ parentChannelId: null,+ parentMessageId: null,+ creatorId: null,+ archived: false,+ lastMessageAt: "2026-09-28T00:00:30.000Z",+ }],+ dms: [],+ profiles: [],+ messages: [],+ },}- const server = {- serverId: "server-rail-only",- serverName: "Rail only",- channels: [{- channelId: "channel-detail-pending",- channelName: "Detail pending",- lastMessageAt: "2026-09-25T00:00:00.000Z",- lastUnreadSeq: 1,- mentionCount: 1,- children: [],+}++function truncatedAttentionWithBoundedItemSnapshot(): AccountAttentionSnapshot {+ const snapshot = truncatedAttentionOnlySnapshot()+ return {+ ...snapshot,+ items: [{+ id: "mention:mention",+ kind: "mention",+ sourceId: "mention",+ scopeId: "channel",+ messageId: "message",+ actorUserId: "author",+ createdAt: "2026-09-28T00:00:30.000Z",}],+ included: {+ ...snapshot.included,+ profiles: [{+ userId: "author",+ name: "Author",+ discriminator: "0002",+ avatar: "",+ avatarVersion: 0,+ }],+ messages: [{+ id: "message",+ channelId: "channel",+ type: "chat",+ authorId: "author",+ authorName: "Author",+ seq: 30,+ createdAt: "2026-09-28T00:00:30.000Z",+ content: "hello",+ }],+ },}- const mention = {- id: "mention-rail-only",- server: "Rail only",- serverId: server.serverId,- channel: "Detail pending",- channelId: server.channels[0].channelId,- m: message,- }- const marked = {- id: "marked-rail-only",- server: "Rail only",- serverId: server.serverId,- channel: "Detail pending",- channelId: server.channels[0].channelId,- m: message,+}++function emptyAttentionScopeSnapshot(): AccountAttentionSnapshot {+ const snapshot = truncatedAttentionOnlySnapshot()+ return {+ ...snapshot,+ scopes: [{+ ...snapshot.scopes[0]!,+ lastUnreadSeq: 0,+ lastAttentionSeq: null,+ attentionCount: 0,+ }],+ limit: 100,+ truncated: false,}- const unreadsData = { friendRequests: [], servers: [server], dms: [], truncated: false }- const mentionsData = { mentions: [mention], truncated: false }- const markedData = { marked: [marked] }- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })- getAccountUnreadProjection(queryClient, "viewer").setNotificationPolicy({})- const registry = createCommunityDbRegistry(queryClient, "viewer")- await registry.preload()- useCommunityWsStore.getState().reset()- useCommunityWsStore.getState().activateProfileAccount("viewer")- ingestServers(registry, {- servers: [{- id: "server-canonical-match",- name: "Canonical match",- initial: "C",- active: false,- unread: false,- mentions: 0,- ownerId: "owner",+}++function dmSnapshot({ mention = false }: { mention?: boolean } = {}): AccountAttentionSnapshot {+ return {+ scopes: [{+ scopeId: "dm",+ channelId: "dm",+ serverId: null,+ parentChannelId: null,+ ordinaryUnread: !mention,+ lastUnreadSeq: 9,+ lastAttentionSeq: mention ? 9 : null,+ attentionCount: mention ? 1 : 0,}],- })- queryClient.setQueryData(communityKeys.servers(), {- servers: [{- id: server.serverId,- name: server.serverName,- initial: "R",- active: false,- unread: true,- mentions: 1,- ownerId: "owner",- unreadSources: [{- channelId: server.channels[0].channelId,- lastUnreadSeq: 1,+ items: mention ? [{+ id: "mention:dm-mention",+ kind: "mention",+ sourceId: "dm-mention",+ scopeId: "dm",+ messageId: "dm-message",+ actorUserId: "peer",+ createdAt: "2026-09-28T00:00:09.000Z",+ }] : [],+ limit: 100,+ truncated: false,+ included: {+ servers: [],+ channels: [],+ dms: [{+ id: "dm",+ userId: "peer",+ name: "Peer",+ discriminator: "0002",+ avatar: "P",+ avatarVersion: 2,+ lastMessageAt: "2026-09-28T00:00:09.000Z",+ lastUnreadSeq: 9,}],- mentionSources: [{- channelId: server.channels[0].channelId,- count: 1,- lastSeq: 1,+ profiles: [{+ userId: "peer",+ name: "Peer",+ discriminator: "0002",+ avatar: "P",+ avatarVersion: 2,}],- }, {- id: "server-canonical-match",- name: "Canonical match raw",- initial: "C",- active: false,- unread: true,- mentions: 0,- ownerId: "owner",- unreadSources: [{- channelId: "channel-canonical-match",- lastUnreadSeq: 2,+ messages: mention ? [{+ id: "dm-message",+ channelId: "dm",+ type: "chat",+ authorId: "peer",+ authorName: "Peer",+ seq: 9,+ createdAt: "2026-09-28T00:00:09.000Z",+ content: "hello",+ }] : [],+ },+ }+}++function childThreadSnapshot(): AccountAttentionSnapshot {+ return {+ scopes: [{+ scopeId: "child",+ channelId: "child",+ serverId: "server",+ parentChannelId: "parent",+ ordinaryUnread: true,+ lastUnreadSeq: 7,+ lastAttentionSeq: null,+ attentionCount: 0,+ }],+ items: [],+ limit: 100,+ truncated: false,+ included: {+ servers: [{ id: "server", name: "Server", discriminator: "0001" }],+ channels: [{+ id: "parent",+ serverId: "server",+ name: "Parent",+ type: "text",+ parentChannelId: null,+ parentMessageId: null,+ creatorId: null,+ archived: false,+ lastMessageAt: "2026-09-28T00:00:06.000Z",+ }, {+ id: "child",+ serverId: "server",+ name: "Child",+ type: "thread",+ parentChannelId: "parent",+ parentMessageId: "opener",+ creatorId: null,+ archived: false,+ lastMessageAt: "2026-09-28T00:00:07.000Z",+ openerSeq: 7,+ openerUnread: false,}],+ dms: [],+ profiles: [],+ messages: [{+ id: "opener",+ channelId: "parent",+ type: "chat",+ seq: 7,+ createdAt: "2026-09-28T00:00:07.000Z",+ content: "Child",+ }],+ },+ }+}++function friendRequestSnapshot(): AccountAttentionSnapshot {+ return {+ scopes: [],+ items: [{+ id: "friend_request:request",+ kind: "friend_request",+ sourceId: "request",+ scopeId: null,+ messageId: null,+ actorUserId: "requester",+ createdAt: "2026-09-28T00:00:05.000Z",}],- })- queryClient.setQueryData(communityKeys.inboxUnreads(), unreadsData)- queryClient.setQueryData(communityKeys.inboxMentions(), mentionsData)- queryClient.setQueryData(communityKeys.inboxMarked(), markedData)- queryClient.setQueryData(communityKeys.pins(server.channels[0].channelId), {- pins: [message],- })- apiFetchMock.mockReturnValue(new Promise(() => undefined))- const { useInboxMarked, useInboxMentions, useInboxUnreads } = await import("./use-inbox")- const { usePins } = await import("./use-channel-panels")- const { useServers } = await import("./use-servers")- let snapshot = {- unreadIds: [] as string[],- mentionIds: [] as string[],- markedIds: [] as string[],- pinIds: [] as string[],- attachmentNames: [] as string[],- railUnreadIds: [] as string[],+ limit: 100,+ truncated: false,+ included: {+ servers: [],+ channels: [],+ dms: [],+ profiles: [{+ userId: "requester",+ name: "Requester",+ discriminator: "0004",+ avatar: "R",+ avatarVersion: 4,+ }],+ messages: [],+ },}- function Harness() {- const unreads = useInboxUnreads()- const mentions = useInboxMentions()- const marks = useInboxMarked(false)- const pins = usePins(server.channels[0].channelId)- const rail = useServers()- snapshot = {- unreadIds: unreads.servers.flatMap((entry) => entry.channels.map((channel) => channel.channelId)),- mentionIds: mentions.mentions.map((entry) => entry.m.id),- markedIds: marks.marked.map((entry) => entry.m.id),- pinIds: pins.pins.map((entry) => entry.id),- attachmentNames: [- ...marks.marked.flatMap((entry) => entry.m.attachments?.map((file) => file.name) ?? []),- ...pins.pins.flatMap((entry) => entry.attachments?.map((file) => file.name) ?? []),- ],- railUnreadIds: rail.servers.filter((entry) => entry.unread).map((entry) => entry.id),- }+}++async function createHarness({+ owner = false,+ previewProfiles,+}: {+ owner?: boolean+ previewProfiles?: ReadonlyMap<string, CommunityProfile>+} = {}) {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ const registry = createCommunityDbRegistry(queryClient, "viewer")+ await registry.preload()+ const unregister = registerCommunityDbRegistry(registry)+ useCommunityWsStore.getState().reset()+ useCommunityWsStore.getState().activateProfileAccount("viewer")+ let latest: ReturnType<typeof useInboxAttention> | undefined+ const paints: Array<{ count: number; children: string[] }> = []+ function Probe() {+ const attention = useInboxAttention()+ latest = attention+ useLayoutEffect(() => {+ paints.push({+ count: attention.exactAttentionCount,+ children: attention.servers.flatMap((server) => (+ server.channels.flatMap((channel) => channel.children.map((child) => child.channelId))+ )),+ })+ })return null}- let renderer!: ReturnType<typeof rtlRender>- await act(async () => {- renderer = rtlRender(React.createElement(+ function OwnerProbe() {+ useAccountAttention()+ return React.createElement(Probe)+ }+ const probe = React.createElement(owner ? OwnerProbe : Probe)+ const rendered = render(+ React.createElement(QueryClientProvider,{ client: queryClient },React.createElement(CommunityDbProvider,{ registry },- React.createElement(Harness),+ previewProfiles+ ? React.createElement(CommunityPreviewProfileOwner, { profiles: previewProfiles }, probe)+ : probe,),- ))- })+ ),+ )return {- get snapshot() { return snapshot },queryClient,registry,- unreadsData,- mentionsData,- markedData,- dispose: async () => {- await act(async () => renderer.unmount())- registry["cleanup"]()+ paints,+ rendered,+ get latest() {+ if (!latest) throw new Error("attention hook did not mount")+ return latest+ },+ dispose() {+ rendered.unmount()+ unregister()},}}-describe("useInboxUnreads / inboxUnreadsQueryFn", () => {- it("does not render raw message entities while the canonical store is empty", async () => {- const mounted = await mountRailOnlyInbox()-- expect([...mounted.registry.collections.channels.keys()]).toEqual([])- expect([...mounted.registry.collections.messages.keys()]).toEqual([])- expect(mounted.snapshot).toEqual({- unreadIds: [],- mentionIds: [],- markedIds: [],- pinIds: [],- attachmentNames: [],- railUnreadIds: [],- })- await mounted.dispose()- })-- it("keeps late Inbox rows hidden after an authoritative server purge", async () => {- const mounted = await mountRailOnlyInbox()- expect(mounted.snapshot.unreadIds).toEqual([])-- await act(async () => {- purgeCommunityServer(mounted.registry, "server-rail-only")- mounted.queryClient.setQueryData(communityKeys.inboxUnreads(), mounted.unreadsData)- mounted.queryClient.setQueryData(communityKeys.inboxMentions(), mounted.mentionsData)- mounted.queryClient.setQueryData(communityKeys.inboxMarked(), mounted.markedData)- })-- expect({- unreadIds: mounted.snapshot.unreadIds,- mentionIds: mounted.snapshot.mentionIds,- markedIds: mounted.snapshot.markedIds,- railUnreadIds: mounted.snapshot.railUnreadIds,- }).toEqual({- unreadIds: [],- mentionIds: [],- markedIds: [],- railUnreadIds: [],- })- await mounted.dispose()- })-- it("does not project legacy Inbox child rows without canonical attention", async () => {- const data = {- friendRequests: [],- servers: [{- serverId: "s1",- serverName: "One",- channels: [{- channelId: "parent",- channelName: "Parent",- lastMessageAt: "2026-09-25T00:00:00.000Z",- lastUnreadSeq: 1,- mentionCount: 0,- hasDirectUnread: true,- children: [{- channelId: "child",- channelName: "Child",- lastMessageAt: "2026-09-25T00:00:01.000Z",- lastUnreadSeq: 2,- mentionCount: 0,- }],- }],- }],- dms: [],- truncated: false,- }- apiFetchMock.mockReturnValue(new Promise(() => undefined))- const { useInboxUnreads } = await import("./use-inbox")- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })- queryClient.setQueryData(communityKeys.inboxUnreads(), data)- const projection = getAccountUnreadProjection(queryClient, "viewer")- projection.setNotificationPolicy({})- let latest: ReturnType<typeof useInboxUnreads> | undefined- function Harness() {- latest = useInboxUnreads()- return null- }- let renderer!: ReturnType<typeof rtlRender>- await act(async () => {- renderer = rtlRender(React.createElement(- QueryClientProvider,- { client: queryClient },- React.createElement(Harness),- ))- })- expect(latest?.servers).toEqual([])-- act(() => projection.retireAccessScope({ kind: "channel", channelId: "child" }))-- expect(latest?.servers).toEqual([])- await act(async () => renderer.unmount())- })-- it("uses the canonical DB rail when the raw servers query is absent", async () => {- apiFetchMock.mockReturnValue(new Promise(() => undefined))- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })- const projection = getAccountUnreadProjection(queryClient, "viewer")- projection.setNotificationPolicy({})- const registry = createCommunityDbRegistry(queryClient, "viewer")- await registry.preload()- ingestServers(registry, {- servers: [{- id: "db-only",- name: "DB only",- initial: "D",- active: false,- unread: false,- mentions: 0,- ownerId: "owner",- }],- })- const { useServers } = await import("./use-servers")- let serverIds: string[] = []- function Harness() {- serverIds = useServers().servers.map((server) => server.id)- return null- }- let renderer!: ReturnType<typeof rtlRender>- await act(async () => {- renderer = rtlRender(React.createElement(- QueryClientProvider,- { client: queryClient },- React.createElement(- CommunityDbProvider,- { registry },- React.createElement(Harness),- ),- ))- })- await vi.waitFor(() => expect(serverIds).toEqual(["db-only"]))-- act(() => projection.retireAccessScope({ kind: "server", serverId: "db-only" }))-- expect(serverIds).toEqual([])- await act(async () => renderer.unmount())- await registry["cleanup"]()- })+beforeEach(() => {+ apiFetchMock.mockReset()+})- it("does not project friend requests from the retired Inbox endpoint", 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+describe("useInboxAttention", () => {+ it("rejects stale marked and message-mark responses instead of publishing empty success", async () => {+ const wrapperFor = (queryClient: QueryClient) => function Wrapper({+ children,+ }: React.PropsWithChildren) {+ return React.createElement(QueryClientProvider, { client: queryClient }, children)}- const renderer = rtlRender(React.createElement(- QueryClientProvider,- { client: qc },- React.createElement(Harness),- ))-- expect(latest?.friendRequests).toEqual([])- expect(latest?.hasOutstandingFriendRequest).toBe(false)- 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,+ apiFetchMock.mockResolvedValueOnce({ marked: [], stale: true })+ const marked = renderHook(() => useInboxMarked(true), {+ wrapper: wrapperFor(new QueryClient({ defaultOptions: { queries: { retry: false } } })),})- const { inboxUnreadsQueryFn } = await import("./use-inbox")-- await inboxUnreadsQueryFn()-- })-- it("ignores last-good friend requests from the retired Inbox endpoint", 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),- ))- expect(latest?.friendRequests).toEqual([])- await qc.invalidateQueries({ queryKey: communityKeys.inboxUnreads(), exact: true })-- expect(latest?.friendRequests).toEqual([])- expect(latest?.hasOutstandingFriendRequest).toBe(false)- 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")-- await expect(inboxUnreadsQueryFn()).resolves.toEqual({ servers: [], dms: [] })- expect(apiFetchMock).toHaveBeenCalledWith(- "/api/community/users/me/inbox/unreads",- { signal: undefined },- )- })-- it("fetches /inbox/unreads and populates queryClient at communityKeys.inboxUnreads()", async () => {- apiFetchMock.mockResolvedValueOnce({ servers: [], dms: [] })- const { inboxUnreadsQueryFn } = await import("./use-inbox")- const qc = new QueryClient()- const key = communityKeys.inboxUnreads()- await qc.fetchQuery({ queryKey: key, queryFn: inboxUnreadsQueryFn })- expect(apiFetchMock).toHaveBeenCalledWith(- "/api/community/users/me/inbox/unreads",- { signal: expect.any(AbortSignal) },- )- expect(qc.getQueryData(key)).toEqual({ servers: [], dms: [] })- })-- it("aborts an in-flight unread read when the exact query is cancelled", async () => {- let signal: AbortSignal | undefined- apiFetchMock.mockImplementationOnce((_url: string, init: RequestInit) => new Promise((_resolve, reject) => {- signal = init.signal as AbortSignal- signal.addEventListener("abort", () => reject(new Error("aborted")))+ await waitFor(() => expect(marked.result.current.error).toMatchObject({+ name: "StaleReadError",}))- const { inboxUnreadsQueryFn } = await import("./use-inbox")- const qc = new QueryClient()- const key = communityKeys.inboxUnreads()- const pending = qc.fetchQuery({ queryKey: key, queryFn: inboxUnreadsQueryFn }).catch(() => undefined)- await vi.waitFor(() => expect(signal).toBeDefined())- await qc.cancelQueries({ queryKey: key, exact: true })- expect(signal?.aborted).toBe(true)- await pending- })-- it("starts canonical Inbox snapshot fences before transport", async () => {- let resolve!: (value: { servers: []; dms: []; truncated: false }) => void- apiFetchMock.mockReturnValueOnce(new Promise((next) => { resolve = next }))- const {- inboxUnreadsProjectedQueryFn,- } = await import("./use-inbox")- const { AccountUnreadProjection } = await import("./account-unread-projection")- const projection = new AccountUnreadProjection("u1")- projection.setNotificationPolicy({})- const qc = new QueryClient()-- const pending = inboxUnreadsProjectedQueryFn(qc, projection)()- projection.recordArrival({ channelId: "later", serverId: "s1", seq: 2 })- resolve({ servers: [], dms: [], truncated: false })- await pending-- expect(projection.projectUnread("inbox-unreads", "later", false)).toBe(true)- })-- it("releases both canonical snapshot fences when transport fails", async () => {- apiFetchMock.mockRejectedValueOnce(new Error("offline"))- const { inboxUnreadsProjectedQueryFn } = await import("./use-inbox")- const { AccountUnreadProjection } = await import("./account-unread-projection")- const projection = new AccountUnreadProjection("u1")-- await expect(inboxUnreadsProjectedQueryFn(new QueryClient(), projection)())- .rejects.toThrow("offline")- expect(projection.inspectForTests().pendingSnapshots).toBe(0)- })+ expect(marked.result.current.data).toBeUndefined()+ marked.unmount()- it("lets a complete empty Inbox response retire pre-request channel and DM sources", async () => {- apiFetchMock.mockResolvedValueOnce({ servers: [], dms: [], truncated: false })- const { inboxUnreadsProjectedQueryFn } = await import("./use-inbox")- const { AccountUnreadProjection } = await import("./account-unread-projection")- const projection = new AccountUnreadProjection("u1")- projection.setNotificationPolicy({})- projection.recordArrival({ channelId: "channel", serverId: "s1", seq: 1 })- projection.recordArrival({ channelId: "dm", seq: 1 })-- await inboxUnreadsProjectedQueryFn(new QueryClient(), projection)()-- expect(projection.projectUnread("inbox-unreads", "channel", false, 1, "channels")).toBe(false)- expect(projection.projectUnread("inbox-unreads", "dm", false, 1, "dms")).toBe(false)- })-- it("retires a complete empty DM domain when the server domain is truncated", async () => {- apiFetchMock.mockResolvedValueOnce({ servers: [], dms: [], truncated: true })- const { inboxUnreadsProjectedQueryFn } = await import("./use-inbox")- const { AccountUnreadProjection } = await import("./account-unread-projection")- const projection = new AccountUnreadProjection("u1")- projection.setNotificationPolicy({})- projection.recordArrival({ channelId: "channel", serverId: "s1" })- projection.recordArrival({ channelId: "dm" })-- await inboxUnreadsProjectedQueryFn(new QueryClient(), projection)()-- expect(projection.projectUnread("inbox-unreads", "channel", false, null, "channels"))- .toBe(true)- expect(projection.projectUnread("inbox-unreads", "dm", false, null, "dms"))- .toBe(false)- })-- it("preserves cold attention facets under mentions-only policy", async () => {- apiFetchMock.mockResolvedValueOnce({- servers: [{- serverId: "s1",- serverName: "One",- channels: [- {- channelId: "attention",- channelName: "Attention",- lastMessageAt: "2026-09-04T00:00:00.000Z",- lastUnreadSeq: 2,- lastAttentionSeq: 2,- mentionCount: 1,- children: [],- },- {- channelId: "ordinary",- channelName: "Ordinary",- lastMessageAt: "2026-09-04T00:00:00.000Z",- lastUnreadSeq: 3,- mentionCount: 0,- children: [],- },- ],- }],- dms: [],- truncated: false,- })- const { inboxUnreadsProjectedQueryFn } = await import("./use-inbox")- const { AccountUnreadProjection } = await import("./account-unread-projection")- const projection = new AccountUnreadProjection("u1")- projection.setNotificationPolicy({ server: { s1: "mentions" } })-- await inboxUnreadsProjectedQueryFn(new QueryClient(), projection)()-- expect(projection.projectUnread("inbox-unreads", "attention", false)).toBe(true)- expect(projection.projectUnread("inbox-unreads", "ordinary", false)).toBe(false)- })-- it("does not treat a later ordinary unread as the older mention facet", async () => {- apiFetchMock.mockResolvedValueOnce({- servers: [{- serverId: "s1",- serverName: "One",- channels: [{- channelId: "mixed",- channelName: "Mixed",- lastMessageAt: "2026-09-04T00:00:00.000Z",- lastUnreadSeq: 10,- lastAttentionSeq: 5,- mentionCount: 1,- children: [],- }],- }],- dms: [],- truncated: false,- })- const { inboxUnreadsProjectedQueryFn } = await import("./use-inbox")- const { AccountUnreadProjection } = await import("./account-unread-projection")- const projection = new AccountUnreadProjection("u1")- projection.setNotificationPolicy({ server: { s1: "mentions" } })-- await inboxUnreadsProjectedQueryFn(new QueryClient(), projection)()- expect(projection.projectUnread("inbox-unreads", "mixed", false)).toBe(true)-- projection.recordRead("mixed", 5)- expect(projection.projectUnread("inbox-unreads", "mixed", false)).toBe(false)- })-- it.each([- ["nothing", false],- ["mentions", true],- ["all", true],- ] as const)("applies cold parent %s policy through the Mentions adapter", async (- parentLevel,- expected,- ) => {- apiFetchMock.mockResolvedValueOnce({- mentions: [{- id: "attention-1",- kind: "mention",- server: "One",- serverId: "s1",- channel: "Post",- channelId: "post-1",- parentChannelId: "forum-1",- m: { id: "message-1", seq: 4 },- }],- truncated: false,- })- const { inboxMentionsProjectedQueryFn } = await import("./use-inbox")- const { AccountUnreadProjection } = await import("./account-unread-projection")- const projection = new AccountUnreadProjection("u1")- projection.setNotificationPolicy({- server: { s1: "all" },- channel: { "forum-1": parentLevel },+ apiFetchMock.mockResolvedValueOnce({ marked: false, stale: true })+ const messageMarked = renderHook(() => useMessageMarked("message", true), {+ wrapper: wrapperFor(new QueryClient({ defaultOptions: { queries: { retry: false } } })),})-- await inboxMentionsProjectedQueryFn(projection)()-- expect(projection.projectUnread(- "inbox-mentions",- "post-1",- false,- 4,- "mentions",- null,- true,- "attention-1",- )).toBe(expected)- })-- it("merges positive rows from a stale response without using its absence", async () => {- apiFetchMock.mockResolvedValueOnce({- servers: [{- serverId: "s1",- serverName: "One",- channels: [{- channelId: "positive",- channelName: "Positive",- lastMessageAt: "2026-09-04T00:00:00.000Z",- lastUnreadSeq: 2,- hasDirectUnread: true,- children: [],- }],- }],- dms: [],- truncated: false,- stale: true,- })- const { inboxUnreadsProjectedQueryFn } = await import("./use-inbox")- const { AccountUnreadProjection } = await import("./account-unread-projection")- const projection = new AccountUnreadProjection("u1")- projection.recordArrival({ channelId: "absent", serverId: "s1", seq: 1 })-- await expect(inboxUnreadsProjectedQueryFn(new QueryClient(), projection)())- .rejects.toThrow("stale D1 read")-- expect(projection.projectUnread("inbox-unreads", "positive", false)).toBe(true)- expect(projection.projectUnread("inbox-unreads", "absent", false)).toBe(true)- })-- it("fences the production query result until a focused candidate is classified", async () => {- const data = {- servers: [{ channels: [{- channelId: "focused",- lastMessageAt: "2026-08-27T01:00:00.000Z",- hasDirectUnread: true,- children: [],- }] }],- dms: [],- }- apiFetchMock.mockResolvedValueOnce(data).mockResolvedValueOnce(data)- const { inboxUnreadsReservedQueryFn } = await import("./use-inbox")- const qc = new QueryClient()- const seen = vi.fn()- const lease = registerInboxReadReservationSurface(qc, "focused", seen)- const first = inboxUnreadsReservedQueryFn(qc)()- void first.catch(() => undefined)- await vi.waitFor(() => expect(seen).toHaveBeenLastCalledWith(expect.objectContaining({- channelId: "focused",- })))-- takeInboxReadReservationNegative(lease)- await expect(first).rejects.toMatchObject({ name: "AbortError" })- await expect(inboxUnreadsReservedQueryFn(qc)()).resolves.toBe(data)- disposeInboxReadReservation(qc)+ await waitFor(() => expect(messageMarked.result.current.error).toMatchObject({+ name: "StaleReadError",+ }))+ expect(messageMarked.result.current.data).toBeUndefined()+ messageMarked.unmount()})- it("keeps the visible hook read-only across rerenders", async () => {- apiFetchMock.mockResolvedValue({ servers: [], dms: [] })- const { useInboxUnreads } = await import("./use-inbox")- const qc = new QueryClient({- defaultOptions: { queries: { retry: false } },- })- function Harness() {- const inbox = useInboxUnreads()- return React.createElement("span", {- "data-count": inbox.servers.length + inbox.dms.length,+ it("projects a DM only while its canonical owner is present", async () => {+ const harness = await createHarness()+ try {+ act(() => ingestAttentionSnapshot(harness.registry, dmSnapshot()))+ await waitFor(() => expect(harness.latest.dms).toEqual([expect.objectContaining({+ channelId: "dm",+ otherUserName: "Peer",+ lastUnreadSeq: 9,+ })]))++ const profileKey = communityKeys.communityDbCollection("viewer", "profiles")+ act(() => {+ harness.registry.collections.profiles.utils.writeDelete("peer")+ harness.queryClient.setQueryData(profileKey, [])})+ await waitFor(() => expect(harness.latest.dms).toEqual([]))+ } finally {+ harness.dispose()}- const tree = React.createElement(- QueryClientProvider,- { client: qc },- React.createElement(Harness),- )- let renderer!: ReturnType<typeof rtlRender>- await act(async () => {- renderer = rtlRender(tree)- })- expect(apiFetchMock).not.toHaveBeenCalled()- await act(async () => {- renderer.rerender(tree)- })- expect(renderer.container.querySelector("span")).toHaveAttribute("data-count", "0")- expect(apiFetchMock).not.toHaveBeenCalled()- await act(async () => renderer.unmount())})- it("ignores nested rows from the retired Inbox endpoint", async () => {- const removable = {- serverId: "s1",- serverName: "One",- channels: [{- channelId: "parent",- channelName: "Forum",- lastMessageAt: "2026-08-29T00:00:00.000Z",- lastUnreadSeq: 2,- mentionCount: 0,- hasDirectUnread: true,- children: [{+ it("projects child opener fields and skips the child when its parent disappears", async () => {+ const harness = await createHarness()+ try {+ act(() => ingestAttentionSnapshot(harness.registry, childThreadSnapshot()))+ await waitFor(() => expect(harness.latest.servers[0]?.channels[0]?.children[0])+ .toMatchObject({channelId: "child",- channelName: "Post",- lastMessageAt: "2026-08-29T00:00:00.000Z",- lastUnreadSeq: 2,- mentionCount: 0,- }],- }],- }- const retained = {- serverId: "s2",- serverName: "Two",- channels: [{- channelId: "keep",- channelName: "General",- lastMessageAt: "2026-08-29T00:00:00.000Z",- lastUnreadSeq: 3,- mentionCount: 0,- hasDirectUnread: true,- children: [],- }],- }- const removedDm = {- channelId: "dm-read",- otherUserId: "u1",- otherUserName: "One",- otherUserDiscriminator: "0001",- otherUserAvatar: "",- otherUserAvatarVersion: 0,- lastMessageAt: "2026-08-29T00:00:00.000Z",- lastUnreadSeq: 2,- }- const keptDm = { ...removedDm, channelId: "dm-keep", lastUnreadSeq: 3 }- const data = { servers: [removable, retained], dms: [removedDm, keptDm], truncated: false }- apiFetchMock.mockResolvedValue(data)- const { useInboxUnreads } = await import("./use-inbox")- const { getActiveAccountUnreadProjection } = await import("./account-unread-projection")- const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })- qc.setQueryData(communityKeys.inboxUnreads(), data)- const projection = getActiveAccountUnreadProjection(qc)- projection.recordRead("parent", 2)- projection.recordRead("child", 2)- projection.recordRead("dm-read", 2)- let latest: ReturnType<typeof useInboxUnreads> | undefined- function Harness() {- latest = useInboxUnreads()- return null- }- let renderer!: ReturnType<typeof rtlRender>- await act(async () => {- renderer = rtlRender(React.createElement(- QueryClientProvider,- { client: qc },- React.createElement(Harness),- ))- })-- expect(latest?.servers).toEqual([])- expect(latest?.dms).toEqual([])- expect(latest?.hasProjectedUnread).toBe(false)- await act(async () => renderer.unmount())- })-- it("does not let a legacy Inbox reservation create canonical attention", async () => {- const channel = {- channelId: "reserved",- channelName: "Reserved",- lastMessageAt: "2026-09-02T00:00:00.000Z",- lastUnreadSeq: 4,- mentionCount: 0,- hasDirectUnread: true,- children: [],- }- const server = {- serverId: "s1",- serverName: "One",- channels: [channel],- }- const data = { servers: [server], dms: [], truncated: false }- apiFetchMock.mockResolvedValue(data)- const { useInboxUnreads } = await import("./use-inbox")- const { useInboxAutoCollapse } = await import("./use-inbox-auto-collapse")- const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })- qc.setQueryData(communityKeys.inboxUnreads(), data)- let latest: ReturnType<typeof useInboxUnreads> | undefined- let collapse: ReturnType<typeof useInboxAutoCollapse> | undefined- function Harness() {- latest = useInboxUnreads()- collapse = useInboxAutoCollapse({- queryClient: qc,- publishedHref: "/c/channels/s0",- navigationPending: false,- pendingHref: null,+ parentChannelId: "parent",+ openerMessageId: "opener",+ openerSeq: 7,+ openerUnread: false,+ }))++ const channelKey = communityKeys.communityDbCollection("viewer", "channels")+ const channels = harness.queryClient.getQueryData<Array<{ id: string }>>(channelKey) ?? []+ act(() => {+ harness.registry.collections.channels.utils.writeDelete("parent")+ harness.queryClient.setQueryData(+ channelKey,+ channels.filter((channel) => channel.id !== "parent"),+ )+ })+ await waitFor(() => expect(harness.latest.servers[0]?.channels ?? []).toEqual([]))+ } finally {+ harness.dispose()+ }+ })++ it("uses forum-item fallback rows and sorts parent and child channels deterministically", async () => {+ const snapshot = forumSnapshot()+ snapshot.scopes[0] = {+ ...snapshot.scopes[0]!,+ ordinaryUnread: false,+ }+ snapshot.scopes.push({+ scopeId: "direct",+ channelId: "direct",+ serverId: "server",+ parentChannelId: null,+ ordinaryUnread: true,+ lastUnreadSeq: 40,+ lastAttentionSeq: null,+ attentionCount: 0,+ })+ snapshot.included.channels.push({+ id: "direct",+ serverId: "server",+ name: "Direct",+ type: "text",+ parentChannelId: null,+ parentMessageId: null,+ creatorId: null,+ archived: false,+ lastMessageAt: "2026-09-28T00:00:40.000Z",+ })+ const harness = await createHarness()+ try {+ act(() => ingestAttentionSnapshot(harness.registry, snapshot))+ await waitFor(() => expect(harness.latest.servers[0]?.channels.map((row) => row.channelId))+ .toEqual(["direct", "forum"]))+ expect(harness.latest.servers[0]?.channels[1]).toMatchObject({+ channelId: "forum",+ hasDirectUnread: false,})- return null+ expect(harness.latest.servers[0]?.channels[1]?.children.map((row) => row.channelId))+ .toEqual(["child-20", "child-10"])+ } finally {+ harness.dispose()}- let renderer!: ReturnType<typeof rtlRender>- await act(async () => {- renderer = rtlRender(React.createElement(- QueryClientProvider,- { client: qc },- React.createElement(Harness),- ))- })- expect(latest?.hasProjectedUnread).toBe(false)-- let epoch = 0- await act(async () => {- epoch = collapse!.beginProjection(- inboxChannelRowTarget(server, channel)!,- "/c/channels/s1/reserved",- )- })- expect(latest?.servers).toEqual([])- expect(latest?.hasProjectedUnread).toBe(false)-- await act(async () => {- collapse!.rollbackProjection(epoch)- })- expect(latest?.servers).toEqual([])- expect(latest?.hasProjectedUnread).toBe(false)- await act(async () => renderer.unmount())})- it("does not project a child-only parent from legacy Inbox data", async () => {- const child = {- channelId: "child",- channelName: "Post",- lastMessageAt: "2026-08-29T00:00:00.000Z",- lastUnreadSeq: 3,- mentionCount: 0,- }- const channel = {- channelId: "parent",- channelName: "Forum",- lastMessageAt: "2026-08-29T00:00:00.000Z",- lastUnreadSeq: 2,- mentionCount: 0,- hasDirectUnread: true,- children: [child],- }- const server = { serverId: "s1", serverName: "One", channels: [channel] }- const data = { servers: [server], dms: [], truncated: false }- apiFetchMock.mockResolvedValue(data)- const { useInboxUnreads } = await import("./use-inbox")- const { getActiveAccountUnreadProjection } = await import("./account-unread-projection")- const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })- qc.setQueryData(communityKeys.inboxUnreads(), data)- getActiveAccountUnreadProjection(qc).recordRead("parent", 2)- let latest: ReturnType<typeof useInboxUnreads> | undefined- function Harness() {- latest = useInboxUnreads()- return null+ it("falls back nullable friend identity fields and skips a missing profile", async () => {+ const nullableProfile = new Map<string, CommunityProfile>([["requester", {+ id: "requester",+ name: null,+ avatar: null,+ avatarVersion: null,+ } as unknown as CommunityProfile]])+ const fallbackHarness = await createHarness({ previewProfiles: nullableProfile })+ try {+ act(() => ingestAttentionSnapshot(fallbackHarness.registry, friendRequestSnapshot()))+ await waitFor(() => expect(fallbackHarness.latest.friendRequests).toEqual([{+ id: "request",+ userId: "requester",+ name: "Deleted user",+ avatar: "",+ avatarVersion: null,+ createdAt: "2026-09-28T00:00:05.000Z",+ }]))+ } finally {+ fallbackHarness.dispose()}- let renderer!: ReturnType<typeof rtlRender>- await act(async () => {- renderer = rtlRender(React.createElement(- QueryClientProvider,- { client: qc },- React.createElement(Harness),- ))- })- expect(latest?.servers).toEqual([])- await act(async () => renderer.unmount())- })- it("does not retain legacy unread evidence after an absent response", async () => {- const data = {- servers: [{- serverId: "s1",- serverName: "One",- channels: [{- channelId: "parent",- channelName: "Forum",- lastMessageAt: "2026-08-29T00:00:00.000Z",- mentionCount: 0,- hasDirectUnread: true,- children: [{- channelId: "child",- channelName: "Post",- lastMessageAt: "2026-08-29T00:00:00.000Z",- mentionCount: 0,- }],- }],- }],- dms: [{- channelId: "dm",- otherUserId: "u1",- otherUserName: "One",- otherUserDiscriminator: "0001",- otherUserAvatar: "",- otherUserAvatarVersion: 0,- lastMessageAt: "2026-08-29T00:00:00.000Z",- }],- }- apiFetchMock.mockResolvedValue({ servers: [], dms: [] })- const { useInboxUnreads } = await import("./use-inbox")- const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })- qc.setQueryData(communityKeys.inboxUnreads(), data)- let latest: ReturnType<typeof useInboxUnreads> | undefined- function Harness() {- latest = useInboxUnreads()- return null+ const missingHarness = await createHarness({ previewProfiles: new Map() })+ try {+ act(() => ingestAttentionSnapshot(missingHarness.registry, friendRequestSnapshot()))+ await waitFor(() => expect(missingHarness.latest.friendRequests).toEqual([]))+ } finally {+ missingHarness.dispose()}- let renderer!: ReturnType<typeof rtlRender>- await act(async () => {- renderer = rtlRender(React.createElement(- QueryClientProvider,- { client: qc },- React.createElement(Harness),- ))- })- await qc.invalidateQueries({- queryKey: communityKeys.inboxUnreads(),- exact: true,- })- await vi.waitFor(() => expect(latest?.servers).toEqual([]))- expect(latest?.servers).toEqual([])- expect(latest?.dms).toEqual([])- expect(latest?.hasProjectedUnread).toBe(false)- await act(async () => renderer.unmount())- })-})--describe("useInboxMentions / inboxMentionsQueryFn", () => {- it("fetches /inbox/mentions and populates queryClient at communityKeys.inboxMentions()", async () => {- apiFetchMock.mockResolvedValueOnce({ mentions: [] })- const { inboxMentionsQueryFn } = await import("./use-inbox")- const qc = new QueryClient()- const key = communityKeys.inboxMentions()- await qc.fetchQuery({ queryKey: key, queryFn: inboxMentionsQueryFn })- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/users/me/inbox/mentions")- expect(qc.getQueryData(key)).toEqual({ mentions: [] })})- it("retires an orphan attention source after a complete empty Mentions response", async () => {- apiFetchMock.mockResolvedValueOnce({ mentions: [], truncated: false })- const { inboxMentionsProjectedQueryFn } = await import("./use-inbox")- const { AccountUnreadProjection } = await import("./account-unread-projection")- const projection = new AccountUnreadProjection("u1")- projection.setNotificationPolicy({})- projection.recordMentionArrival({ channelId: "c1", seq: 4, isMention: true })-- await inboxMentionsProjectedQueryFn(projection)()-- expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(false)- })-- it("publishes only scoped embedded mention messages", async () => {- const message = {- id: "message-1",- type: "chat" as const,- seq: 4,- authorId: "author",- authorName: "Author",- content: "mention",- createdAt: "2026-09-26T00:00:00.000Z",+ it("uses the DM owner name for a DM mention", async () => {+ const harness = await createHarness()+ try {+ act(() => ingestAttentionSnapshot(harness.registry, dmSnapshot({ mention: true })))+ await waitFor(() => expect(harness.latest.mentions).toEqual([expect.objectContaining({+ id: "dm-mention",+ server: "Peer",+ channelId: "dm",+ })]))+ } finally {+ harness.dispose()}- apiFetchMock.mockResolvedValueOnce({- mentions: [- { id: "scoped", server: "One", serverId: "s1", channel: "General", channelId: "c1", m: message },- { id: "unscoped", server: "One", serverId: "s1", channel: "General", m: { ...message, id: "message-2" } },- ],- truncated: false,- })- const { inboxMentionsProjectedQueryFn } = await import("./use-inbox")- const { AccountUnreadProjection } = await import("./account-unread-projection")-- const result = await inboxMentionsProjectedQueryFn(- new AccountUnreadProjection("u1"),- new QueryClient(),- )()-- expect(result.mentions).toHaveLength(2)})- it("cancels Mentions snapshot coverage when the transport fails", async () => {- apiFetchMock.mockRejectedValueOnce(new Error("offline"))- const { inboxMentionsProjectedQueryFn } = await import("./use-inbox")- const { AccountUnreadProjection } = await import("./account-unread-projection")- const projection = new AccountUnreadProjection("u1")-- await expect(inboxMentionsProjectedQueryFn(projection)()).rejects.toThrow("offline")-- expect(projection.inspectForTests().pendingSnapshots).toBe(0)- })-- it("rejects a stale Mentions response before publishing its embedded message", async () => {+ it("publishes a canonical marked row when the marked surface is enabled", async () => {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ const registry = createCommunityDbRegistry(queryClient, "viewer")+ await registry.preload()+ const unregister = registerCommunityDbRegistry(registry)apiFetchMock.mockResolvedValueOnce({- mentions: [{- id: "attention-stale",- server: "One",- serverId: "s1",+ marked: [{+ id: "mark",+ server: "Server",+ serverId: "server",channel: "General",- channelId: "c1",+ channelId: "channel",m: {- id: "message-stale",+ id: "message",type: "chat",- seq: 4,- authorId: "author",- authorName: "Author",- content: "must not publish",- createdAt: "2026-09-26T00:00:00.000Z",+ seq: 5,+ createdAt: "2026-09-28T00:00:05.000Z",+ content: "keep",},}],- truncated: false,- stale: true,})- const { inboxMentionsProjectedQueryFn } = await import("./use-inbox")- const { AccountUnreadProjection } = await import("./account-unread-projection")- const queryClient = new QueryClient()- const registry = createCommunityDbRegistry(queryClient, "u1")- await registry.preload()- const unregister = registerCommunityDbRegistry(registry)- const projection = new AccountUnreadProjection("u1")-+ const rendered = renderHook(() => useInboxMarked(true), {+ wrapper: ({ children }: React.PropsWithChildren) => React.createElement(+ QueryClientProvider,+ { client: queryClient },+ React.createElement(CommunityDbProvider, { registry }, children),+ ),+ })try {- await expect(inboxMentionsProjectedQueryFn(projection, queryClient)())- .rejects.toThrow("stale D1 read")- expect(getCanonicalCommunityMessages(queryClient)).toEqual([])- expect(projection.inspectForTests().pendingSnapshots).toBe(0)- expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(false)+ await waitFor(() => expect(rendered.result.current.marked).toEqual([expect.objectContaining({+ id: "mark",+ channelId: "channel",+ m: expect.objectContaining({ id: "message", content: "keep" }),+ })]))} finally {+ rendered.unmount()unregister()- await registry["cleanup"]()}})- it("ignores mentions from the retired Inbox endpoint", async () => {- const scoped = { id: "m1", channelId: "c1", m: { seq: 2 } }- const unscoped = { id: "m2", m: { seq: 1 } }- const data = { mentions: [scoped, unscoped], truncated: false }- apiFetchMock.mockResolvedValue(data)- const { useInboxMentions } = await import("./use-inbox")- const { getActiveAccountUnreadProjection } = await import("./account-unread-projection")- const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })- qc.setQueryData(communityKeys.inboxMentions(), data)- const projection = getActiveAccountUnreadProjection(qc)- projection.recordRead("c1", 2)- projection.recordMentionArrival({ channelId: "pending", isMention: true })- let latest: ReturnType<typeof useInboxMentions> | undefined- function Harness() {- latest = useInboxMentions()- return null+ it("counts an aggregate-only attention conversation when bounded items are absent", async () => {+ const harness = await createHarness()+ try {+ act(() => ingestAttentionSnapshot(harness.registry, truncatedAttentionOnlySnapshot()))+ await waitFor(() => expect(harness.latest.exactAttentionCount).toBe(1))+ expect(harness.latest.servers[0]?.channels[0]).toMatchObject({+ channelId: "channel",+ mentionCount: 3,+ hasDirectUnread: true,+ })+ expect(harness.latest.mentions).toEqual([])+ } finally {+ harness.dispose()}- let renderer!: ReturnType<typeof rtlRender>- await act(async () => {- renderer = rtlRender(React.createElement(- QueryClientProvider,- { client: qc },- React.createElement(Harness),- ))- })- expect(latest?.mentions).toEqual([])- expect(latest?.hasProjectedMention).toBe(false)- await act(async () => renderer.unmount())})- it("does not let legacy mention reservations mutate canonical attention", async () => {- const channel = {- channelId: "shared",- channelName: "Shared",- lastMessageAt: "2026-09-04T02:00:00.000Z",- lastUnreadSeq: 4,- mentionCount: 1,- hasDirectUnread: true,- children: [],- }- const server = { serverId: "s1", serverName: "One", channels: [channel] }- const same = {- id: "mention-same",- serverId: "s1",- channelId: "shared",- m: { id: "message-same", seq: 4 },- }- const newer = {- id: "mention-newer",- serverId: "s1",- channelId: "shared",- m: { id: "message-newer", seq: 5 },- }- apiFetchMock.mockImplementation((url: string) => Promise.resolve(- url.endsWith("/unreads")- ? { servers: [server], dms: [], truncated: false }- : { mentions: [same, newer], truncated: false },- ))- const { useInboxMentions, useInboxUnreads } = await import("./use-inbox")- const { useInboxAutoCollapse } = await import("./use-inbox-auto-collapse")- const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })- qc.setQueryData(communityKeys.inboxUnreads(), {- servers: [server],- dms: [],- truncated: false,- })- qc.setQueryData(communityKeys.inboxMentions(), {- mentions: [same, newer],- truncated: false,- })- let unreads: ReturnType<typeof useInboxUnreads> | undefined- let mentions: ReturnType<typeof useInboxMentions> | undefined- let collapse: ReturnType<typeof useInboxAutoCollapse> | undefined- function Harness() {- unreads = useInboxUnreads()- mentions = useInboxMentions()- collapse = useInboxAutoCollapse({- queryClient: qc,- publishedHref: "/c/channels/s0",- navigationPending: false,- pendingHref: null,- })- return null- }- let renderer!: ReturnType<typeof rtlRender>- await act(async () => {- renderer = rtlRender(React.createElement(- QueryClientProvider,- { client: qc },- React.createElement(Harness),+ it("does not double-count the conversation when its bounded item arrives", async () => {+ const harness = await createHarness()+ try {+ act(() => ingestAttentionSnapshot(harness.registry, truncatedAttentionOnlySnapshot()))+ await waitFor(() => expect(harness.latest.exactAttentionCount).toBe(1))+ act(() => ingestAttentionSnapshot(+ harness.registry,+ truncatedAttentionWithBoundedItemSnapshot(),))- })- expect(mentions?.mentions).toEqual([])-- let epoch = 0- await act(async () => {- epoch = collapse!.beginProjection(- inboxChannelRowTarget(server, channel)!,- "/c/channels/s1/shared",- )- })-- expect(unreads?.servers).toEqual([])- expect(unreads?.hasProjectedUnread).toBe(false)- expect(mentions?.mentions).toEqual([])- expect(mentions?.hasProjectedMention).toBe(false)-- await act(async () => {- collapse!.rollbackProjection(epoch)- })- expect(unreads?.servers).toEqual([])- expect(mentions?.mentions).toEqual([])- await act(async () => renderer.unmount())+ await waitFor(() => expect(harness.latest.mentions).toHaveLength(1))+ expect(harness.latest.exactAttentionCount).toBe(1)+ } finally {+ harness.dispose()+ }})- it("returns an empty mention projection before query data arrives", async () => {- apiFetchMock.mockReturnValue(new Promise(() => undefined))- const { useInboxMentions } = await import("./use-inbox")- const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })- let latest: ReturnType<typeof useInboxMentions> | undefined- function Harness() {- latest = useInboxMentions()- return null+ it("does not create a row or count for an empty attention-only scope", async () => {+ const harness = await createHarness()+ try {+ act(() => ingestAttentionSnapshot(harness.registry, emptyAttentionScopeSnapshot()))+ await waitFor(() => expect(harness.latest.exactAttentionCount).toBe(0))+ expect(harness.latest.servers).toEqual([])+ expect(harness.latest.hasUnread).toBe(false)+ } finally {+ harness.dispose()}- let renderer!: ReturnType<typeof rtlRender>- await act(async () => {- renderer = rtlRender(React.createElement(- QueryClientProvider,- { client: qc },- React.createElement(Harness),- ))- })- expect(latest?.mentions).toEqual([])- expect(latest?.hasProjectedMention).toBe(false)- await act(async () => renderer.unmount())})- it("does not retain a legacy mention outside canonical attention", async () => {- const legacy = {- id: "legacy",- channelId: "c1",- serverId: "s1",- m: { id: "message" },- }- const data = { mentions: [legacy], truncated: true }- apiFetchMock.mockResolvedValue({ mentions: [], truncated: true })- const { useInboxMentions } = await import("./use-inbox")- const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })- qc.setQueryData(communityKeys.inboxMentions(), data)- let latest: ReturnType<typeof useInboxMentions> | undefined- function Harness() {- latest = useInboxMentions()- return null+ it("publishes two unread forum siblings as two exact presentation rows", async () => {+ const harness = await createHarness()+ try {+ act(() => ingestAttentionSnapshot(harness.registry, forumSnapshot()))+ await waitFor(() => {+ expect(harness.latest.servers[0]?.channels[0]?.children.map((row) => row.channelId))+ .toEqual(["child-20", "child-10"])+ })+ expect(harness.latest.servers[0]?.channels[0]).toMatchObject({+ channelId: "forum",+ hasDirectUnread: false,+ })+ expect(harness.latest.exactAttentionCount).toBe(2)+ expect(harness.latest.mentions).toEqual([])+ } finally {+ harness.dispose()}- let renderer!: ReturnType<typeof rtlRender>- await act(async () => {- renderer = rtlRender(React.createElement(- QueryClientProvider,- { client: qc },- React.createElement(Harness),- ))- })- await qc.invalidateQueries({- queryKey: communityKeys.inboxMentions(),- exact: true,- })- await vi.waitFor(() => expect(latest?.mentions).toEqual([]))- expect(latest?.mentions).toEqual([])- expect(latest?.hasProjectedMention).toBe(false)- await act(async () => renderer.unmount())})-})-describe("canonical account attention query ownership", () => {- it("hydrates cold server and DM scope owners after attention refs arrive", async () => {- useCommunityWsStore.getState().reset()- useCommunityWsStore.getState().activateProfileAccount("viewer")- const directory = deferred<{ directory: Array<{- id: string- name: string- discriminator: string- channels: Array<{ id: string; name: string; type: "text" }>- }> }>()- const dms = deferred<{ conversations: Array<{- id: string- userId: string- name: string- discriminator: string- avatar: string- avatarVersion: number- status: "offline"- preview: string- unread: boolean- lastUnreadSeq: number- }> }>()- apiFetchMock.mockImplementation((url: string) => {- if (url === "/api/community/users/me/attention") {- return Promise.resolve({- scopes: [{- scopeId: "channel-cold",- channelId: "channel-cold",- serverId: "server-cold",- parentChannelId: null,- ordinaryUnread: true,- lastUnreadSeq: 2,- lastAttentionSeq: null,- attentionCount: 0,- }, {- scopeId: "dm-cold",- channelId: "dm-cold",- serverId: null,- parentChannelId: null,- ordinaryUnread: true,- lastUnreadSeq: 3,- lastAttentionSeq: null,- attentionCount: 0,- }],- items: [],- limit: 100,- truncated: false,- })- }- if (url === "/api/community/users/me/channel-directory") return directory.promise- if (url === "/api/community/users/me/dms") return dms.promise- throw new Error(`unexpected request: ${url}`)- })- const { useInboxUnreads } = await import("./use-inbox")- const {- useAccountAttention,- useAccountAttentionScopeHydration,- } = await import("./use-account-attention")- const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })- const registry = createCommunityDbRegistry(qc, "viewer")- await registry.preload()- const unregister = registerCommunityDbRegistry(registry)- let latest: ReturnType<typeof useInboxUnreads> | undefined- function Harness() {- useAccountAttention()- useAccountAttentionScopeHydration()- latest = useInboxUnreads()- return null+ it("removes only the older forum unit when its parent read target advances", async () => {+ const harness = await createHarness()+ try {+ act(() => ingestAttentionSnapshot(harness.registry, forumSnapshot()))+ await waitFor(() => expect(harness.latest.exactAttentionCount).toBe(2))+ act(() => {+ clearAttentionScopeOptimistically(harness.registry, "forum", 10)+ })+ await waitFor(() => {+ expect(harness.latest.servers[0]?.channels[0]?.children.map((row) => row.channelId))+ .toEqual(["child-20"])+ })+ expect(harness.latest.exactAttentionCount).toBe(1)+ } finally {+ harness.dispose()}- let renderer!: ReturnType<typeof rtlRender>- await act(async () => {- renderer = rtlRender(React.createElement(- QueryClientProvider,- { client: qc },- React.createElement(- CommunityDbProvider,- { registry },- React.createElement(Harness),- ),- ))- })-- await vi.waitFor(() => {- expect(latest?.pendingChannelIds).toEqual(expect.arrayContaining([- "channel-cold",- "dm-cold",- ]))- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/users/me/channel-directory")- expect(apiFetchMock).toHaveBeenCalledWith(- "/api/community/users/me/dms",- expect.objectContaining({ signal: expect.any(AbortSignal) }),- )- })- expect(latest?.servers).toEqual([])- expect(latest?.dms).toEqual([])-- await act(async () => directory.resolve({- directory: [{- id: "server-cold",- name: "Cold server",- discriminator: "0042",- channels: [{ id: "channel-cold", name: "cold-channel", type: "text" }],- }],- }))- await vi.waitFor(() => expect(latest?.servers[0]?.channels[0]?.channelId)- .toBe("channel-cold"))- expect(latest?.dms).toEqual([])-- await act(async () => dms.resolve({- conversations: [{- id: "dm-cold",- userId: "peer",- name: "Peer",- discriminator: "0002",- avatar: "",- avatarVersion: 1,- status: "offline",- preview: "",- unread: true,- lastUnreadSeq: 3,- }],- }))- await vi.waitFor(() => expect(latest?.dms[0]?.channelId).toBe("dm-cold"))- expect(latest?.pendingChannelIds).toEqual([])- expect(apiFetchMock.mock.calls.filter(- ([url]) => url === "/api/community/users/me/attention",- )).toHaveLength(1)-- await act(async () => renderer.unmount())- unregister()- await registry["cleanup"]()})- it("keeps visible Inbox projections transport-free across observer remounts", async () => {- apiFetchMock.mockImplementation((url: string) => Promise.resolve(- url.endsWith("/unreads")- ? { servers: [], dms: [] }- : { mentions: [] },- ))- const { useInboxMentions, useInboxUnreads } = await import("./use-inbox")- const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })- function Harness() {- useInboxUnreads()- useInboxMentions()- return null+ it("never paints a positive badge without its forum rows", async () => {+ const harness = await createHarness()+ try {+ act(() => ingestAttentionSnapshot(harness.registry, forumSnapshot()))+ await waitFor(() => expect(harness.latest.exactAttentionCount).toBe(2))+ expect(harness.paints.some((paint) => paint.count > 0 && paint.children.length === 0))+ .toBe(false)+ } finally {+ harness.dispose()}- const tree = React.createElement(- QueryClientProvider,- { client: qc },- React.createElement(Harness),- )- let renderer!: ReturnType<typeof rtlRender>- await act(async () => {- renderer = rtlRender(tree)- })- expect(apiFetchMock).not.toHaveBeenCalled()- await act(async () => renderer.unmount())- await act(async () => {- renderer = rtlRender(tree)- })-- expect(apiFetchMock).not.toHaveBeenCalled()- expect(qc.getQueryCache().find({ queryKey: communityKeys.accountAttention() })).toBeDefined()- expect(qc.getQueryCache().find({ queryKey: communityKeys.inboxUnreads() })).toBeUndefined()- expect(qc.getQueryCache().find({ queryKey: communityKeys.inboxMentions() })).toBeUndefined()- await qc.invalidateQueries({ queryKey: communityKeys.inbox() })- expect(apiFetchMock).not.toHaveBeenCalled()- await act(async () => renderer.unmount())})-})-describe("useInboxMarked", () => {- it("fetches the identity-aware marked feed only when enabled", async () => {- apiFetchMock.mockResolvedValue({ marked: [{- id: "mark-1",- channelId: "c1",- serverId: "s1",- m: {- id: "message-1",- type: "chat",- authorId: "author",- authorName: "Author",- content: "marked",- createdAt: "2026-09-26T00:00:00.000Z",- },- }] })- const { useInboxMarked } = await import("./use-inbox")- const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })- function Harness() {- const result = useInboxMarked(true)- return React.createElement("span", { "data-count": result.marked.length })+ it("keeps the last complete state when a refresh fails", async () => {+ apiFetchMock.mockResolvedValueOnce(forumSnapshot())+ const harness = await createHarness({ owner: true })+ try {+ await waitFor(() => expect(harness.latest.exactAttentionCount).toBe(2))+ apiFetchMock.mockRejectedValueOnce(new Error("offline"))+ await act(async () => { await harness.latest.refetch() })+ expect(harness.latest.exactAttentionCount).toBe(2)+ expect(harness.latest.isInitialError).toBe(false)+ } finally {+ harness.dispose()}- let renderer!: ReturnType<typeof rtlRender>- await act(async () => {- renderer = rtlRender(React.createElement(- QueryClientProvider,- { client: qc },- React.createElement(Harness),- ))- })-- await vi.waitFor(() => {- expect(apiFetchMock).toHaveBeenCalledWith(- "/api/community/users/me/marks",- expect.objectContaining({ signal: expect.any(AbortSignal) }),- )- })- await vi.waitFor(() => expect(renderer.container.querySelector("span"))- .toHaveAttribute("data-count", "1"))- act(() => renderer.unmount())})-})-// 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 both inbox queries in a single call", async () => {- apiFetchMock- .mockResolvedValueOnce({ servers: [], dms: [] })- .mockResolvedValueOnce({ mentions: [] })- const { inboxUnreadsQueryFn, inboxMentionsQueryFn } = await import(- "./use-inbox"- )- const qc = new QueryClient()- const unreadsKey = communityKeys.inboxUnreads()- const mentionsKey = communityKeys.inboxMentions()- await qc.fetchQuery({ queryKey: unreadsKey, queryFn: inboxUnreadsQueryFn })- await qc.fetchQuery({ queryKey: mentionsKey, queryFn: inboxMentionsQueryFn })-- await qc.invalidateQueries({ queryKey: communityKeys.inbox() })-- expect(qc.getQueryState(unreadsKey)?.isInvalidated).toBe(true)- expect(qc.getQueryState(mentionsKey)?.isInvalidated).toBe(true)+ it("exposes an initial error instead of an empty success", async () => {+ apiFetchMock.mockRejectedValueOnce(new Error("offline"))+ const harness = await createHarness({ owner: true })+ try {+ await waitFor(() => expect(harness.latest.isInitialError).toBe(true))+ expect(harness.latest.isLoading).toBe(false)+ expect(harness.latest.exactAttentionCount).toBe(0)+ } finally {+ harness.dispose()+ }})})diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.tsindex fbc911554..424516e72 100644--- a/src/web/src/hooks/community/use-inbox.ts+++ b/src/web/src/hooks/community/use-inbox.ts@@ -1,17 +1,24 @@"use client"import { useMemo, useSyncExternalStore } from "react"-import { useQuery, useQueryClient, keepPreviousData, type QueryClient, type UseQueryResult } from "@tanstack/react-query"+import {+ keepPreviousData,+ useQuery,+ useQueryClient,+ type QueryClient,+ type UseQueryResult,+} from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { apiFetchProfiles, messageProfilePatches } from "@/lib/community/profile-seed"import { communityKeys } from "@/lib/query-keys"-import type { UnreadServer, UnreadDm, InboxFriendRequest, Mention, Marked } from "@/lib/community/models/inbox"-import { reserveInboxUnreadsResponse } from "./inbox-read-reservation"-import {- getActiveAccountUnreadProjection,- type AccountUnreadProjection,- type AccountUnreadSource,-} from "./account-unread-projection"+import type {+ InboxFriendRequest,+ Marked,+ Mention,+ UnreadDm,+ UnreadServer,+} from "@/lib/community/models/inbox"+import { getActiveAccountUnreadProjection } from "./account-unread-projection"import {materializeCanonicalMessage,useCanonicalChannelsById,@@ -27,189 +34,49 @@ import {import { useAccountAttentionProjection } from "./use-account-attention"class StaleReadError extends Error {- constructor() { super("stale D1 read"); this.name = "StaleReadError" }-}-function throwIfStale<T extends { stale?: boolean }>(v: T): T {- if (v?.stale) throw new StaleReadError()- return v-}--// Frozen empty fallbacks — see `use-servers.ts` for the rationale.-const EMPTY_MARKED: readonly Marked[] = Object.freeze([])--type ProjectedUnreadChild = UnreadServer["channels"][number]["children"][number] & {- lastAttentionSeq?: number | null+ constructor() {+ super("stale D1 read")+ this.name = "StaleReadError"+ }}-type ProjectedUnreadChannel = Omit<UnreadServer["channels"][number], "children"> & {- lastAttentionSeq?: number | null- children: ProjectedUnreadChild[]+function throwIfStale<T extends { stale?: boolean }>(value: T): T {+ if (value.stale) throw new StaleReadError()+ return value}-type ProjectedUnreadServer = Omit<UnreadServer, "channels"> & {- channels: ProjectedUnreadChannel[]-}+const EMPTY_MARKED: readonly Marked[] = Object.freeze([])-type ProjectedMention = Mention & {- parentChannelId?: string | null-}+type ProjectedUnreadChannel = UnreadServer["channels"][number]/**- * 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 both in one batch.- *- * 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 the other).+ * The account attention snapshot is the only source for the badge, Unreads,+ * Mentions, and friend-request rows. All owner records arrive in that same+ * fenced response and are published atomically with its scopes and items.*/--export type UnreadsResponse = {- friendRequests: InboxFriendRequest[]- servers: ProjectedUnreadServer[]- dms: UnreadDm[]- limit?: number- truncated?: boolean-}--const inboxUnreadsTransportFn = ({ signal }: { signal?: AbortSignal } = {}) =>- apiFetchProfiles<UnreadsResponse & { stale?: boolean }>(- "/api/community/users/me/inbox/unreads",- (data) => {- 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 },- )--export const inboxUnreadsQueryFn = async (- context: { signal?: AbortSignal } = {},-) => throwIfStale(await inboxUnreadsTransportFn(context))--export const inboxUnreadsReservedQueryFn = (queryClient: ReturnType<typeof useQueryClient>) => (- { signal }: { signal?: AbortSignal } = {},-) => inboxUnreadsQueryFn({ signal }).then(- (data) => reserveInboxUnreadsResponse(queryClient, data, signal),-)--function inboxUnreadSources(data: UnreadsResponse) {- const channels: AccountUnreadSource[] = data.servers.flatMap((server) => (- server.channels.flatMap((channel) => [- ...(channel.lastUnreadSeq === undefined ? [] : [{- channelId: channel.channelId,- serverId: server.serverId,- lastUnreadSeq: channel.lastUnreadSeq,- }]),- ...(channel.lastAttentionSeq === undefined || channel.lastAttentionSeq === null ? [] : [{- channelId: channel.channelId,- serverId: server.serverId,- lastUnreadSeq: channel.lastAttentionSeq,- lastMentionSeq: channel.lastAttentionSeq,- isMention: true,- }]),- ...channel.children.flatMap((child) => [- ...(child.lastUnreadSeq === undefined ? [] : [{- channelId: child.channelId,- serverId: server.serverId,- railChannelId: channel.channelId,- lastUnreadSeq: child.lastUnreadSeq,- }]),- ...(child.lastAttentionSeq === undefined || child.lastAttentionSeq === null ? [] : [{- channelId: child.channelId,- serverId: server.serverId,- railChannelId: channel.channelId,- lastUnreadSeq: child.lastAttentionSeq,- lastMentionSeq: child.lastAttentionSeq,- isMention: true,- }]),- ]),- ])- ))- const dms: AccountUnreadSource[] = data.dms.flatMap((dm) => (- dm.lastUnreadSeq === undefined ? [] : [{- channelId: dm.channelId,- lastUnreadSeq: dm.lastUnreadSeq,- }]- ))- return { channels, dms }-}--export const inboxUnreadsProjectedQueryFn = (- queryClient: ReturnType<typeof useQueryClient>,- projection: AccountUnreadProjection,-) => async ({ signal }: { signal?: AbortSignal } = {}) => {- const channelsToken = projection.beginSnapshot("inbox-unreads", "channels")- const dmsToken = projection.beginSnapshot("inbox-unreads", "dms")- try {- const data = await inboxUnreadsTransportFn({ signal })- const sources = inboxUnreadSources(data)- projection.absorbSnapshot(channelsToken, sources.channels, {- truncated: data.truncated ?? true,- stale: data.stale,- })- // The route's cap and `truncated` bit cover server nodes only. DMs are- // always returned as a complete, independently authoritative domain.- projection.absorbSnapshot(dmsToken, sources.dms, {- truncated: false,- stale: data.stale,- })- throwIfStale(data)- return reserveInboxUnreadsResponse(queryClient, data, signal)- } catch (error) {- projection.cancelSnapshot(channelsToken)- projection.cancelSnapshot(dmsToken)- throw error- }-}--export function useInboxUnreads() {+export function useInboxAttention() {const query = useAccountAttentionProjection()const channelsById = useCanonicalChannelsById()- const serversById = useCanonicalServersById()+ const messagesById = useCanonicalMessagesById()const profilesById = useCanonicalProfilesByUserId()+ const serversById = useCanonicalServersById()const dmProjection = useDmProjection()+const projected = useMemo(() => {- const pendingChannelIds: string[] = []+ const scopesById = new Map(query.scopes.map((scope) => [scope.scopeId, scope]))+ const forumParentScopeIds = new Set(query.items.flatMap((item) => (+ item.kind === "forum_post" && item.scopeId ? [item.scopeId] : []+ )))const dmById = new Map((dmProjection ?? []).map((dm) => [dm.id, dm]))- const dms: UnreadDm[] = []const grouped = new Map<string, Map<string, ProjectedUnreadChannel>>()+ const dms: UnreadDm[] = []+for (const scope of query.scopes) {if (!scope.ordinaryUnread && scope.attentionCount <= 0) continueconst channel = channelsById.get(scope.channelId)- if (!channel) {- pendingChannelIds.push(scope.channelId)- continue- }if (!scope.serverId) {const dm = dmById.get(scope.channelId)- if (!dm) {- pendingChannelIds.push(scope.channelId)- continue- }+ if (!channel || !dm) continuedms.push({channelId: dm.id,otherUserId: dm.userId,@@ -222,14 +89,13 @@ export function useInboxUnreads() {})continue}+ if (!channel) continueconst serverChannels = grouped.get(scope.serverId) ?? new Map<string, ProjectedUnreadChannel>()grouped.set(scope.serverId, serverChannels)+if (scope.parentChannelId) {const parent = channelsById.get(scope.parentChannelId)- if (!parent) {- pendingChannelIds.push(scope.channelId)- continue- }+ if (!parent) continueconst parentRow = serverChannels.get(parent.id) ?? {channelId: parent.id,channelName: parent.name,@@ -245,189 +111,173 @@ export function useInboxUnreads() {type: "thread",lastMessageAt: channel.lastMessageAt ?? "",lastUnreadSeq: scope.lastUnreadSeq,- lastAttentionSeq: scope.lastAttentionSeq,mentionCount: scope.attentionCount,parentChannelId: parent.id,...(channel.parentMessageId ? { openerMessageId: channel.parentMessageId } : {}),+ ...(channel.openerSeq === undefined ? {} : { openerSeq: channel.openerSeq }),+ ...(channel.openerUnread === undefined ? {} : { openerUnread: channel.openerUnread }),})serverChannels.set(parent.id, parentRow)continue}++ const previous = serverChannels.get(channel.id)serverChannels.set(channel.id, {channelId: channel.id,channelName: channel.name,type: channel.type === "forum" ? "forum" : "text",lastMessageAt: channel.lastMessageAt ?? "",lastUnreadSeq: scope.lastUnreadSeq,- lastAttentionSeq: scope.lastAttentionSeq,mentionCount: scope.attentionCount,- hasDirectUnread: scope.ordinaryUnread,- children: serverChannels.get(channel.id)?.children ?? [],+ hasDirectUnread: scope.attentionCount > 0 || (+ scope.ordinaryUnread && !forumParentScopeIds.has(scope.scopeId)+ ),+ children: previous?.children ?? [],})}+ for (const item of query.items) {+ if (+ item.kind !== "forum_post"+ || !item.scopeId+ || !item.childChannelId+ || item.openerSeq === undefined+ || !item.messageId+ ) continue+ const scope = scopesById.get(item.scopeId)+ const parent = scope ? channelsById.get(scope.channelId) : undefined+ const child = channelsById.get(item.childChannelId)+ const opener = messagesById?.get(item.messageId)+ if (!scope?.serverId || !parent || !child || !opener) continue+ const serverChannels = grouped.get(scope.serverId) ?? new Map<string, ProjectedUnreadChannel>()+ grouped.set(scope.serverId, serverChannels)+ const parentRow = serverChannels.get(parent.id) ?? {+ channelId: parent.id,+ channelName: parent.name,+ type: "forum",+ lastMessageAt: parent.lastMessageAt ?? "",+ mentionCount: scope.attentionCount,+ hasDirectUnread: scope.ordinaryUnread,+ children: [],+ }+ const existingIndex = parentRow.children.findIndex((row) => row.channelId === child.id)+ const childRow = {+ channelId: child.id,+ channelName: opener.content?.trim() || child.name,+ type: "thread" as const,+ lastMessageAt: opener.createdAt ?? child.lastMessageAt ?? "",+ lastUnreadSeq: item.openerSeq,+ mentionCount: 0,+ parentChannelId: parent.id,+ openerMessageId: item.messageId,+ openerSeq: item.openerSeq,+ openerUnread: true,+ }+ if (existingIndex >= 0) parentRow.children[existingIndex] = childRow+ else parentRow.children.push(childRow)+ serverChannels.set(parent.id, parentRow)+ }+const servers: UnreadServer[] = [...grouped].flatMap(([serverId, rows]) => {const server = serversById.get(serverId)- if (!server) {- pendingChannelIds.push(...[...rows.values()].map((row) => row.channelId))- return []- }- return [{- serverId,- serverName: server.name,- channels: [...rows.values()].sort((a, b) => b.lastMessageAt.localeCompare(a.lastMessageAt)),- }]+ if (!server) return []+ const channels = [...rows.values()]+ .map((channel) => ({+ ...channel,+ children: channel.children+ .slice()+ .sort((left, right) => right.lastMessageAt.localeCompare(left.lastMessageAt)),+ }))+ .sort((left, right) => right.lastMessageAt.localeCompare(left.lastMessageAt))+ return [{ serverId, serverName: server.name, channels }]})- const friendRequests: InboxFriendRequest[] = query.items- .filter((item) => item.kind === "friend_request")- .map((item) => {- const profile = profilesById.get(item.actorUserId)- return {- id: item.sourceId,- userId: item.actorUserId,- name: profile?.name ?? "Deleted user",- avatar: profile?.avatar ?? "",- avatarVersion: profile?.avatarVersion ?? null,- createdAt: item.createdAt,- pendingIdentity: !profile,- }- })- return { servers, dms, friendRequests, pendingChannelIds }- }, [channelsById, dmProjection, profilesById, query.items, query.scopes, serversById])- return {- ...query,- friendRequests: projected.friendRequests,- servers: projected.servers,- dms: projected.dms,- pendingChannelIds: projected.pendingChannelIds,- isProjectionPending: projected.pendingChannelIds.length > 0,- hasProjectedUnread: projected.servers.length > 0- || projected.dms.length > 0- || projected.pendingChannelIds.length > 0,- hasOutstandingFriendRequest: projected.friendRequests.length > 0,- exactAttentionCount: query.scopes.reduce((total, scope) => total + scope.attentionCount, 0),- }-}--export type MentionsResponse = {- mentions: ProjectedMention[]- limit?: number- truncated?: boolean-}--const inboxMentionsTransportFn = (signal?: AbortSignal) =>- apiFetchProfiles<MentionsResponse & { stale?: boolean }>(- "/api/community/users/me/inbox/mentions",- (data) => messageProfilePatches(data.mentions.map((mention) => mention.m)),- signal ? { signal } : undefined,- )--export const inboxMentionsQueryFn = async () => (- throwIfStale(await inboxMentionsTransportFn())-)--function inboxMentionSources(data: MentionsResponse): AccountUnreadSource[] {- return data.mentions.flatMap((mention) => (- mention.channelId && mention.m.seq- ? [{- channelId: mention.channelId,- serverId: mention.serverId,- railChannelId: mention.parentChannelId ?? undefined,- messageId: mention.m.id,- attentionId: mention.id,- lastUnreadSeq: mention.m.seq,- lastMentionSeq: mention.m.seq,- }]- : []- ))-}+ dms.sort((left, right) => right.lastMessageAt.localeCompare(left.lastMessageAt))-export const inboxMentionsProjectedQueryFn = (- projection: AccountUnreadProjection,- queryClient?: QueryClient,-) => async ({ signal }: { signal?: AbortSignal } = {}) => {- const token = projection.beginSnapshot("inbox-mentions", "mentions")- const publicationToken = queryClient- ? captureCommunityLiveSnapshotToken(queryClient)- : null- try {- const data = throwIfStale(await inboxMentionsTransportFn(signal))- if (queryClient && publicationToken) {- publishCommunityEmbeddedMessages(queryClient, {- entries: data.mentions.flatMap((mention) => mention.channelId- ? [{ channelId: mention.channelId, message: mention.m }]- : []),- proof: { token: publicationToken, signal },- })- }- projection.absorbSnapshot(token, inboxMentionSources(data), {- truncated: data.truncated ?? true,- stale: data.stale,+ const friendRequests: InboxFriendRequest[] = query.items.flatMap((item) => {+ if (item.kind !== "friend_request" || !item.actorUserId) return []+ const profile = profilesById.get(item.actorUserId)+ if (!profile) return []+ return [{+ id: item.sourceId,+ userId: item.actorUserId,+ name: profile.name ?? "Deleted user",+ avatar: profile.avatar ?? "",+ avatarVersion: profile.avatarVersion ?? null,+ createdAt: item.createdAt,+ }]})- return data- } catch (error) {- projection.cancelSnapshot(token)- throw error- }-}-export function useInboxMentions() {- const canonicalMessages = useCanonicalMessagesById()- const channelsById = useCanonicalChannelsById()- const serversById = useCanonicalServersById()- const query = useAccountAttentionProjection()- const projected = useMemo(() => {- const pendingChannelIds: string[] = []- const scopesById = new Map(query.scopes.map((scope) => [scope.scopeId, scope]))- const mentions = query.items.flatMap((item): Mention[] => {- if (item.kind === "friend_request" || !item.scopeId || !item.messageId) return []- if (item.kind === "pending") {- pendingChannelIds.push(item.scopeId)- return []- }+ const mentions: Mention[] = query.items.flatMap((item) => {+ if (+ item.kind !== "mention" && item.kind !== "reply"+ || !item.scopeId+ || !item.messageId+ ) return []const scope = scopesById.get(item.scopeId)- const message = canonicalMessages?.get(item.messageId)const channel = scope ? channelsById.get(scope.channelId) : undefined- if (!scope || !message || !channel) {- pendingChannelIds.push(scope?.channelId ?? item.scopeId)- return [{- id: item.sourceId,- kind: item.kind,- server: "",- ...(scope?.serverId ? { serverId: scope.serverId } : {}),- channel: "",- channelId: scope?.channelId ?? item.scopeId,- pending: true,- m: {- id: item.messageId,- type: "chat",- authorId: item.actorUserId,- },- }]- }+ const message = messagesById?.get(item.messageId)+ if (!scope || !channel || !message) return []return [{id: item.sourceId,kind: item.kind,server: scope.serverId- ? serversById.get(scope.serverId)?.name ?? "Server unavailable"- : "Conversation unavailable",+ ? serversById.get(scope.serverId)?.name ?? ""+ : dmById.get(scope.channelId)?.name ?? "",...(scope.serverId ? { serverId: scope.serverId } : {}),- channel: channel.name || "Conversation unavailable",+ channel: channel.name,channelId: channel.id,m: message,}]})- return { mentions, pendingChannelIds }- }, [canonicalMessages, channelsById, query.items, query.scopes, serversById])++ const conversations = new Set<string>()+ for (const server of servers) {+ for (const channel of server.channels) {+ if (channel.hasDirectUnread !== false) conversations.add(channel.channelId)+ for (const child of channel.children) conversations.add(child.channelId)+ }+ }+ for (const dm of dms) conversations.add(dm.channelId)+ for (const mention of mentions) conversations.add(mention.channelId ?? mention.id)+ const exactAttentionCount = conversations.size + friendRequests.length++ return {+ servers,+ dms,+ mentions,+ friendRequests,+ exactAttentionCount,+ }+ }, [+ channelsById,+ dmProjection,+ messagesById,+ profilesById,+ query.items,+ query.scopes,+ serversById,+ ])+return {...query,- mentions: projected.mentions,- pendingChannelIds: projected.pendingChannelIds,- isProjectionPending: projected.pendingChannelIds.length > 0,- hasProjectedMention: projected.mentions.length > 0 || projected.pendingChannelIds.length > 0,+ ...projected,+ pendingChannelIds: [] as string[],+ isProjectionPending: false,+ hasUnread: projected.servers.length > 0 || projected.dms.length > 0,+ hasMention: projected.mentions.length > 0,+ hasProjectedUnread: projected.servers.length > 0 || projected.dms.length > 0,+ hasProjectedMention: projected.mentions.length > 0,+ hasOutstandingFriendRequest: projected.friendRequests.length > 0,+ isLoading: query.data === undefined && !query.isError,+ isInitialError: query.data === undefined && query.isError,}}+/** Compatibility alias for the friend-request counter in the DM layout. */+export function useInboxUnreads() {+ return useInboxAttention()+}+export type MarkedResponse = { marked: Marked[] }const inboxMarkedQueryFn = (queryClient: QueryClient) =>@@ -453,13 +303,6 @@ const inboxMarkedQueryFn = (queryClient: QueryClient) =>return throwIfStale(data)}-/**- * The Marked feed is lazy — unlike unreads/mentions (which the shell reads- * eagerly to drive the bell badge), the Marked tab has no badge and only- * matters once the viewer opens it. Pass `enabled` = "is the Marked tab- * selected" so the fetch is deferred until then, per the plan's- * enabled-gate lazy-load.- */export function useInboxMarked(enabled: boolean): UseQueryResult<MarkedResponse> & {marked: Marked[]} {@@ -492,10 +335,7 @@ export function useInboxMarked(enabled: boolean): UseQueryResult<MarkedResponse>return message ? [{ ...marked, m: message }] : []})}, [canonicalMessages, query.data?.marked, unreadProjection, unreadVersion])- return {- ...query,- marked,- }+ return { ...query, marked }}export type MessageMarkedResponse = { marked: boolean }@@ -505,15 +345,10 @@ const messageMarkedQueryFn = (messageId: string) => () =>`/api/community/messages/${messageId}/marks`,).then(throwIfStale)-/**- * Whether the viewer has marked one message — fetched lazily when its ⋯ menu- * opens (`enabled` = menu-open) so a channel never pre-loads mark state for- * every row. Single indexed row read; the result is cached per message id so- * re-opening the same menu doesn't re-query. Drives the Mark/Unmark label —- * the menu renders "Mark" first and silently flips to "Unmark" if this- * resolves marked (no spinner, per Alli).- */-export function useMessageMarked(messageId: string, enabled: boolean): UseQueryResult<MessageMarkedResponse> {+export function useMessageMarked(+ messageId: string,+ enabled: boolean,+): UseQueryResult<MessageMarkedResponse> {return useQuery({queryKey: communityKeys.messageMarked(messageId),queryFn: messageMarkedQueryFn(messageId),diff --git a/src/web/src/lib/community-db/schema.ts b/src/web/src/lib/community-db/schema.tsindex c9c34d625..f7f606001 100644--- a/src/web/src/lib/community-db/schema.ts+++ b/src/web/src/lib/community-db/schema.ts@@ -48,6 +48,8 @@ export const channelSchema = z.object({tags: z.array(z.string()),pending: z.boolean(),lastMessageAt: optionalNullableString,+ openerSeq: z.number().int().nonnegative().optional(),+ openerUnread: z.boolean().optional(),preview: z.string().optional(),lastUnreadSeq: z.number().int().nonnegative().optional(),})@@ -129,12 +131,18 @@ export const attentionScopeSchema = z.strictObject({export const attentionItemSchema = z.strictObject({id: z.string().min(1),- kind: z.enum(["mention", "reply", "friend_request", "pending"]),+ kind: z.enum(["mention", "reply", "friend_request", "forum_post"]),sourceId: z.string().min(1),scopeId: optionalNullableString,messageId: optionalNullableString,- actorUserId: z.string().min(1),+ actorUserId: optionalNullableString,createdAt: z.string(),+ childChannelId: z.string().min(1).optional(),+ openerSeq: z.number().int().nonnegative().optional(),+ readTarget: z.strictObject({+ channelId: z.string().min(1),+ seq: z.number().int().nonnegative(),+ }).optional(),})export const folderSchema = z.object({diff --git a/src/web/src/lib/community-db/sync.test.ts b/src/web/src/lib/community-db/sync.test.tsindex fd76c7a0a..7c61b1581 100644--- a/src/web/src/lib/community-db/sync.test.ts+++ b/src/web/src/lib/community-db/sync.test.ts@@ -34,11 +34,10 @@ import {publishCommunityChannelDirectory,publishCommunityLiveSnapshot as publishCommunityLiveSnapshotWithProof,publishAccountAttentionSnapshot,- projectAttentionUnreadBump,- projectAttentionMentionHint,projectCommunityWsEventToDb,purgeCommunityChannel,purgeCommunityServer,+ removeAttentionItemsOptimistically,restoreAttentionScopeOptimisticSnapshot,type CommunityLiveSnapshot,} from "./sync"@@ -1116,7 +1115,7 @@ describe("community DB sync", () => {expect(db.collections.readStates.get("c1")).toBeUndefined()})- it("preserves a WS fact that exists before an older snapshot request begins", async () => {+ it("lets one authoritative snapshot replace the complete prior attention truth", async () => {const db = await registry()const scope = {scopeId: "c1",@@ -1128,20 +1127,168 @@ describe("community DB sync", () => {lastAttentionSeq: 4,attentionCount: 1,}- projectAttentionUnreadBump(db.queryClient, {- type: "community:unread.bump",- userId: db.accountId,- channelId: "c1",- serverId: "s1",- isMention: true,- }, { seq: 4 })+ ingestAttentionSnapshot(db, {+ scopes: [scope],+ items: [],+ limit: 100,+ truncated: false,+ })const token = captureCommunityLiveSnapshotToken(db.queryClient)expect(publishAccountAttentionSnapshot(db.queryClient, {snapshot: { scopes: [], items: [], limit: 100, truncated: false },proof: { token, signal: undefined },})).toBe("published")- expect(db.collections.attentionScopes.get("c1")).toMatchObject(scope)+ expect(db.collections.attentionScopes.get("c1")).toBeUndefined()+ })++ it("hydrates new DMs while preserving richer existing channel state", async () => {+ const db = await registry()+ ingestDms(db, { conversations: [{+ id: "existing",+ userId: "peer-existing",+ name: "Existing",+ discriminator: "0002",+ avatar: "E",+ avatarVersion: 1,+ status: "offline",+ preview: "keep preview",+ activityAt: "2026-09-27T00:00:01.000Z",+ unread: false,+ }] })+ const existing = db.collections.channels.get("existing")!+ const patched = { ...existing, position: 7, muted: true }+ const channelKey = communityKeys.communityDbCollection(db.scopeId, "channels")+ db.collections.channels.utils.writeUpsert(patched)+ db.queryClient.setQueryData(channelKey, [patched])++ ingestAttentionSnapshot(db, {+ scopes: [],+ items: [],+ limit: 100,+ truncated: false,+ included: {+ servers: [],+ channels: [],+ dms: [{+ id: "existing",+ userId: "peer-existing",+ name: "Existing",+ discriminator: "0002",+ avatar: "E",+ avatarVersion: 2,+ lastMessageAt: "2026-09-28T00:00:07.000Z",+ lastUnreadSeq: 7,+ }, {+ id: "new",+ userId: "peer-new",+ name: "New",+ discriminator: "0003",+ avatar: "N",+ avatarVersion: 1,+ lastMessageAt: "2026-09-28T00:00:08.000Z",+ lastUnreadSeq: 8,+ }],+ profiles: [{+ userId: "peer-existing",+ name: "Existing",+ discriminator: "0002",+ avatar: "E",+ avatarVersion: 2,+ }, {+ userId: "peer-new",+ name: "New",+ discriminator: "0003",+ avatar: "N",+ avatarVersion: 1,+ }],+ messages: [],+ },+ })++ await vi.waitFor(() => {+ expect(db.collections.channels.get("existing")).toMatchObject({+ position: 7,+ muted: true,+ preview: "keep preview",+ lastMessageAt: "2026-09-28T00:00:07.000Z",+ lastUnreadSeq: 7,+ })+ expect(db.collections.channels.get("new")).toMatchObject({+ position: 1,+ muted: false,+ preview: "",+ lastMessageAt: "2026-09-28T00:00:08.000Z",+ lastUnreadSeq: 8,+ })+ })+ })++ it("updates every affected scope when attention items are removed", async () => {+ const db = await registry()+ const scope = (+ scopeId: string,+ ordinaryUnread: boolean,+ attentionCount: number,+ ) => ({+ scopeId,+ channelId: scopeId,+ serverId: "s1",+ parentChannelId: null,+ ordinaryUnread,+ lastUnreadSeq: 9,+ lastAttentionSeq: 9,+ attentionCount,+ })+ const attentionItem = (scopeId: string, sourceId: string, kind: "mention" | "reply") => ({+ id: `${kind}:${sourceId}`,+ kind,+ sourceId,+ scopeId,+ messageId: `message:${sourceId}`,+ actorUserId: "actor",+ createdAt: "2026-09-28T00:00:09.000Z",+ })+ const snapshot = {+ scopes: [+ scope("multiple", false, 2),+ scope("attention-only", false, 1),+ scope("ordinary", true, 1),+ ],+ items: [+ attentionItem("multiple", "remove", "mention"),+ attentionItem("multiple", "keep", "reply"),+ attentionItem("attention-only", "final", "mention"),+ attentionItem("ordinary", "ordinary-final", "reply"),+ ],+ limit: 100,+ truncated: false,+ }+ ingestAttentionSnapshot(db, snapshot)++ removeAttentionItemsOptimistically(+ db,+ (entry) => entry.sourceId !== "keep",+ )+ const token = captureCommunityLiveSnapshotToken(db.queryClient)+ expect(publishAccountAttentionSnapshot(db.queryClient, {+ snapshot,+ proof: { token, signal: undefined },+ })).toBe("published")++ await vi.waitFor(() => {+ expect(db.collections.attentionScopes.get("multiple")).toMatchObject({+ attentionCount: 1,+ lastAttentionSeq: 9,+ })+ expect(db.collections.attentionItems.get("reply:keep")).toBeDefined()+ expect(db.collections.attentionScopes.get("attention-only")).toBeUndefined()+ expect(db.collections.attentionScopes.get("ordinary")).toMatchObject({+ ordinaryUnread: true,+ attentionCount: 0,+ lastAttentionSeq: null,+ })+ })})it("does not roll back an optimistic clear started before or during a snapshot GET", async () => {@@ -1325,45 +1472,40 @@ describe("community DB sync", () => {attentionCount: 1,})expect(db.collections.attentionItems.get(newItem.id)).toMatchObject(newItem)- projectAttentionUnreadBump(db.queryClient, {- type: "community:unread.bump",- userId: "viewer",- channelId: "c1",- serverId: "s1",- isMention: true,- }, { seq: 4 })- projectAttentionMentionHint(db.queryClient, {- type: "community:mention.create",- userId: "viewer",- channelId: "c1",- messageId: "m4",- authorName: "Peer",- })- expect(db.collections.attentionScopes.get("c1")?.attentionCount).toBe(1)- expect(db.collections.attentionItems.get("pending:m4")).toBeUndefined()-if (terminal === "success") {ingestAttentionSnapshot(db, truncatedSnapshot)commitAttentionScopeOptimisticSnapshot(db, optimistic)expect(db.collections.attentionScopes.get("c1")?.attentionCount).toBe(1)} else {- projectAttentionUnreadBump(db.queryClient, {- type: "community:unread.bump",- userId: "viewer",- channelId: "c1",- serverId: "s1",- isMention: true,- }, { seq: 6 })- projectAttentionMentionHint(db.queryClient, {- type: "community:mention.create",- userId: "viewer",- channelId: "c1",- messageId: "m6",- authorName: "Peer",+ const newerSnapshot = {+ scopes: [{+ ...truncatedSnapshot.scopes[0]!,+ lastUnreadSeq: 6,+ lastAttentionSeq: 6,+ attentionCount: 2,+ }],+ items: [newItem, {+ id: "mention:m6",+ kind: "mention" as const,+ sourceId: "m6",+ scopeId: "c1",+ messageId: "m6",+ actorUserId: "u2",+ createdAt: "2026-09-27T01:02:00.000Z",+ }],+ limit: 100,+ truncated: true,+ included: { servers: [], channels: [], dms: [], profiles: [], messages: [] },+ }+ const reconcileToken = captureCommunityLiveSnapshotToken(db.queryClient)+ publishAccountAttentionSnapshot(db.queryClient, {+ snapshot: newerSnapshot,+ proof: { token: reconcileToken },})- expect(restoreAttentionScopeOptimisticSnapshot(db, optimistic)).toBe(false)+ expect(restoreAttentionScopeOptimisticSnapshot(db, optimistic)).toBe(true)+ ingestAttentionSnapshot(db, newerSnapshot)expect(db.collections.attentionScopes.get("c1")?.attentionCount).toBe(2)- expect(db.collections.attentionItems.get("pending:m6")).toMatchObject({+ expect(db.collections.attentionItems.get("mention:m6")).toMatchObject({messageId: "m6",})}@@ -1458,7 +1600,8 @@ describe("community DB sync", () => {actorUserId: "u2",createdAt: `2026-09-27T01:0${seq}:00.000Z`,}))- ingestAttentionSnapshot(db, {+ const reconcileToken = captureCommunityLiveSnapshotToken(db.queryClient)+ publishAccountAttentionSnapshot(db.queryClient, { snapshot: {scopes: [{scopeId: "c1",channelId: "c1",@@ -1472,7 +1615,8 @@ describe("community DB sync", () => {items,limit: 100,truncated: false,- })+ included: { servers: [], channels: [], dms: [], profiles: [], messages: [] },+ }, proof: { token: reconcileToken } })const oldest = clearAttentionScopeOptimistically(db, "c1", 4)const middle = clearAttentionScopeOptimistically(db, "c1", 5)const newest = clearAttentionScopeOptimistically(db, "c1", 6)@@ -1484,7 +1628,7 @@ describe("community DB sync", () => {expect(db.collections.attentionItems.get("mention:6")).toBeDefined()})- it("preserves a higher-seq WS scope and item when the older optimistic read fails", async () => {+ it("preserves a higher-seq authoritative scope and item when an older optimistic read fails", async () => {const db = await registry()ingestMessages(db, "c1", [{id: "m5",@@ -1517,28 +1661,39 @@ describe("community DB sync", () => {truncated: false,})const optimistic = clearAttentionScopeOptimistically(db, "c1", 4)- projectAttentionUnreadBump(db.queryClient, {- type: "community:unread.bump",- userId: "viewer",- channelId: "c1",- serverId: "s1",- isMention: true,- }, { seq: 5 })- projectAttentionMentionHint(db.queryClient, {- type: "community:mention.create",- userId: "viewer",- channelId: "c1",- messageId: "m5",- authorName: "Peer",- })+ const newerSnapshot = {+ scopes: [{+ scopeId: "c1",+ channelId: "c1",+ serverId: "s1",+ parentChannelId: null,+ ordinaryUnread: true,+ lastUnreadSeq: 5,+ lastAttentionSeq: 5,+ attentionCount: 1,+ }],+ items: [{+ id: "mention:m5",+ kind: "mention",+ sourceId: "m5",+ scopeId: "c1",+ messageId: "m5",+ actorUserId: "u2",+ createdAt: "2026-09-27T01:01:00.000Z",+ }],+ limit: 100,+ truncated: false,+ }+ ingestAttentionSnapshot(db, newerSnapshot)- expect(restoreAttentionScopeOptimisticSnapshot(db, optimistic)).toBe(false)+ expect(restoreAttentionScopeOptimisticSnapshot(db, optimistic)).toBe(true)+ ingestAttentionSnapshot(db, newerSnapshot)expect(db.collections.attentionScopes.get("c1")).toMatchObject({lastUnreadSeq: 5,lastAttentionSeq: 5,attentionCount: 1,})- expect(db.collections.attentionItems.get("pending:m5")).toMatchObject({+ expect(db.collections.attentionItems.get("mention:m5")).toMatchObject({messageId: "m5",})expect(db.collections.attentionItems.get("mention:old")).toBeUndefined()diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.tsindex 642c9ec61..79a0a132d 100644--- a/src/web/src/lib/community-db/sync.ts+++ b/src/web/src/lib/community-db/sync.ts@@ -861,6 +861,8 @@ function ingestChannelMetadata(creatorId: string | nullarchived: boolean | numberlastMessageAt: string | null+ openerSeq?: number+ openerUnread?: boolean},) {if (!(["text", "forum", "thread"] as const).includes(metadata.type as "text")) return@@ -883,6 +885,8 @@ function ingestChannelMetadata(tags: existing?.tags ?? [],pending: false,lastMessageAt: metadata.lastMessageAt,+ ...(metadata.openerSeq === undefined ? {} : { openerSeq: metadata.openerSeq }),+ ...(metadata.openerUnread === undefined ? {} : { openerUnread: metadata.openerUnread }),}])}@@ -1053,16 +1057,105 @@ export function ingestReadStateSnapshot(function ingestAttentionIncluded(registry: CommunityDbRegistry,- included: AccountAttentionSnapshot["included"],+ included: Partial<AccountAttentionSnapshot["included"]> | undefined,) {- if (!included) return- const profiles = profileSchema.array().safeParse(included.profiles ?? [])+ const existingServers = new Map(+ collectionRows(registry, "servers", serverSchema).map((row) => [row.id, row]),+ )+ const existingChannels = new Map(+ collectionRows(registry, "channels", channelSchema).map((row) => [row.id, row]),+ )+ const viewerId = registry.accountId+ const servers: ServerRow[] = (included?.servers ?? []).map((owner, position) => {+ const existing = existingServers.get(owner.id)+ return {+ id: owner.id,+ position: existing?.position ?? position,+ name: owner.name,+ discriminator: owner.discriminator,+ description: existing?.description ?? "",+ ownerId: existing?.ownerId ?? "",+ icon: existing?.icon ?? null,+ official: existing?.official ?? false,+ isOwner: existing?.isOwner ?? false,+ unread: existing?.unread ?? false,+ mentions: existing?.mentions ?? 0,+ detailComplete: existing?.detailComplete ?? false,+ }+ })+ upsertRows(registry, "servers", serverSchema, (row) => row.id, servers)+ for (const channel of included?.channels ?? []) ingestChannelMetadata(registry, channel)+ const dmChannels: ChannelRow[] = (included?.dms ?? []).map((dm, position) => {+ const existing = existingChannels.get(dm.id)+ return {+ id: dm.id,+ serverId: null,+ categoryId: null,+ name: "",+ type: "dm",+ parentChannelId: null,+ parentMessageId: null,+ creatorId: null,+ position: existing?.position ?? position,+ archived: false,+ muted: existing?.muted ?? false,+ unread: true,+ tags: [],+ pending: false,+ lastMessageAt: dm.lastMessageAt,+ preview: existing?.preview ?? "",+ lastUnreadSeq: dm.lastUnreadSeq,+ }+ })+ upsertRows(registry, "channels", channelSchema, (row) => row.id, dmChannels)+ if (viewerId) {+ upsertRows(+ registry,+ "serverMemberships",+ serverMembershipSchema,+ (row) => row.id,+ servers.map((server) => ({+ id: serverMembershipKey(server.id, viewerId),+ serverId: server.id,+ userId: viewerId,+ role: server.isOwner ? "owner" : "member",+ viewer: true,+ })),+ )+ upsertRows(+ registry,+ "channelMemberships",+ channelMembershipSchema,+ (row) => row.id,+ [+ ...(included?.channels ?? []).map((channel) => ({+ id: channelMembershipKey(channel.id, viewerId, "access"),+ channelId: channel.id,+ userId: viewerId,+ relation: "access" as const,+ source: "inherited" as const,+ })),+ ...(included?.dms ?? []).flatMap((dm) => [{+ id: channelMembershipKey(dm.id, viewerId, "access"),+ channelId: dm.id,+ userId: viewerId,+ relation: "access" as const,+ }, {+ id: channelMembershipKey(dm.id, dm.userId, "access"),+ channelId: dm.id,+ userId: dm.userId,+ relation: "access" as const,+ }]),+ ],+ )+ }+ const profiles = profileSchema.array().safeParse(included?.profiles ?? [])if (profiles.success) {writeCommunityProfilePatches(profiles.data.map((profile) => (communityUserProfilePatch(profile.userId, profile))), registry)}- const messages = messageSchema.array().safeParse(included.messages ?? [])+ const messages = messageSchema.array().safeParse(included?.messages ?? [])if (messages.success) {const current = new Map(collectionRows(registry, "messages", messageSchema).map((row) => [row.id, row]),@@ -1085,10 +1178,6 @@ type AttentionProtectionState = {requiresReconcileOnRestore: boolean}>optimisticItemDeletes: Map<symbol, Set<string>>- heldScopes: Set<string>- heldItems: Set<string>- heldScopeDeletes: Set<string>- heldItemDeletes: Set<string>}const attentionProtectionStates = new WeakMap<QueryClient, AttentionProtectionState>()@@ -1100,10 +1189,6 @@ function attentionProtectionState(queryClient: QueryClient) {optimisticClears: new Set(),optimisticScopeDeletes: new Map(),optimisticItemDeletes: new Map(),- heldScopes: new Set(),- heldItems: new Set(),- heldScopeDeletes: new Set(),- heldItemDeletes: new Set(),}attentionProtectionStates.set(queryClient, state)}@@ -1124,49 +1209,12 @@ export function ingestAttentionSnapshot(snapshot: AccountAttentionSnapshot,) {const protection = attentionProtectionState(registry.queryClient)- const currentScopes = new Map(- collectionRows(registry, "attentionScopes", attentionScopeSchema)- .map((row) => [row.scopeId, row]),- )- const currentItems = new Map(- collectionRows(registry, "attentionItems", attentionItemSchema)- .map((row) => [row.id, row]),- )const scopesById = new Map<string, AttentionScopeRow>(snapshot.scopes.map((row) => [row.scopeId, { ...row }]),)const itemsById = new Map<string, AttentionItemRow>(snapshot.items.map((row) => [row.id, { ...row }]),)- const finalizedMessageIds = new Set(snapshot.items.flatMap((item) => (- item.messageId ? [item.messageId] : []- )))-- // A local WS hint survives one snapshot that does not yet acknowledge it.- // The endpoint is primary-authoritative, so one retry is sufficient while- // still allowing a later snapshot to remove a genuinely obsolete hint.- for (const scopeId of protection.heldScopes) {- if (!scopesById.has(scopeId)) {- const current = currentScopes.get(scopeId)- if (current) scopesById.set(scopeId, current)- }- protection.heldScopes.delete(scopeId)- }- for (const itemId of protection.heldItems) {- const current = currentItems.get(itemId)- const finalized = current?.messageId && finalizedMessageIds.has(current.messageId)- if (!finalized && !itemsById.has(itemId) && current) itemsById.set(itemId, current)- protection.heldItems.delete(itemId)- }- for (const scopeId of protection.heldScopeDeletes) {- scopesById.delete(scopeId)- protection.heldScopeDeletes.delete(scopeId)- }- for (const itemId of protection.heldItemDeletes) {- itemsById.delete(itemId)- protection.heldItemDeletes.delete(itemId)- }-const optimisticClear = protection.optimisticClears.size > 0const optimisticScopeDeletes = [...protection.optimisticScopeDeletes.values()]const optimisticItemDeletes = new Set(@@ -1193,11 +1241,33 @@ export function ingestAttentionSnapshot(if (!fenced) continuefencedItems.add(item.id)}+ const itemDeleteCountsByScope = new Map<string, number>()+ for (const item of itemsById.values()) {+ if (+ !optimisticItemDeletes.has(item.id)+ || !item.scopeId+ || item.kind !== "mention" && item.kind !== "reply"+ ) continue+ itemDeleteCountsByScope.set(+ item.scopeId,+ (itemDeleteCountsByScope.get(item.scopeId) ?? 0) + 1,+ )+ }const scopes = optimisticClear ? [] : [...scopesById.values()].flatMap((scope) => {const targetSeq = optimisticScopeDeletes.reduce((target, entry) => (entry.scopeId === scope.scopeId ? Math.max(target, entry.targetSeq) : target), -1)- if (targetSeq < 0) return [scope]+ if (targetSeq < 0) {+ const deletedAttentionCount = itemDeleteCountsByScope.get(scope.scopeId) ?? 0+ if (deletedAttentionCount === 0) return [scope]+ const attentionCount = Math.max(0, scope.attentionCount - deletedAttentionCount)+ if (!scope.ordinaryUnread && attentionCount === 0) return []+ return [{+ ...scope,+ attentionCount,+ lastAttentionSeq: attentionCount === 0 ? null : scope.lastAttentionSeq,+ }]+ }const clearedAttentionCount = optimisticScopeDeletes.reduce((count, entry) => (entry.scopeId === scope.scopeId ? count + entry.clearedAttentionCount : count), 0)@@ -1246,8 +1316,6 @@ export function clearAttentionOptimistically(}const protection = attentionProtectionState(registry.queryClient)protection.optimisticClears.add(token)- protection.heldScopes.clear()- protection.heldItems.clear()withCanonicalWriteContext(registry.queryClient, { kind: "event" }, () => {notifyManager.batch(() => {deleteRows(registry, "attentionScopes", attentionScopeSchema, () => true)@@ -1510,6 +1578,7 @@ export function restoreAttentionScopeOptimisticSnapshot(export type AttentionItemsOptimisticSnapshot = {token: symbolpublicationRevision: number+ scopes: AttentionScopeRow[]items: AttentionItemRow[]}@@ -1517,16 +1586,56 @@ export function removeAttentionItemsOptimistically(registry: CommunityDbRegistry,remove: (item: AttentionItemRow) => boolean,): AttentionItemsOptimisticSnapshot {- const items = collectionRows(registry, "attentionItems", attentionItemSchema).filter(remove)+ const allItems = collectionRows(registry, "attentionItems", attentionItemSchema)+ const items = allItems.filter(remove)+ const removedMentionCountByScope = new Map<string, number>()+ for (const item of items) {+ if (!item.scopeId || item.kind !== "mention" && item.kind !== "reply") continue+ removedMentionCountByScope.set(+ item.scopeId,+ (removedMentionCountByScope.get(item.scopeId) ?? 0) + 1,+ )+ }+ const scopes = collectionRows(registry, "attentionScopes", attentionScopeSchema)+ .filter((scope) => removedMentionCountByScope.has(scope.scopeId))const token = Symbol("attention-item-delete")const protection = attentionProtectionState(registry.queryClient)protection.optimisticItemDeletes.set(token, new Set(items.map((item) => item.id)))withCanonicalWriteContext(registry.queryClient, { kind: "event" }, () => {- deleteRows(registry, "attentionItems", attentionItemSchema, remove)+ notifyManager.batch(() => {+ for (const scope of scopes) {+ const attentionCount = Math.max(+ 0,+ scope.attentionCount - (removedMentionCountByScope.get(scope.scopeId) ?? 0),+ )+ if (!scope.ordinaryUnread && attentionCount === 0) {+ deleteRows(+ registry,+ "attentionScopes",+ attentionScopeSchema,+ (row) => row.scopeId === scope.scopeId,+ )+ } else {+ upsertRows(+ registry,+ "attentionScopes",+ attentionScopeSchema,+ (row) => row.scopeId,+ [{+ ...scope,+ attentionCount,+ lastAttentionSeq: attentionCount === 0 ? null : scope.lastAttentionSeq,+ }],+ )+ }+ }+ deleteRows(registry, "attentionItems", attentionItemSchema, remove)+ })})return {token,publicationRevision: canonicalRevisionState(registry.queryClient).revision,+ scopes,items,}}@@ -1545,7 +1654,10 @@ export function restoreAttentionItemsOptimisticSnapshot(attentionProtectionState(registry.queryClient).optimisticItemDeletes.delete(snapshot.token)if (canonicalRevisionState(registry.queryClient).revision !== snapshot.publicationRevision) return falsewithCanonicalWriteContext(registry.queryClient, { kind: "event" }, () => {- upsertRows(registry, "attentionItems", attentionItemSchema, (row) => row.id, snapshot.items)+ notifyManager.batch(() => {+ upsertRows(registry, "attentionScopes", attentionScopeSchema, (row) => row.scopeId, snapshot.scopes)+ upsertRows(registry, "attentionItems", attentionItemSchema, (row) => row.id, snapshot.items)+ })})return true}@@ -2284,115 +2396,6 @@ function projectProfilePatch(writeCommunityProfilePatches([{ id: userId, ...patch }], registry, { event: true })}-export function projectAttentionUnreadBump(- queryClient: QueryClient,- event: Extract<CommunityWsEvent, { type: "community:unread.bump" }>,- evidence?: { seq: number },-) {- const registry = getCommunityDbRegistry(queryClient)- if (!registry || event.userId !== registry.accountId) return- const current = collectionRows(registry, "attentionScopes", attentionScopeSchema)- .find((row) => row.scopeId === event.channelId)- const seq = evidence?.seq ?? current?.lastUnreadSeq ?? 0- if (hasAttentionScopeOptimisticFence(queryClient, event.channelId, seq)) return- const next: AttentionScopeRow = {- scopeId: event.channelId,- channelId: event.channelId,- serverId: event.serverId ?? current?.serverId ?? null,- parentChannelId: current?.parentChannelId ?? null,- ordinaryUnread: true,- lastUnreadSeq: Math.max(current?.lastUnreadSeq ?? 0, seq),- lastAttentionSeq: event.isMention- ? Math.max(current?.lastAttentionSeq ?? 0, seq)- : current?.lastAttentionSeq ?? null,- attentionCount: (current?.attentionCount ?? 0) + (event.isMention ? 1 : 0),- }- withCanonicalWriteContext(queryClient, { kind: "event" }, () => {- upsertRows(registry, "attentionScopes", attentionScopeSchema, (row) => row.scopeId, [next])- })- attentionProtectionState(queryClient).heldScopes.add(event.channelId)-}--export function projectAttentionMentionHint(- queryClient: QueryClient,- event: Extract<CommunityWsEvent, { type: "community:mention.create" }>,- evidence?: { createdAt: string },-) {- const registry = getCommunityDbRegistry(queryClient)- if (!registry || event.userId !== registry.accountId || !event.channelId) return- const message = collectionRows(registry, "messages", messageSchema)- .find((row) => row.id === event.messageId)- if (!message?.authorId) return- if (- message.seq !== undefined- && hasAttentionScopeOptimisticFence(queryClient, event.channelId, message.seq)- ) return- const id = `pending:${event.messageId}`- const item: AttentionItemRow = {- id,- kind: "pending",- sourceId: event.messageId,- scopeId: event.channelId,- messageId: event.messageId,- actorUserId: message.authorId,- createdAt: evidence?.createdAt ?? message.createdAt ?? new Date().toISOString(),- }- withCanonicalWriteContext(queryClient, { kind: "event" }, () => {- upsertRows(registry, "attentionItems", attentionItemSchema, (row) => row.id, [item])- })- attentionProtectionState(queryClient).heldItems.add(id)-}--export function projectAttentionFriendEvent(- queryClient: QueryClient,- event: Extract<CommunityWsEvent, {- type:- | "community:friend.request"- | "community:friend.accept"- | "community:friend.reject"- | "community:friend.remove"- | "community:friend.block"- }>,-) {- const registry = getCommunityDbRegistry(queryClient)- if (!registry) return- const protection = attentionProtectionState(queryClient)- if (event.type === "community:friend.request") {- if (event.friendship.addresseeId !== registry.accountId) return- const item: AttentionItemRow = {- id: `friend_request:${event.friendship.id}`,- kind: "friend_request",- sourceId: event.friendship.id,- scopeId: null,- messageId: null,- actorUserId: event.friendship.requesterId,- createdAt: event.friendship.createdAt,- }- withCanonicalWriteContext(queryClient, { kind: "event" }, () => {- upsertRows(registry, "attentionItems", attentionItemSchema, (row) => row.id, [item])- })- protection.heldItems.add(item.id)- return- }- const removed = collectionRows(registry, "attentionItems", attentionItemSchema)- .filter((item) => item.kind === "friend_request" && (- event.type === "community:friend.block"- ? item.actorUserId === event.userId- : item.sourceId === event.friendshipId- ))- .map((item) => item.id)- if (removed.length === 0) return- withCanonicalWriteContext(queryClient, { kind: "event" }, () => {- deleteRows(- registry,- "attentionItems",- attentionItemSchema,- (item) => removed.includes(item.id),- )- })- for (const id of removed) protection.heldItemDeletes.add(id)-}-/*** Applies low-latency WS facts directly to the canonical account-scoped* collections. Existing React Query handlers still own reconciliation anddiff --git a/src/web/src/lib/community/inbox-unread-count.test.ts b/src/web/src/lib/community/inbox-unread-count.test.tsdeleted file mode 100644index 3286f132e..000000000--- a/src/web/src/lib/community/inbox-unread-count.test.ts+++ /dev/null@@ -1,19 +0,0 @@-import { describe, expect, it } from "vitest"-import { inboxUnreadCount } from "./inbox-unread-count"-import type { Mention, UnreadDm, UnreadServer } from "./models/inbox"--describe("inboxUnreadCount", () => {- it("deduplicates mentions and pending arrivals without counting grouping parents", () => {- const servers = [{ serverId: "s", serverName: "S", channels: [- { channelId: "parent", hasDirectUnread: false, children: [{ channelId: "thread" }] },- { channelId: "direct", children: [] },- ] }] as UnreadServer[]- const mentions = [{ id: "m1", channelId: "thread" }, { id: "m2", channelId: "thread" }, { id: "m3", channelId: "mention-only" }] as Mention[]- expect(inboxUnreadCount({ servers, dms: [], mentions, pendingChannelIds: ["direct", "pending", "pending"], friendRequestCount: 2 })).toBe(6)- })-- it("counts DMs, legacy mentions and clears when projected feeds clear", () => {- expect(inboxUnreadCount({ servers: [], dms: [{ channelId: "dm" }] as UnreadDm[], mentions: [{ id: "legacy" }] as Mention[], friendRequestCount: 1 })).toBe(3)- expect(inboxUnreadCount({ servers: [], dms: [], mentions: [], friendRequestCount: 0 })).toBe(0)- })-})diff --git a/src/web/src/lib/community/inbox-unread-count.ts b/src/web/src/lib/community/inbox-unread-count.tsdeleted file mode 100644index a6519d7d1..000000000--- a/src/web/src/lib/community/inbox-unread-count.ts+++ /dev/null@@ -1,20 +0,0 @@-import type { Mention, UnreadDm, UnreadServer } from "./models/inbox"--export function inboxUnreadCount({ servers, dms, mentions, friendRequestCount, pendingChannelIds = [] }: {- servers: UnreadServer[]- dms: UnreadDm[]- mentions: Mention[]- friendRequestCount: number- pendingChannelIds?: string[]-}) {- const conversations = new Set(pendingChannelIds)- for (const server of servers) {- for (const channel of server.channels) {- if (channel.hasDirectUnread !== false) conversations.add(channel.channelId)- for (const child of channel.children) conversations.add(child.channelId)- }- }- for (const dm of dms) conversations.add(dm.channelId)- for (const mention of mentions) conversations.add(mention.channelId ?? `mention:${mention.id}`)- return conversations.size + friendRequestCount-}diff --git a/src/web/src/test/e2e-ui/04-dm.spec.ts b/src/web/src/test/e2e-ui/04-dm.spec.tsindex 93db975c4..42acbf7c2 100644--- a/src/web/src/test/e2e-ui/04-dm.spec.ts+++ b/src/web/src/test/e2e-ui/04-dm.spec.ts@@ -17,10 +17,6 @@ test.describe.serial("direct messages", () => {const proxy = await gotoAfterNotificationStartup(bob.page, bob.context, trace)trace.phase("notification")- let releaseCanonical!: () => void- let canonicalFinished!: () => void- const canonicalGate = new Promise<void>((resolve) => { releaseCanonical = resolve })- const canonicalSettled = new Promise<void>((resolve) => { canonicalFinished = resolve })let dmsGets = 0const dmsPattern = "**/api/community/users/me/dms"await bob.page.route(dmsPattern, async (route) => {@@ -29,14 +25,7 @@ test.describe.serial("direct messages", () => {return}dmsGets += 1- try {- await canonicalGate- await route.continue()- } catch (error) {- if (!(error instanceof Error && error.message.includes("already handled"))) throw error- } finally {- canonicalFinished()- }+ await route.continue()})const notificationRefresh = notificationResponsesFinished(@@ -49,9 +38,7 @@ test.describe.serial("direct messages", () => {await expect.poll(() => trace.events.some((event) =>event.type === "community:unread.bump" && event.channelId === dmId && event.userId === userId("bob"))).toBe(true)await notificationRefresh- await expect.poll(() => dmsGets).toBe(1)- releaseCanonical()- await canonicalSettled+ expect(dmsGets).toBe(0)const routeHistory: string[] = []const recordRoute = (frame: Frame) => {if (frame === bob.page.mainFrame()) routeHistory.push(new URL(frame.url()).pathname)@@ -64,7 +51,7 @@ test.describe.serial("direct messages", () => {await expect(inboxRow).toBeVisible({ timeout: 20_000 })trace.phase("click")const dmsGetsBeforeClick = dmsGets- expect(dmsGetsBeforeClick).toBe(1)+ expect(dmsGetsBeforeClick).toBe(0)await inboxRow.click()await bob.page.waitForURL(new RegExp(`/c/me/${dmId}$`), {@@ -84,8 +71,6 @@ test.describe.serial("direct messages", () => {trace.phase("click-complete")expect(dmsGets - dmsGetsBeforeClick).toBe(0)} finally {- releaseCanonical()- await canonicalSettledbob.page.off("framenavigated", recordRoute)await bob.page.unroute(dmsPattern)await testInfo.attach("community-request-timeline", {@@ -229,13 +214,14 @@ test.describe.serial("direct messages", () => {})await expect(verificationAlert).toBeVisible()await expect(alice.page).toHaveURL(new RegExp(`/c/me/${missingDmId}$`))- await expect.poll(() => canonicalDmsGets).toBeGreaterThanOrEqual(2)+ await expect.poll(() => canonicalDmsGets).toBe(1)await expect(verificationAlert).toBeVisible()await expect(alice.page).toHaveURL(new RegExp(`/c/me/${missingDmId}$`))expect(authorityDmsGets).toBe(1)await verificationAlert.getByRole("button", { name: "Retry" }).click()await expect.poll(() => authorityDmsGets).toBe(2)+ expect(canonicalDmsGets).toBe(1)await expect.poll(() => new URL(alice.page.url()).pathname).toBe("/c/me/friends")} finally {wsProxy.releaseHeldConnections()diff --git a/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts b/src/web/src/test/e2e-ui/34-inbox-read-race.spec.tsindex a6bdc7878..f9cbcee37 100644--- a/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts+++ b/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts@@ -315,7 +315,7 @@ test.describe.serial("Inbox/read refresh ownership", () => {expect(puts).toBe(2)})- test("a cold forum opener aggregate uses the canonical parent row", async ({ asUser }) => {+ test("cold forum openers publish exact child units and read only the selected opener", async ({ asUser }) => {const stamp = Date.now()const serverId = await seedServer("alice", `Inbox opener handoff ${stamp}`)const forumId = await seedChannel("alice", serverId, `handoff-forum-${stamp}`, "forum")@@ -334,23 +334,21 @@ test.describe.serial("Inbox/read refresh ownership", () => {const { page } = await asUser("bob")await gotoAfterUserWsAuth(page, "/c/me")- const unreadResponse = await page.request.get("/api/community/users/me/inbox/unreads")+ const unreadResponse = await page.request.get("/api/community/users/me/attention")expect(unreadResponse.status()).toBe(200)const unread = await unreadResponse.json() as {- servers: Array<{ channels: Array<{ channelId: string; children: Array<{- channelId: string- openerMessageId: string- openerSeq: number- openerUnread: boolean- }> }> }>+ items: Array<{+ kind: string+ childChannelId?: string+ messageId?: string+ openerSeq?: number+ }>}- const children = unread.servers- .flatMap((server) => server.channels)- .find((channel) => channel.channelId === forumId)?.children ?? []- const first = children.find((child) => child.channelId === firstChildId)- const later = children.find((child) => child.channelId === laterChildId)- expect(first).toMatchObject({ openerUnread: true })- expect(later).toMatchObject({ openerUnread: true })+ const forumItems = unread.items.filter((item) => item.kind === "forum_post")+ const first = forumItems.find((item) => item.childChannelId === firstChildId)+ const later = forumItems.find((item) => item.childChannelId === laterChildId)+ expect(first).toMatchObject({ childChannelId: firstChildId })+ expect(later).toMatchObject({ childChannelId: laterChildId })await page.setViewportSize({ width: 768, height: 844 })@@ -368,25 +366,26 @@ test.describe.serial("Inbox/read refresh ownership", () => {await page.getByRole("button", { name: "Inbox", exact: true }).click()await expect(page.getByTestId(tid.inboxUnreadChannel(forumId))).toBeVisible()- await expect(page.getByTestId(tid.inboxUnreadChild(firstChildId))).toHaveCount(0)- await expect(page.getByTestId(tid.inboxUnreadChild(laterChildId))).toHaveCount(0)+ await expect(page.getByTestId(tid.inboxUnreadChild(firstChildId))).toBeVisible()+ await expect(page.getByTestId(tid.inboxUnreadChild(laterChildId))).toBeVisible()const parentRead = page.waitForResponse((response) => (response.request().method() === "PUT"&& new URL(response.url()).pathname === `/api/community/channels/${forumId}/read`))- await page.getByTestId(tid.inboxUnreadChannel(forumId)).click()+ await page.getByTestId(tid.inboxUnreadChild(firstChildId)).click()expect((await parentRead).status()).toBe(200)- await expect.poll(() => new URL(page.url()).searchParams.has("inboxThreadOpener")).toBe(false)- expect(parentTargets).toEqual([later!.openerMessageId])+ expect(parentTargets).toEqual([first!.messageId])expect(childTargets).toEqual([])await page.getByRole("button", { name: "Inbox", exact: true }).click()- await expect(page.getByTestId(tid.inboxUnreadChannel(forumId))).toHaveCount(0)+ await expect(page.getByTestId(tid.inboxUnreadChannel(forumId))).toBeVisible()+ await expect(page.getByTestId(tid.inboxUnreadChild(firstChildId))).toHaveCount(0)+ await expect(page.getByTestId(tid.inboxUnreadChild(laterChildId))).toBeVisible()const snapshot = await (await page.request.get("/api/community/users/me/read-state",)).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }expect(snapshot.readStates.find((row) => row.channelId === forumId)?.lastReadSeq)- .toBe(later!.openerSeq)+ .toBe(first!.openerSeq)expect(snapshot.readStates.some((row) => row.channelId === firstChildId)).toBe(false)})@@ -423,30 +422,31 @@ test.describe.serial("Inbox/read refresh ownership", () => {await page.setViewportSize({ width: 768, height: 844 })await gotoAfterUserWsAuth(page, "/c/me")- const unreadResponse = await page.request.get("/api/community/users/me/inbox/unreads")+ const unreadResponse = await page.request.get("/api/community/users/me/attention")expect(unreadResponse.status()).toBe(200)const unread = await unreadResponse.json() as {- servers: Array<{ channels: Array<{ channelId: string; lastUnreadSeq?: number; children: Array<{- channelId: string- openerMessageId?: string+ scopes: Array<{ channelId: string; lastUnreadSeq: number }>+ included: { channels: Array<{+ id: string+ parentChannelId: string | null+ parentMessageId: string | nullopenerSeq?: numberopenerUnread?: boolean- }> }> }>+ }> }}- const parent = unread.servers- .flatMap((server) => server.channels)- .find((channel) => channel.channelId === parentId)- const readChild = parent?.children.find((child) => child.channelId === readChildId)- const unreadChild = parent?.children.find((child) => child.channelId === unreadChildId)+ const parent = unread.scopes.find((scope) => scope.channelId === parentId)+ const children = unread.included.channels.filter((channel) => channel.parentChannelId === parentId)+ const readChild = children.find((child) => child.id === readChildId)+ const unreadChild = children.find((child) => child.id === unreadChildId)expect(readChild).toMatchObject({- openerMessageId: readOpenerId,+ parentMessageId: readOpenerId,openerUnread: false,})expect(unreadChild).toMatchObject({- openerMessageId: unreadOpenerId,+ parentMessageId: unreadOpenerId,openerUnread: true,})- expect(parent?.children.some((child) => child.channelId === nonParticipantChildId)).toBe(false)+ expect(children.some((child) => child.id === nonParticipantChildId)).toBe(false)const beforeSnapshot = await (await page.request.get("/api/community/users/me/read-state",)).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }@@ -464,8 +464,8 @@ test.describe.serial("Inbox/read refresh ownership", () => {await page.getByRole("button", { name: "Inbox", exact: true }).click()await expect(page.getByTestId(tid.inboxUnreadChannel(parentId))).toBeVisible()- await expect(page.getByTestId(tid.inboxUnreadChild(readChildId))).toHaveCount(0)- await expect(page.getByTestId(tid.inboxUnreadChild(unreadChildId))).toHaveCount(0)+ await expect(page.getByTestId(tid.inboxUnreadChild(readChildId))).toBeVisible()+ await expect(page.getByTestId(tid.inboxUnreadChild(unreadChildId))).toBeVisible()const parentPut = page.waitForResponse((response) => (response.request().method() === "PUT"&& new URL(response.url()).pathname === `/api/community/channels/${parentId}/read`@@ -473,9 +473,9 @@ test.describe.serial("Inbox/read refresh ownership", () => {await page.getByTestId(tid.inboxUnreadChannel(parentId)).click()expect((await parentPut).status()).toBe(200)await page.waitForTimeout(700)- expect(puts.filter((put) => put.channelId === parentId)).toEqual([- { channelId: parentId, target: laterParentMessageId },- ])+ const parentPuts = puts.filter((put) => put.channelId === parentId)+ expect(parentPuts.length).toBeGreaterThan(0)+ expect(parentPuts.at(-1)).toEqual({ channelId: parentId, target: laterParentMessageId })expect(puts.some((put) => put.channelId === readChildId)).toBe(false)expect(puts.some((put) => put.channelId === unreadChildId)).toBe(false)diff --git a/src/web/src/test/e2e-ui/_fixtures/community-notification-requests.ts b/src/web/src/test/e2e-ui/_fixtures/community-notification-requests.tsindex 9c40233ff..fa74cdc5d 100644--- a/src/web/src/test/e2e-ui/_fixtures/community-notification-requests.ts+++ b/src/web/src/test/e2e-ui/_fixtures/community-notification-requests.ts@@ -75,7 +75,7 @@ export async function gotoAfterNotificationStartup(trace.phase("auth-release")const authenticatedRefresh = notificationResponsesFinished(page,- notificationPaths.filter((path) => path.endsWith("/dms")),+ notificationPaths.filter((path) => path.endsWith("/attention")),)holdAuthentication = falseexpect(proxy.releaseHeldConnections((frame) => frame.type === "auth.ok")).toBe(1)