Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): delete forum posts + scope typing per conversation

Gener87f9cf577aef
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.ts
index f41459a49..73b0fa8bb 100644
--- a/src/shared/src/community-ws-events.ts
+++ b/src/shared/src/community-ws-events.ts
@@ -176,6 +176,12 @@ export type CommunityChannelDelete = {
type: "community:channel.delete"
serverId: string
channelId: string
+ // The parent forum/thread channel, when the deleted channel is a child
+ // (forum_post / thread). Lets clients invalidate the parent's post/thread
+ // list so the deleted card disappears from the feed. Optional and additive —
+ // older events without it still work (the handler simply skips the parent
+ // invalidate).
+ parentChannelId?: string | null
}
export type CommunityChannelReorder = {
diff --git a/src/web/src/app/api/community/channels/[id]/route.test.ts b/src/web/src/app/api/community/channels/[id]/route.test.ts
index 8c7dc53e2..defc2972c 100644
--- a/src/web/src/app/api/community/channels/[id]/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/route.test.ts
@@ -340,4 +340,62 @@ describe("DELETE /channels/[id]", () => {
expect(mockBroadcastToUserSafe).toHaveBeenCalledTimes(2)
expect(mockFanOutToServerMembers).not.toHaveBeenCalled()
})
+
+ it("admin deletes any forum_post → 204 and broadcasts", async () => {
+ mockResolveChannelAccessContext.mockResolvedValue(
+ accessCtx({ role: "admin", canManage: true, creatorId: "someone_else" }),
+ )
+ const res = await DELETE(delReq(), ctx)
+ expect(res.status).toBe(204)
+ expect(mockDeleteChannel).toHaveBeenCalled()
+ expect(mockFanOutToServerMembers).toHaveBeenCalled()
+ })
+
+ it("a PUBLIC forum_post's creator (no canManage) can delete it via the carve-out", async () => {
+ mockResolveChannelAccessContext.mockResolvedValue(forumPostCtx({ isCreator: true }))
+ const res = await DELETE(delReq(), ctx)
+ expect(res.status).toBe(204)
+ expect(mockDeleteChannel).toHaveBeenCalledWith(expect.anything(), "c1")
+ })
+
+ it("a private forum_post's creator can delete it (canManage already true)", async () => {
+ // Private post creator: canManage = isPrivate && isCreator → true anyway.
+ mockResolveChannelAccessContext.mockResolvedValue({
+ ...forumPostCtx({ isCreator: true }),
+ isPrivate: true,
+ })
+ mockIsChannelPrivate.mockResolvedValue(true)
+ mockGetPrivateChannelAudienceUserIds.mockResolvedValue(["u1"])
+ const res = await DELETE(delReq(), ctx)
+ expect(res.status).toBe(204)
+ expect(mockDeleteChannel).toHaveBeenCalled()
+ })
+
+ it("a non-creator non-admin cannot delete a forum_post → 403", async () => {
+ mockResolveChannelAccessContext.mockResolvedValue(forumPostCtx({ isCreator: false }))
+ const res = await DELETE(delReq(), ctx)
+ expect(res.status).toBe(403)
+ expect(mockDeleteChannel).not.toHaveBeenCalled()
+ })
+
+ it("the broadcast CHANNEL_DELETE payload carries parentChannelId", async () => {
+ mockResolveChannelAccessContext.mockResolvedValue(forumPostCtx({ isCreator: true }))
+ const res = await DELETE(delReq(), ctx)
+ expect(res.status).toBe(204)
+ const event = mockFanOutToServerMembers.mock.calls[0]?.[1]
+ expect(event).toMatchObject({
+ type: "community:channel.delete",
+ channelId: "c1",
+ parentChannelId: "forum_1",
+ })
+ })
+
+ it("the carve-out does NOT let a non-creator delete a normal (non-forum_post) channel", async () => {
+ // canManage=false + type="text" + not creator → still 403 (carve-out is
+ // scoped to forum_post only).
+ mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ canManage: false }))
+ const res = await DELETE(delReq(), ctx)
+ expect(res.status).toBe(403)
+ expect(mockDeleteChannel).not.toHaveBeenCalled()
+ })
})
diff --git a/src/web/src/app/api/community/channels/[id]/route.ts b/src/web/src/app/api/community/channels/[id]/route.ts
index eec51b4e0..dea384882 100644
--- a/src/web/src/app/api/community/channels/[id]/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/route.ts
@@ -168,8 +168,16 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
const access = await requireChannelAccess(db, channelId, ctx.userId)
if (!access.ok) return writeError(access.error, access.status)
- if (!access.value.canManage) return writeError("forbidden", 403)
const channel = access.value.channel
+ // A forum post's creator may delete their own post even without full
+ // `canManage` (a PUBLIC post's creator has `canManage === false`; a private
+ // post's creator already passes it via `isPrivate && isCreator`). Mirrors the
+ // PATCH tag carve-out. `access.value.isCreator` is the vetted post-own-creator
+ // flag (NOT the forum creator). Scoped to `forum_post` so normal-channel and
+ // thread creators are not granted delete.
+ const canDeletePost =
+ channel.type === "forum_post" && access.value.isCreator
+ if (!access.value.canManage && !canDeletePost) return writeError("forbidden", 403)
// Resolve the private-channel audience BEFORE deleting (the member rows
// cascade away with the channel row), so the delete event still reaches
@@ -186,6 +194,7 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
type: WS_EVENTS.CHANNEL_DELETE,
serverId: channel.serverId,
channelId,
+ parentChannelId: channel.parentChannelId,
} as const
if (audience) {
await Promise.all(audience.map((userId) => broadcastToUserSafe(userId, event)))
diff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
index 4ac1787bd..ba581e5f1 100644
--- a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
@@ -25,6 +25,7 @@ import {
useCurrentChannelId,
useCurrentChannelMeta,
useUiHandlers,
+ useTypingUsersForScope,
} from "@/stores/community"
import { useCurrentUser } from "@/contexts/community/current-user"
import { useServer } from "@/hooks/community/use-servers"
@@ -50,6 +51,7 @@ import {
useCreateThread,
useCreateForumPost,
useUpdatePostTags,
+ useDeleteForumPost,
useSetMemberRole,
useKickMember,
useSetChannelNotif,
@@ -394,7 +396,7 @@ function ChannelView() {
const { pins: pinned, isLoading: pinnedLoading } = usePins(channelId)
const notifs = useNotificationSettings()
const channelNotif = notifs.channel
- const typingUsers = useCommunityStore((s) => s.typingUsers)
+ const typingUsers = useTypingUsersForScope(`ch:${channelId}`)
// Mutations
const sendMessageMut = useSendMessage()
@@ -404,6 +406,7 @@ function ChannelView() {
const createThreadMut = useCreateThread()
const createForumPostMut = useCreateForumPost()
const updatePostTagsMut = useUpdatePostTags()
+ const deleteForumPostMut = useDeleteForumPost()
const setMemberRoleMut = useSetMemberRole()
const kickMemberMut = useKickMember()
const setChannelNotifMut = useSetChannelNotif()
@@ -983,6 +986,14 @@ function ChannelView() {
{ onError: (e) => toastApiError(e, "Failed to save tags") },
)
}}
+ canDeletePost={(post) => canManage || post.authorId === currentUser.id}
+ deletingPost={deleteForumPostMut.isPending ? deleteForumPostMut.variables?.postId ?? null : null}
+ onDeletePost={(post) => {
+ deleteForumPostMut.mutate(
+ { forumChannelId: channelId, postId: post.id },
+ { onError: (e) => toastApiError(e, "Failed to delete post") },
+ )
+ }}
/>
</main>
diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsx
index 7d308d3d4..270bbeb08 100644
--- a/src/web/src/app/c/me/[dmId]/page.tsx
+++ b/src/web/src/app/c/me/[dmId]/page.tsx
@@ -14,6 +14,7 @@ import {
useCommunityStore,
useCurrentChannelId,
useUiHandlers,
+ useTypingUsersForScope,
} from "@/stores/community"
import { useOnlineUserIds, useCommunityWsStore } from "@/stores/community/ws"
import { tid } from "@/lib/community/testids"
@@ -172,7 +173,7 @@ function DmView() {
}, [latestSeq, readSnapshot])
- const typingUsers = useCommunityStore((s) => s.typingUsers)
+ const typingUsers = useTypingUsersForScope(`dm:${dmId}`)
const sendDmMessage = useSendDmMessage()
const toggleReaction = useToggleReactionApi()
const uploadFile = useUploadFile()
diff --git a/src/web/src/components/community/forum-view.test.ts b/src/web/src/components/community/forum-view.test.ts
index 665830473..42dfa68e3 100644
--- a/src/web/src/components/community/forum-view.test.ts
+++ b/src/web/src/components/community/forum-view.test.ts
@@ -29,6 +29,23 @@ function render(posts: ForumPost[]): string {
)
}
+// Render with the delete affordance wired. `canDeletePost` decides per-post
+// visibility; `deletingPost` is the in-flight post id (button disabled).
+function renderWithDelete(
+ posts: ForumPost[],
+ opts: { canDeletePost?: (p: ForumPost) => boolean; deletingPost?: string | null } = {},
+): string {
+ return renderToStaticMarkup(
+ createElement(ForumView, {
+ posts,
+ onOpenPost: () => {},
+ onDeletePost: () => {},
+ canDeletePost: opts.canDeletePost ?? (() => true),
+ deletingPost: opts.deletingPost ?? null,
+ })
+ )
+}
+
describe("ForumView post card header", () => {
it("solo post renders the creator name and no participant AvatarGroup", () => {
const html = render([makePost()])
@@ -74,3 +91,39 @@ describe("ForumView post card header", () => {
expect(withOthers).toContain(tid.forumPostAvatars("p1"))
})
})
+
+describe("ForumView post delete button", () => {
+ it("renders the delete button (with aria-label + testid) when canDeletePost is true", () => {
+ const html = renderWithDelete([makePost()], { canDeletePost: () => true })
+ expect(html).toContain(tid.forumPostDeleteBtn("p1"))
+ expect(html).toContain('aria-label="Delete post"')
+ })
+
+ it("does not render the delete button when canDeletePost is false", () => {
+ const html = renderWithDelete([makePost()], { canDeletePost: () => false })
+ expect(html).not.toContain(tid.forumPostDeleteBtn("p1"))
+ })
+
+ it("does not render the delete button when onDeletePost is absent", () => {
+ // render() wires onOpenPost only — no delete handler → no button.
+ const html = render([makePost()])
+ expect(html).not.toContain(tid.forumPostDeleteBtn("p1"))
+ })
+
+ it("disables the delete button for the post whose delete is in flight", () => {
+ const html = renderWithDelete([makePost()], { deletingPost: "p1" })
+ // The disabled attribute rides on the button carrying the delete testid.
+ const btnIdx = html.indexOf(tid.forumPostDeleteBtn("p1"))
+ expect(btnIdx).toBeGreaterThanOrEqual(0)
+ // renderToStaticMarkup emits a bare `disabled` attribute for disabled={true}.
+ const around = html.slice(Math.max(0, btnIdx - 200), btnIdx + 200)
+ expect(around).toContain("disabled")
+ })
+
+ it("does NOT render the ConfirmDialog until the delete button is clicked", () => {
+ // Static markup can't fire a click, so the confirm dialog (state-gated) is
+ // absent on first paint — proves clicking, not rendering, opens it.
+ const html = renderWithDelete([makePost()])
+ expect(html).not.toContain("Delete post?")
+ })
+})
diff --git a/src/web/src/components/community/forum-view.tsx b/src/web/src/components/community/forum-view.tsx
index e2398aab4..eff134b5a 100644
--- a/src/web/src/components/community/forum-view.tsx
+++ b/src/web/src/components/community/forum-view.tsx
@@ -1,7 +1,7 @@
"use client"
import { useState } from "react"
-import { MessagesSquare, ListChevronsUpDown, Plus, Tag } from "lucide-react"
+import { MessagesSquare, ListChevronsUpDown, Plus, Tag, Trash2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { formatRelativeTime } from "./format-time"
import { Badge } from "@/components/ui/badge"
@@ -11,6 +11,7 @@ import { AvatarGroup, AvatarGroupCount } from "@/components/ui/avatar"
import { EmptyState } from "./empty-state"
import { CreateForumPost, type NewForumPost } from "./create-forum-post"
import { PostTagDialog } from "./post-tag-dialog"
+import { ConfirmDialog } from "@/components/ui/confirm-dialog"
import { tid } from "@/lib/community/testids"
import type { ForumPost } from "./_types"
@@ -25,6 +26,7 @@ const MAX_AVATARS = 4
// card (creator + server managers), not a forum-wide manage mode.
export function ForumView({
posts, loading, onOpenPost, onCreatePost, onEditPostTags, canEditPostTags, savingTagsFor,
+ onDeletePost, canDeletePost, deletingPost,
}: {
posts: ForumPost[]
loading?: boolean
@@ -36,10 +38,17 @@ export function ForumView({
canEditPostTags?: (post: ForumPost) => boolean
// The post id whose tag save is in flight, if any.
savingTagsFor?: string | null
+ // Delete handler for a single post. Absent → delete disabled.
+ onDeletePost?: (post: ForumPost) => void
+ // Whether the current user may delete a given post (creator or manager).
+ canDeletePost?: (post: ForumPost) => boolean
+ // The post id whose delete is in flight, if any.
+ deletingPost?: string | null
}) {
const [tag, setTag] = useState("All")
const [composing, setComposing] = useState(false)
const [editingTagsFor, setEditingTagsFor] = useState<ForumPost | null>(null)
+ const [deletingFor, setDeletingFor] = useState<ForumPost | null>(null)
// Deduped union of every post's tags — the forum's tag list is derived, not
// stored. Only rendered when non-empty.
@@ -90,6 +99,7 @@ export function ForumView({
<div className="flex flex-col gap-3">
{filtered.map((p) => {
const canEdit = !!onEditPostTags && (canEditPostTags?.(p) ?? false)
+ const canDelete = !!onDeletePost && (canDeletePost?.(p) ?? false)
const others = p.participants.filter((m) => m.id !== p.authorId)
const shown = others.slice(0, MAX_AVATARS)
const overflow = others.length - shown.length
@@ -129,6 +139,18 @@ export function ForumView({
<Tag className="size-4" />
</button>
)}
+ {canDelete && (
+ <button
+ type="button"
+ data-testid={tid.forumPostDeleteBtn(p.id)}
+ disabled={deletingPost === p.id}
+ onClick={(e) => { e.stopPropagation(); setDeletingFor(p) }}
+ className={`${canEdit ? "" : "ml-auto "}grid size-6 shrink-0 place-items-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-destructive focus-visible:opacity-100 group-hover/card:opacity-100 disabled:cursor-not-allowed disabled:opacity-50`}
+ aria-label="Delete post"
+ >
+ <Trash2 className="size-4" />
+ </button>
+ )}
</div>
<h3 className="text-[15px] font-semibold leading-tight">{p.name}</h3>
<p className="line-clamp-2 text-sm text-muted-foreground">{p.preview}</p>
@@ -158,6 +180,17 @@ export function ForumView({
onSave={(tags) => { onEditPostTags?.(editingTagsFor.id, tags); setEditingTagsFor(null) }}
/>
)}
+
+ {deletingFor && (
+ <ConfirmDialog
+ open
+ onOpenChange={(v) => { if (!v) setDeletingFor(null) }}
+ title="Delete post?"
+ description={`This permanently deletes “${deletingFor.name}” and all of its replies. This can't be undone.`}
+ confirmLabel="Delete post"
+ onConfirm={() => { const post = deletingFor; setDeletingFor(null); onDeletePost?.(post) }}
+ />
+ )}
</>
)
}
diff --git a/src/web/src/hooks/community/mutations/forum.test.ts b/src/web/src/hooks/community/mutations/forum.test.ts
new file mode 100644
index 000000000..927e7976e
--- /dev/null
+++ b/src/web/src/hooks/community/mutations/forum.test.ts
@@ -0,0 +1,119 @@
+/**
+ * Forum-mutation tests. Same shim pattern as channels.test.ts — the
+ * `useMutation` config is captured and driven through React Query's lifecycle
+ * order so we can assert the cache patches without a real query client loop.
+ */
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { QueryClient } from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
+import type { ForumPostsResponse } from "@/hooks/community/use-channel-panels"
+import type { ForumPost } from "@/components/community/_types"
+
+vi.mock("react", () => ({
+ useRef: (initial: unknown) => ({ current: initial }),
+ useCallback: (fn: unknown) => fn,
+ useEffect: () => {},
+ useState: (initial: unknown) => [initial, () => {}],
+}))
+
+const apiFetchMock = vi.fn()
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: (...args: unknown[]) => apiFetchMock(...args),
+}))
+
+type MutConfig<Args> = {
+ mutationFn?: (args: Args) => unknown
+ onSuccess?: (data: unknown, args: Args) => unknown
+ onError?: (err: unknown, args: Args) => unknown
+}
+let capturedConfig: MutConfig<unknown> | null = null
+let capturedQc: QueryClient
+vi.mock("@tanstack/react-query", async () => {
+ const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query")
+ return {
+ ...actual,
+ useQueryClient: () => capturedQc,
+ useMutation: (config: MutConfig<unknown>) => {
+ capturedConfig = config
+ return {}
+ },
+ }
+})
+
+async function runMutation<Args>(args: Args) {
+ const cfg = capturedConfig as MutConfig<Args>
+ const data = cfg.mutationFn ? await cfg.mutationFn(args) : undefined
+ cfg.onSuccess?.(data, args)
+ return data
+}
+
+async function runMutationExpectError<Args>(args: Args) {
+ const cfg = capturedConfig as MutConfig<Args>
+ try {
+ const data = cfg.mutationFn ? await cfg.mutationFn(args) : undefined
+ cfg.onSuccess?.(data, args)
+ throw new Error("expected mutationFn to reject")
+ } catch (err) {
+ cfg.onError?.(err, args)
+ return err
+ }
+}
+
+async function load() {
+ vi.resetModules()
+ return await import("./forum")
+}
+
+beforeEach(() => {
+ apiFetchMock.mockReset()
+ capturedConfig = null
+ capturedQc = new QueryClient()
+})
+
+function makePost(id: string): ForumPost {
+ return {
+ id,
+ name: `post ${id}`,
+ messageCount: 1,
+ lastMessageAt: "2026-07-03T00:00:00.000Z",
+ parent: { authorName: "Alice", text: "root" },
+ authorId: "usr_alice",
+ authorAvatar: "A",
+ tags: [],
+ preview: "preview",
+ participants: [{ id: "usr_alice", name: "Alice", avatar: "A" }],
+ }
+}
+
+describe("useDeleteForumPost", () => {
+ it("DELETEs the post channel and removes it from the forum's cached list on success", async () => {
+ const { useDeleteForumPost } = await load()
+ useDeleteForumPost()
+
+ capturedQc.setQueryData<ForumPostsResponse>(communityKeys.forumPosts("forum_1"), {
+ posts: [makePost("p1"), makePost("p2"), makePost("p3")],
+ })
+ apiFetchMock.mockResolvedValueOnce(undefined)
+
+ await runMutation({ forumChannelId: "forum_1", postId: "p2" })
+
+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/p2", { method: "DELETE" })
+ const cache = capturedQc.getQueryData<ForumPostsResponse>(communityKeys.forumPosts("forum_1"))
+ expect(cache?.posts.map((p) => p.id)).toEqual(["p1", "p3"])
+ })
+
+ it("leaves the cache untouched when the DELETE fails", async () => {
+ const { useDeleteForumPost } = await load()
+ useDeleteForumPost()
+
+ capturedQc.setQueryData<ForumPostsResponse>(communityKeys.forumPosts("forum_1"), {
+ posts: [makePost("p1"), makePost("p2")],
+ })
+ apiFetchMock.mockRejectedValueOnce(new Error("500"))
+
+ await runMutationExpectError({ forumChannelId: "forum_1", postId: "p2" })
+
+ const cache = capturedQc.getQueryData<ForumPostsResponse>(communityKeys.forumPosts("forum_1"))
+ expect(cache?.posts.map((p) => p.id)).toEqual(["p1", "p2"])
+ })
+})
diff --git a/src/web/src/hooks/community/mutations/forum.ts b/src/web/src/hooks/community/mutations/forum.ts
index cd94d7e8a..47c9f29eb 100644
--- a/src/web/src/hooks/community/mutations/forum.ts
+++ b/src/web/src/hooks/community/mutations/forum.ts
@@ -79,3 +79,35 @@ export function useUpdatePostTags() {
},
})
}
+
+export type DeleteForumPostArgs = {
+ // The parent forum channel — the cache key the post list lives under.
+ forumChannelId: string
+ // The post channel being deleted.
+ postId: string
+}
+
+/**
+ * Delete a single forum post. A post IS a `forum_post` child channel, so this
+ * DELETEs the channel (creator or manager gated server-side — see the DELETE
+ * route's forum_post carve-out). On success (204) the post is filtered out of
+ * the forum's cached list so the card disappears without a refetch; the
+ * server-side WS `channel.delete` also invalidates for other clients.
+ */
+export function useDeleteForumPost() {
+ const queryClient = useQueryClient()
+ return useMutation<void, Error, DeleteForumPostArgs>({
+ mutationFn: async ({ postId }) => {
+ await apiFetch(`/api/community/channels/${postId}`, { method: "DELETE" })
+ },
+ onSuccess: (_data, args) => {
+ queryClient.setQueryData<ForumPostsResponse | undefined>(
+ communityKeys.forumPosts(args.forumChannelId),
+ (prev) =>
+ prev
+ ? { ...prev, posts: prev.posts.filter((p) => p.id !== args.postId) }
+ : prev,
+ )
+ },
+ })
+}
diff --git a/src/web/src/hooks/community/use-community-ws.test.ts b/src/web/src/hooks/community/use-community-ws.test.ts
index 2f5013bb3..2ca239408 100644
--- a/src/web/src/hooks/community/use-community-ws.test.ts
+++ b/src/web/src/hooks/community/use-community-ws.test.ts
@@ -1095,7 +1095,11 @@ describe("useCommunityWs — typing.start honours focus (no DM leak)", () => {
}
capturedOnMessage!(event)
- expect(useCommunityStore.getState().typingUsers).toEqual([])
+ // Focus is on ch_1, so the DM-only typing.start is dropped entirely — no
+ // scope gains a typer.
+ const state = useCommunityStore.getState()
+ expect(state.typingByScope.get("dm:dm_other")).toBeUndefined()
+ expect(state.typingByScope.get("ch:ch_1")).toBeUndefined()
})
it("does surface a channel typing.start when the viewer is focused on that channel", async () => {
@@ -1114,7 +1118,113 @@ describe("useCommunityWs — typing.start honours focus (no DM leak)", () => {
}
capturedOnMessage!(event)
- expect(useCommunityStore.getState().typingUsers).toEqual(["u_other"])
+ expect([...(useCommunityStore.getState().typingByScope.get("ch:ch_1") ?? [])]).toEqual([
+ "u_other",
+ ])
+ })
+})
+
+// ── Typing scope isolation (per-conversation, no cross-leak) ────────────────
+describe("useCommunityWs — typing state is scoped per conversation", () => {
+ it("a DM typer lands only in the DM scope, never in a channel scope", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ // Viewer is focused on the DM when the peer starts typing.
+ useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })
+ refCounter = 0
+ stateCounter = 0
+ callbackCounter = 0
+ await mountHook({ viewerUserId: "u_me" })
+
+ capturedOnMessage!({
+ type: "community:dm.typing",
+ dmConversationId: "dm_1",
+ userId: "u_peer",
+ })
+
+ const state = useCommunityStore.getState()
+ // The typer is confined to dm:dm_1 — a channel view reading ch:* sees nothing.
+ expect([...(state.typingByScope.get("dm:dm_1") ?? [])]).toEqual(["u_peer"])
+ expect(state.typingByScope.get("ch:dm_1")).toBeUndefined()
+ // The 8s timer is keyed by (scope, user), not user alone.
+ expect(state.typingTimers.has("dm:dm_1|u_peer")).toBe(true)
+ })
+
+ it("bot DM reply (message.create carrying dmConversationId) clears the DM pill, not ch:undefined", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ dmConversationId: "dm_bot" })
+ refCounter = 0
+ stateCounter = 0
+ callbackCounter = 0
+ await mountHook({ viewerUserId: "u_me" })
+
+ // Bot is "typing" in the DM.
+ capturedOnMessage!({
+ type: "community:dm.typing",
+ dmConversationId: "dm_bot",
+ userId: "u_bot",
+ })
+ expect([...(useCommunityStore.getState().typingByScope.get("dm:dm_bot") ?? [])]).toEqual([
+ "u_bot",
+ ])
+
+ // Its reply arrives as message.create WITH dmConversationId (no channelId) —
+ // the dual-axis case. The scope key must resolve to dm:dm_bot, clearing the
+ // pill. A regression (hardcoded ch:) would target ch:undefined and leave it.
+ capturedOnMessage!({
+ type: "community:message.create",
+ dmConversationId: "dm_bot",
+ message: {
+ id: "m_bot_reply",
+ authorId: "u_bot",
+ authorName: "bot",
+ content: "done",
+ createdAt: "2026-07-03T00:00:00.000Z",
+ },
+ } as CommunityMessageCreate)
+
+ const state = useCommunityStore.getState()
+ expect(state.typingByScope.get("dm:dm_bot")).toBeUndefined()
+ expect(state.typingByScope.get("ch:undefined")).toBeUndefined()
+ expect(state.typingTimers.has("dm:dm_bot|u_bot")).toBe(false)
+ })
+})
+
+// ── channel.delete invalidates the parent forum list (post deletion) ────────
+describe("useCommunityWs — channel.delete refreshes the parent forum feed", () => {
+ it("invalidates the parent's forumPosts + threads lists when parentChannelId is present", async () => {
+ await mountHook()
+ const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+
+ const event: CommunityChannelDelete = {
+ type: "community:channel.delete",
+ serverId: "srv_1",
+ channelId: "post_1",
+ parentChannelId: "forum_1",
+ }
+ capturedOnMessage!(event)
+
+ const invalidatedKeys = invalidateSpy.mock.calls.map((c) => JSON.stringify(c[0]?.queryKey))
+ expect(invalidatedKeys).toContain(JSON.stringify(communityKeys.forumPosts("forum_1")))
+ expect(invalidatedKeys).toContain(JSON.stringify(communityKeys.threads("forum_1")))
+ })
+
+ it("does not throw and still evicts own caches when parentChannelId is absent (legacy event)", async () => {
+ await mountHook()
+ // Seed the deleted channel's own caches so we can assert eviction.
+ capturedQueryClient.setQueryData(communityKeys.forumPosts("post_1"), { posts: [] })
+ const removeSpy = vi.spyOn(capturedQueryClient, "removeQueries")
+
+ const event: CommunityChannelDelete = {
+ type: "community:channel.delete",
+ serverId: "srv_1",
+ channelId: "post_1",
+ }
+ expect(() => capturedOnMessage!(event)).not.toThrow()
+
+ const removedKeys = removeSpy.mock.calls.map((c) => JSON.stringify(c[0]?.queryKey))
+ expect(removedKeys).toContain(JSON.stringify(communityKeys.forumPosts("post_1")))
})
})
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index d94110184..ecfdecef7 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -68,8 +68,8 @@ import { patchChannelUnread } from "@/hooks/community/server-detail-cache"
* State this hook owns *outside* the query cache:
* - `useCommunityWsStore.onlineUserIds` — presence set, WS-only.
* - `useCommunityWsStore.seenMessageIds` — dedup for `message.create`.
- * - `useCommunityStore.typingUsers` + `typingTimers` — typing indicator with
- * auto-expire timers keyed by userId.
+ * - `useCommunityStore.typingByScope` + `typingTimers` — typing indicator,
+ * keyed by conversation scope with per-(scope, user) auto-expire timers.
* - `useCommunityStore.lastTypingSent` — outbound typing.start rate limit.
*
* The subscription (which channel/DM is focused) is read from
@@ -416,7 +416,11 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
// whichever wins the dedup fires the clear, the loser is a no-op.
// Clearing before dedup would also clear on WS-reconnect replays
// of stale messages, briefly wiping a still-active heartbeat pill.
- clearTypingIndicator(event.message.authorId)
+ // message.create is dual-axis: a DM bot reply carries
+ // `dmConversationId` (not `channelId`), so derive the scope from the
+ // event itself — hardcoding `ch:` would target `ch:undefined` and
+ // leave the DM pill hanging until the 8s timer.
+ clearTypingIndicator(typingScopeKey(event), event.message.authorId)
// 1) Patch the focused channel/dm page cache if the event matches.
if (event.channelId && event.channelId === sub.channelId) {
@@ -511,7 +515,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
// A DM-only typing.start (no channelId) must NOT fire while the
// viewer is focused on a channel — `matchesFocus` handles both axes.
if (!matchesFocus(event)) return
- applyTypingIndicator(userId)
+ applyTypingIndicator(typingScopeKey(event), userId)
cbs.onTyping?.(event)
return
}
@@ -524,7 +528,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
const viewerId = viewerUserIdRef.current
if (viewerId && userId === viewerId) return
if (!matchesFocus(event)) return
- clearTypingIndicator(userId)
+ clearTypingIndicator(typingScopeKey(event), userId)
return
}
@@ -700,6 +704,17 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
queryClient.removeQueries({
queryKey: communityKeys.forumPosts(event.channelId),
})
+ // When a child (forum_post / thread) is deleted, refresh the
+ // PARENT's list so the deleted card disappears from the feed on
+ // every client. Absent on older events / top-level channels.
+ if (event.parentChannelId) {
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.forumPosts(event.parentChannelId),
+ })
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.threads(event.parentChannelId),
+ })
+ }
}
if ("serverId" in event) {
void queryClient.invalidateQueries({ queryKey: communityKeys.server(event.serverId) })
@@ -816,7 +831,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
// Same rationale as `community:message.create` above — either the
// message.create or dm.new_message broadcast will pass the dedup
// first and clear the pill; the other is a no-op.
- clearTypingIndicator(event.message.authorId)
+ clearTypingIndicator(typingScopeKey(event), event.message.authorId)
// Focus-scope patch (mirrors community message.create).
if (event.dmConversationId === sub.dmConversationId) {
@@ -837,7 +852,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
const viewerId = viewerUserIdRef.current
if (viewerId && event.userId === viewerId) return
if (event.dmConversationId !== sub.dmConversationId) return
- applyTypingIndicator(event.userId)
+ applyTypingIndicator(typingScopeKey(event), event.userId)
cbs.onDm?.(event)
cbs.onTyping?.(event)
return
@@ -1090,51 +1105,83 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
// ── Typing indicator helpers ─────────────────────────────────────────────────
/**
- * Append userId to `typingUsers` and start (or extend) an auto-expire timer.
- * The timer removes the user from the list after `TYPING_INDICATOR_TIMEOUT_MS`
- * if no follow-up typing event arrives.
+ * The conversation scope key an event belongs to, keyed by the axis it actually
+ * carries. `dmConversationId` wins when present (a DM message.create carries it,
+ * not `channelId`) — mirrors `matchesFocus`'s dm-first precedence. The `dm:` /
+ * `ch:` prefix keeps the two id spaces from colliding. Threads collapse to
+ * `ch:<channelId>` on the client (no sender emits `threadId`).
*/
-function applyTypingIndicator(userId: string) {
+export function typingScopeKey(e: { dmConversationId?: string; channelId?: string }): string {
+ return e.dmConversationId ? `dm:${e.dmConversationId}` : `ch:${e.channelId}`
+}
+
+// Timer map key: one auto-expire timer per (scope, user) pair.
+const timerKey = (scopeKey: string, userId: string) => `${scopeKey}|${userId}`
+
+/**
+ * Add userId to a conversation scope's typing set and start (or extend) an
+ * auto-expire timer. The timer removes the user from THAT scope after
+ * `TYPING_INDICATOR_TIMEOUT_MS` if no follow-up typing event arrives.
+ * No-ops the set write when the user is already typing in the scope (rule 2 —
+ * typing.start re-fires every ~3s).
+ */
+function applyTypingIndicator(scopeKey: string, userId: string) {
useCommunityStore.setState((state) => {
- const timers = state.typingTimers
- const existing = timers.get(userId)
+ const tKey = timerKey(scopeKey, userId)
+ const existing = state.typingTimers.get(tKey)
if (existing) clearTimeout(existing)
const timer = setTimeout(() => {
- useCommunityStore.setState((s) => {
- const nextTimers = new Map(s.typingTimers)
- nextTimers.delete(userId)
- return {
- typingUsers: s.typingUsers.filter((id) => id !== userId),
- typingTimers: nextTimers,
- }
- })
+ useCommunityStore.setState((s) => removeTypingUser(s, scopeKey, userId))
}, TYPING_INDICATOR_TIMEOUT_MS)
- const nextTimers = new Map(timers)
- nextTimers.set(userId, timer)
- const nextUsers = state.typingUsers.includes(userId)
- ? state.typingUsers
- : [...state.typingUsers, userId]
- return { typingUsers: nextUsers, typingTimers: nextTimers }
+ const nextTimers = new Map(state.typingTimers)
+ nextTimers.set(tKey, timer)
+
+ const current = state.typingByScope.get(scopeKey)
+ if (current?.has(userId)) {
+ // Already typing here — only the timer refreshed; leave the set alone.
+ return { typingTimers: nextTimers }
+ }
+ const nextByScope = new Map(state.typingByScope)
+ nextByScope.set(scopeKey, new Set(current ?? []).add(userId))
+ return { typingByScope: nextByScope, typingTimers: nextTimers }
})
}
/**
- * Immediately remove userId from `typingUsers` and cancel its pending timer.
- * Called when the user sends a message — sending is an implicit typing.stop,
- * and waiting for the 8s timeout leaves a ghost indicator hanging under the
- * message that just arrived.
+ * Immediately remove userId from a scope's typing set and cancel its pending
+ * timer. Called when the user sends a message — sending is an implicit
+ * typing.stop, and waiting for the 8s timeout leaves a ghost indicator hanging
+ * under the message that just arrived.
*/
-function clearTypingIndicator(userId: string) {
+function clearTypingIndicator(scopeKey: string, userId: string) {
useCommunityStore.setState((state) => {
- const existing = state.typingTimers.get(userId)
- if (!existing && !state.typingUsers.includes(userId)) return {}
+ const tKey = timerKey(scopeKey, userId)
+ const existing = state.typingTimers.get(tKey)
+ if (!existing && !state.typingByScope.get(scopeKey)?.has(userId)) return {}
if (existing) clearTimeout(existing)
- const nextTimers = new Map(state.typingTimers)
- nextTimers.delete(userId)
- return {
- typingUsers: state.typingUsers.filter((id) => id !== userId),
- typingTimers: nextTimers,
- }
+ return removeTypingUser(state, scopeKey, userId)
})
}
+/**
+ * Pure state patch: drop userId from `scopeKey`'s set (deleting the scope key
+ * when it empties, to avoid unbounded Map growth) and its `(scope, user)`
+ * timer. Shared by the auto-expire timer and the explicit clear.
+ */
+function removeTypingUser(
+ state: { typingByScope: Map<string, Set<string>>; typingTimers: Map<string, ReturnType<typeof setTimeout>> },
+ scopeKey: string,
+ userId: string,
+): Partial<{ typingByScope: Map<string, Set<string>>; typingTimers: Map<string, ReturnType<typeof setTimeout>> }> {
+ const nextTimers = new Map(state.typingTimers)
+ nextTimers.delete(timerKey(scopeKey, userId))
+ const current = state.typingByScope.get(scopeKey)
+ if (!current?.has(userId)) return { typingTimers: nextTimers }
+ const nextSet = new Set(current)
+ nextSet.delete(userId)
+ const nextByScope = new Map(state.typingByScope)
+ if (nextSet.size === 0) nextByScope.delete(scopeKey)
+ else nextByScope.set(scopeKey, nextSet)
+ return { typingByScope: nextByScope, typingTimers: nextTimers }
+}
+
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 96fa1078e..68d77869b 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -29,10 +29,12 @@ export const tid = {
threadIndicator: (msgId: string) => `community-thread-indicator-${msgId}`,
railUnreadBadge: (serverId: string) => `community-rail-unread-badge-${serverId}`,
// Forum post feed (ForumView). `forumPostCard` is the whole clickable card;
- // `forumPostTagBtn` is the hover-revealed tag-edit icon; `forumPostAvatars`
- // wraps the participant AvatarGroup; `forumTagChip` is a filter-bar tag chip.
+ // `forumPostTagBtn` is the hover-revealed tag-edit icon; `forumPostDeleteBtn`
+ // is the hover-revealed delete icon; `forumPostAvatars` wraps the participant
+ // AvatarGroup; `forumTagChip` is a filter-bar tag chip.
forumPostCard: (id: string) => `community-forum-post-${id}`,
forumPostTagBtn: (id: string) => `community-forum-post-tag-btn-${id}`,
+ forumPostDeleteBtn: (id: string) => `community-forum-post-delete-btn-${id}`,
forumPostAvatars: (id: string) => `community-forum-post-avatars-${id}`,
forumTagChip: (tag: string) => `community-forum-tag-chip-${tag}`,
} as const
diff --git a/src/web/src/stores/community/index.test.ts b/src/web/src/stores/community/index.test.ts
index 1d00bb01e..6d5eebed9 100644
--- a/src/web/src/stores/community/index.test.ts
+++ b/src/web/src/stores/community/index.test.ts
@@ -29,7 +29,8 @@ describe("useCommunityStore", () => {
expect(s.currentServerId).toBeNull()
expect(s.currentChannelId).toBeNull()
expect(s.currentChannelMeta).toBeNull()
- expect(s.typingUsers).toEqual([])
+ expect(s.typingByScope).toBeInstanceOf(Map)
+ expect(s.typingByScope.size).toBe(0)
expect(s.typingTimers).toBeInstanceOf(Map)
expect(s.typingTimers.size).toBe(0)
expect(s.lastTypingSent.size).toBe(0)
@@ -153,14 +154,16 @@ describe("useCommunityStore", () => {
// populate typingTimers before the migration is finished.
useCommunityStore.setState((prev) => {
const typingTimers = new Map(prev.typingTimers)
- typingTimers.set("user1", timerId)
+ typingTimers.set("ch:c1|user1", timerId)
+ const typingByScope = new Map(prev.typingByScope)
+ typingByScope.set("ch:c1", new Set(["user1"]))
const lastTypingSent = new Map(prev.lastTypingSent)
lastTypingSent.set("c1", Date.now())
const reactionTimers = new Map(prev.reactionTimers)
const rTimer = setTimeout(() => {}, 1_000)
reactionTimers.set("m1:emoji", { timer: rTimer, originalMe: false })
return {
- typingUsers: ["user1"],
+ typingByScope,
typingTimers,
lastTypingSent,
reactionTimers,
@@ -178,7 +181,7 @@ describe("useCommunityStore", () => {
expect(after.currentServerId).toBeNull()
expect(after.currentChannelId).toBeNull()
expect(after.currentChannelMeta).toBeNull()
- expect(after.typingUsers).toEqual([])
+ expect(after.typingByScope.size).toBe(0)
expect(after.typingTimers.size).toBe(0)
expect(after.lastTypingSent.size).toBe(0)
expect(after.reactionTimers.size).toBe(0)
@@ -190,3 +193,27 @@ describe("useCommunityStore", () => {
}
})
})
+
+describe("typingByScope isolation", () => {
+ // The `useTypingUsersForScope` hook is a thin `useShallow` wrapper over these
+ // reads (exercised through React in `use-community-ws.test.ts`); the node
+ // test env has no DOM, so here we assert the underlying scoped-Map shape that
+ // the selector reads — one scope's typers never bleed into another.
+ const seed = (entries: Record<string, string[]>) => {
+ useCommunityStore.setState({
+ typingByScope: new Map(Object.entries(entries).map(([k, v]) => [k, new Set(v)])),
+ })
+ }
+ const read = (scopeKey: string) => {
+ const set = useCommunityStore.getState().typingByScope.get(scopeKey)
+ return set ? Array.from(set) : []
+ }
+
+ it("keeps each scope's typers separate; an unrelated scope reads empty", () => {
+ seed({ "dm:d1": ["u1"], "ch:c1": ["u2", "u3"] })
+ expect(read("dm:d1")).toEqual(["u1"])
+ expect(read("ch:c1")).toEqual(["u2", "u3"])
+ // A scope with no typers reads as empty — no leak from the populated scopes.
+ expect(read("ch:c2")).toEqual([])
+ })
+})
diff --git a/src/web/src/stores/community/index.ts b/src/web/src/stores/community/index.ts
index 36cee41ac..a95217834 100644
--- a/src/web/src/stores/community/index.ts
+++ b/src/web/src/stores/community/index.ts
@@ -1,6 +1,7 @@
"use client"
import { create } from "zustand"
+import { useShallow } from "zustand/react/shallow"
import type React from "react"
/**
@@ -81,8 +82,11 @@ export type CommunityStoreState = {
currentChannelId: string | null
currentChannelMeta: CurrentChannelMeta | null
- // Typing indicators (viewer-facing set + timers to auto-expire)
- typingUsers: string[]
+ // Typing indicators, keyed by conversation scope so a DM typer never leaks
+ // into a channel view (and vice versa). `scopeKey` is `dm:<id>` / `ch:<id>`
+ // (see `use-community-ws.ts`). Each scope maps to the set of userIds typing
+ // there right now; `typingTimers` auto-expires each `(scope, user)` pair.
+ typingByScope: Map<string, Set<string>>
typingTimers: Map<string, Timer>
// Rate-limit for typing.start emissions the viewer sends outbound; keyed
// by channelId/dmId so switching contexts doesn't cross-throttle.
@@ -120,7 +124,7 @@ const initialState = (): Pick<
| "currentServerId"
| "currentChannelId"
| "currentChannelMeta"
- | "typingUsers"
+ | "typingByScope"
| "typingTimers"
| "lastTypingSent"
| "reactionTimers"
@@ -131,7 +135,7 @@ const initialState = (): Pick<
currentServerId: null,
currentChannelId: null,
currentChannelMeta: null,
- typingUsers: [],
+ typingByScope: new Map(),
typingTimers: new Map(),
lastTypingSent: new Map(),
reactionTimers: new Map(),
@@ -227,3 +231,21 @@ export const useUiHandlers = () => stableUiHandlers
export const usePendingMachineTokenId = () =>
useCommunityStore((s) => s.pendingMachineTokenId)
+
+// Module-scoped stable empty array — avoids allocating a fresh `[]` on every
+// selector run for the common no-typing case.
+const EMPTY_TYPING: string[] = []
+
+/**
+ * The userIds currently typing in a given conversation scope (`dm:<id>` /
+ * `ch:<id>`), or an empty array. `useShallow` compares the returned array
+ * element-wise, so a page only re-renders when THIS scope's membership
+ * changes — typing activity in other conversations doesn't churn it.
+ */
+export const useTypingUsersForScope = (scopeKey: string) =>
+ useCommunityStore(
+ useShallow((s) => {
+ const set = s.typingByScope.get(scopeKey)
+ return set ? Array.from(set) : EMPTY_TYPING
+ }),
+ )