Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): unify account unread projection

Gener5b1f18ee8afc
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index 5e3ab7d12..e08b7ce07 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -54,6 +54,7 @@ export const SPEC_SECONDS = {
"39-mobile-composer-send.spec.ts": 45,
"40-mobile-server-header-hierarchy.spec.ts": 28,
"40-server-rail-unread.spec.ts": 60,
+ "41-account-unread-projection.spec.ts": 55,
"41-community-initial-load-module-skeletons.spec.ts": 30,
"42-versioned-avatar-identity.spec.ts": 50,
}
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index dae08896d..f0d06529d 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -70,7 +70,7 @@ describe("planE2eShards", () => {
expect(first).toHaveLength(E2E_SHARD_COUNT)
expect([...assigned].sort()).toEqual(specs)
expect(new Set(assigned).size).toBe(specs.length)
- expect(totals.sort((left, right) => left - right)).toEqual([369, 370, 373, 374, 374])
+ expect(totals.sort((left, right) => left - right)).toEqual([380, 382, 383, 385, 385])
expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)
})
diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.ts
index 39ae9ba18..1a535831f 100644
--- a/src/shared/src/db/queries/community/inbox.ts
+++ b/src/shared/src/db/queries/community/inbox.ts
@@ -33,6 +33,10 @@ export interface UnreadChannelRow {
export interface EligibleUnreadChannelRow extends UnreadChannelRow {
mentionCount: number;
+ /** Highest unread message sequence represented by this row. */
+ lastUnreadSeq: number;
+ /** Highest unread attention-bearing message sequence, when present. */
+ lastAttentionSeq: number | null;
}
export interface UnreadForumOpenerRow {
@@ -237,6 +241,8 @@ export async function listEligibleUnreadChannels(
parentChannelId: communityChannel.parentChannelId,
lastMessageAt: sql<string>`MAX(${communityMessage.createdAt})`,
mentionCount: sql<number>`SUM(CASE WHEN ${hasUnreadAttentionSql(userId, communityMessage.id)} THEN 1 ELSE 0 END)`,
+ lastUnreadSeq: sql<number>`MAX(${communityMessage.seq})`.mapWith(Number),
+ lastAttentionSeq: sql<number | null>`MAX(CASE WHEN ${hasUnreadAttentionSql(userId, communityMessage.id)} THEN ${communityMessage.seq} ELSE NULL END)`,
})
.from(communityMessage)
.innerJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))
@@ -546,6 +552,10 @@ export interface UnreadDmRow {
lastMessageAt: string;
}
+export interface EligibleUnreadDmRow extends UnreadDmRow {
+ lastUnreadSeq: number;
+}
+
/**
* Mirrors `isChannelUnread` for DMs (ref/id read-model seq unification).
*
@@ -657,7 +667,7 @@ export async function listUnreadDms(
export async function listEligibleUnreadDms(
db: Database,
userId: string
-): Promise<UnreadDmRow[]> {
+): Promise<EligibleUnreadDmRow[]> {
const selfRows = await db
.select({ channelId: communityChannelMember.channelId })
.from(communityChannelMember)
@@ -684,6 +694,7 @@ export async function listEligibleUnreadDms(
otherUserImage: user.image,
otherUserAvatarVersion: user.avatarVersion,
lastMessageAt: sql<string>`MAX(${communityMessage.createdAt})`,
+ lastUnreadSeq: sql<number>`MAX(${communityMessage.seq})`.mapWith(Number),
})
.from(communityMessage)
.innerJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))
diff --git a/src/shared/src/db/queries/community/server.ts b/src/shared/src/db/queries/community/server.ts
index 8b4906f72..fbce40763 100644
--- a/src/shared/src/db/queries/community/server.ts
+++ b/src/shared/src/db/queries/community/server.ts
@@ -281,6 +281,53 @@ export async function listUserServers(db: Database, userId: string) {
.orderBy(asc(communityServerMember.railOrder));
}
+/**
+ * Exact per-channel evidence behind the human server-rail mention aggregate.
+ * Keep this separate from `listUserServers` so the bot payload remains byte
+ * compatible while the human API can expose absorption fences.
+ */
+export async function listUnreadMentionSources(db: Database, userId: string) {
+ return db
+ .select({
+ serverId: communityChannel.serverId,
+ channelId: communityChannel.id,
+ count: count().as("count"),
+ lastSeq: sql<number>`MAX(${communityMessage.seq})`.mapWith(Number),
+ })
+ .from(communityMention)
+ .innerJoin(communityMessage, eq(communityMessage.id, communityMention.messageId))
+ .innerJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))
+ .leftJoin(
+ communityReadState,
+ and(
+ eq(communityReadState.userId, userId),
+ eq(communityReadState.channelId, communityChannel.id),
+ ),
+ )
+ .where(and(
+ eq(communityMention.userId, userId),
+ eq(communityMention.read, 0),
+ eq(communityMention.kind, MENTION_KIND.MENTION),
+ sql`${communityMessage.seq} > COALESCE(${communityReadState.lastReadSeq}, 0)`,
+ channelReadableSql(userId, {
+ id: communityChannel.id,
+ type: communityChannel.type,
+ serverId: communityChannel.serverId,
+ parentChannelId: communityChannel.parentChannelId,
+ }),
+ notificationEligibleSql(
+ userId,
+ {
+ id: communityChannel.id,
+ serverId: communityChannel.serverId,
+ parentChannelId: communityChannel.parentChannelId,
+ },
+ { id: communityMessage.id },
+ ),
+ ))
+ .groupBy(communityChannel.serverId, communityChannel.id)
+}
+
/**
* Resolve a server by unique handle, scoped to servers
* `userId` is a member of.
diff --git a/src/shared/test/queries/community-inbox.test.ts b/src/shared/test/queries/community-inbox.test.ts
index f8c42976e..819c76501 100644
--- a/src/shared/test/queries/community-inbox.test.ts
+++ b/src/shared/test/queries/community-inbox.test.ts
@@ -453,4 +453,10 @@ describe("listUnreadDms — seq read-watermark behaviour", () => {
const result = await inboxQueries.listUnreadDms(db, "u_viewer");
expect(result).toEqual([]);
});
+
+ it("returns no eligible DMs when the viewer has no DM memberships", async () => {
+ const db = createUnreadDmRowMock([]);
+
+ await expect(inboxQueries.listEligibleUnreadDms(db, "u_viewer")).resolves.toEqual([]);
+ });
});
diff --git a/src/shared/test/queries/param-limit.test.ts b/src/shared/test/queries/param-limit.test.ts
index 8eaa3eb7b..96c462688 100644
--- a/src/shared/test/queries/param-limit.test.ts
+++ b/src/shared/test/queries/param-limit.test.ts
@@ -209,7 +209,7 @@ describe("listEligibleUnreadChannels bound parameters", () => {
expect(statements.map(({ params }) => params.filter(
(value) => typeof value === "string" && value.startsWith("channel_"),
).length)).toEqual([80, 15]);
- expect(statements.map(({ params }) => params.length)).toEqual([91, 26]);
+ expect(statements.map(({ params }) => params.length)).toEqual([92, 27]);
for (const { params } of statements) {
expect(params.length).toBeLessThanOrEqual(D1_MAX_BIND_PARAMS);
}
diff --git a/src/shared/test/queries/server.test.ts b/src/shared/test/queries/server.test.ts
index 9e7d8c90e..e25c8551a 100644
--- a/src/shared/test/queries/server.test.ts
+++ b/src/shared/test/queries/server.test.ts
@@ -469,6 +469,45 @@ describe("listUserServers — mention aggregate for the rail badge", () => {
});
});
+describe("listUnreadMentionSources", () => {
+ it("returns grouped per-channel evidence through the policy joins", async () => {
+ const rows = [{ serverId: "srv_A", channelId: "ch_1", count: 2, lastSeq: 7 }];
+ const call: {
+ from?: unknown;
+ innerJoins: unknown[];
+ leftJoins: unknown[];
+ grouped?: unknown[];
+ } = { innerJoins: [], leftJoins: [] };
+ const chain: any = {};
+ chain.from = (table: unknown) => { call.from = table; return chain; };
+ chain.innerJoin = (table: unknown, condition: unknown) => {
+ call.innerJoins.push({ table, condition });
+ return chain;
+ };
+ chain.leftJoin = (table: unknown, condition: unknown) => {
+ call.leftJoins.push({ table, condition });
+ return chain;
+ };
+ chain.where = () => chain;
+ chain.groupBy = (...columns: unknown[]) => {
+ call.grouped = columns;
+ return Promise.resolve(rows);
+ };
+ const db = { select: vi.fn(() => chain) };
+
+ await expect(serverQueries.listUnreadMentionSources(db as any, "u_1"))
+ .resolves.toEqual(rows);
+ expect(call.from).toBe(communityMention);
+ expect(call.innerJoins.map((join: any) => join.table)).toEqual([
+ communityMessage,
+ communityChannel,
+ ]);
+ expect(call.leftJoins).toHaveLength(1);
+ expect((call.leftJoins[0] as any).table).toBe(communityReadState);
+ expect(call.grouped).toEqual([communityChannel.serverId, communityChannel.id]);
+ });
+});
+
// The reply/DM/read exclusion semantics live in the subquery's WHERE clause.
// We can't execute a WHERE against a mock, but we CAN pin that the subquery
// is built with the right filter shape — a raw `sql` cast or a missing
diff --git a/src/web/src/app/api/community/servers/[id]/unreads/route.test.ts b/src/web/src/app/api/community/servers/[id]/unreads/route.test.ts
index b167d5d6d..1323414f0 100644
--- a/src/web/src/app/api/community/servers/[id]/unreads/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/unreads/route.test.ts
@@ -45,8 +45,19 @@ describe("GET /api/community/servers/[id]/unreads", () => {
mockListVisibleChannelIds.mockResolvedValue(["channel_1", "channel_2"])
mockListVisibleChannelIdsForUser.mockRejectedValue(new Error("cross-server resolver must not run"))
mockListEligibleUnreadChannels.mockResolvedValue([
- { serverId: "server_1", channelId: "channel_1" },
- { serverId: "server_1", channelId: "channel_2", parentChannelId: "channel_1" },
+ {
+ serverId: "server_1",
+ channelId: "channel_1",
+ lastUnreadSeq: 7,
+ lastAttentionSeq: null,
+ },
+ {
+ serverId: "server_1",
+ channelId: "channel_2",
+ parentChannelId: "channel_1",
+ lastUnreadSeq: 11,
+ lastAttentionSeq: 10,
+ },
])
mockListUnreadForumOpeners.mockResolvedValue([])
})
@@ -60,7 +71,16 @@ describe("GET /api/community/servers/[id]/unreads", () => {
expect(response.status).toBe(200)
expect(await response.json()).toEqual({
channelIds: ["channel_1", "channel_2"],
- childChannels: [{ id: "channel_2", parentChannelId: "channel_1" }],
+ sources: [
+ { channelId: "channel_1", lastUnreadSeq: 7, lastAttentionSeq: null },
+ { channelId: "channel_2", lastUnreadSeq: 11, lastAttentionSeq: 10 },
+ ],
+ childChannels: [{
+ id: "channel_2",
+ parentChannelId: "channel_1",
+ lastUnreadSeq: 11,
+ lastAttentionSeq: 10,
+ }],
stale: false,
})
expect(mockListVisibleChannelIds).toHaveBeenCalledWith(expect.anything(), "server_1", "user_1")
@@ -117,6 +137,11 @@ describe("GET /api/community/servers/[id]/unreads", () => {
)
expect(response.status).toBe(200)
- expect(await response.json()).toEqual({ channelIds: [], childChannels: [], stale: true })
+ expect(await response.json()).toEqual({
+ channelIds: [],
+ sources: [],
+ childChannels: [],
+ stale: true,
+ })
})
})
diff --git a/src/web/src/app/api/community/servers/[id]/unreads/route.ts b/src/web/src/app/api/community/servers/[id]/unreads/route.ts
index bfe9a6f28..245e591a2 100644
--- a/src/web/src/app/api/community/servers/[id]/unreads/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/unreads/route.ts
@@ -37,6 +37,11 @@ export const GET = withAuth(async (_req, ctx) => {
)
return {
channelIds: projectedUnread.map((row) => row.channelId),
+ sources: projectedUnread.map((row) => ({
+ channelId: row.channelId,
+ lastUnreadSeq: row.lastUnreadSeq,
+ lastAttentionSeq: row.lastAttentionSeq,
+ })),
// Preserve the canonical child → parent attribution. The client needs
// this even when a participating forum post is outside the sidebar's
// 72h / top-five projection, otherwise a cold boot loses its unread
@@ -44,16 +49,31 @@ export const GET = withAuth(async (_req, ctx) => {
// access, archive, participant, read-cursor, and policy filtering;
// the client narrows them to parents whose canonical type is `forum`.
childChannels: projectedUnread.flatMap((row) => row.parentChannelId
- ? [{ id: row.channelId, parentChannelId: row.parentChannelId }]
+ ? [{
+ id: row.channelId,
+ parentChannelId: row.parentChannelId,
+ lastUnreadSeq: row.lastUnreadSeq,
+ lastAttentionSeq: row.lastAttentionSeq,
+ }]
: []),
}
},
- { channelIds: [] as string[], childChannels: [] as Array<{ id: string; parentChannelId: string }> },
+ {
+ channelIds: [] as string[],
+ sources: [] as Array<{ channelId: string; lastUnreadSeq: number; lastAttentionSeq: number | null }>,
+ childChannels: [] as Array<{
+ id: string
+ parentChannelId: string
+ lastUnreadSeq: number
+ lastAttentionSeq: number | null
+ }>,
+ },
{ route: "community/servers/:id/unreads" },
)
return NextResponse.json({
channelIds: value.channelIds,
+ sources: value.sources,
childChannels: value.childChannels,
stale,
})
diff --git a/src/web/src/app/api/community/servers/route.human.test.ts b/src/web/src/app/api/community/servers/route.human.test.ts
index 5d48a6312..6b826f776 100644
--- a/src/web/src/app/api/community/servers/route.human.test.ts
+++ b/src/web/src/app/api/community/servers/route.human.test.ts
@@ -3,7 +3,9 @@ import { NextRequest, NextResponse } from "next/server"
const mocks = vi.hoisted(() => ({
listUserServers: vi.fn(),
- listEligibleUnreadServerIds: vi.fn(),
+ listVisibleChannelIdsForUser: vi.fn(),
+ listEligibleUnreadChannels: vi.fn(),
+ listUnreadMentionSources: vi.fn(),
}))
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({ kind: "db" })) }))
@@ -31,10 +33,15 @@ vi.mock("@alook/shared", async () => {
communityServer: {
...actual.queries.communityServer,
listUserServers: (...args: unknown[]) => mocks.listUserServers(...args),
+ listUnreadMentionSources: (...args: unknown[]) => mocks.listUnreadMentionSources(...args),
+ },
+ communityChannel: {
+ ...actual.queries.communityChannel,
+ listVisibleChannelIdsForUser: (...args: unknown[]) => mocks.listVisibleChannelIdsForUser(...args),
},
communityInbox: {
...actual.queries.communityInbox,
- listEligibleUnreadServerIds: (...args: unknown[]) => mocks.listEligibleUnreadServerIds(...args),
+ listEligibleUnreadChannels: (...args: unknown[]) => mocks.listEligibleUnreadChannels(...args),
},
},
}
@@ -49,26 +56,62 @@ describe("GET /api/community/servers — human unread seed", () => {
{ id: "server-a", name: "A", icon: null },
{ id: "server-b", name: "B", icon: null },
])
+ mocks.listVisibleChannelIdsForUser.mockResolvedValue(["channel-b"])
+ mocks.listEligibleUnreadChannels.mockResolvedValue([])
+ mocks.listUnreadMentionSources.mockResolvedValue([])
})
- it("adds an explicit boolean to every human row from one unread-id scan", async () => {
- mocks.listEligibleUnreadServerIds.mockResolvedValue(["server-b"])
+ it("adds exact unread and mention source vectors to every human row", async () => {
+ mocks.listEligibleUnreadChannels.mockResolvedValue([{
+ serverId: "server-b",
+ channelId: "channel-b",
+ lastUnreadSeq: 8,
+ }])
+ mocks.listUnreadMentionSources.mockResolvedValue([{
+ serverId: "server-b",
+ channelId: "channel-b",
+ count: 2,
+ lastSeq: 8,
+ }, {
+ serverId: null,
+ channelId: "dm-channel",
+ count: 1,
+ lastSeq: 4,
+ }])
const response = await GET(new NextRequest("http://localhost/api/community/servers"))
expect(response.status).toBe(200)
await expect(response.json()).resolves.toEqual({
servers: [
- { id: "server-a", name: "A", icon: null, unread: false },
- { id: "server-b", name: "B", icon: null, unread: true },
+ {
+ id: "server-a",
+ name: "A",
+ icon: null,
+ unread: false,
+ unreadSources: [],
+ mentionSources: [],
+ },
+ {
+ id: "server-b",
+ name: "B",
+ icon: null,
+ unread: true,
+ unreadSources: [{ channelId: "channel-b", lastUnreadSeq: 8 }],
+ mentionSources: [{ channelId: "channel-b", count: 2, lastSeq: 8 }],
+ },
],
})
- expect(mocks.listEligibleUnreadServerIds).toHaveBeenCalledTimes(1)
- expect(mocks.listEligibleUnreadServerIds).toHaveBeenCalledWith(expect.anything(), "viewer")
+ expect(mocks.listVisibleChannelIdsForUser).toHaveBeenCalledWith(expect.anything(), "viewer")
+ expect(mocks.listEligibleUnreadChannels).toHaveBeenCalledWith(
+ expect.anything(),
+ "viewer",
+ ["channel-b"],
+ )
})
it("fails the human canonical response when its unread source fails", async () => {
- mocks.listEligibleUnreadServerIds.mockRejectedValue(new Error("unread failed"))
+ mocks.listEligibleUnreadChannels.mockRejectedValue(new Error("unread failed"))
await expect(GET(new NextRequest("http://localhost/api/community/servers")))
.rejects.toThrow("unread failed")
diff --git a/src/web/src/app/api/community/servers/route.ts b/src/web/src/app/api/community/servers/route.ts
index d7d8849c2..eed74e524 100644
--- a/src/web/src/app/api/community/servers/route.ts
+++ b/src/web/src/app/api/community/servers/route.ts
@@ -23,14 +23,43 @@ export const GET = withCommunityActor(async (_req, ctx) => {
const servers = rows.map((row) => ({ ...row, icon: serverIconUrl(row) }))
if (ctx.actor.kind === "bot") return writeJSON({ servers })
- const unreadServerIds = new Set(await withD1Retry(
- () => queries.communityInbox.listEligibleUnreadServerIds(db, ctx.actor.userId),
+ const [visibleChannelIds, mentionSourceRows] = await Promise.all([
+ withD1Retry(
+ () => queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.actor.userId),
+ { route: "community/servers:visible-channels" },
+ ),
+ withD1Retry(
+ () => queries.communityServer.listUnreadMentionSources(db, ctx.actor.userId),
+ { route: "community/servers:mention-sources" },
+ ),
+ ])
+ const unreadRows = await withD1Retry(
+ () => queries.communityInbox.listEligibleUnreadChannels(
+ db,
+ ctx.actor.userId,
+ visibleChannelIds,
+ ),
{ route: "community/servers:unread" },
- ))
+ )
+ const unreadSourcesByServer = new Map<string, Array<{ channelId: string; lastUnreadSeq: number }>>()
+ for (const row of unreadRows) {
+ const sources = unreadSourcesByServer.get(row.serverId) ?? []
+ sources.push({ channelId: row.channelId, lastUnreadSeq: row.lastUnreadSeq })
+ unreadSourcesByServer.set(row.serverId, sources)
+ }
+ const mentionSourcesByServer = new Map<string, Array<{ channelId: string; count: number; lastSeq: number }>>()
+ for (const row of mentionSourceRows) {
+ if (!row.serverId) continue
+ const sources = mentionSourcesByServer.get(row.serverId) ?? []
+ sources.push({ channelId: row.channelId, count: row.count, lastSeq: row.lastSeq })
+ mentionSourcesByServer.set(row.serverId, sources)
+ }
return writeJSON({
servers: servers.map((server) => ({
...server,
- unread: unreadServerIds.has(server.id),
+ unread: unreadSourcesByServer.has(server.id),
+ unreadSources: unreadSourcesByServer.get(server.id) ?? [],
+ mentionSources: mentionSourcesByServer.get(server.id) ?? [],
})),
})
})
diff --git a/src/web/src/app/api/community/users/me/dms/route.test.ts b/src/web/src/app/api/community/users/me/dms/route.test.ts
index 57e8aec9b..fbd90e592 100644
--- a/src/web/src/app/api/community/users/me/dms/route.test.ts
+++ b/src/web/src/app/api/community/users/me/dms/route.test.ts
@@ -6,6 +6,7 @@ vi.mock("@opennextjs/cloudflare", () => ({
}))
const mockListDMs = vi.fn()
+const mockListEligibleUnreadDms = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
@@ -17,6 +18,9 @@ vi.mock("@alook/shared", async () => {
communityDm: {
listDMs: (...a: unknown[]) => mockListDMs(...a),
},
+ communityInbox: {
+ listEligibleUnreadDms: (...a: unknown[]) => mockListEligibleUnreadDms(...a),
+ },
communityFriendship: {
isBlocked: vi.fn(),
},
@@ -53,7 +57,10 @@ function getReq() {
}
describe("GET /api/community/users/me/dms — name projection", () => {
- beforeEach(() => vi.clearAllMocks())
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockListEligibleUnreadDms.mockResolvedValue([])
+ })
it("returns the counterpart's user.name verbatim (no email fallback)", async () => {
// Post-migration 0050, user.name is CHECK-constrained non-empty. The
@@ -80,4 +87,29 @@ describe("GET /api/community/users/me/dms — name projection", () => {
expect(body.conversations[0]?.name).not.toContain("@")
expect(body.conversations[0]?.avatar).toBe("A")
})
+
+ it("projects canonical unread state and its sequence evidence", async () => {
+ mockListDMs.mockResolvedValue([{
+ id: "d1",
+ otherUserId: "u2",
+ otherUserName: "Alice",
+ otherUserEmail: "[email protected]",
+ otherUserImage: null,
+ otherUserAvatarVersion: 0,
+ otherUserDiscriminator: "0001",
+ lastMessageAt: "2026-06-30T00:00:00.000Z",
+ createdAt: "2026-06-30T00:00:00.000Z",
+ }])
+ mockListEligibleUnreadDms.mockResolvedValue([{
+ channelId: "d1",
+ lastUnreadSeq: 9,
+ }])
+
+ const res = await GET(getReq(), {} as any)
+ expect((await res.json()).conversations[0]).toMatchObject({
+ id: "d1",
+ unread: true,
+ lastUnreadSeq: 9,
+ })
+ })
})
diff --git a/src/web/src/app/api/community/users/me/dms/route.ts b/src/web/src/app/api/community/users/me/dms/route.ts
index bbb823240..442ba1d2a 100644
--- a/src/web/src/app/api/community/users/me/dms/route.ts
+++ b/src/web/src/app/api/community/users/me/dms/route.ts
@@ -21,7 +21,13 @@ import { canonicalUserImage } from "@/lib/community/storage"
*/
export const GET = withAuth(async (_req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
- const rows = await queries.communityDm.listDMs(db, ctx.userId)
+ const [rows, unreadRows] = await Promise.all([
+ queries.communityDm.listDMs(db, ctx.userId),
+ queries.communityInbox.listEligibleUnreadDms(db, ctx.userId),
+ ])
+ const unreadByChannelId = new Map(
+ unreadRows.map((row) => [row.channelId, row.lastUnreadSeq]),
+ )
const conversations = rows.map((r) => ({
id: r.id,
userId: r.otherUserId,
@@ -32,6 +38,10 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {
avatarVersion: r.otherUserAvatarVersion,
status: "offline" as const,
preview: "",
+ unread: unreadByChannelId.has(r.id),
+ ...(unreadByChannelId.has(r.id)
+ ? { lastUnreadSeq: unreadByChannelId.get(r.id) }
+ : {}),
}))
return writeJSON({ conversations })
})
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.ts
index 37deeb2eb..8b5cc346e 100644
--- a/src/web/src/app/api/community/users/me/inbox/mentions/route.test.ts
+++ b/src/web/src/app/api/community/users/me/inbox/mentions/route.test.ts
@@ -69,7 +69,7 @@ describe("GET /api/community/users/me/inbox/mentions", () => {
mockListUnreadMentions.mockResolvedValue([
{
mention: { id: "mn1", kind: "mention" },
- message: { id: "m1", channelId: "c1", content: "@u1 hi", createdAt: "2026-06-25T10:00:00Z" },
+ message: { id: "m1", seq: 4, channelId: "c1", content: "@u1 hi", createdAt: "2026-06-25T10:00:00Z" },
author: { id: "u-alice", name: "Alice", email: "[email protected]", image: null },
},
])
@@ -89,7 +89,7 @@ describe("GET /api/community/users/me/inbox/mentions", () => {
// 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", authorId: "u-alice", authorName: "Alice", content: "@u1 hi" },
+ m: { id: "m1", seq: 4, authorId: "u-alice", authorName: "Alice", content: "@u1 hi" },
})
})
@@ -120,6 +120,36 @@ describe("GET /api/community/users/me/inbox/mentions", () => {
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: 200, visibleChannelIds: ["c1"] })
+ 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.ts
index 91311d448..3b84b2565 100644
--- a/src/web/src/app/api/community/users/me/inbox/mentions/route.ts
+++ b/src/web/src/app/api/community/users/me/inbox/mentions/route.ts
@@ -36,7 +36,7 @@ export const GET = withAuth(async (req, ctx) => {
async () => {
const visibleChannelIds = await queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId)
const rows = await queries.communityMention.listUnreadMentions(db, ctx.userId, {
- limit,
+ limit: limit + 1,
visibleChannelIds,
})
const channelIds = [...new Set(rows.filter((r) => r.message.channelId).map((r) => r.message.channelId!))]
@@ -51,7 +51,9 @@ export const GET = withAuth(async (req, ctx) => {
if (stale) {
return writeJSON({ mentions: [], limit, stale: true })
}
- const { rows, channels, servers } = fetched
+ 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]))
@@ -71,6 +73,7 @@ export const GET = withAuth(async (req, ctx) => {
channelId: row.message.channelId,
m: {
id: row.message.id,
+ 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.
@@ -88,5 +91,5 @@ export const GET = withAuth(async (req, ctx) => {
}
})
- return writeJSON({ mentions, limit })
+ return writeJSON({ mentions, limit, truncated })
})
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.ts
index 70d960a5e..41bb1cfed 100644
--- a/src/web/src/app/api/community/users/me/inbox/unreads/route.ts
+++ b/src/web/src/app/api/community/users/me/inbox/unreads/route.ts
@@ -107,6 +107,7 @@ export const GET = withAuth(async (req, ctx) => {
type: string | null
lastMessageAt: string
mentionCount: number
+ lastUnreadSeq: number
openerMessageId?: string
parentChannelId?: string
openerSeq?: number
@@ -123,6 +124,7 @@ export const GET = withAuth(async (req, ctx) => {
serverName: string
lastMessageAt: string
mentionCount: number
+ lastUnreadSeq: number
hasDirectUnread: boolean
children: UnreadChild[]
}
@@ -141,6 +143,7 @@ export const GET = withAuth(async (req, ctx) => {
type: row.type,
lastMessageAt: row.lastMessageAt,
mentionCount: row.mentionCount,
+ lastUnreadSeq: row.lastUnreadSeq,
sortSeq: 0,
sortId: row.channelId,
})
@@ -154,6 +157,7 @@ export const GET = withAuth(async (req, ctx) => {
serverName: row.serverName,
lastMessageAt: row.lastMessageAt,
mentionCount: row.mentionCount,
+ lastUnreadSeq: row.lastUnreadSeq,
hasDirectUnread: true,
children: [],
})
@@ -179,6 +183,7 @@ export const GET = withAuth(async (req, ctx) => {
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
@@ -192,6 +197,7 @@ export const GET = withAuth(async (req, ctx) => {
type: "thread",
lastMessageAt: opener.createdAt,
mentionCount: unreadChild?.mentionCount ?? 0,
+ lastUnreadSeq: Math.max(unreadChild?.lastUnreadSeq ?? 0, opener.openerSeq),
parentChannelId: opener.parentChannelId,
openerMessageId: opener.openerMessageId,
openerSeq: opener.openerSeq,
@@ -228,6 +234,7 @@ export const GET = withAuth(async (req, ctx) => {
serverName: "",
lastMessageAt: "",
mentionCount: 0,
+ lastUnreadSeq: 0,
hasDirectUnread: false,
children: [],
})
@@ -290,6 +297,7 @@ export const GET = withAuth(async (req, ctx) => {
type: c.type ?? undefined,
lastMessageAt: c.lastMessageAt,
mentionCount: c.mentionCount,
+ lastUnreadSeq: c.lastUnreadSeq,
hasDirectUnread: c.hasDirectUnread,
children: c.children.map((k) => ({
channelId: k.channelId,
@@ -297,6 +305,7 @@ export const GET = withAuth(async (req, ctx) => {
type: k.type ?? undefined,
lastMessageAt: k.lastMessageAt,
mentionCount: k.mentionCount,
+ lastUnreadSeq: k.lastUnreadSeq,
...(k.parentChannelId ? { parentChannelId: k.parentChannelId } : {}),
...(k.openerMessageId ? { openerMessageId: k.openerMessageId } : {}),
...(k.openerSeq !== undefined ? { openerSeq: k.openerSeq } : {}),
@@ -357,6 +366,7 @@ export const GET = withAuth(async (req, ctx) => {
) ?? avatarInitial(d.otherUserName),
otherUserAvatarVersion: d.otherUserAvatarVersion,
lastMessageAt: d.lastMessageAt,
+ lastUnreadSeq: d.lastUnreadSeq,
}))
.sort((a, b) => (a.lastMessageAt < b.lastMessageAt ? 1 : -1))
diff --git a/src/web/src/app/c/QueryProvider.tsx b/src/web/src/app/c/QueryProvider.tsx
index cd2202955..cd80683ee 100644
--- a/src/web/src/app/c/QueryProvider.tsx
+++ b/src/web/src/app/c/QueryProvider.tsx
@@ -14,6 +14,10 @@ import { disposeAccountReadStateReconciliation } from "@/hooks/community/communi
import { disposeReadCoordinator } from "@/hooks/community/read-coordinator"
import { useCommunityWsStore } from "@/stores/community/ws"
import { seedPersistedMessageProfiles } from "@/lib/community/profile-seed"
+import {
+ disposeAccountUnreadProjection,
+ getAccountUnreadProjection,
+} from "@/hooks/community/account-unread-projection"
/**
* Owns the TanStack QueryClient for the community subtree.
@@ -40,6 +44,7 @@ export function QueryProvider({
profiles.activateProfileAccount(userId)
const restoreProfileSnapshot = useRef(profiles.beginProfileSnapshot()).current
const [queryClient] = useState(() => createQueryClient())
+ if (userId) getAccountUnreadProjection(queryClient, userId)
// Persister is bound to the userId at construction; on account switch the
// whole community subtree unmounts and the shell re-renders with the new
// id, so we don't need to reactively rebuild the persister mid-session.
@@ -57,6 +62,7 @@ export function QueryProvider({
disposeTimer.current = null
disposeReadCoordinator(queryClient)
disposeAccountReadStateReconciliation(queryClient)
+ disposeAccountUnreadProjection(queryClient)
}, 0)
}
}, [queryClient])
diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsx
index 696bcb540..e704a6fc8 100644
--- a/src/web/src/app/c/channels/layout.tsx
+++ b/src/web/src/app/c/channels/layout.tsx
@@ -2,15 +2,11 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react"
import { useParams, usePathname, useRouter, useSearchParams } from "next/navigation"
-import { useQueryClient } from "@tanstack/react-query"
import { toast } from "sonner"
import { toastApiError } from "@/lib/api/client"
-import { communityKeys } from "@/lib/query-keys"
import { markSwitch } from "@/lib/perf/switch-mark"
import { Dialog, DialogContent } from "@/components/ui/dialog"
import { useChannelTree } from "@/components/community/channels/use-channel-tree"
-import { patchChannelUnread } from "@/hooks/community/server-detail-cache"
-import type { ServerDetail } from "@/hooks/community/use-servers"
import { ShellFrame } from "@/components/community/shell/shell-frame"
import {
channelHref,
@@ -41,10 +37,7 @@ import {
import { clearLastChannel } from "@/lib/community/last-channel"
import { usePresence } from "@/hooks/community/use-server-panels"
import {
- patchForumSidebarUnreadExact,
- removeForumSidebarUnreadChild,
resolveForumSidebarRouteCandidate,
- setForumSidebarParentUnreadBase,
useForumSidebarThreads,
type ForumSidebarThread,
} from "@/hooks/community/use-forum-sidebar-threads"
@@ -82,7 +75,6 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
const breakpoint = useBreakpoint()
const router = useRouter()
- const queryClient = useQueryClient()
const cancelPendingNavigation = useCallback(() => {
useCommunityStore.getState().uiHandlers.cancelPendingNavigation?.()
}, [])
@@ -289,42 +281,12 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
// mounted ChannelView sync the store in its own useEffect keeps skeleton
// type consistent with the target channel.
//
- // Also do NOT eagerly mark the channel read. The visible-row read observer
- // advances the pointer as the user actually looks at messages. Clicking
- // the sidebar is not "I read everything"; it's just a navigation event.
- // `channelTree.markRead(id)` is a client-only tint (unread flag on the
- // sidebar row) — kept so the badge fades on click as it did before. If
- // the user then never scrolls to the new messages, the server-side
- // watermark stays put and the badge will re-appear on next refetch,
- // which is the correct behavior.
- //
- // Also patch the `ServerDetail` query cache (not just the local
- // `channelTree` state) to `unread: false` for this channel, via the same
- // `patchChannelUnread` helper the WS handler uses for the opposite
- // direction. This is still just an optimistic *client-side* tint — the
- // server-side watermark stays authoritative, and a subsequent real
- // refetch will correctly re-flip `unread` to `true` if the user never
- // actually scrolled into the channel. Without this cache patch, an
- // unrelated sibling-channel WS patch would resurrect the just-cleared dot
- // before the user even navigates away — `useChannelTree`'s metadata merge
- // trusts the cache unconditionally, so both directions must write to it.
+ // The visible-row observer is the only optimistic/read writer. Navigation
+ // itself must leave account unread state untouched.
markSwitch("channel", id)
cancelPendingNavigation()
useCommunityStore.getState().uiHandlers.navigatePath?.(channelHref(serverId, id))
- channelTree.markRead(id)
- const hasChildFallback = setForumSidebarParentUnreadBase(
- queryClient,
- serverId,
- id,
- false,
- )
- if (!hasChildFallback) {
- queryClient.setQueryData<ServerDetail | undefined>(
- communityKeys.server(serverId),
- (cache) => patchChannelUnread(cache, id, false),
- )
- }
- }, [cancelPendingNavigation, channelTree, queryClient, serverId])
+ }, [cancelPendingNavigation, serverId])
const setActiveForumThread = useCallback((_parentId: string, id: string) => {
markSwitch("channel", id)
@@ -332,9 +294,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
useCommunityStore.getState().uiHandlers.navigatePath?.(
channelHref(serverId, id),
)
- removeForumSidebarUnreadChild(queryClient, serverId, id)
- patchForumSidebarUnreadExact(queryClient, serverId, id, false)
- }, [cancelPendingNavigation, queryClient, serverId])
+ }, [cancelPendingNavigation, serverId])
const prefetchChannel = useCallback(
(id: string, _parentId?: string) => router.prefetch(channelHref(serverId, id)),
diff --git a/src/web/src/app/c/me/layout.tsx b/src/web/src/app/c/me/layout.tsx
index fbd3204b8..f006fea54 100644
--- a/src/web/src/app/c/me/layout.tsx
+++ b/src/web/src/app/c/me/layout.tsx
@@ -1,7 +1,6 @@
"use client"
import { useCallback, useEffect, useMemo, type ReactNode } from "react"
-import { useQueryClient } from "@tanstack/react-query"
import {
useParams,
usePathname,
@@ -16,7 +15,6 @@ import { useCommunityStore, useCurrentChannelId } from "@/stores/community"
import { useDms } from "@/hooks/community/use-dms"
import { useDmRouteVerification } from "@/hooks/community/use-dm-route-verification"
import { useFriends, useFriendsPresence } from "@/hooks/community/use-friends"
-import { communityKeys } from "@/lib/query-keys"
import { useCommunityWsStore } from "@/stores/community/ws"
import { readCommunityProfile } from "@/lib/community/profile-read"
import {
@@ -64,7 +62,6 @@ export default function MeLayout({ children }: { children: ReactNode }) {
)
const { blocked } = useFriends()
const currentChannelId = useCurrentChannelId()
- const queryClient = useQueryClient()
const cancelPendingNavigation = useCallback(() => {
useCommunityStore.getState().uiHandlers.cancelPendingNavigation?.()
}, [])
@@ -101,29 +98,11 @@ export default function MeLayout({ children }: { children: ReactNode }) {
router.replace(ME_ROOT)
}, [cancelPendingNavigation, meLocationStatus, pathname, router])
- // Mirror channel sidebar-click behavior (channels/layout.tsx:226-236): do
- // NOT eagerly mark the DM read on click. That fires a bodyless
- // `PUT /channels/:id/read` which the server aligns to the DM's tail (see
- // api/community/channels/[id]/read/route.ts) — the read-state snapshot then
- // resolves at the tail on mount and `newDividerBefore` computes to
- // `undefined`, so unread DMs open at the bottom with no NEW divider.
- //
- // Instead: client-only optimistic tint on the DM sidebar row so the badge
- // fades on click (matches the pre-fix UX). The visible-row read observer
- // advances the server pointer as the
- // viewer actually looks at messages. If the user opens then leaves without
- // scrolling to the new messages, the server watermark stays put and the
- // badge re-appears on the next refetch, which is the correct behavior.
+ // Navigation is intentionally read-neutral. The visible-row observer owns
+ // both optimistic clearing and the durable cursor write.
const enterDm = useCallback((id: string) => {
- queryClient.setQueryData(
- communityKeys.dms(),
- (prev: { conversations: { id: string; unread?: boolean }[] } | undefined) =>
- prev
- ? { ...prev, conversations: prev.conversations.map((d) => (d.id === id ? { ...d, unread: false } : d)) }
- : prev,
- )
useCommunityStore.getState().uiHandlers.navigatePath?.(`/c/me/${id}`)
- }, [queryClient])
+ }, [])
const onShowFriends = useCallback(() => {
useCommunityStore.getState().setCurrentChannelId(null)
diff --git a/src/web/src/components/community/channels/use-channel-tree.ts b/src/web/src/components/community/channels/use-channel-tree.ts
index fbd3b7db2..bcabb2606 100644
--- a/src/web/src/components/community/channels/use-channel-tree.ts
+++ b/src/web/src/components/community/channels/use-channel-tree.ts
@@ -180,12 +180,6 @@ export function useChannelTree(categories: Category[]) {
if (!cat) return prev
return { ...prev, [cat]: prev[cat].map((c) => c.id === id ? { ...c, name } : c) }
}), [])
- const markRead = useCallback((id: string) =>
- setOrder((prev) => {
- const cat = catOf(id, prev)
- if (!cat) return prev
- return { ...prev, [cat]: prev[cat].map((c) => c.id === id ? { ...c, unread: false } : c) }
- }), [])
// Category delete is driven by the query cache (useDeleteCategory's optimistic
// onMutate/onError), so the tree resettles from `categories` — no local
// removal helper (a local one had no rollback path; see the mutation hook).
@@ -224,11 +218,11 @@ export function useChannelTree(categories: Category[]) {
return useMemo(() => ({
collapsed, catOrder, order, catNames, catPrivate, catPending, catCreators,
- toggleCat, removeChannel, renameChannel, markRead,
+ toggleCat, removeChannel, renameChannel,
renameCategory, onDragOver, onDragEnd,
}), [
collapsed, catOrder, order, catNames, catPrivate, catPending, catCreators,
- toggleCat, removeChannel, renameChannel, markRead,
+ toggleCat, removeChannel, renameChannel,
renameCategory, onDragOver, onDragEnd,
])
}
diff --git a/src/web/src/components/community/shell/community-inbox-popover.tsx b/src/web/src/components/community/shell/community-inbox-popover.tsx
index 64ca75793..b5f9e2d49 100644
--- a/src/web/src/components/community/shell/community-inbox-popover.tsx
+++ b/src/web/src/components/community/shell/community-inbox-popover.tsx
@@ -234,6 +234,8 @@ export function InboxPopover({
marked,
markedLoading,
loading,
+ hasProjectedUnreads,
+ hasProjectedMentions,
onOpenChannel,
onOpenThread,
onOpenForumThread,
@@ -252,6 +254,8 @@ export function InboxPopover({
marked: Marked[]
markedLoading?: boolean
loading?: boolean
+ hasProjectedUnreads?: boolean
+ hasProjectedMentions?: boolean
onOpenChannel?: (server: UnreadServer, channel: UnreadChannel) => void
onOpenThread?: (server: UnreadServer, parent: UnreadChannel, child: UnreadChild) => void
/** Compatibility for non-community showcase fixtures; product wiring uses onOpenThread. */
@@ -272,8 +276,9 @@ export function InboxPopover({
isProjected?: (target: InboxRowTarget | null) => boolean
}) {
const profilesByUserId = useProfilesByUserId()
- const hasUnreads = unreads.length > 0 || unreadDms.length > 0
- const hasAnything = hasUnreads || mentions.length > 0
+ const hasUnreads = hasProjectedUnreads ?? (unreads.length > 0 || unreadDms.length > 0)
+ const hasMentions = hasProjectedMentions ?? mentions.length > 0
+ const hasAnything = hasUnreads || hasMentions
return (
<Tabs
defaultValue="unreads"
@@ -303,7 +308,7 @@ export function InboxPopover({
<TabsTrigger value="mentions">
<span className="inline-flex items-center gap-2">
Mentions
- {mentions.length > 0 && <span className="size-1.5 rounded-full bg-primary" />}
+ {hasMentions && <span className="size-1.5 rounded-full bg-primary" />}
</span>
</TabsTrigger>
<TabsTrigger value="marked">Marked</TabsTrigger>
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.ts
index 3efb4ec2e..72b25215f 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
@@ -174,6 +174,8 @@ export function useShellInboxController({
marked: inboxMarked.marked,
markedLoading: inboxMarked.isLoading,
loading,
+ hasProjectedUnreads: inboxUnreads.hasProjectedUnread,
+ hasProjectedMentions: inboxMentions.hasProjectedMention,
onOpenChannel: openServerChannel,
onOpenThread: openThread,
onOpenDm: openDm,
@@ -189,7 +191,7 @@ export function useShellInboxController({
return {
popoverProps,
hasUnread:
- unreadFeed.length > 0 || unreadDms.length > 0 || mentions.length > 0,
+ inboxUnreads.hasProjectedUnread || inboxMentions.hasProjectedMention,
open: inbox.open,
onOpenChange: inbox.onOpenChange,
}
diff --git a/src/web/src/hooks/community/account-unread-projection.test.ts b/src/web/src/hooks/community/account-unread-projection.test.ts
new file mode 100644
index 000000000..ce03c15f0
--- /dev/null
+++ b/src/web/src/hooks/community/account-unread-projection.test.ts
@@ -0,0 +1,606 @@
+import { QueryClient } from "@tanstack/react-query"
+import { describe, expect, it, vi } from "vitest"
+import {
+ acceptAccountUnreadPrimarySnapshot,
+ AccountUnreadProjection,
+ disposeAccountUnreadProjection,
+ getActiveAccountUnreadProjection,
+ getAccountUnreadProjection,
+ MAX_EXACT_ARRIVALS,
+ MAX_EXACT_ARRIVALS_PER_CHANNEL,
+ MAX_STICKY_SCOPES,
+} from "./account-unread-projection"
+
+describe("AccountUnreadProjection", () => {
+ it("is a per-query-client and account singleton", () => {
+ const client = new QueryClient()
+ expect(getAccountUnreadProjection(client, "u1"))
+ .toBe(getAccountUnreadProjection(client, "u1"))
+ expect(getAccountUnreadProjection(client, "u1"))
+ .not.toBe(getAccountUnreadProjection(client, "u2"))
+ })
+
+ it("publishes synchronous changes and stops after unsubscribe", () => {
+ const projection = new AccountUnreadProjection("u1")
+ const listener = vi.fn()
+ const unsubscribe = projection.subscribe(listener)
+
+ projection.recordArrival({ channelId: "dm", seq: 1 })
+ expect(listener).toHaveBeenCalledOnce()
+ expect(projection.getSnapshot()).toBe(1)
+
+ unsubscribe()
+ projection.recordArrival({ channelId: "dm", seq: 2 })
+ expect(listener).toHaveBeenCalledOnce()
+ expect(projection.projectUnread("dms", "dm", false)).toBe(true)
+ })
+
+ it("ignores malformed arrivals and read cursors", () => {
+ const projection = new AccountUnreadProjection("u1")
+ projection.recordArrival({ channelId: "", seq: 1 })
+ projection.recordRead("c1", 0)
+ projection.recordOptimisticRead("c1", Number.NaN, 1)
+ expect(projection.getSnapshot()).toBe(0)
+ expect(projection.hasPending()).toBe(false)
+ })
+
+ it("records each rolling-deploy legacy snapshot once", () => {
+ const projection = new AccountUnreadProjection("u1")
+ const snapshot = {}
+ projection.recordLegacySnapshot(snapshot, [{
+ family: "servers",
+ channelId: "legacy",
+ serverId: "s1",
+ }])
+ const version = projection.getSnapshot()
+ projection.recordLegacySnapshot(snapshot, [{
+ family: "servers",
+ channelId: "legacy",
+ serverId: "s1",
+ }])
+ expect(projection.getSnapshot()).toBe(version)
+ expect(projection.projectServerUnread("s1", [], false)).toBe(true)
+ })
+
+ it("merges duplicate exact evidence and ignores older read cursors", () => {
+ const projection = new AccountUnreadProjection("u1")
+ projection.recordArrival({ channelId: "c1", serverId: "s1", messageId: "m1", seq: 2 })
+ projection.recordArrival({
+ channelId: "c1",
+ railChannelId: "forum",
+ messageId: "m1",
+ seq: 2,
+ isMention: true,
+ })
+ projection.recordRead("c1", 1)
+ projection.recordRead("c1", 1)
+
+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)
+ expect(projection.projectUnread("dms", "c1", false)).toBe(true)
+ expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(true)
+ })
+
+ it("does not retain an exact replay already covered by the primary cursor", () => {
+ const projection = new AccountUnreadProjection("u1")
+ projection.acceptPrimarySnapshot({
+ revision: 1,
+ readStates: [{ channelId: "c1", lastReadSeq: 4 }],
+ })
+
+ projection.recordArrival({
+ channelId: "c1",
+ serverId: "s1",
+ messageId: "m4",
+ seq: 4,
+ isMention: true,
+ })
+
+ expect(projection.hasPending()).toBe(false)
+ expect(projection.projectUnread("servers", "c1", false)).toBe(false)
+ expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(false)
+ })
+
+ it("keeps an exact arrival until matching family evidence absorbs it", () => {
+ const projection = new AccountUnreadProjection("u1")
+ projection.recordArrival({ channelId: "c1", serverId: "s1", messageId: "m2", seq: 2 })
+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)
+ projection.absorbFamily("servers", [{ channelId: "c1", lastUnreadSeq: 1 }])
+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)
+ projection.absorbFamily("servers", [{ channelId: "c1", lastUnreadSeq: 2 }])
+ expect(projection.projectUnread("servers", "c1", false)).toBe(false)
+ })
+
+ it("does not clear a sticky unknown on empty, same, or truncated evidence", () => {
+ const projection = new AccountUnreadProjection("u1")
+ projection.absorbFamily("inbox-unreads", [{ channelId: "c1", lastUnreadSeq: 8 }])
+ projection.recordArrival({ channelId: "c1", serverId: "s1" })
+ projection.absorbFamily("inbox-unreads", [], { truncated: false })
+ projection.absorbFamily("inbox-unreads", [{ channelId: "c1", lastUnreadSeq: 8 }])
+ expect(projection.projectUnread("inbox-unreads", "c1", false)).toBe(true)
+ projection.absorbFamily("inbox-unreads", [{ channelId: "c1", lastUnreadSeq: 9 }])
+ expect(projection.projectUnread("inbox-unreads", "c1", false)).toBe(false)
+ })
+
+ it("lets a visible read cover exact seq but never an unsequenced sticky bump", () => {
+ const exact = new AccountUnreadProjection("u1")
+ exact.recordArrival({ channelId: "c1", serverId: "s1", seq: 4 })
+ exact.recordRead("c1", 4)
+ expect(exact.projectUnread("servers", "c1", false)).toBe(false)
+
+ const sticky = new AccountUnreadProjection("u1")
+ sticky.recordArrival({ channelId: "c1", serverId: "s1" })
+ sticky.recordRead("c1", 99)
+ expect(sticky.projectUnread("servers", "c1", false)).toBe(true)
+ })
+
+ it("rolls back only the failed optimistic read generation", () => {
+ const projection = new AccountUnreadProjection("u1")
+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 4 })
+ projection.recordOptimisticRead("c1", 4, 1)
+ expect(projection.projectUnread("servers", "c1", false)).toBe(false)
+ projection.settleOptimisticRead(1, false)
+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)
+ })
+
+ it("commits an optimistic read at the greatest confirmed cursor", () => {
+ const projection = new AccountUnreadProjection("u1")
+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 5 })
+ projection.recordOptimisticRead("c1", 4, 2)
+ projection.settleOptimisticRead(404, true, 5)
+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)
+
+ projection.settleOptimisticRead(2, true, 5)
+ expect(projection.projectUnread("servers", "c1", false)).toBe(false)
+ })
+
+ it("settles overlapping optimistic generations independently", () => {
+ const projection = new AccountUnreadProjection("u1")
+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 4 })
+ projection.recordOptimisticRead("c1", 4, 1)
+ projection.recordOptimisticRead("c1", 5, 2)
+ projection.settleOptimisticRead(2, false)
+ expect(projection.projectUnread("servers", "c1", false)).toBe(false)
+ projection.settleOptimisticRead(1, false)
+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)
+
+ projection.recordOptimisticRead("c1", 4, 3)
+ projection.settleOptimisticRead(3, true, 4)
+ projection.recordOptimisticRead("c1", 5, 4)
+ projection.settleOptimisticRead(4, false)
+ expect(projection.projectUnread("servers", "c1", false)).toBe(false)
+ })
+
+ it("lets an accepted primary cursor settle matching optimistic generations", () => {
+ const projection = new AccountUnreadProjection("u1")
+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 4 })
+ projection.recordOptimisticRead("c1", 4, 1)
+ projection.acceptPrimarySnapshot({
+ revision: 1,
+ readStates: [{ channelId: "c1", lastReadSeq: 4 }],
+ })
+ projection.settleOptimisticRead(1, false)
+ expect(projection.projectUnread("servers", "c1", false)).toBe(false)
+ })
+
+ it("keeps post-mark-all arrivals while hiding only the captured prefix", () => {
+ const projection = new AccountUnreadProjection("u1")
+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
+ const token = projection.beginMarkAll("channels")
+ expect(projection.projectUnread("servers", "c1", true, 1)).toBe(false)
+ projection.recordArrival({ channelId: "c2", serverId: "s1", seq: 2 })
+ expect(projection.projectUnread("servers", "c2", false)).toBe(true)
+ projection.rollbackMarkAll(token)
+ expect(projection.projectUnread("servers", "c1", true, 1)).toBe(true)
+ })
+
+ it("keeps channel and DM mark-all domains independent inside Inbox", () => {
+ const projection = new AccountUnreadProjection("u1")
+ const channelToken = projection.beginMarkAll("channels")
+ expect(projection.projectUnread("inbox-unreads", "channel", true, 2)).toBe(false)
+ expect(projection.projectUnread("inbox-unreads", "dm", true, 2, "dms")).toBe(true)
+ projection.rollbackMarkAll(channelToken)
+
+ const dmToken = projection.beginMarkAll("dms")
+ expect(projection.projectUnread("inbox-unreads", "channel", true, 2)).toBe(true)
+ expect(projection.projectUnread("inbox-unreads", "dm", true, 2, "dms")).toBe(false)
+ projection.rollbackMarkAll(dmToken)
+ })
+
+ it("retires only the accepted mark-all domain prefix and preserves later arrivals", () => {
+ const projection = new AccountUnreadProjection("u1")
+ projection.recordArrival({
+ channelId: "channel-before",
+ serverId: "s1",
+ isMention: true,
+ })
+ const channelToken = projection.beginMarkAll("channels")
+ const mentionToken = projection.beginMarkAll("mentions")
+ projection.recordArrival({ channelId: "channel-after", serverId: "s1" })
+ projection.commitMarkAll(channelToken, 4)
+ projection.commitMarkAll(mentionToken, 6)
+
+ projection.acceptPrimarySnapshot({ revision: 4, readStates: [] })
+ expect(projection.projectUnread("servers", "channel-before", false)).toBe(false)
+ expect(projection.projectUnread("servers", "channel-after", false)).toBe(true)
+ expect(projection.projectUnread("inbox-mentions", "channel-before", false)).toBe(false)
+
+ projection.acceptPrimarySnapshot({ revision: 6, readStates: [] })
+ expect(projection.projectUnread("inbox-mentions", "channel-before", false)).toBe(false)
+ })
+
+ it("retires exact family bits and overflow sentinels at an accepted fence", () => {
+ const exact = new AccountUnreadProjection("u1")
+ exact.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
+ const channel = exact.beginMarkAll("channels")
+ exact.recordArrival({ channelId: "c2", serverId: "s1", seq: 2 })
+ exact.commitMarkAll(channel, 2)
+ exact.acceptPrimarySnapshot({ revision: 2, readStates: [] })
+ expect(exact.projectUnread("servers", "c1", false)).toBe(false)
+ expect(exact.projectUnread("servers", "c2", false)).toBe(true)
+
+ const overflow = new AccountUnreadProjection("u1")
+ for (let index = 0; index < MAX_STICKY_SCOPES; index += 1) {
+ overflow.recordArrival({ channelId: `c${index}`, serverId: `s${index}` })
+ }
+ overflow.recordArrival({ channelId: "overflow", serverId: "s-overflow" })
+ const token = overflow.beginMarkAll("channels")
+ overflow.commitMarkAll(token, 3)
+ overflow.acceptPrimarySnapshot({ revision: 3, readStates: [] })
+ expect(overflow.projectUnread("servers", "unrelated", false)).toBe(false)
+ })
+
+ it("applies primary snapshots only to the active account", () => {
+ const client = new QueryClient()
+ const first = getAccountUnreadProjection(client, "u1")
+ first.recordArrival({ channelId: "c1", serverId: "s1", seq: 2 })
+ const second = getAccountUnreadProjection(client, "u2")
+ second.recordArrival({ channelId: "c1", serverId: "s1", seq: 2 })
+
+ acceptAccountUnreadPrimarySnapshot(client, {
+ revision: 1,
+ readStates: [{ channelId: "c1", lastReadSeq: 2 }],
+ })
+
+ expect(first.projectUnread("servers", "c1", false)).toBe(true)
+ expect(second.projectUnread("servers", "c1", false)).toBe(false)
+ })
+
+ it("does not create or update a projection when no account is active", () => {
+ const client = new QueryClient()
+ acceptAccountUnreadPrimarySnapshot(client, {
+ revision: 1,
+ readStates: [{ channelId: "c1", lastReadSeq: 2 }],
+ })
+ const anonymous = getActiveAccountUnreadProjection(client)
+ expect(anonymous.ownerUserId).toBe("__anonymous__")
+ expect(anonymous.getSnapshot()).toBe(0)
+ })
+
+ it("never derives a numeric server mention increment from isMention", () => {
+ const projection = new AccountUnreadProjection("u1")
+ projection.recordArrival({
+ channelId: "c1",
+ serverId: "s1",
+ seq: 2,
+ isMention: true,
+ })
+ expect(projection.projectServerMentionCount("s1", [{
+ channelId: "c1",
+ count: 3,
+ lastSeq: 1,
+ }])).toBe(3)
+ expect(projection.projectMentionCount("inbox-mentions", "c1", 0, 1)).toBe(1)
+ })
+
+ it("absorbs mention arrivals with mention-seq and unread-seq evidence", () => {
+ const projection = new AccountUnreadProjection("u1")
+ projection.recordMentionArrival({ channelId: "c1", seq: 4, isMention: true })
+ projection.absorbFamily("inbox-mentions", [{
+ channelId: "c1",
+ lastUnreadSeq: 5,
+ lastMentionSeq: 3,
+ }])
+ expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(true)
+
+ projection.absorbFamily("inbox-mentions", [{
+ channelId: "c1",
+ lastUnreadSeq: 5,
+ lastMentionSeq: null,
+ }])
+ expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(false)
+ })
+
+ it("absorbs a single-family sticky mention only after newer evidence", () => {
+ const projection = new AccountUnreadProjection("u1")
+ projection.absorbFamily("inbox-mentions", [{ channelId: "c1", lastUnreadSeq: 4 }])
+ projection.recordMentionArrival({ channelId: "c1", isMention: true })
+ projection.absorbFamily("inbox-mentions", [{ channelId: "c1", lastUnreadSeq: 5 }])
+ expect(projection.hasPending("inbox-mentions", "mentions")).toBe(false)
+ })
+
+ it("skips arrivals and sticky scopes owned by another family", () => {
+ const projection = new AccountUnreadProjection("u1")
+ projection.recordArrival({ channelId: "exact", serverId: "s1", seq: 2 })
+ projection.recordArrival({ channelId: "sticky", serverId: "s1" })
+ projection.absorbFamily("dms", [{ channelId: "exact", lastUnreadSeq: 3 }])
+ expect(projection.projectUnread("servers", "exact", false)).toBe(true)
+ expect(projection.projectUnread("servers", "sticky", false)).toBe(true)
+ })
+
+ it("ignores stale family evidence", () => {
+ const projection = new AccountUnreadProjection("u1")
+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 2 })
+ projection.absorbFamily("servers", [{ channelId: "c1", lastUnreadSeq: 2 }], {
+ stale: true,
+ })
+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)
+ })
+
+ it("projects server and channel fallbacks, exact arrivals, and hidden forum children", () => {
+ const projection = new AccountUnreadProjection("u1")
+ expect(projection.projectServerUnread("s1", [], true)).toBe(true)
+ expect(projection.projectServerChannelUnread("s1", "c1", [], true)).toBe(true)
+
+ projection.recordArrival({
+ channelId: "post",
+ railChannelId: "forum",
+ serverId: "s1",
+ seq: 2,
+ })
+ expect(projection.projectServerUnread("s1", [], false)).toBe(true)
+ expect(projection.projectServerChannelUnread("s1", "forum", [], false)).toBe(true)
+ expect(projection.projectForumParentUnread(
+ "s1",
+ "forum",
+ false,
+ null,
+ new Set(),
+ )).toBe(true)
+ expect(projection.projectForumParentUnread(
+ "s1",
+ "forum",
+ false,
+ null,
+ new Set(["post"]),
+ )).toBe(false)
+ expect(projection.projectForumParentUnread(
+ "s1",
+ "forum",
+ true,
+ 3,
+ new Set(["post"]),
+ )).toBe(true)
+ expect(projection.projectServerUnread("other", [], false)).toBe(false)
+ })
+
+ it("projects sticky server, channel, and hidden-forum unread state", () => {
+ const projection = new AccountUnreadProjection("u1")
+ projection.recordArrival({
+ channelId: "post",
+ railChannelId: "forum",
+ serverId: "s1",
+ })
+ expect(projection.projectServerUnread("s1", [], false)).toBe(true)
+ expect(projection.projectServerChannelUnread("s1", "forum", [], false)).toBe(true)
+ expect(projection.projectForumParentUnread(
+ "s1",
+ "forum",
+ false,
+ null,
+ new Set(),
+ )).toBe(true)
+ })
+
+ it("projects canonical server sources and raw mention fallbacks", () => {
+ const projection = new AccountUnreadProjection("u1")
+ expect(projection.projectServerUnread("s1", [{
+ channelId: "c1",
+ lastUnreadSeq: 2,
+ }])).toBe(true)
+ expect(projection.projectServerChannelUnread("s1", "c1", [{
+ channelId: "c1",
+ lastUnreadSeq: 2,
+ }])).toBe(true)
+ expect(projection.projectServerMentionCount("s1", [], 7)).toBe(7)
+ expect(projection.projectServerMentionCount("s1", [{
+ channelId: "c1",
+ count: 3,
+ lastSeq: 2,
+ }])).toBe(3)
+ })
+
+ it("reports pending exact and sticky work by family and domain", () => {
+ const exact = new AccountUnreadProjection("u1")
+ exact.recordArrival({ channelId: "c1", serverId: "s1", seq: 1, isMention: true })
+ expect(exact.hasPending("servers", "channels")).toBe(true)
+ expect(exact.hasPending("inbox-mentions", "mentions")).toBe(true)
+ expect(exact.hasPending("dms", "dms")).toBe(false)
+ expect(exact.hasPending(undefined, "dms")).toBe(false)
+
+ const sticky = new AccountUnreadProjection("u1")
+ sticky.recordArrival({ channelId: "dm", isMention: true })
+ expect(sticky.hasPending("dms")).toBe(true)
+ expect(sticky.hasPending(undefined, "mentions")).toBe(true)
+ expect(sticky.hasPending(undefined, "channels")).toBe(false)
+ expect(sticky.hasPending("servers", "channels")).toBe(false)
+ })
+
+ it("degrades per-channel exact overflow to a sticky sentinel without losing unread", () => {
+ const projection = new AccountUnreadProjection("u1")
+ for (let seq = 1; seq <= MAX_EXACT_ARRIVALS_PER_CHANNEL + 1; seq += 1) {
+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq })
+ }
+ projection.recordRead("c1", MAX_EXACT_ARRIVALS_PER_CHANNEL + 1)
+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)
+ })
+
+ it("folds account-wide exact overflow into a sticky scope", () => {
+ const projection = new AccountUnreadProjection("u1")
+ for (let index = 0; index < MAX_EXACT_ARRIVALS; index += 1) {
+ projection.recordArrival({
+ channelId: `c${index}`,
+ serverId: "s1",
+ seq: 1,
+ })
+ }
+ projection.recordArrival({ channelId: "overflow", serverId: "s1", seq: 1 })
+ projection.recordRead("overflow", 99)
+ expect(projection.projectUnread("servers", "overflow", false)).toBe(true)
+ })
+
+ it("keeps fixed family overflow conservative and generation-aware", () => {
+ const projection = new AccountUnreadProjection("u1")
+ for (let index = 0; index < MAX_STICKY_SCOPES; index += 1) {
+ projection.recordArrival({ channelId: `c${index}`, serverId: `s${index}` })
+ }
+ projection.recordArrival({ channelId: "overflow-before", serverId: "s-overflow" })
+ expect(projection.projectServerChannelUnread(
+ "s-overflow",
+ "overflow-before",
+ [],
+ )).toBe(true)
+
+ const token = projection.beginMarkAll("channels")
+ expect(projection.projectServerChannelUnread(
+ "s-overflow",
+ "overflow-before",
+ [],
+ )).toBe(false)
+ projection.recordArrival({ channelId: "overflow-after", serverId: "s-after" })
+ expect(projection.projectServerChannelUnread("s-after", "overflow-after", [])).toBe(true)
+
+ projection.commitMarkAll(token, 3)
+ projection.acceptPrimarySnapshot({ revision: 3, readStates: [] })
+ expect(projection.projectServerChannelUnread("s-after", "overflow-after", [])).toBe(true)
+ })
+
+ it("exposes fixed overflow sentinels through family pending checks", () => {
+ const projection = new AccountUnreadProjection("u1")
+ for (let index = 0; index < MAX_STICKY_SCOPES; index += 1) {
+ projection.recordArrival({ channelId: `c${index}`, serverId: `s${index}` })
+ }
+ projection.recordArrival({ channelId: "overflow", serverId: "s-overflow" })
+ expect(projection.hasPending("servers")).toBe(true)
+ expect(projection.hasPending("servers", "channels")).toBe(true)
+ expect(projection.projectUnread("servers", "unrelated", false)).toBe(true)
+ expect(projection.projectServerUnread("unrelated", [], false)).toBe(true)
+ expect(projection.projectForumParentUnread(
+ "unrelated",
+ "forum",
+ false,
+ null,
+ new Set(),
+ )).toBe(true)
+ })
+
+ it("clears a sentinel only with advancing evidence for its retained witness", () => {
+ const projection = new AccountUnreadProjection("u1")
+ for (let index = 0; index < MAX_STICKY_SCOPES; index += 1) {
+ projection.recordArrival({ channelId: `c${index}`, serverId: `s${index}` })
+ }
+ projection.absorbFamily("servers", [{ channelId: "overflow", lastUnreadSeq: 8 }])
+ projection.recordArrival({ channelId: "overflow", serverId: "s-overflow" })
+
+ projection.absorbFamily("servers", [{ channelId: "other", lastUnreadSeq: 999 }])
+ expect(projection.projectUnread("servers", "unrelated", false)).toBe(true)
+ projection.absorbFamily("servers", [{ channelId: "overflow", lastUnreadSeq: 8 }])
+ expect(projection.projectUnread("servers", "unrelated", false)).toBe(true)
+ projection.absorbFamily("servers", [{ channelId: "overflow", lastUnreadSeq: 9 }])
+ expect(projection.projectUnread("servers", "unrelated", false)).toBe(false)
+ })
+
+ it("clears a mention sentinel with advancing mention evidence", () => {
+ const projection = new AccountUnreadProjection("u1")
+ for (let index = 0; index < MAX_STICKY_SCOPES; index += 1) {
+ projection.recordArrival({ channelId: `c${index}`, serverId: `s${index}` })
+ }
+ projection.recordArrival({
+ channelId: "mention-overflow",
+ serverId: "s-overflow",
+ isMention: true,
+ })
+ expect(projection.hasPending("inbox-mentions", "mentions")).toBe(true)
+
+ projection.absorbFamily("inbox-mentions", [{
+ channelId: "mention-overflow",
+ lastUnreadSeq: 1,
+ lastMentionSeq: 1,
+ }], { truncated: false })
+ expect(projection.hasPending("inbox-mentions", "mentions")).toBe(false)
+ })
+
+ it("makes a sentinel non-clearable when another scope folds into it", () => {
+ const projection = new AccountUnreadProjection("u1")
+ for (let index = 0; index < MAX_STICKY_SCOPES; index += 1) {
+ projection.recordArrival({ channelId: `c${index}`, serverId: `s${index}` })
+ }
+ projection.recordArrival({ channelId: "first", serverId: "s-first" })
+ projection.recordArrival({ channelId: "second", serverId: "s-second" })
+ projection.absorbFamily("servers", [
+ { channelId: "first", lastUnreadSeq: 9 },
+ { channelId: "second", lastUnreadSeq: 9 },
+ ])
+ expect(projection.projectUnread("servers", "unrelated", false)).toBe(true)
+ })
+
+ it("makes a normalized server-detail sentinel non-clearable across families", () => {
+ const projection = new AccountUnreadProjection("u1")
+ for (let index = 0; index < MAX_STICKY_SCOPES; index += 1) {
+ projection.recordArrival({ channelId: `c${index}`, serverId: `s${index}` })
+ }
+ projection.recordArrival({ channelId: "shared", serverId: "s-first" })
+ projection.recordArrival({ channelId: "shared", serverId: "s-second" })
+ projection.absorbFamily("server-detail:s-first", [{
+ channelId: "shared",
+ lastUnreadSeq: 9,
+ }])
+ expect(projection.hasPending("server-detail:s-first", "channels")).toBe(true)
+ })
+
+ it("ignores superseded mark-all tokens", () => {
+ const projection = new AccountUnreadProjection("u1")
+ const first = projection.beginMarkAll("channels")
+ const second = projection.beginMarkAll("channels")
+ projection.commitMarkAll(first, 1)
+ projection.rollbackMarkAll(first)
+ expect(projection.projectUnread("servers", "c1", true, 1)).toBe(false)
+ projection.rollbackMarkAll(second)
+ expect(projection.projectUnread("servers", "c1", true, 1)).toBe(true)
+ })
+
+ it("refreshes a repeated sticky scope past a mark-all fence", () => {
+ const projection = new AccountUnreadProjection("u1")
+ projection.recordArrival({ channelId: "c1", serverId: "s1" })
+ const token = projection.beginMarkAll("channels")
+ expect(projection.projectUnread("servers", "c1", false)).toBe(false)
+ projection.recordArrival({ channelId: "c1", serverId: "s1" })
+ expect(projection.projectUnread("servers", "c1", false)).toBe(true)
+ projection.rollbackMarkAll(token)
+ })
+
+ it("keeps sticky family epochs independent on the same channel", () => {
+ const projection = new AccountUnreadProjection("u1")
+ projection.recordArrival({ channelId: "c1", serverId: "s1" })
+ const token = projection.beginMarkAll("channels")
+ projection.recordMentionArrival({ channelId: "c1", isMention: true })
+ projection.commitMarkAll(token, 2)
+ projection.acceptPrimarySnapshot({ revision: 2, readStates: [] })
+
+ expect(projection.projectUnread("servers", "c1", false)).toBe(false)
+ expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(true)
+ })
+
+ it("disposes one account or an entire query-client ledger", () => {
+ const client = new QueryClient()
+ const first = getAccountUnreadProjection(client, "u1")
+ getAccountUnreadProjection(client, "u2")
+
+ disposeAccountUnreadProjection(client, "u1")
+ expect(getAccountUnreadProjection(client, "u1")).not.toBe(first)
+
+ disposeAccountUnreadProjection(client)
+ const anonymous = getActiveAccountUnreadProjection(client)
+ expect(anonymous.ownerUserId).toBe("__anonymous__")
+ disposeAccountUnreadProjection(new QueryClient())
+ })
+})
diff --git a/src/web/src/hooks/community/account-unread-projection.ts b/src/web/src/hooks/community/account-unread-projection.ts
new file mode 100644
index 000000000..dbd0f69b9
--- /dev/null
+++ b/src/web/src/hooks/community/account-unread-projection.ts
@@ -0,0 +1,761 @@
+"use client"
+
+import type { QueryClient } from "@tanstack/react-query"
+
+export type AccountUnreadFamily =
+ | "servers"
+ | `server-detail:${string}`
+ | "inbox-unreads"
+ | "inbox-mentions"
+ | "dms"
+
+export type AccountUnreadDomain = "channels" | "dms" | "mentions"
+
+export type AccountUnreadArrival = {
+ channelId: string
+ railChannelId?: string
+ serverId?: string
+ messageId?: string
+ seq?: number
+ isMention?: boolean
+}
+
+export type AccountUnreadSource = {
+ channelId: string
+ lastUnreadSeq: number
+ mentionCount?: number
+ lastMentionSeq?: number | null
+}
+
+export type AccountUnreadLegacySource = {
+ family: AccountUnreadFamily
+ channelId: string
+ serverId?: string
+ railChannelId?: string
+ isMention?: boolean
+}
+
+type PendingArrival = {
+ key: string
+ channelId: string
+ serverId?: string
+ railChannelId?: string
+ seq: number
+ ordinal: number
+ isMention: boolean
+ families: Set<AccountUnreadFamily>
+}
+
+type StickyUnknown = {
+ channelId: string
+ serverId?: string
+ railChannelId?: string
+ isMention: boolean
+ families: Map<AccountUnreadFamily, { boundary: number; ordinal: number }>
+}
+
+type OverflowSentinel = {
+ ordinal: number
+ witnessChannelId: string | null
+ witnessFamily: AccountUnreadFamily | null
+ boundary: number
+}
+
+export type MarkAllToken = {
+ domain: AccountUnreadDomain
+ ordinal: number
+ nonce: symbol
+}
+
+type MarkAllFence = MarkAllToken & {
+ state: "pending" | "committed"
+ revision: number | null
+}
+
+export const MAX_EXACT_ARRIVALS = 512
+export const MAX_EXACT_ARRIVALS_PER_CHANNEL = 64
+export const MAX_STICKY_SCOPES = 256
+
+const owners = new WeakMap<QueryClient, Map<string, AccountUnreadProjection>>()
+const activeOwners = new WeakMap<QueryClient, string>()
+
+function sentinelFamily(family: AccountUnreadFamily) {
+ return family.startsWith("server-detail:") ? "server-detail" : family
+}
+
+function familiesFor(arrival: AccountUnreadArrival): AccountUnreadFamily[] {
+ const families: AccountUnreadFamily[] = ["inbox-unreads"]
+ if (arrival.serverId) {
+ families.push("servers", `server-detail:${arrival.serverId}`)
+ } else {
+ families.push("dms")
+ }
+ if (arrival.isMention) families.push("inbox-mentions")
+ return families
+}
+
+function familyDomain(family: AccountUnreadFamily): AccountUnreadDomain {
+ if (family === "dms") return "dms"
+ if (family === "inbox-mentions") return "mentions"
+ return "channels"
+}
+
+function arrivalDomain(
+ family: AccountUnreadFamily,
+ serverId: string | undefined,
+): AccountUnreadDomain {
+ if (family === "inbox-mentions") return "mentions"
+ return serverId ? "channels" : "dms"
+}
+
+function sentinelKey(family: AccountUnreadFamily, domain: AccountUnreadDomain) {
+ return `${sentinelFamily(family)}\u0000${domain}`
+}
+
+/**
+ * Account-wide optimistic unread ledger. It deliberately owns no fetches,
+ * timers, cache writes, or route transitions: raw TanStack resources remain
+ * authoritative and feed evidence into this synchronous projection.
+ */
+export class AccountUnreadProjection {
+ private ordinal = 0
+ private version = 0
+ private readonly listeners = new Set<() => void>()
+ private readonly exact = new Map<string, PendingArrival>()
+ private readonly exactByChannel = new Map<string, Set<string>>()
+ private readonly sticky = new Map<string, StickyUnknown>()
+ private readonly sentinels = new Map<string, OverflowSentinel>()
+ private readonly evidence = new Map<string, number>()
+ private readonly readSeq = new Map<string, number>()
+ private readonly optimisticReads = new Map<
+ number,
+ { channelId: string; seq: number; committed: boolean }
+ >()
+ private readonly markAll = new Map<AccountUnreadDomain, MarkAllFence>()
+ private readonly legacySnapshots = new WeakSet<object>()
+
+ constructor(readonly ownerUserId: string) {}
+
+ subscribe = (listener: () => void) => {
+ this.listeners.add(listener)
+ return () => this.listeners.delete(listener)
+ }
+
+ getSnapshot = () => this.version
+
+ recordArrival(arrival: AccountUnreadArrival) {
+ this.recordArrivalForFamilies(arrival, familiesFor(arrival))
+ }
+
+ recordMentionArrival(arrival: AccountUnreadArrival) {
+ this.recordArrivalForFamilies(arrival, ["inbox-mentions"])
+ }
+
+ recordLegacySnapshot(
+ snapshot: object,
+ sources: readonly AccountUnreadLegacySource[],
+ ) {
+ if (this.legacySnapshots.has(snapshot)) return
+ this.legacySnapshots.add(snapshot)
+ for (const source of sources) {
+ this.recordSticky(
+ source.channelId,
+ [source.family],
+ source.isMention === true,
+ source.serverId,
+ source.railChannelId,
+ )
+ }
+ }
+
+ absorbLegacyServerAggregate(
+ serverId: string,
+ sources: readonly AccountUnreadSource[],
+ ) {
+ if (sources.length === 0) return
+ const channelId = `\u0000legacy-server:${serverId}`
+ const unknown = this.sticky.get(channelId)
+ if (!unknown?.families.delete("servers")) return
+ if (unknown.families.size === 0) this.sticky.delete(channelId)
+ this.publish()
+ }
+
+ private recordArrivalForFamilies(
+ arrival: AccountUnreadArrival,
+ families: AccountUnreadFamily[],
+ ) {
+ if (!arrival.channelId) return
+ const seq = arrival.seq
+ if (!Number.isSafeInteger(seq) || (seq ?? 0) <= 0) {
+ this.recordSticky(
+ arrival.channelId,
+ families,
+ arrival.isMention === true,
+ arrival.serverId,
+ arrival.railChannelId,
+ )
+ return
+ }
+ if (seq! <= (this.readSeq.get(arrival.channelId) ?? 0)) return
+ const key = arrival.messageId
+ ? `${arrival.channelId}:${arrival.messageId}`
+ : `${arrival.channelId}:seq:${seq}`
+ const existing = this.exact.get(key)
+ if (existing) {
+ for (const family of families) existing.families.add(family)
+ existing.isMention ||= arrival.isMention === true
+ existing.serverId ??= arrival.serverId
+ existing.railChannelId ??= arrival.railChannelId
+ this.publish()
+ return
+ }
+ const channelKeys = this.exactByChannel.get(arrival.channelId) ?? new Set<string>()
+ if (
+ this.exact.size >= MAX_EXACT_ARRIVALS
+ || channelKeys.size >= MAX_EXACT_ARRIVALS_PER_CHANNEL
+ ) {
+ const foldedFamilies = new Set(families)
+ let isMention = arrival.isMention === true
+ let serverId = arrival.serverId
+ let railChannelId = arrival.railChannelId
+ for (const exactKey of [...channelKeys]) {
+ const folded = this.exact.get(exactKey)!
+ for (const family of folded.families) foldedFamilies.add(family)
+ isMention ||= folded.isMention
+ serverId ??= folded.serverId
+ railChannelId ??= folded.railChannelId
+ this.removeExact(exactKey)
+ }
+ this.recordSticky(
+ arrival.channelId,
+ [...foldedFamilies],
+ isMention,
+ serverId,
+ railChannelId,
+ )
+ return
+ }
+ const pending: PendingArrival = {
+ key,
+ channelId: arrival.channelId,
+ serverId: arrival.serverId,
+ railChannelId: arrival.railChannelId,
+ seq: seq!,
+ ordinal: ++this.ordinal,
+ isMention: arrival.isMention === true,
+ families: new Set(families),
+ }
+ this.exact.set(key, pending)
+ channelKeys.add(key)
+ this.exactByChannel.set(arrival.channelId, channelKeys)
+ this.publish()
+ }
+
+ recordRead(channelId: string, seq: number) {
+ if (!Number.isSafeInteger(seq) || seq <= 0) return
+ const previous = this.readSeq.get(channelId) ?? 0
+ if (seq <= previous) return
+ this.readSeq.set(channelId, seq)
+ for (const key of this.exactByChannel.get(channelId) ?? []) {
+ const arrival = this.exact.get(key)
+ if (arrival && arrival.seq <= seq) this.removeExact(key)
+ }
+ this.publish()
+ }
+
+ recordOptimisticRead(channelId: string, seq: number, generation: number) {
+ if (!Number.isSafeInteger(seq) || seq <= 0) return
+ this.optimisticReads.set(generation, { channelId, seq, committed: false })
+ this.publish()
+ }
+
+ settleOptimisticRead(
+ generation: number,
+ committed: boolean,
+ confirmedSeq?: number,
+ ) {
+ const optimistic = this.optimisticReads.get(generation)
+ if (!optimistic) return
+ if (committed) {
+ optimistic.seq = Math.max(optimistic.seq, confirmedSeq ?? 0)
+ optimistic.committed = true
+ this.publish()
+ return
+ }
+ this.optimisticReads.delete(generation)
+ this.publish()
+ }
+
+ acceptPrimarySnapshot(snapshot: {
+ revision: number
+ readStates: Array<{ channelId: string; lastReadSeq: number }>
+ }) {
+ for (const row of snapshot.readStates) {
+ this.recordRead(row.channelId, row.lastReadSeq)
+ for (const [generation, optimistic] of this.optimisticReads) {
+ if (
+ optimistic.channelId === row.channelId
+ && optimistic.seq <= row.lastReadSeq
+ ) this.optimisticReads.delete(generation)
+ }
+ }
+ let changed = false
+ for (const [domain, fence] of this.markAll) {
+ if (
+ fence.state === "committed"
+ && fence.revision !== null
+ && snapshot.revision >= fence.revision
+ ) {
+ for (const [key, arrival] of this.exact) {
+ if (arrival.ordinal > fence.ordinal) continue
+ for (const family of [...arrival.families]) {
+ if (arrivalDomain(family, arrival.serverId) === domain) {
+ arrival.families.delete(family)
+ }
+ }
+ if (arrival.families.size === 0) this.removeExact(key)
+ }
+ for (const [channelId, unknown] of this.sticky) {
+ for (const [family, pending] of [...unknown.families]) {
+ if (
+ pending.ordinal <= fence.ordinal
+ && arrivalDomain(family, unknown.serverId) === domain
+ ) {
+ unknown.families.delete(family)
+ }
+ }
+ if (unknown.families.size === 0) this.sticky.delete(channelId)
+ }
+ this.markAll.delete(domain)
+ for (const [key, sentinel] of this.sentinels) {
+ if (sentinel.ordinal <= fence.ordinal && key.endsWith(`\u0000${domain}`)) {
+ this.sentinels.delete(key)
+ }
+ }
+ changed = true
+ }
+ }
+ if (changed) this.publish()
+ }
+
+ absorbFamily(
+ family: AccountUnreadFamily,
+ sources: readonly AccountUnreadSource[],
+ options: {
+ truncated?: boolean
+ stale?: boolean
+ domain?: AccountUnreadDomain
+ } = {},
+ ) {
+ if (options.stale) return
+ const byChannel = new Map(sources.map((source) => [source.channelId, source]))
+ let changed = false
+ for (const source of sources) {
+ if (source.lastUnreadSeq > 0) {
+ const evidenceKey = this.evidenceKey(family, source.channelId)
+ this.evidence.set(
+ evidenceKey,
+ Math.max(this.evidence.get(evidenceKey) ?? 0, source.lastUnreadSeq),
+ )
+ }
+ }
+ for (const [key, arrival] of this.exact) {
+ if (!arrival.families.has(family)) continue
+ const source = byChannel.get(arrival.channelId)
+ const evidenceSeq = family === "inbox-mentions"
+ ? source?.lastMentionSeq ?? source?.lastUnreadSeq
+ : source?.lastUnreadSeq
+ if (evidenceSeq !== undefined && evidenceSeq !== null && evidenceSeq >= arrival.seq) {
+ arrival.families.delete(family)
+ changed = true
+ if (arrival.families.size === 0) this.removeExact(key)
+ }
+ }
+ for (const [channelId, unknown] of this.sticky) {
+ const pending = unknown.families.get(family)
+ if (!pending) continue
+ const source = byChannel.get(channelId)
+ const evidenceSeq = family === "inbox-mentions"
+ ? source?.lastMentionSeq ?? source?.lastUnreadSeq
+ : source?.lastUnreadSeq
+ if (evidenceSeq !== undefined && evidenceSeq !== null && evidenceSeq > pending.boundary) {
+ unknown.families.delete(family)
+ changed = true
+ if (unknown.families.size === 0) this.sticky.delete(channelId)
+ }
+ }
+ if (!options.truncated) {
+ const key = sentinelKey(family, options.domain ?? familyDomain(family))
+ const sentinel = this.sentinels.get(key)
+ if (
+ sentinel?.witnessChannelId
+ && sentinel.witnessFamily === family
+ ) {
+ const source = byChannel.get(sentinel.witnessChannelId)
+ const evidenceSeq = family === "inbox-mentions"
+ ? source?.lastMentionSeq ?? source?.lastUnreadSeq
+ : source?.lastUnreadSeq
+ if (evidenceSeq !== undefined && evidenceSeq !== null && evidenceSeq > sentinel.boundary) {
+ changed = this.sentinels.delete(key) || changed
+ }
+ }
+ }
+ if (changed) this.publish()
+ }
+
+ projectUnread(
+ family: AccountUnreadFamily,
+ channelId: string,
+ rawUnread: boolean,
+ sourceSeq?: number | null,
+ domain: AccountUnreadDomain = familyDomain(family),
+ ) {
+ const fence = this.markAll.get(domain)
+ const read = this.effectiveReadSeq(channelId)
+ const rawVisible = rawUnread
+ && !(sourceSeq && read >= sourceSeq)
+ && !fence
+ if (rawVisible) return true
+ const sentinel = this.sentinels.get(sentinelKey(family, domain))
+ if (sentinel && (!fence || sentinel.ordinal > fence.ordinal)) return true
+ for (const key of this.exactByChannel.get(channelId) ?? []) {
+ const arrival = this.exact.get(key)
+ if (!arrival || !arrival.families.has(family) || arrival.seq <= read) continue
+ if (!fence || arrival.ordinal > fence.ordinal) return true
+ }
+ const sticky = this.sticky.get(channelId)
+ const pending = sticky?.families.get(family)
+ if (pending) {
+ if (!fence || pending.ordinal > fence.ordinal) return true
+ }
+ return false
+ }
+
+ projectMentionCount(
+ family: "servers" | "inbox-mentions",
+ channelId: string,
+ rawCount: number,
+ sourceSeq?: number | null,
+ ) {
+ const fence = this.markAll.get("mentions")
+ const read = this.effectiveReadSeq(channelId)
+ let count = !fence && !(sourceSeq && read >= sourceSeq) ? rawCount : 0
+ for (const key of this.exactByChannel.get(channelId) ?? []) {
+ const arrival = this.exact.get(key)
+ if (
+ family === "inbox-mentions"
+ && arrival?.isMention
+ && arrival.families.has(family)
+ && arrival.seq > read
+ && !(sourceSeq && sourceSeq >= arrival.seq)
+ && (!fence || arrival.ordinal > fence.ordinal)
+ ) count += 1
+ }
+ return count
+ }
+
+ projectServerUnread(
+ serverId: string,
+ sources: readonly AccountUnreadSource[],
+ rawUnread = false,
+ ) {
+ if (sources.some((source) => this.projectUnread(
+ "servers",
+ source.channelId,
+ true,
+ source.lastUnreadSeq,
+ ))) return true
+ if (rawUnread && sources.length === 0 && !this.markAll.get("channels")) return true
+ const sentinel = this.sentinels.get(sentinelKey("servers", "channels"))
+ const fence = this.markAll.get("channels")
+ if (sentinel && (!fence || sentinel.ordinal > fence.ordinal)) return true
+ for (const arrival of this.exact.values()) {
+ if (
+ arrival.serverId === serverId
+ && this.projectUnread("servers", arrival.channelId, false)
+ ) return true
+ }
+ for (const unknown of this.sticky.values()) {
+ if (
+ unknown.serverId === serverId
+ && this.projectUnread("servers", unknown.channelId, false)
+ ) return true
+ }
+ return false
+ }
+
+ projectServerChannelUnread(
+ serverId: string,
+ channelId: string,
+ sources: readonly AccountUnreadSource[],
+ rawUnread = false,
+ ) {
+ const family = `server-detail:${serverId}` as const
+ if (sources.some((source) => this.projectUnread(
+ family,
+ source.channelId,
+ true,
+ source.lastUnreadSeq,
+ ))) return true
+ if (rawUnread && sources.length === 0 && !this.markAll.get("channels")) return true
+ const sentinel = this.sentinels.get(sentinelKey(family, "channels"))
+ const fence = this.markAll.get("channels")
+ if (sentinel && (!fence || sentinel.ordinal > fence.ordinal)) return true
+ for (const arrival of this.exact.values()) {
+ if (
+ arrival.serverId === serverId
+ && (arrival.channelId === channelId || arrival.railChannelId === channelId)
+ && this.projectUnread(family, arrival.channelId, false)
+ ) return true
+ }
+ for (const unknown of this.sticky.values()) {
+ if (
+ unknown.serverId === serverId
+ && (unknown.channelId === channelId || unknown.railChannelId === channelId)
+ && this.projectUnread(family, unknown.channelId, false)
+ ) return true
+ }
+ return false
+ }
+
+ projectForumParentUnread(
+ serverId: string,
+ parentChannelId: string,
+ rawBaseUnread: boolean,
+ sourceSeq: number | null | undefined,
+ renderedChildIds: ReadonlySet<string>,
+ ) {
+ const family = `server-detail:${serverId}` as const
+ if (this.projectUnread(family, parentChannelId, rawBaseUnread, sourceSeq)) return true
+ for (const arrival of this.exact.values()) {
+ if (
+ arrival.serverId === serverId
+ && arrival.railChannelId === parentChannelId
+ && !renderedChildIds.has(arrival.channelId)
+ && this.projectUnread(family, arrival.channelId, false)
+ ) return true
+ }
+ for (const unknown of this.sticky.values()) {
+ if (
+ unknown.serverId === serverId
+ && unknown.railChannelId === parentChannelId
+ && !renderedChildIds.has(unknown.channelId)
+ && this.projectUnread(family, unknown.channelId, false)
+ ) return true
+ }
+ return false
+ }
+
+ projectServerMentionCount(
+ _serverId: string,
+ sources: ReadonlyArray<{ channelId: string; count: number; lastSeq: number }>,
+ rawFallback = 0,
+ ) {
+ return sources.length === 0 && !this.markAll.get("mentions")
+ ? rawFallback
+ : sources.reduce((sum, source) => sum + this.projectMentionCount(
+ "servers",
+ source.channelId,
+ source.count,
+ source.lastSeq,
+ ), 0)
+ }
+
+ hasPending(family?: AccountUnreadFamily, domain?: AccountUnreadDomain) {
+ if (family && domain) {
+ const sentinel = this.sentinels.get(sentinelKey(family, domain))
+ const fence = this.markAll.get(domain)
+ if (sentinel && (!fence || sentinel.ordinal > fence.ordinal)) return true
+ }
+ if (family && !domain) {
+ const prefix = `${sentinelFamily(family)}\u0000`
+ for (const [key, sentinel] of this.sentinels) {
+ if (!key.startsWith(prefix)) continue
+ const sentinelDomain = key.slice(prefix.length) as AccountUnreadDomain
+ const fence = this.markAll.get(sentinelDomain)
+ if (!fence || sentinel.ordinal > fence.ordinal) return true
+ }
+ }
+ for (const arrival of this.exact.values()) {
+ if (family && !arrival.families.has(family)) continue
+ const arrivalDomain = family === "inbox-mentions" || arrival.isMention && domain === "mentions"
+ ? "mentions"
+ : arrival.serverId ? "channels" : "dms"
+ if (domain && arrivalDomain !== domain) continue
+ const fence = this.markAll.get(domain ?? arrivalDomain)
+ if (!fence || arrival.ordinal > fence.ordinal) return true
+ }
+ for (const unknown of this.sticky.values()) {
+ for (const [pendingFamily, pending] of unknown.families) {
+ if (family && pendingFamily !== family) continue
+ const pendingDomain = arrivalDomain(pendingFamily, unknown.serverId)
+ if (domain && pendingDomain !== domain) continue
+ const fence = this.markAll.get(domain ?? pendingDomain)
+ if (!fence || pending.ordinal > fence.ordinal) return true
+ }
+ }
+ return false
+ }
+
+ beginMarkAll(domain: AccountUnreadDomain): MarkAllToken {
+ const token: MarkAllToken = { domain, ordinal: this.ordinal, nonce: Symbol(domain) }
+ this.markAll.set(domain, { ...token, state: "pending", revision: null })
+ this.publish()
+ return token
+ }
+
+ commitMarkAll(token: MarkAllToken, revision: number) {
+ const fence = this.markAll.get(token.domain)
+ if (!fence || fence.nonce !== token.nonce) return
+ fence.state = "committed"
+ fence.revision = revision
+ this.publish()
+ }
+
+ rollbackMarkAll(token: MarkAllToken) {
+ const fence = this.markAll.get(token.domain)
+ if (!fence || fence.nonce !== token.nonce) return
+ this.markAll.delete(token.domain)
+ this.publish()
+ }
+
+ private recordSticky(
+ channelId: string,
+ families: AccountUnreadFamily[],
+ isMention: boolean,
+ serverId?: string,
+ railChannelId?: string,
+ ) {
+ const arrivalOrdinal = ++this.ordinal
+ let unknown = this.sticky.get(channelId)
+ if (!unknown) {
+ if (this.sticky.size >= MAX_STICKY_SCOPES) {
+ for (const family of families) {
+ const key = sentinelKey(family, arrivalDomain(family, serverId))
+ const existing = this.sentinels.get(key)
+ if (existing) {
+ existing.ordinal = arrivalOrdinal
+ if (
+ existing.witnessChannelId !== channelId
+ || existing.witnessFamily !== family
+ ) {
+ existing.witnessChannelId = null
+ existing.witnessFamily = null
+ }
+ } else {
+ this.sentinels.set(key, {
+ ordinal: arrivalOrdinal,
+ witnessChannelId: channelId,
+ witnessFamily: family,
+ boundary: this.evidence.get(this.evidenceKey(family, channelId)) ?? 0,
+ })
+ }
+ }
+ this.publish()
+ return
+ }
+ unknown = {
+ channelId,
+ serverId,
+ railChannelId,
+ isMention,
+ families: new Map(),
+ }
+ this.sticky.set(channelId, unknown)
+ }
+ unknown.isMention ||= isMention
+ unknown.serverId ??= serverId
+ unknown.railChannelId ??= railChannelId
+ for (const family of families) {
+ const pending = unknown.families.get(family)
+ if (pending) {
+ pending.ordinal = arrivalOrdinal
+ } else {
+ unknown.families.set(
+ family,
+ {
+ boundary: this.evidence.get(this.evidenceKey(family, channelId)) ?? 0,
+ ordinal: arrivalOrdinal,
+ },
+ )
+ }
+ }
+ this.publish()
+ }
+
+ private evidenceKey(family: AccountUnreadFamily, channelId: string) {
+ return `${family}\u0000${channelId}`
+ }
+
+ private effectiveReadSeq(channelId: string) {
+ let seq = this.readSeq.get(channelId) ?? 0
+ for (const optimistic of this.optimisticReads.values()) {
+ if (optimistic.channelId === channelId) seq = Math.max(seq, optimistic.seq)
+ }
+ return seq
+ }
+
+ private removeExact(key: string) {
+ const arrival = this.exact.get(key)!
+ this.exact.delete(key)
+ const channelKeys = this.exactByChannel.get(arrival.channelId)
+ channelKeys?.delete(key)
+ if (channelKeys?.size === 0) this.exactByChannel.delete(arrival.channelId)
+ }
+
+ private publish() {
+ this.version += 1
+ for (const listener of this.listeners) listener()
+ }
+}
+
+export function getAccountUnreadProjection(
+ queryClient: QueryClient,
+ ownerUserId: string,
+) {
+ if (ownerUserId !== "__anonymous__") activeOwners.set(queryClient, ownerUserId)
+ let byUser = owners.get(queryClient)
+ if (!byUser) {
+ byUser = new Map()
+ owners.set(queryClient, byUser)
+ }
+ let projection = byUser.get(ownerUserId)
+ if (!projection) {
+ projection = new AccountUnreadProjection(ownerUserId)
+ byUser.set(ownerUserId, projection)
+ }
+ return projection
+}
+
+export function getActiveAccountUnreadProjection(queryClient: QueryClient) {
+ return getAccountUnreadProjection(
+ queryClient,
+ activeOwners.get(queryClient) ?? "__anonymous__",
+ )
+}
+
+export function disposeAccountUnreadProjection(
+ queryClient: QueryClient,
+ ownerUserId?: string,
+) {
+ const byUser = owners.get(queryClient)
+ if (!byUser) return
+ if (ownerUserId) byUser.delete(ownerUserId)
+ else byUser.clear()
+ if (!ownerUserId || activeOwners.get(queryClient) === ownerUserId) {
+ activeOwners.delete(queryClient)
+ }
+ if (byUser.size === 0) owners.delete(queryClient)
+}
+
+export function acceptAccountUnreadPrimarySnapshot(
+ queryClient: QueryClient,
+ snapshot: {
+ revision: number
+ readStates: Array<{ channelId: string; lastReadSeq: number }>
+ },
+) {
+ const ownerUserId = activeOwners.get(queryClient)
+ if (!ownerUserId) return
+ owners.get(queryClient)?.get(ownerUserId)?.acceptPrimarySnapshot(snapshot)
+}
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.ts
index e4f29cf7f..b04f42eee 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
@@ -37,6 +37,7 @@ import {
releaseReadSurface,
submitReadIntent,
} from "@/hooks/community/read-coordinator"
+import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
beforeEach(async () => {
reconcileCommunityWsReconnect.mockClear()
@@ -376,6 +377,12 @@ describe("useCommunityWs — operation bundles", () => {
expect(capturedQueryClient.getQueryData<{ servers: Array<{ id: string; mentions: number }> }>(
communityKeys.servers(),
)?.servers[0]?.mentions).toBe(5)
+ const unreadProjection = getActiveAccountUnreadProjection(capturedQueryClient)
+ expect(unreadProjection.projectUnread("servers", "ch-1", false)).toBe(true)
+ // A correlated bundle carries seq=1 dispatch-locally, so a real visible
+ // 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(invalidationCount(communityKeys.servers())).toBe(1)
@@ -395,7 +402,52 @@ describe("useCommunityWs — operation bundles", () => {
}
})
- it("merges a fetching unread fence with batch mention invalidations into one replacement", async () => {
+ it("treats an ambiguous same-channel bundle as sticky instead of temporally pairing", async () => {
+ await mountHook({ viewerUserId: "viewer-1" })
+ const frame = await batchFor("ambiguous-bump", [
+ { ...message, message: { ...message.message, id: "ambiguous-1", seq: 1 } },
+ { ...message, message: { ...message.message, id: "ambiguous-2", seq: 2 } },
+ mentionEvents[1]!,
+ ])
+ capturedOnMessage!(frame)
+ const projection = getActiveAccountUnreadProjection(capturedQueryClient)
+ projection.recordRead("ch-1", 999)
+ expect(projection.projectUnread("servers", "ch-1", false)).toBe(true)
+ })
+
+ it("correlates a unique same-channel bump regardless of child order", async () => {
+ await mountHook({ viewerUserId: "viewer-1" })
+ const frame = await batchFor("reordered-bump", [
+ mentionEvents[1]!,
+ mentionEvents[2]!,
+ mentionEvents[0]!,
+ ])
+ capturedOnMessage!(frame)
+ const projection = getActiveAccountUnreadProjection(capturedQueryClient)
+ expect(projection.projectUnread("servers", "ch-1", false)).toBe(true)
+ projection.recordRead("ch-1", 1)
+ expect(projection.projectUnread("servers", "ch-1", false)).toBe(false)
+ })
+
+ it("does not borrow seq evidence for a different mention message id", async () => {
+ await mountHook({ viewerUserId: "viewer-1" })
+ const frame = await batchFor("mismatched-mention", [
+ message,
+ {
+ type: "community:mention.create",
+ userId: "viewer-1",
+ messageId: "different-message",
+ channelId: "ch-1",
+ authorName: "Alice",
+ },
+ ])
+ capturedOnMessage!(frame)
+ const projection = getActiveAccountUnreadProjection(capturedQueryClient)
+ projection.recordRead("ch-1", 999)
+ expect(projection.projectUnread("inbox-mentions", "ch-1", false)).toBe(true)
+ })
+
+ it("does not cancel or restart an in-flight raw server resource for a projected bump", async () => {
await mountHook({ viewerUserId: "viewer-1" })
const key = communityKeys.servers()
capturedQueryClient.setQueryData(key, {
@@ -404,11 +456,6 @@ describe("useCommunityWs — operation bundles", () => {
let queryCalls = 0
const queryFn = ({ signal }: { signal: AbortSignal }) => {
queryCalls += 1
- if (queryCalls > 1) {
- return Promise.resolve({
- servers: [{ id: "server-1", unread: true, mentions: 6 }],
- })
- }
return new Promise<never>((_resolve, reject) => {
signal.addEventListener("abort", () => {
reject(new DOMException("aborted", "AbortError"))
@@ -419,17 +466,14 @@ describe("useCommunityWs — operation bundles", () => {
.catch(() => undefined)
await vi.waitFor(() => expect(queryCalls).toBe(1))
const cancel = vi.spyOn(capturedQueryClient, "cancelQueries")
- const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")
capturedOnMessage!(await batchFor("message-fenced-mention", mentionEvents))
- await vi.waitFor(() => expect(queryCalls).toBe(2))
- await vi.waitFor(() => expect(capturedQueryClient.getQueryData<{
- servers: Array<{ unread: boolean; mentions: number }>
- }>(key)?.servers[0]).toMatchObject({ unread: true, mentions: 6 }))
- expect(cancel).toHaveBeenCalledTimes(1)
- expect(invalidate.mock.calls.filter(([filters]) =>
- JSON.stringify(filters.queryKey) === JSON.stringify(key))).toHaveLength(1)
+ expect(queryCalls).toBe(1)
+ expect(cancel).not.toHaveBeenCalled()
+ expect(getActiveAccountUnreadProjection(capturedQueryClient)
+ .projectServerUnread("server-1", [])).toBe(true)
+ await capturedQueryClient.cancelQueries({ queryKey: key, exact: true })
await first
})
@@ -539,7 +583,8 @@ describe("useCommunityWs — operation bundles", () => {
channels: [{ id: "text-parent", type: "text", unread: false }],
}],
})
- const setQueryData = vi.spyOn(capturedQueryClient, "setQueryData")
+ const unreadProjection = getActiveAccountUnreadProjection(capturedQueryClient)
+ const recordArrival = vi.spyOn(unreadProjection, "recordArrival")
.mockImplementationOnce(() => { throw new Error("second-child fault") })
vi.spyOn(capturedQueryClient, "invalidateQueries")
const events: CommunityWsEvent[] = [
@@ -575,7 +620,7 @@ describe("useCommunityWs — operation bundles", () => {
expect(getMessageOverlay({ kind: "channel", id: "ch-1", serverId: "s1" })
.liveById.has("message-before-second-child-fault")).toBe(true)
- setQueryData.mockRestore()
+ recordArrival.mockRestore()
const invalidationsAfterFailure = vi.mocked(capturedQueryClient.invalidateQueries).mock.calls.length
capturedOnMessage!(conflicting)
expect(reconcileCommunityWsReconnect).toHaveBeenCalledTimes(2)
@@ -593,9 +638,11 @@ describe("useCommunityWs — operation bundles", () => {
expect(useCommunityWsStore.getState().seenMessageIds.size).toBe(1)
expect(getMessageOverlay({ kind: "channel", id: "ch-1", serverId: "s1" }).liveById.size)
.toBe(1)
- expect(capturedQueryClient.getQueryData<{
- categories: Array<{ channels: Array<{ id: string; unread: boolean }> }>
- }>(communityKeys.server("s1"))?.categories[0]?.channels[0]?.unread).toBe(true)
+ expect(unreadProjection.projectServerChannelUnread(
+ "s1",
+ "text-parent",
+ [],
+ )).toBe(true)
const invalidationsAfterCompletion = vi.mocked(capturedQueryClient.invalidateQueries).mock.calls.length
capturedOnMessage!(frame)
@@ -699,9 +746,11 @@ describe("useCommunityWs — operation bundles", () => {
// All preceding children are legal committed-message projections. Their
// writes remain visible when the final parent projection throws.
expect(useCommunityWsStore.getState().seenMessageIds.has("message-before-fault")).toBe(true)
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(
- communityKeys.forumSidebarThreads("s1"),
- )?.threads).toMatchObject([{ id: "ch-1", unread: true }])
+ expect(getActiveAccountUnreadProjection(capturedQueryClient).projectUnread(
+ "server-detail:s1",
+ "ch-1",
+ false,
+ )).toBe(true)
expect(capturedQueryClient.getQueryData<{
servers: Array<{ id: string; mentions: number }>
}>(communityKeys.servers())?.servers[0]?.mentions).toBe(5)
@@ -723,9 +772,11 @@ describe("useCommunityWs — operation bundles", () => {
expect(capturedQueryClient.getQueryData<{
servers: Array<{ id: string; mentions: number }>
}>(communityKeys.servers())?.servers[0]?.mentions).toBe(5)
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(
- communityKeys.forumSidebarThreads("s1"),
- )?.threads).toMatchObject([{ id: "ch-1", unread: true }])
+ expect(getActiveAccountUnreadProjection(capturedQueryClient).projectUnread(
+ "server-detail:s1",
+ "ch-1",
+ false,
+ )).toBe(true)
expect(capturedQueryClient.getQueryData<{
pages: Array<{ messages: Array<{ thread: { messageCount: number } }> }>
}>(communityKeys.channelMessages("forum_1"))?.pages[0]?.messages[0]?.thread.messageCount)
@@ -770,7 +821,8 @@ describe("useCommunityWs — operation bundles", () => {
}
throw new Error(`unexpected API fetch: ${String(url)}`)
})
- const setQueryData = vi.spyOn(capturedQueryClient, "setQueryData")
+ const unreadProjection = getActiveAccountUnreadProjection(capturedQueryClient)
+ const recordArrival = vi.spyOn(unreadProjection, "recordArrival")
.mockImplementationOnce(() => { throw new Error("later child fault") })
vi.spyOn(capturedQueryClient, "invalidateQueries")
const messageId = `retry-${retryTiming}`
@@ -811,7 +863,7 @@ describe("useCommunityWs — operation bundles", () => {
seq: 1,
})).toBe(true)
- setQueryData.mockRestore()
+ recordArrival.mockRestore()
if (retryTiming === "before") capturedOnMessage!(frame)
await vi.advanceTimersByTimeAsync(500)
expect(invalidationCount(communityKeys.inbox())).toBe(1)
diff --git a/src/web/src/hooks/community/community-ws/handler-context.ts b/src/web/src/hooks/community/community-ws/handler-context.ts
index 5a034413b..c1c7338f6 100644
--- a/src/web/src/hooks/community/community-ws/handler-context.ts
+++ b/src/web/src/hooks/community/community-ws/handler-context.ts
@@ -2,6 +2,7 @@ import type { QueryClient } from "@tanstack/react-query"
import type { useCommunityStore } from "@/stores/community"
import type { useCommunityWsStore } from "@/stores/community/ws"
import type { CommunityWsProjectionTransaction } from "@/hooks/community/community-ws/projection-transaction"
+import type { CommunityWsEvent } from "@alook/shared"
export type Subscription = {
// The focused regular channel/thread.
@@ -39,6 +40,16 @@ export type CommunityWsDispatchContext = {
export type CommunityWsHandlerContext = CommunityWsDispatchContext & {
projection: CommunityWsProjectionTransaction
+ unreadBumpEvidence?: ReadonlyMap<CommunityWsEvent, {
+ messageId: string
+ seq: number
+ createdAt: string
+ }>
+ messageEvidenceByChannel?: ReadonlyMap<string, {
+ messageId: string
+ seq: number
+ createdAt: string
+ }>
}
export type MessageEventContext = CommunityWsHandlerContext
@@ -57,7 +68,7 @@ export type MembershipEventContext = Pick<
export type SocialEventContext = Pick<
CommunityWsHandlerContext,
"deliveryMode" | "queryClient" | "sub" | "viewerUserIdRef" | "projection"
- | "scheduleInboxInvalidate"
+ | "scheduleInboxInvalidate" | "unreadBumpEvidence" | "messageEvidenceByChannel"
>
export type PresenceMachineEventContext = Pick<
CommunityWsHandlerContext,
diff --git a/src/web/src/hooks/community/community-ws/invalidation-projections.ts b/src/web/src/hooks/community/community-ws/invalidation-projections.ts
index 45025398c..db32fbc38 100644
--- a/src/web/src/hooks/community/community-ws/invalidation-projections.ts
+++ b/src/web/src/hooks/community/community-ws/invalidation-projections.ts
@@ -29,15 +29,6 @@ export function invalidateServersList(
})
}
-export function fenceServersList(
- projection: CommunityWsProjectionTransaction,
-) {
- projection.fence("servers-list", {
- queryKey: communityKeys.servers(),
- exact: true,
- })
-}
-
export function invalidateChannelMembers(
projection: CommunityWsProjectionTransaction,
channelId: string,
diff --git a/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts b/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts
index 38cdf30db..368d1de1c 100644
--- a/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts
+++ b/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts
@@ -2,6 +2,7 @@ import { notifyManager, type QueryClient, type QueryKey } from "@tanstack/react-
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import { projectReadCoordinatorSnapshot } from "@/hooks/community/read-coordinator-snapshot-projection"
+import { acceptAccountUnreadPrimarySnapshot } from "@/hooks/community/account-unread-projection"
type AccountReadState = {
channelId: string
@@ -98,12 +99,14 @@ function applyAccountReadStateSnapshot(
// concurrent auth/live reconciliations joined the same HTTP request.
projectReadStateRows(queryClient, snapshot)
projectReadCoordinatorSnapshot(queryClient, snapshot)
+ acceptAccountUnreadPrimarySnapshot(queryClient, snapshot)
return "stale" as const
}
notifyManager.batch(() => {
queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), snapshot)
projectReadStateRows(queryClient, snapshot)
projectReadCoordinatorSnapshot(queryClient, snapshot)
+ acceptAccountUnreadPrimarySnapshot(queryClient, snapshot)
})
return "applied" as const
}
diff --git a/src/web/src/hooks/community/community-ws/registry.ts b/src/web/src/hooks/community/community-ws/registry.ts
index 545ea33ad..d33a08922 100644
--- a/src/web/src/hooks/community/community-ws/registry.ts
+++ b/src/web/src/hooks/community/community-ws/registry.ts
@@ -116,8 +116,52 @@ export function dispatchCommunityWsEvents(
events: readonly CommunityWsEvent[],
context: CommunityWsDispatchContext,
) {
+ const createsByChannel = new Map<string, Array<Extract<CommunityWsEvent, {
+ type: "community:message.create"
+ }>>>()
+ for (const event of events) {
+ if (event.type !== "community:message.create") continue
+ const creates = createsByChannel.get(event.channelId) ?? []
+ creates.push(event)
+ createsByChannel.set(event.channelId, creates)
+ }
+ const unreadBumpEvidence = new Map<CommunityWsEvent, {
+ messageId: string
+ seq: number
+ createdAt: string
+ }>()
+ const messageEvidenceByChannel = new Map<string, {
+ messageId: string
+ seq: number
+ createdAt: string
+ }>()
+ for (const [channelId, creates] of createsByChannel) {
+ if (creates.length !== 1) continue
+ const message = creates[0]!.message
+ messageEvidenceByChannel.set(channelId, {
+ messageId: message.id,
+ seq: message.seq,
+ createdAt: message.createdAt,
+ })
+ }
+ for (const event of events) {
+ if (event.type !== "community:unread.bump") continue
+ const creates = createsByChannel.get(event.channelId) ?? []
+ if (creates.length !== 1) continue
+ const message = creates[0]!.message
+ unreadBumpEvidence.set(event, {
+ messageId: message.id,
+ seq: message.seq,
+ createdAt: message.createdAt,
+ })
+ }
runCommunityWsProjectionTransaction(context.queryClient, (projection) => {
- const handlerContext: CommunityWsHandlerContext = { ...context, projection }
+ const handlerContext: CommunityWsHandlerContext = {
+ ...context,
+ projection,
+ unreadBumpEvidence,
+ messageEvidenceByChannel,
+ }
for (const event of events) {
const entry = communityWsRegistry[event.type] as RegistryEntry<typeof event.type>
entry.handler(event, handlerContext)
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.ts
index 5ca7ed407..89989e422 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
@@ -2,23 +2,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import type {
CommunityFriendRequest,
CommunityMentionCreate,
- CommunityMessageCreate,
} from "@alook/shared"
import { getMessageOverlay } from "@/stores/community/message-stream"
import { communityKeys } from "@/lib/query-keys"
-import type { ServerDetail } from "../use-servers"
-import {
- deriveForumSidebarProjection,
- patchForumSidebarUnread,
- reconcileForumSidebarUnreadFallbacks,
- type ForumSidebarQueryData,
- type ForumSidebarUnreadFallbackState,
-} from "../use-forum-sidebar-threads"
+import { getActiveAccountUnreadProjection } from "../account-unread-projection"
import {
capturedOnMessage,
capturedQueryClient,
cleanupCommunityWsHarness,
- forumSidebarFixture,
messageCreate,
mountHook,
resetCommunityWsHarness,
@@ -29,415 +20,115 @@ import {
beforeEach(resetCommunityWsHarness)
afterEach(cleanupCommunityWsHarness)
-describe("useCommunityWs — message.create patches channel unread in the open server's cache", () => {
- function serverDetailFixture(channelId: string, type = "text") {
+describe("useCommunityWs — account unread projection", () => {
+ function serverDetailFixture(channelId: string) {
return {
id: "srv_open",
name: "Server",
description: "",
icon: null,
ownerId: "u_owner",
- categories: [
- { id: "cat_A", name: "Category A", channels: [{ id: channelId, name: "random", type, active: false, unread: false }] },
- ],
+ categories: [{
+ id: "cat_A",
+ name: "Category A",
+ channels: [{
+ id: channelId,
+ name: "random",
+ type: "text",
+ active: false,
+ unread: false,
+ }],
+ }],
}
}
- it("flips the channel's unread to true on unread.bump when it belongs to the currently-open server's cached ServerDetail", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_open")
- capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_random"))
-
- capturedOnMessage!(unreadBump("ch_random", "u_me"))
-
- const cache = capturedQueryClient.getQueryData<{
- categories: { channels: { id: string; unread: boolean }[] }[]
- }>(communityKeys.server("srv_open"))
- expect(cache?.categories[0].channels[0]).toMatchObject({ id: "ch_random", unread: true })
- })
-
- it("routes a child unread.bump to its loaded forum-sidebar row instead of the parent forum", async () => {
- await mountHook({ viewerUserId: "u_me" })
- capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("forum_1"))
- const sidebarKey = communityKeys.forumSidebarThreads("srv_open")
- capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture())
-
- capturedOnMessage!(unreadBump("post_1", "u_me", {
- serverId: "srv_open",
- railChannelId: "forum_1",
- }))
-
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(sidebarKey)?.threads[0].unread)
- .toBe(true)
- expect(capturedQueryClient.getQueryData<ReturnType<typeof serverDetailFixture>>(
- communityKeys.server("srv_open"),
- )?.categories[0].channels[0].unread).toBe(false)
- expect(capturedQueryClient.getQueryData<ServerDetail>(
- communityKeys.server("srv_open"),
- )?.forumUnreadState?.forum_1?.childIds).toEqual(["post_1"])
- })
-
- it("keeps an inactive retained-only child on the parent fallback, then transfers it on the activation render", async () => {
+ it("records a viewer bump without mutating raw server resources", async () => {
await mountHook({ viewerUserId: "u_me" })
- const serverKey = communityKeys.server("srv_open")
- const baseKey = communityKeys.forumSidebarThreads("srv_open")
- const retainedKey = communityKeys.forumSidebarRetained("srv_open", "post_extra")
- capturedQueryClient.setQueryData(serverKey, serverDetailFixture("forum_1", "forum"))
- capturedQueryClient.setQueryData(baseKey, forumSidebarFixture([
- "post_1", "post_2", "post_3", "post_4", "post_5",
- ]))
- capturedQueryClient.setQueryData(retainedKey, {
- ...forumSidebarFixture(["post_extra"]).threads[0],
- })
+ const key = communityKeys.server("srv_open")
+ const raw = serverDetailFixture("ch_random")
+ capturedQueryClient.setQueryData(key, raw)
- capturedOnMessage!(unreadBump("post_extra", "u_me", {
- serverId: "srv_open",
- railChannelId: "forum_1",
- }))
-
- expect(capturedQueryClient.getQueryData<ServerDetail>(serverKey)
- ?.categories[0]?.channels[0]?.unread).toBe(true)
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>["threads"][number]>(
- retainedKey,
- )?.unread).toBe(false)
+ capturedOnMessage!(unreadBump("ch_random", "u_me", { serverId: "srv_open" }))
- const ownership = capturedQueryClient.getQueryData<ServerDetail>(serverKey)?.forumUnreadState
- const active = deriveForumSidebarProjection(
- capturedQueryClient.getQueryData(baseKey),
- capturedQueryClient.getQueryData(retainedKey),
- ownership,
- )
- expect(active.threads.find((thread) => thread.id === "post_extra")?.unread).toBe(true)
- expect(active.parentUnread.forum_1).toBe(false)
+ expect(capturedQueryClient.getQueryData(key)).toBe(raw)
+ const projection = getActiveAccountUnreadProjection(capturedQueryClient)
+ expect(projection.projectServerChannelUnread(
+ "srv_open",
+ "ch_random",
+ [],
+ )).toBe(true)
+ expect(projection.projectServerUnread("srv_open", [])).toBe(true)
})
- it("keeps a canonical fifth child on the parent fallback when an active extra displaces it", async () => {
+ it("keeps a focused bump unread until the visible-row observer submits a read", async () => {
const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().subscribe({ channelId: "post_extra" })
+ useCommunityStore.getState().subscribe({ channelId: "ch_focused" })
+ resetHookMemoization()
await mountHook({ viewerUserId: "u_me" })
- const serverKey = communityKeys.server("srv_open")
- const baseKey = communityKeys.forumSidebarThreads("srv_open")
- capturedQueryClient.setQueryData(serverKey, serverDetailFixture("forum_1", "forum"))
- capturedQueryClient.setQueryData(baseKey, forumSidebarFixture([
- "post_1", "post_2", "post_3", "post_4", "post_5",
- ]))
- capturedQueryClient.setQueryData(
- communityKeys.forumSidebarRetained("srv_open", "post_extra"),
- forumSidebarFixture(["post_extra"]).threads[0],
- )
- capturedOnMessage!(unreadBump("post_5", "u_me", {
- serverId: "srv_open",
- railChannelId: "forum_1",
- }))
+ capturedOnMessage!(unreadBump("ch_focused", "u_me", { serverId: "srv_open" }))
- expect(capturedQueryClient.getQueryData<ServerDetail>(serverKey)
- ?.categories[0]?.channels[0]?.unread).toBe(true)
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(baseKey)
- ?.threads.find((thread) => thread.id === "post_5")?.unread).toBe(false)
+ const projection = getActiveAccountUnreadProjection(capturedQueryClient)
+ expect(projection.projectUnread(
+ "server-detail:srv_open",
+ "ch_focused",
+ false,
+ )).toBe(true)
+ projection.recordRead("ch_focused", 999)
+ expect(projection.projectUnread(
+ "server-detail:srv_open",
+ "ch_focused",
+ false,
+ )).toBe(true)
})
- it("falls back to the parent forum dot when the child has no locatable sidebar row", async () => {
+ it("uses railChannelId only as a parent fallback and leaves raw rows untouched", async () => {
await mountHook({ viewerUserId: "u_me" })
- capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("forum_1"))
- capturedQueryClient.setQueryData(
- communityKeys.forumSidebarThreads("srv_open"),
- forumSidebarFixture([]),
- )
+ const key = communityKeys.server("srv_open")
+ const raw = serverDetailFixture("forum_1")
+ capturedQueryClient.setQueryData(key, raw)
- capturedOnMessage!(unreadBump("post_missing", "u_me", {
+ capturedOnMessage!(unreadBump("post_1", "u_me", {
serverId: "srv_open",
railChannelId: "forum_1",
}))
- expect(capturedQueryClient.getQueryData<ReturnType<typeof serverDetailFixture>>(
- communityKeys.server("srv_open"),
- )?.categories[0].channels[0].unread).toBe(true)
- expect(capturedQueryClient.getQueryData<ForumSidebarUnreadFallbackState>(
- communityKeys.forumSidebarUnreadFallbacks("srv_open"),
- )).toEqual({
- forum_1: { baseUnread: false, childIds: ["post_missing"] },
- })
+ const projection = getActiveAccountUnreadProjection(capturedQueryClient)
+ expect(projection.projectForumParentUnread(
+ "srv_open",
+ "forum_1",
+ false,
+ undefined,
+ new Set(),
+ )).toBe(true)
+ expect(capturedQueryClient.getQueryData(key)).toBe(raw)
})
- it("moves message.create → unread.bump fallback ownership to the refetched child", async () => {
+ it("never increments a numeric rail badge from an unsequenced isMention hint", async () => {
await mountHook({ viewerUserId: "u_me" })
- const serverKey = communityKeys.server("srv_open")
- const sidebarKey = communityKeys.forumSidebarThreads("srv_open")
- capturedQueryClient.setQueryData(serverKey, serverDetailFixture("forum_1", "forum"))
- capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture([]))
-
- capturedOnMessage!({
- ...messageCreate("post_new"),
- serverId: "srv_open",
- parentChannelId: "forum_1",
- } satisfies CommunityMessageCreate)
- await vi.waitFor(() => {
- expect(capturedQueryClient.getQueryState(sidebarKey)?.isInvalidated).toBe(true)
- })
-
- capturedOnMessage!(unreadBump("post_new", "u_me", {
- serverId: "srv_open",
- railChannelId: "forum_1",
+ capturedOnMessage!(unreadBump("ch_a", "u_me", {
+ serverId: "srv_x",
+ isMention: true,
}))
- expect(capturedQueryClient.getQueryData<ReturnType<typeof serverDetailFixture>>(
- serverKey,
- )?.categories[0].channels[0].unread).toBe(true)
-
- const refetched = forumSidebarFixture(["post_new"])
- refetched.threads[0]!.unread = true
- capturedQueryClient.setQueryData(sidebarKey, refetched)
- reconcileForumSidebarUnreadFallbacks(capturedQueryClient, "srv_open", ["post_new"])
-
- expect(capturedQueryClient.getQueryData<ForumSidebarQueryData>(sidebarKey)?.threads[0]?.unread).toBe(true)
- expect(capturedQueryClient.getQueryData<ReturnType<typeof serverDetailFixture>>(
- serverKey,
- )?.categories[0].channels[0].unread).toBe(false)
-
- capturedQueryClient.setQueryData<ForumSidebarQueryData>(sidebarKey, (data) =>
- patchForumSidebarUnread(data, "post_new", false),
- )
- expect(capturedQueryClient.getQueryData<ForumSidebarQueryData>(sidebarKey)?.threads[0]?.unread).toBe(false)
- expect(capturedQueryClient.getQueryData<ReturnType<typeof serverDetailFixture>>(
- serverKey,
- )?.categories[0].channels[0].unread).toBe(false)
- })
-
- it("message.create alone does NOT flip the sidebar unread (mute-gated bump is the only trigger now)", async () => {
- // Regression pin: mute ≠ blindness. The message.create still arrives (and
- // content syncs), but the unread dot is flipped ONLY by the server's
- // per-recipient, mute-gated unread.bump — so a muted channel's message.create
- // must NOT light the dot. Don't "fix" this back onto message.create.
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_open")
- capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_random"))
-
- capturedOnMessage!(messageCreate("ch_random"))
-
- const cache = capturedQueryClient.getQueryData<{
- categories: { channels: { id: string; unread: boolean }[] }[]
- }>(communityKeys.server("srv_open"))
- expect(cache?.categories[0].channels[0].unread).toBe(false)
- })
-
- it("does NOT flip unread on a bump addressed to a different user", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_open")
- capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_random"))
-
- capturedOnMessage!(unreadBump("ch_random", "someone_else"))
-
- const cache = capturedQueryClient.getQueryData<{
- categories: { channels: { id: string; unread: boolean }[] }[]
- }>(communityKeys.server("srv_open"))
- expect(cache?.categories[0].channels[0].unread).toBe(false)
- })
-
- it("does NOT flip unread for the currently-subscribed (active) channel", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_open")
- useCommunityStore.getState().subscribe({ channelId: "ch_random" })
- resetHookMemoization()
- await mountHook({ viewerUserId: "u_me" })
- capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_random"))
-
- capturedOnMessage!(unreadBump("ch_random", "u_me"))
-
- const cache = capturedQueryClient.getQueryData<{
- categories: { channels: { id: string; unread: boolean }[] }[]
- }>(communityKeys.server("srv_open"))
- expect(cache?.categories[0].channels[0].unread).toBe(false)
- })
-
- it("is a no-op when the channel isn't present in the currently cached ServerDetail (different server / no cache)", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_open")
- capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_other"))
-
- expect(() => capturedOnMessage!(unreadBump("ch_random", "u_me"))).not.toThrow()
-
- const cache = capturedQueryClient.getQueryData<{
- categories: { channels: { id: string; unread: boolean }[] }[]
- }>(communityKeys.server("srv_open"))
- // Untouched — the fixture's own channel stays unread: false.
- expect(cache?.categories[0].channels[0]).toMatchObject({ id: "ch_other", unread: false })
- })
-
- it("does not crash and is a no-op when no server is currently open", async () => {
- await mountHook({ viewerUserId: "u_me" })
- expect(() => capturedOnMessage!(unreadBump("ch_random", "u_me"))).not.toThrow()
- })
-
- // ── inbox-dot-ws-driven ② : bump carries serverId / railChannelId / isMention ──
-
- it("lights the dot on the bump's OWN serverId, even when a DIFFERENT server is open (the cross-server bug)", async () => {
- // The core fix: previously the handler only patched the currently-open
- // server, so a message in another server never lit its dot. With
- // `serverId` on the bump we patch the right server's detail regardless of
- // which one is focused.
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_open") // a different server is focused
- capturedQueryClient.setQueryData(communityKeys.server("srv_other"), serverDetailFixture("ch_bg"))
-
- capturedOnMessage!(unreadBump("ch_bg", "u_me", { serverId: "srv_other" }))
-
- const cache = capturedQueryClient.getQueryData<{
- categories: { channels: { id: string; unread: boolean }[] }[]
- }>(communityKeys.server("srv_other"))
- expect(cache?.categories[0].channels[0]).toMatchObject({ id: "ch_bg", unread: true })
- })
-
- it("lights the PARENT channel row for a thread bump (railChannelId), not the thread's own id", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_open")
- // The tree row is the parent channel; the thread has no independent row.
- capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_parent"))
-
- // channelId = the thread's id (true scope), railChannelId = parent row.
- capturedOnMessage!(unreadBump("ch_thread", "u_me", { serverId: "srv_open", railChannelId: "ch_parent" }))
-
- const cache = capturedQueryClient.getQueryData<{
- categories: { channels: { id: string; unread: boolean }[] }[]
- }>(communityKeys.server("srv_open"))
- expect(cache?.categories[0].channels[0]).toMatchObject({ id: "ch_parent", unread: true })
+ expect(getActiveAccountUnreadProjection(capturedQueryClient)
+ .projectServerMentionCount("srv_x", [], 7)).toBe(7)
})
- it("suppresses the dot when the viewer is looking at the RAIL row (thread bump whose parent is open)", async () => {
+ it("ignores bumps addressed to a different account", async () => {
await mountHook({ viewerUserId: "u_me" })
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_open")
- useCommunityStore.getState().subscribe({ channelId: "ch_parent" }) // parent row is open
- resetHookMemoization()
- await mountHook({ viewerUserId: "u_me" })
- capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_parent"))
-
- capturedOnMessage!(unreadBump("ch_thread", "u_me", { serverId: "srv_open", railChannelId: "ch_parent" }))
-
- const cache = capturedQueryClient.getQueryData<{
- categories: { channels: { id: string; unread: boolean }[] }[]
- }>(communityKeys.server("srv_open"))
- expect(cache?.categories[0].channels[0].unread).toBe(false)
+ capturedOnMessage!(unreadBump("ch_random", "someone_else", { serverId: "srv_open" }))
+ expect(getActiveAccountUnreadProjection(capturedQueryClient)
+ .projectServerUnread("srv_open", [])).toBe(false)
})
- it("bumps the rail mention badge (servers() mentions +1) ONLY when isMention is set", async () => {
+ it("message.create alone syncs content but does not manufacture unread authority", async () => {
await mountHook({ viewerUserId: "u_me" })
- capturedQueryClient.setQueryData(communityKeys.servers(), {
- servers: [{ id: "srv_x", name: "X", initial: "X", active: false, mentions: 2, icon: null }],
- })
-
- // Plain unread (no isMention) → mention count unchanged.
- capturedOnMessage!(unreadBump("ch_a", "u_me", { serverId: "srv_x" }))
- let servers = capturedQueryClient.getQueryData<{ servers: { id: string; mentions: number }[] }>(communityKeys.servers())
- expect(servers?.servers[0].mentions).toBe(2)
-
- // Mention → +1.
- capturedOnMessage!(unreadBump("ch_a", "u_me", { serverId: "srv_x", isMention: true }))
- servers = capturedQueryClient.getQueryData<{ servers: { id: string; mentions: number }[] }>(communityKeys.servers())
- expect(servers?.servers[0].mentions).toBe(3)
- })
-
- it("projects the addressed background server row to unread without touching siblings", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const sibling = { id: "srv_y", name: "Y", initial: "Y", active: false, unread: false, mentions: 0 }
- capturedQueryClient.setQueryData(communityKeys.servers(), {
- servers: [
- { id: "srv_x", name: "X", initial: "X", active: false, unread: false, mentions: 0 },
- sibling,
- ],
- })
-
- capturedOnMessage!(unreadBump("ch_a", "u_me", { serverId: "srv_x" }))
-
- const data = capturedQueryClient.getQueryData<{
- servers: Array<{ id: string; unread: boolean }>
- }>(communityKeys.servers())!
- expect(data.servers.map(({ id, unread }) => ({ id, unread }))).toEqual([
- { id: "srv_x", unread: true },
- { id: "srv_y", unread: false },
- ])
- expect(data.servers[1]).toBe(sibling)
- })
-
- it("preserves response/list/row identity and skips invalidation for an idle already-true row", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const row = { id: "srv_x", name: "X", initial: "X", active: false, unread: true, mentions: 0 }
- const seeded = { servers: [row] }
- capturedQueryClient.setQueryData(communityKeys.servers(), seeded)
- const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")
-
- capturedOnMessage!(unreadBump("ch_a", "u_me", { serverId: "srv_x" }))
-
- const data = capturedQueryClient.getQueryData(communityKeys.servers())
- expect(data).toBe(seeded)
- expect((data as typeof seeded).servers).toBe(seeded.servers)
- expect((data as typeof seeded).servers[0]).toBe(row)
- expect(invalidate).not.toHaveBeenCalled()
- })
-
- it.each([
- ["absent", undefined],
- ["cached false", false],
- ["cached true", true],
- ] as const)("fences a %s in-flight server-list request and converges to post-commit true", async (_label, cachedUnread) => {
- await mountHook({ viewerUserId: "u_me" })
- const key = communityKeys.servers()
- if (cachedUnread !== undefined) {
- capturedQueryClient.setQueryData(key, {
- servers: [{ id: "srv_x", name: "X", initial: "X", active: false, unread: cachedUnread, mentions: 0 }],
- })
- }
- let calls = 0
- let firstAborted = false
- const queryFn = ({ signal }: { signal: AbortSignal }) => {
- calls += 1
- if (calls > 1) {
- return Promise.resolve({
- servers: [{ id: "srv_x", name: "X", initial: "X", active: false, unread: true, mentions: 0 }],
- })
- }
- return new Promise<never>((_resolve, reject) => {
- signal.addEventListener("abort", () => {
- firstAborted = true
- reject(new DOMException("aborted", "AbortError"))
- }, { once: true })
- })
- }
- const first = capturedQueryClient.fetchQuery({ queryKey: key, queryFn, staleTime: 0 })
- .catch(() => undefined)
- await vi.waitFor(() => expect(calls).toBe(1))
-
- capturedOnMessage!(unreadBump("ch_a", "u_me", { serverId: "srv_x" }))
-
- await vi.waitFor(() => expect(calls).toBe(2))
- await vi.waitFor(() => expect(capturedQueryClient.getQueryData<{
- servers: Array<{ unread: boolean }>
- }>(key)?.servers[0]?.unread).toBe(true))
- expect(firstAborted).toBe(true)
- await first
- })
-
- it("leaves an absent or unrelated server rail cache unchanged on a legacy mention bump", async () => {
- await mountHook({ viewerUserId: "u_me" })
-
- capturedOnMessage!(unreadBump("ch_a", "u_me", { serverId: "srv_x", isMention: true }))
- expect(capturedQueryClient.getQueryData(communityKeys.servers())).toBeUndefined()
-
- const unrelated = {
- servers: [{ id: "srv_other", name: "Other", initial: "O", active: false, mentions: 4, icon: null }],
- }
- capturedQueryClient.setQueryData(communityKeys.servers(), unrelated)
- capturedOnMessage!(unreadBump("ch_a", "u_me", { serverId: "srv_x", isMention: true }))
- expect(capturedQueryClient.getQueryData(communityKeys.servers())).toEqual(unrelated)
+ capturedOnMessage!(messageCreate("ch_random"))
+ expect(getActiveAccountUnreadProjection(capturedQueryClient)
+ .projectServerUnread("s1", [])).toBe(false)
})
- it("existing focused-channel message patch and debounced inbox invalidation still fire on message.create", async () => {
+ it("keeps focused content sync and the existing debounced Inbox refresh", async () => {
vi.useFakeTimers()
try {
await mountHook({ viewerUserId: "u_me" })
@@ -446,32 +137,25 @@ describe("useCommunityWs — message.create patches channel unread in the open s
useCommunityStore.getState().subscribe({ channelId: "ch_focused" })
resetHookMemoization()
await mountHook({ viewerUserId: "u_me" })
-
- capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_focused"), {
- pages: [{ messages: [], hasMore: false }],
- pageParams: [null],
- })
- capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("ch_focused"))
const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
capturedOnMessage!(messageCreate("ch_focused"))
await vi.advanceTimersByTimeAsync(500)
- const messagesCache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(
- communityKeys.channelMessages("ch_focused"),
- )
- expect(messagesCache?.pages[0].messages).toEqual([])
- expect(getMessageOverlay({ kind: "channel", id: "ch_focused", serverId: "s1" }).liveById.has("m_1")).toBe(true)
- const inboxCalls = invalidateSpy.mock.calls.filter((c) => {
- const key = c[0]?.queryKey
- return Array.isArray(key) && key.includes("inbox")
- })
- expect(inboxCalls).toHaveLength(1)
+ expect(getMessageOverlay({
+ kind: "channel",
+ id: "ch_focused",
+ serverId: "s1",
+ }).liveById.has("m_1")).toBe(true)
+ expect(invalidateSpy.mock.calls.some((call) => (
+ (call[0]?.queryKey as unknown[] | undefined)?.includes("inbox")
+ ))).toBe(true)
} finally {
vi.useRealTimers()
}
})
})
+
describe("useCommunityWs — friend + mention → invalidate", () => {
it("friend.request invalidates communityKeys.friends()", async () => {
await mountHook()
@@ -487,12 +171,9 @@ describe("useCommunityWs — friend + mention → invalidate", () => {
},
}
capturedOnMessage!(event)
- expect(
- spy.mock.calls.some((c) => {
- const key = c[0]?.queryKey as unknown[] | undefined
- return Array.isArray(key) && key.includes("friends")
- }),
- ).toBe(true)
+ expect(spy.mock.calls.some((call) => (
+ (call[0]?.queryKey as unknown[] | undefined)?.includes("friends")
+ ))).toBe(true)
})
it("routes mention.create through the debounced Inbox owner", async () => {
@@ -509,18 +190,15 @@ describe("useCommunityWs — friend + mention → invalidate", () => {
capturedOnMessage!(event)
expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.inbox() })
await vi.advanceTimersByTimeAsync(500)
- expect(
- spy.mock.calls.some((c) => {
- const key = c[0]?.queryKey as unknown[] | undefined
- return Array.isArray(key) && key.includes("inbox")
- }),
- ).toBe(true)
+ expect(spy.mock.calls.some((call) => (
+ (call[0]?.queryKey as unknown[] | undefined)?.includes("inbox")
+ ))).toBe(true)
} finally {
vi.useRealTimers()
}
})
- it("mention.create also invalidates communityKeys.servers() so the rail badge ticks", async () => {
+ it("mention.create invalidates servers so authoritative source counts refresh", async () => {
await mountHook()
const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
const event: CommunityMentionCreate = {
@@ -530,10 +208,9 @@ describe("useCommunityWs — friend + mention → invalidate", () => {
authorName: "A",
}
capturedOnMessage!(event)
- const serversInvalidates = spy.mock.calls.filter((c) => {
- const key = c[0]?.queryKey as unknown[] | undefined
- return Array.isArray(key) && key.length === 2 && key[0] === "community" && key[1] === "servers"
- })
- expect(serversInvalidates).toHaveLength(1)
+ expect(spy.mock.calls.filter((call) => {
+ const key = call[0]?.queryKey as unknown[] | undefined
+ return key?.length === 2 && key[0] === "community" && key[1] === "servers"
+ })).toHaveLength(1)
})
})
diff --git a/src/web/src/hooks/community/community-ws/social-events.ts b/src/web/src/hooks/community/community-ws/social-events.ts
index 8fc03fa2e..a773e01c0 100644
--- a/src/web/src/hooks/community/community-ws/social-events.ts
+++ b/src/web/src/hooks/community/community-ws/social-events.ts
@@ -9,19 +9,8 @@ import type {
CommunityReadStateAdvanced,
CommunityWsEvent,
} from "@alook/shared"
-import { communityKeys } from "@/lib/query-keys"
-import { useCommunityStore } from "@/stores/community"
-import { patchChannelUnread } from "@/hooks/community/server-detail-cache"
-import type { ServersResponse, ServerDetail } from "@/hooks/community/use-servers"
-import {
- hasProjectedForumSidebarThread,
- patchForumSidebarUnreadExact,
- recordForumSidebarChildUnread,
- setForumSidebarParentUnreadBase,
-} from "@/hooks/community/use-forum-sidebar-threads"
import type { SocialEventContext } from "@/hooks/community/community-ws/handler-context"
import {
- fenceServersList,
invalidateFriends,
invalidateServersList,
} from "./invalidation-projections"
@@ -29,6 +18,7 @@ import {
projectReadStateEnvelope,
reconcileAccountReadState,
} from "./read-state-reconciliation"
+import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
export function handleReadStateAdvanced(
event: CommunityReadStateAdvanced,
@@ -71,105 +61,28 @@ type CommunityUnreadBump = Extract<
// defensively).
export function handleUnreadBump(
event: CommunityUnreadBump,
- { deliveryMode, projection, queryClient, viewerUserIdRef, sub }: SocialEventContext,
+ context: SocialEventContext,
) {
+ const {
+ queryClient,
+ viewerUserIdRef,
+ unreadBumpEvidence,
+ scheduleInboxInvalidate,
+ } = context
const viewerId = viewerUserIdRef.current
- // `railChannelId` is the always-locatable fallback. A participating
- // forum child now has its own nested row, so prefer that row when it
- // is loaded; ordinary/expired children continue to light the parent.
- const railChannelId = event.railChannelId ?? event.channelId
- const targetServerId =
- event.serverId ?? useCommunityStore.getState().currentServerId
- if (deliveryMode === "batch" && event.isMention && event.serverId) {
- invalidateServersList(projection)
- }
- const hasChildSidebarRow = !!targetServerId && event.channelId !== railChannelId &&
- hasProjectedForumSidebarThread(
- queryClient,
- targetServerId,
- event.channelId,
- sub.channelId,
- )
- const sidebarChannelId = hasChildSidebarRow ? event.channelId : railChannelId
- // Suppress the dot for the channel the viewer is actually looking at
- // (its unread clears on read anyway) — compare against the ROW being
- // lit, so a thread bump whose parent is open still suppresses.
- if (event.userId === viewerId && sidebarChannelId !== sub.channelId) {
- if (event.serverId) {
- const serversKey = communityKeys.servers()
- if (queryClient.getQueryState(serversKey)?.fetchStatus === "fetching") {
- fenceServersList(projection)
- }
- queryClient.setQueryData<ServersResponse | undefined>(serversKey, (prev) => {
- if (!prev) return prev
- const index = prev.servers.findIndex((server) => server.id === event.serverId)
- if (index < 0 || prev.servers[index]?.unread) return prev
- const servers = [...prev.servers]
- servers[index] = { ...servers[index]!, unread: true }
- return { ...prev, servers }
- })
- }
- // Channel-tree dot: patch the RIGHT server's detail. `serverId`
- // (inbox-dot-ws-driven) lets an other-server message light its dot
- // — previously only the open server was patched, so cross-server
- // bumps never lit. Absent serverId (DM bump / older frame) → fall
- // back to the currently-open server (backward-compatible).
- if (hasChildSidebarRow && targetServerId) {
- patchForumSidebarUnreadExact(queryClient, targetServerId, event.channelId, true)
- recordForumSidebarChildUnread(
- queryClient,
- targetServerId!,
- railChannelId,
- event.channelId,
- true,
- )
- } else if (targetServerId) {
- if (event.channelId !== railChannelId) {
- recordForumSidebarChildUnread(
- queryClient,
- targetServerId,
- railChannelId,
- event.channelId,
- )
- } else {
- const hasChildFallback = setForumSidebarParentUnreadBase(
- queryClient,
- targetServerId,
- railChannelId,
- true,
- )
- if (!hasChildFallback) {
- queryClient.setQueryData<ServerDetail | undefined>(
- communityKeys.server(targetServerId),
- (cache) => patchChannelUnread(cache, railChannelId, true),
- )
- }
- }
- }
- // Rail mention badge: the rail row carries only a `mentions` count
- // (no separate unread dot — plain unread lives on the tree dot
- // above). So bump the rail badge ONLY for a mention, on the right
- // server row. Needs `serverId`; a DM/older frame without it can't
- // locate a rail row, so skip (the tree dot / inbox still reflect it).
- if (event.isMention && event.serverId) {
- const bumpServerId = event.serverId
- if (deliveryMode === "single") {
- queryClient.setQueryData<ServersResponse | undefined>(
- communityKeys.servers(),
- (prev) =>
- prev
- ? {
- ...prev,
- servers: prev.servers.map((s) =>
- s.id === bumpServerId
- ? { ...s, mentions: s.mentions + 1 }
- : s,
- ),
- }
- : prev,
- )
- }
- }
+ if (event.userId === viewerId && viewerId) {
+ const evidence = unreadBumpEvidence?.get(event)
+ getAccountUnreadProjection(queryClient, viewerId).recordArrival({
+ channelId: event.channelId,
+ railChannelId: event.railChannelId,
+ serverId: event.serverId,
+ isMention: event.isMention,
+ messageId: evidence?.messageId,
+ seq: evidence?.seq,
+ })
+ // 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 })
}
}
@@ -188,9 +101,26 @@ export function handleFriendEvent(
}
export function handleMentionCreate(
- _event: CommunityMentionCreate,
- { projection, scheduleInboxInvalidate }: SocialEventContext,
+ event: CommunityMentionCreate,
+ {
+ projection,
+ scheduleInboxInvalidate,
+ queryClient,
+ viewerUserIdRef,
+ messageEvidenceByChannel,
+ }: SocialEventContext,
) {
+ const viewerId = viewerUserIdRef.current
+ if (viewerId && event.userId === viewerId && event.channelId) {
+ const candidate = messageEvidenceByChannel?.get(event.channelId)
+ const evidence = candidate?.messageId === event.messageId ? candidate : undefined
+ getAccountUnreadProjection(queryClient, viewerId).recordMentionArrival({
+ channelId: event.channelId,
+ messageId: event.messageId,
+ seq: evidence?.seq,
+ 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
diff --git a/src/web/src/hooks/community/mutations/messages.test.ts b/src/web/src/hooks/community/mutations/messages.test.ts
index f62fc407b..95f97cd21 100644
--- a/src/web/src/hooks/community/mutations/messages.test.ts
+++ b/src/web/src/hooks/community/mutations/messages.test.ts
@@ -905,7 +905,7 @@ describe("useMarkAllInboxRead", () => {
])
})
- it("clears both inbox caches optimistically", async () => {
+ it("keeps raw inbox caches authoritative while projection fences hide the captured prefix", async () => {
capturedQc.setQueryData(communityKeys.inboxUnreads(), {
servers: [{ serverId: "s_1", serverName: "s", channels: [{ channelId: "ch_1" }] }],
})
@@ -915,24 +915,40 @@ describe("useMarkAllInboxRead", () => {
apiFetchMock.mockResolvedValue(undefined)
const mod = await loadMod()
mod.useMarkAllInboxRead()
- await runMutation<void>(undefined as unknown as void)
- expect(capturedQc.getQueryData(communityKeys.inboxUnreads())).toEqual({ servers: [], dms: [] })
- expect(capturedQc.getQueryData(communityKeys.inboxMentions())).toEqual({ mentions: [] })
+ const cfg = capturedConfig as MutConfig<void, unknown>
+ await cfg.onMutate?.(undefined as unknown as void)
+ expect(capturedQc.getQueryData(communityKeys.inboxUnreads())).toEqual({
+ servers: [{ serverId: "s_1", serverName: "s", channels: [{ channelId: "ch_1" }] }],
+ })
+ expect(capturedQc.getQueryData(communityKeys.inboxMentions())).toEqual({
+ mentions: [{ id: "men_1" }],
+ })
+ const { getActiveAccountUnreadProjection } = await import(
+ "@/hooks/community/account-unread-projection"
+ )
+ expect(getActiveAccountUnreadProjection(capturedQc).projectUnread(
+ "inbox-unreads",
+ "ch_1",
+ true,
+ 1,
+ )).toBe(false)
})
- it("onSuccess invalidates communityKeys.servers() so every rail badge drops to 0", async () => {
- // Mark-all-read clears every unread mention row on the server — the rail
- // aggregate must refresh across all servers, not just the inbox feeds.
- apiFetchMock.mockResolvedValue(undefined)
+ it("reconciles fulfilled domains through the primary snapshot and server surfaces", async () => {
+ apiFetchMock.mockImplementation(async (path: string) => {
+ if (path === "/api/community/users/me/read-state") {
+ return { revision: 3, readStates: [] }
+ }
+ return { revision: 3 }
+ })
const mod = await loadMod()
mod.useMarkAllInboxRead()
const spy = vi.spyOn(capturedQc, "invalidateQueries")
await runMutation<void>(undefined as unknown as void)
- const serversInvalidates = spy.mock.calls.filter((c) => {
+ await vi.waitFor(() => expect(spy.mock.calls.filter((c) => {
const key = c[0]?.queryKey as unknown[] | undefined
return Array.isArray(key) && key.length === 2 && key[0] === "community" && key[1] === "servers"
- })
- expect(serversInvalidates.length).toBeGreaterThanOrEqual(1)
+ }).length).toBeGreaterThanOrEqual(1))
})
it("toasts the failure reason when one of the three read-all POSTs fails", async () => {
@@ -943,6 +959,36 @@ describe("useMarkAllInboxRead", () => {
expect(toastMock).toHaveBeenCalledWith("boom")
})
+ it("rolls back every domain fence when all three read-all requests fail", async () => {
+ apiFetchMock.mockRejectedValue(new Error("all domains failed"))
+ const mod = await loadMod()
+ mod.useMarkAllInboxRead()
+
+ await expect(runMutation<void>(undefined as unknown as void))
+ .rejects.toThrow("all domains failed")
+
+ const { getActiveAccountUnreadProjection } = await import(
+ "@/hooks/community/account-unread-projection"
+ )
+ const projection = getActiveAccountUnreadProjection(capturedQc)
+ expect(projection.projectUnread("inbox-unreads", "channel", true, 1)).toBe(true)
+ expect(projection.projectUnread("dms", "dm", true, 1, "dms")).toBe(true)
+ expect(projection.projectUnread("inbox-mentions", "mention", true, 1, "mentions"))
+ .toBe(true)
+ expect(toastMock).toHaveBeenCalledWith("all domains failed")
+ })
+
+ it("ignores an unexpected result whose optimistic domain token is absent", async () => {
+ const mod = await loadMod()
+ mod.useMarkAllInboxRead()
+ const cfg = capturedConfig as MutConfig<void, { tokens: Map<string, unknown> }>
+ expect(() => cfg.onSuccess?.(
+ [{ domain: "channels", result: { status: "fulfilled", value: { revision: 1 } } }],
+ undefined as unknown as void,
+ { tokens: new Map() },
+ )).not.toThrow()
+ })
+
it("retries all three idempotent routes after mentions and DMs commit before unreads fails", async () => {
let unreadAttempts = 0
apiFetchMock.mockImplementation(async (path: string) => {
diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.ts
index d0e871e5e..dcdfb7c9f 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -37,6 +37,12 @@ import {
} from "@/hooks/community/use-forum-sidebar-threads"
import { reconcileForumOpenerTitle } from "@/hooks/community/forum-opener-title-reconciliation"
import { isBlocked, type MentionType } from "@alook/shared"
+import {
+ getActiveAccountUnreadProjection,
+ type AccountUnreadDomain,
+ type MarkAllToken,
+} from "@/hooks/community/account-unread-projection"
+import { reconcileAccountReadState } from "@/hooks/community/community-ws/read-state-reconciliation"
/**
@@ -802,32 +808,72 @@ export function useCreateThread() {
export function useMarkAllInboxRead() {
const queryClient = useQueryClient()
- return useMutation<void, Error, void>({
+ const unreadProjection = getActiveAccountUnreadProjection(queryClient)
+ type ReadAllResponse = { revision: number }
+ type DomainResult = {
+ domain: AccountUnreadDomain
+ result: PromiseSettledResult<ReadAllResponse>
+ }
+ type MarkAllContext = { tokens: Map<AccountUnreadDomain, MarkAllToken> }
+ return useMutation<DomainResult[], Error, void, MarkAllContext>({
mutationFn: async () => {
- await Promise.all([
- apiFetch("/api/community/users/me/inbox/mentions/read-all", { method: "POST" }),
- apiFetch("/api/community/users/me/inbox/unreads/read-all", { method: "POST" }),
- apiFetch("/api/community/users/me/inbox/dms/read-all", { method: "POST" }),
- ])
+ const requests = [
+ ["mentions", "/api/community/users/me/inbox/mentions/read-all"],
+ ["channels", "/api/community/users/me/inbox/unreads/read-all"],
+ ["dms", "/api/community/users/me/inbox/dms/read-all"],
+ ] as const
+ const settled = await Promise.allSettled(requests.map(([, path]) => (
+ apiFetch<ReadAllResponse>(path, { method: "POST" })
+ )))
+ const results = requests.map(([domain], index) => ({
+ domain,
+ result: settled[index]!,
+ }))
+ const failures = results.filter(
+ (entry): entry is DomainResult & { result: PromiseRejectedResult } => (
+ entry.result.status === "rejected"
+ ),
+ )
+ if (failures.length === results.length) {
+ throw failures[0]!.result.reason
+ }
+ return results
},
onMutate: async () => {
- // Clear both inbox keys so the popover's "caught up" empty state renders
- // while the mutation is in flight. DMs live under `inboxUnreads` and are
- // now marked read server-side too (the dms/read-all POST above).
- queryClient.setQueryData(communityKeys.inboxUnreads(), { servers: [], dms: [] })
- queryClient.setQueryData(communityKeys.inboxMentions(), { mentions: [] })
- },
- onSuccess: () => {
- // "Mark everything read" clears every unread mention row — the rail
- // badges across all servers must fall to 0 in one refetch.
- void queryClient.invalidateQueries({ queryKey: communityKeys.servers() })
+ return {
+ tokens: new Map<AccountUnreadDomain, MarkAllToken>([
+ ["channels", unreadProjection.beginMarkAll("channels")],
+ ["dms", unreadProjection.beginMarkAll("dms")],
+ ["mentions", unreadProjection.beginMarkAll("mentions")],
+ ]),
+ }
},
- onError: (e) => {
+ onSuccess: (results, _variables, context) => {
+ let targetRevision = 0
+ let firstFailure: unknown
+ for (const { domain, result } of results) {
+ const token = context.tokens.get(domain)
+ if (!token) continue
+ if (result.status === "fulfilled") {
+ targetRevision = Math.max(targetRevision, result.value?.revision ?? 0)
+ unreadProjection.commitMarkAll(token, result.value?.revision ?? 0)
+ } else {
+ unreadProjection.rollbackMarkAll(token)
+ firstFailure ??= result.reason
+ }
+ }
+ if (firstFailure) toastApiError(firstFailure, "Some inbox items could not be marked read")
+ void reconcileAccountReadState(queryClient, {
+ surfaceMode: "all",
+ targetRevision,
+ }).catch(() => undefined)
+ },
+ onError: (e, _variables, context) => {
+ for (const token of context?.tokens.values() ?? []) {
+ unreadProjection.rollbackMarkAll(token)
+ }
toastApiError(e, "Failed to mark inbox read")
void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })
- // A partial write is possible (one of the two POSTs may have succeeded
- // before the other failed) — refresh the rail badges too so the UI
- // reflects whatever landed on the server.
void queryClient.invalidateQueries({ queryKey: communityKeys.servers() })
},
})
diff --git a/src/web/src/hooks/community/read-coordinator.test.ts b/src/web/src/hooks/community/read-coordinator.test.ts
index fb0804049..f8827dda4 100644
--- a/src/web/src/hooks/community/read-coordinator.test.ts
+++ b/src/web/src/hooks/community/read-coordinator.test.ts
@@ -35,6 +35,7 @@ import {
reserveInboxUnreadsResponse,
type InboxRowTarget,
} from "./inbox-read-reservation"
+import { getAccountUnreadProjection } from "./account-unread-projection"
function timelineLease(queryClient: QueryClient, confirmedSeq = 0) {
return registerReadSurface(
@@ -96,7 +97,7 @@ describe("read coordinator", () => {
expect(submitTimeline(lease, 3)).toBe(true)
expect(submitTimeline(lease, 7)).toBe(true)
- expect(submitTimeline(lease, 5)).toBe(true)
+ expect(submitTimeline(lease, 5)).toBe(false)
await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
expect(apiFetch).toHaveBeenCalledTimes(1)
@@ -116,6 +117,30 @@ describe("read coordinator", () => {
expect(submitTimeline(lease, 7)).toBe(false)
})
+ it("settles a queued optimistic generation when a higher target supersedes it", () => {
+ const queryClient = new QueryClient()
+ const lease = timelineLease(queryClient)
+ const projection = getAccountUnreadProjection(queryClient, "user-1")
+ projection.recordArrival({ channelId: "channel-1", serverId: "server-1", seq: 4 })
+ const first = submitReadIntentGeneration(lease, {
+ kind: "timeline",
+ channelId: "channel-1",
+ messageId: "message-4",
+ seq: 4,
+ })!
+ projection.recordOptimisticRead("channel-1", 4, first)
+ const second = submitReadIntentGeneration(lease, {
+ kind: "timeline",
+ channelId: "channel-1",
+ messageId: "message-5",
+ seq: 5,
+ })!
+ projection.recordOptimisticRead("channel-1", 5, second)
+
+ projection.settleOptimisticRead(second, false)
+ expect(projection.projectUnread("servers", "channel-1", false)).toBe(true)
+ })
+
it("rejects hidden submissions without accepting a target", async () => {
const queryClient = new QueryClient()
const lease = timelineLease(queryClient)
@@ -136,6 +161,45 @@ describe("read coordinator", () => {
expect(apiFetch).toHaveBeenCalledTimes(1)
})
+ it("rolls back the matching optimistic projection on a terminal PUT failure", async () => {
+ const queryClient = new QueryClient()
+ const lease = timelineLease(queryClient)
+ const projection = getAccountUnreadProjection(queryClient, "user-1")
+ projection.recordArrival({ channelId: "channel-1", serverId: "server-1", seq: 4 })
+ const generation = submitReadIntentGeneration(lease, {
+ kind: "timeline",
+ channelId: "channel-1",
+ messageId: "message-4",
+ seq: 4,
+ })!
+ projection.recordOptimisticRead("channel-1", 4, generation)
+ apiFetch.mockRejectedValue(new ApiError("forbidden", 403))
+
+ expect(projection.projectUnread("servers", "channel-1", false)).toBe(false)
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+ expect(projection.projectUnread("servers", "channel-1", false)).toBe(true)
+ })
+
+ it("rolls back the matching optimistic projection while a transient retry waits", async () => {
+ const queryClient = new QueryClient()
+ const lease = timelineLease(queryClient)
+ const projection = getAccountUnreadProjection(queryClient, "user-1")
+ projection.recordArrival({ channelId: "channel-1", serverId: "server-1", seq: 4 })
+ const generation = submitReadIntentGeneration(lease, {
+ kind: "timeline",
+ channelId: "channel-1",
+ messageId: "message-4",
+ seq: 4,
+ })!
+ projection.recordOptimisticRead("channel-1", 4, generation)
+ apiFetch.mockRejectedValue(new ApiError("busy", 503))
+
+ expect(projection.projectUnread("servers", "channel-1", false)).toBe(false)
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+ expect(apiFetch).toHaveBeenCalledOnce()
+ expect(projection.projectUnread("servers", "channel-1", false)).toBe(true)
+ })
+
it("bounds transient retries, retains dirty intent, and resumes it later", async () => {
const queryClient = new QueryClient()
const lease = timelineLease(queryClient)
@@ -601,6 +665,53 @@ describe("read coordinator", () => {
await vi.waitFor(() => expect(reconcileAccountReadState).not.toHaveBeenCalled())
})
+ it("fences a committed mutation whose Inbox settlement loses ownership", async () => {
+ const queryClient = new QueryClient()
+ const data = {
+ servers: [{
+ serverId: "s1",
+ channels: [{
+ channelId: "channel-1",
+ lastMessageAt: "2026-08-27T01:00:00.000Z",
+ hasDirectUnread: true,
+ children: [],
+ }],
+ }],
+ dms: [],
+ }
+ const reservation = registerInboxReadReservationSurface(
+ queryClient,
+ "channel-1",
+ vi.fn(),
+ )
+ const held = reserveInboxUnreadsResponse(queryClient, data)
+ void held.catch(() => undefined)
+ const lease = timelineLease(queryClient)
+ const generation = submitReadIntentGeneration(lease, {
+ kind: "timeline",
+ channelId: "channel-1",
+ messageId: "message-4",
+ seq: 4,
+ })!
+ const { promoteInboxReadReservation } = await import("./inbox-read-reservation")
+ promoteInboxReadReservation(reservation, generation)
+ apiFetch.mockResolvedValue({ changed: true, revision: 20, targetSeq: 4 })
+ let releaseCancel!: () => void
+ const cancelQueries = vi.spyOn(queryClient, "cancelQueries").mockReturnValue(
+ new Promise<void>((resolve) => {
+ releaseCancel = resolve
+ }),
+ )
+
+ const work = flushPendingReadIntents(queryClient)
+ await vi.waitFor(() => expect(cancelQueries).toHaveBeenCalledOnce())
+ disposeReadCoordinator(queryClient)
+ releaseCancel()
+
+ await expect(work).resolves.toEqual({ consumed: false, cutoff: generation })
+ expect(reconcileAccountReadState).not.toHaveBeenCalled()
+ })
+
it("does not consume a committed read whose authoritative refresh fails", async () => {
const queryClient = new QueryClient()
const lease = timelineLease(queryClient)
diff --git a/src/web/src/hooks/community/read-coordinator.ts b/src/web/src/hooks/community/read-coordinator.ts
index 3e7d09bd3..5c6ab7b2d 100644
--- a/src/web/src/hooks/community/read-coordinator.ts
+++ b/src/web/src/hooks/community/read-coordinator.ts
@@ -16,6 +16,7 @@ import {
publishInboxProjectionGenerationTerminal,
settleInboxReadReservationGeneration,
} from "./inbox-read-reservation"
+import { getAccountUnreadProjection } from "./account-unread-projection"
export const READ_COORDINATOR_DEBOUNCE_MS = 500
@@ -196,6 +197,8 @@ class ReadCoordinator {
state.retryTimer = null
}
for (const generation of canceledGenerations) {
+ getAccountUnreadProjection(this.queryClient, this.ownerUserId)
+ .settleOptimisticRead(generation, false)
void settleInboxReadReservationGeneration(
this.queryClient,
generation,
@@ -221,6 +224,20 @@ class ReadCoordinator {
return null
}
if (this.confirmed(state, intent)) return null
+ const pendingSeq = Math.max(
+ state.accepted?.intent.seq ?? 0,
+ state.dirty?.intent.seq ?? 0,
+ state.inFlight?.target.intent.seq ?? 0,
+ )
+ if (pendingSeq >= intent.seq) return null
+ const supersededGenerations = new Set<number>()
+ for (const pending of [state.accepted, state.dirty]) {
+ if (
+ pending
+ && pending.intent.seq < intent.seq
+ && pending.generation !== state.inFlight?.target.generation
+ ) supersededGenerations.add(pending.generation)
+ }
const queued = {
intent,
generation: ++this.latestIntentGeneration,
@@ -229,6 +246,10 @@ class ReadCoordinator {
}
state.accepted = laterIntent(state.accepted, queued)
state.dirty = laterIntent(state.dirty, queued)
+ for (const generation of supersededGenerations) {
+ getAccountUnreadProjection(this.queryClient, this.ownerUserId)
+ .settleOptimisticRead(generation, false)
+ }
this.schedule(state, READ_COORDINATOR_DEBOUNCE_MS)
return queued.generation
}
@@ -425,6 +446,8 @@ class ReadCoordinator {
false,
target.intent.channelId,
)
+ getAccountUnreadProjection(this.queryClient, this.ownerUserId)
+ .settleOptimisticRead(target.generation, false)
if (!retryable(error)) {
if (state.dirty && sameIntent(state.dirty, target)) state.dirty = null
state.retryCount = 0
@@ -454,15 +477,15 @@ class ReadCoordinator {
return { committed: false, reconciled: false }
}
state.confirmedSeq = Math.max(state.confirmedSeq, response.targetSeq)
+ getAccountUnreadProjection(this.queryClient, this.ownerUserId)
+ .settleOptimisticRead(target.generation, true, response.targetSeq)
state.dirty = sameIntent(state.dirty ?? target, target) ? null : state.dirty
state.retryCount = 0
if (state.inFlight?.attemptEpoch === attemptEpoch) {
state.inFlight.phase = "reconciling"
}
- const activeAttempt = state.inFlight?.attemptEpoch === attemptEpoch
- ? state.inFlight
- /* istanbul ignore next -- attemptActive succeeded and no write or await can replace inFlight */
- : null
+ // `attemptActive` succeeded after the last await, so this attempt still owns inFlight.
+ const activeAttempt = state.inFlight!
const deferInboxDms = activeAttempt?.deferInboxDms?.() === true
|| (activeAttempt?.drainCutoff !== undefined
&& state.accepted !== null
@@ -510,11 +533,11 @@ class ReadCoordinator {
state: ScopeState,
attemptEpoch: number,
) {
- const drainCutoff = state.inFlight?.attemptEpoch === attemptEpoch
- ? state.inFlight.drainCutoff
- /* istanbul ignore next -- this reconciliation finally is the attempt's only finisher */
- : undefined
- if (state.inFlight?.attemptEpoch === attemptEpoch) state.inFlight = null
+ let drainCutoff: number | undefined
+ if (state.inFlight?.attemptEpoch === attemptEpoch) {
+ drainCutoff = state.inFlight.drainCutoff
+ state.inFlight = null
+ }
if (this.disposed || !state.accepted || state.retryTimer !== null) return
if (
drainCutoff !== undefined
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index 867706164..6de7a184f 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 { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
import { runCommunityWsProjectionTransaction } from "@/hooks/community/community-ws/projection-transaction"
import {
invalidateDms,
@@ -221,6 +222,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
const viewerUserIdRef = useRef<string | null>(options?.viewerUserId ?? null)
const hasAuthenticatedRef = useRef(false)
const viewerUserId = options?.viewerUserId ?? null
+ if (viewerUserId) getAccountUnreadProjection(queryClient, viewerUserId)
viewerUserIdRef.current = viewerUserId
useEffect(() => {
const store = useCommunityWsStore.getState()
diff --git a/src/web/src/hooks/community/use-dms.test.ts b/src/web/src/hooks/community/use-dms.test.ts
index 1ecf945e7..cb0d5b782 100644
--- a/src/web/src/hooks/community/use-dms.test.ts
+++ b/src/web/src/hooks/community/use-dms.test.ts
@@ -1,9 +1,10 @@
-import { describe, it, expect, vi, beforeEach } from "vitest"
import React from "react"
import TestRenderer, { act } from "react-test-renderer"
+import { describe, it, expect, vi, beforeEach } from "vitest"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
import { useCommunityWsStore } from "@/stores/community/ws"
+import type { DM } from "@/lib/community/models/people"
const apiFetchMock = vi.fn()
vi.mock("@/lib/api/client", () => ({
@@ -83,6 +84,78 @@ describe("useDms / dmsQueryFn", () => {
preview: "hello",
})
expect(qc.getQueryData(communityKeys.dms())).toBe(raw)
- act(() => renderer.unmount())
+ await act(async () => renderer.unmount())
+ })
+
+ it("projects unread arrivals alongside canonical peer profiles", async () => {
+ const conversations = [
+ {
+ id: "dm_1", userId: "u_1", name: "Alice", discriminator: "0001",
+ avatar: "a", avatarVersion: 1, status: "offline", preview: "one", unread: false,
+ },
+ {
+ id: "dm_2", userId: "u_2", name: "Bob", discriminator: "0002",
+ avatar: "b", avatarVersion: 1, status: "offline", preview: "two",
+ unread: true, lastUnreadSeq: 3,
+ },
+ {
+ id: "dm_legacy", userId: "u_3", name: "Carol", discriminator: "0003",
+ avatar: "c", avatarVersion: 1, status: "offline", preview: "three", unread: true,
+ },
+ ] as DM[]
+ apiFetchMock.mockResolvedValue({ conversations })
+ const { useDms } = await import("./use-dms")
+ const { getActiveAccountUnreadProjection } = await import("./account-unread-projection")
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ qc.setQueryData(communityKeys.dms(), { conversations })
+ getActiveAccountUnreadProjection(qc).recordArrival({ channelId: "dm_1", seq: 2 })
+ let latest: ReturnType<typeof useDms> | undefined
+
+ function Harness() {
+ latest = useDms()
+ return null
+ }
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(
+ QueryClientProvider,
+ { client: qc },
+ React.createElement(Harness),
+ ))
+ })
+
+ expect(latest?.dms[0]?.unread).toBe(true)
+ expect(latest?.dms[1]?.unread).toBe(true)
+ expect(latest?.dms[2]?.unread).toBe(true)
+ expect(qc.getQueryData(communityKeys.dms())).toEqual({ conversations })
+ await act(async () => renderer.unmount())
+ })
+
+ it("returns a stable empty projection while the query has no data", async () => {
+ apiFetchMock.mockReturnValue(new Promise(() => undefined))
+ const { useDms } = await import("./use-dms")
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ let latest: ReturnType<typeof useDms> | undefined
+ function Harness() {
+ latest = useDms()
+ return null
+ }
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(
+ QueryClientProvider,
+ { client: qc },
+ React.createElement(Harness),
+ ))
+ })
+ const first = latest?.dms
+ await act(async () => renderer.update(React.createElement(
+ QueryClientProvider,
+ { client: qc },
+ React.createElement(Harness),
+ )))
+ expect(latest?.dms).toBe(first)
+ expect(latest?.dms).toEqual([])
+ await act(async () => renderer.unmount())
})
})
diff --git a/src/web/src/hooks/community/use-dms.ts b/src/web/src/hooks/community/use-dms.ts
index 866737655..3b4e4999c 100644
--- a/src/web/src/hooks/community/use-dms.ts
+++ b/src/web/src/hooks/community/use-dms.ts
@@ -1,15 +1,16 @@
"use client"
-import { useQuery, type UseQueryResult } from "@tanstack/react-query"
+import { useQuery, useQueryClient, type UseQueryResult } from "@tanstack/react-query"
import {
apiFetchProfiles,
communityUserProfilePatch,
} from "@/lib/community/profile-seed"
import { communityKeys } from "@/lib/query-keys"
import type { DM } from "@/lib/community/models/people"
-import { useMemo } from "react"
+import { useEffect, useMemo, useSyncExternalStore } from "react"
import { useProfilesByUserId } from "@/stores/community/ws"
import { readCommunityProfile } from "@/lib/community/profile-read"
+import { getActiveAccountUnreadProjection } from "./account-unread-projection"
/**
* Fetches the DM conversation sidebar list.
@@ -31,14 +32,49 @@ export const dmsQueryFn = () =>
)
export function useDms(): UseQueryResult<DmsResponse> & { dms: DM[] } {
+ const queryClient = useQueryClient()
+ const unreadProjection = useMemo(
+ () => getActiveAccountUnreadProjection(queryClient),
+ [queryClient],
+ )
+ const unreadVersion = useSyncExternalStore(
+ unreadProjection.subscribe,
+ unreadProjection.getSnapshot,
+ unreadProjection.getSnapshot,
+ )
const query = useQuery({
queryKey: communityKeys.dms(),
queryFn: dmsQueryFn,
})
const profilesByUserId = useProfilesByUserId()
- const dms = useMemo(
- () => (query.data?.conversations ?? EMPTY_DMS).map((dm) => {
+ useEffect(() => {
+ if (!query.data) return
+ unreadProjection.absorbFamily(
+ "dms",
+ query.data.conversations.flatMap((dm) => dm.lastUnreadSeq === undefined ? [] : [{
+ channelId: dm.id,
+ lastUnreadSeq: dm.lastUnreadSeq,
+ }]),
+ )
+ unreadProjection.recordLegacySnapshot(
+ query.data,
+ query.data.conversations.flatMap((dm) => (
+ dm.unread && dm.lastUnreadSeq === undefined
+ ? [{ family: "dms" as const, channelId: dm.id }]
+ : []
+ )),
+ )
+ }, [query.data, unreadProjection])
+ const dms = useMemo(() => {
+ void unreadVersion
+ return (query.data?.conversations ?? EMPTY_DMS).map((dm) => {
const profile = readCommunityProfile(profilesByUserId.get(dm.userId), dm.userId)
+ const unread = unreadProjection.projectUnread(
+ "dms",
+ dm.id,
+ dm.unread === true,
+ dm.lastUnreadSeq,
+ )
return {
...dm,
name: profile.name,
@@ -46,10 +82,10 @@ export function useDms(): UseQueryResult<DmsResponse> & { dms: DM[] } {
avatar: profile.avatar,
avatarVersion: profile.avatarVersion,
status: profile.presence,
+ unread,
}
- }),
- [profilesByUserId, query.data?.conversations],
- )
+ })
+ }, [profilesByUserId, query.data?.conversations, unreadProjection, unreadVersion])
return {
...query,
dms,
diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts
index 9c940f09f..7ca55da83 100644
--- a/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts
+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts
@@ -31,6 +31,7 @@ import {
} from "./use-forum-sidebar-threads"
import type { ServerDetail } from "./use-servers"
import { useCommunityWsStore } from "@/stores/community/ws"
+import { getActiveAccountUnreadProjection } from "./account-unread-projection"
const apiFetchMock = vi.fn()
vi.mock("@/lib/api/client", () => ({
@@ -116,6 +117,47 @@ function parentUnread(queryClient: QueryClient): boolean {
}
describe("useForumSidebarThreads", () => {
+ it("projects a read thread from server-detail source evidence", async () => {
+ apiFetchMock.mockResolvedValue(envelope(["post-1"]))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ queryClient.setQueryData(communityKeys.server("server-1"), {
+ ...serverDetail(true),
+ forumUnreadState: {
+ "forum-1": { baseUnread: false, childIds: ["post-1"] },
+ },
+ unreadSources: [{
+ channelId: "post-1",
+ lastUnreadSeq: 2,
+ lastAttentionSeq: null,
+ }],
+ } satisfies ServerDetail)
+ getActiveAccountUnreadProjection(queryClient).recordRead("post-1", 2)
+ function Harness() {
+ const result = useForumSidebarThreads("server-1", null)
+ return React.createElement("output", {
+ "data-count": result.threads.length,
+ "data-unread": String(result.threads[0]?.unread),
+ })
+ }
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Harness),
+ ))
+ })
+ await waitFor(() => (
+ renderer.root.findByType("output").props["data-count"] === 1
+ ))
+ const raw = queryClient.getQueryData<ForumSidebarQueryData>(
+ communityKeys.forumSidebarThreads("server-1"),
+ )?.threads[0]
+ expect(raw?.unread).toBe(true)
+ expect(renderer.root.findByType("output").props["data-unread"]).toBe("false")
+ await act(async () => renderer.unmount())
+ })
+
it("preserves a genuine parent unread when a child fallback becomes locatable", () => {
const queryClient = new QueryClient()
queryClient.setQueryData(communityKeys.server("server-1"), serverDetail(true))
diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.ts
index fd2148275..041dd58e0 100644
--- a/src/web/src/hooks/community/use-forum-sidebar-threads.ts
+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.ts
@@ -1,12 +1,13 @@
"use client"
-import { useEffect, useMemo, useRef, useState } from "react"
+import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react"
import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import { patchChannelUnread } from "@/hooks/community/server-detail-cache"
import type { ServerDetail } from "@/hooks/community/use-servers"
import { useCommunityWsStore } from "@/stores/community/ws"
+import { getActiveAccountUnreadProjection } from "./account-unread-projection"
export type ForumSidebarThread = {
id: string
@@ -95,7 +96,6 @@ export function resolveForumSidebarRouteCandidate(
type InflightDelta = {
activity: Map<string, { parentChannelId: string; activityAt: string }>
titles: Map<string, string>
- unread: Map<string, boolean>
removed: Set<string>
archiveRemovals: Map<string, number>
}
@@ -499,29 +499,6 @@ function getForumSidebarRetained(
)
}
-export function hasProjectedForumSidebarThread(
- queryClient: QueryClient,
- serverId: string,
- childId: string,
- activeChildId: string | null | undefined,
-) {
- const access = useCommunityWsStore.getState()
- const base = getForumSidebarBase(queryClient, serverId)
- if (
- !access.accessConnected ||
- !base ||
- base.verifiedEpoch !== access.accessEpoch
- ) return false
- const activeExtra = activeChildId
- ? getForumSidebarRetained(queryClient, serverId, activeChildId)
- : null
- const ownership = queryClient.getQueryData<ServerDetail>(
- communityKeys.server(serverId),
- )?.forumUnreadState
- return deriveForumSidebarProjection(base, activeExtra, ownership)
- .threads.some((thread) => thread.id === childId)
-}
-
export function isKnownNonForumSidebarChannel(
queryClient: QueryClient,
serverId: string,
@@ -631,22 +608,6 @@ export function patchForumSidebarTitleExact(
}
}
-export function patchForumSidebarUnreadExact(
- queryClient: QueryClient,
- serverId: string,
- childId: string,
- unread: boolean,
-) {
- recordInflightDelta(serverId, (delta) => {
- delta.unread.set(childId, unread)
- })
- queryClient.setQueryData<ForumSidebarQueryData | undefined>(
- communityKeys.forumSidebarThreads(serverId),
- (data) => patchForumSidebarUnread(data, childId, unread),
- )
- patchRetained(queryClient, serverId, childId, (thread) => ({ ...thread, unread }))
-}
-
export function removeForumSidebarThreadExact(
queryClient: QueryClient,
serverId: string,
@@ -867,7 +828,6 @@ function fetchForumSidebar(serverId: string, retainId: string | null, signal?: A
const delta: InflightDelta = {
activity: new Map(),
titles: new Map(),
- unread: new Map(),
removed: new Set(),
archiveRemovals: new Map(),
}
@@ -915,10 +875,6 @@ function fetchForumSidebar(serverId: string, retainId: string | null, signal?: A
}
}
}
- for (const [childId, unread] of delta.unread) {
- base = patchForumSidebarUnread(base, childId, unread)
- if (retained?.id === childId) retained = { ...retained, unread }
- }
for (const childId of delta.removed) {
const meta = channelMetas[childId]
if (meta) delete openerHints[meta.parentMessageId]
@@ -1015,6 +971,15 @@ export function useForumSidebarThreads(
enabled = true,
) {
const queryClient = useQueryClient()
+ const unreadProjection = useMemo(
+ () => getActiveAccountUnreadProjection(queryClient),
+ [queryClient],
+ )
+ const unreadVersion = useSyncExternalStore(
+ unreadProjection.subscribe,
+ unreadProjection.getSnapshot,
+ unreadProjection.getSnapshot,
+ )
const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)
const previousRetainId = useRef(retainId)
// Observe (without fetching) the already-canonical ServerDetail cache so a
@@ -1094,11 +1059,61 @@ export function useForumSidebarThreads(
const renderableBase = query.data?.verifiedEpoch === accessEpoch
? query.data
: trustedBase?.serverId === serverId ? trustedBase.data : undefined
- const projection = useMemo(() => deriveForumSidebarProjection(
+ const projection = useMemo(() => {
+ void unreadVersion
+ const raw = deriveForumSidebarProjection(
+ renderableBase,
+ renderableBase ? retainedQuery.data : null,
+ serverDetailQuery.data?.forumUnreadState,
+ )
+ const family = `server-detail:${serverId}` as const
+ const sourceByChannel = new Map(
+ (serverDetailQuery.data?.unreadSources ?? []).map((source) => [source.channelId, source]),
+ )
+ const threads = raw.threads.map((thread) => {
+ const source = sourceByChannel.get(thread.id)
+ const unread = unreadProjection.projectUnread(
+ family,
+ thread.id,
+ thread.unread,
+ source?.lastUnreadSeq,
+ )
+ if (unread === thread.unread) return thread
+ return { ...thread, unread }
+ })
+ const renderedChildIds = new Set(threads.map((thread) => thread.id))
+ let parentChanged = false
+ let parentUnread = raw.parentUnread
+ for (const [parentId, state] of Object.entries(
+ serverDetailQuery.data?.forumUnreadState ?? {},
+ )) {
+ const unread = unreadProjection.projectForumParentUnread(
+ serverId,
+ parentId,
+ state.baseUnread || raw.parentUnread[parentId] === true,
+ sourceByChannel.get(parentId)?.lastUnreadSeq,
+ renderedChildIds,
+ )
+ if (unread === raw.parentUnread[parentId]) continue
+ if (!parentChanged) parentUnread = { ...raw.parentUnread }
+ parentChanged = true
+ parentUnread[parentId] = unread
+ }
+ return {
+ threads: threads.every((thread, index) => thread === raw.threads[index])
+ ? raw.threads
+ : threads,
+ parentUnread,
+ }
+ }, [
renderableBase,
- renderableBase ? retainedQuery.data : null,
+ retainedQuery.data,
serverDetailQuery.data?.forumUnreadState,
- ), [renderableBase, retainedQuery.data, serverDetailQuery.data?.forumUnreadState])
+ serverDetailQuery.data?.unreadSources,
+ serverId,
+ unreadProjection,
+ unreadVersion,
+ ])
useEffect(() => {
if (!query.data) return
diff --git a/src/web/src/hooks/community/use-inbox.test.ts b/src/web/src/hooks/community/use-inbox.test.ts
index bd212126b..b2102725a 100644
--- a/src/web/src/hooks/community/use-inbox.test.ts
+++ b/src/web/src/hooks/community/use-inbox.test.ts
@@ -104,6 +104,180 @@ describe("useInboxUnreads / inboxUnreadsQueryFn", () => {
expect(apiFetchMock).toHaveBeenCalledOnce()
await act(async () => renderer.unmount())
})
+
+ it("projects nested channel and DM reads while preserving unchanged rows", 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: [{
+ 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!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(
+ QueryClientProvider,
+ { client: qc },
+ React.createElement(Harness),
+ ))
+ })
+
+ expect(latest?.servers).toEqual([retained])
+ expect(latest?.servers[0]).toBe(retained)
+ expect(latest?.dms).toEqual([keptDm])
+ expect(latest?.dms[0]).toBe(keptDm)
+ expect(latest?.hasProjectedUnread).toBe(true)
+ await act(async () => renderer.unmount())
+ })
+
+ it("keeps a child-only parent and clones only its changed channel path", 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
+ }
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(
+ QueryClientProvider,
+ { client: qc },
+ React.createElement(Harness),
+ ))
+ })
+ expect(latest?.servers[0]).not.toBe(server)
+ expect(latest?.servers[0]?.channels[0]).not.toBe(channel)
+ expect(latest?.servers[0]?.channels[0]?.hasDirectUnread).toBe(false)
+ expect(latest?.servers[0]?.channels[0]?.children[0]).toBe(child)
+ await act(async () => renderer.unmount())
+ })
+
+ it("retains legacy unread evidence after an absent rolling-deploy 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
+ }
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(
+ QueryClientProvider,
+ { client: qc },
+ React.createElement(Harness),
+ ))
+ })
+ await vi.waitFor(() => expect(latest?.servers).toEqual([]))
+ expect(latest?.servers).toEqual([])
+ expect(latest?.dms).toEqual([])
+ expect(latest?.hasProjectedUnread).toBe(true)
+ await act(async () => renderer.unmount())
+ })
})
describe("useInboxMentions / inboxMentionsQueryFn", () => {
@@ -116,6 +290,90 @@ describe("useInboxMentions / inboxMentionsQueryFn", () => {
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/users/me/inbox/mentions")
expect(qc.getQueryData(key)).toEqual({ mentions: [] })
})
+
+ it("filters read mentions, preserves unscoped rows, and reports pending arrivals", async () => {
+ const scoped = { id: "m1", channelId: "c1", m: { seq: 2 } }
+ const unscoped = { id: "m2", m: { seq: 1 } }
+ 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
+ }
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(
+ QueryClientProvider,
+ { client: qc },
+ React.createElement(Harness),
+ ))
+ })
+ expect(latest?.mentions).toEqual([unscoped])
+ expect(latest?.mentions[0]).toBe(unscoped)
+ expect(latest?.hasProjectedMention).toBe(true)
+ await act(async () => renderer.unmount())
+ })
+
+ it("returns an empty mention projection before query data arrives", async () => {
+ apiFetchMock.mockReturnValue(new Promise(() => undefined))
+ const { useInboxMentions } = await import("./use-inbox")
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ let latest: ReturnType<typeof useInboxMentions> | undefined
+ function Harness() {
+ latest = useInboxMentions()
+ return null
+ }
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(
+ QueryClientProvider,
+ { client: qc },
+ React.createElement(Harness),
+ ))
+ })
+ expect(latest?.mentions).toEqual([])
+ expect(latest?.hasProjectedMention).toBe(false)
+ await act(async () => renderer.unmount())
+ })
+
+ it("retains a legacy mention after it falls outside a later window", 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
+ }
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(
+ QueryClientProvider,
+ { client: qc },
+ React.createElement(Harness),
+ ))
+ })
+ await vi.waitFor(() => expect(latest?.mentions).toEqual([]))
+ expect(latest?.mentions).toEqual([])
+ expect(latest?.hasProjectedMention).toBe(true)
+ await act(async () => renderer.unmount())
+ })
})
describe("useInboxMarked", () => {
diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.ts
index bc6b86dd4..95572e257 100644
--- a/src/web/src/hooks/community/use-inbox.ts
+++ b/src/web/src/hooks/community/use-inbox.ts
@@ -1,12 +1,13 @@
"use client"
-import { useMemo } from "react"
+import { useEffect, useMemo, useSyncExternalStore } from "react"
import { useQuery, useQueryClient, keepPreviousData, 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, Mention, Marked } from "@/lib/community/models/inbox"
import { reserveInboxUnreadsResponse } from "./inbox-read-reservation"
+import { getActiveAccountUnreadProjection } from "./account-unread-projection"
class StaleReadError extends Error {
constructor() { super("stale D1 read"); this.name = "StaleReadError" }
@@ -35,7 +36,12 @@ const EMPTY_MARKED: readonly Marked[] = Object.freeze([])
* refresh doesn't re-render the other).
*/
-export type UnreadsResponse = { servers: UnreadServer[]; dms: UnreadDm[] }
+export type UnreadsResponse = {
+ servers: UnreadServer[]
+ dms: UnreadDm[]
+ limit?: number
+ truncated?: boolean
+}
export const inboxUnreadsQueryFn = ({ signal }: { signal?: AbortSignal } = {}) =>
apiFetchProfiles<UnreadsResponse & { stale?: boolean }>(
@@ -66,22 +72,138 @@ export const inboxUnreadsReservedQueryFn = (queryClient: ReturnType<typeof useQu
export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {
servers: UnreadServer[]
dms: UnreadDm[]
+ hasProjectedUnread: boolean
} {
const queryClient = useQueryClient()
+ const unreadProjection = useMemo(
+ () => getActiveAccountUnreadProjection(queryClient),
+ [queryClient],
+ )
+ const unreadVersion = useSyncExternalStore(
+ unreadProjection.subscribe,
+ unreadProjection.getSnapshot,
+ unreadProjection.getSnapshot,
+ )
const queryFn = useMemo(() => inboxUnreadsReservedQueryFn(queryClient), [queryClient])
const query = useQuery({
queryKey: communityKeys.inboxUnreads(),
queryFn,
placeholderData: keepPreviousData,
})
+ useEffect(() => {
+ if (!query.data) return
+ const channelSources = query.data.servers.flatMap((server) => server.channels.flatMap((channel) => [
+ ...(channel.lastUnreadSeq === undefined ? [] : [{
+ channelId: channel.channelId,
+ lastUnreadSeq: channel.lastUnreadSeq,
+ }]),
+ ...channel.children.flatMap((child) => child.lastUnreadSeq === undefined ? [] : [{
+ channelId: child.channelId,
+ lastUnreadSeq: child.lastUnreadSeq,
+ }]),
+ ]))
+ const dmSources = query.data.dms.flatMap((dm) => dm.lastUnreadSeq === undefined ? [] : [{
+ channelId: dm.channelId,
+ lastUnreadSeq: dm.lastUnreadSeq,
+ }])
+ unreadProjection.absorbFamily("inbox-unreads", channelSources, {
+ truncated: query.data.truncated ?? true,
+ domain: "channels",
+ })
+ unreadProjection.absorbFamily("inbox-unreads", dmSources, {
+ truncated: false,
+ domain: "dms",
+ })
+ unreadProjection.recordLegacySnapshot(query.data, [
+ ...query.data.servers.flatMap((server) => server.channels.flatMap((channel) => [
+ ...(channel.lastUnreadSeq === undefined && channel.hasDirectUnread !== false
+ ? [{
+ family: "inbox-unreads" as const,
+ channelId: channel.channelId,
+ serverId: server.serverId,
+ }]
+ : []),
+ ...channel.children.flatMap((child) => child.lastUnreadSeq === undefined
+ ? [{
+ family: "inbox-unreads" as const,
+ channelId: child.channelId,
+ serverId: server.serverId,
+ railChannelId: channel.channelId,
+ }]
+ : []),
+ ])),
+ ...query.data.dms.flatMap((dm) => dm.lastUnreadSeq === undefined
+ ? [{ family: "inbox-unreads" as const, channelId: dm.channelId }]
+ : []),
+ ])
+ }, [query.data, unreadProjection])
+ const projected = useMemo(() => {
+ void unreadVersion
+ const rawServers = query.data?.servers ?? (EMPTY_UNREADS as UnreadServer[])
+ let serversChanged = false
+ const servers = rawServers.flatMap((server) => {
+ let channelsChanged = false
+ const channels = server.channels.flatMap((channel) => {
+ const children = channel.children.filter((child) => unreadProjection.projectUnread(
+ "inbox-unreads",
+ child.channelId,
+ true,
+ child.lastUnreadSeq,
+ ))
+ const direct = channel.hasDirectUnread !== false && unreadProjection.projectUnread(
+ "inbox-unreads",
+ channel.channelId,
+ true,
+ channel.lastUnreadSeq,
+ )
+ if (!direct && children.length === 0) {
+ channelsChanged = true
+ return []
+ }
+ const childrenChanged = children.length !== channel.children.length
+ const directChanged = direct !== (channel.hasDirectUnread !== false)
+ if (!childrenChanged && !directChanged) return [channel]
+ channelsChanged = true
+ return [{ ...channel, hasDirectUnread: direct, children }]
+ })
+ if (channels.length === 0) {
+ serversChanged = true
+ return []
+ }
+ if (!channelsChanged) return [server]
+ serversChanged = true
+ return [{ ...server, channels }]
+ })
+ const rawDms = query.data?.dms ?? (EMPTY_DMS as UnreadDm[])
+ const dms = rawDms.filter((dm) => unreadProjection.projectUnread(
+ "inbox-unreads",
+ dm.channelId,
+ true,
+ dm.lastUnreadSeq,
+ "dms",
+ ))
+ return {
+ servers: serversChanged ? servers : rawServers,
+ dms: dms.length === rawDms.length ? rawDms : dms,
+ }
+ }, [query.data, unreadProjection, unreadVersion])
return {
...query,
- servers: query.data?.servers ?? (EMPTY_UNREADS as UnreadServer[]),
- dms: query.data?.dms ?? (EMPTY_DMS as UnreadDm[]),
+ servers: projected.servers ?? (EMPTY_UNREADS as UnreadServer[]),
+ dms: projected.dms ?? (EMPTY_DMS as UnreadDm[]),
+ hasProjectedUnread:
+ projected.servers.length > 0
+ || projected.dms.length > 0
+ || unreadProjection.hasPending("inbox-unreads", "channels")
+ || unreadProjection.hasPending("inbox-unreads", "dms"),
}
}
-export type MentionsResponse = { mentions: Mention[] }
+export type MentionsResponse = {
+ mentions: Mention[]
+ limit?: number
+ truncated?: boolean
+}
export const inboxMentionsQueryFn = () =>
apiFetchProfiles<MentionsResponse & { stale?: boolean }>(
@@ -94,15 +216,71 @@ export const inboxMentionsQueryFn = () =>
export function useInboxMentions(): UseQueryResult<MentionsResponse> & {
mentions: Mention[]
+ hasProjectedMention: boolean
} {
+ const queryClient = useQueryClient()
+ const unreadProjection = useMemo(
+ () => getActiveAccountUnreadProjection(queryClient),
+ [queryClient],
+ )
+ const unreadVersion = useSyncExternalStore(
+ unreadProjection.subscribe,
+ unreadProjection.getSnapshot,
+ unreadProjection.getSnapshot,
+ )
const query = useQuery({
queryKey: communityKeys.inboxMentions(),
queryFn: inboxMentionsQueryFn,
placeholderData: keepPreviousData,
})
+ useEffect(() => {
+ if (!query.data) return
+ unreadProjection.absorbFamily(
+ "inbox-mentions",
+ query.data.mentions.flatMap((mention) => (
+ mention.channelId && mention.m.seq
+ ? [{
+ channelId: mention.channelId,
+ lastUnreadSeq: mention.m.seq,
+ lastMentionSeq: mention.m.seq,
+ }]
+ : []
+ )),
+ { truncated: query.data.truncated ?? true },
+ )
+ unreadProjection.recordLegacySnapshot(
+ query.data,
+ query.data.mentions.flatMap((mention) => (
+ mention.channelId && !mention.m.seq
+ ? [{
+ family: "inbox-mentions" as const,
+ channelId: mention.channelId,
+ serverId: mention.serverId,
+ isMention: true,
+ }]
+ : []
+ )),
+ )
+ }, [query.data, unreadProjection])
+ const mentions = useMemo(() => {
+ void unreadVersion
+ const raw = query.data?.mentions ?? (EMPTY_MENTIONS as Mention[])
+ const projected = raw.filter((mention) => (
+ !mention.channelId
+ || unreadProjection.projectUnread(
+ "inbox-mentions",
+ mention.channelId,
+ true,
+ mention.m.seq,
+ )
+ ))
+ return projected.length === raw.length ? raw : projected
+ }, [query.data, unreadProjection, unreadVersion])
return {
...query,
- mentions: query.data?.mentions ?? (EMPTY_MENTIONS as Mention[]),
+ mentions,
+ hasProjectedMention:
+ mentions.length > 0 || unreadProjection.hasPending("inbox-mentions", "mentions"),
}
}
diff --git a/src/web/src/hooks/community/use-read-observer.test.ts b/src/web/src/hooks/community/use-read-observer.test.ts
index bdc11e611..0fc87efcc 100644
--- a/src/web/src/hooks/community/use-read-observer.test.ts
+++ b/src/web/src/hooks/community/use-read-observer.test.ts
@@ -15,6 +15,9 @@ const reservation = vi.hoisted(() => ({
promote: vi.fn(),
negative: vi.fn(() => true),
}))
+const projection = vi.hoisted(() => ({
+ recordOptimisticRead: vi.fn(),
+}))
const hookState = vi.hoisted(() => ({
candidate: null as null | {
channelId: string
@@ -87,6 +90,10 @@ vi.mock("./inbox-read-reservation", () => ({
takeInboxReadReservationNegative: (...args: unknown[]) => reservation.negative(...args),
}))
+vi.mock("./account-unread-projection", () => ({
+ getAccountUnreadProjection: () => projection,
+}))
+
import { useTimelineReadObserver } from "./use-read-observer"
type ObserverRecord = {
@@ -240,6 +247,18 @@ describe("useTimelineReadObserver", () => {
messageId: "message-4",
seq: 4,
})
+ expect(projection.recordOptimisticRead).toHaveBeenCalledWith("channel-1", 4, 1)
+ })
+
+ it("does not clear projection or promote an Inbox lease when the coordinator rejects intent", () => {
+ coordinator.submit.mockReturnValueOnce(null)
+ const { row } = useTestRender()
+ runEffects()
+
+ trigger(observers[0]!, row)
+
+ expect(projection.recordOptimisticRead).not.toHaveBeenCalled()
+ expect(reservation.promote).not.toHaveBeenCalled()
})
it("keeps observing visible rows when MutationObserver is unavailable", () => {
diff --git a/src/web/src/hooks/community/use-read-observer.ts b/src/web/src/hooks/community/use-read-observer.ts
index dbba976b2..cb8f237e3 100644
--- a/src/web/src/hooks/community/use-read-observer.ts
+++ b/src/web/src/hooks/community/use-read-observer.ts
@@ -18,6 +18,7 @@ import {
type InboxReadCandidate,
type InboxReadReservationLease,
} from "./inbox-read-reservation"
+import { getAccountUnreadProjection } from "./account-unread-projection"
const READ_VISIBILITY_THRESHOLD = 0.2
@@ -193,6 +194,10 @@ export function useTimelineReadObserver({
messageId: message.id,
seq: message.seq,
})
+ if (generation !== null) {
+ getAccountUnreadProjection(queryClient, currentUser.id)
+ .recordOptimisticRead(channelId, message.seq, generation)
+ }
if (generation !== null && correlated) {
promoteInboxReadReservation(reservationLease, generation)
}
diff --git a/src/web/src/hooks/community/use-servers.test.ts b/src/web/src/hooks/community/use-servers.test.ts
index 136ac7748..08c175d73 100644
--- a/src/web/src/hooks/community/use-servers.test.ts
+++ b/src/web/src/hooks/community/use-servers.test.ts
@@ -2,6 +2,16 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
import { QueryClient } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
+vi.mock("react", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("react")>()
+ return {
+ ...actual,
+ useEffect: (effect: () => void) => effect(),
+ useMemo: <T,>(factory: () => T) => factory(),
+ useSyncExternalStore: (_subscribe: unknown, getSnapshot: () => unknown) => getSnapshot(),
+ }
+})
+
const apiFetchMock = vi.fn()
vi.mock("@/lib/api/client", () => ({
apiFetch: (...args: unknown[]) => apiFetchMock(...args),
@@ -13,6 +23,7 @@ type CapturedQueryConfig = {
}
let capturedQueryConfig: CapturedQueryConfig | null = null
let capturedHookQueryClient: QueryClient
+let capturedHookQueryData: unknown
vi.mock("@tanstack/react-query", async () => {
const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query")
return {
@@ -20,7 +31,7 @@ vi.mock("@tanstack/react-query", async () => {
useQueryClient: () => capturedHookQueryClient,
useQuery: (config: CapturedQueryConfig) => {
capturedQueryConfig = config
- return { data: undefined }
+ return { data: capturedHookQueryData }
},
}
})
@@ -29,6 +40,7 @@ beforeEach(() => {
apiFetchMock.mockReset()
capturedQueryConfig = null
capturedHookQueryClient = new QueryClient()
+ capturedHookQueryData = undefined
})
describe("useServers / serversQueryFn", () => {
@@ -98,6 +110,87 @@ describe("useServers / serversQueryFn", () => {
await qc.fetchQuery({ queryKey: key, queryFn: serversQueryFn })
expect(qc.getQueryData(key)).toEqual({ servers: [] })
})
+
+ it("projects a live unread arrival and preserves unchanged server identity", async () => {
+ const changed = {
+ id: "s1",
+ unread: false,
+ mentions: 0,
+ unreadSources: [],
+ mentionSources: [],
+ }
+ const unchanged = {
+ id: "s2",
+ unread: true,
+ mentions: 2,
+ unreadSources: [{ channelId: "c2", lastUnreadSeq: 2 }],
+ mentionSources: [{ channelId: "c2", count: 2, lastSeq: 2 }],
+ }
+ const legacy = { id: "s3", unread: true, mentions: 0 }
+ const raw = [changed, unchanged, legacy]
+ capturedHookQueryData = { servers: raw }
+ const { getActiveAccountUnreadProjection } = await import("./account-unread-projection")
+ getActiveAccountUnreadProjection(capturedHookQueryClient).recordArrival({
+ channelId: "c1",
+ serverId: "s1",
+ seq: 1,
+ })
+ const { useServers } = await import("./use-servers")
+
+ const result = useServers()
+
+ expect(result.servers).not.toBe(raw)
+ expect(result.servers[0]).not.toBe(changed)
+ expect(result.servers[0]?.unread).toBe(true)
+ expect(result.servers[1]).toBe(unchanged)
+ expect(result.servers[2]).toBe(legacy)
+ })
+
+ it("returns the frozen empty server list before query data arrives", async () => {
+ const { useServers } = await import("./use-servers")
+ const first = useServers().servers
+ const second = useServers().servers
+ expect(first).toBe(second)
+ expect(first).toEqual([])
+ })
+
+ it("retains a rolling-deploy rail unread without a source vector", async () => {
+ capturedHookQueryData = {
+ servers: [{ id: "s1", unread: true, mentions: 0 }],
+ }
+ const { useServers } = await import("./use-servers")
+ expect(useServers().servers[0]?.unread).toBe(true)
+
+ capturedHookQueryData = {
+ servers: [{ id: "s1", unread: false, mentions: 0 }],
+ }
+ expect(useServers().servers[0]?.unread).toBe(true)
+ })
+
+ it("hands a rolling-deploy rail unread to exact sources once they arrive", async () => {
+ capturedHookQueryData = {
+ servers: [{ id: "s1", unread: true, mentions: 0 }],
+ }
+ const { useServers } = await import("./use-servers")
+ expect(useServers().servers[0]?.unread).toBe(true)
+
+ capturedHookQueryData = {
+ servers: [{
+ id: "s1",
+ unread: true,
+ mentions: 0,
+ unreadSources: [{ channelId: "c1", lastUnreadSeq: 4 }],
+ }],
+ }
+ expect(useServers().servers[0]?.unread).toBe(true)
+
+ const { getActiveAccountUnreadProjection } = await import("./account-unread-projection")
+ getActiveAccountUnreadProjection(capturedHookQueryClient).acceptPrimarySnapshot({
+ revision: 1,
+ readStates: [{ channelId: "c1", lastReadSeq: 4 }],
+ })
+ expect(useServers().servers[0]?.unread).toBe(false)
+ })
})
describe("useServer / serverQueryFn", () => {
@@ -113,6 +206,72 @@ describe("useServer / serverQueryFn", () => {
expect(apiFetchMock).not.toHaveBeenCalled()
})
+ it("projects server-detail channels while preserving unchanged category paths", async () => {
+ const changedChannel = { id: "c1", unread: false }
+ const unchangedChannel = { id: "c2", unread: true }
+ const changedCategory = { id: "cat1", channels: [changedChannel] }
+ const unchangedCategory = { id: "cat2", channels: [unchangedChannel] }
+ const detail = {
+ id: "s1",
+ categories: [changedCategory, unchangedCategory],
+ unreadSources: [{ channelId: "c1", lastUnreadSeq: 1, lastAttentionSeq: null }],
+ forumUnreadState: {},
+ }
+ capturedHookQueryData = detail
+ const { getActiveAccountUnreadProjection } = await import("./account-unread-projection")
+ getActiveAccountUnreadProjection(capturedHookQueryClient).recordArrival({
+ channelId: "c1",
+ serverId: "s1",
+ seq: 1,
+ })
+ const { useServer } = await import("./use-servers")
+
+ const result = useServer("s1")
+
+ expect(result.server).not.toBe(detail)
+ expect(result.server?.categories[0]).not.toBe(changedCategory)
+ expect(result.server?.categories[0]?.channels[0]?.unread).toBe(true)
+ expect(result.server?.categories[1]).toBe(unchangedCategory)
+ expect(result.server?.categories[1]?.channels[0]).toBe(unchangedChannel)
+ })
+
+ it("retains rolling-deploy server-detail unread rows without source vectors", async () => {
+ const channel = { id: "c1", unread: true }
+ const baseUnreadForum = { id: "forum-base", unread: false }
+ const childUnreadForum = { id: "forum-child", unread: false }
+ const detail = {
+ id: "s1",
+ categories: [{
+ id: "cat1",
+ channels: [channel, baseUnreadForum, childUnreadForum],
+ }],
+ forumUnreadState: {
+ "forum-base": { baseUnread: true, childIds: [] },
+ "forum-child": { baseUnread: false, childIds: ["child"] },
+ },
+ }
+ capturedHookQueryData = detail
+ const { useServer } = await import("./use-servers")
+ const first = useServer("s1")
+ expect(first.server?.categories[0]?.channels[0]?.unread).toBe(true)
+ expect(first.server?.categories[0]?.channels[1]?.unread).toBe(true)
+ expect(first.server?.categories[0]?.channels[2]?.unread).toBe(true)
+
+ capturedHookQueryData = {
+ ...detail,
+ categories: [{
+ id: "cat1",
+ channels: [
+ { id: "c1", unread: false },
+ { id: "forum-base", unread: false },
+ { id: "forum-child", unread: false },
+ ],
+ }],
+ }
+ const second = useServer("s1")
+ expect(second.server?.categories[0]?.channels[0]?.unread).toBe(true)
+ })
+
it("composes a single server detail from canonical resources", async () => {
const detail = { id: "srv_1", name: "Alook", description: "", icon: null, ownerId: "u_1" }
apiFetchMock.mockImplementation(async (url: string) => {
diff --git a/src/web/src/hooks/community/use-servers.ts b/src/web/src/hooks/community/use-servers.ts
index d16b07141..aeadad156 100644
--- a/src/web/src/hooks/community/use-servers.ts
+++ b/src/web/src/hooks/community/use-servers.ts
@@ -7,11 +7,13 @@ import {
type QueryFunctionContext,
type UseQueryResult,
} from "@tanstack/react-query"
+import { useEffect, useMemo, useSyncExternalStore } from "react"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import { avatarInitial } from "@/lib/community/avatar"
import { isServerOwner, UNCATEGORIZED_CATEGORY_ID } from "@alook/shared"
import type { Server, Category, Channel } from "@/lib/community/models/navigation"
+import { getActiveAccountUnreadProjection } from "./account-unread-projection"
/**
* Fetches the sidebar list of servers the current user is in.
@@ -32,6 +34,8 @@ type RawServerRow = {
unread?: boolean
description?: string | null
ownerId: string
+ unreadSources?: Array<{ channelId: string; lastUnreadSeq: number }>
+ mentionSources?: Array<{ channelId: string; count: number; lastSeq: number }>
}
export type ServersResponse = { servers: Server[] }
@@ -62,6 +66,8 @@ export const serversQueryFn = async (
mentions: s.mentions ?? 0,
isOwner: isServerOwner(s.role),
icon: s.icon ?? null,
+ ...(s.unreadSources ? { unreadSources: s.unreadSources } : {}),
+ ...(s.mentionSources ? { mentionSources: s.mentionSources } : {}),
}))
return { servers }
}
@@ -91,9 +97,63 @@ export function useServers(): UseQueryResult<ServersResponse> & {
staleTime: Infinity,
refetchOnReconnect: true,
})
+ const queryClient = useQueryClient()
+ const unreadProjection = useMemo(
+ () => getActiveAccountUnreadProjection(queryClient),
+ [queryClient],
+ )
+ const unreadVersion = useSyncExternalStore(
+ unreadProjection.subscribe,
+ unreadProjection.getSnapshot,
+ unreadProjection.getSnapshot,
+ )
+ useEffect(() => {
+ const sources = query.data?.servers.flatMap((server) => server.unreadSources ?? [])
+ if (sources) unreadProjection.absorbFamily("servers", sources)
+ if (!query.data) return
+ for (const server of query.data.servers) {
+ if (server.unreadSources) {
+ unreadProjection.absorbLegacyServerAggregate(server.id, server.unreadSources)
+ }
+ }
+ unreadProjection.recordLegacySnapshot(
+ query.data,
+ query.data.servers.flatMap((server) => (
+ server.unread && server.unreadSources === undefined
+ ? [{
+ family: "servers" as const,
+ channelId: `\u0000legacy-server:${server.id}`,
+ serverId: server.id,
+ }]
+ : []
+ )),
+ )
+ }, [query.data, unreadProjection])
+ const projectedServers = useMemo(() => {
+ void unreadVersion
+ const raw = query.data?.servers
+ if (!raw) return undefined
+ let changed = false
+ const projected = raw.map((server) => {
+ const unread = unreadProjection.projectServerUnread(
+ server.id,
+ server.unreadSources ?? [],
+ server.unread,
+ )
+ const mentions = unreadProjection.projectServerMentionCount(
+ server.id,
+ server.mentionSources ?? [],
+ server.mentions,
+ )
+ if (unread === server.unread && mentions === server.mentions) return server
+ changed = true
+ return { ...server, unread, mentions }
+ })
+ return changed ? projected : raw
+ }, [query.data, unreadProjection, unreadVersion])
return {
...query,
- servers: query.data?.servers ?? (EMPTY_SERVERS as Server[]),
+ servers: projectedServers ?? (EMPTY_SERVERS as Server[]),
}
}
@@ -109,6 +169,11 @@ export type ServerDetail = {
categories: Category[]
/** Canonical unread ownership for participating children of forum channels. */
forumUnreadState?: ForumUnreadState
+ unreadSources?: Array<{
+ channelId: string
+ lastUnreadSeq: number
+ lastAttentionSeq: number | null
+ }>
}
type ForumUnreadState = Record<string, {
@@ -122,7 +187,17 @@ type RawChannel = Channel & { categoryId: string | null }
type UnreadResponse = {
stale?: boolean
channelIds: string[]
- childChannels?: Array<{ id: string; parentChannelId: string }>
+ sources?: Array<{
+ channelId: string
+ lastUnreadSeq: number
+ lastAttentionSeq: number | null
+ }>
+ childChannels?: Array<{
+ id: string
+ parentChannelId: string
+ lastUnreadSeq?: number
+ lastAttentionSeq?: number | null
+ }>
}
export const serverQueryFn = (
@@ -180,6 +255,7 @@ export const serverQueryFn = (
ownerId: server.ownerId ?? "",
categories,
forumUnreadState,
+ ...(unreadData.sources ? { unreadSources: unreadData.sources } : {}),
}
}
@@ -192,6 +268,15 @@ export function useServer(
serverId: string | null,
): UseQueryResult<ServerDetail> & { server: ServerDetail | null } {
const queryClient = useQueryClient()
+ const unreadProjection = useMemo(
+ () => getActiveAccountUnreadProjection(queryClient),
+ [queryClient],
+ )
+ const unreadVersion = useSyncExternalStore(
+ unreadProjection.subscribe,
+ unreadProjection.getSnapshot,
+ unreadProjection.getSnapshot,
+ )
const enabled = !!serverId
const query = useQuery({
queryKey: enabled ? communityKeys.server(serverId!) : communityKeys.server("__none__"),
@@ -207,8 +292,72 @@ export function useServer(
staleTime: Infinity,
refetchOnReconnect: true,
})
+ useEffect(() => {
+ if (!serverId || !query.data) return
+ const family = `server-detail:${serverId}` as const
+ if (query.data.unreadSources) {
+ unreadProjection.absorbFamily(family, query.data.unreadSources)
+ return
+ }
+ unreadProjection.recordLegacySnapshot(
+ query.data,
+ query.data.categories.flatMap((category) => category.channels.flatMap((channel) => {
+ const forum = query.data?.forumUnreadState?.[channel.id]
+ if (forum) {
+ return [
+ ...(forum.baseUnread ? [{
+ family,
+ channelId: channel.id,
+ serverId,
+ }] : []),
+ ...forum.childIds.map((childId) => ({
+ family,
+ channelId: childId,
+ serverId,
+ railChannelId: channel.id,
+ })),
+ ]
+ }
+ return channel.unread ? [{ family, channelId: channel.id, serverId }] : []
+ })),
+ )
+ }, [query.data, serverId, unreadProjection])
+ const projectedServer = useMemo(() => {
+ void unreadVersion
+ if (!query.data || !serverId) return null
+ const sourceByChannel = new Map(
+ (query.data.unreadSources ?? []).map((source) => [source.channelId, source]),
+ )
+ let changed = false
+ const categories = query.data.categories.map((category) => {
+ let categoryChanged = false
+ const channels = category.channels.map((channel) => {
+ const forum = query.data?.forumUnreadState?.[channel.id]
+ const sourceIds = forum
+ ? [channel.id, ...forum.childIds]
+ : [channel.id]
+ const sources = sourceIds.flatMap((id) => {
+ const source = sourceByChannel.get(id)
+ return source ? [source] : []
+ })
+ const unread = unreadProjection.projectServerChannelUnread(
+ serverId,
+ channel.id,
+ sources,
+ channel.unread,
+ )
+ if (unread === channel.unread) return channel
+ categoryChanged = true
+ return { ...channel, unread }
+ })
+ if (!categoryChanged) return category
+ changed = true
+ return { ...category, channels }
+ })
+ return changed ? { ...query.data, categories } : query.data
+ }, [query.data, serverId, unreadProjection, unreadVersion])
return {
...query,
- server: query.data ?? null,
+ server: projectedServer,
}
}
diff --git a/src/web/src/hooks/community/ws-live-query-config.test.ts b/src/web/src/hooks/community/ws-live-query-config.test.ts
index 561ea4b77..709650f50 100644
--- a/src/web/src/hooks/community/ws-live-query-config.test.ts
+++ b/src/web/src/hooks/community/ws-live-query-config.test.ts
@@ -25,6 +25,7 @@ vi.mock("react", () => ({
useRef: (init: unknown) => ({ current: init }),
useCallback: (fn: unknown) => fn,
useEffect: () => {},
+ useSyncExternalStore: (_subscribe: unknown, getSnapshot: () => unknown) => getSnapshot(),
}))
// ── react-query shim — capture each query's options ─────────────────────────
diff --git a/src/web/src/lib/community/models/inbox.ts b/src/web/src/lib/community/models/inbox.ts
index 139bc93db..34da4a2a0 100644
--- a/src/web/src/lib/community/models/inbox.ts
+++ b/src/web/src/lib/community/models/inbox.ts
@@ -48,6 +48,7 @@ type UnreadChild = {
// MessagesSquare). Optional for backward-compat with cached responses.
type?: EntityKind
lastMessageAt: string
+ lastUnreadSeq?: number
mentionCount: number
// Required together when canonical parent-opener metadata is available.
// The child id remains the navigation target; opener seq belongs to the
@@ -71,6 +72,7 @@ export type UnreadServer = {
// channel shows the forum glyph, not a generic hash.
type?: EntityKind
lastMessageAt: string
+ lastUnreadSeq?: number
mentionCount: number
hasDirectUnread?: boolean
children: UnreadChild[]
@@ -89,4 +91,5 @@ export type UnreadDm = {
otherUserAvatar: string
otherUserAvatarVersion: number
lastMessageAt: string
+ lastUnreadSeq?: number
}
diff --git a/src/web/src/lib/community/models/navigation.ts b/src/web/src/lib/community/models/navigation.ts
index f79a9b7f2..004add66e 100644
--- a/src/web/src/lib/community/models/navigation.ts
+++ b/src/web/src/lib/community/models/navigation.ts
@@ -13,6 +13,10 @@ export type Server = {
active: boolean
unread: boolean
mentions: number
+ /** Exact human unread sources. Absent only for rolling-deploy cache rows. */
+ unreadSources?: Array<{ channelId: string; lastUnreadSeq: number }>
+ /** Exact direct-mention sources behind the numeric rail badge. */
+ mentionSources?: Array<{ channelId: string; count: number; lastSeq: number }>
isOwner?: boolean
icon?: string | null
}
diff --git a/src/web/src/lib/community/models/people.ts b/src/web/src/lib/community/models/people.ts
index 7183fe737..f8e10fe92 100644
--- a/src/web/src/lib/community/models/people.ts
+++ b/src/web/src/lib/community/models/people.ts
@@ -109,6 +109,7 @@ export type DM = CommunityUserCore & {
status: Presence
preview: string
unread?: boolean
+ lastUnreadSeq?: number
}
// ── Settings rows ──────────────────────────────────────────────────────────
diff --git a/src/web/src/test/architecture/community-read-state-writer-contract.test.ts b/src/web/src/test/architecture/community-read-state-writer-contract.test.ts
index d95634edd..683efcbc8 100644
--- a/src/web/src/test/architecture/community-read-state-writer-contract.test.ts
+++ b/src/web/src/test/architecture/community-read-state-writer-contract.test.ts
@@ -103,6 +103,29 @@ describe("human account read-state writer contract", () => {
])
})
+ it("keeps the account unread ledger synchronous and I/O-free", () => {
+ const projection = source(
+ "src/web/src/hooks/community/account-unread-projection.ts",
+ )
+ expect(projection).not.toMatch(/\b(?:apiFetch|fetch|setTimeout|setInterval)\s*\(/)
+ expect(projection).not.toMatch(
+ /queryClient\.(?:setQueryData|invalidateQueries|fetchQuery|refetchQueries|cancelQueries)\s*\(/,
+ )
+ })
+
+ it("keeps optimistic unread clearing owned by the visible-row observer", () => {
+ const webSourceRoot = resolve(repositoryRoot, "src/web/src")
+ const owners = walkTypeScript(webSourceRoot)
+ .filter((path) => !path.includes("/test/") && !path.endsWith(".test.ts"))
+ .filter((path) => /\.recordOptimisticRead\s*\(/.test(readFileSync(path, "utf8")))
+ .map((path) => relative(repositoryRoot, path).replaceAll("\\", "/"))
+ .sort()
+
+ expect(owners).toEqual([
+ "src/web/src/hooks/community/use-read-observer.ts",
+ ])
+ })
+
it("keeps type-specific access in the adapter and the post-auth read effect generic", () => {
const route = source("src/web/src/app/api/community/channels/[id]/read/route.ts")
const postAuthorization = route.slice(route.indexOf("if (!auth.ok)"))
diff --git a/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts b/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts
index 6850f7f60..7ef52d677 100644
--- a/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts
+++ b/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts
@@ -1,3 +1,4 @@
+import type { Route } from "@playwright/test"
import { test, expect, userId } from "./_fixtures/community-fixture"
import { gotoAfterUserWsAuth } from "./_fixtures/actions"
import { tid } from "./_fixtures/testids"
@@ -209,17 +210,48 @@ test("one human account converges read state across two browser profiles", async
await expect(deviceB.page.getByRole("button", { name: "Mark all read" })).toBeEnabled()
const readAllFrameStarts = [proxyA.frames.length, proxyB.frames.length]
+ // Keep the first profile's read-all response from clearing the second
+ // profile's button before Playwright can dispatch both concurrent clicks.
+ // The mutation launches all three domains in parallel, so release only once
+ // both profiles have put every request on the wire.
+ const readAllPattern = "**/api/community/users/me/inbox/**/read-all"
+ let interceptedReadAllRequests = 0
+ let releaseReadAllRequests!: () => void
+ const readAllRequestGate = new Promise<void>((resolve) => {
+ releaseReadAllRequests = resolve
+ })
+ const holdReadAllRequests = async (route: Route) => {
+ if (route.request().method() !== "POST") {
+ await route.continue()
+ return
+ }
+ interceptedReadAllRequests += 1
+ await readAllRequestGate
+ await route.continue()
+ }
+ await Promise.all([
+ deviceA.page.route(readAllPattern, holdReadAllRequests),
+ deviceB.page.route(readAllPattern, holdReadAllRequests),
+ ])
+
const readAllResponses = [deviceA.page, deviceB.page].flatMap((page) => [
page.waitForResponse((response) => response.request().method() === "POST"
&& new URL(response.url()).pathname === "/api/community/users/me/inbox/unreads/read-all"),
page.waitForResponse((response) => response.request().method() === "POST"
&& new URL(response.url()).pathname === "/api/community/users/me/inbox/dms/read-all"),
])
- await Promise.all([
+ const markAllClicks = Promise.all([
deviceA.page.getByRole("button", { name: "Mark all read" }).click(),
deviceB.page.getByRole("button", { name: "Mark all read" }).click(),
])
+ await expect.poll(() => interceptedReadAllRequests, { timeout: 20_000 }).toBe(6)
+ releaseReadAllRequests()
+ await markAllClicks
const completedReadAllResponses = await Promise.all(readAllResponses)
+ await Promise.all([
+ deviceA.page.unroute(readAllPattern, holdReadAllRequests),
+ deviceB.page.unroute(readAllPattern, holdReadAllRequests),
+ ])
expect(completedReadAllResponses.every((response) => response.status() === 200)).toBe(true)
const readAllResults = await Promise.all(completedReadAllResponses.map(async (response) => ({
path: new URL(response.url()).pathname,
diff --git a/src/web/src/test/e2e-ui/33-picker-async-layout.spec.ts b/src/web/src/test/e2e-ui/33-picker-async-layout.spec.ts
index 218331393..cffb01dc4 100644
--- a/src/web/src/test/e2e-ui/33-picker-async-layout.spec.ts
+++ b/src/web/src/test/e2e-ui/33-picker-async-layout.spec.ts
@@ -133,9 +133,10 @@ test.describe.serial("invite and participant picker async states", () => {
await dmGate.promise
await route.continue()
})
- await expect(dialog.getByRole("button", { name: "Invite" })).toHaveCount(2)
const selectedRow = dialog.getByText(bobName, { exact: true }).locator("..").locator("..")
const otherRow = dialog.getByText(carolName, { exact: true }).locator("..").locator("..")
+ await expect(selectedRow.getByRole("button", { name: "Invite" })).toHaveCount(1)
+ await expect(otherRow.getByRole("button", { name: "Invite" })).toHaveCount(1)
await selectedRow.getByRole("button", { name: "Invite" }).click()
await expect.poll(() => writes.filter((path) => path === "/api/community/channels").length).toBe(1)
await expect(selectedRow.locator("button")).toBeDisabled()
diff --git a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
new file mode 100644
index 000000000..b973c4ea1
--- /dev/null
+++ b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
@@ -0,0 +1,263 @@
+import type { Page } from "@playwright/test"
+import { expect, test, userId } from "./_fixtures/community-fixture"
+import { gotoAfterUserWsAuth } from "./_fixtures/actions"
+import {
+ communityFrameEvents,
+ proxyCommunityWebSockets,
+ type CapturedCommunityFrame,
+} from "./_fixtures/community-ws-proxy"
+import {
+ seedChannel,
+ seedDm,
+ seedDmMessage,
+ seedForumThread,
+ seedJoinServer,
+ seedMessage,
+ seedServer,
+} from "./_fixtures/seed"
+import { tid } from "./_fixtures/testids"
+
+async function installReadObserverGate(page: Page) {
+ await page.addInitScript(() => {
+ const NativeIntersectionObserver = window.IntersectionObserver
+ const queued: Array<() => void> = []
+ let blocked = false
+ class GatedIntersectionObserver implements IntersectionObserver {
+ readonly root: Element | Document | null
+ readonly rootMargin: string
+ readonly scrollMargin: string
+ readonly thresholds: readonly number[]
+ private readonly observer: IntersectionObserver
+
+ constructor(callback: IntersectionObserverCallback, options?: IntersectionObserverInit) {
+ this.observer = new NativeIntersectionObserver((entries) => {
+ const deliver = () => callback(entries, this)
+ if (blocked && entries.some((entry) => (
+ (entry.target as HTMLElement).hasAttribute("data-msg-id")
+ ))) {
+ queued.push(deliver)
+ return
+ }
+ deliver()
+ }, options)
+ this.root = this.observer.root
+ this.rootMargin = this.observer.rootMargin
+ this.scrollMargin = this.observer.scrollMargin
+ this.thresholds = this.observer.thresholds
+ }
+
+ disconnect() { this.observer.disconnect() }
+ observe(target: Element) { this.observer.observe(target) }
+ takeRecords() { return this.observer.takeRecords() }
+ unobserve(target: Element) { this.observer.unobserve(target) }
+ }
+ window.IntersectionObserver = GatedIntersectionObserver
+ ;(window as unknown as Record<string, unknown>).__accountUnreadObserverGate = {
+ block: () => { blocked = true },
+ pending: () => queued.length,
+ release: () => {
+ blocked = false
+ for (const deliver of queued.splice(0)) deliver()
+ },
+ }
+ })
+ const invoke = async (method: "block" | "pending" | "release") => page.evaluate((name) => {
+ const gate = (window as unknown as Record<string, {
+ block: () => void
+ pending: () => number
+ release: () => void
+ }>).__accountUnreadObserverGate
+ return gate[name]()
+ }, method)
+ return {
+ block: () => invoke("block"),
+ pending: () => invoke("pending") as Promise<number>,
+ release: () => invoke("release"),
+ }
+}
+
+function hasCorrelatedBundle(
+ frames: CapturedCommunityFrame[],
+ messageId: string,
+ channelId: string,
+) {
+ return frames.some((frame) => {
+ if (frame.type !== "community:events.batch") return false
+ const events = communityFrameEvents(frame)
+ return events.some((event) => (
+ event.type === "community:message.create"
+ && event.message?.id === messageId
+ && event.message?.seq !== undefined
+ )) && events.some((event) => (
+ event.type === "community:unread.bump"
+ && event.channelId === channelId
+ ))
+ })
+}
+
+async function expectUnreadDot(row: ReturnType<Page["getByTestId"]>) {
+ await expect(row.locator("span.rounded-full.bg-primary")).toHaveCount(1)
+}
+
+test.describe.serial("account unread projection", () => {
+ test.setTimeout(180_000)
+
+ test("one committed bundle projects every surface and only a visible row clears it", async ({ asUser }, testInfo) => {
+ const stamp = Date.now()
+ const foregroundServer = await seedServer("alice", `Projection foreground ${stamp}`)
+ const foregroundChannel = await seedChannel("alice", foregroundServer, `foreground-${stamp}`)
+ const backgroundServer = await seedServer("alice", `Projection background ${stamp}`)
+ const landingChannel = await seedChannel("alice", backgroundServer, `landing-${stamp}`)
+ const unreadChannel = await seedChannel("alice", backgroundServer, `unread-${stamp}`)
+ const forumId = await seedChannel("alice", backgroundServer, `forum-${stamp}`, "forum")
+ await seedJoinServer("alice", "bob", foregroundServer)
+ await seedJoinServer("alice", "bob", backgroundServer)
+ const forumChild = await seedForumThread(
+ "bob",
+ forumId,
+ `Projection post ${stamp}`,
+ `Bob participation ${stamp}`,
+ )
+ const dmId = await seedDm("alice", userId("bob"))
+
+ const { context, page } = await asUser("bob")
+ await page.setViewportSize({ width: 1280, height: 900 })
+ const observerGate = await installReadObserverGate(page)
+ const proxy = await proxyCommunityWebSockets(context)
+ await gotoAfterUserWsAuth(page, `/c/channels/${foregroundServer}/${foregroundChannel}`)
+ await expect(page.getByTestId(tid.serverIcon(backgroundServer))).toBeVisible({ timeout: 30_000 })
+ const beforeSnapshot = await (await page.request.get(
+ "/api/community/users/me/read-state",
+ )).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
+ const beforeCursor = (channelId: string) => beforeSnapshot.readStates
+ .find((row) => row.channelId === channelId)?.lastReadSeq ?? 0
+
+ const frameStart = proxy.frames.length
+ const channelMessage = await seedMessage("alice", unreadChannel, `Projected channel ${stamp}`)
+ const childMessage = await seedMessage("alice", forumChild, `Projected forum child ${stamp}`)
+ const dmMessage = await seedDmMessage("alice", dmId, `Projected DM ${stamp}`)
+ for (const [messageId, channelId] of [
+ [channelMessage, unreadChannel],
+ [childMessage, forumChild],
+ [dmMessage, dmId],
+ ]) {
+ await expect.poll(() => hasCorrelatedBundle(
+ proxy.frames.slice(frameStart),
+ messageId,
+ channelId,
+ ), { timeout: 20_000 }).toBe(true)
+ }
+
+ await expect.poll(async () => page
+ .getByTestId(tid.serverRailIndicator(backgroundServer))
+ .evaluate((element) => element.getBoundingClientRect().height), {
+ timeout: 20_000,
+ }).toBe(10)
+ await gotoAfterUserWsAuth(
+ page,
+ `/c/channels/${backgroundServer}/${landingChannel}`,
+ )
+ await expect(page).toHaveURL(`/c/channels/${backgroundServer}/${landingChannel}`)
+ await expectUnreadDot(page.getByTestId(tid.channelRow(unreadChannel)))
+
+ await gotoAfterUserWsAuth(page, `/c/channels/${backgroundServer}/${forumId}`)
+ await expect(page).toHaveURL(`/c/channels/${backgroundServer}/${forumId}`)
+ await expectUnreadDot(page.getByTestId(tid.forumSidebarThread(forumChild)))
+ await page.getByRole("button", { name: "Inbox" }).click()
+ await expect(page.getByTestId(tid.inboxUnreadChannel(unreadChannel))).toBeVisible()
+ await expect(page.getByTestId(tid.inboxUnreadChild(forumChild))).toBeVisible()
+ await expect(page.getByTestId(tid.inboxUnreadDm(dmId))).toBeVisible()
+ await page.waitForTimeout(500)
+ await page.screenshot({
+ path: testInfo.outputPath("account-unread-projection-1280.png"),
+ fullPage: true,
+ })
+
+ await observerGate.block()
+ const targetPuts: string[] = []
+ page.on("request", (request) => {
+ if (
+ request.method() === "PUT"
+ && new URL(request.url()).pathname === `/api/community/channels/${unreadChannel}/read`
+ ) targetPuts.push(request.url())
+ })
+ await page.getByTestId(tid.inboxUnreadChannel(unreadChannel)).click()
+ await expect(page).toHaveURL(`/c/channels/${backgroundServer}/${unreadChannel}`)
+ await expect(page.getByText(`Projected channel ${stamp}`, { exact: true })).toBeVisible({
+ timeout: 20_000,
+ })
+ await expect.poll(observerGate.pending).toBeGreaterThan(0)
+ expect(targetPuts).toEqual([])
+
+ const readResponse = page.waitForResponse((response) => (
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname === `/api/community/channels/${unreadChannel}/read`
+ ))
+ await observerGate.release()
+ expect((await readResponse).status()).toBe(200)
+ expect(targetPuts).toHaveLength(1)
+
+ await page.setViewportSize({ width: 390, height: 844 })
+ await gotoAfterUserWsAuth(page, "/c/me")
+ await page.getByRole("button", { name: "Inbox" }).click()
+ await expect(page.getByTestId(tid.inboxUnreadChannel(unreadChannel))).toHaveCount(0)
+ await expect(page.getByTestId(tid.inboxUnreadChild(forumChild))).toBeVisible()
+ await expect(page.getByTestId(tid.inboxUnreadDm(dmId))).toBeVisible()
+ await page.waitForTimeout(500)
+ await page.screenshot({
+ path: testInfo.outputPath("account-unread-projection-390.png"),
+ fullPage: true,
+ })
+
+ const snapshot = await (await page.request.get(
+ "/api/community/users/me/read-state",
+ )).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
+ const cursor = (channelId: string) => snapshot.readStates
+ .find((row) => row.channelId === channelId)?.lastReadSeq ?? 0
+ expect(cursor(unreadChannel)).toBeGreaterThan(beforeCursor(unreadChannel))
+ expect(cursor(forumChild)).toBe(beforeCursor(forumChild))
+ expect(cursor(dmId)).toBe(beforeCursor(dmId))
+ })
+
+ test("mark all settles three domains and rolls back only the failed domain", async ({ asUser }) => {
+ const stamp = Date.now()
+ const serverId = await seedServer("alice", `Projection mark all ${stamp}`)
+ const channelId = await seedChannel("alice", serverId, `mark-all-${stamp}`)
+ await seedJoinServer("alice", "bob", serverId)
+ await seedMessage("alice", channelId, `Channel mark all ${stamp}`)
+ const dmId = await seedDm("alice", userId("bob"))
+ await seedDmMessage("alice", dmId, `DM mark all ${stamp}`)
+
+ const { page } = await asUser("bob")
+ await gotoAfterUserWsAuth(page, "/c/me")
+ await page.getByRole("button", { name: "Inbox" }).click()
+ await expect(page.getByTestId(tid.inboxUnreadChannel(channelId))).toBeVisible()
+ await expect(page.getByTestId(tid.inboxUnreadDm(dmId))).toBeVisible()
+
+ const paths: string[] = []
+ page.on("request", (request) => {
+ const path = new URL(request.url()).pathname
+ if (request.method() === "POST" && path.endsWith("/read-all")) paths.push(path)
+ })
+ await page.route("**/api/community/users/me/inbox/dms/read-all", async (route) => {
+ await route.fulfill({
+ status: 503,
+ contentType: "application/json",
+ body: '{"error":"dm read-all unavailable"}',
+ })
+ })
+ await page.getByRole("button", { name: "Mark all read" }).click()
+ await expect.poll(() => paths.length, { timeout: 20_000 }).toBe(3)
+ expect([...paths].sort()).toEqual([
+ "/api/community/users/me/inbox/dms/read-all",
+ "/api/community/users/me/inbox/mentions/read-all",
+ "/api/community/users/me/inbox/unreads/read-all",
+ ])
+ await expect(page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0)
+ await expect(page.getByTestId(tid.inboxUnreadDm(dmId))).toBeVisible()
+
+ await page.unroute("**/api/community/users/me/inbox/dms/read-all")
+ await page.getByRole("button", { name: "Mark all read" }).click()
+ await expect(page.getByText("Caught up", { exact: true })).toBeVisible({ timeout: 20_000 })
+ })
+})