Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): unify unread presentation (#684)

Gener6f9ad86b07fe
diff --git a/src/shared/src/db/queries/community/notification-setting.ts b/src/shared/src/db/queries/community/notification-setting.ts
index 7ed174ed7..9f18bda1d 100644
--- a/src/shared/src/db/queries/community/notification-setting.ts
+++ b/src/shared/src/db/queries/community/notification-setting.ts
@@ -5,21 +5,16 @@ import {
isNull,
isNotNull,
inArray,
- gt,
exists,
- notExists,
sql,
} from "drizzle-orm";
import type { SQLWrapper } from "drizzle-orm";
-import { alias } from "drizzle-orm/sqlite-core";
import { nanoid } from "nanoid";
import {
communityNotificationSetting,
communityChannel,
communityCategory,
communityChannelMember,
- communityMessage,
- communityReadState,
communityServerMember,
} from "../../community-schema";
import type { Database } from "../../index";
@@ -334,79 +329,6 @@ function nextEffectiveLevelSql(userId: string, change: SettingChange) {
)`;
}
-/**
- * Build the cursor half of a notification-setting mutation.
- *
- * The product contract treats a setting change as handling every old unread
- * in the affected scope. The statement selects each channel's latest real
- * message and advances all three aligned read-state fields together. Empty
- * channels produce no row, while the conflict guard prevents a concurrent or
- * already-newer cursor from regressing.
- */
-function buildClearAffectedUnreadStatement(
- db: Database,
- userId: string,
- change: SettingChange,
-) {
- const scope: MutationScope = change.kind === "set-server"
- ? { kind: "server", id: change.id }
- : { kind: "channel", id: change.id };
- const latestMessage = alias(communityMessage, "notification_latest_message");
- const newerMessage = alias(communityMessage, "notification_newer_message");
- const channelSql = {
- id: communityChannel.id,
- serverId: communityChannel.serverId,
- parentChannelId: communityChannel.parentChannelId,
- };
- const currentLevel = currentEffectiveLevelSql(userId, channelSql);
- const nextLevel = nextEffectiveLevelSql(userId, change);
- const selected = db
- .select({
- id: sql<string>`lower(hex(randomblob(16)))`.as("id"),
- userId: sql<string>`${userId}`.as("user_id"),
- channelId: communityChannel.id,
- lastReadAt: latestMessage.createdAt,
- lastReadMessageId: latestMessage.id,
- lastReadSeq: latestMessage.seq,
- })
- .from(communityChannel)
- .innerJoin(
- latestMessage,
- eq(latestMessage.channelId, communityChannel.id),
- )
- .where(
- and(
- affectedChannelWhere(scope),
- userCanAccessChannelSql(userId),
- sql`${currentLevel} <> ${nextLevel}`,
- notExists(
- db
- .select({ one: sql<number>`1` })
- .from(newerMessage)
- .where(
- and(
- eq(newerMessage.channelId, latestMessage.channelId),
- gt(newerMessage.seq, latestMessage.seq),
- ),
- ),
- ),
- ),
- );
-
- return db
- .insert(communityReadState)
- .select(selected)
- .onConflictDoUpdate({
- target: [communityReadState.userId, communityReadState.channelId],
- set: {
- lastReadAt: sql`excluded.last_read_at`,
- lastReadMessageId: sql`excluded.last_read_message_id`,
- lastReadSeq: sql`excluded.last_read_seq`,
- },
- setWhere: sql`${communityReadState.lastReadSeq} < excluded.last_read_seq`,
- });
-}
-
function effectivePolicyChangesCondition(
db: Database,
userId: string,
@@ -439,24 +361,18 @@ async function applySettingMutation(
mutation: unknown,
actorKind: "human" | "bot",
): Promise<number | null> {
- // Clear first while the current projection still represents the "before"
- // level used by the changed-effective predicate. D1 batch is atomic, so no
- // observer can see the cursor advance without the setting write (or vice
- // versa), and any failure rolls both statements back.
- const clearUnread = buildClearAffectedUnreadStatement(db, userId, change);
if (actorKind === "bot") {
- await db.batch([clearUnread, mutation] as any);
+ await mutation;
return null;
}
const effectChanges = effectivePolicyChangesCondition(db, userId, change);
const results = await db.batch([
advanceReadStateRevisionWhenBuilder(db, userId, effectChanges),
- clearUnread,
mutation,
accountReadStateRevisionBuilder(db, userId),
] as any) as unknown[];
const changed = (results[0] as Array<{ revision: number }>).length > 0;
- const revision = (results[3] as Array<{ revision: number }>)[0]?.revision ?? 0;
+ const revision = (results[2] as Array<{ revision: number }>)[0]?.revision ?? 0;
return changed ? revision : null;
}
diff --git a/src/shared/test/queries/community-notification-cursor-clear.test.ts b/src/shared/test/queries/community-notification-cursor-clear.test.ts
index ad08fef83..719d59c36 100644
--- a/src/shared/test/queries/community-notification-cursor-clear.test.ts
+++ b/src/shared/test/queries/community-notification-cursor-clear.test.ts
@@ -36,7 +36,7 @@ describe("policyAllows", () => {
});
});
-describe("notification setting cursor-clear contract", () => {
+describe("notification setting read-state isolation contract", () => {
let sqlite: Sqlite.Database;
let db: Database;
@@ -174,13 +174,23 @@ describe("notification setting cursor-clear contract", () => {
ORDER BY channel_id
`).all();
- it("atomically sets a server level and clears every non-empty channel in that server", async () => {
- await setServerLevel(db, { userId: "u", serverId: "server", level: "nothing", actorKind: "human" });
+ it("sets a server policy without manufacturing or advancing channel cursors", async () => {
+ sqlite.exec(`
+ INSERT INTO community_read_state
+ (id, user_id, channel_id, last_read_at, last_read_message_id, last_read_seq)
+ VALUES ('rs', 'u', 'parent', '2026-01-01T00:00:01Z', 'parent-1', 1);
+ `);
+ const result = await setServerLevel(db, {
+ userId: "u",
+ serverId: "server",
+ level: "nothing",
+ actorKind: "human",
+ });
+
+ expect(result.readStateRevision).toBe(1);
expect(cursors()).toEqual([
- { channel_id: "child", last_read_message_id: "child-3", last_read_at: "2026-01-01T00:00:03Z", last_read_seq: 3 },
- { channel_id: "parent", last_read_message_id: "parent-2", last_read_at: "2026-01-01T00:00:02Z", last_read_seq: 2 },
- { channel_id: "sibling", last_read_message_id: "sibling-4", last_read_at: "2026-01-01T00:00:04Z", last_read_seq: 4 },
+ { channel_id: "parent", last_read_message_id: "parent-1", last_read_at: "2026-01-01T00:00:01Z", last_read_seq: 1 },
]);
expect(sqlite.prepare("SELECT level FROM community_notification_setting WHERE user_id='u' AND server_id='server'").get())
.toEqual({ level: "nothing" });
@@ -199,7 +209,7 @@ describe("notification setting cursor-clear contract", () => {
.toEqual({ count: 0 });
});
- it("advances a forum's ordinary cursor and versions only an effective policy change", async () => {
+ it("versions an effective human policy change without writing a forum cursor", async () => {
sqlite.exec(`
UPDATE community_channel SET type = 'forum' WHERE id = 'parent';
`);
@@ -211,12 +221,7 @@ describe("notification setting cursor-clear contract", () => {
actorKind: "human",
});
expect(first.readStateRevision).toBe(1);
- expect(cursors()).toContainEqual({
- channel_id: "parent",
- last_read_message_id: "parent-2",
- last_read_at: "2026-01-01T00:00:02Z",
- last_read_seq: 2,
- });
+ expect(cursors()).toEqual([]);
const duplicate = await setChannelLevel(db, {
userId: "u",
@@ -230,40 +235,35 @@ describe("notification setting cursor-clear contract", () => {
`).get()).toEqual({ revision: 1 });
});
- it("does not clear a private channel the target identity cannot access", async () => {
- sqlite.exec(`
- INSERT INTO community_category (id, server_id, private) VALUES ('private', 'server', 1);
- UPDATE community_channel SET category_id = 'private', creator_id = 'author' WHERE id = 'sibling';
- `);
-
- await setServerLevel(db, { userId: "u", serverId: "server", level: "nothing", actorKind: "human" });
- expect(cursors().map((row: any) => row.channel_id)).toEqual(["child", "parent"]);
- });
-
- it("a parent override clears the parent and its children, but not a sibling", async () => {
+ it("a parent override leaves parent, child, and sibling unread state untouched", async () => {
await setChannelLevel(db, { userId: "u", channelId: "parent", level: "mentions", actorKind: "human" });
- expect(cursors().map((row: any) => row.channel_id)).toEqual(["child", "parent"]);
+ expect(cursors()).toEqual([]);
});
- it("server changes do not clear descendants protected by a more specific override", async () => {
+ it("server changes leave descendants with a more specific override unread", async () => {
sqlite.prepare(`
INSERT INTO community_notification_setting (id, user_id, channel_id, level)
VALUES ('child-own', 'u', 'child', 'all')
`).run();
await setServerLevel(db, { userId: "u", serverId: "server", level: "nothing", actorKind: "human" });
- expect(cursors().map((row: any) => row.channel_id)).toEqual(["parent", "sibling"]);
+ expect(cursors()).toEqual([]);
});
- it("does not clear when an explicit override leaves the effective level unchanged", async () => {
+ it("does not mint a revision or cursor when an explicit override leaves policy unchanged", async () => {
await setServerLevel(db, { userId: "u", serverId: "server", level: "mentions", actorKind: "human" });
- sqlite.prepare("DELETE FROM community_read_state").run();
- await setChannelLevel(db, { userId: "u", channelId: "parent", level: "mentions", actorKind: "human" });
+ const result = await setChannelLevel(db, {
+ userId: "u",
+ channelId: "parent",
+ level: "mentions",
+ actorKind: "human",
+ });
+ expect(result.readStateRevision).toBeNull();
expect(cursors()).toEqual([]);
});
- it("an idempotent retry preserves messages that arrived after the successful change", async () => {
+ it("an idempotent retry preserves every old and newly arrived unread message", async () => {
await setChannelLevel(db, { userId: "u", channelId: "parent", level: "nothing", actorKind: "human" });
sqlite.exec(`
INSERT INTO community_message (id, channel_id, created_at, seq) VALUES
@@ -272,59 +272,51 @@ describe("notification setting cursor-clear contract", () => {
`);
await setChannelLevel(db, { userId: "u", channelId: "parent", level: "nothing", actorKind: "human" });
- expect(cursors()).toEqual([
- { channel_id: "child", last_read_message_id: "child-3", last_read_at: "2026-01-01T00:00:03Z", last_read_seq: 3 },
- { channel_id: "parent", last_read_message_id: "parent-2", last_read_at: "2026-01-01T00:00:02Z", last_read_seq: 2 },
- ]);
- });
-
- it("a DM uses the same channel-scope setting and only clears that DM", async () => {
- await setChannelLevel(db, { userId: "u", channelId: "dm", level: "nothing", actorKind: "human" });
- expect(cursors()).toEqual([
- { channel_id: "dm", last_read_message_id: "dm-5", last_read_at: "2026-01-01T00:00:05Z", last_read_seq: 5 },
- ]);
- });
-
- it("empty channels never manufacture a read-state row", async () => {
- await setChannelLevel(db, { userId: "u", channelId: "empty", level: "nothing", actorKind: "human" });
expect(cursors()).toEqual([]);
});
- it("never regresses an already-newer aligned cursor", async () => {
+ it("a DM setting and override removal preserve its unread cursor", async () => {
sqlite.exec(`
- INSERT INTO community_message (id, channel_id, created_at, seq)
- VALUES ('parent-9', 'parent', '2026-01-01T00:00:09Z', 9);
INSERT INTO community_read_state
(id, user_id, channel_id, last_read_at, last_read_message_id, last_read_seq)
- VALUES ('rs', 'u', 'parent', '2026-01-01T00:00:09Z', 'parent-9', 9);
- DELETE FROM community_message WHERE id = 'parent-9';
+ VALUES ('dm-rs', 'u', 'dm', '2026-01-01T00:00:05Z', 'dm-5', 5);
`);
+ const before = cursors();
+
+ const set = await setChannelLevel(db, {
+ userId: "u",
+ channelId: "dm",
+ level: "nothing",
+ actorKind: "human",
+ });
+ expect(set.readStateRevision).toBe(1);
+ expect(cursors()).toEqual(before);
+ const removed = await removeChannelOverride(db, {
+ userId: "u",
+ channelId: "dm",
+ actorKind: "human",
+ });
- await setChannelLevel(db, { userId: "u", channelId: "parent", level: "all", actorKind: "human" });
- expect(sqlite.prepare("SELECT last_read_message_id, last_read_seq FROM community_read_state WHERE id='rs'").get())
- .toEqual({ last_read_message_id: "parent-9", last_read_seq: 9 });
+ expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_notification_setting WHERE channel_id='dm'").get())
+ .toEqual({ count: 0 });
+ expect(removed.readStateRevision).toBe(2);
+ expect(cursors()).toEqual(before);
});
- it("rolls the setting back when cursor advancement fails", async () => {
+ it("succeeds even when the database rejects every read-state insert", async () => {
sqlite.exec(`
CREATE TRIGGER reject_read_state BEFORE INSERT ON community_read_state
BEGIN SELECT RAISE(ABORT, 'cursor rejected'); END;
`);
- await expect(setServerLevel(db, { userId: "u", serverId: "server", level: "nothing", actorKind: "human" }))
- .rejects.toThrow("cursor rejected");
+ await expect(setServerLevel(db, {
+ userId: "u",
+ serverId: "server",
+ level: "nothing",
+ actorKind: "human",
+ })).resolves.toMatchObject({ setting: { level: "nothing" } });
expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_notification_setting").get())
- .toEqual({ count: 0 });
- });
-
- it("override removal also clears old unread before inheriting again", async () => {
- await setChannelLevel(db, { userId: "u", channelId: "dm", level: "nothing", actorKind: "human" });
- sqlite.prepare("DELETE FROM community_read_state").run();
- await removeChannelOverride(db, { userId: "u", channelId: "dm", actorKind: "human" });
-
- expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_notification_setting WHERE channel_id='dm'").get())
- .toEqual({ count: 0 });
- expect(cursors().map((row: any) => row.channel_id)).toEqual(["dm"]);
+ .toEqual({ count: 1 });
});
it("a no-op override removal preserves unread and creates no cursor", async () => {
@@ -356,7 +348,7 @@ describe("notification setting cursor-clear contract", () => {
expect(row).toEqual({ mentioned: 1, plain: 0 });
});
- it("rail mention badge follows policy changes and the aligned read cursor", async () => {
+ it("rail mention badge hides and restores old unread without moving the cursor", async () => {
sqlite.exec(`
INSERT INTO community_mention (id, message_id, user_id, kind, read)
VALUES ('rail-old', 'child-3', 'u', 'mention', 0);
@@ -376,14 +368,15 @@ describe("notification setting cursor-clear contract", () => {
await expect(railCount()).resolves.toBe(0);
await setChannelLevel(db, { userId: "u", channelId: "child", level: "mentions", actorKind: "human" });
- await expect(railCount()).resolves.toBe(0);
+ await expect(railCount()).resolves.toBe(2);
+ expect(cursors()).toEqual([]);
sqlite.exec(`
INSERT INTO community_message (id, channel_id, created_at, seq)
VALUES ('child-7', 'child', '2026-01-01T00:00:07Z', 7);
INSERT INTO community_mention (id, message_id, user_id, kind, read)
VALUES ('rail-new', 'child-7', 'u', 'mention', 0);
`);
- await expect(railCount()).resolves.toBe(1);
+ await expect(railCount()).resolves.toBe(3);
});
it("rail mention badge disappears immediately when private-channel access is revoked", async () => {
diff --git a/src/web/src/components/community/channels/channel-sidebar.crumb.test.ts b/src/web/src/components/community/channels/channel-sidebar.crumb.test.ts
index c26b8598d..7f1ba820e 100644
--- a/src/web/src/components/community/channels/channel-sidebar.crumb.test.ts
+++ b/src/web/src/components/community/channels/channel-sidebar.crumb.test.ts
@@ -68,7 +68,7 @@ const forumTree = {
catPending: { cat_1: false },
} as unknown as ChannelTree
-const renderForum = (muted = false) => renderToStaticMarkup(
+const renderForum = (muted = false, activeThreadId = "post_2") => renderToStaticMarkup(
createElement(ChannelSidebar, {
tree: forumTree,
serverName: "Alpha",
@@ -97,7 +97,7 @@ const renderForum = (muted = false) => renderToStaticMarkup(
},
],
},
- activeThreadId: "post_2",
+ activeThreadId,
onSelectForumThread: vi.fn(),
}),
)
@@ -149,4 +149,11 @@ describe("ChannelSidebar header", () => {
it("suppresses the child unread dot when its parent forum is muted", () => {
expect(renderForum(true)).not.toContain("bg-primary")
})
+
+ it("uses the active child shape without treating route activation as read", () => {
+ const html = renderForum(false, "post_1")
+ expect(html).toContain('data-testid="community-forum-sidebar-thread-post_1"')
+ expect(html).toContain('aria-current="page"')
+ expect(html).not.toContain("bg-primary")
+ })
})
diff --git a/src/web/src/components/community/channels/channel-sidebar.tsx b/src/web/src/components/community/channels/channel-sidebar.tsx
index c5f89c71c..f490e6b21 100644
--- a/src/web/src/components/community/channels/channel-sidebar.tsx
+++ b/src/web/src/components/community/channels/channel-sidebar.tsx
@@ -23,6 +23,7 @@ import type { SettingsSection } from "@/components/community/settings/settings-t
import { UNCATEGORIZED_CATEGORY_ID, type ChannelType } from "@alook/shared"
import { tid } from "@/lib/community/testids"
import type { ForumSidebarThread } from "@/hooks/community/use-forum-sidebar-threads"
+import { selectUnreadPresentation } from "@/hooks/community/unread-presentation"
type Dialog =
@@ -447,6 +448,11 @@ function ForumSidebarThreadRow({
onClick: () => void
onPrefetch?: () => void
}) {
+ const unread = selectUnreadPresentation({
+ accountUnread: thread.unread,
+ active,
+ muted,
+ })
return (
<div className="relative h-7">
<button
@@ -466,13 +472,13 @@ function ForumSidebarThreadRow({
? "bg-sidebar-accent text-foreground"
: muted
? "text-muted-foreground/50 hover:bg-sidebar-accent/60 hover:text-muted-foreground"
- : thread.unread
+ : unread.emphasize
? "text-foreground hover:bg-sidebar-accent/60"
: "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",
].join(" ")}
>
<span className="truncate">{thread.title}</span>
- {!muted && thread.unread && !active ? (
+ {unread.showDot ? (
<span className="ml-auto size-2 shrink-0 rounded-full bg-primary" />
) : null}
</button>
diff --git a/src/web/src/components/community/channels/dm-sidebar.prefetch.test.ts b/src/web/src/components/community/channels/dm-sidebar.prefetch.test.ts
index 3a2307716..8f74e994e 100644
--- a/src/web/src/components/community/channels/dm-sidebar.prefetch.test.ts
+++ b/src/web/src/components/community/channels/dm-sidebar.prefetch.test.ts
@@ -117,4 +117,43 @@ describe("DmSidebar navigation intent", () => {
act(() => renderer.unmount())
})
+
+ it("uses the active row shape without a duplicate unread dot", async () => {
+ const dm = {
+ id: "dm_1",
+ userId: "user_1",
+ name: "Melly",
+ discriminator: "0001",
+ avatar: "M",
+ avatarVersion: 0,
+ status: "online" as const,
+ preview: "hello",
+ unread: true,
+ }
+ let renderer!: ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(DmSidebar, {
+ dms: [dm],
+ activeDm: "dm_1",
+ onPickDm: vi.fn(),
+ onShowFriends: vi.fn(),
+ }))
+ })
+ const unreadDots = () => renderer.root.findAll((node) => (
+ node.type === "span"
+ && node.props.className === "size-2 shrink-0 rounded-full bg-primary"
+ ))
+ expect(unreadDots()).toHaveLength(0)
+
+ await act(async () => {
+ renderer.update(createElement(DmSidebar, {
+ dms: [dm],
+ activeDm: null,
+ onPickDm: vi.fn(),
+ onShowFriends: vi.fn(),
+ }))
+ })
+ expect(unreadDots()).toHaveLength(1)
+ act(() => renderer.unmount())
+ })
})
diff --git a/src/web/src/components/community/channels/dm-sidebar.tsx b/src/web/src/components/community/channels/dm-sidebar.tsx
index 9c830c511..17f3fb599 100644
--- a/src/web/src/components/community/channels/dm-sidebar.tsx
+++ b/src/web/src/components/community/channels/dm-sidebar.tsx
@@ -6,6 +6,7 @@ import { Avatar } from "../avatar"
import { Skeleton } from "@/components/ui/skeleton"
import { tid } from "@/lib/community/testids"
import type { DM } from "@/lib/community/models/people"
+import { selectUnreadPresentation } from "@/hooks/community/unread-presentation"
export const DmSidebar = memo(function DmSidebar({
dms, activeDm, blockedUserIds, loading, onPickDm, onShowFriends, onShowMachines, onShowBots,
@@ -84,6 +85,11 @@ export const DmSidebar = memo(function DmSidebar({
{dms.map((d) => {
const active = d.id === activeDm
const isBlocked = blockedUserIds?.has(d.userId)
+ const unread = selectUnreadPresentation({
+ accountUnread: d.unread === true,
+ active,
+ muted: isBlocked,
+ })
return (
<button
key={d.id}
@@ -102,7 +108,7 @@ export const DmSidebar = memo(function DmSidebar({
<div className="truncate text-xs leading-tight text-muted-foreground">{d.preview}</div>
</div>
{isBlocked && <Ban className="size-4 shrink-0 text-destructive" />}
- {!isBlocked && d.unread && <span className="size-2 shrink-0 rounded-full bg-primary" />}
+ {unread.showDot && <span className="size-2 shrink-0 rounded-full bg-primary" />}
</button>
)
})}
diff --git a/src/web/src/components/community/channels/sortable-channel.tsx b/src/web/src/components/community/channels/sortable-channel.tsx
index 136edaab9..09995114f 100644
--- a/src/web/src/components/community/channels/sortable-channel.tsx
+++ b/src/web/src/components/community/channels/sortable-channel.tsx
@@ -10,6 +10,7 @@ import { ConfirmDialog } from "@/components/ui/confirm-dialog"
import { DropLine } from "../drop-line"
import { tid } from "@/lib/community/testids"
import type { Channel } from "@/lib/community/models/navigation"
+import { selectUnreadPresentation } from "@/hooks/community/unread-presentation"
// True when the row has at least one right-click action. With none, we skip the
// ContextMenu wrapper entirely so a non-manager doesn't get an empty popover strip.
@@ -52,6 +53,11 @@ export function SortableChannel({ ch, active, onClick, onPrefetch, onEdit, onDel
const style = { transform: CSS.Transform.toString(transform), transition, opacity: isDragging ? 0.4 : 1, zIndex: isDragging ? 10 : undefined }
const showLine = isOver && !isDragging
const lineSide: "top" | "bottom" = activeIndex !== -1 && activeIndex < index ? "bottom" : "top"
+ const unread = selectUnreadPresentation({
+ accountUnread: ch.unread,
+ active,
+ muted: ch.muted === true,
+ })
const row = (
<div
ref={setNodeRef}
@@ -69,7 +75,7 @@ export function SortableChannel({ ch, active, onClick, onPrefetch, onEdit, onDel
? "bg-sidebar-accent text-foreground"
: ch.muted
? "text-muted-foreground/50 hover:bg-sidebar-accent/60 hover:text-muted-foreground"
- : ch.unread
+ : unread.emphasize
? "text-foreground hover:bg-sidebar-accent/60"
: "text-muted-foreground hover:bg-sidebar-accent/60 hover:text-foreground",
].join(" ")}
@@ -81,7 +87,7 @@ export function SortableChannel({ ch, active, onClick, onPrefetch, onEdit, onDel
<span className="truncate font-semibold">{ch.name}</span>
{ch.muted ? (
<BellOff className="ml-auto size-4 shrink-0 opacity-70" />
- ) : ch.unread && !active ? (
+ ) : unread.showDot ? (
<span className="ml-auto size-2 rounded-full bg-primary" />
) : null}
</div>
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 b0c80e796..af7063985 100644
--- a/src/web/src/components/community/shell/community-inbox-popover.tsx
+++ b/src/web/src/components/community/shell/community-inbox-popover.tsx
@@ -16,6 +16,7 @@ import {
inboxThreadRowTarget,
type InboxRowTarget,
} from "@/hooks/community/inbox-read-reservation"
+import { selectUnreadPresentation } from "@/hooks/community/unread-presentation"
import { tid } from "@/lib/community/testids"
import type { CommunityProfile } from "@/lib/community/models/people"
import { useProfilesByUserId } from "@/stores/community/ws"
@@ -386,6 +387,12 @@ export function InboxPopover({
const profilesByUserId = useProfilesByUserId()
const hasUnreads = hasProjectedUnreads ?? (unreads.length > 0 || unreadDms.length > 0)
const hasMentions = hasProjectedMentions ?? mentions.length > 0
+ const showUnreadDot = selectUnreadPresentation({
+ accountUnread: hasUnreads,
+ }).showDot
+ const showMentionDot = selectUnreadPresentation({
+ accountUnread: hasMentions,
+ }).showDot
const hasAnything = hasUnreads || hasMentions
return (
<Tabs
@@ -415,13 +422,13 @@ export function InboxPopover({
<TabsTrigger value="unreads">
<span className="inline-flex items-center gap-2">
Unreads
- {hasUnreads && <span className="size-1.5 rounded-full bg-primary" />}
+ {showUnreadDot && <span className="size-1.5 rounded-full bg-primary" />}
</span>
</TabsTrigger>
<TabsTrigger value="mentions">
<span className="inline-flex items-center gap-2">
Mentions
- {hasMentions && <span className="size-1.5 rounded-full bg-primary" />}
+ {showMentionDot && <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/community-inbox-surface.tsx b/src/web/src/components/community/shell/community-inbox-surface.tsx
index ca10e5c8d..5dc577f80 100644
--- a/src/web/src/components/community/shell/community-inbox-surface.tsx
+++ b/src/web/src/components/community/shell/community-inbox-surface.tsx
@@ -15,6 +15,7 @@ import type { Breakpoint } from "@/hooks/use-mobile"
import { tid } from "@/lib/community/testids"
import { cn } from "@/lib/utils"
import { COMMUNITY_USER_BAR_HEIGHT_CSS } from "./shell-frame-geometry"
+import { selectUnreadPresentation } from "@/hooks/community/unread-presentation"
type Props = {
breakpoint: Breakpoint
@@ -37,6 +38,7 @@ export function CommunityInboxSurface({
}: Props) {
const triggerRef = useRef<HTMLButtonElement>(null)
const mobile = breakpoint === "mobile"
+ const unread = selectUnreadPresentation({ accountUnread: hasUnread === true })
return (
<Popover
@@ -74,14 +76,14 @@ export function CommunityInboxSurface({
{mobile ? (
<span className="relative grid size-4 place-items-center">
<Inbox className="size-4" />
- {hasUnread && (
+ {unread.showDot && (
<span className="absolute -right-1 -top-1 size-2 rounded-full bg-primary" />
)}
</span>
) : (
<>
<Inbox className="size-4" />
- {hasUnread && (
+ {unread.showDot && (
<span className="absolute right-1 top-1 size-2 rounded-full bg-primary" />
)}
</>
diff --git a/src/web/src/components/community/shell/rail-indicator.tsx b/src/web/src/components/community/shell/rail-indicator.tsx
index 400e97236..a1edc1310 100644
--- a/src/web/src/components/community/shell/rail-indicator.tsx
+++ b/src/web/src/components/community/shell/rail-indicator.tsx
@@ -1,3 +1,5 @@
+import { selectUnreadPresentation } from "@/hooks/community/unread-presentation"
+
export function RailIndicator({
active,
unread,
@@ -7,14 +9,18 @@ export function RailIndicator({
unread?: boolean
testId?: string
}) {
+ const presentation = selectUnreadPresentation({
+ accountUnread: unread === true,
+ active: active === true,
+ })
return (
<span
data-testid={testId}
className={[
"absolute left-0 top-1/2 w-1 -translate-y-1/2 rounded-r-full bg-foreground transition-all duration-150",
- active
+ presentation.active
? "h-10"
- : `${unread ? "h-2.5" : "h-0"} group-hover:h-5 group-focus-within:h-5`,
+ : `${presentation.showDot ? "h-2.5" : "h-0"} group-hover:h-5 group-focus-within:h-5`,
].join(" ")}
/>
)
diff --git a/src/web/src/hooks/community/account-unread-projection.test.ts b/src/web/src/hooks/community/account-unread-projection.test.ts
index ce03c15f0..22e8ae9f8 100644
--- a/src/web/src/hooks/community/account-unread-projection.test.ts
+++ b/src/web/src/hooks/community/account-unread-projection.test.ts
@@ -409,6 +409,74 @@ describe("AccountUnreadProjection", () => {
}])).toBe(3)
})
+ it("excludes only the reserved channel boundary and preserves later arrivals", () => {
+ const projection = new AccountUnreadProjection("u1")
+ const exclusion = { channelId: "c1", throughSeq: 2 }
+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 2 })
+
+ expect(projection.projectUnread(
+ "servers",
+ "c1",
+ true,
+ 2,
+ "channels",
+ exclusion,
+ )).toBe(false)
+ expect(projection.projectServerUnread("s1", [{
+ channelId: "c1",
+ lastUnreadSeq: 2,
+ }], false, exclusion)).toBe(false)
+ expect(projection.projectServerChannelUnread("s1", "c1", [{
+ channelId: "c1",
+ lastUnreadSeq: 2,
+ }], false, exclusion)).toBe(false)
+ expect(projection.hasPending("servers", "channels", exclusion)).toBe(false)
+
+ projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 3 })
+ expect(projection.projectUnread(
+ "servers",
+ "c1",
+ true,
+ 2,
+ "channels",
+ exclusion,
+ )).toBe(true)
+ expect(projection.projectServerUnread("s1", [{
+ channelId: "c1",
+ lastUnreadSeq: 2,
+ }], false, exclusion)).toBe(true)
+ expect(projection.hasPending("servers", "channels", exclusion)).toBe(true)
+ })
+
+ it("keeps unrelated aggregate sources visible during an exact reservation", () => {
+ const projection = new AccountUnreadProjection("u1")
+ const exclusion = { channelId: "post", throughSeq: 4 }
+ projection.recordArrival({
+ channelId: "post",
+ railChannelId: "forum",
+ serverId: "s1",
+ seq: 4,
+ })
+ projection.recordArrival({ channelId: "sibling", serverId: "s1", seq: 1 })
+
+ expect(projection.projectServerUnread("s1", [], false, exclusion)).toBe(true)
+ expect(projection.projectServerChannelUnread(
+ "s1",
+ "forum",
+ [],
+ false,
+ exclusion,
+ )).toBe(false)
+ expect(projection.projectForumParentUnread(
+ "s1",
+ "forum",
+ false,
+ null,
+ new Set(),
+ exclusion,
+ )).toBe(false)
+ })
+
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 })
diff --git a/src/web/src/hooks/community/account-unread-projection.ts b/src/web/src/hooks/community/account-unread-projection.ts
index dbd0f69b9..9296cb3db 100644
--- a/src/web/src/hooks/community/account-unread-projection.ts
+++ b/src/web/src/hooks/community/account-unread-projection.ts
@@ -27,6 +27,11 @@ export type AccountUnreadSource = {
lastMentionSeq?: number | null
}
+export type AccountUnreadPresentationExclusion = {
+ channelId: string
+ throughSeq?: number
+}
+
export type AccountUnreadLegacySource = {
family: AccountUnreadFamily
channelId: string
@@ -112,6 +117,16 @@ function sentinelKey(family: AccountUnreadFamily, domain: AccountUnreadDomain) {
return `${sentinelFamily(family)}\u0000${domain}`
}
+function excludesUnread(
+ exclusion: AccountUnreadPresentationExclusion | null | undefined,
+ channelId: string,
+ seq?: number | null,
+) {
+ if (!exclusion || exclusion.channelId !== channelId) return false
+ if (exclusion.throughSeq === undefined) return true
+ return seq !== undefined && seq !== null && seq <= exclusion.throughSeq
+}
+
/**
* Account-wide optimistic unread ledger. It deliberately owns no fetches,
* timers, cache writes, or route transitions: raw TanStack resources remain
@@ -409,23 +424,27 @@ export class AccountUnreadProjection {
rawUnread: boolean,
sourceSeq?: number | null,
domain: AccountUnreadDomain = familyDomain(family),
+ exclusion?: AccountUnreadPresentationExclusion | null,
) {
const fence = this.markAll.get(domain)
const read = this.effectiveReadSeq(channelId)
const rawVisible = rawUnread
&& !(sourceSeq && read >= sourceSeq)
&& !fence
+ && !excludesUnread(exclusion, channelId, sourceSeq)
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 (excludesUnread(exclusion, channelId, arrival.seq)) continue
if (!fence || arrival.ordinal > fence.ordinal) return true
}
const sticky = this.sticky.get(channelId)
const pending = sticky?.families.get(family)
if (pending) {
+ if (excludesUnread(exclusion, channelId)) return false
if (!fence || pending.ordinal > fence.ordinal) return true
}
return false
@@ -458,12 +477,17 @@ export class AccountUnreadProjection {
serverId: string,
sources: readonly AccountUnreadSource[],
rawUnread = false,
+ exclusion?: AccountUnreadPresentationExclusion | null,
) {
- if (sources.some((source) => this.projectUnread(
- "servers",
- source.channelId,
- true,
- source.lastUnreadSeq,
+ if (sources.some((source) => (
+ this.projectUnread(
+ "servers",
+ source.channelId,
+ true,
+ source.lastUnreadSeq,
+ "channels",
+ exclusion,
+ )
))) return true
if (rawUnread && sources.length === 0 && !this.markAll.get("channels")) return true
const sentinel = this.sentinels.get(sentinelKey("servers", "channels"))
@@ -472,13 +496,27 @@ export class AccountUnreadProjection {
for (const arrival of this.exact.values()) {
if (
arrival.serverId === serverId
- && this.projectUnread("servers", arrival.channelId, false)
+ && this.projectUnread(
+ "servers",
+ arrival.channelId,
+ false,
+ undefined,
+ "channels",
+ exclusion,
+ )
) return true
}
for (const unknown of this.sticky.values()) {
if (
unknown.serverId === serverId
- && this.projectUnread("servers", unknown.channelId, false)
+ && this.projectUnread(
+ "servers",
+ unknown.channelId,
+ false,
+ undefined,
+ "channels",
+ exclusion,
+ )
) return true
}
return false
@@ -489,13 +527,18 @@ export class AccountUnreadProjection {
channelId: string,
sources: readonly AccountUnreadSource[],
rawUnread = false,
+ exclusion?: AccountUnreadPresentationExclusion | null,
) {
const family = `server-detail:${serverId}` as const
- if (sources.some((source) => this.projectUnread(
- family,
- source.channelId,
- true,
- source.lastUnreadSeq,
+ if (sources.some((source) => (
+ this.projectUnread(
+ family,
+ source.channelId,
+ true,
+ source.lastUnreadSeq,
+ "channels",
+ exclusion,
+ )
))) return true
if (rawUnread && sources.length === 0 && !this.markAll.get("channels")) return true
const sentinel = this.sentinels.get(sentinelKey(family, "channels"))
@@ -505,14 +548,28 @@ export class AccountUnreadProjection {
if (
arrival.serverId === serverId
&& (arrival.channelId === channelId || arrival.railChannelId === channelId)
- && this.projectUnread(family, arrival.channelId, false)
+ && this.projectUnread(
+ family,
+ arrival.channelId,
+ false,
+ undefined,
+ "channels",
+ exclusion,
+ )
) 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)
+ && this.projectUnread(
+ family,
+ unknown.channelId,
+ false,
+ undefined,
+ "channels",
+ exclusion,
+ )
) return true
}
return false
@@ -524,15 +581,32 @@ export class AccountUnreadProjection {
rawBaseUnread: boolean,
sourceSeq: number | null | undefined,
renderedChildIds: ReadonlySet<string>,
+ exclusion?: AccountUnreadPresentationExclusion | null,
) {
const family = `server-detail:${serverId}` as const
- if (this.projectUnread(family, parentChannelId, rawBaseUnread, sourceSeq)) return true
+ if (
+ this.projectUnread(
+ family,
+ parentChannelId,
+ rawBaseUnread,
+ sourceSeq,
+ "channels",
+ exclusion,
+ )
+ ) 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)
+ && this.projectUnread(
+ family,
+ arrival.channelId,
+ false,
+ undefined,
+ "channels",
+ exclusion,
+ )
) return true
}
for (const unknown of this.sticky.values()) {
@@ -540,7 +614,14 @@ export class AccountUnreadProjection {
unknown.serverId === serverId
&& unknown.railChannelId === parentChannelId
&& !renderedChildIds.has(unknown.channelId)
- && this.projectUnread(family, unknown.channelId, false)
+ && this.projectUnread(
+ family,
+ unknown.channelId,
+ false,
+ undefined,
+ "channels",
+ exclusion,
+ )
) return true
}
return false
@@ -561,7 +642,11 @@ export class AccountUnreadProjection {
), 0)
}
- hasPending(family?: AccountUnreadFamily, domain?: AccountUnreadDomain) {
+ hasPending(
+ family?: AccountUnreadFamily,
+ domain?: AccountUnreadDomain,
+ exclusion?: AccountUnreadPresentationExclusion | null,
+ ) {
if (family && domain) {
const sentinel = this.sentinels.get(sentinelKey(family, domain))
const fence = this.markAll.get(domain)
@@ -578,6 +663,7 @@ export class AccountUnreadProjection {
}
for (const arrival of this.exact.values()) {
if (family && !arrival.families.has(family)) continue
+ if (excludesUnread(exclusion, arrival.channelId, arrival.seq)) continue
const arrivalDomain = family === "inbox-mentions" || arrival.isMention && domain === "mentions"
? "mentions"
: arrival.serverId ? "channels" : "dms"
@@ -586,6 +672,7 @@ export class AccountUnreadProjection {
if (!fence || arrival.ordinal > fence.ordinal) return true
}
for (const unknown of this.sticky.values()) {
+ if (excludesUnread(exclusion, unknown.channelId)) continue
for (const [pendingFamily, pending] of unknown.families) {
if (family && pendingFamily !== family) continue
const pendingDomain = arrivalDomain(pendingFamily, unknown.serverId)
diff --git a/src/web/src/hooks/community/inbox-read-reservation.test.ts b/src/web/src/hooks/community/inbox-read-reservation.test.ts
index 294ba71f6..47b9c075c 100644
--- a/src/web/src/hooks/community/inbox-read-reservation.test.ts
+++ b/src/web/src/hooks/community/inbox-read-reservation.test.ts
@@ -8,7 +8,10 @@ import {
completeThreadOpenerReservationHandoff,
disposeInboxReadReservation,
getThreadOpenerReservationHandoff,
+ inboxChannelRowTarget,
+ inboxDmRowTarget,
inboxReadCandidateFingerprint,
+ inboxThreadRowTarget,
publishInboxProjectionGenerationTerminal,
promoteInboxReadReservation,
registerInboxProjectionTicket,
@@ -71,6 +74,47 @@ describe("inbox read reservation", () => {
queryClient = client()
})
+ it("carries the exact unread sequence boundary on reservable row targets", () => {
+ const server = {
+ serverId: "server",
+ serverName: "Server",
+ channels: [{
+ channelId: "forum",
+ channelName: "Forum",
+ lastMessageAt: "2026-09-02T00:00:00.000Z",
+ lastUnreadSeq: 4,
+ hasDirectUnread: true,
+ mentionCount: 0,
+ children: [{
+ channelId: "child",
+ channelName: "Child",
+ lastMessageAt: "2026-09-02T00:00:00.000Z",
+ lastUnreadSeq: 7,
+ mentionCount: 0,
+ }],
+ }],
+ }
+ const dm = {
+ channelId: "dm",
+ otherUserId: "peer",
+ otherUserName: "Peer",
+ otherUserDiscriminator: "0001",
+ otherUserAvatar: "P",
+ otherUserAvatarVersion: 0,
+ lastMessageAt: "2026-09-02T00:00:00.000Z",
+ lastUnreadSeq: 9,
+ }
+
+ expect(inboxChannelRowTarget(server, server.channels[0]!))
+ .toMatchObject({ reservedThroughSeq: 4 })
+ expect(inboxThreadRowTarget(
+ server,
+ server.channels[0]!,
+ server.channels[0]!.children[0]!,
+ )).toMatchObject({ reservedThroughSeq: 7 })
+ expect(inboxDmRowTarget(dm)).toMatchObject({ reservedThroughSeq: 9 })
+ })
+
it("passes unrelated responses through and holds a focused response unchanged", async () => {
const seen = vi.fn()
registerInboxReadReservationSurface(queryClient, "focused", seen)
diff --git a/src/web/src/hooks/community/inbox-read-reservation.ts b/src/web/src/hooks/community/inbox-read-reservation.ts
index a27b7c490..3d83061d2 100644
--- a/src/web/src/hooks/community/inbox-read-reservation.ts
+++ b/src/web/src/hooks/community/inbox-read-reservation.ts
@@ -41,6 +41,7 @@ export type InboxRowTarget =
confirmationChannelId: string
serverId: string
channelId: string
+ reservedThroughSeq?: number
}
| {
kind: "thread"
@@ -50,6 +51,7 @@ export type InboxRowTarget =
serverId: string
parentChannelId: string
childChannelId: string
+ reservedThroughSeq?: number
}
| {
kind: "dm"
@@ -57,6 +59,7 @@ export type InboxRowTarget =
fingerprint: string
confirmationChannelId: string
channelId: string
+ reservedThroughSeq?: number
}
| {
kind: "mention"
@@ -235,6 +238,9 @@ export function inboxChannelRowTarget(
confirmationChannelId: channel.channelId,
serverId: server.serverId,
channelId: channel.channelId,
+ ...(channel.lastUnreadSeq !== undefined
+ ? { reservedThroughSeq: channel.lastUnreadSeq }
+ : {}),
}
}
@@ -265,6 +271,9 @@ export function inboxThreadRowTarget(
serverId: server.serverId,
parentChannelId,
childChannelId: child.channelId,
+ ...(child.lastUnreadSeq !== undefined
+ ? { reservedThroughSeq: child.lastUnreadSeq }
+ : {}),
}
}
@@ -279,6 +288,7 @@ export function inboxDmRowTarget(dm: UnreadDm): InboxRowTarget {
}),
confirmationChannelId: dm.channelId,
channelId: dm.channelId,
+ ...(dm.lastUnreadSeq !== undefined ? { reservedThroughSeq: dm.lastUnreadSeq } : {}),
}
}
diff --git a/src/web/src/hooks/community/unread-presentation.test.ts b/src/web/src/hooks/community/unread-presentation.test.ts
new file mode 100644
index 000000000..0ace9b5db
--- /dev/null
+++ b/src/web/src/hooks/community/unread-presentation.test.ts
@@ -0,0 +1,126 @@
+import { describe, expect, it } from "vitest"
+import type { InboxRowTarget } from "./inbox-read-reservation"
+import {
+ isInboxTargetReserved,
+ reservedUnreadExclusion,
+ selectUnreadPresentation,
+} from "./unread-presentation"
+
+describe("unread presentation", () => {
+ it("keeps one diagnostic decision snapshot for account, reservation, active, and mute policy", () => {
+ expect({
+ unread: selectUnreadPresentation({ accountUnread: true }),
+ active: selectUnreadPresentation({ accountUnread: true, active: true }),
+ muted: selectUnreadPresentation({ accountUnread: true, muted: true }),
+ reserved: selectUnreadPresentation({ accountUnread: true, reserved: true }),
+ }).toMatchInlineSnapshot(`
+ {
+ "active": {
+ "accountUnread": true,
+ "active": true,
+ "effectiveUnread": true,
+ "emphasize": false,
+ "muted": false,
+ "reserved": false,
+ "showDot": false,
+ "state": "active",
+ },
+ "muted": {
+ "accountUnread": true,
+ "active": false,
+ "effectiveUnread": true,
+ "emphasize": false,
+ "muted": true,
+ "reserved": false,
+ "showDot": false,
+ "state": "muted",
+ },
+ "reserved": {
+ "accountUnread": true,
+ "active": false,
+ "effectiveUnread": false,
+ "emphasize": false,
+ "muted": false,
+ "reserved": true,
+ "showDot": false,
+ "state": "reserved",
+ },
+ "unread": {
+ "accountUnread": true,
+ "active": false,
+ "effectiveUnread": true,
+ "emphasize": true,
+ "muted": false,
+ "reserved": false,
+ "showDot": true,
+ "state": "unread",
+ },
+ }
+ `)
+ })
+
+ it("maps only unread Inbox targets into their account domains", () => {
+ const channel = {
+ kind: "channel-direct",
+ identity: "channel",
+ fingerprint: "channel-v1",
+ confirmationChannelId: "channel-1",
+ serverId: "server-1",
+ channelId: "channel-1",
+ } satisfies InboxRowTarget
+ const thread = {
+ kind: "thread",
+ identity: "thread",
+ fingerprint: "thread-v1",
+ confirmationChannelId: "thread-1",
+ serverId: "server-1",
+ parentChannelId: "forum-1",
+ childChannelId: "thread-1",
+ } satisfies InboxRowTarget
+ const dm = {
+ kind: "dm",
+ identity: "dm",
+ fingerprint: "dm-v1",
+ confirmationChannelId: "dm-1",
+ channelId: "dm-1",
+ } satisfies InboxRowTarget
+ const mention = {
+ kind: "mention",
+ identity: "mention",
+ fingerprint: "mention-v1",
+ confirmationChannelId: "channel-1",
+ mentionId: "mention-1",
+ } satisfies InboxRowTarget
+
+ expect(reservedUnreadExclusion(channel, "channels")).toEqual({
+ channelId: "channel-1",
+ })
+ expect(reservedUnreadExclusion(thread, "channels")).toEqual({
+ channelId: "thread-1",
+ })
+ expect(reservedUnreadExclusion(dm, "dms")).toEqual({ channelId: "dm-1" })
+ expect(reservedUnreadExclusion({ ...channel, reservedThroughSeq: 4 }, "channels"))
+ .toEqual({ channelId: "channel-1", throughSeq: 4 })
+ expect(reservedUnreadExclusion({ ...thread, reservedThroughSeq: 7 }, "channels"))
+ .toEqual({ channelId: "thread-1", throughSeq: 7 })
+ expect(reservedUnreadExclusion({ ...dm, reservedThroughSeq: 9 }, "dms"))
+ .toEqual({ channelId: "dm-1", throughSeq: 9 })
+ expect(reservedUnreadExclusion(channel, "dms")).toBeNull()
+ expect(reservedUnreadExclusion(dm, "channels")).toBeNull()
+ expect(reservedUnreadExclusion(mention, "channels")).toBeNull()
+ })
+
+ it("requires exact identity and fingerprint for row reservation", () => {
+ const target = {
+ kind: "dm",
+ identity: "dm-1",
+ fingerprint: "v1",
+ confirmationChannelId: "dm-1",
+ channelId: "dm-1",
+ } satisfies InboxRowTarget
+ expect(isInboxTargetReserved(target, target)).toBe(true)
+ expect(isInboxTargetReserved(target, { ...target, fingerprint: "v2" })).toBe(false)
+ expect(isInboxTargetReserved(target, { ...target, identity: "dm-2" })).toBe(false)
+ expect(isInboxTargetReserved(target, null)).toBe(false)
+ })
+})
diff --git a/src/web/src/hooks/community/unread-presentation.ts b/src/web/src/hooks/community/unread-presentation.ts
new file mode 100644
index 000000000..50c506743
--- /dev/null
+++ b/src/web/src/hooks/community/unread-presentation.ts
@@ -0,0 +1,95 @@
+import type { InboxRowTarget } from "./inbox-read-reservation"
+
+export type UnreadPresentationInput = {
+ accountUnread: boolean
+ reserved?: boolean
+ active?: boolean
+ muted?: boolean
+}
+
+export type UnreadPresentationDecision = {
+ accountUnread: boolean
+ reserved: boolean
+ active: boolean
+ muted: boolean
+ effectiveUnread: boolean
+ emphasize: boolean
+ showDot: boolean
+ state: "idle" | "unread" | "active" | "muted" | "reserved"
+}
+
+export function selectUnreadPresentation({
+ accountUnread,
+ reserved = false,
+ active = false,
+ muted = false,
+}: UnreadPresentationInput): UnreadPresentationDecision {
+ const effectiveUnread = accountUnread && !reserved
+ return {
+ accountUnread,
+ reserved,
+ active,
+ muted,
+ effectiveUnread,
+ emphasize: effectiveUnread && !active && !muted,
+ showDot: effectiveUnread && !active && !muted,
+ state: reserved && accountUnread
+ ? "reserved"
+ : active
+ ? "active"
+ : muted
+ ? "muted"
+ : effectiveUnread
+ ? "unread"
+ : "idle",
+ }
+}
+
+export type UnreadPresentationExclusion = {
+ channelId: string
+ throughSeq?: number
+}
+
+export function reservedUnreadExclusion(
+ target: InboxRowTarget | null,
+ domain: "channels" | "dms",
+): UnreadPresentationExclusion | null {
+ if (!target || target.kind === "mention") return null
+ if (domain === "dms") {
+ return target.kind === "dm"
+ ? {
+ channelId: target.channelId,
+ ...(target.reservedThroughSeq !== undefined
+ ? { throughSeq: target.reservedThroughSeq }
+ : {}),
+ }
+ : null
+ }
+ if (target.kind === "channel-direct") {
+ return {
+ channelId: target.channelId,
+ ...(target.reservedThroughSeq !== undefined
+ ? { throughSeq: target.reservedThroughSeq }
+ : {}),
+ }
+ }
+ if (target.kind === "thread") {
+ return {
+ channelId: target.childChannelId,
+ ...(target.reservedThroughSeq !== undefined
+ ? { throughSeq: target.reservedThroughSeq }
+ : {}),
+ }
+ }
+ return null
+}
+
+export function isInboxTargetReserved(
+ target: InboxRowTarget | null,
+ candidate: InboxRowTarget | null,
+) {
+ return !!target
+ && !!candidate
+ && target.identity === candidate.identity
+ && target.fingerprint === candidate.fingerprint
+}
diff --git a/src/web/src/hooks/community/use-dms.test.ts b/src/web/src/hooks/community/use-dms.test.ts
index e34c1c62a..86b475861 100644
--- a/src/web/src/hooks/community/use-dms.test.ts
+++ b/src/web/src/hooks/community/use-dms.test.ts
@@ -5,6 +5,7 @@ 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"
+import { inboxDmRowTarget } from "./inbox-read-reservation"
const apiFetchMock = vi.fn()
vi.mock("@/lib/api/client", () => ({
@@ -164,6 +165,67 @@ describe("useDms / dmsQueryFn", () => {
await act(async () => renderer.unmount())
})
+ it("projects and rolls back the exact Inbox DM reservation without hiding a sibling", async () => {
+ const conversations = [
+ {
+ id: "dm_1", userId: "u_1", name: "Alice", discriminator: "0001",
+ avatar: "a", avatarVersion: 1, status: "offline", preview: "one",
+ unread: true, lastUnreadSeq: 2,
+ },
+ {
+ id: "dm_2", userId: "u_2", name: "Bob", discriminator: "0002",
+ avatar: "b", avatarVersion: 1, status: "offline", preview: "two",
+ unread: true, lastUnreadSeq: 3,
+ },
+ ] as DM[]
+ const inboxDm = {
+ channelId: "dm_1",
+ otherUserId: "u_1",
+ otherUserName: "Alice",
+ otherUserDiscriminator: "0001",
+ otherUserAvatar: "a",
+ otherUserAvatarVersion: 1,
+ lastMessageAt: "2026-09-02T00:00:00.000Z",
+ lastUnreadSeq: 2,
+ }
+ const { useDms } = await import("./use-dms")
+ const { useInboxAutoCollapse } = await import("./use-inbox-auto-collapse")
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ qc.setQueryData(communityKeys.dms(), { conversations })
+ let latest: ReturnType<typeof useDms> | undefined
+ let collapse: ReturnType<typeof useInboxAutoCollapse> | undefined
+ function Harness() {
+ latest = useDms()
+ collapse = useInboxAutoCollapse({
+ queryClient: qc,
+ publishedHref: "/c/me",
+ navigationPending: false,
+ pendingHref: null,
+ })
+ return null
+ }
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(
+ QueryClientProvider,
+ { client: qc },
+ React.createElement(Harness),
+ ))
+ })
+
+ let epoch = 0
+ await act(async () => {
+ epoch = collapse!.beginProjection(inboxDmRowTarget(inboxDm), "/c/me/dm_1")
+ })
+ expect(latest?.dms.map((dm) => dm.unread)).toEqual([false, true])
+
+ await act(async () => {
+ collapse!.rollbackProjection(epoch)
+ })
+ expect(latest?.dms.map((dm) => dm.unread)).toEqual([true, true])
+ 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")
diff --git a/src/web/src/hooks/community/use-dms.ts b/src/web/src/hooks/community/use-dms.ts
index 855a8ce60..2fba38556 100644
--- a/src/web/src/hooks/community/use-dms.ts
+++ b/src/web/src/hooks/community/use-dms.ts
@@ -11,6 +11,11 @@ import { useEffect, useMemo, useSyncExternalStore } from "react"
import { useProfilesByUserId } from "@/stores/community/ws"
import { readCommunityProfile } from "@/lib/community/profile-read"
import { getActiveAccountUnreadProjection } from "./account-unread-projection"
+import { useInboxProjectionTarget } from "./use-inbox-auto-collapse"
+import {
+ reservedUnreadExclusion,
+ selectUnreadPresentation,
+} from "./unread-presentation"
/**
* Fetches the DM conversation sidebar list.
@@ -42,6 +47,11 @@ export function useDms(): UseQueryResult<DmsResponse> & { dms: DM[] } {
unreadProjection.getSnapshot,
unreadProjection.getSnapshot,
)
+ const reservationTarget = useInboxProjectionTarget(queryClient)
+ const unreadExclusion = useMemo(
+ () => reservedUnreadExclusion(reservationTarget, "dms"),
+ [reservationTarget],
+ )
const query = useQuery({
queryKey: communityKeys.dms(),
queryFn: dmsQueryFn,
@@ -74,12 +84,16 @@ export function useDms(): UseQueryResult<DmsResponse> & { dms: DM[] } {
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,
- )
+ const unread = selectUnreadPresentation({
+ accountUnread: unreadProjection.projectUnread(
+ "dms",
+ dm.id,
+ dm.unread === true,
+ dm.lastUnreadSeq,
+ "dms",
+ unreadExclusion,
+ ),
+ }).effectiveUnread
return {
...dm,
name: profile.name,
@@ -90,7 +104,7 @@ export function useDms(): UseQueryResult<DmsResponse> & { dms: DM[] } {
unread,
}
})
- }, [profilesByUserId, query.data?.conversations, unreadProjection, unreadVersion])
+ }, [profilesByUserId, query.data?.conversations, unreadExclusion, unreadProjection, unreadVersion])
return {
...query,
dms,
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 041dd58e0..54c1fcfdb 100644
--- a/src/web/src/hooks/community/use-forum-sidebar-threads.ts
+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.ts
@@ -8,6 +8,11 @@ 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"
+import { useInboxProjectionTarget } from "./use-inbox-auto-collapse"
+import {
+ reservedUnreadExclusion,
+ selectUnreadPresentation,
+} from "./unread-presentation"
export type ForumSidebarThread = {
id: string
@@ -980,6 +985,11 @@ export function useForumSidebarThreads(
unreadProjection.getSnapshot,
unreadProjection.getSnapshot,
)
+ const reservationTarget = useInboxProjectionTarget(queryClient)
+ const unreadExclusion = useMemo(
+ () => reservedUnreadExclusion(reservationTarget, "channels"),
+ [reservationTarget],
+ )
const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)
const previousRetainId = useRef(retainId)
// Observe (without fetching) the already-canonical ServerDetail cache so a
@@ -1072,12 +1082,16 @@ export function useForumSidebarThreads(
)
const threads = raw.threads.map((thread) => {
const source = sourceByChannel.get(thread.id)
- const unread = unreadProjection.projectUnread(
- family,
- thread.id,
- thread.unread,
- source?.lastUnreadSeq,
- )
+ const unread = selectUnreadPresentation({
+ accountUnread: unreadProjection.projectUnread(
+ family,
+ thread.id,
+ thread.unread,
+ source?.lastUnreadSeq,
+ "channels",
+ unreadExclusion,
+ ),
+ }).effectiveUnread
if (unread === thread.unread) return thread
return { ...thread, unread }
})
@@ -1093,6 +1107,7 @@ export function useForumSidebarThreads(
state.baseUnread || raw.parentUnread[parentId] === true,
sourceByChannel.get(parentId)?.lastUnreadSeq,
renderedChildIds,
+ unreadExclusion,
)
if (unread === raw.parentUnread[parentId]) continue
if (!parentChanged) parentUnread = { ...raw.parentUnread }
@@ -1110,6 +1125,7 @@ export function useForumSidebarThreads(
retainedQuery.data,
serverDetailQuery.data?.forumUnreadState,
serverDetailQuery.data?.unreadSources,
+ unreadExclusion,
serverId,
unreadProjection,
unreadVersion,
diff --git a/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts b/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts
index 85cc9c2e9..0bf6a8a59 100644
--- a/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts
+++ b/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts
@@ -1,11 +1,15 @@
import { createElement } from "react"
+import { renderToStaticMarkup } from "react-dom/server"
import TestRenderer, { act } from "react-test-renderer"
import { beforeEach, describe, expect, it, vi } from "vitest"
import type {
InboxProjectionTerminalReceipt,
InboxRowTarget,
} from "./inbox-read-reservation"
-import { useInboxAutoCollapse } from "./use-inbox-auto-collapse"
+import {
+ useInboxAutoCollapse,
+ useInboxProjectionTarget,
+} from "./use-inbox-auto-collapse"
const mocks = vi.hoisted(() => ({
callbacks: new Map<symbol, (receipt: InboxProjectionTerminalReceipt) => void>(),
@@ -49,6 +53,17 @@ function Capture({ options, onResult }: { options: Options; onResult: (api: Api)
return null
}
+function ProjectionCapture({
+ queryClient,
+ onResult,
+}: {
+ queryClient: Options["queryClient"]
+ onResult: (target: InboxRowTarget | null) => void
+}) {
+ onResult(useInboxProjectionTarget(queryClient))
+ return null
+}
+
async function renderHook(overrides: Partial<Options> = {}) {
let current!: Api
let options = {
@@ -98,11 +113,42 @@ describe("useInboxAutoCollapse", () => {
await hook.call(() => hook.current.beginProjection(target(), "/c/channels/s1/c1"))
expect(hook.current.open).toBe(false)
+ expect(hook.current.projectionTarget).toEqual(target())
expect(hook.current.isProjected(target())).toBe(true)
expect(hook.current.isProjected(target("g2"))).toBe(false)
expect(hook.current.isProjected(target("g1", "c2"))).toBe(false)
})
+ it("publishes the current target to external subscribers and unsubscribes cleanly", async () => {
+ const queryClient = {} as Options["queryClient"]
+ let projected: InboxRowTarget | null = null
+ let subscriber!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ subscriber = TestRenderer.create(createElement(ProjectionCapture, {
+ queryClient,
+ onResult: (value) => { projected = value },
+ }))
+ })
+ const hook = await renderHook({ queryClient })
+
+ await hook.call(() => hook.current.beginProjection(target(), "/c/channels/s1/c1"))
+ expect(projected).toEqual(target())
+
+ await act(async () => subscriber.unmount())
+ await hook.call(() => hook.current.beginProjection(target("g2"), "/c/channels/s1/c1"))
+ expect(projected).toEqual(target())
+ await hook.unmount()
+ })
+
+ it("provides a stable server snapshot before any projection exists", () => {
+ let projected: InboxRowTarget | null | undefined
+ expect(renderToStaticMarkup(createElement(ProjectionCapture, {
+ queryClient: {} as Options["queryClient"],
+ onResult: (value) => { projected = value },
+ }))).toBe("")
+ expect(projected).toBeNull()
+ })
+
it("preserves a tombstone across manual close and reopen", async () => {
const hook = await renderHook()
await hook.call(() => hook.current.onOpenChange(true))
@@ -178,6 +224,7 @@ describe("useInboxAutoCollapse", () => {
await hook.call(() => { epoch = hook.current.beginProjection(target(), "/c/channels/s1/c1") })
await hook.call(() => hook.current.rollbackProjection(epoch, true))
expect(hook.current.open).toBe(true)
+ expect(hook.current.projectionTarget).toBeNull()
expect(hook.current.isProjected(target())).toBe(false)
})
diff --git a/src/web/src/hooks/community/use-inbox-auto-collapse.ts b/src/web/src/hooks/community/use-inbox-auto-collapse.ts
index d574e093f..79942d143 100644
--- a/src/web/src/hooks/community/use-inbox-auto-collapse.ts
+++ b/src/web/src/hooks/community/use-inbox-auto-collapse.ts
@@ -44,6 +44,18 @@ function projectionStoreFor(queryClient: QueryClient) {
return store
}
+export function useInboxProjectionTarget(queryClient: QueryClient) {
+ const store = projectionStoreFor(queryClient)
+ return useSyncExternalStore(
+ (listener) => {
+ store.listeners.add(listener)
+ return () => store.listeners.delete(listener)
+ },
+ () => store.current?.target ?? null,
+ () => store.current?.target ?? null,
+ )
+}
+
function publishProjection(store: ProjectionStore, lease: ProjectionLease | null) {
store.current = lease
for (const listener of store.listeners) listener()
@@ -83,6 +95,7 @@ export function useInboxAutoCollapse({
() => store.current,
() => store.current,
)
+ const projectionTarget = projection?.target ?? null
const openRef = useRef(open)
const previousPublishedHrefRef = useRef(publishedHref)
@@ -165,10 +178,10 @@ export function useInboxAutoCollapse({
}, [])
const isProjected = useCallback((target: InboxRowTarget | null) => {
- if (!target || !projection) return false
- return projection.target.identity === target.identity
- && projection.target.fingerprint === target.fingerprint
- }, [projection])
+ if (!target || !projectionTarget) return false
+ return projectionTarget.identity === target.identity
+ && projectionTarget.fingerprint === target.fingerprint
+ }, [projectionTarget])
const isLatestProjection = useCallback((epoch: number) => (
store.current?.epoch === epoch
@@ -195,6 +208,7 @@ export function useInboxAutoCollapse({
return {
open,
+ projectionTarget,
onOpenChange,
beginProjection,
markProjectionSubmitted,
diff --git a/src/web/src/hooks/community/use-inbox.test.ts b/src/web/src/hooks/community/use-inbox.test.ts
index cc2078028..0217daf32 100644
--- a/src/web/src/hooks/community/use-inbox.test.ts
+++ b/src/web/src/hooks/community/use-inbox.test.ts
@@ -5,6 +5,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
import {
disposeInboxReadReservation,
+ inboxChannelRowTarget,
registerInboxReadReservationSurface,
takeInboxReadReservationNegative,
} from "./inbox-read-reservation"
@@ -181,6 +182,67 @@ describe("useInboxUnreads / inboxUnreadsQueryFn", () => {
await act(async () => renderer.unmount())
})
+ it("projects one Inbox reservation into the feed aggregate and restores it on rollback", async () => {
+ const channel = {
+ channelId: "reserved",
+ channelName: "Reserved",
+ lastMessageAt: "2026-09-02T00:00:00.000Z",
+ lastUnreadSeq: 4,
+ mentionCount: 0,
+ hasDirectUnread: true,
+ children: [],
+ }
+ const server = {
+ serverId: "s1",
+ serverName: "One",
+ channels: [channel],
+ }
+ const data = { servers: [server], dms: [], truncated: false }
+ apiFetchMock.mockResolvedValue(data)
+ const { useInboxUnreads } = await import("./use-inbox")
+ const { useInboxAutoCollapse } = await import("./use-inbox-auto-collapse")
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ qc.setQueryData(communityKeys.inboxUnreads(), data)
+ let latest: ReturnType<typeof useInboxUnreads> | undefined
+ let collapse: ReturnType<typeof useInboxAutoCollapse> | undefined
+ function Harness() {
+ latest = useInboxUnreads()
+ collapse = useInboxAutoCollapse({
+ queryClient: qc,
+ publishedHref: "/c/channels/s0",
+ navigationPending: false,
+ pendingHref: null,
+ })
+ return null
+ }
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(
+ QueryClientProvider,
+ { client: qc },
+ React.createElement(Harness),
+ ))
+ })
+ expect(latest?.hasProjectedUnread).toBe(true)
+
+ let epoch = 0
+ await act(async () => {
+ epoch = collapse!.beginProjection(
+ inboxChannelRowTarget(server, channel)!,
+ "/c/channels/s1/reserved",
+ )
+ })
+ expect(latest?.servers).toEqual([])
+ expect(latest?.hasProjectedUnread).toBe(false)
+
+ await act(async () => {
+ collapse!.rollbackProjection(epoch)
+ })
+ expect(latest?.servers).toEqual([server])
+ 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",
diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.ts
index a75a71d5f..8c49ced9d 100644
--- a/src/web/src/hooks/community/use-inbox.ts
+++ b/src/web/src/hooks/community/use-inbox.ts
@@ -6,8 +6,17 @@ 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 {
+ inboxMentionRowTarget,
+ reserveInboxUnreadsResponse,
+} from "./inbox-read-reservation"
import { getActiveAccountUnreadProjection } from "./account-unread-projection"
+import { useInboxProjectionTarget } from "./use-inbox-auto-collapse"
+import {
+ isInboxTargetReserved,
+ reservedUnreadExclusion,
+ selectUnreadPresentation,
+} from "./unread-presentation"
class StaleReadError extends Error {
constructor() { super("stale D1 read"); this.name = "StaleReadError" }
@@ -84,6 +93,15 @@ export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {
unreadProjection.getSnapshot,
unreadProjection.getSnapshot,
)
+ const reservationTarget = useInboxProjectionTarget(queryClient)
+ const channelExclusion = useMemo(
+ () => reservedUnreadExclusion(reservationTarget, "channels"),
+ [reservationTarget],
+ )
+ const dmExclusion = useMemo(
+ () => reservedUnreadExclusion(reservationTarget, "dms"),
+ [reservationTarget],
+ )
const queryFn = useMemo(() => inboxUnreadsReservedQueryFn(queryClient), [queryClient])
const query = useQuery({
queryKey: communityKeys.inboxUnreads(),
@@ -146,18 +164,26 @@ export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {
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,
- )
+ const children = channel.children.filter((child) => selectUnreadPresentation({
+ accountUnread: unreadProjection.projectUnread(
+ "inbox-unreads",
+ child.channelId,
+ true,
+ child.lastUnreadSeq,
+ "channels",
+ channelExclusion,
+ ),
+ }).effectiveUnread)
+ const direct = channel.hasDirectUnread !== false && selectUnreadPresentation({
+ accountUnread: unreadProjection.projectUnread(
+ "inbox-unreads",
+ channel.channelId,
+ true,
+ channel.lastUnreadSeq,
+ "channels",
+ channelExclusion,
+ ),
+ }).effectiveUnread
if (!direct && children.length === 0) {
channelsChanged = true
return []
@@ -177,18 +203,21 @@ export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {
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",
- ))
+ const dms = rawDms.filter((dm) => selectUnreadPresentation({
+ accountUnread: unreadProjection.projectUnread(
+ "inbox-unreads",
+ dm.channelId,
+ true,
+ dm.lastUnreadSeq,
+ "dms",
+ dmExclusion,
+ ),
+ }).effectiveUnread)
return {
servers: serversChanged ? servers : rawServers,
dms: dms.length === rawDms.length ? rawDms : dms,
}
- }, [query.data, unreadProjection, unreadVersion])
+ }, [channelExclusion, dmExclusion, query.data, unreadProjection, unreadVersion])
return {
...query,
servers: projected.servers ?? (EMPTY_UNREADS as UnreadServer[]),
@@ -196,8 +225,8 @@ export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {
hasProjectedUnread:
projected.servers.length > 0
|| projected.dms.length > 0
- || unreadProjection.hasPending("inbox-unreads", "channels")
- || unreadProjection.hasPending("inbox-unreads", "dms"),
+ || unreadProjection.hasPending("inbox-unreads", "channels", channelExclusion)
+ || unreadProjection.hasPending("inbox-unreads", "dms", dmExclusion),
}
}
@@ -230,6 +259,7 @@ export function useInboxMentions(): UseQueryResult<MentionsResponse> & {
unreadProjection.getSnapshot,
unreadProjection.getSnapshot,
)
+ const reservationTarget = useInboxProjectionTarget(queryClient)
const query = useQuery({
queryKey: communityKeys.inboxMentions(),
queryFn: inboxMentionsQueryFn,
@@ -271,15 +301,21 @@ export function useInboxMentions(): UseQueryResult<MentionsResponse> & {
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,
- )
+ || selectUnreadPresentation({
+ accountUnread: unreadProjection.projectUnread(
+ "inbox-mentions",
+ mention.channelId,
+ true,
+ mention.m.seq,
+ ),
+ reserved: isInboxTargetReserved(
+ reservationTarget,
+ inboxMentionRowTarget(mention),
+ ),
+ }).effectiveUnread
))
return projected.length === raw.length ? raw : projected
- }, [query.data, unreadProjection, unreadVersion])
+ }, [query.data, reservationTarget, unreadProjection, unreadVersion])
return {
...query,
mentions,
diff --git a/src/web/src/hooks/community/use-servers.ts b/src/web/src/hooks/community/use-servers.ts
index 81859c300..76c3b6f1a 100644
--- a/src/web/src/hooks/community/use-servers.ts
+++ b/src/web/src/hooks/community/use-servers.ts
@@ -14,6 +14,8 @@ import { avatarInitial } from "@/lib/community/avatar"
import { isServerOwner, UNCATEGORIZED_CATEGORY_ID } from "@alook/shared"
import type { Server, Category, Channel } from "@/lib/community/models/navigation"
import { getActiveAccountUnreadProjection } from "./account-unread-projection"
+import { useInboxProjectionTarget } from "./use-inbox-auto-collapse"
+import { reservedUnreadExclusion } from "./unread-presentation"
/**
* Fetches the sidebar list of servers the current user is in.
@@ -107,6 +109,11 @@ export function useServers(): UseQueryResult<ServersResponse> & {
unreadProjection.getSnapshot,
unreadProjection.getSnapshot,
)
+ const reservationTarget = useInboxProjectionTarget(queryClient)
+ const unreadExclusion = useMemo(
+ () => reservedUnreadExclusion(reservationTarget, "channels"),
+ [reservationTarget],
+ )
useEffect(() => {
const sources = query.data?.servers.flatMap((server) => server.unreadSources ?? [])
if (sources) unreadProjection.absorbFamily("servers", sources)
@@ -139,6 +146,7 @@ export function useServers(): UseQueryResult<ServersResponse> & {
server.id,
server.unreadSources ?? [],
server.unread,
+ unreadExclusion,
)
const mentions = unreadProjection.projectServerMentionCount(
server.id,
@@ -150,7 +158,7 @@ export function useServers(): UseQueryResult<ServersResponse> & {
return { ...server, unread, mentions }
})
return changed ? projected : raw
- }, [query.data, unreadProjection, unreadVersion])
+ }, [query.data, unreadExclusion, unreadProjection, unreadVersion])
return {
...query,
servers: projectedServers ?? (EMPTY_SERVERS as Server[]),
@@ -289,6 +297,11 @@ export function useServer(
unreadProjection.getSnapshot,
unreadProjection.getSnapshot,
)
+ const reservationTarget = useInboxProjectionTarget(queryClient)
+ const unreadExclusion = useMemo(
+ () => reservedUnreadExclusion(reservationTarget, "channels"),
+ [reservationTarget],
+ )
const enabled = !!serverId
const query = useQuery({
queryKey: enabled ? communityKeys.server(serverId!) : communityKeys.server("__none__"),
@@ -357,6 +370,7 @@ export function useServer(
channel.id,
sources,
channel.unread,
+ unreadExclusion,
)
if (unread === channel.unread) return channel
categoryChanged = true
@@ -367,7 +381,7 @@ export function useServer(
return { ...category, channels }
})
return changed ? { ...query.data, categories } : query.data
- }, [query.data, serverId, unreadProjection, unreadVersion])
+ }, [query.data, unreadExclusion, serverId, unreadProjection, unreadVersion])
return {
...query,
server: projectedServer,
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 683efcbc8..ee5dc3367 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
@@ -45,7 +45,6 @@ describe("human account read-state writer contract", () => {
expect(directWriters).toEqual([
"src/shared/src/db/queries/community/forum-post-delete.ts",
"src/shared/src/db/queries/community/message.ts",
- "src/shared/src/db/queries/community/notification-setting.ts",
"src/shared/src/db/queries/community/read-state.ts",
])
})
@@ -62,6 +61,7 @@ describe("human account read-state writer contract", () => {
const notification = source("src/shared/src/db/queries/community/notification-setting.ts")
expect(notification).toContain('actorKind: "human" | "bot"')
expect(notification).toContain("advanceReadStateRevisionWhenBuilder")
+ expect(notification).not.toContain("communityReadState")
expect(notification).not.toContain("accountReadStateRowsBuilder")
const forumDelete = source("src/shared/src/db/queries/community/forum-post-delete.ts")
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 7ef52d677..0d45355ad 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
@@ -720,7 +720,7 @@ test("forum cards use the ordinary parent cursor while child cursors stay indepe
deviceA.page.off("response", trackForumResponse)
})
-test("human author-send and notification writers replace both active profiles", async ({ asUser }) => {
+test("human author-send replaces both profiles while notification policy preserves unread", async ({ asUser }) => {
test.setTimeout(150_000)
const stamp = Date.now()
const serverId = await seedServer("alice", `Writer sync ${stamp}`)
@@ -736,6 +736,10 @@ test("human author-send and notification writers replace both active profiles",
const proxyB = await proxyCommunityWebSockets(deviceB.context)
await gotoAfterUserWsAuth(deviceA.page, "/c/me")
await gotoAfterUserWsAuth(deviceB.page, "/c/me")
+ await Promise.all([
+ expect(deviceA.page.getByTestId(tid.serverIcon(serverId))).toBeVisible({ timeout: 30_000 }),
+ expect(deviceB.page.getByTestId(tid.serverIcon(serverId))).toBeVisible({ timeout: 30_000 }),
+ ])
await deviceB.page.getByRole("button", { name: "Inbox" }).click()
await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(authorChannelId))).toBeVisible()
await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(notificationChannelId))).toBeVisible()
@@ -797,8 +801,31 @@ test("human author-send and notification writers replace both active profiles",
)).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
expect(writerSnapshot.readStates.find((state) => state.channelId === authorChannelId)?.lastReadSeq)
.toBeGreaterThan(0)
- expect(writerSnapshot.readStates.find((state) => state.channelId === notificationChannelId)?.lastReadSeq)
- .toBeGreaterThan(0)
+ expect(writerSnapshot.readStates.find((state) => state.channelId === notificationChannelId)?.lastReadSeq ?? 0)
+ .toBe(0)
+
+ const restoreStarts = [proxyA.frames.length, proxyB.frames.length]
+ const restoreStatus = await deviceA.page.evaluate(async (channelId) => {
+ const response = await fetch(`/api/community/users/me/notifications/channel/${channelId}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ level: "all" }),
+ })
+ return response.status
+ }, notificationChannelId)
+ expect(restoreStatus).toBe(200)
+
+ for (const [proxy, start] of [[proxyA, restoreStarts[0]], [proxyB, restoreStarts[1]]] as const) {
+ await expect.poll(() => readStateEventsSince(proxy.frames, start!).length, {
+ timeout: 20_000,
+ }).toBe(1)
+ }
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(notificationChannelId))).toBeVisible()
+ const restoredSnapshot = await (await deviceB.page.request.get(
+ "/api/community/users/me/read-state",
+ )).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
+ expect(restoredSnapshot.readStates.find((state) => state.channelId === notificationChannelId)?.lastReadSeq ?? 0)
+ .toBe(0)
})
test("forum delete broadcasts replacement and removal to both active profiles", async ({ asUser }) => {
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
index 09b75095b..bbe35f0fa 100644
--- a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
+++ b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
@@ -100,6 +100,10 @@ async function expectUnreadDot(row: ReturnType<Page["getByTestId"]>) {
await expect(row.locator("span.rounded-full.bg-primary")).toHaveCount(1)
}
+async function expectNoUnreadDot(row: ReturnType<Page["getByTestId"]>) {
+ await expect(row.locator("span.rounded-full.bg-primary")).toHaveCount(0)
+}
+
async function readSeq(page: Page, channelId: string): Promise<number> {
const response = await page.request.get("/api/community/users/me/read-state")
expect(response.ok()).toBe(true)
@@ -298,6 +302,13 @@ test.describe.serial("account unread projection", () => {
timeout: 20_000,
})
await expect.poll(observerGate.pending).toBeGreaterThan(0)
+ await expectNoUnreadDot(page.getByTestId(tid.channelRow(unreadChannel)))
+ await page.getByTestId(tid.inboxTrigger).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 expectUnreadDot(page.getByTestId(tid.inboxTrigger))
+ await page.getByTestId(tid.inboxTrigger).click()
expect(targetPuts).toEqual([])
const readResponse = page.waitForResponse((response) => (