Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(web): preserve thread-opener read ownership (#578)
Gener79c5a3e59f76
diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.tsindex 914955fa7..0d1625983 100644--- a/src/shared/src/db/queries/community/inbox.ts+++ b/src/shared/src/db/queries/community/inbox.ts@@ -43,6 +43,17 @@ export interface UnreadForumOpenerRow {openerSeq: number;}+export interface ThreadOpenerRow {+ parentChannelId: string;+ parentType: string | null;+ openerMessageId: string;+ childChannelId: string;+ title: string;+ createdAt: string;+ openerSeq: number;+ openerUnread: boolean;+}+/*** Two-branch unread predicate, shared by every reader that groups channels* by "unread since I last looked."@@ -405,44 +416,73 @@ export async function listUnreadForumOpeners(}/**- * Resolve canonical forum opener metadata for an already-authorized set of- * unread child channels. The caller owns visibility, participation, and mute- * filtering; this query only validates the child → forum → opener structure.+ * Resolve canonical parent-opener metadata for child rows that already passed+ * Inbox visibility, participation, notification, and mute filtering. This+ * lookup enriches those rows only; it never discovers additional children.*/-export async function listForumOpenersByChildIds(+export async function listThreadOpenersByChildIds(db: Database,+ userId: string,childIds: string[]-): Promise<UnreadForumOpenerRow[]> {+): Promise<ThreadOpenerRow[]> {if (childIds.length === 0) return [];- const childChannel = aliasedTable(communityChannel, "forum_inbox_child_lookup");- const parentForum = aliasedTable(communityChannel, "forum_inbox_parent_lookup");+ const childChannel = aliasedTable(communityChannel, "thread_inbox_child_lookup");+ const parentChannel = aliasedTable(communityChannel, "thread_inbox_parent_lookup");const rows = (await Promise.all(chunk(childIds, D1_MAX_IN_PARAMS).map((ids) =>db.select({- forumChannelId: parentForum.id,+ parentChannelId: parentChannel.id,+ parentType: parentChannel.type,openerMessageId: communityMessage.id,openerContent: communityMessage.content,openerSeq: communityMessage.seq,childChannelId: childChannel.id,childName: childChannel.name,createdAt: communityMessage.createdAt,+ openerUnread: sql<number>`(+ (+ (${communityReadState.id} IS NOT NULL AND ${communityMessage.seq} > COALESCE(${communityReadState.lastReadSeq}, 0))+ OR+ (${communityReadState.id} IS NULL AND ${communityMessage.createdAt} > ${communityServerMember.joinedAt})+ )+ AND ${notificationEligibleSql(+ userId,+ {+ id: parentChannel.id,+ serverId: parentChannel.serverId,+ parentChannelId: parentChannel.parentChannelId,+ },+ { id: communityMessage.id }+ )}+ )`,}).from(childChannel).innerJoin(- parentForum,- and(- eq(parentForum.id, childChannel.parentChannelId),- eq(parentForum.type, "forum")- )+ parentChannel,+ eq(parentChannel.id, childChannel.parentChannelId)).innerJoin(communityMessage,and(eq(communityMessage.id, childChannel.parentMessageId),- eq(communityMessage.channelId, parentForum.id)+ eq(communityMessage.channelId, parentChannel.id)+ )+ )+ .innerJoin(+ communityServerMember,+ and(+ eq(communityServerMember.serverId, parentChannel.serverId),+ eq(communityServerMember.userId, userId)+ )+ )+ .leftJoin(+ communityReadState,+ and(+ eq(communityReadState.channelId, parentChannel.id),+ eq(communityReadState.userId, userId))).where(@@ -450,7 +490,8 @@ export async function listForumOpenersByChildIds(inArray(childChannel.id, ids),eq(childChannel.type, "thread"),eq(childChannel.archived, 0),- eq(parentForum.archived, 0)+ eq(parentChannel.archived, 0),+ isNull(parentChannel.parentChannelId))))@@ -465,7 +506,8 @@ export async function listForumOpenersByChildIds();return rows.map((row) => ({- forumChannelId: row.forumChannelId,+ parentChannelId: row.parentChannelId,+ parentType: row.parentType,openerMessageId: row.openerMessageId,childChannelId: row.childChannelId,title:@@ -474,6 +516,7 @@ export async function listForumOpenersByChildIds(: row.childName?.trim() || "Thread",createdAt: row.createdAt,openerSeq: row.openerSeq,+ openerUnread: Boolean(row.openerUnread),}));}diff --git a/src/shared/test/queries/community-inbox.test.ts b/src/shared/test/queries/community-inbox.test.tsindex e345cf3b1..f8c42976e 100644--- a/src/shared/test/queries/community-inbox.test.ts+++ b/src/shared/test/queries/community-inbox.test.ts@@ -30,8 +30,8 @@ describe("community/inbox exports", () => {expect(typeof inboxQueries.listUnreadForumOpeners).toBe("function");});- it("exports listForumOpenersByChildIds", () => {- expect(typeof inboxQueries.listForumOpenersByChildIds).toBe("function");+ it("exports listThreadOpenersByChildIds", () => {+ expect(typeof inboxQueries.listThreadOpenersByChildIds).toBe("function");});});@@ -109,6 +109,7 @@ describe("listUnreadChannels — seq read-watermark behaviour", () => {chain.from = vi.fn(() => chain);chain.innerJoin = vi.fn(() => chain);chain.leftJoin = vi.fn(() => chain);+ chain.leftJoin = vi.fn(() => chain);chain.where = vi.fn(() => Promise.resolve(rows));return chain;}@@ -303,45 +304,56 @@ describe("listUnreadForumOpeners — scoped forum projection", () => {});});-describe("listForumOpenersByChildIds — structurally validated child projection", () => {+describe("listThreadOpenersByChildIds — structurally validated child projection", () => {function createChildOpenerMock(responseSets: any[][]) {let call = 0;const chain: any = {};chain.select = vi.fn(() => chain);chain.from = vi.fn(() => chain);chain.innerJoin = vi.fn(() => chain);+ chain.leftJoin = vi.fn(() => chain);chain.where = vi.fn(() => Promise.resolve(responseSets[call++] ?? []));return chain;}const raw = (overrides: Record<string, unknown> = {}) => ({- forumChannelId: "forum_1",+ parentChannelId: "parent_1",+ parentType: "text",openerMessageId: "opener_1",openerContent: "Canonical title",openerSeq: 7,childChannelId: "post_1",childName: "derived",createdAt: "2026-07-07T10:00:00.000Z",+ openerUnread: 1,...overrides,});it("does not query for an empty authorized child scope", async () => {const db = createChildOpenerMock([]);- await expect(inboxQueries.listForumOpenersByChildIds(db, [])).resolves.toEqual([]);+ await expect(inboxQueries.listThreadOpenersByChildIds(db, "u1", [])).resolves.toEqual([]);expect(db.select).not.toHaveBeenCalled();});it("returns full canonical content and falls back only for blank content", async () => {const db = createChildOpenerMock([[raw(),- raw({ openerMessageId: "blank", childChannelId: "post_2", openerContent: " ", childName: "Fallback" }),+ raw({ openerMessageId: "blank", childChannelId: "post_2", openerContent: " ", childName: "Fallback", openerUnread: 0 }),]]);- const rows = await inboxQueries.listForumOpenersByChildIds(db, ["post_1", "post_2"]);+ const rows = await inboxQueries.listThreadOpenersByChildIds(db, "u1", ["post_1", "post_2"]);expect(rows.map((row) => [row.childChannelId, row.title])).toEqual([["post_1", "Canonical title"],["post_2", "Fallback"],]);- expect(db.innerJoin).toHaveBeenCalledTimes(2);+ expect(db.innerJoin).toHaveBeenCalledTimes(3);+ expect(db.leftJoin).toHaveBeenCalledTimes(1);+ expect(rows[0]).toMatchObject({+ parentChannelId: "parent_1",+ parentType: "text",+ openerSeq: 7,+ openerUnread: true,+ });+ expect(rows[1]?.openerUnread).toBe(false);});it("chunks the bounded child id set and globally sorts results", async () => {@@ -351,7 +363,7 @@ describe("listForumOpenersByChildIds — structurally validated child projectionraw({ openerMessageId: "newer", childChannelId: "post_new", createdAt: "2026-07-07T11:00:00.000Z" }),]]);const ids = Array.from({ length: 91 }, (_, index) => `post_${index}`);- const rows = await inboxQueries.listForumOpenersByChildIds(db, ids);+ const rows = await inboxQueries.listThreadOpenersByChildIds(db, "u1", ids);expect(db.select).toHaveBeenCalledTimes(2);expect(rows.map((row) => row.openerMessageId)).toEqual(["newer", "older"]);});diff --git a/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts b/src/web/src/app/api/community/users/me/inbox/unreads/route.test.tsindex 96bfac530..ce623e915 100644--- a/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts+++ b/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts@@ -3,7 +3,7 @@ import { NextRequest } from "next/server"const mockListEligibleUnreadChannels = vi.fn()const mockListUnreadForumOpeners = vi.fn()-const mockListForumOpenersByChildIds = vi.fn()+const mockListThreadOpenersByChildIds = vi.fn()const mockListEligibleUnreadDms = vi.fn()const mockListVisibleChannelIds = vi.fn()const mockGetChannelsByIds = vi.fn()@@ -22,7 +22,7 @@ vi.mock("@alook/shared", async () => {communityInbox: {listEligibleUnreadChannels: (...args: unknown[]) => mockListEligibleUnreadChannels(...args),listUnreadForumOpeners: (...args: unknown[]) => mockListUnreadForumOpeners(...args),- listForumOpenersByChildIds: (...args: unknown[]) => mockListForumOpenersByChildIds(...args),+ listThreadOpenersByChildIds: (...args: unknown[]) => mockListThreadOpenersByChildIds(...args),listEligibleUnreadDms: (...args: unknown[]) => mockListEligibleUnreadDms(...args),},communityChannel: {@@ -84,12 +84,35 @@ function opener(overrides: Partial<{}}+function threadOpener(overrides: Partial<{+ parentChannelId: string+ parentType: string+ openerMessageId: string+ childChannelId: string+ title: string+ createdAt: string+ openerSeq: number+ openerUnread: boolean+}> = {}) {+ return {+ parentChannelId: "f1",+ parentType: "forum",+ openerMessageId: "m1",+ childChannelId: "p1",+ title: "Full opener content",+ createdAt: "2026-06-25T10:00:00Z",+ openerSeq: 1,+ openerUnread: false,+ ...overrides,+ }+}+describe("GET /api/community/users/me/inbox/unreads", () => {beforeEach(() => {vi.clearAllMocks()mockListEligibleUnreadDms.mockResolvedValue([])mockListUnreadForumOpeners.mockResolvedValue([])- mockListForumOpenersByChildIds.mockResolvedValue([])+ mockListThreadOpenersByChildIds.mockResolvedValue([])mockListVisibleChannelIds.mockResolvedValue([])mockGetChannelsByIds.mockResolvedValue([])})@@ -260,6 +283,39 @@ describe("GET /api/community/users/me/inbox/unreads", () => {const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()expect(body.servers[0].channels[0].children).toEqual([])+ expect(mockListThreadOpenersByChildIds).toHaveBeenCalledWith(expect.anything(), "u1", [])+ })++ it("enriches only already-eligible text child rows without replacing their names", async () => {+ mockListEligibleUnreadChannels.mockResolvedValue([+ row({ channelId: "c1", channelName: "general", type: "text" }),+ row({ channelId: "t1", channelName: "Chosen thread name", type: "thread", parentChannelId: "c1", lastMessageAt: "2026-06-25T12:00:00Z" }),+ row({ channelId: "t2", channelName: "Read opener thread", type: "thread", parentChannelId: "c1", lastMessageAt: "2026-06-25T11:00:00Z" }),+ ])+ mockListThreadOpenersByChildIds.mockResolvedValue([+ threadOpener({ parentChannelId: "c1", parentType: "text", childChannelId: "t1", openerMessageId: "m7", openerSeq: 7, openerUnread: true, title: "Parent message content" }),+ threadOpener({ parentChannelId: "c1", parentType: "text", childChannelId: "t2", openerMessageId: "m4", openerSeq: 4, openerUnread: false, title: "Other parent content" }),+ ])++ const body = await (await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))).json()+ expect(body.servers[0].channels[0].children).toEqual([+ expect.objectContaining({+ channelId: "t1",+ channelName: "Chosen thread name",+ parentChannelId: "c1",+ openerMessageId: "m7",+ openerSeq: 7,+ openerUnread: true,+ }),+ expect.objectContaining({+ channelId: "t2",+ channelName: "Read opener thread",+ parentChannelId: "c1",+ openerMessageId: "m4",+ openerSeq: 4,+ openerUnread: false,+ }),+ ])})// ── Entity type plumbing (drives the inbox icon) ───────────────────────────@@ -329,13 +385,15 @@ describe("GET /api/community/users/me/inbox/unreads", () => {const body = await (await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))).json()const children = body.servers[0].channels[0].children- expect(children.map((child: { channelId: string; channelName: string; openerMessageId: string }) => ({+ expect(children.map((child: { channelId: string; channelName: string; openerMessageId: string; openerSeq: number; openerUnread: boolean }) => ({channelId: child.channelId,title: child.channelName,openerMessageId: child.openerMessageId,+ openerSeq: child.openerSeq,+ openerUnread: child.openerUnread,}))).toEqual([- { channelId: "p2", title: "Second full opener", openerMessageId: "m2" },- { channelId: "p1", title: "First full opener", openerMessageId: "m1" },+ { channelId: "p2", title: "Second full opener", openerMessageId: "m2", openerSeq: 2, openerUnread: true },+ { channelId: "p1", title: "First full opener", openerMessageId: "m1", openerSeq: 1, openerUnread: true },])})@@ -355,6 +413,8 @@ describe("GET /api/community/users/me/inbox/unreads", () => {channelId: "p1",channelName: "Canonical opener title",openerMessageId: "m1",+ openerSeq: 7,+ openerUnread: true,lastMessageAt: "2026-06-25T12:00:00Z",mentionCount: 2,})@@ -373,19 +433,21 @@ describe("GET /api/community/users/me/inbox/unreads", () => {mockGetChannelsByIds.mockResolvedValue([{ id: "forum_1", name: "Forum", type: "forum", serverId: "s1" },])- mockListForumOpenersByChildIds.mockResolvedValue([- opener({ forumChannelId: "forum_1", childChannelId: "post_1", title: "Full canonical opener" }),+ mockListThreadOpenersByChildIds.mockResolvedValue([+ threadOpener({ parentChannelId: "forum_1", childChannelId: "post_1", title: "Full canonical opener" }),])const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))const body = await res.json()- expect(mockListForumOpenersByChildIds).toHaveBeenCalledWith(expect.anything(), ["post_1"])+ expect(mockListThreadOpenersByChildIds).toHaveBeenCalledWith(expect.anything(), "u1", ["post_1"])expect(body.servers[0].channels[0].children).toEqual([expect.objectContaining({channelId: "post_1",channelName: "Full canonical opener",openerMessageId: "m1",+ openerSeq: 1,+ openerUnread: false,}),])})@@ -395,7 +457,7 @@ describe("GET /api/community/users/me/inbox/unreads", () => {row({ channelId: "post_ok", parentChannelId: "forum_ok", type: "thread" }),])await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))- expect(mockListForumOpenersByChildIds).toHaveBeenCalledWith(expect.anything(), ["post_ok"])+ expect(mockListThreadOpenersByChildIds).toHaveBeenCalledWith(expect.anything(), "u1", ["post_ok"])})it("removes a phantom forum parent when no unread opener or child remains", async () => {diff --git a/src/web/src/app/api/community/users/me/inbox/unreads/route.ts b/src/web/src/app/api/community/users/me/inbox/unreads/route.tsindex 6b96e6839..fc2b6303b 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@@ -26,10 +26,11 @@ export const GET = withAuth(async (req, ctx) => {type UnreadRow = Awaited<ReturnType<typeof queries.communityInbox.listEligibleUnreadChannels>>[number]type UnreadDmRow = Awaited<ReturnType<typeof queries.communityInbox.listEligibleUnreadDms>>[number]type ForumOpenerRow = Awaited<ReturnType<typeof queries.communityInbox.listUnreadForumOpeners>>[number]+ type ThreadOpenerRow = Awaited<ReturnType<typeof queries.communityInbox.listThreadOpenersByChildIds>>[number]const { value: fetched, stale } = await readOrStale<{unread: UnreadRow[]unreadDms: UnreadDmRow[]- forumOpeners: ForumOpenerRow[]+ threadOpeners: Array<ThreadOpenerRow>}>(async () => {const visibleChannelIds = await queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId)@@ -49,7 +50,7 @@ export const GET = withAuth(async (req, ctx) => {).map((row) => row.channelId),)]- const unreadForumChildIds = [...new Set(+ const unreadChildIds = [...new Set(unread.filter((row) =>@@ -57,15 +58,27 @@ export const GET = withAuth(async (req, ctx) => {).map((row) => row.channelId),)]- const [directForumOpeners, childForumOpeners] = await Promise.all([+ const [directForumOpeners, childThreadOpeners] = await Promise.all([queries.communityInbox.listUnreadForumOpeners(db, ctx.userId, forumParentIds),- queries.communityInbox.listForumOpenersByChildIds(db, unreadForumChildIds),+ queries.communityInbox.listThreadOpenersByChildIds(db, ctx.userId, unreadChildIds),])- const forumOpeners = [...new Map(- [...directForumOpeners, ...childForumOpeners].map((row) => [row.childChannelId, row]),+ const directThreadOpeners: ThreadOpenerRow[] = directForumOpeners.map(+ (row: ForumOpenerRow) => ({+ parentChannelId: row.forumChannelId,+ parentType: "forum",+ openerMessageId: row.openerMessageId,+ childChannelId: row.childChannelId,+ title: row.title,+ createdAt: row.createdAt,+ openerSeq: row.openerSeq,+ openerUnread: true,+ }),+ )+ const threadOpeners = [...new Map(+ [...childThreadOpeners, ...directThreadOpeners].map((row) => [row.childChannelId, row]),).values()]const forumParentsWithUnread = new Set([- ...forumOpeners.map((row) => row.forumChannelId),+ ...directForumOpeners.map((row) => row.forumChannelId),...unread.flatMap((row) => row.parentChannelId ? [row.parentChannelId] : []),])const withoutPhantomForumParents = unread.filter(@@ -74,15 +87,15 @@ export const GET = withAuth(async (req, ctx) => {row.type !== "forum" ||forumParentsWithUnread.has(row.channelId),)- return { unread: withoutPhantomForumParents, unreadDms, forumOpeners }+ return { unread: withoutPhantomForumParents, unreadDms, threadOpeners }},- { unread: [], unreadDms: [], forumOpeners: [] },+ { unread: [], unreadDms: [], threadOpeners: [] },{ route: "community/inbox/unreads" },)if (stale) {return writeJSON({ servers: [], dms: [], limit, truncated: false, stale: true })}- const { unread, unreadDms, forumOpeners } = fetched+ const { unread, unreadDms, threadOpeners } = fetched// Split unread rows into top-level channels and child threads.// A child nests under its `parentChannelId`; a parent surfaces in the tree@@ -94,6 +107,9 @@ export const GET = withAuth(async (req, ctx) => {lastMessageAt: stringmentionCount: numberopenerMessageId?: string+ parentChannelId?: string+ openerSeq?: number+ openerUnread?: boolean// Private stable-order fields. They are removed from the response below.sortSeq: numbersortId: string@@ -143,41 +159,47 @@ export const GET = withAuth(async (req, ctx) => {}}- // Project unread parent openers as post rows. An opener and unread replies- // for the same post share one childChannelId, so merge them into one row- // while retaining the opener id as the parent forum's progressive-read- // target. The authoritative title is supplied by the opener query.- for (const opener of forumOpeners) {- const parent = parents.get(opener.forumChannelId)+ // Enrich already-eligible child rows with their canonical parent opener.+ // Forum opener-only rows retain their existing nested presentation; text+ // opener-only unread remains represented by its parent channel row.+ for (const opener of threadOpeners) {+ const parent = parents.get(opener.parentChannelId)const unreadChild = unreadByChannelId.get(opener.childChannelId)- if (!parent && unreadChild?.parentChannelId !== opener.forumChannelId) continue+ if (!parent && unreadChild?.parentChannelId !== opener.parentChannelId) continueconst serverId = parent?.serverId ?? unreadChild?.serverIdif (!serverId) continue- const children = childrenByParent.get(opener.forumChannelId) ?? new Map<string, UnreadChild>()+ const children = childrenByParent.get(opener.parentChannelId) ?? new Map<string, UnreadChild>()const existing = children.get(opener.childChannelId)if (existing) {- existing.channelName = opener.title+ if (opener.parentType === "forum") existing.channelName = opener.titleexisting.type = existing.type ?? "thread"+ existing.parentChannelId = opener.parentChannelIdexisting.openerMessageId = opener.openerMessageId+ existing.openerSeq = opener.openerSeq+ existing.openerUnread = opener.openerUnreadif (opener.createdAt >= existing.lastMessageAt) {existing.lastMessageAt = opener.createdAtexisting.sortSeq = opener.openerSeqexisting.sortId = opener.openerMessageId}} else {+ if (opener.parentType !== "forum" || !opener.openerUnread) continuechildren.set(opener.childChannelId, {channelId: opener.childChannelId,channelName: opener.title,type: "thread",lastMessageAt: opener.createdAt,mentionCount: unreadChild?.mentionCount ?? 0,+ parentChannelId: opener.parentChannelId,openerMessageId: opener.openerMessageId,+ openerSeq: opener.openerSeq,+ openerUnread: opener.openerUnread,sortSeq: opener.openerSeq,sortId: opener.openerMessageId,})}- childrenByParent.set(opener.forumChannelId, children)+ childrenByParent.set(opener.parentChannelId, children)}// Parents that have an unread child but no direct unread aren't in `unread`,@@ -274,7 +296,10 @@ export const GET = withAuth(async (req, ctx) => {type: k.type ?? undefined,lastMessageAt: k.lastMessageAt,mentionCount: k.mentionCount,+ ...(k.parentChannelId ? { parentChannelId: k.parentChannelId } : {}),...(k.openerMessageId ? { openerMessageId: k.openerMessageId } : {}),+ ...(k.openerSeq !== undefined ? { openerSeq: k.openerSeq } : {}),+ ...(k.openerMessageId ? { openerUnread: k.openerUnread === true } : {}),})),})),}))diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsxindex 24ff968e3..b1cb1bd74 100644--- a/src/web/src/app/c/me/[dmId]/page.tsx+++ b/src/web/src/app/c/me/[dmId]/page.tsx@@ -148,6 +148,9 @@ function DmView() {jumpToPresent,presentVersion,latestSeq,+ isPending: messagesPending,+ isError: messagesError,+ refetch: refetchMessages,} = useDmMessages(dmId, {lastReadMessageId: readSnapshotFetching? undefined@@ -224,8 +227,19 @@ function DmView() {dmId,messages,scrollRootEl,- snapshotReady: !readSnapshotFetching,+ snapshotStatus: readSnapshotFetching+ ? "pending"+ : readSnapshot+ ? "ready"+ : "error",+ feedStatus: messagesPending+ ? "pending"+ : messagesError+ ? "error"+ : "ready",+ tailAttached: !hasMoreNewerMessages,confirmedSeq: readSnapshot?.lastReadSeq ?? 0,+ catchUp: () => refetchMessages(),})// `↓ N` unread count. Same math as channel: server truth isdiff --git a/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts b/src/web/src/components/community/channels/channel-route.text-scroll-target.test.tsindex 1b3d25645..0045b744d 100644--- a/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts+++ b/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts@@ -14,11 +14,15 @@ const {mockUiHandlers,mockBreakpoint,mockHeaderBack,+ mockOpenerGate,+ mockSearchParams,} = vi.hoisted(() => ({mockRouter: { push: vi.fn(), replace: vi.fn(), back: vi.fn() },mockUiHandlers: { replacePath: vi.fn(), goBackMobile: vi.fn() },mockBreakpoint: { value: "desktop" as "desktop" | "mobile" },mockHeaderBack: { current: undefined as undefined | (() => void) },+ mockOpenerGate: vi.fn(() => null),+ mockSearchParams: { value: "msg=m_target&keep=1" },mockRouteModel: {server: {id: "server_1",@@ -40,6 +44,7 @@ const {isForumPostChild: false,isNotifyUnit: false,routeHydrated: true,+ routeLifecycle: "ready" as "pending" | "ready" | "terminal-error",},mockMemberViewModel: {composerMembers: [],@@ -54,11 +59,16 @@ const {vi.mock("next/navigation", () => ({useRouter: () => mockRouter,usePathname: () => "/c/channels/server_1/channel_1",- useSearchParams: () => new URLSearchParams("msg=m_target&keep=1"),+ useSearchParams: () => new URLSearchParams(mockSearchParams.value),}))vi.mock("sonner", () => ({ toast: vi.fn() }))vi.mock("@/lib/api/client", () => ({ apiFetch: vi.fn(), toastApiError: vi.fn() }))vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mockBreakpoint.value }))+vi.mock("@/hooks/community/thread-opener-read-handoff", () => ({+ THREAD_OPENER_HANDOFF_PARAM: "inboxThreadOpener",+ useClaimThreadOpenerReadHandoff: vi.fn(),+ useThreadOpenerRouteGate: (...args: unknown[]) => mockOpenerGate(...args),+}))vi.mock("@/components/community/channels/channel-header", () => ({ChannelHeader: ({ onBack }: { onBack?: () => void }) => {if (onBack) mockHeaderBack.current = onBack@@ -232,6 +242,8 @@ describe("ChannelRoute message surface ownership", () => {beforeEach(() => {vi.useFakeTimers()mockedMessageList.mockClear()+ mockOpenerGate.mockClear()+ mockSearchParams.value = "msg=m_target&keep=1"mockBreakpoint.value = "desktop"mockHeaderBack.current = undefinedObject.assign(mockRouteModel, {@@ -249,7 +261,53 @@ describe("ChannelRoute message surface ownership", () => {isForumPostChild: false,isNotifyUnit: false,routeHydrated: true,+ routeLifecycle: "ready",+ })+ })++ it("forwards the route lifecycle and canonical child tuple to the opener gate", () => {+ configureThreadRoute()+ mockRouteModel.routeLifecycle = "pending"+ mockedUseChannelMessageFeed.mockReturnValue(feed())+ act(() => {+ TestRenderer.create(React.createElement(ChannelRoute, {+ serverId: "server_1",+ serverParam: "server_1",+ channelId: "channel_1",+ }))+ })+ expect(mockOpenerGate).toHaveBeenCalledWith({+ serverId: "server_1",+ childChannelId: "channel_1",+ parentChannelId: "parent_1",+ openerMessageId: "opener_1",+ lifecycle: "pending",+ })+ })++ it("defers child msg cleanup until the handoff nonce has its own cleanup", () => {+ mockSearchParams.value = "inboxThreadOpener=nonce-1&msg=m_target&keep=1"+ mockedUseChannelMessageFeed.mockReturnValue(feed())+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(ChannelRoute, {+ serverParam: "server_1",+ channelId: "channel_1",+ }))+ })+ expect(mockRouter.replace).not.toHaveBeenCalled()++ mockSearchParams.value = "msg=m_target&keep=1"+ act(() => {+ renderer.update(React.createElement(ChannelRoute, {+ serverParam: "server_1",+ channelId: "channel_1",+ }))})+ expect(mockRouter.replace).toHaveBeenCalledWith(+ "/c/channels/server_1/channel_1?keep=1",+ { scroll: false },+ )})afterEach(() => {diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsxindex 12c8bc885..ef181dc15 100644--- a/src/web/src/components/community/channels/channel-route.tsx+++ b/src/web/src/components/community/channels/channel-route.tsx@@ -28,6 +28,10 @@ import { useForumOpenerHint } from "@/hooks/community/use-forum-opener-hint"import { useNotificationSettings } from "@/hooks/community/use-notification-settings"import { useSetChannelNotif } from "@/hooks/community/mutations"import { channelHref, removeCommunityParam } from "@/lib/community/community-route"+import {+ THREAD_OPENER_HANDOFF_PARAM,+ useThreadOpenerRouteGate,+} from "@/hooks/community/thread-opener-read-handoff"/*** /c/channels/:serverId/:channelId@@ -75,6 +79,13 @@ export function ChannelRoute({ serverParam, channelId }: {currentChannelMeta?.parentMessageId,isForumPostChild && routeModel.routeHydrated,)+ const threadOpenerHandoff = useThreadOpenerRouteGate({+ serverId,+ childChannelId: channelId,+ parentChannelId: currentChannelMeta?.parentChannelId ?? null,+ openerMessageId: currentChannelMeta?.parentMessageId ?? null,+ lifecycle: routeModel.routeLifecycle,+ })const channelName = useMemo(() => resolveChannelDisplayName({forumPostTitle: isForumPostChild ? forumPostOpener.data?.content : null,topLevelName: channelInServer?.name,@@ -134,13 +145,15 @@ export function ChannelRoute({ serverParam, channelId }: {// re-trigger the jump. The frozen `jumpTargetId` still seeds the mounted// message controller for this mount; this only cleans the address.useEffect(() => {- if (!jumpTargetId) return+ if (!jumpTargetId || searchParams.has(THREAD_OPENER_HANDOFF_PARAM)) returnconst search = searchParams.toString()const routePath = channelHref(serverParam, channelId)const href = `${routePath}${search ? `?${search}` : ""}`- router.replace(removeCommunityParam(href, "msg"), { scroll: false })- // eslint-disable-next-line react-hooks/exhaustive-deps -- run once for this mount's jump- }, [])+ router.replace(+ removeCommunityParam(href, "msg"),+ { scroll: false },+ )+ }, [channelId, jumpTargetId, router, searchParams, serverParam])const enterThread = useCallback((id: string) => {useCommunityStore.getState().uiHandlers.navigatePath?.(@@ -204,6 +217,7 @@ export function ChannelRoute({ serverParam, channelId }: {parentMessageId={currentChannelMeta?.parentMessageId ?? null}parentChannelName={parentChannelInServer?.name ?? "channel"}parentIsForum={isForumPostChild}+ threadOpenerHandoff={threadOpenerHandoff}childCreatorId={currentChannelMeta?.creatorId}canRenameThread={canManageServer(myRole)}headerServer={bp === "mobile" && currentServerdiff --git a/src/web/src/components/community/channels/dm-header.test.ts b/src/web/src/components/community/channels/dm-header.test.tsindex 20a674e29..e0ff6eb38 100644--- a/src/web/src/components/community/channels/dm-header.test.ts+++ b/src/web/src/components/community/channels/dm-header.test.ts@@ -1,7 +1,30 @@import { createElement } from "react"import { renderToStaticMarkup } from "react-dom/server"import { describe, expect, it, vi } from "vitest"-import { DmHeaderSkeleton } from "./dm-header"+import { tid } from "@/lib/community/testids"+import { DmHeader, DmHeaderSkeleton } from "./dm-header"++const dm = {+ id: "dm-1",+ userId: "user-bob",+ name: "Bob",+ discriminator: "0042",+ avatar: "B",+ status: "online" as const,+ preview: "hello",+}++describe("DmHeader", () => {+ it.each(["h1", "div"] as const)("exposes stable header and %s title contracts", (titleAs) => {+ const markup = renderToStaticMarkup(createElement(DmHeader, { dm, titleAs }))++ expect(markup).toContain(`data-testid="${tid.dmHeader}"`)+ expect(markup).toContain(`data-testid="${tid.dmHeaderTitle}"`)+ expect(markup).toContain(`<${titleAs}`)+ expect(markup).toContain("Bob")+ expect(markup).toContain("#0042")+ })+})describe("DmHeaderSkeleton", () => {it("reserves avatar, title, notification, and optional Back footprints", () => {diff --git a/src/web/src/components/community/channels/dm-header.tsx b/src/web/src/components/community/channels/dm-header.tsxindex 6b04407f0..fefe93d5c 100644--- a/src/web/src/components/community/channels/dm-header.tsx+++ b/src/web/src/components/community/channels/dm-header.tsx@@ -5,6 +5,7 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTriggeimport { Skeleton } from "@/components/ui/skeleton"import { Avatar } from "../avatar"import type { DM } from "@/lib/community/models/people"+import { tid } from "@/lib/community/testids"export function DmHeader({ dm, onBack, titleAs: Title = "h1", notifLevel, onSetNotifLevel }: {dm: DM@@ -14,12 +15,12 @@ export function DmHeader({ dm, onBack, titleAs: Title = "h1", notifLevel, onSetNonSetNotifLevel?: (level: NotifLevel) => void}) {return (- <header className="flex h-12 shrink-0 items-center gap-2 border-b border-border/40 px-3">+ <header data-testid={tid.dmHeader} className="flex h-12 shrink-0 items-center gap-2 border-b border-border/40 px-3">{onBack && (<Button variant="ghost" size="icon-sm" onClick={onBack} className="text-muted-foreground hover:text-foreground" aria-label="Back"><ChevronLeft className="size-5" /></Button>)}<Avatar label={dm.avatar} seed={dm.userId} size={24} presence={dm.status} />- <Title className="min-w-0 truncate font-heading text-base font-medium leading-[1.15] tracking-[-0.015em]">+ <Title data-testid={tid.dmHeaderTitle} className="min-w-0 truncate font-heading text-base font-medium leading-[1.15] tracking-[-0.015em]">{dm.name}{dm.discriminator && (<span className="ml-1 text-xs font-normal tracking-wide text-muted-foreground">diff --git a/src/web/src/components/community/channels/forum-surface.test.ts b/src/web/src/components/community/channels/forum-surface.test.tsindex 1a7feca28..9b98bae99 100644--- a/src/web/src/components/community/channels/forum-surface.test.ts+++ b/src/web/src/components/community/channels/forum-surface.test.ts@@ -17,6 +17,7 @@ const mocks = vi.hoisted(() => ({authorId: "alice",authorAvatar: "A",openerMessageId: "opener-a",+ openerCreatedAt: "2026-08-27T01:00:00.000Z",parentSeq: 3,tags: [],preview: "",@@ -39,6 +40,9 @@ const mocks = vi.hoisted(() => ({},],isLoading: false,+ isPending: false,+ isError: false,+ refetch: vi.fn(() => Promise.resolve()),tag: "All",availableTags: [],selectTag: vi.fn(),@@ -80,10 +84,18 @@ describe("ForumSurface generic read-row adapter", () => {expect(mocks.observe).toHaveBeenLastCalledWith({channelId: "forum-1",- messages: [{ id: "opener-a", seq: 3, authorId: "alice" }],+ messages: [{+ id: "opener-a",+ seq: 3,+ authorId: "alice",+ createdAt: "2026-08-27T01:00:00.000Z",+ }],scrollRootEl: null,- snapshotReady: true,+ snapshotStatus: "ready",+ feedStatus: "ready",+ tailAttached: true,confirmedSeq: 2,+ catchUp: expect.any(Function),})const root = {} as HTMLDivElementdiff --git a/src/web/src/components/community/channels/forum-surface.tsx b/src/web/src/components/community/channels/forum-surface.tsxindex 8f4002d9f..d09e44b15 100644--- a/src/web/src/components/community/channels/forum-surface.tsx+++ b/src/web/src/components/community/channels/forum-surface.tsx@@ -31,12 +31,28 @@ export function ForumSurface({ serverId, forumChannelId, ...props }: {channelId: forumChannelId,messages: feed.posts.flatMap((post) => (post.openerMessageId && post.parentSeq- ? [{ id: post.openerMessageId, seq: post.parentSeq, authorId: post.authorId }]+ ? [{+ id: post.openerMessageId,+ seq: post.parentSeq,+ authorId: post.authorId,+ createdAt: post.openerCreatedAt,+ }]: [])),scrollRootEl,- snapshotReady: !readState.isFetching,+ snapshotStatus: readState.isFetching+ ? "pending"+ : readState.snapshot+ ? "ready"+ : "error",+ feedStatus: feed.isPending+ ? "pending"+ : feed.isError+ ? "error"+ : "ready",+ tailAttached: true,confirmedSeq: readState.snapshot?.lastReadSeq ?? 0,+ catchUp: () => feed.refetch(),})return <ForumViewforumChannelId={forumChannelId}diff --git a/src/web/src/components/community/channels/thread-channel-surface.test.ts b/src/web/src/components/community/channels/thread-channel-surface.test.tsindex 520e98bbb..fa3422e1f 100644--- a/src/web/src/components/community/channels/thread-channel-surface.test.ts+++ b/src/web/src/components/community/channels/thread-channel-surface.test.ts@@ -9,6 +9,7 @@ import { MessageContextSheet } from "../messages/message-context-sheet"import { MessageList } from "../messages/message-list"import { ThreadOpener } from "../messages/thread-opener"import { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"+import { useClaimThreadOpenerReadHandoff } from "@/hooks/community/thread-opener-read-handoff"import type { MessageChannelControllerValue } from "../messages/message-channel-controller"const mocks = vi.hoisted(() => ({@@ -30,6 +31,9 @@ vi.mock("@/lib/api/client", () => ({toastApiError: mocks.toastApiError,}))vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))+vi.mock("@/hooks/community/thread-opener-read-handoff", () => ({+ useClaimThreadOpenerReadHandoff: vi.fn(),+}))vi.mock("@/hooks/community/use-channel-message-feed", () => ({useChannelMessageFeed: vi.fn(),}))@@ -131,6 +135,7 @@ const mockedComposer = vi.mocked(Composer)const mockedMessageContextSheet = vi.mocked(MessageContextSheet)const mockedMessageList = vi.mocked(MessageList)const mockedUseChannelMessageFeed = vi.mocked(useChannelMessageFeed)+const mockedUseClaimThreadOpenerReadHandoff = vi.mocked(useClaimThreadOpenerReadHandoff)function feed(overrides: Record<string, unknown> = {}) {return {@@ -198,11 +203,29 @@ function renderSurface(overrides: Record<string, unknown> = {}) {describe("ThreadChannelSurface ownership", () => {beforeEach(() => {+ mockedUseClaimThreadOpenerReadHandoff.mockReset()mockedUseChannelMessageFeed.mockReturnValue(feed())mocks.apiFetch.mockResolvedValue({})mocks.editMessage.mockResolvedValue({})})+ it("installs the parent-opener claim hook before initializing the child feed", () => {+ const order: string[] = []+ const handoff = { nonce: "nonce-1" } as never+ mockedUseClaimThreadOpenerReadHandoff.mockImplementation(() => { order.push("claim") })+ mockedUseChannelMessageFeed.mockImplementation(() => {+ order.push("feed")+ return feed()+ })++ act(() => {+ TestRenderer.create(renderSurface({ threadOpenerHandoff: handoff, parentIsForum: true }))+ })++ expect(order.slice(0, 2)).toEqual(["claim", "feed"])+ expect(mockedUseClaimThreadOpenerReadHandoff).toHaveBeenCalledWith(handoff)+ })+afterEach(() => {vi.unstubAllGlobals()vi.clearAllMocks()diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsxindex ab059c734..1170d85c5 100644--- a/src/web/src/components/community/channels/thread-channel-surface.tsx+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx@@ -19,6 +19,10 @@ import type { OpenProfile } from "@/components/community/social/profile-types"import type { RightPanel } from "@/components/community/shell/panel-types"import type { ChannelMemberPanelProps } from "@/components/community/members/channel-member-view-model"import { tid } from "@/lib/community/testids"+import {+ useClaimThreadOpenerReadHandoff,+ type ThreadOpenerReadHandoff,+} from "@/hooks/community/thread-opener-read-handoff"const ignoreNestedThread = () => {}@@ -33,6 +37,7 @@ export function ThreadChannelSurface({parentMessageId,parentChannelName,parentIsForum,+ threadOpenerHandoff,childCreatorId,canRenameThread,headerServer,@@ -59,6 +64,7 @@ export function ThreadChannelSurface({parentMessageId: string | nullparentChannelName: stringparentIsForum: boolean+ threadOpenerHandoff?: ThreadOpenerReadHandoff | nullchildCreatorId?: string | nullcanRenameThread: booleanheaderServer?: { id: string; name: string; icon: string | null }@@ -84,6 +90,7 @@ export function ThreadChannelSurface({const [rightPanel, setRightPanel] = useState<RightPanel>(null)const [localName, setLocalName] = useState<string | null>(null)const { mutateAsync: editMessageAsync } = useEditMessage()+ useClaimThreadOpenerReadHandoff(threadOpenerHandoff)const feed = useChannelMessageFeed({channelId,serverId,diff --git a/src/web/src/components/community/shell/community-inbox-popover.test.ts b/src/web/src/components/community/shell/community-inbox-popover.test.tsindex 9c0bee986..c53c890d2 100644--- a/src/web/src/components/community/shell/community-inbox-popover.test.ts+++ b/src/web/src/components/community/shell/community-inbox-popover.test.ts@@ -34,7 +34,10 @@ function unreadFixture(): UnreadServer[] {type: "thread",lastMessageAt: "2026-08-07T10:00:00.000Z",mentionCount: 0,+ parentChannelId: "f1",openerMessageId: "m1",+ openerSeq: 7,+ openerUnread: true,},{channelId: "t1",@@ -48,30 +51,37 @@ function unreadFixture(): UnreadServer[] {}]}-function popover(onOpenChannel: ReturnType<typeof vi.fn>, onOpenForumThread: ReturnType<typeof vi.fn>) {+function popover(onOpenChannel: ReturnType<typeof vi.fn>, onOpenThread: ReturnType<typeof vi.fn>) {return React.createElement(InboxPopover, {unreads: unreadFixture(),unreadDms: [],mentions: [],marked: [],onOpenChannel,- onOpenForumThread,+ onOpenThread,})}-describe("InboxPopover forum post rows", () => {- it("requires the forum-thread callback so opener-backed buttons cannot be inert", () => {+describe("InboxPopover thread opener rows", () => {+ it("accepts the generic thread callback used by opener-backed buttons", () => {expectTypeOf<Parameters<typeof InboxPopover>[0]>().toMatchTypeOf<{- onOpenForumThread: (serverId: string, parentChannelId: string, childChannelId: string, openerMessageId: string) => void+ onOpenThread?: (+ serverId: string,+ parentChannelId: string,+ childChannelId: string,+ openerMessageId: string,+ openerSeq?: number,+ openerUnread?: boolean,+ ) => void}>()})it("renders the authoritative opener title and passes parent/opener targets", async () => {const onOpenChannel = vi.fn()- const onOpenForumThread = vi.fn()+ const onOpenThread = vi.fn()let renderer!: TestRenderer.ReactTestRendererawait act(async () => {- renderer = TestRenderer.create(popover(onOpenChannel, onOpenForumThread))+ renderer = TestRenderer.create(popover(onOpenChannel, onOpenThread))})const row = renderer.root@@ -80,16 +90,16 @@ describe("InboxPopover forum post rows", () => {expect(row).toBeDefined()await act(async () => row!.props.onClick())- expect(onOpenForumThread).toHaveBeenCalledWith("s1", "f1", "p1", "m1")+ expect(onOpenThread).toHaveBeenCalledWith("s1", "f1", "p1", "m1", 7, true)expect(onOpenChannel).not.toHaveBeenCalledWith("s1", "p1")})it("keeps reply-only child rows on the existing channel callback", async () => {const onOpenChannel = vi.fn()- const onOpenForumThread = vi.fn()+ const onOpenThread = vi.fn()let renderer!: TestRenderer.ReactTestRendererawait act(async () => {- renderer = TestRenderer.create(popover(onOpenChannel, onOpenForumThread))+ renderer = TestRenderer.create(popover(onOpenChannel, onOpenThread))})const row = renderer.root@@ -99,7 +109,7 @@ describe("InboxPopover forum post rows", () => {await act(async () => row!.props.onClick())expect(onOpenChannel).toHaveBeenCalledWith("s1", "t1", "f1")- expect(onOpenForumThread).not.toHaveBeenCalled()+ expect(onOpenThread).not.toHaveBeenCalled()})})@@ -121,7 +131,7 @@ describe("InboxPopover DM rows", () => {unreadDms: [dm],mentions: [],marked: [],- onOpenForumThread: vi.fn(),+ onOpenThread: vi.fn(),onOpenDm,}))})diff --git a/src/web/src/components/community/shell/community-inbox-popover.tsx b/src/web/src/components/community/shell/community-inbox-popover.tsxindex 4ab2b79a6..5261b1632 100644--- a/src/web/src/components/community/shell/community-inbox-popover.tsx+++ b/src/web/src/components/community/shell/community-inbox-popover.tsx@@ -20,12 +20,19 @@ function MentionBadge({ count }: { count: number }) {)}-function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenForumThread, onOpenDm }: {+function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenThread, onOpenDm }: {servers: UnreadServer[]dms: UnreadDm[]loading?: booleanonOpenChannel?: (serverId: string, channelId: string, parentChannelId?: string) => void- onOpenForumThread: (serverId: string, parentChannelId: string, childChannelId: string, openerMessageId: string) => void+ onOpenThread: (+ serverId: string,+ parentChannelId: string,+ childChannelId: string,+ openerMessageId: string,+ openerSeq?: number,+ openerUnread?: boolean,+ ) => voidonOpenDm?: (dm: UnreadDm) => void}) {const nothingUnread = servers.length === 0 && dms.length === 0@@ -72,7 +79,14 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenForumThread, odata-testid={tid.inboxUnreadChild(child.channelId)}onClick={() => {if (child.openerMessageId) {- onOpenForumThread(s.serverId, c.channelId, child.channelId, child.openerMessageId)+ onOpenThread(+ s.serverId,+ child.parentChannelId ?? c.channelId,+ child.channelId,+ child.openerMessageId,+ child.openerSeq,+ child.openerUnread,+ )} else {onOpenChannel?.(s.serverId, child.channelId, c.channelId)}@@ -191,6 +205,7 @@ export function InboxPopover({markedLoading,loading,onOpenChannel,+ onOpenThread,onOpenForumThread,onOpenDm,onOpenMention,@@ -207,7 +222,23 @@ export function InboxPopover({markedLoading?: booleanloading?: booleanonOpenChannel?: (serverId: string, channelId: string, parentChannelId?: string) => void- onOpenForumThread: (serverId: string, parentChannelId: string, childChannelId: string, openerMessageId: string) => void+ onOpenThread?: (+ serverId: string,+ parentChannelId: string,+ childChannelId: string,+ openerMessageId: string,+ openerSeq?: number,+ openerUnread?: boolean,+ ) => void+ /** Compatibility for non-community showcase fixtures; product wiring uses onOpenThread. */+ onOpenForumThread?: (+ serverId: string,+ parentChannelId: string,+ childChannelId: string,+ openerMessageId: string,+ openerSeq?: number,+ openerUnread?: boolean,+ ) => voidonOpenDm?: (dm: UnreadDm) => voidonOpenMention?: (m: Mention) => voidonOpenMarked?: (m: Marked) => void@@ -255,7 +286,14 @@ export function InboxPopover({<TabsTrigger value="marked">Marked</TabsTrigger></TabsList><TabsContent value="unreads" className="min-h-0 flex-1">- <UnreadsTab servers={unreads} dms={unreadDms} loading={loading} onOpenChannel={onOpenChannel} onOpenForumThread={onOpenForumThread} onOpenDm={onOpenDm} />+ <UnreadsTab+ servers={unreads}+ dms={unreadDms}+ loading={loading}+ onOpenChannel={onOpenChannel}+ onOpenThread={onOpenThread ?? onOpenForumThread ?? (() => {})}+ onOpenDm={onOpenDm}+ /></TabsContent><TabsContent value="mentions" className="min-h-0 flex-1"><MentionsTab mentions={mentions} loading={loading} onOpenMention={onOpenMention} onDeleteMention={onDeleteMention} />diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.test.tsindex ead4c4d94..efdca8531 100644--- a/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts@@ -11,6 +11,8 @@ const mocks = vi.hoisted(() => ({deleteMention: vi.fn(),unmark: vi.fn(),verifyDm: vi.fn(),+ armOpener: vi.fn(),+ clearOpener: vi.fn(),}))const unreadDm = {@@ -45,6 +47,10 @@ vi.mock("@/hooks/community/mutations", () => ({vi.mock("@/hooks/community/use-dm-route-verification", () => ({startDmRouteVerification: (...args: unknown[]) => mocks.verifyDm(...args),}))+vi.mock("@/hooks/community/thread-opener-read-handoff", () => ({+ armThreadOpenerReadHandoff: (...args: unknown[]) => mocks.armOpener(...args),+ clearThreadOpenerReadHandoff: (...args: unknown[]) => mocks.clearOpener(...args),+}))type Result = ReturnType<typeof useShellInboxController>@@ -65,11 +71,15 @@ async function renderController(initialDmCache: DmCache = { conversations: [{status: "offline" as const,preview: "",unread: true,-}] }) {+}] }, pushError?: Error) {const order: string[] = []const pushed: string[] = []const router = {- push: (href: string) => { order.push("push"); pushed.push(href) },+ push: (href: string) => {+ order.push("push")+ pushed.push(href)+ if (pushError) throw pushError+ },replace: vi.fn(),prefetch: vi.fn(),}@@ -107,9 +117,12 @@ async function renderController(initialDmCache: DmCache = { conversations: [{describe("useShellInboxController", () => {beforeEach(() => {mocks.markedEnabled.length = 0- for (const mock of [mocks.watch, mocks.markAll, mocks.deleteMention, mocks.unmark, mocks.verifyDm]) {+ for (const mock of [mocks.watch, mocks.markAll, mocks.deleteMention, mocks.unmark, mocks.verifyDm, mocks.armOpener, mocks.clearOpener]) {mock.mockReset()}+ mocks.armOpener.mockImplementation(() => {+ return "/c/channels/s1/child?inboxThreadOpener=nonce-1"+ })})it("keeps Marked lazy and latches it after first selection", async () => {@@ -167,7 +180,7 @@ describe("useShellInboxController", () => {it("preserves forum and mention watch keys and non-blocking routes", async () => {const hook = await renderController()hook.order.length = 0- await act(async () => hook.current.popoverProps.onOpenForumThread("s1", "forum", "child", "opener"))+ await act(async () => hook.current.popoverProps.onOpenThread("s1", "forum", "child", "opener"))expect(hook.order).toEqual(["watch", "cancel", "push"])expect(mocks.watch).toHaveBeenCalledWith("channel:child")expect(hook.pushed.at(-1)).toBe("/c/channels/s1/child")@@ -180,6 +193,64 @@ describe("useShellInboxController", () => {expect(hook.pushed.at(-1)).toBe("/c/channels/s1/c1")})+ it("arms a genuine unread opener after watch/cancel and before pushing its nonce URL", async () => {+ const hook = await renderController()+ mocks.armOpener.mockImplementation(() => {+ hook.order.push("arm")+ return "/c/channels/s1/child?inboxThreadOpener=nonce-1"+ })+ hook.order.length = 0++ await act(async () => hook.current.popoverProps.onOpenThread(+ "s1",+ "forum",+ "child",+ "opener-7",+ 7,+ true,+ ))++ expect(hook.order).toEqual(["watch", "cancel", "arm", "push"])+ expect(mocks.armOpener).toHaveBeenCalledWith(expect.anything(), {+ serverId: "s1",+ parentChannelId: "forum",+ childChannelId: "child",+ openerMessageId: "opener-7",+ openerSeq: 7,+ })+ expect(hook.pushed.at(-1)).toBe("/c/channels/s1/child?inboxThreadOpener=nonce-1")+ expect(mocks.clearOpener).not.toHaveBeenCalled()+ })++ it("clears an obsolete handoff for an ordinary child navigation", async () => {+ const hook = await renderController()+ await act(async () => hook.current.popoverProps.onOpenThread(+ "s1",+ "forum",+ "child",+ "opener-7",+ 7,+ false,+ ))+ expect(mocks.armOpener).not.toHaveBeenCalled()+ expect(mocks.clearOpener).toHaveBeenCalledWith(expect.anything())+ expect(hook.pushed.at(-1)).toBe("/c/channels/s1/child")+ })++ it("clears the armed opener when router.push fails synchronously", async () => {+ const error = new Error("push failed")+ const hook = await renderController(undefined, error)+ await expect(act(async () => hook.current.popoverProps.onOpenThread(+ "s1",+ "forum",+ "child",+ "opener-7",+ 7,+ true,+ ))).rejects.toThrow("push failed")+ expect(mocks.clearOpener).toHaveBeenCalledWith(expect.anything())+ })+it("routes marked rows by server/DM with optional seq and exact watch keys", async () => {const hook = await renderController()await act(async () => hook.current.popoverProps.onOpenMarked?.({diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.tsindex cb2b750c3..093ab00cf 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@@ -16,6 +16,10 @@ import {import type { InboxPopover } from "./community-inbox-popover"import type { QueryClient } from "@tanstack/react-query"import type { ShellRouter } from "./shell-frame-types"+import {+ armThreadOpenerReadHandoff,+ clearThreadOpenerReadHandoff,+} from "@/hooks/community/thread-opener-read-handoff"type Options = {router: ShellRouter@@ -50,23 +54,44 @@ export function useShellInboxController({) => {watchInboxItem(watchKey)cancelPendingNavigation()+ clearThreadOpenerReadHandoff(queryClient)router.push(channelHref(serverId, channelId))- }, [cancelPendingNavigation, router, watchInboxItem])+ }, [cancelPendingNavigation, queryClient, router, watchInboxItem])- const openForumThread = useCallback((+ const openThread = useCallback((serverId: string,parentChannelId: string,childChannelId: string,- _openerMessageId: string,+ openerMessageId: string,+ openerSeq?: number,+ openerUnread?: boolean,) => {watchInboxItem(`channel:${childChannelId}`)cancelPendingNavigation()- router.push(channelHref(serverId, childChannelId))- }, [cancelPendingNavigation, router, watchInboxItem])+ const href = openerUnread === true && openerSeq !== undefined+ ? armThreadOpenerReadHandoff(queryClient, {+ serverId,+ parentChannelId: parentChannelId,+ childChannelId,+ openerMessageId,+ openerSeq,+ })+ : channelHref(serverId, childChannelId)+ if (openerUnread !== true || openerSeq === undefined) {+ clearThreadOpenerReadHandoff(queryClient)+ }+ try {+ router.push(href)+ } catch (error) {+ clearThreadOpenerReadHandoff(queryClient)+ throw error+ }+ }, [cancelPendingNavigation, queryClient, router, watchInboxItem])const openMarked = useCallback((marked: Marked) => {watchInboxItem(`marked:${marked.id}`)cancelPendingNavigation()+ clearThreadOpenerReadHandoff(queryClient)const seqQuery = marked.m.seq != null ? `?seq=${marked.m.seq}` : ""if (marked.serverId) {const channelPath = channelHref(marked.serverId, marked.channelId)@@ -74,7 +99,7 @@ export function useShellInboxController({} else {router.push(`/c/me/${marked.channelId}${seqQuery}`)}- }, [cancelPendingNavigation, router, watchInboxItem])+ }, [cancelPendingNavigation, queryClient, router, watchInboxItem])const openDm = useCallback((dm: UnreadDm) => {const dmId = dm.channelId@@ -85,6 +110,7 @@ export function useShellInboxController({)watchInboxItem(`dm:${dmId}`)cancelPendingNavigation()+ clearThreadOpenerReadHandoff(queryClient)router.push(`/c/me/${dmId}`)void startDmRouteVerification(queryClient, dmId).catch(() => undefined)}, [cancelPendingNavigation, queryClient, router, watchInboxItem])@@ -97,7 +123,7 @@ export function useShellInboxController({markedLoading: inboxMarked.isLoading,loading,onOpenChannel: openServerChannel,- onOpenForumThread: openForumThread,+ onOpenThread: openThread,onOpenDm: openDm,onOpenMention: (mention) => {if (mention.serverId && mention.channelId) {diff --git a/src/web/src/hooks/community/community-ws/message-events.test.ts b/src/web/src/hooks/community/community-ws/message-events.test.tsindex f7700d3b9..46bed4403 100644--- a/src/web/src/hooks/community/community-ws/message-events.test.ts+++ b/src/web/src/hooks/community/community-ws/message-events.test.ts@@ -12,6 +12,13 @@ import {releaseReadSurface,submitReadIntent,} from "@/hooks/community/read-coordinator"+import {+ promoteInboxReadReservation,+ registerInboxReadReservationSurface,+ releaseInboxReadReservationSurface,+ reserveInboxUnreadsResponse,+ settleInboxReadReservationGeneration,+} from "@/hooks/community/inbox-read-reservation"import {capturedOnMessage,capturedQueryClient,@@ -517,6 +524,103 @@ describe("useCommunityWs — message.create", () => {}})+ it("arms one exact focused candidate before scheduling its inbox refresh", async () => {+ vi.useFakeTimers()+ try {+ await mountHook({ viewerUserId: "u_me" })+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().subscribe({ channelId: "ch_focused" })+ const order: string[] = []+ const lease = registerInboxReadReservationSurface(+ capturedQueryClient,+ "ch_focused",+ (candidate) => {+ if (candidate) order.push("candidate")+ },+ )+ const originalInvalidate = capturedQueryClient.invalidateQueries.bind(capturedQueryClient)+ vi.spyOn(capturedQueryClient, "invalidateQueries")+ .mockImplementation((filters, options) => {+ const key = filters.queryKey as unknown[] | undefined+ if (Array.isArray(key) && key.includes("inbox")) order.push("inbox-refresh")+ return originalInvalidate(filters, options)+ })+ const event = messageCreate("ch_focused", "m_focused")++ capturedOnMessage!(event)+ capturedOnMessage!(event)+ expect(order).toEqual(["candidate"])++ await vi.advanceTimersByTimeAsync(500)+ await vi.waitFor(() => expect(order).toContain("inbox-refresh"))+ expect(order.indexOf("candidate")).toBeLessThan(order.indexOf("inbox-refresh"))+ releaseInboxReadReservationSurface(lease)+ } finally {+ vi.useRealTimers()+ }+ })++ it("does not re-arm a committed candidate when reconnect replays the seen message", async () => {+ await mountHook({ viewerUserId: "u_me" })+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().subscribe({ channelId: "ch_focused" })+ const seen = vi.fn()+ const lease = registerInboxReadReservationSurface(+ capturedQueryClient,+ "ch_focused",+ seen,+ )+ const event = messageCreate("ch_focused", "m_committed")++ capturedOnMessage!(event)+ expect(promoteInboxReadReservation(lease, 20)).toBe(true)+ await settleInboxReadReservationGeneration(+ capturedQueryClient,+ 20,+ true,+ "ch_focused",+ )+ seen.mockClear()++ capturedOnMessage!(event)++ expect(seen).not.toHaveBeenCalled()+ await expect(reserveInboxUnreadsResponse(capturedQueryClient, {+ servers: [{+ channels: [{+ channelId: "ch_focused",+ lastMessageAt: event.message.createdAt,+ hasDirectUnread: true,+ children: [],+ }],+ }],+ dms: [],+ })).rejects.toMatchObject({ name: "AbortError" })+ releaseInboxReadReservationSurface(lease)+ })++ it("does not arm self-authored or unfocused message candidates", async () => {+ await mountHook({ viewerUserId: "u_author" })+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().subscribe({ channelId: "ch_focused" })+ const seen: string[] = []+ const lease = registerInboxReadReservationSurface(+ capturedQueryClient,+ "ch_focused",+ (candidate) => {+ if (candidate) seen.push(candidate.channelId)+ },+ )++ capturedOnMessage!(messageCreate("ch_focused", "m_self"))+ const background = messageCreate("ch_background", "m_background")+ background.message.authorId = "u_other"+ capturedOnMessage!(background)++ expect(seen).toEqual([])+ releaseInboxReadReservationSurface(lease)+ })+it("holds a focused refresh until the visible read reconciles authoritatively", async () => {vi.useFakeTimers()try {diff --git a/src/web/src/hooks/community/community-ws/message-events.ts b/src/web/src/hooks/community/community-ws/message-events.tsindex c9908da80..f74d9071e 100644--- a/src/web/src/hooks/community/community-ws/message-events.ts+++ b/src/web/src/hooks/community/community-ws/message-events.ts@@ -21,6 +21,7 @@ import { reconcileForumOpenerTitle } from "@/hooks/community/forum-opener-title-import { clearTypingIndicator, typingScopeKey } from "@/hooks/community/community-ws/typing"import type { MessageEventContext } from "@/hooks/community/community-ws/handler-context"import { scheduleFocusedMessageGapRepair } from "@/hooks/community/community-ws/reconnect-messages"+import { armInboxReadReservationCandidate } from "@/hooks/community/inbox-read-reservation"import {projectApprovalCopies,projectEditedCopies,@@ -50,6 +51,16 @@ export function handleMessageCreate(projection,}: MessageEventContext,) {+ const viewerId = viewerUserIdRef.current+ const hasSeenMessage = wsStore.hasSeenMessage(event.message.id)+ const isForeignFocused = event.message.authorId !== viewerId+ && (event.channelId === sub.channelId || event.channelId === sub.dmConversationId)+ if (isForeignFocused && !hasSeenMessage) {+ armInboxReadReservationCandidate(queryClient, {+ channelId: event.channelId,+ lastMessageAt: event.message.createdAt,+ })+ }const projected = projectCommunityMessageCreate(event.message)if (event.channelId === sub.channelId) {const serverId = useCommunityStore.getState().currentServerId@@ -76,11 +87,10 @@ export function handleMessageCreate({ type: "wsMessage", message: projected },)}- const viewerId = viewerUserIdRef.currentif (deliveryMode === "batch" && event.message.authorId !== viewerId) {scheduleInboxInvalidate({ inbox: true, dms: true })}- if (wsStore.hasSeenMessage(event.message.id)) return+ if (hasSeenMessage) returnwsStore.markSeenMessage(event.message.id)// Sending a message is an implicit typing.stop for its author —// clear once we know this is a fresh message. Clearing before dedupdiff --git a/src/web/src/hooks/community/inbox-read-reservation.test.ts b/src/web/src/hooks/community/inbox-read-reservation.test.tsnew file mode 100644index 000000000..11fa7af9b--- /dev/null+++ b/src/web/src/hooks/community/inbox-read-reservation.test.ts@@ -0,0 +1,742 @@+import type { QueryClient } from "@tanstack/react-query"+import { beforeEach, describe, expect, it, vi } from "vitest"+import {+ armInboxReadReservationCandidate,+ armThreadOpenerReservationHandoff,+ clearThreadOpenerReservationHandoff,+ completeThreadOpenerReservationHandoff,+ disposeInboxReadReservation,+ getThreadOpenerReservationHandoff,+ promoteInboxReadReservation,+ registerThreadOpenerRouteLease,+ registerInboxReadReservationSurface,+ releaseThreadOpenerRouteLease,+ releaseInboxReadReservationSurface,+ reserveInboxUnreadsResponse,+ settleInboxReadReservationGeneration,+ takeInboxReadReservationNegative,+ terminateThreadOpenerReservationHandoff,+} from "./inbox-read-reservation"++function client() {+ return {+ cancelQueries: vi.fn().mockResolvedValue(undefined),+ refetchQueries: vi.fn().mockResolvedValue(undefined),+ } as unknown as QueryClient+}++function response(channelId = "focused", lastMessageAt = "2026-08-27T01:00:00.000Z") {+ return {+ servers: [{+ channels: [{+ channelId,+ lastMessageAt,+ hasDirectUnread: true,+ children: [],+ }],+ }],+ dms: [{ channelId: "background-dm", lastMessageAt: "2026-08-27T02:00:00.000Z" }],+ }+}++function openerResponse() {+ return {+ servers: [{+ channels: [{+ channelId: "forum",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ children: [{+ channelId: "child",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ openerMessageId: "opener-7",+ openerSeq: 7,+ openerUnread: true,+ }],+ }],+ }],+ dms: [],+ }+}++describe("inbox read reservation", () => {+ let queryClient: QueryClient++ beforeEach(() => {+ queryClient = client()+ })++ it("passes unrelated responses through and holds a focused response unchanged", async () => {+ const seen = vi.fn()+ registerInboxReadReservationSurface(queryClient, "focused", seen)+ const unrelated = response("other")+ await expect(reserveInboxUnreadsResponse(queryClient, unrelated)).resolves.toBe(unrelated)++ seen.mockClear()+ const focused = response()+ const pending = reserveInboxUnreadsResponse(queryClient, focused)+ let settled = false+ void pending.then(() => { settled = true }, () => { settled = true })+ await Promise.resolve()++ expect(settled).toBe(false)+ expect(seen).toHaveBeenCalledTimes(1)+ expect(seen).toHaveBeenCalledWith(expect.objectContaining({+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ }))+ disposeInboxReadReservation(queryClient)+ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ })++ it("classifies and fingerprints a focused DM response", async () => {+ const seen = vi.fn()+ registerInboxReadReservationSurface(queryClient, "background-dm", seen)+ const pending = reserveInboxUnreadsResponse(queryClient, response())+ void pending.catch(() => undefined)++ expect(seen).toHaveBeenCalledWith(expect.objectContaining({+ channelId: "background-dm",+ lastMessageAt: "2026-08-27T02:00:00.000Z",+ openerUnread: false,+ fingerprint: expect.stringContaining("background-dm"),+ }))+ disposeInboxReadReservation(queryClient)+ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ })++ it("promotes the held epoch to the exact committed generation", async () => {+ const lease = registerInboxReadReservationSurface(queryClient, "focused", vi.fn())+ const pending = reserveInboxUnreadsResponse(queryClient, response())+ void pending.catch(() => undefined)++ expect(promoteInboxReadReservation(lease, 11)).toBe(true)+ await settleInboxReadReservationGeneration(queryClient, 10, true, "focused")+ expect((queryClient.cancelQueries as ReturnType<typeof vi.fn>)).not.toHaveBeenCalled()++ await settleInboxReadReservationGeneration(queryClient, 11, true, "focused")+ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ expect(queryClient.cancelQueries).toHaveBeenCalledTimes(1)+ expect(queryClient.refetchQueries).not.toHaveBeenCalled()+ })++ it("keeps a focused WS candidate classified when the response arrives later", async () => {+ const seen = vi.fn()+ const lease = registerInboxReadReservationSurface(queryClient, "focused", seen)++ expect(armInboxReadReservationCandidate(queryClient, {+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ })).toBe(true)+ expect(promoteInboxReadReservation(lease, 12)).toBe(true)+ seen.mockClear()+ const pending = reserveInboxUnreadsResponse(queryClient, response())+ void pending.catch(() => undefined)++ expect(seen).toHaveBeenCalledTimes(1)+ expect(seen).toHaveBeenCalledWith(expect.objectContaining({+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ }))+ await settleInboxReadReservationGeneration(queryClient, 12, true, "focused")+ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ })++ it("discards an exact response that arrives after its committed generation", async () => {+ const lease = registerInboxReadReservationSurface(queryClient, "focused", vi.fn())+ armInboxReadReservationCandidate(queryClient, {+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ })+ promoteInboxReadReservation(lease, 13)++ await settleInboxReadReservationGeneration(queryClient, 13, true, "focused")++ await expect(reserveInboxUnreadsResponse(queryClient, response())).rejects.toMatchObject({+ name: "AbortError",+ })+ const later = reserveInboxUnreadsResponse(+ queryClient,+ response("focused", "2026-08-27T01:00:01.000Z"),+ )+ let laterSettled = false+ void later.then(() => { laterSettled = true }, () => { laterSettled = true })+ await Promise.resolve()+ expect(laterSettled).toBe(false)+ disposeInboxReadReservation(queryClient)+ await expect(later).rejects.toMatchObject({ name: "AbortError" })+ })++ it("grants a negative permit only to the exact armed identity", async () => {+ const lease = registerInboxReadReservationSurface(queryClient, "focused", vi.fn())+ const exact = response()+ armInboxReadReservationCandidate(queryClient, {+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ })++ expect(takeInboxReadReservationNegative(lease)).toBe(true)+ await Promise.resolve()+ await expect(reserveInboxUnreadsResponse(queryClient, exact)).resolves.toBe(exact)++ const later = response("focused", "2026-08-27T01:00:01.000Z")+ const held = reserveInboxUnreadsResponse(queryClient, later)+ void held.catch(() => undefined)+ await Promise.resolve()+ disposeInboxReadReservation(queryClient)+ await expect(held).rejects.toMatchObject({ name: "AbortError" })+ })++ it("supersedes an old permit and ignores unfocused or released arms", async () => {+ const seen = vi.fn()+ const lease = registerInboxReadReservationSurface(queryClient, "focused", seen)+ expect(armInboxReadReservationCandidate(queryClient, {+ channelId: "other",+ lastMessageAt: "t-other",+ })).toBe(false)+ armInboxReadReservationCandidate(queryClient, {+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ })+ takeInboxReadReservationNegative(lease)+ armInboxReadReservationCandidate(queryClient, {+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:01.000Z",+ })++ const stale = reserveInboxUnreadsResponse(queryClient, response())+ void stale.catch(() => undefined)+ await Promise.resolve()+ releaseInboxReadReservationSurface(lease)+ expect(armInboxReadReservationCandidate(queryClient, {+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:02.000Z",+ })).toBe(false)+ await expect(stale).rejects.toMatchObject({ name: "AbortError" })+ })++ it("cancels a held armed identity when a newer focused candidate supersedes it", async () => {+ registerInboxReadReservationSurface(queryClient, "focused", vi.fn())+ armInboxReadReservationCandidate(queryClient, {+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ })+ const stale = reserveInboxUnreadsResponse(queryClient, response())+ void stale.catch(() => undefined)++ expect(armInboxReadReservationCandidate(queryClient, {+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:01.000Z",+ })).toBe(true)++ await expect(stale).rejects.toMatchObject({ name: "AbortError" })+ disposeInboxReadReservation(queryClient)+ })++ it("discards a late superseded response without rebinding the newer focused generation", async () => {+ const seen = vi.fn()+ const lease = registerInboxReadReservationSurface(queryClient, "focused", seen)+ armInboxReadReservationCandidate(queryClient, {+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ })+ promoteInboxReadReservation(lease, 18)+ await settleInboxReadReservationGeneration(queryClient, 18, true, "focused")++ armInboxReadReservationCandidate(queryClient, {+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:01.000Z",+ })+ seen.mockClear()++ await expect(reserveInboxUnreadsResponse(queryClient, response())).rejects.toMatchObject({+ name: "AbortError",+ })+ expect(seen).not.toHaveBeenCalled()++ const current = reserveInboxUnreadsResponse(+ queryClient,+ response("focused", "2026-08-27T01:00:01.000Z"),+ )+ void current.catch(() => undefined)+ expect(seen).toHaveBeenLastCalledWith(expect.objectContaining({+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:01.000Z",+ }))+ expect(promoteInboxReadReservation(lease, 19)).toBe(true)++ await settleInboxReadReservationGeneration(queryClient, 18, true, "focused")+ let settled = false+ void current.then(() => { settled = true }, () => { settled = true })+ await Promise.resolve()+ expect(settled).toBe(false)++ await settleInboxReadReservationGeneration(queryClient, 19, true, "focused")+ await expect(current).rejects.toMatchObject({ name: "AbortError" })+ })++ it("adopts a newer response as the active identity without inheriting the older generation", async () => {+ const seen = vi.fn()+ const lease = registerInboxReadReservationSurface(queryClient, "focused", seen)+ armInboxReadReservationCandidate(queryClient, {+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:01.000Z",+ })+ const previous = reserveInboxUnreadsResponse(+ queryClient,+ response("focused", "2026-08-27T01:00:01.000Z"),+ )+ void previous.catch(() => undefined)+ promoteInboxReadReservation(lease, 20)+ seen.mockClear()++ const current = reserveInboxUnreadsResponse(+ queryClient,+ response("focused", "2026-08-27T01:00:02.000Z"),+ )+ void current.catch(() => undefined)++ expect(seen).toHaveBeenCalledTimes(1)+ expect(seen).toHaveBeenCalledWith(expect.objectContaining({+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:02.000Z",+ }))+ await expect(previous).rejects.toMatchObject({ name: "AbortError" })++ await settleInboxReadReservationGeneration(queryClient, 20, true, "focused")+ let settled = false+ void current.then(() => { settled = true }, () => { settled = true })+ await Promise.resolve()+ expect(settled).toBe(false)++ expect(promoteInboxReadReservation(lease, 21)).toBe(true)+ await settleInboxReadReservationGeneration(queryClient, 21, true, "focused")+ await expect(current).rejects.toMatchObject({ name: "AbortError" })+ })++ it("keeps an enriched thread response through a sparse replay of the same WS identity", async () => {+ const lease = registerInboxReadReservationSurface(queryClient, "child", vi.fn())+ armInboxReadReservationCandidate(queryClient, {+ channelId: "child",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ })+ const pending = reserveInboxUnreadsResponse(queryClient, openerResponse())+ void pending.catch(() => undefined)+ expect(promoteInboxReadReservation(lease, 22)).toBe(true)++ expect(armInboxReadReservationCandidate(queryClient, {+ channelId: "child",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ })).toBe(false)++ await settleInboxReadReservationGeneration(queryClient, 22, true, "child")+ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ })++ it("supersedes an enriched thread identity when opener metadata conflicts", async () => {+ registerInboxReadReservationSurface(queryClient, "child", vi.fn())+ armInboxReadReservationCandidate(queryClient, {+ channelId: "child",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ openerMessageId: "opener-7",+ openerSeq: 7,+ })+ const pending = reserveInboxUnreadsResponse(queryClient, openerResponse())+ void pending.catch(() => undefined)++ expect(armInboxReadReservationCandidate(queryClient, {+ channelId: "child",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ openerMessageId: "opener-8",+ openerSeq: 8,+ })).toBe(true)++ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ disposeInboxReadReservation(queryClient)+ })++ it("lets a newer identity revoke a committed-response discard", async () => {+ const lease = registerInboxReadReservationSurface(queryClient, "focused", vi.fn())+ armInboxReadReservationCandidate(queryClient, {+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ openerMessageId: "opener-old",+ openerSeq: 7,+ })+ promoteInboxReadReservation(lease, 14)+ await settleInboxReadReservationGeneration(queryClient, 14, true, "focused")++ expect(armInboxReadReservationCandidate(queryClient, {+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:01.000Z",+ })).toBe(true)+ const stale = reserveInboxUnreadsResponse(queryClient, response())+ void stale.catch(() => undefined)+ await Promise.resolve()+ disposeInboxReadReservation(queryClient)+ await expect(stale).rejects.toMatchObject({ name: "AbortError" })+ })++ it("grants an exact permit when an armed generation fails before its response", async () => {+ const lease = registerInboxReadReservationSurface(queryClient, "focused", vi.fn())+ armInboxReadReservationCandidate(queryClient, {+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ })+ promoteInboxReadReservation(lease, 15)++ await settleInboxReadReservationGeneration(queryClient, 15, false, "focused")++ const exact = response()+ await expect(reserveInboxUnreadsResponse(queryClient, exact)).resolves.toBe(exact)+ expect(queryClient.refetchQueries).toHaveBeenCalledOnce()+ })++ it("clears a committed-response discard when its route lease releases", async () => {+ const lease = registerInboxReadReservationSurface(queryClient, "focused", vi.fn())+ armInboxReadReservationCandidate(queryClient, {+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ })+ promoteInboxReadReservation(lease, 16)+ await settleInboxReadReservationGeneration(queryClient, 16, true, "focused")++ releaseInboxReadReservationSurface(lease)++ await Promise.resolve()+ expect(queryClient.refetchQueries).not.toHaveBeenCalled()+ })++ it("clears an armed generation after its matching held response fails", async () => {+ const lease = registerInboxReadReservationSurface(queryClient, "focused", vi.fn())+ armInboxReadReservationCandidate(queryClient, {+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ })+ const pending = reserveInboxUnreadsResponse(queryClient, response())+ void pending.catch(() => undefined)+ promoteInboxReadReservation(lease, 17)++ await settleInboxReadReservationGeneration(queryClient, 17, false, "focused")++ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ expect(queryClient.refetchQueries).toHaveBeenCalledOnce()+ })++ it("consumes a handoff negative permit and clears its matching focused identity", async () => {+ registerInboxReadReservationSurface(queryClient, "child", vi.fn())+ armInboxReadReservationCandidate(queryClient, {+ channelId: "child",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ })+ armThreadOpenerReservationHandoff(queryClient, {+ nonce: "nonce-focused-negative",+ serverId: "server",+ parentChannelId: "forum",+ childChannelId: "child",+ openerMessageId: "opener-7",+ openerSeq: 7,+ })+ const data = openerResponse()+ const pending = reserveInboxUnreadsResponse(queryClient, data)+ void pending.catch(() => undefined)++ expect(terminateThreadOpenerReservationHandoff(+ queryClient,+ "nonce-focused-negative",+ )).toBe(true)+ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ await expect(reserveInboxUnreadsResponse(queryClient, data)).resolves.toBe(data)+ })++ it("publishes only one matching authoritative response after a negative decision", async () => {+ const lease = registerInboxReadReservationSurface(queryClient, "focused", vi.fn())+ const data = response()+ const pending = reserveInboxUnreadsResponse(queryClient, data)+ void pending.catch(() => undefined)++ expect(takeInboxReadReservationNegative(lease)).toBe(true)+ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ await Promise.resolve()+ expect(queryClient.refetchQueries).toHaveBeenCalledTimes(1)+ await expect(reserveInboxUnreadsResponse(queryClient, data)).resolves.toBe(data)++ const heldAgain = reserveInboxUnreadsResponse(queryClient, data)+ let settled = false+ void heldAgain.then(() => { settled = true }, () => { settled = true })+ await Promise.resolve()+ expect(settled).toBe(false)+ disposeInboxReadReservation(queryClient)+ })++ it("publishes the next focused response when failure settles before the payload arrives", async () => {+ registerInboxReadReservationSurface(queryClient, "focused", vi.fn())++ await settleInboxReadReservationGeneration(queryClient, 17, false, "focused")+ expect(queryClient.cancelQueries).toHaveBeenCalledOnce()+ expect(queryClient.refetchQueries).toHaveBeenCalledOnce()++ const data = response()+ await expect(reserveInboxUnreadsResponse(queryClient, data)).resolves.toBe(data)+ const heldAgain = reserveInboxUnreadsResponse(queryClient, data)+ let settled = false+ void heldAgain.then(() => { settled = true }, () => { settled = true })+ await Promise.resolve()+ expect(settled).toBe(false)+ disposeInboxReadReservation(queryClient)+ })++ it("reclassifies a held account payload under a same-commit route replacement", async () => {+ const oldSeen = vi.fn()+ const nextSeen = vi.fn()+ const oldLease = registerInboxReadReservationSurface(queryClient, "old", oldSeen)+ const data = {+ servers: [{ channels: [+ { channelId: "old", lastMessageAt: "t-old", hasDirectUnread: true, children: [] },+ { channelId: "next", lastMessageAt: "t-next", hasDirectUnread: true, children: [] },+ ] }],+ dms: [],+ }+ const pending = reserveInboxUnreadsResponse(queryClient, data)+ void pending.catch(() => undefined)+ releaseInboxReadReservationSurface(oldLease)+ registerInboxReadReservationSurface(queryClient, "next", nextSeen)+ await Promise.resolve()++ expect(nextSeen).toHaveBeenCalledWith(expect.objectContaining({+ channelId: "next",+ lastMessageAt: "t-next",+ }))+ expect(queryClient.refetchQueries).not.toHaveBeenCalled()+ disposeInboxReadReservation(queryClient)+ })++ it("negatively releases a held payload when its replacement surface has no candidate", async () => {+ const oldLease = registerInboxReadReservationSurface(queryClient, "old", vi.fn())+ const pending = reserveInboxUnreadsResponse(queryClient, response("old", "t-old"))+ void pending.catch(() => undefined)++ releaseInboxReadReservationSurface(oldLease)+ registerInboxReadReservationSurface(queryClient, "missing", vi.fn())+ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ await Promise.resolve()++ expect(queryClient.refetchQueries).toHaveBeenCalledOnce()+ })++ it("reclassifies old-to-target under an exact route lease before awaiting the claim", async () => {+ armThreadOpenerReservationHandoff(queryClient, {+ nonce: "nonce-reclassify",+ serverId: "server",+ parentChannelId: "forum",+ childChannelId: "child",+ openerMessageId: "opener-7",+ openerSeq: 7,+ })+ const oldLease = registerInboxReadReservationSurface(queryClient, "old", vi.fn())+ const data = {+ servers: [{ channels: [+ { channelId: "old", lastMessageAt: "t-old", hasDirectUnread: true, children: [] },+ ...openerResponse().servers[0]!.channels,+ { channelId: "unrelated", lastMessageAt: "t-new", hasDirectUnread: true, children: [] },+ ] }],+ dms: [],+ }+ const pending = reserveInboxUnreadsResponse(queryClient, data)+ void pending.catch(() => undefined)+ registerThreadOpenerRouteLease(queryClient, "nonce-reclassify", "server", "child")++ releaseInboxReadReservationSurface(oldLease)+ const childLease = registerInboxReadReservationSurface(queryClient, "child", vi.fn())++ expect(getThreadOpenerReservationHandoff(queryClient, "nonce-reclassify")?.phase)+ .toBe("awaiting-opener-claim")+ expect(takeInboxReadReservationNegative(childLease)).toBe(false)+ expect(completeThreadOpenerReservationHandoff(+ queryClient,+ "nonce-reclassify",+ 41,+ )).toBe(true)+ await settleInboxReadReservationGeneration(queryClient, 41, true, "forum")+ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ expect(queryClient.refetchQueries).not.toHaveBeenCalled()+ })++ it("blocks child negative release until an exact opener claim transfers ownership", async () => {+ armThreadOpenerReservationHandoff(queryClient, {+ nonce: "nonce-1",+ serverId: "server",+ parentChannelId: "forum",+ childChannelId: "child",+ openerMessageId: "opener-7",+ openerSeq: 7,+ })+ const lease = registerInboxReadReservationSurface(queryClient, "child", vi.fn())+ const pending = reserveInboxUnreadsResponse(queryClient, openerResponse())+ void pending.catch(() => undefined)++ expect(getThreadOpenerReservationHandoff(queryClient, "nonce-1")?.phase)+ .toBe("armed")+ registerThreadOpenerRouteLease(queryClient, "nonce-1", "server", "child")+ expect(getThreadOpenerReservationHandoff(queryClient, "nonce-1")?.phase)+ .toBe("awaiting-opener-claim")+ expect(takeInboxReadReservationNegative(lease)).toBe(false)+ expect(queryClient.refetchQueries).not.toHaveBeenCalled()+ expect(completeThreadOpenerReservationHandoff(queryClient, "nonce-1", 23)).toBe(true)+ expect(promoteInboxReadReservation(lease, 24)).toBe(true)++ await settleInboxReadReservationGeneration(queryClient, 23, true, "forum")+ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ expect(queryClient.refetchQueries).not.toHaveBeenCalled()+ })++ it("awaits a claim when the exact route lease exists before the response", async () => {+ armThreadOpenerReservationHandoff(queryClient, {+ nonce: "nonce-lease-first",+ serverId: "server",+ parentChannelId: "forum",+ childChannelId: "child",+ openerMessageId: "opener-7",+ openerSeq: 7,+ })+ const lease = registerInboxReadReservationSurface(queryClient, "child", vi.fn())+ registerThreadOpenerRouteLease(queryClient, "nonce-lease-first", "server", "child")+ const pending = reserveInboxUnreadsResponse(queryClient, openerResponse())+ void pending.catch(() => undefined)++ expect(getThreadOpenerReservationHandoff(queryClient, "nonce-lease-first")?.phase)+ .toBe("awaiting-opener-claim")+ expect(takeInboxReadReservationNegative(lease)).toBe(false)+ disposeInboxReadReservation(queryClient)+ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ })++ it("removes an aborted held response exactly once", async () => {+ registerInboxReadReservationSurface(queryClient, "focused", vi.fn())+ const controller = new AbortController()+ const pending = reserveInboxUnreadsResponse(queryClient, response(), controller.signal)+ controller.abort()++ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ disposeInboxReadReservation(queryClient)+ expect(queryClient.refetchQueries).not.toHaveBeenCalled()+ })++ it("clears as a no-op when no handoff is active", () => {+ expect(clearThreadOpenerReservationHandoff(queryClient)).toBe(false)+ expect(queryClient.refetchQueries).not.toHaveBeenCalled()+ })++ it("does not let an orphaned nonce gate a later direct visit to the same child", async () => {+ armThreadOpenerReservationHandoff(queryClient, {+ nonce: "nonce-orphan",+ serverId: "server",+ parentChannelId: "forum",+ childChannelId: "child",+ openerMessageId: "opener-7",+ openerSeq: 7,+ })+ const lease = registerInboxReadReservationSurface(queryClient, "child", vi.fn())+ const data = openerResponse()+ const pending = reserveInboxUnreadsResponse(queryClient, data)+ void pending.catch(() => undefined)++ expect(getThreadOpenerReservationHandoff(queryClient, "nonce-orphan")?.phase)+ .toBe("armed")+ expect(takeInboxReadReservationNegative(lease)).toBe(true)+ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ await Promise.resolve()+ expect(getThreadOpenerReservationHandoff(queryClient, "nonce-orphan")).toBeNull()+ expect(queryClient.refetchQueries).toHaveBeenCalledOnce()+ await expect(reserveInboxUnreadsResponse(queryClient, data)).resolves.toBe(data)+ })++ it("binds a matching response that arrives after the opener claim to the parent generation", async () => {+ armThreadOpenerReservationHandoff(queryClient, {+ nonce: "nonce-after-claim",+ serverId: "server",+ parentChannelId: "forum",+ childChannelId: "child",+ openerMessageId: "opener-7",+ openerSeq: 7,+ })+ const lease = registerInboxReadReservationSurface(queryClient, "child", vi.fn())++ expect(completeThreadOpenerReservationHandoff(+ queryClient,+ "nonce-after-claim",+ 23,+ )).toBe(true)+ const pending = reserveInboxUnreadsResponse(queryClient, openerResponse())+ void pending.catch(() => undefined)++ expect(takeInboxReadReservationNegative(lease)).toBe(true)+ expect(promoteInboxReadReservation(lease, 24)).toBe(true)+ expect(queryClient.refetchQueries).not.toHaveBeenCalled()++ await settleInboxReadReservationGeneration(queryClient, 23, true, "forum")+ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ expect(queryClient.refetchQueries).not.toHaveBeenCalled()+ })++ it("terminates a matching unclaimed handoff through one authoritative refetch", async () => {+ armThreadOpenerReservationHandoff(queryClient, {+ nonce: "nonce-2",+ serverId: "server",+ parentChannelId: "forum",+ childChannelId: "child",+ openerMessageId: "opener-7",+ openerSeq: 7,+ })+ registerInboxReadReservationSurface(queryClient, "child", vi.fn())+ const pending = reserveInboxUnreadsResponse(queryClient, openerResponse())+ void pending.catch(() => undefined)++ expect(terminateThreadOpenerReservationHandoff(queryClient, "nonce-2")).toBe(true)+ expect(terminateThreadOpenerReservationHandoff(queryClient, "nonce-2")).toBe(false)+ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ await Promise.resolve()+ expect(queryClient.refetchQueries).toHaveBeenCalledTimes(1)+ })++ it("releases a claimed opener when its navigation-owned generation is cancelled", async () => {+ armThreadOpenerReservationHandoff(queryClient, {+ nonce: "nonce-3",+ serverId: "server",+ parentChannelId: "forum",+ childChannelId: "child",+ openerMessageId: "opener-7",+ openerSeq: 7,+ })+ registerInboxReadReservationSurface(queryClient, "child", vi.fn())+ const pending = reserveInboxUnreadsResponse(queryClient, openerResponse())+ void pending.catch(() => undefined)+ completeThreadOpenerReservationHandoff(queryClient, "nonce-3", 31)++ await settleInboxReadReservationGeneration(queryClient, 31, false, "forum")+ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ expect(queryClient.refetchQueries).toHaveBeenCalledOnce()+ })++ it("keeps a pending nonce across same-identity effect replay and terminates a true release once", async () => {+ armThreadOpenerReservationHandoff(queryClient, {+ nonce: "nonce-route",+ serverId: "server",+ parentChannelId: "parent",+ childChannelId: "child",+ openerMessageId: "opener-7",+ openerSeq: 7,+ })+ const first = registerThreadOpenerRouteLease(queryClient, "nonce-route", "server", "child")+ releaseThreadOpenerRouteLease(first)+ const replacement = registerThreadOpenerRouteLease(queryClient, "nonce-route", "server", "child")+ await Promise.resolve()+ expect(getThreadOpenerReservationHandoff(queryClient, "nonce-route")).not.toBeNull()+ expect(queryClient.refetchQueries).not.toHaveBeenCalled()++ releaseThreadOpenerRouteLease(replacement)+ await Promise.resolve()+ await Promise.resolve()+ expect(getThreadOpenerReservationHandoff(queryClient, "nonce-route")).toBeNull()+ expect(queryClient.refetchQueries).toHaveBeenCalledOnce()+ })+})diff --git a/src/web/src/hooks/community/inbox-read-reservation.ts b/src/web/src/hooks/community/inbox-read-reservation.tsnew file mode 100644index 000000000..22c286e1e--- /dev/null+++ b/src/web/src/hooks/community/inbox-read-reservation.ts@@ -0,0 +1,729 @@+"use client"++import { communityKeys } from "@/lib/query-keys"+import type { QueryClient } from "@tanstack/react-query"++type InboxChild = {+ channelId: string+ lastMessageAt: string+ openerMessageId?: string+ openerSeq?: number+ openerUnread?: boolean+}++type InboxChannel = {+ channelId: string+ lastMessageAt: string+ hasDirectUnread?: boolean+ children: InboxChild[]+}++type InboxResponse = {+ servers: Array<{ channels: InboxChannel[] }>+ dms: Array<{ channelId: string; lastMessageAt: string }>+}++export type InboxReadCandidate = {+ channelId: string+ lastMessageAt: string+ fingerprint: string+ openerMessageId?: string+ openerSeq?: number+ openerUnread: boolean+}++export type InboxReadReservationLease = {+ queryClient: QueryClient+ token: symbol+ epoch: number+ channelId: string+}++export type ThreadOpenerRouteLease = {+ queryClient: QueryClient+ token: symbol+ nonce: string+ serverId: string+ childChannelId: string+}++export type ThreadOpenerHandoffTarget = {+ nonce: string+ serverId: string+ parentChannelId: string+ childChannelId: string+ openerMessageId: string+ openerSeq: number+}++type ThreadOpenerHandoff = ThreadOpenerHandoffTarget & {+ epoch: number+ phase: "armed" | "awaiting-opener-claim" | "claimed-parent-generation"+}++type ClaimedThreadOpener = ThreadOpenerHandoffTarget & {+ generation: number+}++type HeldResponse<T extends InboxResponse = InboxResponse> = {+ id: number+ candidate: InboxReadCandidate+ data: T+ generation: number | null+ openerClaimLocked: boolean+ reject: (error: unknown) => void+ removeAbort: () => void+}++type LeaseState = {+ lease: InboxReadReservationLease+ onCandidate: (candidate: InboxReadCandidate | null) => void+}++type FocusedCandidate = {+ epoch: number+ candidate: InboxReadCandidate+ generation: number | null+}++type ResponsePermit = {+ epoch: number+ channelId: string+ lastMessageAt: string | null+ fingerprint: string | null+}++type ManagerState = {+ queryClient: QueryClient+ leases: Map<symbol, LeaseState>+ latestToken: symbol | null+ nextEpoch: number+ nextResponseId: number+ held: Map<number, HeldResponse>+ focusedCandidate: FocusedCandidate | null+ discardedCandidate: { epoch: number; candidate: InboxReadCandidate } | null+ permit: ResponsePermit | null+ handoff: ThreadOpenerHandoff | null+ claimedOpeners: Map<number, ClaimedThreadOpener>+ routeLeases: Map<symbol, ThreadOpenerRouteLease>+ refetch: Promise<unknown> | null+ disposed: boolean+}++const managers = new WeakMap<QueryClient, ManagerState>()++function managerFor(queryClient: QueryClient) {+ let state = managers.get(queryClient)+ if (!state) {+ state = {+ queryClient,+ leases: new Map(),+ latestToken: null,+ nextEpoch: 0,+ nextResponseId: 0,+ held: new Map(),+ focusedCandidate: null,+ discardedCandidate: null,+ permit: null,+ handoff: null,+ claimedOpeners: new Map(),+ routeLeases: new Map(),+ refetch: null,+ disposed: false,+ }+ managers.set(queryClient, state)+ }+ return state+}++function fingerprint(candidate: Omit<InboxReadCandidate, "fingerprint">) {+ return JSON.stringify([+ candidate.channelId,+ candidate.lastMessageAt,+ candidate.openerMessageId ?? null,+ candidate.openerSeq ?? null,+ candidate.openerUnread,+ ])+}++function candidateFor(data: InboxResponse, channelId: string): InboxReadCandidate | null {+ for (const server of data.servers) {+ for (const channel of server.channels) {+ const child = channel.children.find((row) => row.channelId === channelId)+ if (child) {+ const candidate = {+ channelId,+ lastMessageAt: child.lastMessageAt,+ ...(child.openerMessageId ? { openerMessageId: child.openerMessageId } : {}),+ ...(child.openerSeq !== undefined ? { openerSeq: child.openerSeq } : {}),+ openerUnread: child.openerUnread === true,+ }+ return { ...candidate, fingerprint: fingerprint(candidate) }+ }+ if (channel.channelId === channelId && channel.hasDirectUnread !== false) {+ const candidate = {+ channelId,+ lastMessageAt: channel.lastMessageAt,+ openerUnread: false,+ }+ return { ...candidate, fingerprint: fingerprint(candidate) }+ }+ }+ }+ const dm = data.dms.find((row) => row.channelId === channelId)+ if (!dm) return null+ const candidate = {+ channelId,+ lastMessageAt: dm.lastMessageAt,+ openerUnread: false,+ }+ return { ...candidate, fingerprint: fingerprint(candidate) }+}++function activeLease(state: ManagerState) {+ return state.latestToken ? state.leases.get(state.latestToken) ?? null : null+}++function handoffMatches(+ handoff: ThreadOpenerHandoffTarget | null,+ candidate: InboxReadCandidate,+) {+ return !!handoff+ && handoff.childChannelId === candidate.channelId+ && handoff.openerMessageId === candidate.openerMessageId+ && handoff.openerSeq === candidate.openerSeq+ && candidate.openerUnread+}++function claimedOpenerForCandidate(+ state: ManagerState,+ candidate: InboxReadCandidate,+) {+ let match: ClaimedThreadOpener | null = null+ for (const claimed of state.claimedOpeners.values()) {+ if (handoffMatches(claimed, candidate)) match = claimed+ }+ return match+}++function hasExactRouteLease(+ state: ManagerState,+ handoff: ThreadOpenerHandoffTarget,+) {+ return [...state.routeLeases.values()].some((lease) => (+ lease.nonce === handoff.nonce+ && lease.serverId === handoff.serverId+ && lease.childChannelId === handoff.childChannelId+ ))+}++function shouldAwaitOpenerClaim(+ state: ManagerState,+ candidate: InboxReadCandidate,+) {+ const handoff = state.handoff+ return !!handoff+ && handoff.phase === "armed"+ && handoffMatches(handoff, candidate)+ && hasExactRouteLease(state, handoff)+}++function notifyActive(state: ManagerState, candidate: InboxReadCandidate | null) {+ activeLease(state)?.onCandidate(candidate)+}++function candidateIdentityMatches(+ expected: InboxReadCandidate,+ actual: InboxReadCandidate,+) {+ return expected.channelId === actual.channelId+ && expected.lastMessageAt === actual.lastMessageAt+ && (+ expected.openerMessageId === undefined+ || actual.openerMessageId === undefined+ || expected.openerMessageId === actual.openerMessageId+ )+ && (+ expected.openerSeq === undefined+ || actual.openerSeq === undefined+ || expected.openerSeq === actual.openerSeq+ )+}++function permitMatches(+ permit: ResponsePermit,+ epoch: number,+ candidate: InboxReadCandidate,+) {+ return permit.epoch === epoch+ && permit.channelId === candidate.channelId+ && (permit.lastMessageAt === null || permit.lastMessageAt === candidate.lastMessageAt)+ && (permit.fingerprint === null || permit.fingerprint === candidate.fingerprint)+}++function cancelHeld(state: ManagerState, held: HeldResponse) {+ if (!state.held.delete(held.id)) return+ held.removeAbort()+ held.reject(new DOMException("Inbox response superseded", "AbortError"))+}++function queueAuthoritativeRefetch(state: ManagerState) {+ if (state.disposed || state.refetch) return state.refetch ?? Promise.resolve()+ const queryKey = communityKeys.inboxUnreads()+ state.refetch = state.queryClient.cancelQueries({ queryKey, exact: true })+ .then(() => state.queryClient.refetchQueries({ queryKey, exact: true, type: "active" }))+ .finally(() => {+ state.refetch = null+ })+ return state.refetch+}++function releaseHeldNegative(state: ManagerState, held: HeldResponse) {+ const handoff = state.handoff+ if (+ handoff?.phase === "armed"+ && handoffMatches(handoff, held.candidate)+ && !hasExactRouteLease(state, handoff)+ ) {+ state.handoff = null+ }+ state.permit = {+ epoch: activeLease(state)?.lease.epoch ?? state.nextEpoch,+ channelId: held.candidate.channelId,+ lastMessageAt: held.candidate.lastMessageAt,+ fingerprint: held.candidate.fingerprint,+ }+ cancelHeld(state, held)+ notifyActive(state, null)+ return queueAuthoritativeRefetch(state)+}++function reclassifyHeld(state: ManagerState) {+ const lease = activeLease(state)+ if (!lease) return+ let latest: InboxReadCandidate | null = null+ for (const held of state.held.values()) {+ if (held.openerClaimLocked) continue+ const candidate = candidateFor(held.data, lease.lease.channelId)+ if (!candidate) {+ void releaseHeldNegative(state, held)+ continue+ }+ held.candidate = candidate+ const claimed = claimedOpenerForCandidate(state, candidate)+ held.generation = claimed?.generation ?? null+ held.openerClaimLocked = claimed !== null+ if (shouldAwaitOpenerClaim(state, candidate) && state.handoff) {+ state.handoff.phase = "awaiting-opener-claim"+ }+ latest = candidate+ }+ notifyActive(state, latest)+}++export function registerInboxReadReservationSurface(+ queryClient: QueryClient,+ channelId: string,+ onCandidate: (candidate: InboxReadCandidate | null) => void,+): InboxReadReservationLease {+ const state = managerFor(queryClient)+ const token = Symbol(channelId)+ const lease = {+ queryClient,+ token,+ epoch: ++state.nextEpoch,+ channelId,+ }+ state.leases.set(token, { lease, onCandidate })+ state.latestToken = token+ if (state.focusedCandidate?.epoch !== lease.epoch) state.focusedCandidate = null+ reclassifyHeld(state)+ return lease+}++export function armInboxReadReservationCandidate(+ queryClient: QueryClient,+ input: {+ channelId: string+ lastMessageAt: string+ openerMessageId?: string+ openerSeq?: number+ },+) {+ const state = managerFor(queryClient)+ const lease = activeLease(state)+ if (state.disposed || !lease || lease.lease.channelId !== input.channelId) return false+ const candidateBase = {+ channelId: input.channelId,+ lastMessageAt: input.lastMessageAt,+ ...(input.openerMessageId ? { openerMessageId: input.openerMessageId } : {}),+ ...(input.openerSeq !== undefined ? { openerSeq: input.openerSeq } : {}),+ openerUnread: false,+ }+ const candidate = { ...candidateBase, fingerprint: fingerprint(candidateBase) }+ const current = state.focusedCandidate+ if (+ current?.epoch === lease.lease.epoch+ && candidateIdentityMatches(current.candidate, candidate)+ ) return false++ if (current?.epoch === lease.lease.epoch) {+ for (const held of [...state.held.values()]) {+ if (candidateIdentityMatches(current.candidate, held.candidate)) cancelHeld(state, held)+ }+ }+ if (+ state.permit?.epoch === lease.lease.epoch+ && state.permit.channelId === input.channelId+ ) {+ state.permit = null+ }+ if (+ state.discardedCandidate?.epoch === lease.lease.epoch+ && state.discardedCandidate.candidate.channelId === input.channelId+ ) {+ state.discardedCandidate = null+ }+ state.focusedCandidate = {+ epoch: lease.lease.epoch,+ candidate,+ generation: null,+ }+ notifyActive(state, candidate)+ return true+}++export function releaseInboxReadReservationSurface(lease: InboxReadReservationLease) {+ const state = managers.get(lease.queryClient)+ if (!state || state.disposed) return+ state.leases.delete(lease.token)+ if (state.latestToken !== lease.token) return+ state.latestToken = null+ if (state.focusedCandidate?.epoch === lease.epoch) state.focusedCandidate = null+ if (state.discardedCandidate?.epoch === lease.epoch) state.discardedCandidate = null+ if (state.permit?.epoch === lease.epoch) state.permit = null+ const epoch = ++state.nextEpoch+ queueMicrotask(() => {+ if (state.disposed || state.latestToken || state.nextEpoch !== epoch) return+ for (const held of [...state.held.values()]) void releaseHeldNegative(state, held)+ })+}++export function promoteInboxReadReservation(+ lease: InboxReadReservationLease,+ generation: number,+) {+ const state = managers.get(lease.queryClient)+ const current = state?.leases.get(lease.token)+ if (!state || !current || current.lease.epoch !== lease.epoch) return false+ if (+ state.focusedCandidate?.epoch === lease.epoch+ && state.focusedCandidate.candidate.channelId === lease.channelId+ ) {+ state.focusedCandidate.generation = generation+ }+ for (const held of state.held.values()) {+ if (held.candidate.channelId === lease.channelId && !held.openerClaimLocked) {+ held.generation = generation+ }+ }+ return true+}++export function takeInboxReadReservationNegative(+ lease: InboxReadReservationLease,+) {+ const state = managers.get(lease.queryClient)+ const current = state?.leases.get(lease.token)+ if (!state || !current || current.lease.epoch !== lease.epoch) return false+ if (state.handoff?.phase === "awaiting-opener-claim") return false+ let released = false+ for (const held of [...state.held.values()]) {+ if (held.candidate.channelId === lease.channelId && held.generation === null) {+ released = true+ void releaseHeldNegative(state, held)+ }+ }+ const focused = state.focusedCandidate+ if (+ focused?.epoch === lease.epoch+ && focused.candidate.channelId === lease.channelId+ && focused.generation === null+ ) {+ state.focusedCandidate = null+ if (!released) {+ state.permit = {+ epoch: lease.epoch,+ channelId: focused.candidate.channelId,+ lastMessageAt: focused.candidate.lastMessageAt,+ fingerprint: null,+ }+ notifyActive(state, null)+ void queueAuthoritativeRefetch(state)+ }+ }+ return true+}++export async function settleInboxReadReservationGeneration(+ queryClient: QueryClient,+ generation: number,+ committed: boolean,+ channelId: string,+) {+ const state = managers.get(queryClient)+ if (!state || state.disposed) return+ const claimed = state.claimedOpeners.get(generation) ?? null+ const matching = [...state.held.values()].filter((held) => held.generation === generation)+ if (!committed) {+ state.claimedOpeners.delete(generation)+ if (matching.length === 0) {+ const lease = activeLease(state)+ const permitChannelId = claimed?.childChannelId ?? channelId+ if (lease?.lease.channelId !== permitChannelId) return+ state.permit = {+ epoch: lease.lease.epoch,+ channelId: permitChannelId,+ lastMessageAt: state.focusedCandidate?.generation === generation+ ? state.focusedCandidate.candidate.lastMessageAt+ : null,+ fingerprint: null,+ }+ if (state.focusedCandidate?.generation === generation) {+ state.focusedCandidate = null+ }+ notifyActive(state, null)+ await queueAuthoritativeRefetch(state)+ return+ }+ await Promise.all(matching.map((held) => releaseHeldNegative(state, held)))+ if (state.focusedCandidate?.generation === generation) state.focusedCandidate = null+ return+ }+ if (matching.length === 0 && !claimed) {+ const focused = state.focusedCandidate+ if (committed && focused?.generation === generation) {+ state.discardedCandidate = {+ epoch: focused.epoch,+ candidate: focused.candidate,+ }+ state.focusedCandidate = null+ notifyActive(state, null)+ }+ return+ }+ await state.queryClient.cancelQueries({+ queryKey: communityKeys.inboxUnreads(),+ exact: true,+ })+ state.claimedOpeners.delete(generation)+ for (const held of [...state.held.values()]) {+ if (held.generation === generation) cancelHeld(state, held)+ }+ if (state.focusedCandidate?.generation === generation) state.focusedCandidate = null+ notifyActive(state, null)+}++export async function reserveInboxUnreadsResponse<T extends InboxResponse>(+ queryClient: QueryClient,+ data: T,+ signal?: AbortSignal,+): Promise<T> {+ const state = managerFor(queryClient)+ const lease = activeLease(state)+ if (state.disposed || !lease) return data+ const candidate = candidateFor(data, lease.lease.channelId)+ if (!candidate) return data+ const claimed = claimedOpenerForCandidate(state, candidate)+ const armed = state.focusedCandidate?.epoch === lease.lease.epoch+ && state.focusedCandidate.candidate.channelId === candidate.channelId+ ? state.focusedCandidate+ : null+ let focused = armed && candidateIdentityMatches(armed.candidate, candidate)+ ? armed+ : null+ if (armed && !focused) {+ if (candidate.lastMessageAt <= armed.candidate.lastMessageAt) {+ throw new DOMException("Inbox response superseded", "AbortError")+ }+ for (const held of [...state.held.values()]) {+ if (candidateIdentityMatches(armed.candidate, held.candidate)) cancelHeld(state, held)+ }+ focused = {+ epoch: armed.epoch,+ candidate,+ generation: null,+ }+ state.focusedCandidate = focused+ }+ if (+ state.discardedCandidate?.epoch === lease.lease.epoch+ && candidateIdentityMatches(state.discardedCandidate.candidate, candidate)+ ) {+ throw new DOMException("Inbox response superseded", "AbortError")+ }+ if (+ !claimed+ && state.permit+ && permitMatches(state.permit, lease.lease.epoch, candidate)+ ) {+ state.permit = null+ if (focused) state.focusedCandidate = null+ return data+ }+ if (signal?.aborted) throw new DOMException("Inbox response aborted", "AbortError")+ return new Promise<T>((_resolve, reject) => {+ const id = ++state.nextResponseId+ const onAbort = () => {+ const held = state.held.get(id)+ if (!held) return+ state.held.delete(id)+ held.removeAbort()+ reject(new DOMException("Inbox response aborted", "AbortError"))+ }+ signal?.addEventListener("abort", onAbort, { once: true })+ const held: HeldResponse<T> = {+ id,+ candidate,+ data,+ generation: claimed?.generation ?? focused?.generation ?? null,+ openerClaimLocked: claimed !== null,+ reject,+ removeAbort: () => signal?.removeEventListener("abort", onAbort),+ }+ state.held.set(id, held)+ if (focused) {+ focused.candidate = candidate+ }+ if (shouldAwaitOpenerClaim(state, candidate) && state.handoff) {+ state.handoff.phase = "awaiting-opener-claim"+ }+ lease.onCandidate(candidate)+ })+}++export function armThreadOpenerReservationHandoff(+ queryClient: QueryClient,+ target: ThreadOpenerHandoffTarget,+) {+ const state = managerFor(queryClient)+ if (state.handoff) terminateThreadOpenerReservationHandoff(queryClient, state.handoff.nonce)+ state.handoff = {+ ...target,+ epoch: ++state.nextEpoch,+ phase: "armed",+ }+}++export function getThreadOpenerReservationHandoff(+ queryClient: QueryClient,+ nonce: string,+) {+ const handoff = managerFor(queryClient).handoff+ return handoff?.nonce === nonce ? { ...handoff } : null+}++export function registerThreadOpenerRouteLease(+ queryClient: QueryClient,+ nonce: string,+ serverId: string,+ childChannelId: string,+): ThreadOpenerRouteLease {+ const state = managerFor(queryClient)+ const lease = {+ queryClient,+ token: Symbol(`${serverId}/${childChannelId}`),+ nonce,+ serverId,+ childChannelId,+ }+ state.routeLeases.set(lease.token, lease)+ const handoff = state.handoff+ if (+ handoff?.phase === "armed"+ && hasExactRouteLease(state, handoff)+ && [...state.held.values()].some((held) => handoffMatches(handoff, held.candidate))+ ) {+ handoff.phase = "awaiting-opener-claim"+ }+ return lease+}++export function releaseThreadOpenerRouteLease(lease: ThreadOpenerRouteLease) {+ const state = managers.get(lease.queryClient)+ if (!state || state.disposed || !state.routeLeases.delete(lease.token)) return+ queueMicrotask(() => {+ if (state.disposed) return+ const replaced = [...state.routeLeases.values()].some((candidate) => (+ candidate.nonce === lease.nonce+ && candidate.serverId === lease.serverId+ && candidate.childChannelId === lease.childChannelId+ ))+ if (replaced) return+ const handoff = state.handoff+ if (+ handoff?.nonce === lease.nonce+ && handoff.serverId === lease.serverId+ && handoff.childChannelId === lease.childChannelId+ ) {+ terminateThreadOpenerReservationHandoff(lease.queryClient, lease.nonce)+ }+ })+}++export function completeThreadOpenerReservationHandoff(+ queryClient: QueryClient,+ nonce: string,+ generation: number,+) {+ const state = managerFor(queryClient)+ const handoff = state.handoff+ if (!handoff || handoff.nonce !== nonce) return false+ handoff.phase = "claimed-parent-generation"+ for (const held of state.held.values()) {+ if (handoffMatches(handoff, held.candidate)) {+ held.generation = generation+ held.openerClaimLocked = true+ }+ }+ state.claimedOpeners.set(generation, { ...handoff, generation })+ state.handoff = null+ return true+}++export function terminateThreadOpenerReservationHandoff(+ queryClient: QueryClient,+ nonce: string,+) {+ const state = managerFor(queryClient)+ const handoff = state.handoff+ if (!handoff || handoff.nonce !== nonce) return false+ const matching = [...state.held.values()].filter((held) => handoffMatches(handoff, held.candidate))+ state.handoff = null+ for (const held of matching) void releaseHeldNegative(state, held)+ if (matching.length === 0) void queueAuthoritativeRefetch(state)+ return true+}++export function clearThreadOpenerReservationHandoff(queryClient: QueryClient) {+ const handoff = managerFor(queryClient).handoff+ return handoff+ ? terminateThreadOpenerReservationHandoff(queryClient, handoff.nonce)+ : false+}++export function disposeInboxReadReservation(queryClient: QueryClient) {+ const state = managers.get(queryClient)+ if (!state || state.disposed) return+ state.disposed = true+ state.handoff = null+ state.claimedOpeners.clear()+ state.routeLeases.clear()+ state.focusedCandidate = null+ state.discardedCandidate = null+ state.permit = null+ state.leases.clear()+ state.latestToken = null+ for (const held of [...state.held.values()]) cancelHeld(state, held)+ managers.delete(queryClient)+}diff --git a/src/web/src/hooks/community/read-coordinator.test.ts b/src/web/src/hooks/community/read-coordinator.test.tsindex 0d6541b8f..31f4f0354 100644--- a/src/web/src/hooks/community/read-coordinator.test.ts+++ b/src/web/src/hooks/community/read-coordinator.test.ts@@ -14,6 +14,7 @@ vi.mock("./community-ws/read-state-reconciliation", () => ({}))import {+ confirmReadSurface,disposeReadCoordinator,flushPendingReadIntents,getReadCoordinator,@@ -23,6 +24,7 @@ import {releaseReadSurface,resumeReadCoordinator,submitReadIntent,+ submitReadIntentGeneration,} from "./read-coordinator"function timelineLease(queryClient: QueryClient, confirmedSeq = 0) {@@ -210,6 +212,97 @@ describe("read coordinator", () => {)})+ it("cancels an uncommitted navigation-owned opener without flushing it", async () => {+ const queryClient = new QueryClient()+ const lease = registerReadSurface(+ queryClient,+ "user-1",+ { kind: "timeline", channelId: "forum-1" },+ 0,+ "cancel-uncommitted",+ )+ expect(submitReadIntentGeneration(lease, {+ kind: "timeline",+ channelId: "forum-1",+ messageId: "opener-7",+ seq: 7,+ })).toBe(1)++ releaseReadSurface(lease)+ await vi.runAllTimersAsync()+ expect(apiFetch).not.toHaveBeenCalled()+ expect(submitReadIntentGeneration(lease, {+ kind: "timeline",+ channelId: "forum-1",+ messageId: "opener-8",+ seq: 8,+ })).toBeNull()+ })++ it("uses default registration semantics and confirms monotonically through the public adapter", async () => {+ const queryClient = new QueryClient()+ const lease = registerReadSurface(queryClient, "user-1", {+ kind: "timeline",+ channelId: "channel-1",+ })+ expect(submitTimeline(lease, 6)).toBe(true)+ confirmReadSurface(lease, 6)+ confirmReadSurface(lease, 2)+ expect(submitTimeline(lease, 5)).toBe(false)+ await vi.runAllTimersAsync()+ expect(apiFetch).not.toHaveBeenCalled()+ })++ it("aborts and fences an active navigation-owned mutation on release", async () => {+ const queryClient = new QueryClient()+ const lease = registerReadSurface(+ queryClient,+ "user-1",+ { kind: "timeline", channelId: "forum-1" },+ 0,+ "cancel-uncommitted",+ )+ apiFetch.mockReturnValue(new Promise(() => undefined))+ submitReadIntentGeneration(lease, {+ kind: "timeline",+ channelId: "forum-1",+ messageId: "opener-7",+ seq: 7,+ })+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)+ const signal = apiFetch.mock.calls[0]?.[1]?.signal as AbortSignal++ releaseReadSurface(lease)++ expect(signal.aborted).toBe(true)+ expect(reconcileAccountReadState).not.toHaveBeenCalled()+ })++ it("cancels a navigation-owned retry timer and dirty generation on release", async () => {+ const queryClient = new QueryClient()+ const lease = registerReadSurface(+ queryClient,+ "user-1",+ { kind: "timeline", channelId: "forum-1" },+ 0,+ "cancel-uncommitted",+ )+ apiFetch.mockRejectedValue(new ApiError("busy", 503))+ submitReadIntentGeneration(lease, {+ kind: "timeline",+ channelId: "forum-1",+ messageId: "opener-7",+ seq: 7,+ })+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)+ expect(apiFetch).toHaveBeenCalledOnce()++ releaseReadSurface(lease)+ await vi.runAllTimersAsync()++ expect(apiFetch).toHaveBeenCalledOnce()+ })+it("serializes a newer visible target behind the active request", 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.tsindex 43bce0411..c2db478e6 100644--- a/src/web/src/hooks/community/read-coordinator.ts+++ b/src/web/src/hooks/community/read-coordinator.ts@@ -11,6 +11,10 @@ import {type ReadCoordinatorSnapshot,unregisterReadCoordinatorSnapshotProjector,} from "./read-coordinator-snapshot-projection"+import {+ disposeInboxReadReservation,+ settleInboxReadReservationGeneration,+} from "./inbox-read-reservation"export const READ_COORDINATOR_DEBOUNCE_MS = 500@@ -27,6 +31,7 @@ type QueuedReadIntent = {intent: ReadIntentgeneration: numberdueAt: number+ ownerToken: symbol}export type PendingReadFlushOutcome = {@@ -56,6 +61,7 @@ type SurfaceLease = {key: stringtoken: symbolepoch: number+ releasePolicy: "flush" | "cancel-uncommitted"}type ScopeState = {@@ -117,7 +123,11 @@ class ReadCoordinator {readonly ownerUserId: string,) {}- register(surface: ReadSurface, confirmedSeq = 0): SurfaceLease {+ register(+ surface: ReadSurface,+ confirmedSeq: number,+ releasePolicy: SurfaceLease["releasePolicy"],+ ): SurfaceLease {this.assertActive()const key = scopeKey(surface)let state = this.states.get(key)@@ -150,13 +160,50 @@ class ReadCoordinator {readStates: Array<{ channelId: string; lastReadSeq: number }>}>(communityKeys.accountReadStateSnapshot())if (cached) this.applySnapshot(cached)- return { coordinator: this, key, token, epoch: state.epoch }+ return { coordinator: this, key, token, epoch: state.epoch, releasePolicy }}release(lease: SurfaceLease) {const state = this.validState(lease)if (!state) returnstate.leases.delete(lease.token)+ if (lease.releasePolicy === "cancel-uncommitted") {+ const canceledGenerations = new Set<number>()+ if (state.accepted?.ownerToken === lease.token) {+ canceledGenerations.add(state.accepted.generation)+ state.accepted = null+ }+ if (state.dirty?.ownerToken === lease.token) {+ canceledGenerations.add(state.dirty.generation)+ state.dirty = null+ }+ if (+ state.inFlight?.target.ownerToken === lease.token+ && state.inFlight.phase === "mutation"+ ) {+ canceledGenerations.add(state.inFlight.target.generation)+ state.attemptEpoch += 1+ state.inFlight.controller.abort()+ state.inFlight = null+ }+ if (!state.accepted && state.timer !== null) {+ clearTimeout(state.timer)+ state.timer = null+ }+ if (!state.dirty && state.retryTimer !== null) {+ clearTimeout(state.retryTimer)+ state.retryTimer = null+ }+ for (const generation of canceledGenerations) {+ void settleInboxReadReservationGeneration(+ this.queryClient,+ generation,+ false,+ state.surface.channelId,+ )+ }+ return+ }if (state.leases.size > 0 || state.releaseTimer !== null) returnstate.releaseTimer = setTimeout(() => {state.releaseTimer = null@@ -166,22 +213,30 @@ class ReadCoordinator {}, 0)}- submit(lease: SurfaceLease, intent: ReadIntent) {+ submit(lease: SurfaceLease, intent: ReadIntent): number | null {const state = this.validState(lease)- if (!state || !this.matchesSurface(state.surface, intent)) return false+ if (!state || !this.matchesSurface(state.surface, intent)) return nullif (typeof document !== "undefined" && document.visibilityState !== "visible") {- return false+ return null}- if (this.confirmed(state, intent)) return false+ if (this.confirmed(state, intent)) return nullconst queued = {intent,generation: ++this.latestIntentGeneration,dueAt: Date.now() + READ_COORDINATOR_DEBOUNCE_MS,+ ownerToken: lease.token,}state.accepted = laterIntent(state.accepted, queued)state.dirty = laterIntent(state.dirty, queued)this.schedule(state, READ_COORDINATOR_DEBOUNCE_MS)- return true+ return queued.generation+ }++ confirm(lease: SurfaceLease, confirmedSeq: number) {+ const state = this.validState(lease)+ if (!state) return+ state.confirmedSeq = Math.max(state.confirmedSeq, confirmedSeq)+ this.cancelConfirmedWork(state)}resume() {@@ -363,6 +418,12 @@ class ReadCoordinator {if (!this.attemptActive(state, attemptEpoch, identityEpoch)) {return { committed: false, reconciled: false }}+ await settleInboxReadReservationGeneration(+ this.queryClient,+ target.generation,+ false,+ target.intent.channelId,+ )if (!retryable(error)) {if (state.dirty && sameIntent(state.dirty, target)) state.dirty = nullstate.retryCount = 0@@ -379,6 +440,15 @@ class ReadCoordinator {return { committed: false, reconciled: false }}+ if (!this.attemptActive(state, attemptEpoch, identityEpoch)) {+ return { committed: false, reconciled: false }+ }+ await settleInboxReadReservationGeneration(+ this.queryClient,+ target.generation,+ true,+ target.intent.channelId,+ )if (!this.attemptActive(state, attemptEpoch, identityEpoch)) {return { committed: false, reconciled: false }}@@ -516,6 +586,7 @@ export function getReadCoordinator(export function disposeReadCoordinator(queryClient: QueryClient) {disposedClients.add(queryClient)coordinators.get(queryClient)?.dispose()+ disposeInboxReadReservation(queryClient)unregisterReadCoordinatorSnapshotProjector(queryClient)}@@ -531,15 +602,28 @@ export function registerReadSurface(ownerUserId: string,surface: ReadSurface,confirmedSeq = 0,+ releasePolicy: SurfaceLease["releasePolicy"] = "flush",) {- return getReadCoordinator(queryClient, ownerUserId).register(surface, confirmedSeq)+ return getReadCoordinator(queryClient, ownerUserId).register(+ surface,+ confirmedSeq,+ releasePolicy,+ )}export function releaseReadSurface(lease: SurfaceLease) {lease.coordinator.release(lease)}+export function confirmReadSurface(lease: SurfaceLease, confirmedSeq: number) {+ lease.coordinator.confirm(lease, confirmedSeq)+}+export function submitReadIntent(lease: SurfaceLease, intent: ReadIntent) {+ return lease.coordinator.submit(lease, intent) !== null+}++export function submitReadIntentGeneration(lease: SurfaceLease, intent: ReadIntent) {return lease.coordinator.submit(lease, intent)}diff --git a/src/web/src/hooks/community/thread-opener-read-handoff.test.ts b/src/web/src/hooks/community/thread-opener-read-handoff.test.tsnew file mode 100644index 000000000..7dc28b322--- /dev/null+++ b/src/web/src/hooks/community/thread-opener-read-handoff.test.ts@@ -0,0 +1,423 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import type { QueryClient } from "@tanstack/react-query"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"++const state = vi.hoisted(() => ({+ queryClient: null as QueryClient | null,+ params: "inboxThreadOpener=nonce-1&msg=message-9&tab=all",+ pathname: "/c/channels/server-1/child-1",+}))+const mocks = vi.hoisted(() => ({+ replace: vi.fn(),+ register: vi.fn(() => ({ lease: "parent" })),+ release: vi.fn(),+ confirm: vi.fn(),+ resume: vi.fn(),+ submit: vi.fn(() => 17),+}))++vi.mock("next/navigation", () => ({+ useRouter: () => ({ replace: mocks.replace }),+ useSearchParams: () => new URLSearchParams(state.params),+ usePathname: () => state.pathname,+}))+vi.mock("@tanstack/react-query", async () => {+ const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query")+ return { ...actual, useQueryClient: () => state.queryClient }+})+vi.mock("@/contexts/community/current-user", () => ({+ useCurrentUser: () => ({ id: "viewer" }),+}))+vi.mock("./read-coordinator", () => ({+ registerReadSurface: (...args: unknown[]) => mocks.register(...args),+ releaseReadSurface: (...args: unknown[]) => mocks.release(...args),+ confirmReadSurface: (...args: unknown[]) => mocks.confirm(...args),+ resumeReadCoordinator: (...args: unknown[]) => mocks.resume(...args),+ submitReadIntentGeneration: (...args: unknown[]) => mocks.submit(...args),+}))++import {+ armThreadOpenerReadHandoff,+ clearThreadOpenerReadHandoff,+ useClaimThreadOpenerReadHandoff,+ useThreadOpenerRouteGate,+} from "./thread-opener-read-handoff"+import {+ armThreadOpenerReservationHandoff,+ disposeInboxReadReservation,+ getThreadOpenerReservationHandoff,+ reserveInboxUnreadsResponse,+ type ThreadOpenerHandoffTarget,+} from "./inbox-read-reservation"+import { useTimelineReadObserver } from "./use-read-observer"++type Lifecycle = "pending" | "ready" | "terminal-error"++const target: ThreadOpenerHandoffTarget = {+ nonce: "nonce-1",+ serverId: "server-1",+ parentChannelId: "parent-1",+ childChannelId: "child-1",+ openerMessageId: "opener-7",+ openerSeq: 7,+}++function client() {+ return {+ cancelQueries: vi.fn().mockResolvedValue(undefined),+ refetchQueries: vi.fn().mockResolvedValue(undefined),+ } as unknown as QueryClient+}++function Claim({ handoff }: {+ handoff: ReturnType<typeof getThreadOpenerReservationHandoff> | undefined+}) {+ useClaimThreadOpenerReadHandoff(handoff)+ return null+}++function Harness({+ lifecycle,+ childChannelId = "child-1",+ parentChannelId = "parent-1",+ openerMessageId = "opener-7",+}: {+ lifecycle: Lifecycle+ childChannelId?: string+ parentChannelId?: string | null+ openerMessageId?: string | null+}) {+ const handoff = useThreadOpenerRouteGate({+ serverId: "server-1",+ childChannelId,+ parentChannelId,+ openerMessageId,+ lifecycle,+ })+ return React.createElement(Claim, { handoff: handoff ?? undefined })+}++const noCatchUp = () => Promise.resolve()+const emptyScrollRoot = {+ querySelectorAll: () => [],+ contains: () => false,+} as unknown as HTMLElement++function DirectChildHarness() {+ useTimelineReadObserver({+ channelId: "child-1",+ messages: [],+ scrollRootEl: emptyScrollRoot,+ snapshotStatus: "error",+ feedStatus: "error",+ tailAttached: false,+ confirmedSeq: 0,+ catchUp: noCatchUp,+ })+ return null+}++function openerResponse() {+ return {+ servers: [{+ channels: [{+ channelId: "parent-1",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ children: [{+ channelId: "child-1",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ openerMessageId: "opener-7",+ openerSeq: 7,+ openerUnread: true,+ }],+ }],+ }],+ dms: [],+ }+}++async function render(lifecycle: Lifecycle = "pending") {+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ React.createElement(React.StrictMode, null, React.createElement(Harness, { lifecycle })),+ )+ })+ return renderer+}++describe("thread opener read handoff", () => {+ beforeEach(() => {+ state.queryClient = client()+ state.params = "inboxThreadOpener=nonce-1&msg=message-9&tab=all"+ state.pathname = "/c/channels/server-1/child-1"+ vi.clearAllMocks()+ mocks.submit.mockReturnValue(17)+ })++ afterEach(() => {+ if (state.queryClient) disposeInboxReadReservation(state.queryClient)+ vi.unstubAllGlobals()+ })++ it("arms an opaque generic nonce URL and clears it explicitly", () => {+ vi.stubGlobal("crypto", { randomUUID: () => "nonce-fixed" })+ const href = armThreadOpenerReadHandoff(state.queryClient!, {+ serverId: "server-1",+ parentChannelId: "parent-1",+ childChannelId: "child-1",+ openerMessageId: "opener-7",+ openerSeq: 7,+ })+ expect(href).toBe("/c/channels/server-1/child-1?inboxThreadOpener=nonce-fixed")+ expect(getThreadOpenerReservationHandoff(state.queryClient!, "nonce-fixed"))+ .toMatchObject({ parentChannelId: "parent-1", openerSeq: 7 })+ expect(clearThreadOpenerReadHandoff(state.queryClient!)).toBeUndefined()+ expect(getThreadOpenerReservationHandoff(state.queryClient!, "nonce-fixed")).toBeNull()+ })++ it("falls back to unique local nonces when randomUUID is unavailable", () => {+ vi.stubGlobal("crypto", undefined)+ const input = {+ serverId: "server-1",+ parentChannelId: "parent-1",+ childChannelId: "child-1",+ openerMessageId: "opener-7",+ openerSeq: 7,+ }+ const first = armThreadOpenerReadHandoff(state.queryClient!, input)+ const second = armThreadOpenerReadHandoff(state.queryClient!, input)+ expect(first).toMatch(/inboxThreadOpener=opener-\d+$/)+ expect(second).toMatch(/inboxThreadOpener=opener-\d+$/)+ expect(second).not.toBe(first)+ })++ it("cleans an aligned nonce URL when no matching handoff exists", async () => {+ const renderer = await render("ready")+ expect(mocks.submit).not.toHaveBeenCalled()+ expect(mocks.replace).toHaveBeenCalledWith(+ "/c/channels/server-1/child-1?msg=message-9&tab=all",+ { scroll: false },+ )+ await act(async () => renderer.unmount())+ })++ it("keeps a nonce-free aligned route outside handoff ownership", async () => {+ state.params = "msg=message-9&tab=all"+ const renderer = await render("ready")+ expect(mocks.register).not.toHaveBeenCalled()+ expect(mocks.submit).not.toHaveBeenCalled()+ expect(mocks.replace).not.toHaveBeenCalled()+ expect(state.queryClient!.refetchQueries).not.toHaveBeenCalled()+ await act(async () => renderer.unmount())+ })++ it("survives a real pending-to-ready rerender, then claims the exact parent and preserves child msg", async () => {+ armThreadOpenerReservationHandoff(state.queryClient!, target)+ const renderer = await render("pending")+ expect(mocks.submit).not.toHaveBeenCalled()+ expect(getThreadOpenerReservationHandoff(state.queryClient!, "nonce-1")).not.toBeNull()++ await act(async () => {+ renderer.update(React.createElement(Harness, { lifecycle: "ready" }))+ })++ expect(mocks.register).toHaveBeenCalledWith(+ state.queryClient,+ "viewer",+ { kind: "timeline", channelId: "parent-1" },+ 0,+ "cancel-uncommitted",+ )+ expect(mocks.submit).toHaveBeenCalledWith({ lease: "parent" }, {+ kind: "timeline",+ channelId: "parent-1",+ messageId: "opener-7",+ seq: 7,+ })+ expect(state.queryClient!.refetchQueries).not.toHaveBeenCalled()+ expect(mocks.replace).toHaveBeenCalledWith(+ "/c/channels/server-1/child-1?msg=message-9&tab=all",+ { scroll: false },+ )+ })++ it("waits through a transient stale child render before classifying the aligned route", async () => {+ const nextTarget = { ...target, childChannelId: "child-2" }+ state.pathname = "/c/channels/server-1/child-2"+ armThreadOpenerReservationHandoff(state.queryClient!, nextTarget)+ const renderer = await render("pending")+ expect(getThreadOpenerReservationHandoff(state.queryClient!, "nonce-1")).not.toBeNull()+ expect(state.queryClient!.refetchQueries).not.toHaveBeenCalled()++ await act(async () => {+ renderer.update(React.createElement(+ React.StrictMode,+ null,+ React.createElement(Harness, { lifecycle: "ready", childChannelId: "child-2" }),+ ))+ })++ expect(mocks.submit).toHaveBeenCalledWith({ lease: "parent" }, {+ kind: "timeline",+ channelId: "parent-1",+ messageId: "opener-7",+ seq: 7,+ })+ })++ it("releases the prior parent lease before claiming a replacement target", async () => {+ armThreadOpenerReservationHandoff(state.queryClient!, target)+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(Claim, { handoff: target }))+ })++ const replacement = {+ ...target,+ nonce: "nonce-2",+ openerMessageId: "opener-8",+ openerSeq: 8,+ }+ armThreadOpenerReservationHandoff(state.queryClient!, replacement)+ state.params = "inboxThreadOpener=nonce-2&msg=message-9&tab=all"+ await act(async () => {+ renderer.update(React.createElement(Claim, { handoff: replacement }))+ })++ expect(mocks.release).toHaveBeenCalledWith({ lease: "parent" })+ expect(mocks.submit).toHaveBeenLastCalledWith({ lease: "parent" }, {+ kind: "timeline",+ channelId: "parent-1",+ messageId: "opener-8",+ seq: 8,+ })+ await act(async () => renderer.unmount())+ })++ it("terminates a stale claim target without submitting its parent read", async () => {+ armThreadOpenerReservationHandoff(state.queryClient!, { ...target, openerSeq: 8 })+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(Claim, { handoff: target }))+ })+ expect(mocks.submit).not.toHaveBeenCalled()+ expect(getThreadOpenerReservationHandoff(state.queryClient!, "nonce-1")).toBeNull()+ await act(async () => renderer.unmount())+ })++ it("releases and terminates when the coordinator rejects the opener generation", async () => {+ mocks.submit.mockReturnValue(null)+ armThreadOpenerReservationHandoff(state.queryClient!, target)+ const renderer = await render("ready")+ expect(mocks.release).toHaveBeenCalledWith({ lease: "parent" })+ expect(getThreadOpenerReservationHandoff(state.queryClient!, "nonce-1")).toBeNull()+ await act(async () => renderer.unmount())+ })++ it("defers a claimed parent lease release until a true hook unmount", async () => {+ armThreadOpenerReservationHandoff(state.queryClient!, target)+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(Claim, { handoff: target }))+ })+ expect(mocks.release).not.toHaveBeenCalled()+ await act(async () => {+ renderer.unmount()+ await Promise.resolve()+ })+ expect(mocks.release).toHaveBeenCalledWith({ lease: "parent" })+ })++ it("fences the deferred release when the hook lifetime is replaced before its microtask", async () => {+ const firstClient = state.queryClient!+ armThreadOpenerReservationHandoff(firstClient, target)+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(Claim, { handoff: target }))+ })++ state.queryClient = client()+ await act(async () => {+ renderer.update(React.createElement(Claim, { handoff: target }))+ await Promise.resolve()+ })++ expect(mocks.release).not.toHaveBeenCalled()+ await act(async () => {+ renderer.unmount()+ await Promise.resolve()+ })+ expect(mocks.release).toHaveBeenCalledWith({ lease: "parent" })+ disposeInboxReadReservation(firstClient)+ })++ it("settles an orphaned push when a later nonce-free direct child route matches", async () => {+ armThreadOpenerReservationHandoff(state.queryClient!, target)+ state.params = "tab=all"+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ React.createElement(+ React.StrictMode,+ null,+ React.createElement(DirectChildHarness),+ ),+ )+ })++ let pending!: Promise<ReturnType<typeof openerResponse>>+ await act(async () => {+ pending = reserveInboxUnreadsResponse(state.queryClient!, openerResponse())+ void pending.catch(() => undefined)+ await Promise.resolve()+ })++ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ expect(getThreadOpenerReservationHandoff(state.queryClient!, "nonce-1")).toBeNull()+ expect(state.queryClient!.refetchQueries).toHaveBeenCalledTimes(1)+ expect(mocks.submit).not.toHaveBeenCalled()+ expect(mocks.replace).not.toHaveBeenCalled()++ await act(async () => renderer.unmount())+ })++ it.each([+ ["terminal-error", null, null],+ ["ready", "parent-other", "opener-other"],+ ] as const)("takes one negative path for %s without consuming child msg", async (+ lifecycle,+ parentChannelId,+ openerMessageId,+ ) => {+ armThreadOpenerReservationHandoff(state.queryClient!, target)+ const renderer = await render("pending")+ await act(async () => {+ renderer.update(React.createElement(Harness, {+ lifecycle,+ parentChannelId,+ openerMessageId,+ }))+ await Promise.resolve()+ })++ expect(mocks.submit).not.toHaveBeenCalled()+ expect(state.queryClient!.refetchQueries).toHaveBeenCalledTimes(1)+ expect(mocks.replace).toHaveBeenCalledWith(+ "/c/channels/server-1/child-1?msg=message-9&tab=all",+ { scroll: false },+ )+ })++ it("terminates once after a true pending-route unmount", async () => {+ armThreadOpenerReservationHandoff(state.queryClient!, target)+ const renderer = await render("pending")+ await act(async () => {+ renderer.unmount()+ await Promise.resolve()+ })+ expect(mocks.submit).not.toHaveBeenCalled()+ expect(state.queryClient!.refetchQueries).toHaveBeenCalledTimes(1)+ })+})diff --git a/src/web/src/hooks/community/thread-opener-read-handoff.ts b/src/web/src/hooks/community/thread-opener-read-handoff.tsnew file mode 100644index 000000000..bc7ffafb5--- /dev/null+++ b/src/web/src/hooks/community/thread-opener-read-handoff.ts@@ -0,0 +1,201 @@+"use client"++import { useCallback, useLayoutEffect, useRef } from "react"+import { usePathname, useRouter, useSearchParams } from "next/navigation"+import { useQueryClient } from "@tanstack/react-query"+import { useCurrentUser } from "@/contexts/community/current-user"+import { channelHref, removeCommunityParam } from "@/lib/community/community-route"+import {+ registerReadSurface,+ releaseReadSurface,+ submitReadIntentGeneration,+} from "./read-coordinator"+import {+ armThreadOpenerReservationHandoff,+ clearThreadOpenerReservationHandoff,+ completeThreadOpenerReservationHandoff,+ getThreadOpenerReservationHandoff,+ registerThreadOpenerRouteLease,+ releaseThreadOpenerRouteLease,+ terminateThreadOpenerReservationHandoff,+ type ThreadOpenerHandoffTarget,+} from "./inbox-read-reservation"++export const THREAD_OPENER_HANDOFF_PARAM = "inboxThreadOpener"++let fallbackNonce = 0++function createNonce() {+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {+ return crypto.randomUUID()+ }+ fallbackNonce += 1+ return `opener-${fallbackNonce}`+}++export function armThreadOpenerReadHandoff(+ queryClient: ReturnType<typeof useQueryClient>,+ target: Omit<ThreadOpenerHandoffTarget, "nonce">,+) {+ const nonce = createNonce()+ armThreadOpenerReservationHandoff(queryClient, { ...target, nonce })+ const href = channelHref(target.serverId, target.childChannelId)+ return `${href}?${THREAD_OPENER_HANDOFF_PARAM}=${encodeURIComponent(nonce)}`+}++export function clearThreadOpenerReadHandoff(+ queryClient: ReturnType<typeof useQueryClient>,+) {+ clearThreadOpenerReservationHandoff(queryClient)+}++type RouteLifecycle = "pending" | "ready" | "terminal-error"++export type ThreadOpenerReadHandoff = NonNullable<+ ReturnType<typeof getThreadOpenerReservationHandoff>+>++export function useThreadOpenerRouteGate({+ serverId,+ childChannelId,+ parentChannelId,+ openerMessageId,+ lifecycle,+}: {+ serverId: string+ childChannelId: string+ parentChannelId: string | null+ openerMessageId: string | null+ lifecycle: RouteLifecycle+}) {+ const queryClient = useQueryClient()+ const router = useRouter()+ const pathname = usePathname()+ const searchParams = useSearchParams()+ const nonce = searchParams.get(THREAD_OPENER_HANDOFF_PARAM)+ const handoff = nonce+ ? getThreadOpenerReservationHandoff(queryClient, nonce)+ : null+ const cleanUrl = useCallback(() => {+ if (!nonce) return+ const search = searchParams.toString()+ const href = `${channelHref(serverId, childChannelId)}${search ? `?${search}` : ""}`+ router.replace(+ removeCommunityParam(href, THREAD_OPENER_HANDOFF_PARAM),+ { scroll: false },+ )+ }, [childChannelId, nonce, router, searchParams, serverId])+ const routeMatches = !!handoff+ && handoff.serverId === serverId+ && handoff.childChannelId === childChannelId+ const routeAligned = pathname === channelHref(serverId, childChannelId)+ const canonicalMatches = routeMatches+ && lifecycle === "ready"+ && handoff.parentChannelId === parentChannelId+ && handoff.openerMessageId === openerMessageId++ useLayoutEffect(() => {+ if (!nonce || !routeAligned) return+ const lease = registerThreadOpenerRouteLease(+ queryClient,+ nonce,+ serverId,+ childChannelId,+ )+ return () => releaseThreadOpenerRouteLease(lease)+ }, [childChannelId, nonce, queryClient, routeAligned, serverId])++ useLayoutEffect(() => {+ if (!nonce || !routeAligned) return+ if (!routeMatches || lifecycle === "terminal-error") {+ terminateThreadOpenerReservationHandoff(queryClient, nonce)+ cleanUrl()+ return+ }+ if (lifecycle === "ready" && !canonicalMatches) {+ terminateThreadOpenerReservationHandoff(queryClient, nonce)+ cleanUrl()+ return+ }+ }, [canonicalMatches, cleanUrl, lifecycle, nonce, queryClient, routeAligned, routeMatches])++ return routeAligned && canonicalMatches && handoff ? handoff : null+}++export function useClaimThreadOpenerReadHandoff(+ target: ReturnType<typeof getThreadOpenerReservationHandoff> | undefined,+) {+ const queryClient = useQueryClient()+ const currentUser = useCurrentUser()+ const router = useRouter()+ const searchParams = useSearchParams()+ const leaseRef = useRef<ReturnType<typeof registerReadSurface> | null>(null)+ const claimedNonceRef = useRef<string | null>(null)+ const lifetimeEpochRef = useRef(0)++ useLayoutEffect(() => {+ if (!target || claimedNonceRef.current === target.nonce) return+ if (leaseRef.current) {+ releaseReadSurface(leaseRef.current)+ leaseRef.current = null+ claimedNonceRef.current = null+ }+ const current = getThreadOpenerReservationHandoff(queryClient, target.nonce)+ if (+ !current+ || current.serverId !== target.serverId+ || current.parentChannelId !== target.parentChannelId+ || current.childChannelId !== target.childChannelId+ || current.openerMessageId !== target.openerMessageId+ || current.openerSeq !== target.openerSeq+ ) {+ terminateThreadOpenerReservationHandoff(queryClient, target.nonce)+ return+ }+ const lease = registerReadSurface(+ queryClient,+ currentUser.id,+ { kind: "timeline", channelId: current.parentChannelId },+ 0,+ "cancel-uncommitted",+ )+ const generation = submitReadIntentGeneration(lease, {+ kind: "timeline",+ channelId: current.parentChannelId,+ messageId: current.openerMessageId,+ seq: current.openerSeq,+ })+ if (generation === null) {+ releaseReadSurface(lease)+ terminateThreadOpenerReservationHandoff(queryClient, current.nonce)+ return+ }+ leaseRef.current = lease+ claimedNonceRef.current = current.nonce+ completeThreadOpenerReservationHandoff(queryClient, current.nonce, generation)+ const search = searchParams.toString()+ const href = `${channelHref(current.serverId, current.childChannelId)}${search ? `?${search}` : ""}`+ router.replace(+ removeCommunityParam(href, THREAD_OPENER_HANDOFF_PARAM),+ { scroll: false },+ )+ }, [currentUser.id, queryClient, router, searchParams, target])++ useLayoutEffect(() => {+ lifetimeEpochRef.current += 1+ return () => {+ const releaseEpoch = ++lifetimeEpochRef.current+ const lease = leaseRef.current+ if (!lease) return+ queueMicrotask(() => {+ if (+ lifetimeEpochRef.current !== releaseEpoch+ || leaseRef.current !== lease+ ) return+ leaseRef.current = null+ claimedNonceRef.current = null+ releaseReadSurface(lease)+ })+ }+ }, [queryClient])+}diff --git a/src/web/src/hooks/community/use-channel-message-feed.ts b/src/web/src/hooks/community/use-channel-message-feed.tsindex 8e6611396..1e0850ee0 100644--- a/src/web/src/hooks/community/use-channel-message-feed.ts+++ b/src/web/src/hooks/community/use-channel-message-feed.ts@@ -58,8 +58,19 @@ export function useChannelMessageFeed({channelId,messages: messagesQuery.messages,scrollRootEl,- snapshotReady: !readState.isFetching,+ snapshotStatus: readState.isFetching+ ? "pending"+ : readSnapshot+ ? "ready"+ : "error",+ feedStatus: messagesQuery.isPending+ ? "pending"+ : messagesQuery.isError+ ? "error"+ : "ready",+ tailAttached: !messagesQuery.hasMoreNewer,confirmedSeq: readSnapshot?.lastReadSeq ?? 0,+ catchUp: () => messagesQuery.refetch(),})const unreadCount = useMemo(() => {const difference = messagesQuery.latestSeq - (readSnapshot?.lastReadSeq ?? 0)diff --git a/src/web/src/hooks/community/use-channel-route-model.subscription.test.ts b/src/web/src/hooks/community/use-channel-route-model.subscription.test.tsindex 081fbe95b..808eb26c5 100644--- a/src/web/src/hooks/community/use-channel-route-model.subscription.test.ts+++ b/src/web/src/hooks/community/use-channel-route-model.subscription.test.ts@@ -10,10 +10,12 @@ const mocks = vi.hoisted(() => ({replace: vi.fn(),clearLastChannel: vi.fn(),lastChannel: null as string | null,+ server: undefined as undefined | Record<string, unknown>,metaQuery: {data: undefined as undefined | Record<string, unknown>,error: null as unknown,isVerified: false,+ isError: false,},}))@@ -27,15 +29,7 @@ vi.mock("@tanstack/react-query", async () => {return { ...actual, useQueryClient: () => queryClient }})vi.mock("./use-servers", () => ({- useServer: () => ({- server: {- id: "server-1",- categories: [{- id: "cat-1",- channels: [{ id: "forum-1", name: "Forum", type: "forum" }],- }],- },- }),+ useServer: () => ({ server: mocks.server }),}))vi.mock("./use-child-channel-meta", () => ({useChildChannelMeta: () => mocks.metaQuery,@@ -50,11 +44,15 @@ vi.mock("@/lib/community/last-channel", () => ({clearLastChannel: (...args: unknown[]) => mocks.clearLastChannel(...args),}))-import { useChannelRouteModel } from "./use-channel-route-model"+import { buildChannelRouteModel, useChannelRouteModel } from "./use-channel-route-model"-function Harness() {- useChannelRouteModel("server-1", "server-1", "post-1")- return null+function Harness({ channelId = "post-1" }: { channelId?: string }) {+ const result = useChannelRouteModel("server-1", "server-1", channelId)+ return React.createElement("span", { "data-lifecycle": result.routeLifecycle })+}++function lifecycle(renderer: TestRenderer.ReactTestRenderer) {+ return renderer.root.findByType("span").props["data-lifecycle"]}beforeEach(() => {@@ -64,7 +62,14 @@ beforeEach(() => {mocks.replace.mockClear()mocks.clearLastChannel.mockClear()mocks.lastChannel = null- mocks.metaQuery = { data: undefined, error: null, isVerified: false }+ mocks.server = {+ id: "server-1",+ categories: [{+ id: "cat-1",+ channels: [{ id: "forum-1", name: "Forum", type: "forum" }],+ }],+ }+ mocks.metaQuery = { data: undefined, error: null, isVerified: false, isError: false }})afterEach(() => {@@ -72,6 +77,52 @@ afterEach(() => {})describe("useChannelRouteModel subscription ownership", () => {+ it("moves a top-level channel from pending to ready when server categories hydrate", () => {+ mocks.server = undefined+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(Harness, { channelId: "forum-1" }))+ })+ expect(lifecycle(renderer!)).toBe("pending")++ mocks.server = {+ id: "server-1",+ categories: [{+ id: "cat-1",+ channels: [{ id: "forum-1", name: "Forum", type: "forum" }],+ }],+ }+ act(() => {+ renderer!.update(React.createElement(Harness, { channelId: "forum-1" }))+ })++ expect(lifecycle(renderer!)).toBe("ready")+ expect(mocks.metaQuery.isVerified).toBe(false)+ act(() => renderer!.unmount())+ })++ it("does not hydrate a verified child with the previous child's store metadata", () => {+ const model = buildChannelRouteModel(+ {+ id: "server-1",+ categories: [{+ id: "cat-1",+ channels: [{ id: "forum-1", name: "Forum", type: "forum" }],+ }],+ } as never,+ {+ id: "post-old",+ parentChannelId: "forum-1",+ parentMessageId: "opener-old",+ } as never,+ "post-1",+ { channelId: "post-1", settled: true },+ )++ expect(model.currentChannelMeta).toBeNull()+ expect(model.routeHydrated).toBe(false)+ })+it("does not unsubscribe/resubscribe when metadata becomes verified", () => {let renderer: TestRenderer.ReactTestRendereract(() => {@@ -79,6 +130,7 @@ describe("useChannelRouteModel subscription ownership", () => {})expect(mocks.subscribe).toHaveBeenCalledTimes(1)expect(mocks.unsubscribe).not.toHaveBeenCalled()+ expect(lifecycle(renderer!)).toBe("pending")mocks.metaQuery = {data: {@@ -95,6 +147,7 @@ describe("useChannelRouteModel subscription ownership", () => {},error: null,isVerified: true,+ isError: false,}act(() => {renderer!.update(React.createElement(Harness))@@ -106,11 +159,27 @@ describe("useChannelRouteModel subscription ownership", () => {parentChannelId: "forum-1",parentMessageId: "opener-1",})+ expect(lifecycle(renderer!)).toBe("ready")act(() => renderer!.unmount())expect(mocks.unsubscribe).toHaveBeenCalledTimes(1)})+ it("exposes terminal-error only after the child metadata query errors", () => {+ mocks.metaQuery = {+ data: undefined,+ error: new Error("metadata unavailable"),+ isVerified: false,+ isError: true,+ }+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(Harness))+ })+ expect(lifecycle(renderer!)).toBe("terminal-error")+ act(() => renderer!.unmount())+ })+it("clears an exact flat last-channel value when verified metadata is archived", () => {mocks.lastChannel = "post-1"mocks.metaQuery = {@@ -128,6 +197,7 @@ describe("useChannelRouteModel subscription ownership", () => {},error: null,isVerified: true,+ isError: false,}let renderer: TestRenderer.ReactTestRendererdiff --git a/src/web/src/hooks/community/use-channel-route-model.ts b/src/web/src/hooks/community/use-channel-route-model.tsindex 89cece2ae..f96c0f99b 100644--- a/src/web/src/hooks/community/use-channel-route-model.ts+++ b/src/web/src/hooks/community/use-channel-route-model.ts@@ -29,7 +29,12 @@ export function buildChannelRouteModel(const channel = channels.find((candidate) => candidate.id === channelId) ?? nullconst isChild = !channel && !!server?.categoriesconst metaSettled = !isChild || (metaState?.channelId === channelId && metaState.settled)- const channelMeta = !isChild || metaSettled ? currentChannelMeta : null+ const currentMetaMatches = !currentChannelMeta+ || !("id" in currentChannelMeta)+ || currentChannelMeta.id === channelId+ const channelMeta = !isChild || (metaSettled && currentMetaMatches)+ ? currentChannelMeta+ : nullconst parent = channelMeta?.parentChannelId? channels.find((candidate) => candidate.id === channelMeta.parentChannelId) ?? null: null@@ -68,6 +73,15 @@ export function useChannelRouteModel(serverId: string, serverParam: string, chan),[channelId, currentChannelMeta, isChild, metaQuery.isVerified, server],)+ const routeLifecycle = !server?.categories+ ? "pending" as const+ : !isChild+ ? "ready" as const+ : metaQuery.isError+ ? "terminal-error" as const+ : model.routeHydrated+ ? "ready" as const+ : "pending" as constuseEffect(() => {useCommunityStore.getState().setCurrentChannelId(channelId)return () => { useCommunityStore.getState().setCurrentChannelId(null) }@@ -98,5 +112,5 @@ export function useChannelRouteModel(serverId: string, serverParam: string, chantoastApiError(metaQuery.error, "Failed to load thread")}}, [channelId, isChild, metaQuery.data, metaQuery.error, metaQuery.isVerified, queryClient, router, serverId, serverParam])- return model+ return { ...model, routeLifecycle }}diff --git a/src/web/src/hooks/community/use-channel-watermark.ts b/src/web/src/hooks/community/use-channel-watermark.tsindex d30f55f71..13c2f98da 100644--- a/src/web/src/hooks/community/use-channel-watermark.ts+++ b/src/web/src/hooks/community/use-channel-watermark.ts@@ -8,20 +8,29 @@ export function useChannelWatermark({channelId,messages,scrollRootEl,- snapshotReady,+ snapshotStatus,+ feedStatus,+ tailAttached,confirmedSeq,+ catchUp,}: {channelId: string | null | undefinedmessages: Msg[]scrollRootEl: HTMLElement | null- snapshotReady: boolean+ snapshotStatus: "pending" | "ready" | "error"+ feedStatus: "pending" | "ready" | "error"+ tailAttached: booleanconfirmedSeq: number+ catchUp: () => Promise<unknown>}) {useTimelineReadObserver({channelId,messages,scrollRootEl,- snapshotReady,+ snapshotStatus,+ feedStatus,+ tailAttached,confirmedSeq,+ catchUp,})}diff --git a/src/web/src/hooks/community/use-dm-watermark.ts b/src/web/src/hooks/community/use-dm-watermark.tsindex 211c03e91..67742d789 100644--- a/src/web/src/hooks/community/use-dm-watermark.ts+++ b/src/web/src/hooks/community/use-dm-watermark.ts@@ -8,20 +8,29 @@ export function useDmWatermark({dmId,messages,scrollRootEl,- snapshotReady,+ snapshotStatus,+ feedStatus,+ tailAttached,confirmedSeq,+ catchUp,}: {dmId: string | null | undefinedmessages: Msg[]scrollRootEl: HTMLElement | null- snapshotReady: boolean+ snapshotStatus: "pending" | "ready" | "error"+ feedStatus: "pending" | "ready" | "error"+ tailAttached: booleanconfirmedSeq: number+ catchUp: () => Promise<unknown>}) {useTimelineReadObserver({channelId: dmId,messages,scrollRootEl,- snapshotReady,+ snapshotStatus,+ feedStatus,+ tailAttached,confirmedSeq,+ catchUp,})}diff --git a/src/web/src/hooks/community/use-forum-feed.test.ts b/src/web/src/hooks/community/use-forum-feed.test.tsindex 1f1f0ab90..0521e8e3c 100644--- a/src/web/src/hooks/community/use-forum-feed.test.ts+++ b/src/web/src/hooks/community/use-forum-feed.test.ts@@ -118,7 +118,7 @@ describe("mapForumFeedPages", () => {],included: {parentMessages: [- { id: "m2", channelId: "forum_1", seq: 42, content: " Opener title ", authorId: "u2", authorName: "Alice", authorImage: null },+ { id: "m2", channelId: "forum_1", seq: 42, content: " Opener title ", authorId: "u2", authorName: "Alice", authorImage: null, createdAt: "2026-08-08T00:15:00.000Z" },],firstMessages: [{ channelId: "t2", content: "First reply preview" }],tags: [{ messageId: "m2", tag: "bug" }, { messageId: "m2", tag: "help" }],@@ -155,6 +155,7 @@ describe("mapForumFeedPages", () => {expect(result[1]).toMatchObject({name: " Opener title ",parentSeq: 42,+ openerCreatedAt: "2026-08-08T00:15:00.000Z",authorId: "u2",authorAvatar: "A",preview: "First reply preview",diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.tsindex a895250e8..84ce0ebf6 100644--- a/src/web/src/hooks/community/use-forum-feed.ts+++ b/src/web/src/hooks/community/use-forum-feed.ts@@ -25,6 +25,7 @@ type IncludedMessage = {id: stringchannelId: stringseq: number+ createdAt?: stringcontent: stringauthorId: stringauthorName: string@@ -148,6 +149,7 @@ export function mapForumFeedPages(pages: ForumFeedPage[]): ForumThread[] {authorId: opener?.authorId ?? thread.creatorId ?? "",authorAvatar: opener?.authorImage ?? avatarInitial(opener?.authorName ?? ""),openerMessageId: thread.parentMessageId ?? "",+ ...(opener?.createdAt ? { openerCreatedAt: opener.createdAt } : {}),...(opener ? { parentSeq: opener.seq } : {}),tags: thread.parentMessageId ? tagsByMessage.get(thread.parentMessageId) ?? [] : [],preview: (first?.content ?? "").slice(0, 100),diff --git a/src/web/src/hooks/community/use-inbox.test.ts b/src/web/src/hooks/community/use-inbox.test.tsindex d0e904d96..7bb6b7974 100644--- a/src/web/src/hooks/community/use-inbox.test.ts+++ b/src/web/src/hooks/community/use-inbox.test.ts@@ -1,6 +1,13 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"import { describe, it, expect, vi, beforeEach } from "vitest"-import { QueryClient } from "@tanstack/react-query"+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"+import {+ disposeInboxReadReservation,+ registerInboxReadReservationSurface,+ takeInboxReadReservationNegative,+} from "./inbox-read-reservation"const apiFetchMock = vi.fn()vi.mock("@/lib/api/client", () => ({@@ -40,6 +47,63 @@ describe("useInboxUnreads / inboxUnreadsQueryFn", () => {expect(signal?.aborted).toBe(true)await pending})++ it("fences the production query result until a focused candidate is classified", async () => {+ const data = {+ servers: [{ channels: [{+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ hasDirectUnread: true,+ children: [],+ }] }],+ dms: [],+ }+ apiFetchMock.mockResolvedValueOnce(data).mockResolvedValueOnce(data)+ const { inboxUnreadsReservedQueryFn } = await import("./use-inbox")+ const qc = new QueryClient()+ const seen = vi.fn()+ const lease = registerInboxReadReservationSurface(qc, "focused", seen)+ const first = inboxUnreadsReservedQueryFn(qc)()+ void first.catch(() => undefined)+ await vi.waitFor(() => expect(seen).toHaveBeenLastCalledWith(expect.objectContaining({+ channelId: "focused",+ })))++ takeInboxReadReservationNegative(lease)+ await expect(first).rejects.toMatchObject({ name: "AbortError" })+ await expect(inboxUnreadsReservedQueryFn(qc)()).resolves.toBe(data)+ disposeInboxReadReservation(qc)+ })++ it("wires the production hook to its live QueryClient across rerenders", async () => {+ apiFetchMock.mockResolvedValue({ servers: [], dms: [] })+ const { useInboxUnreads } = await import("./use-inbox")+ const qc = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ })+ function Harness() {+ const inbox = useInboxUnreads()+ return React.createElement("span", {+ "data-count": inbox.servers.length + inbox.dms.length,+ })+ }+ const tree = React.createElement(+ QueryClientProvider,+ { client: qc },+ React.createElement(Harness),+ )+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(tree)+ })+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())+ await act(async () => {+ renderer.update(tree)+ })+ expect(renderer.root.findByType("span").props["data-count"]).toBe(0)+ expect(apiFetchMock).toHaveBeenCalledOnce()+ await act(async () => renderer.unmount())+ })})describe("useInboxMentions / inboxMentionsQueryFn", () => {diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.tsindex dd1859ac0..ad89a41f7 100644--- a/src/web/src/hooks/community/use-inbox.ts+++ b/src/web/src/hooks/community/use-inbox.ts@@ -1,9 +1,11 @@"use client"-import { useQuery, keepPreviousData, type UseQueryResult } from "@tanstack/react-query"+import { useMemo } from "react"+import { useQuery, useQueryClient, keepPreviousData, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import type { UnreadServer, UnreadDm, Mention, Marked } from "@/lib/community/models/inbox"+import { reserveInboxUnreadsResponse } from "./inbox-read-reservation"class StaleReadError extends Error {constructor() { super("stale D1 read"); this.name = "StaleReadError" }@@ -40,13 +42,21 @@ export const inboxUnreadsQueryFn = ({ signal }: { signal?: AbortSignal } = {}) ={ signal },).then(throwIfStale)+export const inboxUnreadsReservedQueryFn = (queryClient: ReturnType<typeof useQueryClient>) => (+ { signal }: { signal?: AbortSignal } = {},+) => inboxUnreadsQueryFn({ signal }).then(+ (data) => reserveInboxUnreadsResponse(queryClient, data, signal),+)+export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {servers: UnreadServer[]dms: UnreadDm[]} {+ const queryClient = useQueryClient()+ const queryFn = useMemo(() => inboxUnreadsReservedQueryFn(queryClient), [queryClient])const query = useQuery({queryKey: communityKeys.inboxUnreads(),- queryFn: inboxUnreadsQueryFn,+ queryFn,placeholderData: keepPreviousData,})return {diff --git a/src/web/src/hooks/community/use-read-observer.test.ts b/src/web/src/hooks/community/use-read-observer.test.tsindex 6bb565730..bdc11e611 100644--- a/src/web/src/hooks/community/use-read-observer.test.ts+++ b/src/web/src/hooks/community/use-read-observer.test.ts@@ -5,13 +5,63 @@ const queryClient = {}const coordinator = vi.hoisted(() => ({register: vi.fn(() => ({ lease: "timeline" })),release: vi.fn(),+ confirm: vi.fn(),resume: vi.fn(),- submit: vi.fn(() => true),+ submit: vi.fn(() => 1),}))+const reservation = vi.hoisted(() => ({+ register: vi.fn(() => ({ lease: "reservation" })),+ release: vi.fn(),+ promote: vi.fn(),+ negative: vi.fn(() => true),+}))+const hookState = vi.hoisted(() => ({+ candidate: null as null | {+ channelId: string+ lastMessageAt: string+ fingerprint: string+ openerUnread: boolean+ },+}))+const refState = vi.hoisted(() => {+ let cursor = 0+ const slots: Array<{ current: unknown }> = []+ return {+ persistent: false,+ beginRender() {+ cursor = 0+ },+ next(initial: unknown) {+ const index = cursor+++ const existing = slots[index]+ if (existing) return existing+ const value = { current: initial }+ slots[index] = value+ return value+ },+ reset() {+ this.persistent = false+ cursor = 0+ slots.length = 0+ },+ }+})vi.mock("react", () => ({- useRef: (initial: unknown) => ({ current: initial }),+ useCallback: (callback: unknown) => callback,+ useRef: (initial: unknown) => {+ if (!refState.persistent) return { current: initial }+ return refState.next(initial)+ },+ useState: (initial: unknown) => initial === null+ ? [hookState.candidate, (next: unknown) => {+ hookState.candidate = typeof next === "function"+ ? (next as (value: typeof hookState.candidate) => typeof hookState.candidate)(hookState.candidate)+ : next as typeof hookState.candidate+ }]+ : [initial, vi.fn()],useEffect: (effect: () => void | (() => void)) => effects.push(effect),+ useLayoutEffect: (effect: () => void | (() => void)) => effects.push(effect),}))vi.mock("@tanstack/react-query", () => ({@@ -25,8 +75,16 @@ vi.mock("@/contexts/community/current-user", () => ({vi.mock("./read-coordinator", () => ({registerReadSurface: (...args: unknown[]) => coordinator.register(...args),releaseReadSurface: (...args: unknown[]) => coordinator.release(...args),+ confirmReadSurface: (...args: unknown[]) => coordinator.confirm(...args),resumeReadCoordinator: (...args: unknown[]) => coordinator.resume(...args),- submitReadIntent: (...args: unknown[]) => coordinator.submit(...args),+ submitReadIntentGeneration: (...args: unknown[]) => coordinator.submit(...args),+}))++vi.mock("./inbox-read-reservation", () => ({+ registerInboxReadReservationSurface: (...args: unknown[]) => reservation.register(...args),+ releaseInboxReadReservationSurface: (...args: unknown[]) => reservation.release(...args),+ promoteInboxReadReservation: (...args: unknown[]) => reservation.promote(...args),+ takeInboxReadReservationNegative: (...args: unknown[]) => reservation.negative(...args),}))import { useTimelineReadObserver } from "./use-read-observer"@@ -96,14 +154,18 @@ function trigger(record: ObserverRecord, target: Element, ratio = 1) {}function useTestRender(options: Partial<Parameters<typeof useTimelineReadObserver>[0]> = {}) {+ if (refState.persistent) refState.beginRender()const row = makeRow("message-4")const root = makeRoot([row])useTimelineReadObserver({channelId: "channel-1",- messages: [{ id: "message-4", seq: 4, authorId: "other-1" }] as any,+ messages: [{ id: "message-4", seq: 4, authorId: "other-1", createdAt: "t4" }] as any,scrollRootEl: root,- snapshotReady: true,+ snapshotStatus: "ready",+ feedStatus: "ready",+ tailAttached: true,confirmedSeq: 2,+ catchUp: () => Promise.resolve(),...options,})return { row, root }@@ -117,6 +179,8 @@ describe("useTimelineReadObserver", () => {visibilityListeners = new Set()pageShowListeners = new Set()mutationCallback = undefined+ hookState.candidate = null+ refState.reset()vi.clearAllMocks()vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver)vi.stubGlobal("MutationObserver", class {@@ -153,21 +217,23 @@ describe("useTimelineReadObserver", () => {})it("accepts only after the snapshot-ready observer sees a visible foreign row", () => {- useTestRender({ snapshotReady: false })+ useTestRender({ snapshotStatus: "pending" })runEffects()- expect(observers).toHaveLength(0)- expect(coordinator.register).not.toHaveBeenCalled()+ expect(coordinator.register).toHaveBeenCalled()+ trigger(observers[0]!, makeRow("message-4"))+ expect(coordinator.submit).not.toHaveBeenCalled()effects.length = 0- const { row } = useTestRender({ snapshotReady: true })+ vi.clearAllMocks()+ const { row } = useTestRender({ snapshotStatus: "ready" })runEffects()expect(coordinator.register).toHaveBeenCalledWith(queryClient,"viewer-1",{ kind: "timeline", channelId: "channel-1" },- 2,)- trigger(observers[0]!, row)+ expect(coordinator.confirm).toHaveBeenCalledWith({ lease: "timeline" }, 2)+ trigger(observers.at(-1)!, row)expect(coordinator.submit).toHaveBeenCalledWith({ lease: "timeline" }, {kind: "timeline",channelId: "channel-1",@@ -221,6 +287,8 @@ describe("useTimelineReadObserver", () => {visibility = "hidden"trigger(observers[0]!, row)expect(coordinator.submit).not.toHaveBeenCalled()+ expect(reservation.negative).toHaveBeenCalledWith({ lease: "reservation" })+ for (const listener of visibilityListeners) listener()visibility = "visible"for (const listener of visibilityListeners) listener()@@ -229,6 +297,125 @@ describe("useTimelineReadObserver", () => {expect(coordinator.submit).toHaveBeenCalledOnce()})+ it.each([+ { snapshotStatus: "error" as const },+ { feedStatus: "error" as const },+ { tailAttached: false },+ ])("negatively classifies an unusable ready surface: $snapshotStatus$feedStatus$tailAttached", (options) => {+ hookState.candidate = {+ channelId: "channel-1",+ lastMessageAt: "t4",+ fingerprint: "focused-t4",+ openerUnread: false,+ }+ useTestRender(options)+ runEffects()+ expect(reservation.negative).toHaveBeenCalledWith({ lease: "reservation" })+ })++ it("negatively classifies a hidden ready surface before correlating messages", () => {+ hookState.candidate = {+ channelId: "channel-1",+ lastMessageAt: "t4",+ fingerprint: "focused-t4",+ openerUnread: false,+ }+ visibility = "hidden"+ useTestRender()+ runEffects()+ expect(reservation.negative).toHaveBeenCalledWith({ lease: "reservation" })+ })++ it("correlates duplicate timestamps to the highest sequence and requires its DOM node", () => {+ hookState.candidate = {+ channelId: "channel-1",+ lastMessageAt: "t4",+ fingerprint: "focused-t4",+ openerUnread: false,+ }+ const high = makeRow("message-high")+ useTestRender({+ messages: [+ { id: "message-low", seq: 2, authorId: "other-1", createdAt: "t4" },+ { id: "message-high", seq: 5, authorId: "other-1", createdAt: "t4" },+ ],+ scrollRootEl: makeRoot([high]),+ })+ runEffects()+ expect(reservation.negative).not.toHaveBeenCalled()++ effects.length = 0+ vi.clearAllMocks()+ hookState.candidate = {+ channelId: "channel-1",+ lastMessageAt: "t4",+ fingerprint: "focused-t4",+ openerUnread: false,+ }+ useTestRender({ scrollRootEl: makeRoot([]) })+ runEffects()+ expect(reservation.negative).toHaveBeenCalledWith({ lease: "reservation" })+ })++ it("starts one catch-up for an unordered behind tail, then settles that fingerprint", async () => {+ refState.persistent = true+ const candidate = {+ channelId: "channel-1",+ lastMessageAt: "t9",+ fingerprint: "focused-t9",+ openerUnread: false,+ }+ hookState.candidate = candidate+ const catchUp = vi.fn().mockResolvedValue(undefined)+ const messages = [+ { id: "message-8", seq: 8, authorId: "other-1", createdAt: "t8" },+ { id: "message-7", seq: 7, authorId: "other-1", createdAt: "t7" },+ ] as any[]+ useTestRender({ catchUp, messages })+ runEffects()+ expect(catchUp).toHaveBeenCalledOnce()+ expect(reservation.negative).not.toHaveBeenCalled()+ await catchUp.mock.results[0]!.value+ await Promise.resolve()++ effects.length = 0+ hookState.candidate = candidate+ useTestRender({ catchUp, messages })+ runEffects()+ expect(catchUp).toHaveBeenCalledOnce()+ expect(reservation.negative).toHaveBeenCalledOnce()+ expect(reservation.negative).toHaveBeenCalledWith({ lease: "reservation" })+ })++ it.each([+ { messages: [] as any[] },+ { messages: [{ id: "message-10", seq: 10, authorId: "other-1", createdAt: "u10" }] as any[] },+ ])("negatively classifies a missing candidate after the loaded tail is authoritative", ({ messages }) => {+ hookState.candidate = {+ channelId: "channel-1",+ lastMessageAt: "t9",+ fingerprint: "focused-t9",+ openerUnread: false,+ }+ useTestRender({ messages })+ runEffects()+ expect(reservation.negative).toHaveBeenCalledWith({ lease: "reservation" })+ })++ it("negatively classifies the correlated row below the visibility threshold", () => {+ hookState.candidate = {+ channelId: "channel-1",+ lastMessageAt: "t4",+ fingerprint: "focused-t4",+ openerUnread: false,+ }+ const { row } = useTestRender()+ runEffects()+ trigger(observers[0]!, row, 0.1)+ expect(reservation.negative).toHaveBeenCalledWith({ lease: "reservation" })+ expect(coordinator.submit).not.toHaveBeenCalled()+ })+it("fences a recycled node and a callback from a released route scope", () => {const { row } = useTestRender()const cleanups = runEffects()diff --git a/src/web/src/hooks/community/use-read-observer.ts b/src/web/src/hooks/community/use-read-observer.tsindex 0b6df16db..dbba976b2 100644--- a/src/web/src/hooks/community/use-read-observer.ts+++ b/src/web/src/hooks/community/use-read-observer.ts@@ -1,14 +1,23 @@"use client"-import { useEffect, useRef } from "react"+import { useEffect, useLayoutEffect, useRef, useState } from "react"import { useQueryClient } from "@tanstack/react-query"import { useCurrentUser } from "@/contexts/community/current-user"import {+ confirmReadSurface,registerReadSurface,releaseReadSurface,resumeReadCoordinator,- submitReadIntent,+ submitReadIntentGeneration,} from "./read-coordinator"+import {+ promoteInboxReadReservation,+ registerInboxReadReservationSurface,+ releaseInboxReadReservationSurface,+ takeInboxReadReservationNegative,+ type InboxReadCandidate,+ type InboxReadReservationLease,+} from "./inbox-read-reservation"const READ_VISIBILITY_THRESHOLD = 0.2@@ -16,40 +25,141 @@ export type ReadCandidate = {id: stringseq?: numberauthorId?: string+ createdAt?: string}+type Lifecycle = "pending" | "ready" | "error"+export function useTimelineReadObserver({channelId,messages,scrollRootEl,- snapshotReady,+ snapshotStatus,+ feedStatus,+ tailAttached,confirmedSeq,+ catchUp,}: {channelId: string | null | undefinedmessages: ReadCandidate[]scrollRootEl: HTMLElement | null- snapshotReady: boolean+ snapshotStatus: Lifecycle+ feedStatus: Lifecycle+ tailAttached: booleanconfirmedSeq: number+ catchUp: () => Promise<unknown>}) {const queryClient = useQueryClient()const currentUser = useCurrentUser()const messagesRef = useRef(messages)- const readyRef = useRef(snapshotReady)+ const readyRef = useRef(snapshotStatus === "ready" && feedStatus === "ready")+ const candidateRef = useRef<InboxReadCandidate | null>(null)+ const readLeaseRef = useRef<ReturnType<typeof registerReadSurface> | null>(null)+ const reservationLeaseRef = useRef<InboxReadReservationLease | null>(null)+ const catchUpStartedRef = useRef(new Set<string>())+ const catchUpSettledRef = useRef(new Set<string>())+ const [candidate, setCandidate] = useState<InboxReadCandidate | null>(null)+ const [, setCatchUpVersion] = useState(0)- useEffect(() => {+ useLayoutEffect(() => {messagesRef.current = messages- readyRef.current = snapshotReady- }, [messages, snapshotReady])+ readyRef.current = snapshotStatus === "ready" && feedStatus === "ready"+ candidateRef.current = candidate+ }, [candidate, feedStatus, messages, snapshotStatus])- useEffect(() => {- if (!channelId || !scrollRootEl || !snapshotReady) return- if (typeof IntersectionObserver === "undefined") return- const lease = registerReadSurface(+ useLayoutEffect(() => {+ setCandidate(null)+ if (!channelId) return+ const reservationLease = registerInboxReadReservationSurface(+ queryClient,+ channelId,+ setCandidate,+ )+ const readLease = registerReadSurface(queryClient,currentUser.id,{ kind: "timeline", channelId },- confirmedSeq,)+ reservationLeaseRef.current = reservationLease+ readLeaseRef.current = readLease+ return () => {+ reservationLeaseRef.current = null+ readLeaseRef.current = null+ releaseInboxReadReservationSurface(reservationLease)+ releaseReadSurface(readLease)+ }+ }, [channelId, currentUser.id, queryClient])++ useEffect(() => {+ const lease = readLeaseRef.current+ if (!lease || snapshotStatus !== "ready") return+ confirmReadSurface(lease, confirmedSeq)+ }, [confirmedSeq, snapshotStatus])++ useEffect(() => {+ if (!candidate || !channelId) return+ const reservationLease = reservationLeaseRef.current+ if (!reservationLease) return+ if (snapshotStatus === "pending" || feedStatus === "pending" || !scrollRootEl) return+ if (+ snapshotStatus === "error"+ || feedStatus === "error"+ || !tailAttached+ || document.visibilityState !== "visible"+ ) {+ takeInboxReadReservationNegative(reservationLease)+ return+ }+ const correlated = messages+ .filter((message) => message.createdAt === candidate.lastMessageAt)+ .sort((left, right) => (right.seq ?? 0) - (left.seq ?? 0))[0]+ if (!correlated) {+ const loadedTail = messages.reduce<string | undefined>((latest, message) => (+ message.createdAt && (!latest || message.createdAt > latest)+ ? message.createdAt+ : latest+ ), undefined)+ if (+ loadedTail+ && loadedTail < candidate.lastMessageAt+ && !catchUpStartedRef.current.has(candidate.fingerprint)+ ) {+ catchUpStartedRef.current.add(candidate.fingerprint)+ void catchUp().finally(() => {+ catchUpSettledRef.current.add(candidate.fingerprint)+ setCatchUpVersion((value) => value + 1)+ })+ return+ }+ if (+ !loadedTail+ || loadedTail >= candidate.lastMessageAt+ || catchUpSettledRef.current.has(candidate.fingerprint)+ ) {+ takeInboxReadReservationNegative(reservationLease)+ }+ return+ }+ const node = [...scrollRootEl.querySelectorAll<HTMLElement>("[data-msg-id]")]+ .find((element) => element.dataset.msgId === correlated.id)+ if (!node) takeInboxReadReservationNegative(reservationLease)+ }, [+ candidate,+ catchUp,+ channelId,+ feedStatus,+ messages,+ scrollRootEl,+ snapshotStatus,+ tailAttached,+ ])++ useEffect(() => {+ if (!channelId || !scrollRootEl) return+ if (typeof IntersectionObserver === "undefined") return+ const readLease = readLeaseRef.current+ const reservationLease = reservationLeaseRef.current+ if (!readLease || !reservationLease) returnlet observerGeneration = 0const bindings = new WeakMap<Element, { id: string; generation: number }>()const bind = (node: Element) => {@@ -59,26 +169,41 @@ export function useTimelineReadObserver({observer.observe(node)}const observer = new IntersectionObserver((entries) => {- if (!readyRef.current || document.visibilityState !== "visible") return+ if (!readyRef.current) return+ if (document.visibilityState !== "visible") {+ takeInboxReadReservationNegative(reservationLease)+ return+ }for (const entry of entries) {- if (!entry.isIntersecting || entry.intersectionRatio < READ_VISIBILITY_THRESHOLD) continueconst binding = bindings.get(entry.target)if (!binding || binding.generation !== observerGeneration) continueif (!scrollRootEl.contains(entry.target)) continueif ((entry.target as HTMLElement).dataset.msgId !== binding.id) continueconst message = messagesRef.current.find((row) => row.id === binding.id)if (!message?.seq || message.authorId === currentUser.id) continue- submitReadIntent(lease, {+ const activeCandidate = candidateRef.current+ const correlated = activeCandidate?.lastMessageAt === message.createdAt+ if (!entry.isIntersecting || entry.intersectionRatio < READ_VISIBILITY_THRESHOLD) {+ if (correlated) takeInboxReadReservationNegative(reservationLease)+ continue+ }+ const generation = submitReadIntentGeneration(readLease, {kind: "timeline",channelId,messageId: message.id,seq: message.seq,})+ if (generation !== null && correlated) {+ promoteInboxReadReservation(reservationLease, generation)+ }}}, { root: scrollRootEl, threshold: READ_VISIBILITY_THRESHOLD })const sample = () => {- if (document.visibilityState !== "visible") return+ if (document.visibilityState !== "visible") {+ takeInboxReadReservationNegative(reservationLease)+ return+ }observerGeneration += 1scrollRootEl.querySelectorAll<HTMLElement>("[data-msg-id]").forEach((node) => {observer.unobserve(node)@@ -101,29 +226,19 @@ export function useTimelineReadObserver({}})mutations?.observe(scrollRootEl, { childList: true, subtree: true })- const onVisibility = () => sample()- const onPageShow = () => sample()- document.addEventListener("visibilitychange", onVisibility)- window.addEventListener("pageshow", onPageShow)+ document.addEventListener("visibilitychange", sample)+ window.addEventListener("pageshow", sample)return () => {observerGeneration += 1observer.disconnect()mutations?.disconnect()- document.removeEventListener("visibilitychange", onVisibility)- window.removeEventListener("pageshow", onPageShow)- releaseReadSurface(lease)+ document.removeEventListener("visibilitychange", sample)+ window.removeEventListener("pageshow", sample)}- }, [- channelId,- confirmedSeq,- currentUser.id,- queryClient,- scrollRootEl,- snapshotReady,- ])+ }, [channelId, currentUser.id, feedStatus, queryClient, scrollRootEl, snapshotStatus])useEffect(() => {- if (!channelId || !snapshotReady || document.visibilityState !== "visible") return+ if (!channelId || snapshotStatus !== "ready" || document.visibilityState !== "visible") returnresumeReadCoordinator(queryClient)- }, [channelId, messages, queryClient, snapshotReady])+ }, [channelId, messages, queryClient, snapshotStatus])}diff --git a/src/web/src/lib/community/models/inbox.ts b/src/web/src/lib/community/models/inbox.tsindex 47d63b764..bf675f8dc 100644--- a/src/web/src/lib/community/models/inbox.ts+++ b/src/web/src/lib/community/models/inbox.ts@@ -49,10 +49,13 @@ type UnreadChild = {type?: EntityKindlastMessageAt: stringmentionCount: number- // Present when this row projects an unread opener from the parent forum.- // The child id remains the navigation target; this opener id is the parent- // channel's progressive-read target.+ // Required together when canonical parent-opener metadata is available.+ // The child id remains the navigation target; opener seq belongs to the+ // independent parent-channel progressive read cursor.+ parentChannelId?: stringopenerMessageId?: string+ openerSeq?: number+ openerUnread?: boolean}// "Unreads" — channels with unread messages, grouped by server. Each channel@@ -69,6 +72,7 @@ export type UnreadServer = {type?: EntityKindlastMessageAt: stringmentionCount: number+ hasDirectUnread?: booleanchildren: UnreadChild[]}>}diff --git a/src/web/src/lib/community/models/message.ts b/src/web/src/lib/community/models/message.tsindex 6e514563c..9565fa2d8 100644--- a/src/web/src/lib/community/models/message.ts+++ b/src/web/src/lib/community/models/message.ts@@ -116,6 +116,7 @@ export type ForumThread = Thread & {authorId: stringauthorAvatar: stringopenerMessageId: string+ openerCreatedAt?: stringtags: string[]preview: string// The post's participant (notify) set — creator first, then whoeverdiff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.tsindex 10fc1101c..9853912b7 100644--- a/src/web/src/lib/community/testids.ts+++ b/src/web/src/lib/community/testids.ts@@ -31,6 +31,8 @@ export const tid = {newDivider: "community-new-divider",typingIndicator: "community-typing-indicator",dmBlockedNotice: "community-dm-blocked-notice",+ dmHeader: "community-dm-header",+ dmHeaderTitle: "community-dm-header-title",profileCard: "community-profile-card",profileContextBadge: "community-profile-context-badge",profileBotBadge: "community-profile-bot-badge",diff --git a/src/web/src/test/e2e-ui/04-dm.spec.ts b/src/web/src/test/e2e-ui/04-dm.spec.tsindex f216b81f4..691043eee 100644--- a/src/web/src/test/e2e-ui/04-dm.spec.ts+++ b/src/web/src/test/e2e-ui/04-dm.spec.ts@@ -142,20 +142,18 @@ test.describe.serial("direct messages", () => {try {await alice.page.goto(`/c/me/${dmId}`)- await expect(alice.page.getByRole("heading", {- level: 1,- name: new RegExp(userName("bob")),- })).toBeVisible({ timeout: 20_000 })+ const dmHeader = alice.page.getByTestId(tid.dmHeader)+ const dmTitle = alice.page.getByTestId(tid.dmHeaderTitle)+ await expect(dmHeader).toHaveCount(1, { timeout: 20_000 })+ await expect(dmTitle).toContainText(userName("bob"))await expect(alice.page.getByTestId(tid.composerInput)).toBeVisible()await expect(alice.page.getByTestId(tid.messageScroller).locator('[data-slot="skeleton"]')).not.toHaveCount(0)releaseRead()await readSettledawait messagesRequest- await expect(alice.page.getByRole("heading", {- level: 1,- name: new RegExp(userName("bob")),- })).toBeVisible()+ await expect(dmHeader).toHaveCount(1)+ await expect(dmTitle).toContainText(userName("bob"))await expect(alice.page.getByTestId(tid.composerInput)).toBeVisible()await expect(alice.page.getByTestId(tid.messageScroller).locator('[data-slot="skeleton"]')).not.toHaveCount(0)await expect.poll(() => wsProxy.heldConnectionCount()).toBe(1)diff --git a/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts b/src/web/src/test/e2e-ui/34-inbox-read-race.spec.tsindex 8310ebdb6..0702aa7e5 100644--- a/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts+++ b/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts@@ -8,6 +8,7 @@ import {seedJoinServer,seedMessage,seedServer,+ seedThread,} from "./_fixtures/seed"import {communityFrameEvents,@@ -20,6 +21,67 @@ function deferred() {return { promise, resolve }}+async function installReadObserverGate(+ page: Parameters<typeof gotoAfterUserWsAuth>[0],+) {+ 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>).__inboxReadObserverGate = {+ 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+ }>).__inboxReadObserverGate+ return gate[name]()+ }, method)+ return {+ block: () => invoke("block"),+ pending: () => invoke("pending") as Promise<number>,+ release: () => invoke("release"),+ }+}+async function watchInboxRow(page: Parameters<typeof gotoAfterUserWsAuth>[0], testId: string) {const key = `__inboxRace_${testId}`await page.evaluate(({ key, testId }) => {@@ -60,6 +122,7 @@ test.describe.serial("Inbox/read refresh ownership", () => {await seedJoinServer("alice", "bob", serverId)const dmId = await seedDm("alice", userId("bob"))const { context, page } = await asUser("bob")+ const readObserverGate = await installReadObserverGate(page)const proxy = await proxyCommunityWebSockets(context)await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelA}`)const initialInbox = page.waitForResponse((response) => (@@ -79,14 +142,11 @@ test.describe.serial("Inbox/read refresh ownership", () => {}))const requestStart = requests.lengthconst frameStart = proxy.frames.length- const firstReadGate = deferred()- const firstReadStarted = deferred()- await page.route(`**/api/community/channels/${channelA}/read`, async (route) => {- if (route.request().method() !== "PUT") return route.continue()- firstReadStarted.resolve()- await firstReadGate.promise- await route.continue()- })+ await readObserverGate.block()+ const staleInboxResponse = page.waitForResponse((response) => (+ response.request().method() === "GET"+ && new URL(response.url()).pathname === "/api/community/users/me/inbox/unreads"+ ))const readResponse = page.waitForResponse((response) => (response.request().method() === "PUT"&& new URL(response.url()).pathname === `/api/community/channels/${channelA}/read`@@ -96,10 +156,24 @@ test.describe.serial("Inbox/read refresh ownership", () => {const bodyDm = `background dm ${stamp}`const messageA = await seedMessage("alice", channelA, bodyA)await expect(page.getByText(bodyA, { exact: true })).toBeVisible({ timeout: 20_000 })- await firstReadStarted.promise+ const staleResponse = await staleInboxResponse+ expect(staleResponse.status()).toBe(200)+ const stalePayload = await staleResponse.json() as {+ servers: Array<{ channels: Array<{+ channelId: string+ children: Array<{ channelId: string }>+ }> }>+ dms: Array<{ channelId: string }>+ }+ expect(stalePayload.servers.some((server) => server.channels.some((channel) => (+ channel.channelId === channelA+ || channel.children.some((child) => child.channelId === channelA)+ )))).toBe(true)+ expect(await readObserverGate.pending()).toBeGreaterThan(0)+ await expect(page.getByTestId(tid.inboxUnreadChannel(channelA))).toHaveCount(0)const messageB = await seedMessage("alice", channelB, bodyB)const messageDm = await seedDmMessage("alice", dmId, bodyDm)- firstReadGate.resolve()+ await readObserverGate.release()expect((await readResponse).status()).toBe(200)await expect(page.getByTestId(tid.inboxUnreadChannel(channelB))).toBeVisible({ timeout: 20_000 })await expect(page.getByTestId(tid.inboxUnreadDm(dmId))).toBeVisible({ timeout: 20_000 })@@ -124,7 +198,7 @@ test.describe.serial("Inbox/read refresh ownership", () => {&& request.path === "/api/community/users/me/inbox/unreads"))expect(readIndex).toBeGreaterThanOrEqual(0)- expect(inboxIndex).toBeGreaterThan(readIndex)+ expect(inboxIndex).toBeLessThan(readIndex)const snapshot = await (await page.request.get("/api/community/users/me/read-state",@@ -180,6 +254,185 @@ test.describe.serial("Inbox/read refresh ownership", () => {expect(puts).toBe(2)})+ test("an Inbox forum child claims only its exact opener and preserves a later opener", async ({ asUser }) => {+ const stamp = Date.now()+ const serverId = await seedServer("alice", `Inbox opener handoff ${stamp}`)+ const forumId = await seedChannel("alice", serverId, `handoff-forum-${stamp}`, "forum")+ await seedJoinServer("alice", "bob", serverId)+ const alice = await asUser("alice")+ const createEmptyPost = async (label: string) => {+ const response = await alice.page.request.post(+ `/api/community/channels/${forumId}/messages`,+ { data: { content: label, nonce: `e2e:${crypto.randomUUID()}:opener` } },+ )+ expect(response.status()).toBe(201)+ return (await response.json() as { threadId: string }).threadId+ }+ const firstChildId = await createEmptyPost(`First opener ${stamp}`)+ const laterChildId = await createEmptyPost(`Later opener ${stamp}`)++ const { page } = await asUser("bob")+ await gotoAfterUserWsAuth(page, "/c/me")+ const unreadResponse = await page.request.get("/api/community/users/me/inbox/unreads")+ expect(unreadResponse.status()).toBe(200)+ const unread = await unreadResponse.json() as {+ servers: Array<{ channels: Array<{ channelId: string; children: Array<{+ channelId: string+ openerMessageId: string+ openerSeq: number+ openerUnread: boolean+ }> }> }>+ }+ const children = unread.servers+ .flatMap((server) => server.channels)+ .find((channel) => channel.channelId === forumId)?.children ?? []+ const first = children.find((child) => child.channelId === firstChildId)+ const later = children.find((child) => child.channelId === laterChildId)+ expect(first).toMatchObject({ openerUnread: true })+ expect(later).toMatchObject({ openerUnread: true })++ const parentTargets: string[] = []+ const childTargets: string[] = []+ page.on("request", (request) => {+ if (request.method() !== "PUT") return+ const path = new URL(request.url()).pathname+ const target = (request.postDataJSON() as { lastReadMessageId?: string } | null)+ ?.lastReadMessageId+ if (!target) return+ if (path === `/api/community/channels/${forumId}/read`) parentTargets.push(target)+ if (path === `/api/community/channels/${firstChildId}/read`) childTargets.push(target)+ })++ await page.getByRole("button", { name: "Inbox" }).click()+ await expect(page.getByTestId(tid.inboxUnreadChild(firstChildId))).toBeVisible()+ const parentRead = page.waitForResponse((response) => (+ response.request().method() === "PUT"+ && new URL(response.url()).pathname === `/api/community/channels/${forumId}/read`+ ))+ await page.getByTestId(tid.inboxUnreadChild(firstChildId)).click()+ expect((await parentRead).status()).toBe(200)+ await expect.poll(() => new URL(page.url()).searchParams.has("inboxThreadOpener")).toBe(false)+ expect(parentTargets).toEqual([first!.openerMessageId])+ expect(childTargets).toEqual([])++ await page.getByRole("button", { name: "Inbox" }).click()+ await expect(page.getByTestId(tid.inboxUnreadChild(firstChildId))).toHaveCount(0)+ await expect(page.getByTestId(tid.inboxUnreadChild(laterChildId))).toBeVisible()+ const snapshot = await (await page.request.get(+ "/api/community/users/me/read-state",+ )).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }+ expect(snapshot.readStates.find((row) => row.channelId === forumId)?.lastReadSeq)+ .toBe(first!.openerSeq)+ expect(snapshot.readStates.some((row) => row.channelId === firstChildId)).toBe(false)+ })++ test("eligible text children enrich opener state without widening participation", async ({ asUser }) => {+ const stamp = Date.now()+ const serverId = await seedServer("alice", `Inbox text opener ${stamp}`)+ const parentId = await seedChannel("alice", serverId, `text-parent-${stamp}`)+ await seedJoinServer("alice", "bob", serverId)++ const readOpenerId = await seedMessage("alice", parentId, `Already-read opener ${stamp}`)+ const readChildId = await seedThread("alice", readOpenerId, `Read opener thread ${stamp}`)+ await seedMessage("bob", readChildId, `Bob joins read child ${stamp}`)+ await seedMessage("alice", readChildId, `Unread reply under read opener ${stamp}`)++ const { page } = await asUser("bob")+ const markRead = await page.request.put(`/api/community/channels/${parentId}/read`, {+ data: { lastReadMessageId: readOpenerId },+ })+ expect(markRead.status()).toBe(200)++ const unreadOpenerId = await seedMessage("alice", parentId, `Unread opener ${stamp}`)+ const unreadChildId = await seedThread("alice", unreadOpenerId, `Unread opener thread ${stamp}`)+ await seedMessage("bob", unreadChildId, `Bob joins unread child ${stamp}`)+ await seedMessage("alice", unreadChildId, `Unread reply under unread opener ${stamp}`)++ const nonParticipantOpenerId = await seedMessage("alice", parentId, `Nonparticipant opener ${stamp}`)+ const nonParticipantChildId = await seedThread(+ "alice",+ nonParticipantOpenerId,+ `Nonparticipant thread ${stamp}`,+ )+ await seedMessage("alice", nonParticipantChildId, `Invisible child reply ${stamp}`)+ await seedMessage("alice", parentId, `Later parent message ${stamp}`)++ await gotoAfterUserWsAuth(page, "/c/me")+ const unreadResponse = await page.request.get("/api/community/users/me/inbox/unreads")+ expect(unreadResponse.status()).toBe(200)+ const unread = await unreadResponse.json() as {+ servers: Array<{ channels: Array<{ channelId: string; children: Array<{+ channelId: string+ openerMessageId?: string+ openerSeq?: number+ openerUnread?: boolean+ }> }> }>+ }+ const parent = unread.servers+ .flatMap((server) => server.channels)+ .find((channel) => channel.channelId === parentId)+ const readChild = parent?.children.find((child) => child.channelId === readChildId)+ const unreadChild = parent?.children.find((child) => child.channelId === unreadChildId)+ expect(readChild).toMatchObject({+ openerMessageId: readOpenerId,+ openerUnread: false,+ })+ expect(unreadChild).toMatchObject({+ openerMessageId: unreadOpenerId,+ openerUnread: true,+ })+ expect(parent?.children.some((child) => child.channelId === nonParticipantChildId)).toBe(false)++ const puts: Array<{ channelId: string; target: string }> = []+ page.on("request", (request) => {+ if (request.method() !== "PUT") return+ const match = new URL(request.url()).pathname.match(/^\/api\/community\/channels\/([^/]+)\/read$/)+ const target = (request.postDataJSON() as { lastReadMessageId?: string } | null)+ ?.lastReadMessageId+ if (match?.[1] && target) puts.push({ channelId: match[1], target })+ })++ await page.getByRole("button", { name: "Inbox" }).click()+ await expect(page.getByTestId(tid.inboxUnreadChild(readChildId))).toBeVisible()+ const readChildPut = page.waitForResponse((response) => (+ response.request().method() === "PUT"+ && new URL(response.url()).pathname === `/api/community/channels/${readChildId}/read`+ ))+ await page.getByTestId(tid.inboxUnreadChild(readChildId)).click()+ expect((await readChildPut).status()).toBe(200)+ await page.waitForTimeout(700)+ expect(puts.filter((put) => put.channelId === parentId)).toEqual([])++ await page.getByRole("button", { name: "Inbox" }).click()+ await expect(page.getByTestId(tid.inboxUnreadChild(unreadChildId))).toBeVisible()+ const parentPut = page.waitForResponse((response) => (+ response.request().method() === "PUT"+ && new URL(response.url()).pathname === `/api/community/channels/${parentId}/read`+ ))+ const unreadChildPut = page.waitForResponse((response) => (+ response.request().method() === "PUT"+ && new URL(response.url()).pathname === `/api/community/channels/${unreadChildId}/read`+ ))+ await page.getByTestId(tid.inboxUnreadChild(unreadChildId)).click()+ expect((await parentPut).status()).toBe(200)+ expect((await unreadChildPut).status()).toBe(200)+ expect(puts.filter((put) => put.channelId === parentId)).toEqual([+ { channelId: parentId, target: unreadOpenerId },+ ])++ 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(parentId)).toBe(unreadChild!.openerSeq)+ expect(cursor(readChildId)).toBeGreaterThan(0)+ expect(cursor(unreadChildId)).toBeGreaterThan(0)+ await page.getByRole("button", { name: "Inbox" }).click()+ await expect(page.getByTestId(tid.inboxUnreadChannel(parentId))).toBeVisible()+ await expect(page.getByTestId(tid.inboxUnreadChild(nonParticipantChildId))).toHaveCount(0)+ })+test("a later focused intent keeps its own 500ms generation", async ({ asUser }) => {const stamp = Date.now()const serverId = await seedServer("alice", `Inbox race cutoff ${stamp}`)