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): project exact inbox rows during navigation (#605)
Generecb4a98d575b
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 c53c890d2..27929f220 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@@ -66,12 +66,9 @@ describe("InboxPopover thread opener rows", () => {it("accepts the generic thread callback used by opener-backed buttons", () => {expectTypeOf<Parameters<typeof InboxPopover>[0]>().toMatchTypeOf<{onOpenThread?: (- serverId: string,- parentChannelId: string,- childChannelId: string,- openerMessageId: string,- openerSeq?: number,- openerUnread?: boolean,+ server: UnreadServer,+ parent: UnreadServer["channels"][number],+ child: UnreadServer["channels"][number]["children"][number],) => void}>()})@@ -90,11 +87,15 @@ describe("InboxPopover thread opener rows", () => {expect(row).toBeDefined()await act(async () => row!.props.onClick())- expect(onOpenThread).toHaveBeenCalledWith("s1", "f1", "p1", "m1", 7, true)- expect(onOpenChannel).not.toHaveBeenCalledWith("s1", "p1")+ expect(onOpenThread).toHaveBeenCalledWith(+ unreadFixture()[0],+ unreadFixture()[0]!.channels[0],+ unreadFixture()[0]!.channels[0]!.children[0],+ )+ expect(onOpenChannel).not.toHaveBeenCalled()})- it("keeps reply-only child rows on the existing channel callback", async () => {+ it("passes reply-only children through the same exact thread-row callback", async () => {const onOpenChannel = vi.fn()const onOpenThread = vi.fn()let renderer!: TestRenderer.ReactTestRenderer@@ -108,8 +109,56 @@ describe("InboxPopover thread opener rows", () => {expect(row).toBeDefined()await act(async () => row!.props.onClick())- expect(onOpenChannel).toHaveBeenCalledWith("s1", "t1", "f1")- expect(onOpenThread).not.toHaveBeenCalled()+ expect(onOpenThread).toHaveBeenCalledWith(+ unreadFixture()[0],+ unreadFixture()[0]!.channels[0],+ unreadFixture()[0]!.channels[0]!.children[1],+ )+ expect(onOpenChannel).not.toHaveBeenCalled()+ })++ it("omits a structural parent button while retaining its child rows", async () => {+ const unreads = unreadFixture()+ unreads[0]!.channels[0]!.hasDirectUnread = false+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(InboxPopover, {+ unreads,+ unreadDms: [],+ mentions: [],+ marked: [],+ onOpenThread: vi.fn(),+ }))+ })+ expect(renderer.root.findAllByProps({+ "data-testid": tid.inboxUnreadChannel("f1"),+ })).toHaveLength(0)+ expect(renderer.root.findAllByProps({+ "data-testid": tid.inboxUnreadChild("p1"),+ })).toHaveLength(1)+ })++ it("hides only a projected direct parent and keeps sibling children", async () => {+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(InboxPopover, {+ unreads: unreadFixture(),+ unreadDms: [],+ mentions: [],+ marked: [],+ onOpenThread: vi.fn(),+ isProjected: (target) => target?.kind === "channel-direct",+ }))+ })+ expect(renderer.root.findAllByProps({+ "data-testid": tid.inboxUnreadChannel("f1"),+ })).toHaveLength(0)+ expect(renderer.root.findAllByProps({+ "data-testid": tid.inboxUnreadChild("p1"),+ })).toHaveLength(1)+ expect(renderer.root.findAllByProps({+ "data-testid": tid.inboxUnreadChild("t1"),+ })).toHaveLength(1)})})diff --git a/src/web/src/components/community/shell/community-inbox-popover.tsx b/src/web/src/components/community/shell/community-inbox-popover.tsxindex 5261b1632..5d4d5dede 100644--- a/src/web/src/components/community/shell/community-inbox-popover.tsx+++ b/src/web/src/components/community/shell/community-inbox-popover.tsx@@ -9,8 +9,18 @@ import { ChannelIcon } from "../channels/channel-icon"import { EmptyState } from "../empty-state"import { formatRelativeTime } from "@/lib/community/format-time"import type { Marked, Mention, UnreadDm, UnreadServer } from "@/lib/community/models/inbox"+import {+ inboxChannelRowTarget,+ inboxDmRowTarget,+ inboxMentionRowTarget,+ inboxThreadRowTarget,+ type InboxRowTarget,+} from "@/hooks/community/inbox-read-reservation"import { tid } from "@/lib/community/testids"+type UnreadChannel = UnreadServer["channels"][number]+type UnreadChild = UnreadChannel["children"][number]+function MentionBadge({ count }: { count: number }) {if (count <= 0) return nullreturn (@@ -20,30 +30,36 @@ function MentionBadge({ count }: { count: number }) {)}-function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenThread, onOpenDm }: {+function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenThread, onOpenDm, isProjected }: {servers: UnreadServer[]dms: UnreadDm[]loading?: boolean- onOpenChannel?: (serverId: string, channelId: string, parentChannelId?: string) => void- onOpenThread: (- serverId: string,- parentChannelId: string,- childChannelId: string,- openerMessageId: string,- openerSeq?: number,- openerUnread?: boolean,- ) => void+ onOpenChannel?: (server: UnreadServer, channel: UnreadChannel) => void+ onOpenThread: (server: UnreadServer, parent: UnreadChannel, child: UnreadChild) => voidonOpenDm?: (dm: UnreadDm) => void+ isProjected: (target: InboxRowTarget | null) => boolean}) {- const nothingUnread = servers.length === 0 && dms.length === 0+ const visibleDms = dms.filter((dm) => !isProjected(inboxDmRowTarget(dm)))+ const visibleServers = servers.map((server) => ({+ server,+ channels: server.channels.map((channel) => ({+ channel,+ directVisible: !isProjected(inboxChannelRowTarget(server, channel))+ && channel.hasDirectUnread !== false,+ children: channel.children.filter((child) => (+ !isProjected(inboxThreadRowTarget(server, channel, child))+ )),+ })).filter((group) => group.directVisible || group.children.length > 0),+ })).filter((group) => group.channels.length > 0)+ const nothingUnread = visibleServers.length === 0 && visibleDms.length === 0return (<div className="h-full overflow-y-auto thin-scrollbar p-3">{loading && nothingUnread && <InboxUnreadsSkeleton />}{!loading && nothingUnread && <EmptyState icon={Inbox} label="Caught up" />}- {dms.length > 0 && (+ {visibleDms.length > 0 && (<div className="mb-3"><div className="px-2 pb-1 text-xs font-semibold text-muted-foreground">Direct Messages</div>- {dms.map((d) => (+ {visibleDms.map((d) => (<buttonkey={d.channelId}data-testid={tid.inboxUnreadDm(d.channelId)}@@ -57,40 +73,26 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenThread, onOpen))}</div>)}- {servers.map((s) => (- <div key={s.serverId} className="mb-3">- <div className="px-2 pb-1 text-xs font-semibold text-muted-foreground">{s.serverName}</div>- {s.channels.map((c) => (- <div key={c.channelId}>- <button- data-testid={tid.inboxUnreadChannel(c.channelId)}- onClick={() => onOpenChannel?.(s.serverId, c.channelId)}+ {visibleServers.map(({ server, channels }) => (+ <div key={server.serverId} className="mb-3">+ <div className="px-2 pb-1 text-xs font-semibold text-muted-foreground">{server.serverName}</div>+ {channels.map(({ channel, directVisible, children }) => (+ <div key={channel.channelId}>+ {directVisible && <button+ data-testid={tid.inboxUnreadChannel(channel.channelId)}+ onClick={() => onOpenChannel?.(server, channel)}className="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-accent">- <EntityIcon kind={c.type} className="size-4 shrink-0 text-muted-foreground" />- <span className="min-w-0 flex-1 truncate">{c.channelName}</span>- <MentionBadge count={c.mentionCount} />+ <EntityIcon kind={channel.type} className="size-4 shrink-0 text-muted-foreground" />+ <span className="min-w-0 flex-1 truncate">{channel.channelName}</span>+ <MentionBadge count={channel.mentionCount} /><ChevronRight className="size-4 shrink-0 text-muted-foreground" />- </button>- {/* Unread child threads, indented under their parent. */}- {c.children.map((child) => (+ </button>}+ {children.map((child) => (<buttonkey={child.channelId}data-testid={tid.inboxUnreadChild(child.channelId)}- onClick={() => {- if (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)- }- }}+ onClick={() => onOpenThread(server, channel, child)}className="flex w-full items-center gap-2 rounded-md py-1.5 pl-8 pr-2 text-left text-sm hover:bg-accent"><EntityIcon kind={child.type} className="size-3.5 shrink-0 text-muted-foreground" />@@ -107,17 +109,21 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenThread, onOpen)}-function MentionsTab({ mentions, loading, onOpenMention, onDeleteMention }: {+function MentionsTab({ mentions, loading, onOpenMention, onDeleteMention, isProjected }: {mentions: Mention[]loading?: booleanonOpenMention?: (m: Mention) => voidonDeleteMention?: (id: string) => void+ isProjected: (target: InboxRowTarget | null) => boolean}) {+ const visibleMentions = mentions.filter((mention) => (+ !isProjected(inboxMentionRowTarget(mention))+ ))return (<div className="h-full overflow-y-auto thin-scrollbar p-3">- {loading && mentions.length === 0 && <InboxRowsSkeleton />}- {!loading && mentions.length === 0 && <EmptyState icon={Inbox} label="No mentions" />}- {mentions.map((mn) => (+ {loading && visibleMentions.length === 0 && <InboxRowsSkeleton />}+ {!loading && visibleMentions.length === 0 && <EmptyState icon={Inbox} label="No mentions" />}+ {visibleMentions.map((mn) => (<div key={mn.id} className="group flex w-full items-start gap-3 rounded-md p-2 text-left hover:bg-accent"><button onClick={() => onOpenMention?.(mn)} className="flex min-w-0 flex-1 items-start gap-3 text-left"><Avatar label={mn.m.authorAvatar ?? "?"} seed={mn.m.authorId} size={36} />@@ -214,6 +220,7 @@ export function InboxPopover({onUnmark,onMarkedTabSelected,onMarkAllRead,+ isProjected = () => false,}: {unreads: UnreadServer[]unreadDms: UnreadDm[]@@ -221,23 +228,13 @@ export function InboxPopover({marked: Marked[]markedLoading?: booleanloading?: boolean- onOpenChannel?: (serverId: string, channelId: string, parentChannelId?: string) => void- onOpenThread?: (- serverId: string,- parentChannelId: string,- childChannelId: string,- openerMessageId: string,- openerSeq?: number,- openerUnread?: boolean,- ) => void+ onOpenChannel?: (server: UnreadServer, channel: UnreadChannel) => void+ onOpenThread?: (server: UnreadServer, parent: UnreadChannel, child: UnreadChild) => void/** Compatibility for non-community showcase fixtures; product wiring uses onOpenThread. */onOpenForumThread?: (- serverId: string,- parentChannelId: string,- childChannelId: string,- openerMessageId: string,- openerSeq?: number,- openerUnread?: boolean,+ server: UnreadServer,+ parent: UnreadChannel,+ child: UnreadChild,) => voidonOpenDm?: (dm: UnreadDm) => voidonOpenMention?: (m: Mention) => void@@ -248,6 +245,7 @@ export function InboxPopover({// the (lazy) marked-feed query only once the viewer actually opens the tab.onMarkedTabSelected?: () => voidonMarkAllRead?: () => void+ isProjected?: (target: InboxRowTarget | null) => boolean}) {const hasUnreads = unreads.length > 0 || unreadDms.length > 0const hasAnything = hasUnreads || mentions.length > 0@@ -293,10 +291,11 @@ export function InboxPopover({onOpenChannel={onOpenChannel}onOpenThread={onOpenThread ?? onOpenForumThread ?? (() => {})}onOpenDm={onOpenDm}+ isProjected={isProjected}/></TabsContent><TabsContent value="mentions" className="min-h-0 flex-1">- <MentionsTab mentions={mentions} loading={loading} onOpenMention={onOpenMention} onDeleteMention={onDeleteMention} />+ <MentionsTab mentions={mentions} loading={loading} onOpenMention={onOpenMention} onDeleteMention={onDeleteMention} isProjected={isProjected} /></TabsContent><TabsContent value="marked" className="min-h-0 flex-1"><MarkedTab marked={marked} loading={markedLoading} onOpenMarked={onOpenMarked} onUnmark={onUnmark} />diff --git a/src/web/src/components/community/shell/shell-frame.test.ts b/src/web/src/components/community/shell/shell-frame.test.tsindex def287bd5..0a9cba899 100644--- a/src/web/src/components/community/shell/shell-frame.test.ts+++ b/src/web/src/components/community/shell/shell-frame.test.ts@@ -28,6 +28,7 @@ const mocks = vi.hoisted(() => {cancelPendingNavigation: handlers.cancelPendingNavigation,},railOptions: vi.fn(),+ inboxOptions: vi.fn(),profile: {previewImage: handlers.previewImage,previewAttachment: handlers.previewAttachment,@@ -75,7 +76,10 @@ vi.mock("./use-shell-profile-controller", () => ({useShellProfileController: () => mocks.profile,}))vi.mock("./use-shell-inbox-controller", () => ({- useShellInboxController: () => mocks.inbox,+ useShellInboxController: (options: unknown) => {+ mocks.inboxOptions(options)+ return mocks.inbox+ },}))vi.mock("./shell-frame-view", () => ({ShellFrameView: (props: Record<string, unknown>) => createElement("shell-frame-view", props),@@ -100,6 +104,7 @@ describe("ShellFrame orchestration", () => {mocks.replace.mockClear()mocks.push.mockClear()mocks.railOptions.mockClear()+ mocks.inboxOptions.mockClear()})afterEach(() => vi.unstubAllGlobals())@@ -155,6 +160,11 @@ describe("ShellFrame orchestration", () => {targetHref: "/c/channels/s1",main: { kind: "target-skeleton", href: "/c/channels/s1" },})+ expect(mocks.inboxOptions).toHaveBeenLastCalledWith(expect.objectContaining({+ publishedHref: "/c/channels/s1/c1",+ navigationPending: true,+ pendingHref: "/c/channels/s1",+ }))mocks.pendingHref.current = "/c/me/dm_1?from=inbox"await act(async () => {diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsxindex 382cb73ae..99f998232 100644--- a/src/web/src/components/community/shell/shell-frame.tsx+++ b/src/web/src/components/community/shell/shell-frame.tsx@@ -95,6 +95,9 @@ export function ShellFrame(props: ShellFrameProps) {router: navigation,queryClient,cancelPendingNavigation: navigation.cancelPendingNavigation,+ publishedHref: navigation.publishedHref,+ navigationPending: navigation.navigationPending,+ pendingHref: navigation.pendingHref,})const goBackMobile = useCallback(() => {if (route.parentPath) navigation.replace(route.parentPath)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 efdca8531..c1d7e9ff0 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@@ -2,20 +2,27 @@ import { createElement } from "react"import TestRenderer, { act } from "react-test-renderer"import { beforeEach, describe, expect, it, vi } from "vitest"import type { DmCache } from "@/lib/community/dm-cache"+import type { Mention, UnreadDm, UnreadServer } from "@/lib/community/models/inbox"import { useShellInboxController } from "./use-shell-inbox-controller"+const order: string[] = []const mocks = vi.hoisted(() => ({markedEnabled: [] as boolean[],- watch: vi.fn(),markAll: vi.fn(),deleteMention: vi.fn(),unmark: vi.fn(),verifyDm: vi.fn(),armOpener: vi.fn(),clearOpener: vi.fn(),+ terminateOpener: vi.fn(),+ begin: vi.fn(),+ submitted: vi.fn(),+ rollback: vi.fn(),+ close: vi.fn(),+ latestEpoch: 0,}))-const unreadDm = {+const unreadDm: UnreadDm = {channelId: "dm1",otherUserId: "u2",otherUserName: "Peer",@@ -24,20 +31,56 @@ const unreadDm = {lastMessageAt: "2026-08-24T00:00:00.000Z",}+const server: UnreadServer = {+ serverId: "s1",+ serverName: "Server",+ channels: [{+ channelId: "c1",+ channelName: "Channel",+ lastMessageAt: "2026-08-24T00:00:00.000Z",+ mentionCount: 0,+ hasDirectUnread: true,+ children: [{+ channelId: "child",+ channelName: "Child",+ lastMessageAt: "2026-08-24T00:00:00.000Z",+ mentionCount: 0,+ parentChannelId: "c1",+ openerMessageId: "opener-7",+ openerSeq: 7,+ openerUnread: true,+ }],+ }],+}++const mention: Mention = {+ id: "m1",+ server: "Server",+ serverId: "s1",+ channel: "Channel",+ channelId: "c1",+ m: { id: "msg1", seq: 4 } as Mention["m"],+}+vi.mock("@/hooks/community/use-inbox", () => ({- useInboxUnreads: () => ({- servers: [],- dms: [unreadDm],- isLoading: false,- }),- useInboxMentions: () => ({ mentions: [], isLoading: false }),+ useInboxUnreads: () => ({ servers: [server], dms: [unreadDm], isLoading: false }),+ useInboxMentions: () => ({ mentions: [mention], isLoading: false }),useInboxMarked: (enabled: boolean) => {mocks.markedEnabled.push(enabled)return { marked: [], isLoading: false }},}))vi.mock("@/hooks/community/use-inbox-auto-collapse", () => ({- useInboxAutoCollapse: () => ({ open: true, onOpenChange: vi.fn(), watchItem: mocks.watch }),+ useInboxAutoCollapse: () => ({+ open: true,+ onOpenChange: vi.fn(),+ beginProjection: (...args: unknown[]) => mocks.begin(...args),+ markProjectionSubmitted: (...args: unknown[]) => mocks.submitted(...args),+ rollbackProjection: (...args: unknown[]) => mocks.rollback(...args),+ closeWithoutProjection: (...args: unknown[]) => mocks.close(...args),+ isProjected: () => false,+ isLatestProjection: (epoch: number) => epoch === mocks.latestEpoch,+ }),}))vi.mock("@/hooks/community/mutations", () => ({useMarkAllInboxRead: () => ({ mutate: mocks.markAll }),@@ -51,6 +94,13 @@ vi.mock("@/hooks/community/thread-opener-read-handoff", () => ({armThreadOpenerReadHandoff: (...args: unknown[]) => mocks.armOpener(...args),clearThreadOpenerReadHandoff: (...args: unknown[]) => mocks.clearOpener(...args),}))+vi.mock("@/hooks/community/inbox-read-reservation", async (importOriginal) => {+ const original = await importOriginal<typeof import("@/hooks/community/inbox-read-reservation")>()+ return {+ ...original,+ terminateThreadOpenerReservationHandoff: (...args: unknown[]) => mocks.terminateOpener(...args),+ }+})type Result = ReturnType<typeof useShellInboxController>@@ -62,23 +112,16 @@ function Capture({ options, onResult }: {return null}-async function renderController(initialDmCache: DmCache = { conversations: [{- id: "dm2",- userId: "u3",- name: "Other",- discriminator: "3333",- avatar: "O",- status: "offline" as const,- preview: "",- unread: true,-}] }, pushError?: Error) {- const order: string[] = []+async function renderController(+ initialDmCache: DmCache = { conversations: [] },+ push?: (href: string) => void,+) {const pushed: string[] = []const router = {push: (href: string) => {order.push("push")pushed.push(href)- if (pushError) throw pushError+ push?.(href)},replace: vi.fn(),prefetch: vi.fn(),@@ -91,23 +134,22 @@ async function renderController(initialDmCache: DmCache = { conversations: [{}),}const cancelPendingNavigation = vi.fn(() => { order.push("cancel") })- mocks.watch.mockImplementation(() => { order.push("watch") })- mocks.verifyDm.mockImplementation(() => {- order.push("verify")- return Promise.resolve("present")- })let current!: Result- let renderer!: TestRenderer.ReactTestRenderer- const options = { router, queryClient, cancelPendingNavigation } as neverawait act(async () => {- renderer = TestRenderer.create(createElement(Capture, {- options,+ TestRenderer.create(createElement(Capture, {+ options: {+ router,+ queryClient,+ cancelPendingNavigation,+ publishedHref: "/c/channels/s1",+ navigationPending: false,+ pendingHref: null,+ } as never,onResult: (result) => { current = result },}))})return {get current() { return current },- renderer,order,pushed,get dmCache() { return dmCache },@@ -116,13 +158,42 @@ async function renderController(initialDmCache: DmCache = { conversations: [{describe("useShellInboxController", () => {beforeEach(() => {+ order.length = 0mocks.markedEnabled.length = 0- for (const mock of [mocks.watch, mocks.markAll, mocks.deleteMention, mocks.unmark, mocks.verifyDm, mocks.armOpener, mocks.clearOpener]) {- mock.mockReset()- }+ for (const mock of [+ mocks.markAll,+ mocks.deleteMention,+ mocks.unmark,+ mocks.verifyDm,+ mocks.armOpener,+ mocks.clearOpener,+ mocks.terminateOpener,+ mocks.begin,+ mocks.submitted,+ mocks.rollback,+ mocks.close,+ ]) mock.mockReset()+ mocks.latestEpoch = 0+ mocks.begin.mockImplementation(() => {+ order.push("project")+ mocks.latestEpoch += 1+ return mocks.latestEpoch+ })+ mocks.submitted.mockImplementation((epoch: number) => {+ order.push("submitted")+ return epoch === mocks.latestEpoch+ })+ mocks.rollback.mockImplementation(() => { order.push("rollback"); return true })+ mocks.close.mockImplementation(() => { order.push("close"); return true })+ mocks.clearOpener.mockImplementation(() => { order.push("clear") })mocks.armOpener.mockImplementation(() => {+ order.push("arm")return "/c/channels/s1/child?inboxThreadOpener=nonce-1"})+ mocks.verifyDm.mockImplementation(() => {+ order.push("verify")+ return Promise.resolve("present")+ })})it("keeps Marked lazy and latches it after first selection", async () => {@@ -130,156 +201,138 @@ describe("useShellInboxController", () => {expect(mocks.markedEnabled.at(-1)).toBe(false)await act(async () => hook.current.popoverProps.onMarkedTabSelected?.())expect(mocks.markedEnabled.at(-1)).toBe(true)- await act(async () => hook.current.popoverProps.onMarkedTabSelected?.())- expect(mocks.markedEnabled.at(-1)).toBe(true)})- it("provisionally upserts a missing DM before push and starts background verification", async () => {+ it("closes/projects before cancel and pushes a direct channel without data work", async () => {const hook = await renderController()- hook.order.length = 0- await act(async () => hook.current.popoverProps.onOpenDm?.(unreadDm))- expect(hook.order).toEqual(["query", "watch", "cancel", "push", "verify"])- expect(mocks.watch).toHaveBeenCalledWith("dm:dm1")- expect(hook.pushed).toEqual(["/c/me/dm1"])- expect(hook.dmCache.conversations[0]).toEqual({- id: "dm1",- userId: "u2",- name: "Peer",- discriminator: "2222",- avatar: "P",- status: "offline",- preview: "",- unread: false,- })- expect(hook.dmCache.conversations[1]?.id).toBe("dm2")- expect(mocks.verifyDm).toHaveBeenCalledWith(expect.anything(), "dm1")+ order.length = 0+ await act(async () => hook.current.popoverProps.onOpenChannel?.(server, server.channels[0]!))+ expect(order).toEqual(["project", "cancel", "clear", "push", "submitted"])+ expect(hook.pushed).toEqual(["/c/channels/s1/c1"])})- it("preserves an existing canonical preview and presence when verification fails transiently", async () => {- const canonical = {- id: "dm1",- userId: "u2",- name: "Peer",- discriminator: "2222",- avatar: "P",- status: "online" as const,- preview: "canonical preview",- unread: true,- }- const hook = await renderController({ conversations: [canonical] })- mocks.verifyDm.mockRejectedValueOnce(new Error("offline"))-- await act(async () => hook.current.popoverProps.onOpenDm?.(unreadDm))-- expect(hook.dmCache.conversations).toEqual([{- ...canonical,- unread: false,- }])- })-- it("preserves forum and mention watch keys and non-blocking routes", async () => {+ it("upserts a DM only after projection/cancel and verifies only after push", async () => {const hook = await renderController()- hook.order.length = 0- 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")-- hook.order.length = 0- await act(async () => hook.current.popoverProps.onOpenMention?.({ id: "m1" } as never))- expect(hook.order).toEqual([])- await act(async () => hook.current.popoverProps.onOpenMention?.({ id: "m1", serverId: "s1", channelId: "c1" } as never))- expect(mocks.watch).toHaveBeenLastCalledWith("mention:m1")- expect(hook.pushed.at(-1)).toBe("/c/channels/s1/c1")+ order.length = 0+ await act(async () => hook.current.popoverProps.onOpenDm?.(unreadDm))+ expect(order).toEqual([+ "project",+ "cancel",+ "clear",+ "query",+ "push",+ "submitted",+ "verify",+ ])+ expect(hook.dmCache.conversations[0]?.id).toBe("dm1")})- it("arms a genuine unread opener after watch/cancel and before pushing its nonce URL", async () => {+ it("arms an exact unread opener after stale setup is cleared and before push", 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,+ order.length = 0+ await act(async () => hook.current.popoverProps.onOpenThread?.(+ server,+ server.channels[0]!,+ server.channels[0]!.children[0]!,))-- 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()+ expect(order).toEqual(["project", "cancel", "clear", "arm", "push", "submitted"])+ expect(hook.pushed).toEqual(["/c/channels/s1/child?inboxThreadOpener=nonce-1"])})- it("clears an obsolete handoff for an ordinary child navigation", async () => {+ it("leaves an invalid Mention completely untouched", 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")+ order.length = 0+ await act(async () => hook.current.popoverProps.onOpenMention?.({ id: "bad" } as Mention))+ expect(order).toEqual([])})- 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("projects a valid Mention and submits its channel synchronously", async () => {+ const hook = await renderController()+ order.length = 0+ await act(async () => hook.current.popoverProps.onOpenMention?.(mention))+ expect(order).toEqual(["project", "cancel", "clear", "push", "submitted"])+ expect(hook.pushed).toEqual(["/c/channels/s1/c1"])})- it("routes marked rows by server/DM with optional seq and exact watch keys", async () => {+ it("closes Marked without creating a projection", async () => {const hook = await renderController()+ order.length = 0await act(async () => hook.current.popoverProps.onOpenMarked?.({id: "mk1",serverId: "s1",channelId: "c1",m: { seq: 7 },} as never))- expect(mocks.watch).toHaveBeenLastCalledWith("marked:mk1")- expect(hook.pushed.at(-1)).toBe("/c/channels/s1/c1?seq=7")+ expect(order).toEqual(["close", "cancel", "clear", "push"])+ expect(mocks.begin).not.toHaveBeenCalled()+ })- await act(async () => hook.current.popoverProps.onOpenMarked?.({- id: "mk-child",- serverId: "s1",- channelId: "child1",- parentChannelId: "parent1",- m: { seq: 8 },- } as never))- expect(mocks.watch).toHaveBeenLastCalledWith("marked:mk-child")- expect(hook.pushed.at(-1)).toBe("/c/channels/s1/child1?seq=8")+ it("rolls back and reopens the latest projection when push throws", async () => {+ const error = new Error("push failed")+ const hook = await renderController(undefined, () => { throw error })+ order.length = 0+ await expect(act(async () => hook.current.popoverProps.onOpenChannel?.(+ server,+ server.channels[0]!,+ ))).rejects.toThrow("push failed")+ expect(order).toEqual([+ "project",+ "cancel",+ "clear",+ "push",+ "cancel",+ "rollback",+ ])+ expect(mocks.rollback).toHaveBeenCalledWith(1, true)+ })- await act(async () => hook.current.popoverProps.onOpenMarked?.({- id: "mk2",- serverId: null,- channelId: "dm1",- m: {},- } as never))- expect(mocks.watch).toHaveBeenLastCalledWith("marked:mk2")- expect(hook.pushed.at(-1)).toBe("/c/me/dm1")+ it("terminates only the exact thread handoff and never verifies a failed DM push", async () => {+ const error = new Error("push failed")+ const hook = await renderController(undefined, () => { throw error })+ await expect(act(async () => hook.current.popoverProps.onOpenThread?.(+ server,+ server.channels[0]!,+ server.channels[0]!.children[0]!,+ ))).rejects.toThrow("push failed")+ expect(mocks.terminateOpener).toHaveBeenCalledWith(expect.anything(), "nonce-1")++ order.length = 0+ await expect(act(async () => hook.current.popoverProps.onOpenDm?.(unreadDm)))+ .rejects.toThrow("push failed")+ expect(mocks.verifyDm).not.toHaveBeenCalled()+ })++ it("lets re-entrant B keep ownership when stale A throws afterward", async () => {+ const serverB: UnreadServer = {+ ...server,+ channels: [{+ ...server.channels[0]!,+ channelId: "c2",+ channelName: "Channel B",+ children: [],+ }],+ }+ const holder: { hook?: Awaited<ReturnType<typeof renderController>> } = {}+ const hook = await renderController(undefined, (href) => {+ if (href !== "/c/channels/s1/c1") return+ holder.hook!.current.popoverProps.onOpenChannel?.(serverB, serverB.channels[0]!)+ throw new Error("stale A failed")+ })+ holder.hook = hook+ order.length = 0++ await expect(act(async () => hook.current.popoverProps.onOpenChannel?.(+ server,+ server.channels[0]!,+ ))).rejects.toThrow("stale A failed")++ expect(hook.pushed).toEqual([+ "/c/channels/s1/c1",+ "/c/channels/s1/c2",+ ])+ expect(mocks.latestEpoch).toBe(2)+ expect(mocks.rollback).not.toHaveBeenCalled()+ expect(order.filter((item) => item === "cancel")).toHaveLength(2)})it("wires mark/delete/unmark payloads", async () => {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 093ab00cf..3efb4ec2e 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@@ -3,11 +3,19 @@import { useCallback, useState, type ComponentProps } from "react"import { communityKeys } from "@/lib/query-keys"import { channelHref } from "@/lib/community/community-route"-import type { Marked, UnreadDm } from "@/lib/community/models/inbox"+import type { Marked, Mention, UnreadDm, UnreadServer } from "@/lib/community/models/inbox"import { dmSummaryFromInbox, upsertDmSummary, type DmCache } from "@/lib/community/dm-cache"import { useInboxUnreads, useInboxMentions, useInboxMarked } from "@/hooks/community/use-inbox"import { startDmRouteVerification } from "@/hooks/community/use-dm-route-verification"import { useInboxAutoCollapse } from "@/hooks/community/use-inbox-auto-collapse"+import {+ inboxChannelRowTarget,+ inboxDmRowTarget,+ inboxMentionRowTarget,+ inboxThreadRowTarget,+ terminateThreadOpenerReservationHandoff,+ type InboxRowTarget,+} from "@/hooks/community/inbox-read-reservation"import {useMarkAllInboxRead,useDeleteMention,@@ -21,16 +29,25 @@ import {clearThreadOpenerReadHandoff,} from "@/hooks/community/thread-opener-read-handoff"+type UnreadChannel = UnreadServer["channels"][number]+type UnreadChild = UnreadChannel["children"][number]+type Options = {router: ShellRouterqueryClient: QueryClientcancelPendingNavigation: () => void+ publishedHref: string+ navigationPending: boolean+ pendingHref: string | null}export function useShellInboxController({router,queryClient,cancelPendingNavigation,+ publishedHref,+ navigationPending,+ pendingHref,}: Options) {const inboxUnreads = useInboxUnreads()const inboxMentions = useInboxMentions()@@ -43,77 +60,112 @@ export function useShellInboxController({const { mutate: unmarkMessageMutate } = useUnmarkMessage()const markAllInboxRead = useMarkAllInboxRead()const deleteMention = useDeleteMention()- const inbox = useInboxAutoCollapse({ unreads: unreadFeed, unreadDms, mentions })- const watchInboxItem = inbox.watchItem+ const inbox = useInboxAutoCollapse({+ queryClient,+ publishedHref,+ navigationPending,+ pendingHref,+ })- const openServerChannel = useCallback((- serverId: string,- channelId: string,- _parentChannelId?: string,- watchKey: string = `channel:${channelId}`,+ const pushProjected = useCallback((+ target: InboxRowTarget,+ destinationHref: string,+ prepare?: () => string | void,+ afterPush?: () => void,) => {- watchInboxItem(watchKey)+ const epoch = inbox.beginProjection(target, destinationHref)cancelPendingNavigation()clearThreadOpenerReadHandoff(queryClient)- router.push(channelHref(serverId, channelId))- }, [cancelPendingNavigation, queryClient, router, watchInboxItem])-- const openThread = useCallback((- serverId: string,- parentChannelId: string,- childChannelId: string,- openerMessageId: string,- openerSeq?: number,- openerUnread?: boolean,- ) => {- watchInboxItem(`channel:${childChannelId}`)- cancelPendingNavigation()- const href = openerUnread === true && openerSeq !== undefined- ? armThreadOpenerReadHandoff(queryClient, {- serverId,- parentChannelId: parentChannelId,- childChannelId,- openerMessageId,- openerSeq,- })- : channelHref(serverId, childChannelId)- if (openerUnread !== true || openerSeq === undefined) {- clearThreadOpenerReadHandoff(queryClient)- }+ let pushedHref = destinationHreftry {- router.push(href)+ pushedHref = prepare?.() ?? destinationHref+ router.push(pushedHref)+ if (inbox.markProjectionSubmitted(epoch)) afterPush?.()} catch (error) {- clearThreadOpenerReadHandoff(queryClient)+ const nonce = new URLSearchParams(pushedHref.split("?")[1] ?? "")+ .get("inboxThreadOpener")+ if (nonce) terminateThreadOpenerReservationHandoff(queryClient, nonce)+ if (inbox.isLatestProjection(epoch)) {+ cancelPendingNavigation()+ inbox.rollbackProjection(epoch, true)+ }throw error}- }, [cancelPendingNavigation, queryClient, router, watchInboxItem])+ }, [cancelPendingNavigation, inbox, queryClient, router])++ const openServerChannel = useCallback((+ server: UnreadServer,+ channel: UnreadChannel,+ ) => {+ const target = inboxChannelRowTarget(server, channel)+ if (!target) return+ const href = channelHref(server.serverId, channel.channelId)+ pushProjected(target, href)+ }, [pushProjected])++ const openThread = useCallback((+ server: UnreadServer,+ parent: UnreadChannel,+ child: UnreadChild,+ ) => {+ const target = inboxThreadRowTarget(server, parent, child)+ const href = channelHref(server.serverId, child.channelId)+ pushProjected(target, href, () => (+ child.openerMessageId+ && child.openerUnread === true+ && child.openerSeq !== undefined+ ? armThreadOpenerReadHandoff(queryClient, {+ serverId: server.serverId,+ parentChannelId: child.parentChannelId ?? parent.channelId,+ childChannelId: child.channelId,+ openerMessageId: child.openerMessageId,+ openerSeq: child.openerSeq,+ })+ : href+ ))+ }, [pushProjected, queryClient])const openMarked = useCallback((marked: Marked) => {- watchInboxItem(`marked:${marked.id}`)+ const previousOpen = inbox.closeWithoutProjection()cancelPendingNavigation()clearThreadOpenerReadHandoff(queryClient)const seqQuery = marked.m.seq != null ? `?seq=${marked.m.seq}` : ""- if (marked.serverId) {- const channelPath = channelHref(marked.serverId, marked.channelId)- router.push(`${channelPath}${seqQuery}`)- } else {- router.push(`/c/me/${marked.channelId}${seqQuery}`)+ const href = marked.serverId+ ? `${channelHref(marked.serverId, marked.channelId)}${seqQuery}`+ : `/c/me/${marked.channelId}${seqQuery}`+ try {+ router.push(href)+ } catch (error) {+ cancelPendingNavigation()+ inbox.onOpenChange(previousOpen)+ throw error}- }, [cancelPendingNavigation, queryClient, router, watchInboxItem])+ }, [cancelPendingNavigation, inbox, queryClient, router])const openDm = useCallback((dm: UnreadDm) => {const dmId = dm.channelId- queryClient.setQueryData(- communityKeys.dms(),- (previous: DmCache | undefined) =>- upsertDmSummary(previous, dmSummaryFromInbox(dm)),+ pushProjected(+ inboxDmRowTarget(dm),+ `/c/me/${dmId}`,+ () => {+ queryClient.setQueryData(+ communityKeys.dms(),+ (previous: DmCache | undefined) => (+ upsertDmSummary(previous, dmSummaryFromInbox(dm))+ ),+ )+ },+ () => {+ void startDmRouteVerification(queryClient, dmId).catch(() => undefined)+ },)- watchInboxItem(`dm:${dmId}`)- cancelPendingNavigation()- clearThreadOpenerReadHandoff(queryClient)- router.push(`/c/me/${dmId}`)- void startDmRouteVerification(queryClient, dmId).catch(() => undefined)- }, [cancelPendingNavigation, queryClient, router, watchInboxItem])+ }, [pushProjected, queryClient])++ const openMention = useCallback((mention: Mention) => {+ const target = inboxMentionRowTarget(mention)+ if (!target || !mention.serverId || !mention.channelId) return+ pushProjected(target, channelHref(mention.serverId, mention.channelId))+ }, [pushProjected])const popoverProps: ComponentProps<typeof InboxPopover> = {unreads: unreadFeed,@@ -125,16 +177,13 @@ export function useShellInboxController({onOpenChannel: openServerChannel,onOpenThread: openThread,onOpenDm: openDm,- onOpenMention: (mention) => {- if (mention.serverId && mention.channelId) {- openServerChannel(mention.serverId, mention.channelId, undefined, `mention:${mention.id}`)- }- },+ onOpenMention: openMention,onOpenMarked: openMarked,onMarkedTabSelected: () => setMarkedTabOpened(true),onMarkAllRead: () => { markAllInboxRead.mutate() },onDeleteMention: (id) => deleteMention.mutate({ mentionId: id }),onUnmark: (messageId) => unmarkMessageMutate({ messageId }),+ isProjected: inbox.isProjected,}return {diff --git a/src/web/src/hooks/community/inbox-read-reservation.test.ts b/src/web/src/hooks/community/inbox-read-reservation.test.tsindex 11fa7af9b..294ba71f6 100644--- a/src/web/src/hooks/community/inbox-read-reservation.test.ts+++ b/src/web/src/hooks/community/inbox-read-reservation.test.ts@@ -1,13 +1,17 @@import type { QueryClient } from "@tanstack/react-query"import { beforeEach, describe, expect, it, vi } from "vitest"import {+ activateInboxProjectionTicket,armInboxReadReservationCandidate,armThreadOpenerReservationHandoff,clearThreadOpenerReservationHandoff,completeThreadOpenerReservationHandoff,disposeInboxReadReservation,getThreadOpenerReservationHandoff,+ inboxReadCandidateFingerprint,+ publishInboxProjectionGenerationTerminal,promoteInboxReadReservation,+ registerInboxProjectionTicket,registerThreadOpenerRouteLease,registerInboxReadReservationSurface,releaseThreadOpenerRouteLease,@@ -16,6 +20,7 @@ import {settleInboxReadReservationGeneration,takeInboxReadReservationNegative,terminateThreadOpenerReservationHandoff,+ type InboxRowTarget,} from "./inbox-read-reservation"function client() {@@ -28,6 +33,7 @@ function client() {function response(channelId = "focused", lastMessageAt = "2026-08-27T01:00:00.000Z") {return {servers: [{+ serverId: "server",channels: [{channelId,lastMessageAt,@@ -739,4 +745,249 @@ describe("inbox read reservation", () => {expect(getThreadOpenerReservationHandoff(queryClient, "nonce-route")).toBeNull()expect(queryClient.refetchQueries).toHaveBeenCalledOnce()})++ it("keeps projection tickets dormant and emits success only for their bound generation", async () => {+ const data = {+ servers: [{+ serverId: "server",+ serverName: "Server",+ channels: [{+ channelId: "focused",+ channelName: "Focused",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ mentionCount: 0,+ hasDirectUnread: true,+ children: [],+ }],+ }],+ dms: [],+ }+ const cache = { current: data as typeof data | { servers: []; dms: [] } }+ queryClient = {+ ...client(),+ getQueryData: vi.fn(() => cache.current),+ } as unknown as QueryClient+ const target: InboxRowTarget = {+ kind: "channel-direct",+ identity: JSON.stringify(["channel-direct", "server", "focused"]),+ fingerprint: inboxReadCandidateFingerprint({+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ openerUnread: false,+ }),+ confirmationChannelId: "focused",+ serverId: "server",+ channelId: "focused",+ }+ const receipt = vi.fn()+ const ticket = registerInboxProjectionTicket(queryClient, 4, target, receipt)+ const lease = registerInboxReadReservationSurface(queryClient, "focused", vi.fn())+ const pending = reserveInboxUnreadsResponse(queryClient, data)+ void pending.catch(() => undefined)+ promoteInboxReadReservation(lease, 41)++ publishInboxProjectionGenerationTerminal(queryClient, 99, "success")+ expect(receipt).not.toHaveBeenCalled()+ activateInboxProjectionTicket(ticket)+ expect(receipt).not.toHaveBeenCalled()++ await settleInboxReadReservationGeneration(queryClient, 41, true, "focused")+ cache.current = { servers: [], dms: [] }+ publishInboxProjectionGenerationTerminal(queryClient, 41, "success")+ expect(receipt).toHaveBeenCalledWith(expect.objectContaining({+ epoch: 4,+ terminal: "success",+ disposition: "retire",+ observedFingerprint: null,+ }))+ })++ it("freezes exact retention as rollback after an owned negative refetch", async () => {+ const data = response()+ queryClient = {+ ...client(),+ getQueryData: vi.fn(() => data),+ } as unknown as QueryClient+ const target: InboxRowTarget = {+ kind: "channel-direct",+ identity: JSON.stringify(["channel-direct", "server", "focused"]),+ fingerprint: inboxReadCandidateFingerprint({+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ openerUnread: false,+ }),+ confirmationChannelId: "focused",+ serverId: "server",+ channelId: "focused",+ }+ const receipt = vi.fn()+ activateInboxProjectionTicket(registerInboxProjectionTicket(+ queryClient,+ 5,+ target,+ receipt,+ ))+ const lease = registerInboxReadReservationSurface(queryClient, "focused", vi.fn())+ const pending = reserveInboxUnreadsResponse(queryClient, data)+ void pending.catch(() => undefined)+ promoteInboxReadReservation(lease, 51)++ await settleInboxReadReservationGeneration(queryClient, 51, false, "focused")+ expect(receipt).toHaveBeenCalledWith(expect.objectContaining({+ terminal: "negative",+ disposition: "rollback",+ observedFingerprint: target.fingerprint,+ }))+ })++ it("forces Mention-negative and deferred terminals to rollback without cache authority", async () => {+ queryClient = {+ ...client(),+ getQueryData: vi.fn(() => undefined),+ } as unknown as QueryClient+ const mentionTarget: InboxRowTarget = {+ kind: "mention",+ identity: JSON.stringify(["mention", "mention-1"]),+ fingerprint: JSON.stringify(["mention-1", "message-1", 7]),+ confirmationChannelId: "focused",+ mentionId: "mention-1",+ }+ const negativeReceipt = vi.fn()+ activateInboxProjectionTicket(registerInboxProjectionTicket(+ queryClient,+ 6,+ mentionTarget,+ negativeReceipt,+ ))+ const lease = registerInboxReadReservationSurface(queryClient, "focused", vi.fn())+ const pending = reserveInboxUnreadsResponse(queryClient, response())+ void pending.catch(() => undefined)+ promoteInboxReadReservation(lease, 61)+ await settleInboxReadReservationGeneration(queryClient, 61, false, "focused")+ expect(negativeReceipt).toHaveBeenCalledWith(expect.objectContaining({+ disposition: "rollback",+ observedFingerprint: null,+ }))++ const deferredReceipt = vi.fn()+ const ticket = registerInboxProjectionTicket(+ queryClient,+ 7,+ mentionTarget,+ deferredReceipt,+ )+ armInboxReadReservationCandidate(queryClient, {+ channelId: "focused",+ lastMessageAt: "2026-08-27T03:00:00.000Z",+ })+ promoteInboxReadReservation(lease, 62)+ activateInboxProjectionTicket(ticket)+ publishInboxProjectionGenerationTerminal(queryClient, 62, "deferred")+ expect(deferredReceipt).toHaveBeenCalledWith(expect.objectContaining({+ terminal: "deferred",+ disposition: "rollback",+ }))+ })++ it("binds an exact child target to its opener-owned parent generation", async () => {+ const data = {+ servers: [{+ serverId: "server",+ 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: [],+ }+ const cache = { current: data as typeof data | { servers: []; dms: [] } }+ queryClient = {+ ...client(),+ getQueryData: vi.fn(() => cache.current),+ } as unknown as QueryClient+ const target: InboxRowTarget = {+ kind: "thread",+ identity: JSON.stringify(["thread", "server", "forum", "child"]),+ fingerprint: inboxReadCandidateFingerprint({+ channelId: "child",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ openerMessageId: "opener-7",+ openerSeq: 7,+ openerUnread: true,+ }),+ confirmationChannelId: "forum",+ serverId: "server",+ parentChannelId: "forum",+ childChannelId: "child",+ }+ const receipt = vi.fn()+ activateInboxProjectionTicket(registerInboxProjectionTicket(+ queryClient,+ 8,+ target,+ receipt,+ ))+ armThreadOpenerReservationHandoff(queryClient, {+ nonce: "projection-thread",+ serverId: "server",+ parentChannelId: "forum",+ childChannelId: "child",+ openerMessageId: "opener-7",+ openerSeq: 7,+ })+ registerInboxReadReservationSurface(queryClient, "child", vi.fn())+ const pending = reserveInboxUnreadsResponse(queryClient, data)+ void pending.catch(() => undefined)+ completeThreadOpenerReservationHandoff(queryClient, "projection-thread", 81)+ await settleInboxReadReservationGeneration(queryClient, 81, true, "forum")+ cache.current = { servers: [], dms: [] }+ publishInboxProjectionGenerationTerminal(queryClient, 81, "success")++ expect(receipt).toHaveBeenCalledWith(expect.objectContaining({+ terminal: "success",+ disposition: "retire",+ }))+ })++ it("attaches an activated same-href ticket to a just-settled exact generation", async () => {+ const data = response()+ queryClient = {+ ...client(),+ getQueryData: vi.fn(() => ({ servers: [], dms: [] })),+ } as unknown as QueryClient+ const lease = registerInboxReadReservationSurface(queryClient, "focused", vi.fn())+ const pending = reserveInboxUnreadsResponse(queryClient, data)+ void pending.catch(() => undefined)+ promoteInboxReadReservation(lease, 91)+ await settleInboxReadReservationGeneration(queryClient, 91, true, "focused")+ publishInboxProjectionGenerationTerminal(queryClient, 91, "success")++ const target: InboxRowTarget = {+ kind: "channel-direct",+ identity: JSON.stringify(["channel-direct", "server", "focused"]),+ fingerprint: inboxReadCandidateFingerprint({+ channelId: "focused",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ openerUnread: false,+ }),+ confirmationChannelId: "focused",+ serverId: "server",+ channelId: "focused",+ }+ const receipt = vi.fn()+ const ticket = registerInboxProjectionTicket(queryClient, 9, target, receipt)+ expect(receipt).not.toHaveBeenCalled()+ activateInboxProjectionTicket(ticket)+ expect(receipt).toHaveBeenCalledWith(expect.objectContaining({+ terminal: "success",+ disposition: "retire",+ }))+ })})diff --git a/src/web/src/hooks/community/inbox-read-reservation.ts b/src/web/src/hooks/community/inbox-read-reservation.tsindex 22c286e1e..a27b7c490 100644--- a/src/web/src/hooks/community/inbox-read-reservation.ts+++ b/src/web/src/hooks/community/inbox-read-reservation.ts@@ -1,6 +1,7 @@"use client"import { communityKeys } from "@/lib/query-keys"+import type { Mention, UnreadDm, UnreadServer } from "@/lib/community/models/inbox"import type { QueryClient } from "@tanstack/react-query"type InboxChild = {@@ -32,6 +33,53 @@ export type InboxReadCandidate = {openerUnread: boolean}+export type InboxRowTarget =+ | {+ kind: "channel-direct"+ identity: string+ fingerprint: string+ confirmationChannelId: string+ serverId: string+ channelId: string+ }+ | {+ kind: "thread"+ identity: string+ fingerprint: string+ confirmationChannelId: string+ serverId: string+ parentChannelId: string+ childChannelId: string+ }+ | {+ kind: "dm"+ identity: string+ fingerprint: string+ confirmationChannelId: string+ channelId: string+ }+ | {+ kind: "mention"+ identity: string+ fingerprint: string+ confirmationChannelId: string+ mentionId: string+ }++export type InboxProjectionTerminalReceipt = {+ epoch: number+ target: InboxRowTarget+ terminal: "success" | "negative" | "deferred" | "error"+ disposition: "retire" | "rollback"+ observedFingerprint: string | null+}++export type InboxProjectionTicket = {+ queryClient: QueryClient+ token: symbol+ epoch: number+}+export type InboxReadReservationLease = {queryClient: QueryClienttoken: symbol@@ -107,9 +155,25 @@ type ManagerState = {claimedOpeners: Map<number, ClaimedThreadOpener>routeLeases: Map<symbol, ThreadOpenerRouteLease>refetch: Promise<unknown> | null+ projectionTickets: Map<symbol, ProjectionTicketState>+ projectionCandidates: Map<number, InboxReadCandidate>+ projectionTerminals: Map<number, ProjectionTerminalState>disposed: boolean}+type ProjectionTicketState = {+ ticket: InboxProjectionTicket+ target: InboxRowTarget+ active: boolean+ generation: number | null+ onReceipt: (receipt: InboxProjectionTerminalReceipt) => void+}++type ProjectionTerminalState = {+ terminal: InboxProjectionTerminalReceipt["terminal"]+ candidate: InboxReadCandidate | null+}+const managers = new WeakMap<QueryClient, ManagerState>()function managerFor(queryClient: QueryClient) {@@ -129,6 +193,9 @@ function managerFor(queryClient: QueryClient) {claimedOpeners: new Map(),routeLeases: new Map(),refetch: null,+ projectionTickets: new Map(),+ projectionCandidates: new Map(),+ projectionTerminals: new Map(),disposed: false,}managers.set(queryClient, state)@@ -136,7 +203,9 @@ function managerFor(queryClient: QueryClient) {return state}-function fingerprint(candidate: Omit<InboxReadCandidate, "fingerprint">) {+export function inboxReadCandidateFingerprint(+ candidate: Omit<InboxReadCandidate, "fingerprint">,+) {return JSON.stringify([candidate.channelId,candidate.lastMessageAt,@@ -146,6 +215,84 @@ function fingerprint(candidate: Omit<InboxReadCandidate, "fingerprint">) {])}+function inboxMentionFingerprint(mention: Mention) {+ return JSON.stringify([mention.id, mention.m.id, mention.m.seq ?? null])+}++export function inboxChannelRowTarget(+ server: UnreadServer,+ channel: UnreadServer["channels"][number],+): InboxRowTarget | null {+ if (channel.hasDirectUnread === false) return null+ return {+ kind: "channel-direct",+ identity: JSON.stringify(["channel-direct", server.serverId, channel.channelId]),+ fingerprint: inboxReadCandidateFingerprint({+ channelId: channel.channelId,+ lastMessageAt: channel.lastMessageAt,+ openerUnread: false,+ }),+ confirmationChannelId: channel.channelId,+ serverId: server.serverId,+ channelId: channel.channelId,+ }+}++export function inboxThreadRowTarget(+ server: UnreadServer,+ parent: UnreadServer["channels"][number],+ child: UnreadServer["channels"][number]["children"][number],+): InboxRowTarget {+ const parentChannelId = child.parentChannelId ?? parent.channelId+ return {+ kind: "thread",+ identity: JSON.stringify([+ "thread",+ server.serverId,+ parentChannelId,+ child.channelId,+ ]),+ fingerprint: inboxReadCandidateFingerprint({+ channelId: child.channelId,+ lastMessageAt: child.lastMessageAt,+ ...(child.openerMessageId ? { openerMessageId: child.openerMessageId } : {}),+ ...(child.openerSeq !== undefined ? { openerSeq: child.openerSeq } : {}),+ openerUnread: child.openerUnread === true,+ }),+ confirmationChannelId: child.openerUnread === true && child.openerSeq !== undefined+ ? parentChannelId+ : child.channelId,+ serverId: server.serverId,+ parentChannelId,+ childChannelId: child.channelId,+ }+}++export function inboxDmRowTarget(dm: UnreadDm): InboxRowTarget {+ return {+ kind: "dm",+ identity: JSON.stringify(["dm", dm.channelId]),+ fingerprint: inboxReadCandidateFingerprint({+ channelId: dm.channelId,+ lastMessageAt: dm.lastMessageAt,+ openerUnread: false,+ }),+ confirmationChannelId: dm.channelId,+ channelId: dm.channelId,+ }+}++export function inboxMentionRowTarget(mention: Mention): InboxRowTarget | null {+ if (!mention.serverId || !mention.channelId) return null+ return {+ kind: "mention",+ identity: JSON.stringify(["mention", mention.id]),+ fingerprint: inboxMentionFingerprint(mention),+ confirmationChannelId: mention.channelId,+ mentionId: mention.id,+ }+}+function candidateFor(data: InboxResponse, channelId: string): InboxReadCandidate | null {for (const server of data.servers) {for (const channel of server.channels) {@@ -158,7 +305,7 @@ function candidateFor(data: InboxResponse, channelId: string): InboxReadCandidat...(child.openerSeq !== undefined ? { openerSeq: child.openerSeq } : {}),openerUnread: child.openerUnread === true,}- return { ...candidate, fingerprint: fingerprint(candidate) }+ return { ...candidate, fingerprint: inboxReadCandidateFingerprint(candidate) }}if (channel.channelId === channelId && channel.hasDirectUnread !== false) {const candidate = {@@ -166,7 +313,7 @@ function candidateFor(data: InboxResponse, channelId: string): InboxReadCandidatlastMessageAt: channel.lastMessageAt,openerUnread: false,}- return { ...candidate, fingerprint: fingerprint(candidate) }+ return { ...candidate, fingerprint: inboxReadCandidateFingerprint(candidate) }}}}@@ -177,7 +324,166 @@ function candidateFor(data: InboxResponse, channelId: string): InboxReadCandidatlastMessageAt: dm.lastMessageAt,openerUnread: false,}- return { ...candidate, fingerprint: fingerprint(candidate) }+ return { ...candidate, fingerprint: inboxReadCandidateFingerprint(candidate) }+}++function targetMatchesCandidate(+ target: InboxRowTarget,+ candidate: InboxReadCandidate,+) {+ if (target.kind === "mention") {+ return target.confirmationChannelId === candidate.channelId+ }+ const channelId = target.kind === "thread"+ ? target.childChannelId+ : target.channelId+ return channelId === candidate.channelId && target.fingerprint === candidate.fingerprint+}++function observedProjectionFingerprint(+ queryClient: QueryClient,+ target: InboxRowTarget,+) {+ if (target.kind === "mention") {+ const data = queryClient.getQueryData<{ mentions: Mention[] }>(+ communityKeys.inboxMentions(),+ )+ const mention = data?.mentions.find((row) => row.id === target.mentionId)+ return mention ? inboxMentionFingerprint(mention) : null+ }+ const data = queryClient.getQueryData<InboxResponse>(communityKeys.inboxUnreads())+ if (!data) return null+ if (target.kind === "dm") {+ const dm = data.dms.find((row) => row.channelId === target.channelId)+ return dm ? inboxDmRowTarget(dm as UnreadDm).fingerprint : null+ }+ const server = data.servers.find((row) => (+ "serverId" in row && row.serverId === target.serverId+ )) as UnreadServer | undefined+ if (!server) return null+ if (target.kind === "channel-direct") {+ const channel = server.channels.find((row) => row.channelId === target.channelId)+ return channel ? inboxChannelRowTarget(server, channel)?.fingerprint ?? null : null+ }+ const parent = server.channels.find((row) => row.channelId === target.parentChannelId)+ const child = parent?.children.find((row) => row.channelId === target.childChannelId)+ return parent && child ? inboxThreadRowTarget(server, parent, child).fingerprint : null+}++function freezeProjectionReceipt(+ state: ManagerState,+ ticket: ProjectionTicketState,+ terminal: InboxProjectionTerminalReceipt["terminal"],+) {+ const observedFingerprint = terminal === "deferred"+ || terminal === "error"+ || (terminal === "negative" && ticket.target.kind === "mention")+ ? null+ : observedProjectionFingerprint(state.queryClient, ticket.target)+ const disposition = terminal === "deferred"+ || terminal === "error"+ || (terminal === "negative" && ticket.target.kind === "mention")+ || observedFingerprint === ticket.target.fingerprint+ ? "rollback"+ : "retire"+ return {+ epoch: ticket.ticket.epoch,+ target: ticket.target,+ terminal,+ disposition,+ observedFingerprint,+ } satisfies InboxProjectionTerminalReceipt+}++function deliverProjectionTerminal(+ state: ManagerState,+ ticket: ProjectionTicketState,+ terminal: InboxProjectionTerminalReceipt["terminal"],+) {+ if (!ticket.active || !state.projectionTickets.delete(ticket.ticket.token)) return+ ticket.onReceipt(freezeProjectionReceipt(state, ticket, terminal))+}++function bindProjectionTickets(+ state: ManagerState,+ candidate: InboxReadCandidate,+ generation: number | null,+) {+ for (const ticket of state.projectionTickets.values()) {+ if (!targetMatchesCandidate(ticket.target, candidate)) continue+ if (generation !== null) ticket.generation = generation+ const terminal = generation === null+ ? null+ : state.projectionTerminals.get(generation)?.terminal ?? null+ if (terminal) deliverProjectionTerminal(state, ticket, terminal)+ }+}++function rememberProjectionCandidate(+ state: ManagerState,+ generation: number,+ candidate: InboxReadCandidate,+) {+ state.projectionCandidates.set(generation, candidate)+ while (state.projectionCandidates.size > 32) {+ const oldest = state.projectionCandidates.keys().next().value+ if (oldest === undefined) break+ state.projectionCandidates.delete(oldest)+ }+ bindProjectionTickets(state, candidate, generation)+}++function publishProjectionTerminal(+ state: ManagerState,+ generation: number,+ terminal: InboxProjectionTerminalReceipt["terminal"],+) {+ const candidate = state.projectionCandidates.get(generation) ?? null+ state.projectionTerminals.set(generation, { terminal, candidate })+ while (state.projectionTerminals.size > 32) {+ const oldest = state.projectionTerminals.keys().next().value+ if (oldest === undefined) break+ state.projectionTerminals.delete(oldest)+ }+ for (const ticket of [...state.projectionTickets.values()]) {+ if (ticket.generation === generation) {+ deliverProjectionTerminal(state, ticket, terminal)+ }+ }+}++function publishProjectionCandidateTerminal(+ state: ManagerState,+ candidate: InboxReadCandidate,+ terminal: "negative" | "error",+) {+ const generations = new Set<number>()+ for (const ticket of [...state.projectionTickets.values()]) {+ if (!targetMatchesCandidate(ticket.target, candidate)) continue+ if (ticket.generation !== null) generations.add(ticket.generation)+ else deliverProjectionTerminal(state, ticket, terminal)+ }+ for (const generation of generations) {+ publishProjectionTerminal(state, generation, terminal)+ }+}++function publishProjectionHandoffTerminal(+ state: ManagerState,+ handoff: ThreadOpenerHandoffTarget,+ terminal: "negative" | "error",+) {+ for (const ticket of [...state.projectionTickets.values()]) {+ const target = ticket.target+ if (+ target.kind === "thread"+ && target.serverId === handoff.serverId+ && target.parentChannelId === handoff.parentChannelId+ && target.childChannelId === handoff.childChannelId+ ) {+ deliverProjectionTerminal(state, ticket, terminal)+ }+ }}function activeLease(state: ManagerState) {@@ -295,7 +601,12 @@ function releaseHeldNegative(state: ManagerState, held: HeldResponse) {}cancelHeld(state, held)notifyActive(state, null)- return queueAuthoritativeRefetch(state)+ return queueAuthoritativeRefetch(state).then(+ () => publishProjectionCandidateTerminal(state, held.candidate, "negative"),+ () => {+ publishProjectionCandidateTerminal(state, held.candidate, "error")+ },+ )}function reclassifyHeld(state: ManagerState) {@@ -316,11 +627,67 @@ function reclassifyHeld(state: ManagerState) {if (shouldAwaitOpenerClaim(state, candidate) && state.handoff) {state.handoff.phase = "awaiting-opener-claim"}+ bindProjectionTickets(state, candidate, held.generation)latest = candidate}notifyActive(state, latest)}+export function registerInboxProjectionTicket(+ queryClient: QueryClient,+ epoch: number,+ target: InboxRowTarget,+ onReceipt: (receipt: InboxProjectionTerminalReceipt) => void,+): InboxProjectionTicket {+ const state = managerFor(queryClient)+ const ticket = { queryClient, token: Symbol(target.identity), epoch }+ const ticketState: ProjectionTicketState = {+ ticket,+ target,+ active: false,+ generation: null,+ onReceipt,+ }+ state.projectionTickets.set(ticket.token, ticketState)+ const focused = state.focusedCandidate+ if (focused && targetMatchesCandidate(target, focused.candidate)) {+ ticketState.generation = focused.generation+ }+ if (ticketState.generation === null) {+ const generations = [...state.projectionCandidates.entries()].reverse()+ const match = generations.find(([, candidate]) => targetMatchesCandidate(target, candidate))+ if (match) ticketState.generation = match[0]+ }+ return ticket+}++export function activateInboxProjectionTicket(ticket: InboxProjectionTicket) {+ const state = managers.get(ticket.queryClient)+ const current = state?.projectionTickets.get(ticket.token)+ if (!state || !current || current.ticket.epoch !== ticket.epoch) return false+ current.active = true+ const terminal = current.generation === null+ ? null+ : state.projectionTerminals.get(current.generation)?.terminal ?? null+ if (terminal) deliverProjectionTerminal(state, current, terminal)+ return true+}++export function cancelInboxProjectionTicket(ticket: InboxProjectionTicket) {+ const state = managers.get(ticket.queryClient)+ return state?.projectionTickets.delete(ticket.token) ?? false+}++export function publishInboxProjectionGenerationTerminal(+ queryClient: QueryClient,+ generation: number,+ terminal: "success" | "deferred" | "error",+) {+ const state = managers.get(queryClient)+ if (!state || state.disposed) return+ publishProjectionTerminal(state, generation, terminal)+}+export function registerInboxReadReservationSurface(queryClient: QueryClient,channelId: string,@@ -360,7 +727,10 @@ export function armInboxReadReservationCandidate(...(input.openerSeq !== undefined ? { openerSeq: input.openerSeq } : {}),openerUnread: false,}- const candidate = { ...candidateBase, fingerprint: fingerprint(candidateBase) }+ const candidate = {+ ...candidateBase,+ fingerprint: inboxReadCandidateFingerprint(candidateBase),+ }const current = state.focusedCandidateif (current?.epoch === lease.lease.epoch@@ -389,6 +759,7 @@ export function armInboxReadReservationCandidate(candidate,generation: null,}+ bindProjectionTickets(state, candidate, null)notifyActive(state, candidate)return true}@@ -421,10 +792,16 @@ export function promoteInboxReadReservation(&& state.focusedCandidate.candidate.channelId === lease.channelId) {state.focusedCandidate.generation = generation+ rememberProjectionCandidate(+ state,+ generation,+ state.focusedCandidate.candidate,+ )}for (const held of state.held.values()) {if (held.candidate.channelId === lease.channelId && !held.openerClaimLocked) {held.generation = generation+ rememberProjectionCandidate(state, generation, held.candidate)}}return true@@ -459,7 +836,10 @@ export function takeInboxReadReservationNegative(fingerprint: null,}notifyActive(state, null)- void queueAuthoritativeRefetch(state)+ void queueAuthoritativeRefetch(state).then(+ () => publishProjectionCandidateTerminal(state, focused.candidate, "negative"),+ () => publishProjectionCandidateTerminal(state, focused.candidate, "error"),+ )}}return true@@ -493,10 +873,17 @@ export async function settleInboxReadReservationGeneration(state.focusedCandidate = null}notifyActive(state, null)- await queueAuthoritativeRefetch(state)+ try {+ await queueAuthoritativeRefetch(state)+ const candidate = state.projectionCandidates.get(generation)+ if (candidate) publishProjectionTerminal(state, generation, "negative")+ } catch {+ publishProjectionTerminal(state, generation, "error")+ }return}await Promise.all(matching.map((held) => releaseHeldNegative(state, held)))+ publishProjectionTerminal(state, generation, "negative")if (state.focusedCandidate?.generation === generation) state.focusedCandidate = nullreturn}@@ -598,6 +985,7 @@ export async function reserveInboxUnreadsResponse<T extends InboxResponse>(if (shouldAwaitOpenerClaim(state, candidate) && state.handoff) {state.handoff.phase = "awaiting-opener-claim"}+ bindProjectionTickets(state, candidate, held.generation)lease.onCandidate(candidate)})}@@ -684,6 +1072,7 @@ export function completeThreadOpenerReservationHandoff(if (handoffMatches(handoff, held.candidate)) {held.generation = generationheld.openerClaimLocked = true+ rememberProjectionCandidate(state, generation, held.candidate)}}state.claimedOpeners.set(generation, { ...handoff, generation })@@ -701,7 +1090,12 @@ export function terminateThreadOpenerReservationHandoff(const matching = [...state.held.values()].filter((held) => handoffMatches(handoff, held.candidate))state.handoff = nullfor (const held of matching) void releaseHeldNegative(state, held)- if (matching.length === 0) void queueAuthoritativeRefetch(state)+ if (matching.length === 0) {+ void queueAuthoritativeRefetch(state).then(+ () => publishProjectionHandoffTerminal(state, handoff, "negative"),+ () => publishProjectionHandoffTerminal(state, handoff, "error"),+ )+ }return true}@@ -724,6 +1118,9 @@ export function disposeInboxReadReservation(queryClient: QueryClient) {state.permit = nullstate.leases.clear()state.latestToken = null+ state.projectionTickets.clear()+ state.projectionCandidates.clear()+ state.projectionTerminals.clear()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 31f4f0354..fb0804049 100644--- a/src/web/src/hooks/community/read-coordinator.test.ts+++ b/src/web/src/hooks/community/read-coordinator.test.ts@@ -1,6 +1,7 @@import { QueryClient } from "@tanstack/react-query"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { ApiError } from "@/lib/errors"+import { communityKeys } from "@/lib/query-keys"const apiFetch = vi.hoisted(() => vi.fn())const reconcileAccountReadState = vi.hoisted(() => vi.fn())@@ -26,6 +27,14 @@ import {submitReadIntent,submitReadIntentGeneration,} from "./read-coordinator"+import {+ activateInboxProjectionTicket,+ inboxReadCandidateFingerprint,+ registerInboxProjectionTicket,+ registerInboxReadReservationSurface,+ reserveInboxUnreadsResponse,+ type InboxRowTarget,+} from "./inbox-read-reservation"function timelineLease(queryClient: QueryClient, confirmedSeq = 0) {return registerReadSurface(@@ -604,4 +613,142 @@ describe("read coordinator", () => {cutoff: 1,})})++ it("publishes success only after the owned Inbox reconciliation settles", async () => {+ const queryClient = new QueryClient()+ const data = {+ servers: [{+ serverId: "s1",+ channels: [{+ channelId: "channel-1",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ hasDirectUnread: true,+ children: [],+ }],+ }],+ dms: [],+ }+ queryClient.setQueryData(communityKeys.inboxUnreads(), data)+ const target: InboxRowTarget = {+ kind: "channel-direct",+ identity: JSON.stringify(["channel-direct", "s1", "channel-1"]),+ fingerprint: inboxReadCandidateFingerprint({+ channelId: "channel-1",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ openerUnread: false,+ }),+ confirmationChannelId: "channel-1",+ serverId: "s1",+ channelId: "channel-1",+ }+ const receipt = vi.fn()+ activateInboxProjectionTicket(registerInboxProjectionTicket(+ queryClient,+ 1,+ target,+ receipt,+ ))+ const reservation = registerInboxReadReservationSurface(+ queryClient,+ "channel-1",+ vi.fn(),+ )+ const pending = reserveInboxUnreadsResponse(queryClient, data)+ void pending.catch(() => undefined)+ const readLease = timelineLease(queryClient)+ const generation = submitReadIntentGeneration(readLease, {+ kind: "timeline",+ channelId: "channel-1",+ messageId: "message-4",+ seq: 4,+ })!+ const { promoteInboxReadReservation } = await import("./inbox-read-reservation")+ promoteInboxReadReservation(reservation, generation)+ apiFetch.mockResolvedValue({ changed: true, revision: 20, targetSeq: 4 })+ let resolveReconciliation!: () => void+ reconcileAccountReadState.mockReturnValue(new Promise<void>((resolve) => {+ resolveReconciliation = resolve+ }))++ const work = flushPendingReadIntents(queryClient)+ await vi.waitFor(() => expect(reconcileAccountReadState).toHaveBeenCalled())+ expect(receipt).not.toHaveBeenCalled()+ queryClient.setQueryData(communityKeys.inboxUnreads(), { servers: [], dms: [] })+ resolveReconciliation()+ await expect(work).resolves.toEqual({ consumed: true, cutoff: generation })+ expect(receipt).toHaveBeenCalledWith(expect.objectContaining({+ terminal: "success",+ disposition: "retire",+ }))+ })++ it("publishes deferred and reconciliation-error receipts as deterministic rollback", async () => {+ const run = async (mode: "deferred" | "error") => {+ const queryClient = new QueryClient()+ const data = {+ servers: [{+ serverId: "s1",+ channels: [{+ channelId: "channel-1",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ hasDirectUnread: true,+ children: [],+ }],+ }],+ dms: [],+ }+ queryClient.setQueryData(communityKeys.inboxUnreads(), data)+ const target: InboxRowTarget = {+ kind: "channel-direct",+ identity: JSON.stringify(["channel-direct", "s1", "channel-1"]),+ fingerprint: inboxReadCandidateFingerprint({+ channelId: "channel-1",+ lastMessageAt: "2026-08-27T01:00:00.000Z",+ openerUnread: false,+ }),+ confirmationChannelId: "channel-1",+ serverId: "s1",+ channelId: "channel-1",+ }+ const receipt = vi.fn()+ activateInboxProjectionTicket(registerInboxProjectionTicket(+ queryClient,+ 1,+ target,+ receipt,+ ))+ const reservation = registerInboxReadReservationSurface(+ queryClient,+ "channel-1",+ vi.fn(),+ )+ const pending = reserveInboxUnreadsResponse(queryClient, data)+ void pending.catch(() => undefined)+ const readLease = timelineLease(queryClient)+ const generation = submitReadIntentGeneration(readLease, {+ kind: "timeline",+ channelId: "channel-1",+ messageId: "message-4",+ seq: 4,+ })!+ const { promoteInboxReadReservation } = await import("./inbox-read-reservation")+ promoteInboxReadReservation(reservation, generation)+ apiFetch.mockResolvedValue({ changed: true, revision: 20, targetSeq: 4 })+ if (mode === "error") {+ reconcileAccountReadState.mockRejectedValue(new Error("refresh failed"))+ }+ await flushPendingReadIntents(queryClient, mode === "deferred"+ ? { deferInboxDms: () => true }+ : undefined)+ expect(receipt).toHaveBeenCalledWith(expect.objectContaining({+ terminal: mode,+ disposition: "rollback",+ observedFingerprint: null,+ }))+ }+ await run("deferred")+ apiFetch.mockReset()+ reconcileAccountReadState.mockReset().mockResolvedValue(undefined)+ await run("error")+ })})diff --git a/src/web/src/hooks/community/read-coordinator.ts b/src/web/src/hooks/community/read-coordinator.tsindex c2db478e6..3e7d09bd3 100644--- a/src/web/src/hooks/community/read-coordinator.ts+++ b/src/web/src/hooks/community/read-coordinator.ts@@ -13,6 +13,7 @@ import {} from "./read-coordinator-snapshot-projection"import {disposeInboxReadReservation,+ publishInboxProjectionGenerationTerminal,settleInboxReadReservationGeneration,} from "./inbox-read-reservation"@@ -473,17 +474,32 @@ class ReadCoordinator {targetRevision: response.revision,})if (deferInboxDms) {+ publishInboxProjectionGenerationTerminal(+ this.queryClient,+ target.generation,+ "deferred",+ )return {committed: true,reconciled: false,deferred: true,}}+ publishInboxProjectionGenerationTerminal(+ this.queryClient,+ target.generation,+ "success",+ )return {committed: true,reconciled: this.attemptActive(state, attemptEpoch, identityEpoch),}} catch {+ publishInboxProjectionGenerationTerminal(+ this.queryClient,+ target.generation,+ "error",+ )return { committed: true, reconciled: false }} finally {this.finishAttempt(state, attemptEpoch)diff --git a/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts b/src/web/src/hooks/community/use-inbox-auto-collapse.test.tsindex 834e68704..11f1d483e 100644--- a/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts+++ b/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts@@ -1,298 +1,203 @@-import { describe, it, expect } from "vitest"-import React from "react"+import { createElement } from "react"import TestRenderer, { act } from "react-test-renderer"-import type { Mention, UnreadDm, UnreadServer } from "@/lib/community/models/inbox"-import {- inboxItemPresent,- useInboxAutoCollapse,- type InboxLists,-} from "./use-inbox-auto-collapse"--// ── Fixtures ─────────────────────────────────────────────────────────────────--function server(serverId: string, channels: Array<{ id: string; children?: string[] }>): UnreadServer {- return {- serverId,- serverName: serverId,- channels: channels.map((c) => ({- channelId: c.id,- channelName: c.id,- lastMessageAt: "2026-01-01T00:00:00.000Z",- mentionCount: 0,- children: (c.children ?? []).map((chId) => ({- channelId: chId,- channelName: chId,- lastMessageAt: "2026-01-01T00:00:00.000Z",- mentionCount: 0,- })),- })),- }-}--function dm(id: string): UnreadDm {- return {- channelId: id,- otherUserId: `u-${id}`,- otherUserName: id,- otherUserDiscriminator: "0001",- otherUserAvatar: "?",- lastMessageAt: "2026-01-01T00:00:00.000Z",- }-}--function mention(id: string, channelId = "c1"): Mention {+import { beforeEach, describe, expect, it, vi } from "vitest"+import type {+ InboxProjectionTerminalReceipt,+ InboxRowTarget,+} from "./inbox-read-reservation"+import { useInboxAutoCollapse } from "./use-inbox-auto-collapse"++const mocks = vi.hoisted(() => ({+ callbacks: new Map<symbol, (receipt: InboxProjectionTerminalReceipt) => void>(),+ activate: vi.fn(),+ cancel: vi.fn(),+}))++vi.mock("./inbox-read-reservation", async (importOriginal) => {+ const original = await importOriginal<typeof import("./inbox-read-reservation")>()return {- id,- server: "s1",- serverId: "s1",- channel: channelId,- channelId,- m: { id: `msg-${id}`, authorId: "a", authorName: "A", authorAvatar: "?", content: "hi" } as Mention["m"],+ ...original,+ registerInboxProjectionTicket: (+ queryClient: unknown,+ epoch: number,+ _target: InboxRowTarget,+ callback: (receipt: InboxProjectionTerminalReceipt) => void,+ ) => {+ const token = Symbol(String(epoch))+ mocks.callbacks.set(token, callback)+ return { queryClient, epoch, token }+ },+ activateInboxProjectionTicket: (...args: unknown[]) => mocks.activate(...args),+ cancelInboxProjectionTicket: (...args: unknown[]) => mocks.cancel(...args),}-}--const EMPTY: InboxLists = { unreads: [], unreadDms: [], mentions: [] }--// ── inboxItemPresent (pure) ──────────────────────────────────────────────────--describe("inboxItemPresent", () => {- it("finds a dm:<id> present in unreadDms; false when absent", () => {- const lists: InboxLists = { ...EMPTY, unreadDms: [dm("d1")] }- expect(inboxItemPresent(lists, "dm:d1")).toBe(true)- expect(inboxItemPresent(lists, "dm:d2")).toBe(false)- })-- it("finds a channel:<id> that is a top-level channel", () => {- const lists: InboxLists = { ...EMPTY, unreads: [server("s1", [{ id: "c1" }])] }- expect(inboxItemPresent(lists, "channel:c1")).toBe(true)- expect(inboxItemPresent(lists, "channel:c2")).toBe(false)- })-- it("finds a channel:<id> that is a nested child thread", () => {- const lists: InboxLists = { ...EMPTY, unreads: [server("s1", [{ id: "c1", children: ["t1"] }])] }- expect(inboxItemPresent(lists, "channel:t1")).toBe(true)- })-- it("finds a mention:<id> present in mentions; false when absent", () => {- const lists: InboxLists = { ...EMPTY, mentions: [mention("m1")] }- expect(inboxItemPresent(lists, "mention:m1")).toBe(true)- expect(inboxItemPresent(lists, "mention:m2")).toBe(false)- })-- it("returns false for an unknown / garbage key", () => {- const lists: InboxLists = { unreads: [server("s1", [{ id: "c1" }])], unreadDms: [dm("d1")], mentions: [mention("m1")] }- expect(inboxItemPresent(lists, "bogus")).toBe(false)- expect(inboxItemPresent(lists, "")).toBe(false)- expect(inboxItemPresent(lists, "widget:c1")).toBe(false)- })})-// ── Hook harness ─────────────────────────────────────────────────────────────+const target = (fingerprint = "g1", channelId = "c1"): InboxRowTarget => ({+ kind: "channel-direct",+ identity: JSON.stringify(["channel-direct", "s1", channelId]),+ fingerprint,+ confirmationChannelId: channelId,+ serverId: "s1",+ channelId,+})+type Options = Parameters<typeof useInboxAutoCollapse>[0]type Api = ReturnType<typeof useInboxAutoCollapse>-function Capture({ lists, onResult }: { lists: InboxLists; onResult: (r: Api) => void }) {- const api = useInboxAutoCollapse(lists)- onResult(api)+function Capture({ options, onResult }: { options: Options; onResult: (api: Api) => void }) {+ onResult(useInboxAutoCollapse(options))return null}-async function renderHook(initial: InboxLists) {- let latest!: Api+async function renderHook(overrides: Partial<Options> = {}) {+ let current!: Api+ let options = {+ queryClient: {} as Options["queryClient"],+ publishedHref: "/c/channels/s1",+ navigationPending: false,+ pendingHref: null,+ ...overrides,+ }let renderer!: TestRenderer.ReactTestRendererawait act(async () => {- renderer = TestRenderer.create(- React.createElement(Capture, { lists: initial, onResult: (r) => { latest = r } }),- )+ renderer = TestRenderer.create(createElement(Capture, {+ options,+ onResult: (api) => { current = api },+ }))})return {- get current() {- return latest+ get current() { return current },+ async call(callback: () => void) {+ await act(async () => callback())},- async rerender(lists: InboxLists) {+ async rerender(next: Partial<Options>) {+ options = { ...options, ...next }await act(async () => {- renderer.update(- React.createElement(Capture, { lists, onResult: (r) => { latest = r } }),- )+ renderer.update(createElement(Capture, {+ options,+ onResult: (api) => { current = api },+ }))})},- async call(fn: () => void) {- await act(async () => {- fn()- })+ async unmount() {+ await act(async () => renderer.unmount())},}}-// ── useInboxAutoCollapse ─────────────────────────────────────────────────────-describe("useInboxAutoCollapse", () => {- it("collapses once a watched channel leaves the list", async () => {- const withC1: InboxLists = { ...EMPTY, unreads: [server("s1", [{ id: "c1" }])] }- const hook = await renderHook(withC1)- await hook.call(() => hook.current.onOpenChange(true))- await hook.call(() => hook.current.watchItem("channel:c1"))- // Still present → stays open.- await hook.rerender(withC1)- expect(hook.current.open).toBe(true)- // c1 gone → collapses.- await hook.rerender(EMPTY)- expect(hook.current.open).toBe(false)- })-- it("keeps the popover open when a watched forum parent remains to host an unread child", async () => {- const withForum: InboxLists = { ...EMPTY, unreads: [server("s1", [{ id: "forum1", children: ["p1"] }])] }- const hook = await renderHook(withForum)- await hook.call(() => hook.current.onOpenChange(true))- await hook.call(() => hook.current.watchItem("channel:forum1"))- // The parent's own opener unread is gone, but it remains to host p1.- await hook.rerender({ ...EMPTY, unreads: [server("s1", [{ id: "forum1", children: ["p1"] }])] })- expect(hook.current.open).toBe(true)+ beforeEach(() => {+ mocks.callbacks.clear()+ mocks.activate.mockReset()+ mocks.cancel.mockReset()})- it("collapses an opener-only forum thread after the successful parent refresh removes it", async () => {- const withOpener = { ...EMPTY, unreads: [server("s1", [{ id: "forum1", children: ["post1"] }])] }- const hook = await renderHook(withOpener)+ it("closes immediately and projects only the exact identity and fingerprint", async () => {+ const hook = await renderHook()await hook.call(() => hook.current.onOpenChange(true))- await hook.call(() => hook.current.watchItem("channel:post1"))+ await hook.call(() => hook.current.beginProjection(target(), "/c/channels/s1/c1"))- // Parent progressive read consumes the opener; there are no child replies,- // so the nested thread row leaves the Inbox immediately after refetch.- await hook.rerender(EMPTY)expect(hook.current.open).toBe(false)+ expect(hook.current.isProjected(target())).toBe(true)+ expect(hook.current.isProjected(target("g2"))).toBe(false)+ expect(hook.current.isProjected(target("g1", "c2"))).toBe(false)})- it("keeps an opener-plus-reply thread until the child eager read consumes replies", async () => {- const withPost = { ...EMPTY, unreads: [server("s1", [{ id: "forum1", children: ["post1"] }])] }- const hook = await renderHook(withPost)+ it("preserves a tombstone across manual close and reopen", async () => {+ const hook = await renderHook()await hook.call(() => hook.current.onOpenChange(true))- await hook.call(() => hook.current.watchItem("channel:post1"))-- // Parent read removes the opener projection, but the same deduped child row- // remains because it still has unread replies.- await hook.rerender(withPost)- expect(hook.current.open).toBe(true)-- // The destination child's existing eager read then removes the reply row.- await hook.rerender(EMPTY)- expect(hook.current.open).toBe(false)- })-- it("collapses when a watched DM leaves the list", async () => {- const withD1: InboxLists = { ...EMPTY, unreadDms: [dm("d1")] }- const hook = await renderHook(withD1)- await hook.call(() => hook.current.onOpenChange(true))- await hook.call(() => hook.current.watchItem("dm:d1"))- await hook.rerender(EMPTY)- expect(hook.current.open).toBe(false)- })-- it("collapses when a watched mention leaves the list", async () => {- const withM1: InboxLists = { ...EMPTY, mentions: [mention("m1")] }- const hook = await renderHook(withM1)- await hook.call(() => hook.current.onOpenChange(true))- await hook.call(() => hook.current.watchItem("mention:m1"))- await hook.rerender(EMPTY)- expect(hook.current.open).toBe(false)- })-- it("clears the pending key after a collapse — later unrelated changes don't re-close", async () => {- const withC1D1: InboxLists = { ...EMPTY, unreads: [server("s1", [{ id: "c1" }])], unreadDms: [dm("d1")] }- const hook = await renderHook(withC1D1)- await hook.call(() => hook.current.onOpenChange(true))- await hook.call(() => hook.current.watchItem("channel:c1"))- // c1 leaves → collapse.- await hook.rerender({ ...EMPTY, unreadDms: [dm("d1")] })- expect(hook.current.open).toBe(false)- // Reopen by user; then an unrelated DM leaves. Must NOT auto-close (no key).- await hook.call(() => hook.current.onOpenChange(true))- await hook.rerender(EMPTY)- expect(hook.current.open).toBe(true)- })-- it("reopening (onOpenChange(true)) clears a stale pending key so it can't fire later", async () => {- const withC1: InboxLists = { ...EMPTY, unreads: [server("s1", [{ id: "c1" }])] }- const hook = await renderHook(withC1)- await hook.call(() => hook.current.onOpenChange(true))- await hook.call(() => hook.current.watchItem("channel:c1"))- // User closes manually, then reopens — this clears the pending key.- await hook.call(() => hook.current.onOpenChange(false))+ await hook.call(() => hook.current.beginProjection(target(), "/c/channels/s1/c1"))await hook.call(() => hook.current.onOpenChange(true))- // c1 now leaves → must stay open (stale key was cleared on reopen).- await hook.rerender(EMPTY)- expect(hook.current.open).toBe(true)- })-- it("does nothing while closed even if a watched item leaves", async () => {- const withC1: InboxLists = { ...EMPTY, unreads: [server("s1", [{ id: "c1" }])] }- const hook = await renderHook(withC1)- // watchItem set while popover is closed (open=false by default).- await hook.call(() => hook.current.watchItem("channel:c1"))- await hook.rerender(EMPTY)+ expect(hook.current.isProjected(target())).toBe(true)+ })++ it("preserves the latest lease across a shell controller remount", async () => {+ const queryClient = {} as Options["queryClient"]+ const href = "/c/channels/s1/c1"+ const first = await renderHook({+ queryClient,+ navigationPending: true,+ pendingHref: href,+ })+ let epoch = 0+ await first.call(() => { epoch = first.current.beginProjection(target(), href) })+ await first.call(() => first.current.markProjectionSubmitted(epoch))+ await first.unmount()++ const second = await renderHook({ queryClient, publishedHref: href })+ expect(second.current.isProjected(target())).toBe(true)+ })++ it("activates a same-href ticket immediately after submission", async () => {+ const hook = await renderHook({ publishedHref: "/c/channels/s1/c1" })+ let epoch = 0+ await hook.call(() => { epoch = hook.current.beginProjection(target(), "/c/channels/s1/c1") })+ await hook.call(() => hook.current.markProjectionSubmitted(epoch))+ expect(mocks.activate).toHaveBeenCalledTimes(1)+ })++ it("activates only after a pending destination publishes", async () => {+ const href = "/c/channels/s1/c1"+ const hook = await renderHook()+ let epoch = 0+ await hook.call(() => { epoch = hook.current.beginProjection(target(), href) })+ await hook.rerender({ navigationPending: true, pendingHref: href })+ await hook.call(() => hook.current.markProjectionSubmitted(epoch))+ expect(mocks.activate).not.toHaveBeenCalled()+ await hook.rerender({ publishedHref: href, navigationPending: false, pendingHref: null })+ expect(mocks.activate).toHaveBeenCalledTimes(1)+ })++ it("rolls back a canceled pre-commit intent without reopening", async () => {+ const href = "/c/channels/s1/c1"+ const hook = await renderHook({ navigationPending: true, pendingHref: href })+ let epoch = 0+ await hook.call(() => { epoch = hook.current.beginProjection(target(), href) })+ await hook.call(() => hook.current.markProjectionSubmitted(epoch))+ await hook.rerender({ navigationPending: false, pendingHref: null })+ expect(hook.current.isProjected(target())).toBe(false)expect(hook.current.open).toBe(false)})- it("does not collapse without a watchItem call (mark-all-read / remove-mention path)", async () => {- const full: InboxLists = { unreads: [server("s1", [{ id: "c1" }])], unreadDms: [dm("d1")], mentions: [mention("m1")] }- const hook = await renderHook(full)+ it("restores the prior open state for a latest synchronous push failure", async () => {+ const hook = await renderHook()await hook.call(() => hook.current.onOpenChange(true))- // No watchItem — everything empties (e.g. Mark all read).- await hook.rerender(EMPTY)+ let epoch = 0+ await hook.call(() => { epoch = hook.current.beginProjection(target(), "/c/channels/s1/c1") })+ await hook.call(() => hook.current.rollbackProjection(epoch, true))expect(hook.current.open).toBe(true)- })-- // Regression for the watch-key overwrite bug: the shell's onOpenMention calls- // openServerChannel(serverId, channelId, `mention:<id>`), and openServerChannel- // forwards its `watchKey` param to watchItem. If openServerChannel ignored the- // param and hardcoded `channel:<cid>`, the mention key would be overwritten.- // These two tests pin that the forwarded key wins.- it("openServerChannel forwards an explicit watchKey (mention path) instead of hardcoding channel:<cid>", async () => {- // Mirror the shell wiring: openServerChannel(sid, cid, watchKey) → watchItem(watchKey).- const before: InboxLists = {- unreads: [server("s1", [{ id: "c1", children: ["p1"] }])],- unreadDms: [],- mentions: [mention("m1", "c1")],- }- const hook = await renderHook(before)- const openServerChannel = (_sid: string, cid: string, watchKey = `channel:${cid}`) => {- hook.current.watchItem(watchKey)- }- await hook.call(() => hook.current.onOpenChange(true))- // onOpenMention path: pass the mention key.- await hook.call(() => openServerChannel("s1", "c1", "mention:m1"))- // Channel c1 stays (hosts child p1); only the mention leaves.- await hook.rerender({ unreads: [server("s1", [{ id: "c1", children: ["p1"] }])], unreadDms: [], mentions: [] })- // If the channel key had overwritten the mention key, c1 would still be- // present and this would be `true` (the bug). It must collapse.- expect(hook.current.open).toBe(false)- })-- it("openServerChannel defaults watchKey to channel:<cid> when the caller omits it (plain channel click)", async () => {- const before: InboxLists = { ...EMPTY, unreads: [server("s1", [{ id: "c1" }])] }- const hook = await renderHook(before)- const openServerChannel = (_sid: string, cid: string, watchKey = `channel:${cid}`) => {- hook.current.watchItem(watchKey)- }- await hook.call(() => hook.current.onOpenChange(true))- await hook.call(() => openServerChannel("s1", "c1"))- await hook.rerender(EMPTY)- expect(hook.current.open).toBe(false)- })-- it("watching the mention key collapses even when the mention's channel persists to host unread children", async () => {- // Mention m1 lives in c1; c1 also hosts an unread child p1. Reading the- // channel clears m1 but keeps c1 (to host p1). Because we watch the mention- // key — not channel:c1 — the popover still collapses when m1 leaves.- const before: InboxLists = {- unreads: [server("s1", [{ id: "c1", children: ["p1"] }])],- unreadDms: [],- mentions: [mention("m1", "c1")],- }- const hook = await renderHook(before)- await hook.call(() => hook.current.onOpenChange(true))- await hook.call(() => hook.current.watchItem("mention:m1"))- // m1 gone, c1 still present.- await hook.rerender({ unreads: [server("s1", [{ id: "c1", children: ["p1"] }])], unreadDms: [], mentions: [] })- expect(hook.current.open).toBe(false)+ expect(hook.current.isProjected(target())).toBe(false)+ })++ it("ignores a stale receipt after A is superseded by B", async () => {+ const hook = await renderHook()+ let aEpoch = 0+ await hook.call(() => { aEpoch = hook.current.beginProjection(target(), "/c/channels/s1/c1") })+ const aCallback = [...mocks.callbacks.values()][0]!+ await hook.call(() => hook.current.beginProjection(target("b1", "c2"), "/c/channels/s1/c2"))+ await hook.call(() => aCallback({+ epoch: aEpoch,+ target: target(),+ terminal: "success",+ disposition: "retire",+ observedFingerprint: null,+ }))+ expect(hook.current.isProjected(target("b1", "c2"))).toBe(true)+ })++ it("clears the matching projection for either frozen terminal disposition", async () => {+ const hook = await renderHook({ publishedHref: "/c/channels/s1/c1" })+ let epoch = 0+ await hook.call(() => { epoch = hook.current.beginProjection(target(), "/c/channels/s1/c1") })+ const callback = [...mocks.callbacks.values()][0]!+ await hook.call(() => hook.current.markProjectionSubmitted(epoch))+ await hook.call(() => callback({+ epoch,+ target: target(),+ terminal: "negative",+ disposition: "rollback",+ observedFingerprint: "g1",+ }))+ expect(hook.current.isProjected(target())).toBe(false)})})diff --git a/src/web/src/hooks/community/use-inbox-auto-collapse.ts b/src/web/src/hooks/community/use-inbox-auto-collapse.tsindex ac6482e98..d2ff73446 100644--- a/src/web/src/hooks/community/use-inbox-auto-collapse.ts+++ b/src/web/src/hooks/community/use-inbox-auto-collapse.ts@@ -1,81 +1,197 @@"use client"-import { useCallback, useEffect, useRef, useState } from "react"-import type { Mention, UnreadDm, UnreadServer } from "@/lib/community/models/inbox"--/**- * Inbox auto-collapse.- *- * The inbox popover should close by itself the moment the row the user clicked- * leaves the list — and only then. A forum parent can remain after its own- * opener messages are read when it still hosts unread child channels, so the- * popover stays open while that exact `channel:<id>` row is present.- *- * The mechanism: record the clicked row's key (a "pending close" marker held in- * a ref so setting it doesn't render), then watch the inbox lists. When that- * exact key is no longer present, collapse.- *- * Row → key:- * - DM row → `dm:<channelId>` (a DM is a channel)- * - channel row → `channel:<channelId>` (top-level or nested child thread)- * - mention row → `mention:<mention.id>`- */--export type InboxLists = {- unreads: UnreadServer[]- unreadDms: UnreadDm[]- mentions: Mention[]+import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react"+import type { QueryClient } from "@tanstack/react-query"+import {+ activateInboxProjectionTicket,+ cancelInboxProjectionTicket,+ registerInboxProjectionTicket,+ type InboxProjectionTicket,+ type InboxRowTarget,+} from "./inbox-read-reservation"++type ProjectionLease = {+ epoch: number+ target: InboxRowTarget+ destinationHref: string+ previousOpen: boolean+ phase: "submitting" | "committed"+ submitted: boolean+ ticket: InboxProjectionTicket+}++type Options = {+ queryClient: QueryClient+ publishedHref: string+ navigationPending: boolean+ pendingHref: string | null+}++type ProjectionStore = {+ current: ProjectionLease | null+ listeners: Set<() => void>+ nextEpoch: number+}++const projectionStores = new WeakMap<QueryClient, ProjectionStore>()++function projectionStoreFor(queryClient: QueryClient) {+ let store = projectionStores.get(queryClient)+ if (!store) {+ store = { current: null, listeners: new Set(), nextEpoch: 0 }+ projectionStores.set(queryClient, store)+ }+ return store+}++function publishProjection(store: ProjectionStore, lease: ProjectionLease | null) {+ store.current = lease+ for (const listener of store.listeners) listener()+}++function allocateProjectionEpoch(store: ProjectionStore) {+ store.nextEpoch += 1+ return store.nextEpoch}-// Pure: is the keyed row still somewhere in the inbox lists?-export function inboxItemPresent(lists: InboxLists, key: string): boolean {- const sep = key.indexOf(":")- if (sep < 0) return false- const kind = key.slice(0, sep)- const id = key.slice(sep + 1)- switch (kind) {- case "dm":- return lists.unreadDms.some((d) => d.channelId === id)- case "channel":- return lists.unreads.some((s) =>- s.channels.some(- (c) => c.channelId === id || c.children.some((ch) => ch.channelId === id),- ),- )- case "mention":- return lists.mentions.some((m) => m.id === id)- default:- return false+function destinationMatches(observed: string | null, expected: string) {+ if (observed === expected) return true+ if (!observed) return false+ const removeHandoff = (href: string) => {+ const [pathname, query = ""] = href.split("?")+ const params = new URLSearchParams(query)+ params.delete("inboxThreadOpener")+ const search = params.toString()+ return `${pathname}${search ? `?${search}` : ""}`}+ return removeHandoff(observed) === removeHandoff(expected)}-export function useInboxAutoCollapse({ unreads, unreadDms, mentions }: InboxLists) {+export function useInboxAutoCollapse({+ queryClient,+ publishedHref,+ navigationPending,+ pendingHref,+}: Options) {const [open, setOpen] = useState(false)- const pendingKeyRef = useRef<string | null>(null)+ const store = projectionStoreFor(queryClient)+ const projection = useSyncExternalStore(+ (listener) => {+ store.listeners.add(listener)+ return () => store.listeners.delete(listener)+ },+ () => store.current,+ () => store.current,+ )+ const openRef = useRef(open)++ const commitLease = useCallback((lease: ProjectionLease) => {+ if (store.current?.epoch !== lease.epoch) return+ const committed = { ...lease, phase: "committed" as const }+ publishProjection(store, committed)+ activateInboxProjectionTicket(lease.ticket)+ }, [store])++ const rollbackProjection = useCallback((epoch: number, reopen = false) => {+ const lease = store.current+ if (!lease || lease.epoch !== epoch) return false+ cancelInboxProjectionTicket(lease.ticket)+ publishProjection(store, null)+ if (reopen) {+ openRef.current = lease.previousOpen+ setOpen(lease.previousOpen)+ }+ return true+ }, [store])++ const beginProjection = useCallback((+ target: InboxRowTarget,+ destinationHref: string,+ ) => {+ const previous = store.current+ if (previous) cancelInboxProjectionTicket(previous.ticket)+ const epoch = allocateProjectionEpoch(store)+ const previousOpen = openRef.current+ const ticket = registerInboxProjectionTicket(+ queryClient,+ epoch,+ target,+ (receipt) => {+ const current = store.current+ if (!current || current.epoch !== receipt.epoch) return+ publishProjection(store, null)+ },+ )+ const lease: ProjectionLease = {+ epoch,+ target,+ destinationHref,+ previousOpen,+ phase: "submitting",+ submitted: false,+ ticket,+ }+ publishProjection(store, lease)+ openRef.current = false+ setOpen(false)+ return epoch+ }, [queryClient, store])++ const markProjectionSubmitted = useCallback((epoch: number) => {+ const lease = store.current+ if (!lease || lease.epoch !== epoch) return false+ const submitted = { ...lease, submitted: true }+ publishProjection(store, submitted)+ if (destinationMatches(publishedHref, lease.destinationHref)) {+ commitLease(submitted)+ }+ return true+ }, [commitLease, publishedHref, store])++ const closeWithoutProjection = useCallback(() => {+ const lease = store.current+ if (lease) cancelInboxProjectionTicket(lease.ticket)+ publishProjection(store, null)+ const previousOpen = openRef.current+ openRef.current = false+ setOpen(false)+ return previousOpen+ }, [store])- // Toggling the popover (open OR close, by user or by us) clears any pending- // marker so a stale key can never fire a surprise close later.const onOpenChange = useCallback((next: boolean) => {- pendingKeyRef.current = null+ openRef.current = nextsetOpen(next)}, [])- // Call when a row is opened AND navigation happens.- const watchItem = useCallback((key: string) => {- pendingKeyRef.current = key- }, [])+ const isProjected = useCallback((target: InboxRowTarget | null) => {+ if (!target || !projection) return false+ return projection.target.identity === target.identity+ && projection.target.fingerprint === target.fingerprint+ }, [projection])++ const isLatestProjection = useCallback((epoch: number) => (+ store.current?.epoch === epoch+ ), [store])- // When the watched row leaves the list, collapse. Keyed off the list arrays- // (stable references from React Query) so it re-checks precisely when the- // "row disappeared" signal lands, not on every render.useEffect(() => {- const key = pendingKeyRef.current- if (!open || !key) return- if (!inboxItemPresent({ unreads, unreadDms, mentions }, key)) {- pendingKeyRef.current = null- setOpen(false)+ const lease = store.current+ if (!lease || !lease.submitted || lease.phase !== "submitting") return+ if (destinationMatches(publishedHref, lease.destinationHref)) {+ commitLease(lease)+ return}- }, [open, unreads, unreadDms, mentions])+ if (navigationPending && destinationMatches(pendingHref, lease.destinationHref)) return+ rollbackProjection(lease.epoch)+ }, [commitLease, navigationPending, pendingHref, projection, publishedHref, rollbackProjection, store])- return { open, onOpenChange, watchItem }+ return {+ open,+ onOpenChange,+ beginProjection,+ markProjectionSubmitted,+ rollbackProjection,+ closeWithoutProjection,+ isProjected,+ isLatestProjection,+ }}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 a5dffdd05..a20ad2c63 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@@ -114,10 +114,63 @@ async function watchInboxRow(page: Parameters<typeof gotoAfterUserWsAuth>[0], tetest.describe.serial("Inbox/read refresh ownership", () => {test.setTimeout(180_000)+ test("an Inbox click closes, publishes, and hides only its exact row before read settles", async ({ asUser }) => {+ const stamp = Date.now()+ const serverId = await seedServer("alice", `Inbox projection ${stamp}`)+ const channelAName = `project-a-${stamp}`+ const channelA = await seedChannel("alice", serverId, channelAName)+ const channelB = await seedChannel("alice", serverId, `project-b-${stamp}`)+ await seedJoinServer("alice", "bob", serverId)+ await seedMessage("alice", channelA, `Projected A ${stamp}`)+ await seedMessage("alice", channelB, `Unrelated B ${stamp}`)++ const { page } = await asUser("bob")+ await gotoAfterUserWsAuth(page, "/c/me")+ await page.getByRole("button", { name: "Inbox" }).click()+ await expect(page.getByTestId(tid.inboxUnreadChannel(channelA))).toBeVisible()+ await expect(page.getByTestId(tid.inboxUnreadChannel(channelB))).toBeVisible()++ const readGate = deferred()+ const readStarted = deferred()+ const hrefsAtRead: string[] = []+ await page.route(`**/api/community/channels/${channelA}/read`, async (route) => {+ if (route.request().method() !== "PUT") return route.continue()+ hrefsAtRead.push(page.url())+ readStarted.resolve()+ await readGate.promise+ await route.continue()+ })++ await page.getByTestId(tid.inboxUnreadChannel(channelA)).click()+ await expect(page).toHaveURL(`/c/channels/${serverId}/${channelA}`)+ await expect(page.getByRole("heading", { name: "Inbox" })).toHaveCount(0)+ await expect(page.getByRole("heading", { name: channelAName, exact: true })).toBeVisible({+ timeout: 20_000,+ })++ await page.getByRole("button", { name: "Inbox" }).click()+ await expect(page.getByTestId(tid.inboxUnreadChannel(channelA))).toHaveCount(0)+ await expect(page.getByTestId(tid.inboxUnreadChannel(channelB))).toBeVisible()+ await readStarted.promise+ expect(hrefsAtRead).toEqual([+ expect.stringContaining(`/c/channels/${serverId}/${channelA}`),+ ])++ const reconciledInbox = page.waitForResponse((response) => (+ response.request().method() === "GET"+ && new URL(response.url()).pathname === "/api/community/users/me/inbox/unreads"+ ))+ readGate.resolve()+ expect((await reconciledInbox).status()).toBe(200)+ await expect(page.getByTestId(tid.inboxUnreadChannel(channelA))).toHaveCount(0)+ await expect(page.getByTestId(tid.inboxUnreadChannel(channelB))).toBeVisible()+ })+test("focused A never flashes while same-window B and DM remain unread", async ({ asUser }) => {const stamp = Date.now()const serverId = await seedServer("alice", `Inbox race mixed ${stamp}`)- const channelA = await seedChannel("alice", serverId, `focused-a-${stamp}`)+ const channelAName = `focused-a-${stamp}`+ const channelA = await seedChannel("alice", serverId, channelAName)const channelB = await seedChannel("alice", serverId, `unread-b-${stamp}`)await seedJoinServer("alice", "bob", serverId)const dmId = await seedDm("carol", userId("bob"))@@ -129,6 +182,9 @@ test.describe.serial("Inbox/read refresh ownership", () => {response.request().method() === "GET"&& new URL(response.url()).pathname === "/api/community/users/me/inbox/unreads"))+ await expect(page.getByRole("heading", { name: channelAName, exact: true })).toBeVisible({+ timeout: 20_000,+ })await page.getByRole("button", { name: "Inbox" }).click()expect((await initialInbox).status()).toBe(200)await expect(page.getByTestId(tid.inboxUnreadChannel(channelA))).toHaveCount(0)@@ -214,7 +270,8 @@ test.describe.serial("Inbox/read refresh ownership", () => {test("a failed focused read falls back once, then retry converges", async ({ asUser }) => {const stamp = Date.now()const serverId = await seedServer("alice", `Inbox race failure ${stamp}`)- const channelId = await seedChannel("alice", serverId, `failure-${stamp}`)+ const channelName = `failure-${stamp}`+ const channelId = await seedChannel("alice", serverId, channelName)await seedJoinServer("alice", "bob", serverId)const { page } = await asUser("bob")await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)@@ -222,6 +279,9 @@ test.describe.serial("Inbox/read refresh ownership", () => {response.request().method() === "GET"&& new URL(response.url()).pathname === "/api/community/users/me/inbox/unreads"))+ await expect(page.getByRole("heading", { name: channelName, exact: true })).toBeVisible({+ timeout: 20_000,+ })await page.getByRole("button", { name: "Inbox" }).click()expect((await initialInbox).status()).toBe(200)await expect(page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0)@@ -436,7 +496,8 @@ test.describe.serial("Inbox/read refresh ownership", () => {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}`)- const channelId = await seedChannel("alice", serverId, `cutoff-${stamp}`)+ const channelName = `cutoff-${stamp}`+ const channelId = await seedChannel("alice", serverId, channelName)await seedJoinServer("alice", "bob", serverId)const { page } = await asUser("bob")await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)@@ -444,6 +505,9 @@ test.describe.serial("Inbox/read refresh ownership", () => {response.request().method() === "GET"&& new URL(response.url()).pathname === "/api/community/users/me/inbox/unreads"))+ await expect(page.getByRole("heading", { name: channelName, exact: true })).toBeVisible({+ timeout: 20_000,+ })await page.getByRole("button", { name: "Inbox" }).click()expect((await initialInbox).status()).toBe(200)await expect(page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0)