Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): auto-collapse inbox when the clicked row leaves the list (#387)

Gener94ae58c13e12
diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsx
index 5f5ba3398..c9d83ffb8 100644
--- a/src/web/src/components/community/shell-frame.tsx
+++ b/src/web/src/components/community/shell-frame.tsx
@@ -36,6 +36,7 @@ import { useFolders } from "@/hooks/community/use-folders"
import { useFriends } from "@/hooks/community/use-friends"
import { useServerMembers } from "@/hooks/community/use-server-members"
import { useInboxUnreads, useInboxMentions } from "@/hooks/community/use-inbox"
+import { useInboxAutoCollapse } from "@/hooks/community/use-inbox-auto-collapse"
import {
useCreateServer,
useJoinServer,
@@ -111,6 +112,10 @@ export function ShellFrame({
const unreadDms = inboxUnreads.dms
const mentions = inboxMentions.mentions
const inboxLoading = inboxUnreads.isLoading || inboxMentions.isLoading
+ // Popover open-state + auto-collapse: the inbox closes itself once the row
+ // the viewer clicked leaves the list. See use-inbox-auto-collapse.
+ const inbox = useInboxAutoCollapse({ unreads: unreadFeed, unreadDms, mentions })
+ const watchInboxItem = inbox.watchItem
// Mutations wired through the shell.
const createServer = useCreateServer()
@@ -455,13 +460,17 @@ export function ShellFrame({
}
const openServerChannel = useCallback(
- (sid: string, cid: string) => {
+ (sid: string, cid: string, watchKey: string = `channel:${cid}`) => {
// No PUT here — the channel/thread page's `useEagerChannelRead` fires the
// mark-read on mount, AFTER its read-state snapshot latches, so the NEW
// divider still anchors to the pre-open pointer. Navigating is enough.
+ // `watchKey` lets the caller own what row the inbox watches for removal —
+ // a mention click passes `mention:<id>` so the mention row (not the
+ // channel, which may persist to host unread children) drives the collapse.
+ watchInboxItem(watchKey)
router.push(`/c/channels/${sid}/${cid}`)
},
- [router],
+ [router, watchInboxItem],
)
const openInboxDm = useCallback(
@@ -478,9 +487,10 @@ export function ShellFrame({
? { ...prev, conversations: prev.conversations.map((d) => (d.id === dmId ? { ...d, unread: false } : d)) }
: prev,
)
+ watchInboxItem(`dm:${dmId}`)
router.push(`/c/me/${dmId}`)
},
- [router, queryClient],
+ [router, queryClient, watchInboxItem],
)
const inboxElement = (
@@ -492,7 +502,7 @@ export function ShellFrame({
onOpenChannel={openServerChannel}
onOpenDm={openInboxDm}
onOpenMention={(mention) => {
- if (mention.serverId && mention.channelId) openServerChannel(mention.serverId, mention.channelId)
+ if (mention.serverId && mention.channelId) openServerChannel(mention.serverId, mention.channelId, `mention:${mention.id}`)
}}
onMarkAllRead={() => { markAllInboxRead.mutate() }}
onDeleteMention={(id) => deleteMention.mutate({ mentionId: id })}
@@ -634,7 +644,7 @@ export function ShellFrame({
</ResizablePanelGroup>
</AppSurface>
<div className="absolute bottom-0 left-0 z-10" style={{ width: sidebarW + 56, marginLeft: -56 }}>
- <UserBar user={{ id: currentUser.id, name: currentUser.name, avatar: currentUser.avatar }} onOpenProfile={openProfile} onEditProfile={() => setEditingProfile(true)} inbox={inboxElement} hasUnread={inboxHasUnread} />
+ <UserBar user={{ id: currentUser.id, name: currentUser.name, avatar: currentUser.avatar }} onOpenProfile={openProfile} onEditProfile={() => setEditingProfile(true)} inbox={inboxElement} hasUnread={inboxHasUnread} inboxOpen={inbox.open} onInboxOpenChange={inbox.onOpenChange} />
</div>
</div>
{profile && <ProfileCard key={`${profile.data.userId ?? profile.data.name}:${profile.x}:${profile.y}`} data={profile.data} x={profile.x} y={profile.y} bp={bp} onClose={() => setProfile(null)} onMessage={profileMessage} isSelf={!!profile.data.userId && profile.data.userId === currentUser.id} onUpdateStatus={updateOwnStatus} initialStatusEmoji={profile.initialStatusEmoji} initialStatusText={profile.initialStatusText} />}
@@ -653,7 +663,7 @@ export function ShellFrame({
<ServerRail {...railProps} bottomInset={60} />
<div className="flex min-h-0 flex-1 flex-col bg-sidebar">
<div className="flex min-h-0 flex-1">{sidebar({ noHeader: false })}</div>
- <UserBar user={{ id: currentUser.id, name: currentUser.name, avatar: currentUser.avatar }} onOpenProfile={openProfile} onEditProfile={() => setEditingProfile(true)} inbox={inboxElement} hasUnread={inboxHasUnread} />
+ <UserBar user={{ id: currentUser.id, name: currentUser.name, avatar: currentUser.avatar }} onOpenProfile={openProfile} onEditProfile={() => setEditingProfile(true)} inbox={inboxElement} hasUnread={inboxHasUnread} inboxOpen={inbox.open} onInboxOpenChange={inbox.onOpenChange} />
</div>
</>
)}
diff --git a/src/web/src/components/community/user-bar.tsx b/src/web/src/components/community/user-bar.tsx
index fd3cfb744..59643e869 100644
--- a/src/web/src/components/community/user-bar.tsx
+++ b/src/web/src/components/community/user-bar.tsx
@@ -11,28 +11,32 @@ import { resolveProfilePresence } from "@/lib/community/presence"
// the self → online branch and never consults an online set.
const EMPTY_ONLINE_SET: ReadonlySet<string> = new Set()
-export function UserBar({ user, onOpenProfile, onEditProfile, inbox, hasUnread }: {
+export function UserBar({ user, onOpenProfile, onEditProfile, inbox, hasUnread, inboxOpen, onInboxOpenChange }: {
user: { id: string; name: string; avatar: string }
onOpenProfile?: OpenProfile
onEditProfile?: () => void
inbox?: React.ReactNode
hasUnread?: boolean
+ inboxOpen?: boolean
+ onInboxOpenChange?: (open: boolean) => void
}) {
return (
<div className="shrink-0 px-3 pb-3 pt-0">
<div className="flex h-12 items-center gap-3 rounded-xl bg-muted px-4 ring-1 ring-border/40">
- <Inner user={user} onOpenProfile={onOpenProfile} onEditProfile={onEditProfile} inbox={inbox} hasUnread={hasUnread} />
+ <Inner user={user} onOpenProfile={onOpenProfile} onEditProfile={onEditProfile} inbox={inbox} hasUnread={hasUnread} inboxOpen={inboxOpen} onInboxOpenChange={onInboxOpenChange} />
</div>
</div>
)
}
-function Inner({ user, onOpenProfile, onEditProfile, inbox, hasUnread }: {
+function Inner({ user, onOpenProfile, onEditProfile, inbox, hasUnread, inboxOpen, onInboxOpenChange }: {
user: { id: string; name: string; avatar: string }
onOpenProfile?: OpenProfile
onEditProfile?: () => void
inbox?: React.ReactNode
hasUnread?: boolean
+ inboxOpen?: boolean
+ onInboxOpenChange?: (open: boolean) => void
}) {
return (
<div className="flex flex-1 items-center gap-2">
@@ -44,7 +48,7 @@ function Inner({ user, onOpenProfile, onEditProfile, inbox, hasUnread }: {
</button>
<div className="flex items-center gap-1">
{inbox && (
- <Popover>
+ <Popover open={inboxOpen} onOpenChange={onInboxOpenChange}>
<PopoverTrigger
render={
<button className="relative grid size-7 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none" aria-label="Inbox" />
diff --git a/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts b/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts
new file mode 100644
index 000000000..91dbbb490
--- /dev/null
+++ b/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts
@@ -0,0 +1,269 @@
+import { describe, it, expect } from "vitest"
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import type { Mention, UnreadDm, UnreadServer } from "@/components/community/_types"
+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 {
+ dmConversationId: id,
+ otherUserId: `u-${id}`,
+ otherUserName: id,
+ otherUserAvatar: "?",
+ lastMessageAt: "2026-01-01T00:00:00.000Z",
+ }
+}
+
+function mention(id: string, channelId = "c1"): Mention {
+ return {
+ id,
+ server: "s1",
+ serverId: "s1",
+ channel: channelId,
+ channelId,
+ m: { id: `msg-${id}`, authorId: "a", authorName: "A", authorAvatar: "?", content: "hi" } as Mention["m"],
+ }
+}
+
+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 / forum-post)", () => {
+ 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 ─────────────────────────────────────────────────────────────
+
+type Api = ReturnType<typeof useInboxAutoCollapse>
+
+function Capture({ lists, onResult }: { lists: InboxLists; onResult: (r: Api) => void }) {
+ const api = useInboxAutoCollapse(lists)
+ onResult(api)
+ return null
+}
+
+async function renderHook(initial: InboxLists) {
+ let latest!: Api
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(Capture, { lists: initial, onResult: (r) => { latest = r } }),
+ )
+ })
+ return {
+ get current() {
+ return latest
+ },
+ async rerender(lists: InboxLists) {
+ await act(async () => {
+ renderer.update(
+ React.createElement(Capture, { lists, onResult: (r) => { latest = r } }),
+ )
+ })
+ },
+ async call(fn: () => void) {
+ await act(async () => {
+ fn()
+ })
+ },
+ }
+}
+
+// ── 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 channel persists (navigate-only forum parent)", 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"))
+ // Re-render with the parent still present (posts unread) → stays open.
+ await hook.rerender({ ...EMPTY, unreads: [server("s1", [{ id: "forum1", children: ["p1"] }])] })
+ expect(hook.current.open).toBe(true)
+ })
+
+ 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.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.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)
+ await hook.call(() => hook.current.onOpenChange(true))
+ // No watchItem — everything empties (e.g. Mark all read).
+ await hook.rerender(EMPTY)
+ 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)
+ })
+})
diff --git a/src/web/src/hooks/community/use-inbox-auto-collapse.ts b/src/web/src/hooks/community/use-inbox-auto-collapse.ts
new file mode 100644
index 000000000..52e2d7fbe
--- /dev/null
+++ b/src/web/src/hooks/community/use-inbox-auto-collapse.ts
@@ -0,0 +1,81 @@
+"use client"
+
+import { useCallback, useEffect, useRef, useState } from "react"
+import type { Mention, UnreadDm, UnreadServer } from "@/components/community/_types"
+
+/**
+ * Inbox auto-collapse.
+ *
+ * The inbox popover should close by itself the moment the row the user clicked
+ * leaves the list — and only then. Clicking a row that merely navigates (e.g. a
+ * forum-channel parent, whose unread posts aren't read by visiting the listing)
+ * keeps its `channel:<id>` row present, so the popover stays open.
+ *
+ * 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:<dmConversationId>`
+ * - channel row → `channel:<channelId>` (top-level OR nested thread/forum-post)
+ * - mention row → `mention:<mention.id>`
+ */
+
+export type InboxLists = {
+ unreads: UnreadServer[]
+ unreadDms: UnreadDm[]
+ mentions: Mention[]
+}
+
+// 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.dmConversationId === 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
+ }
+}
+
+export function useInboxAutoCollapse({ unreads, unreadDms, mentions }: InboxLists) {
+ const [open, setOpen] = useState(false)
+ const pendingKeyRef = useRef<string | null>(null)
+
+ // 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
+ setOpen(next)
+ }, [])
+
+ // Call when a row is opened AND navigation happens.
+ const watchItem = useCallback((key: string) => {
+ pendingKeyRef.current = key
+ }, [])
+
+ // 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)
+ }
+ }, [open, unreads, unreadDms, mentions])
+
+ return { open, onOpenChange, watchItem }
+}