Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): optimistic channel/category create, delete rollback, delete/post redirects (#368)

Generfee91eb97f84
diff --git a/src/shared/src/constants/community.ts b/src/shared/src/constants/community.ts
index f2a7f9eb1..c7d60a38c 100644
--- a/src/shared/src/constants/community.ts
+++ b/src/shared/src/constants/community.ts
@@ -68,6 +68,12 @@ export const MAX_INVITE_MAX_USES = 1000
export const MAX_INVITE_EXPIRY_DAYS = 30
export const MAX_ACTIVE_INVITES_PER_SERVER = 50
+// Synthetic id for the uncategorized-channel bucket the server-detail response
+// projects channels with no category into. It is NOT a real category row —
+// clients must translate it back to `categoryId: null` before any create/move
+// API call, or the server 404s ("category not found").
+export const UNCATEGORIZED_CATEGORY_ID = "__uncategorized__"
+
// Previews
export const MESSAGE_PREVIEW_LENGTH = 120
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 8e78523a4..ff85b67b4 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -148,6 +148,7 @@ export {
MAX_INVITE_MAX_USES,
MAX_INVITE_EXPIRY_DAYS,
MAX_ACTIVE_INVITES_PER_SERVER,
+ UNCATEGORIZED_CATEGORY_ID,
MESSAGE_PREVIEW_LENGTH,
DEFAULT_INBOX_PAGE_SIZE,
MAX_INBOX_PAGE_SIZE,
diff --git a/src/web/src/app/api/community/servers/[id]/route.ts b/src/web/src/app/api/community/servers/[id]/route.ts
index 91453ea21..9bec71473 100644
--- a/src/web/src/app/api/community/servers/[id]/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/route.ts
@@ -7,6 +7,7 @@ import {
isServerOwner,
MAX_SERVER_NAME_LENGTH,
MAX_SERVER_DESCRIPTION_LENGTH,
+ UNCATEGORIZED_CATEGORY_ID,
WS_EVENTS,
slugify,
} from "@alook/shared"
@@ -57,7 +58,7 @@ export const GET = withAuth(async (_req, ctx) => {
const uncategorized = channels.filter((ch) => !ch.categoryId)
if (uncategorized.length > 0) {
categoriesWithChannels.push({
- id: "__uncategorized__",
+ id: UNCATEGORIZED_CATEGORY_ID,
serverId: server.id,
// Empty name is load-bearing: the sidebar detects the uncategorized
// bucket by `name === ""` (renders its channels as the bare top list, and
diff --git a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx
index b083c873a..6a43971bb 100644
--- a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx
+++ b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx
@@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useState } from "react"
import { useParams, useRouter, useSearchParams } from "next/navigation"
import { toast } from "sonner"
import { apiFetch, toastApiError } from "@/lib/api/client"
+import { ApiError } from "@/lib/errors"
import { useBreakpoint } from "@/hooks/use-mobile"
import { ChannelHeader, ChannelHeaderSkeleton, type ChannelNotifLevel } from "@/components/community/channel-header"
import { MessageList } from "@/components/community/message-list"
@@ -433,6 +434,15 @@ function ChannelView() {
)
.catch((e) => {
useCommunityStore.getState().setCurrentChannelMeta(null)
+ // A channel not in the server tree is either a real thread/forum-post
+ // (meta fetch succeeds above) or one that was just deleted out from
+ // under us (meta 404s here). On the delete case, don't strand the user
+ // on a dead URL with a misleading "thread" error — bounce to the server
+ // root, which forwards to the first remaining channel.
+ if (e instanceof ApiError && e.status === 404) {
+ router.replace(`/community/channels/${params.serverId}`)
+ return
+ }
toastApiError(e, "Failed to load thread")
})
} else {
@@ -441,7 +451,7 @@ function ChannelView() {
return () => {
communityWsUnsubscribe()
}
- }, [channelId, isChildChannel])
+ }, [channelId, isChildChannel, params.serverId, router])
// ── Local UI state ──────────────────────────────────────────────────────
const [rightPanel, setRightPanel] = useState<RightPanel>(null)
@@ -667,10 +677,14 @@ function ChannelView() {
communityWsSendTyping({ channelId })
}
- const createForumPost = (post: { name: string; content: string; tags: string[] }) => {
- createForumPostMut.mutate({ channelId, ...post }, {
- onError: (e) => toastApiError(e, "Failed to create post"),
- })
+ const createForumPost = async (post: { name: string; content: string; tags: string[] }) => {
+ try {
+ const data = await createForumPostMut.mutateAsync({ channelId, ...post })
+ // A post is its own child channel — open it, same as clicking a post row.
+ enterThread(data.post.id)
+ } catch (e) {
+ toastApiError(e, "Failed to create post")
+ }
}
const myRole = members.find((m) => m.userId === currentUser.id)?.role
diff --git a/src/web/src/app/community/channels/layout.tsx b/src/web/src/app/community/channels/layout.tsx
index e617ecd0b..160e4915e 100644
--- a/src/web/src/app/community/channels/layout.tsx
+++ b/src/web/src/app/community/channels/layout.tsx
@@ -283,11 +283,14 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
[channelNotif]
)
- const onCreateChannelInSidebar = useCallback((categoryId: string, name: string, type: ChannelType) => {
- createChannelMut.mutate(
- { serverId, categoryId, name, type },
- { onError: (e) => toastApiError(e, "Failed to create channel") },
- )
+ const onCreateChannelInSidebar = useCallback(async (categoryId: string, name: string, type: ChannelType) => {
+ try {
+ const res = await createChannelMut.mutateAsync({ serverId, categoryId, name, type })
+ return res.channel.id
+ } catch (e) {
+ toastApiError(e, "Failed to create channel")
+ return null
+ }
}, [createChannelMut, serverId])
const onCreateCategoryInSidebar = useCallback((name: string, opts?: { private?: boolean }) => {
createCategoryMut.mutate(
diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.ts
index 3202cec8a..4412b724a 100644
--- a/src/web/src/components/community/_types.ts
+++ b/src/web/src/components/community/_types.ts
@@ -62,6 +62,8 @@ export type Channel = {
type?: ChannelType
tags?: string[]
creatorId?: string | null
+ // Optimistic placeholder row — non-interactive until the create resolves.
+ pending?: boolean
}
export type Category = {
@@ -70,6 +72,8 @@ export type Category = {
channels: Channel[]
private?: number | boolean
creatorId?: string | null
+ // Optimistic placeholder category — reconciled when the create resolves.
+ pending?: boolean
}
// ── Messages ───────────────────────────────────────────────────────────────
diff --git a/src/web/src/components/community/channel-sidebar.tsx b/src/web/src/components/community/channel-sidebar.tsx
index 58ff98c07..d646bb2b2 100644
--- a/src/web/src/components/community/channel-sidebar.tsx
+++ b/src/web/src/components/community/channel-sidebar.tsx
@@ -10,7 +10,7 @@ import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem }
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"
import { Skeleton } from "@/components/ui/skeleton"
import { SortableCategory } from "./sortable-category"
-import { SortableChannel } from "./sortable-channel"
+import { SortableChannel, PendingChannelRow } from "./sortable-channel"
import { CreateChannelDialog } from "./create-channel-dialog"
import { CreateCategoryDialog } from "./create-category-dialog"
import { CategorySettingsDialog } from "./category-settings-dialog"
@@ -19,7 +19,7 @@ import { InviteDialog } from "./invite-dialog"
import { ChannelAddMembersDialog } from "./channel-add-members-dialog"
import { ServerCrumb } from "./channel-header"
import type { Channel, SettingsSection } from "./_types"
-import type { ChannelType } from "@alook/shared"
+import { UNCATEGORIZED_CATEGORY_ID, type ChannelType } from "@alook/shared"
type Dialog =
@@ -68,7 +68,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({
invitePopoverOpen?: boolean
onInvitePopoverOpenChange?: (open: boolean) => void
}) {
- const { collapsed, catOrder, order, catNames, catPrivate, toggleCat, removeChannel, renameChannel, removeCategory, renameCategory, onDragOver, onDragEnd: treeDragEnd } = tree
+ const { collapsed, catOrder, order, catNames, catPrivate, catPending, toggleCat, removeChannel, renameChannel, renameCategory, onDragOver, onDragEnd: treeDragEnd } = tree
// Category the dragged channel started in — captured at drag start, because
// `onDragOver` mutates `order` mid-drag so by drop time it already reflects
// the destination.
@@ -95,7 +95,8 @@ export const ChannelSidebar = memo(function ChannelSidebar({
next.splice(to, 0, item)
return next
})() : null
- if (reordered) onReorderCategories?.(reordered)
+ // Never send an optimistic (pending) category id to the reorder endpoint.
+ if (reordered) onReorderCategories?.(reordered.filter((cid) => !catPending[cid]))
} else if (!activeStr.startsWith("cat_")) {
// The channel's category AFTER onDragOver settled the optimistic move.
const destCat = catOf(activeStr, order)
@@ -113,11 +114,11 @@ export const ChannelSidebar = memo(function ChannelSidebar({
}
// Persist a same-privacy cross-category move: write the new categoryId
// (translating the synthetic uncategorized bucket to null), then reorder.
- const allChannelIds = catOrder.flatMap((cat) => (order[cat] ?? []).map((c) => c.id))
+ const allChannelIds = catOrder.flatMap((cat) => (order[cat] ?? []).filter((c) => !c.pending).map((c) => c.id))
if (destCat && originCat && destCat !== originCat) {
// The uncategorized bucket (empty name, synthetic id) maps back to a
// real `categoryId: null` for the PATCH.
- const isUncategorized = catNames[destCat] === "" || destCat === "__uncategorized__"
+ const isUncategorized = catNames[destCat] === "" || destCat === UNCATEGORIZED_CATEGORY_ID
onMoveChannel?.(activeStr, isUncategorized ? null : destCat)
}
onReorderChannels?.(allChannelIds)
@@ -160,9 +161,11 @@ export const ChannelSidebar = memo(function ChannelSidebar({
<DndContext id="d-channels" sensors={sensors} collisionDetection={closestCenter} onDragStart={onDragStart} onDragOver={onDragOver} onDragEnd={onDragEnd}>
{/* uncategorized channels (empty-name category) render bare at the top — no header */}
{noneCatId && order[noneCatId]?.length > 0 && (
- <SortableContext items={order[noneCatId].map((c) => c.id)} strategy={verticalListSortingStrategy}>
+ <SortableContext items={order[noneCatId].filter((c) => !c.pending).map((c) => c.id)} strategy={verticalListSortingStrategy}>
<div className="mb-4 space-y-1">
- {order[noneCatId].map((ch) => (
+ {order[noneCatId].map((ch) => ch.pending ? (
+ <PendingChannelRow key={ch.id} ch={ch} />
+ ) : (
<SortableChannel
key={ch.id}
ch={withMute(ch)}
@@ -176,7 +179,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({
</div>
</SortableContext>
)}
- <SortableContext items={catOrder.filter((id) => catNames[id] !== "").map((id) => catId(id))} strategy={verticalListSortingStrategy}>
+ <SortableContext items={catOrder.filter((id) => catNames[id] !== "" && !catPending[id]).map((id) => catId(id))} strategy={verticalListSortingStrategy}>
{catOrder.filter((id) => catNames[id] !== "").map((id) => (
<SortableCategory
key={id}
@@ -184,15 +187,17 @@ export const ChannelSidebar = memo(function ChannelSidebar({
name={catNames[id] ?? id}
open={!collapsed.has(id)}
onToggle={() => toggleCat(id)}
- onAddChannel={canCreateInCategory(id) ? () => requestCreateChannel(id) : undefined}
- onSettings={isAdmin ? () => setDialog({ kind: "category-settings", categoryId: id }) : undefined}
- onDelete={isAdmin ? () => { removeCategory(id); onDeleteCategory?.(id) } : undefined}
+ onAddChannel={!catPending[id] && canCreateInCategory(id) ? () => requestCreateChannel(id) : undefined}
+ onSettings={!catPending[id] && isAdmin ? () => setDialog({ kind: "category-settings", categoryId: id }) : undefined}
+ onDelete={!catPending[id] && isAdmin ? () => onDeleteCategory?.(id) : undefined}
isPrivate={catPrivate[id]}
- canReorder={isAdmin}
+ canReorder={isAdmin && !catPending[id]}
+ pending={catPending[id]}
>
- <SortableContext items={(order[id] ?? []).map((c) => c.id)} strategy={verticalListSortingStrategy}>
+ <SortableContext items={(order[id] ?? []).filter((c) => !c.pending).map((c) => c.id)} strategy={verticalListSortingStrategy}>
<div className="mt-1 min-h-2 space-y-1">
{(order[id] ?? []).map((ch) => {
+ if (ch.pending) return <PendingChannelRow key={ch.id} ch={ch} />
// Manage/edit rights:
// - admins everywhere
// - private category: the channel creator too
diff --git a/src/web/src/components/community/sortable-category.tsx b/src/web/src/components/community/sortable-category.tsx
index aaf8b9835..6a2412862 100644
--- a/src/web/src/components/community/sortable-category.tsx
+++ b/src/web/src/components/community/sortable-category.tsx
@@ -20,7 +20,7 @@ export function hasCategoryMenu(h: { onAddChannel?: () => void; onSettings?: ()
// activation distance distinguishes a click (collapse) from a drag. It is also a drop
// target so channels can be dropped onto it (including its empty space). Right-click
// (or the gear) opens Settings; the "+" creates a channel; a lock shows when private.
-export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChannel, onSettings, onDelete, isPrivate, canReorder = true, children }: {
+export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChannel, onSettings, onDelete, isPrivate, canReorder = true, pending = false, children }: {
id: string
name: string
open: boolean
@@ -30,6 +30,7 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChan
onDelete?: () => void
isPrivate?: boolean
canReorder?: boolean
+ pending?: boolean
children: React.ReactNode
}) {
const [confirmingDelete, setConfirmingDelete] = useState(false)
@@ -74,7 +75,7 @@ export function SortableCategory({ id: catDndId, name, open, onToggle, onAddChan
</>
)
return (
- <div ref={setNodeRef} style={style} className="relative mb-4">
+ <div ref={setNodeRef} style={style} className={`relative mb-4 ${pending ? "opacity-60" : ""}`}>
{showLine && <DropLine side={lineSide} />}
{hasCategoryMenu({ onAddChannel, onSettings, onDelete }) ? (
<ContextMenu>
diff --git a/src/web/src/components/community/sortable-channel.test.ts b/src/web/src/components/community/sortable-channel.test.ts
index 333b874d2..7f4453be3 100644
--- a/src/web/src/components/community/sortable-channel.test.ts
+++ b/src/web/src/components/community/sortable-channel.test.ts
@@ -1,5 +1,8 @@
import { describe, it, expect } from "vitest"
-import { hasChannelMenu } from "./sortable-channel"
+import { createElement } from "react"
+import { renderToStaticMarkup } from "react-dom/server"
+import { hasChannelMenu, PendingChannelRow } from "./sortable-channel"
+import type { Channel } from "./_types"
const noop = () => {}
@@ -14,3 +17,19 @@ describe("hasChannelMenu", () => {
expect(hasChannelMenu({ onDelete: noop })).toBe(true)
})
})
+
+describe("PendingChannelRow", () => {
+ const ch: Channel = { id: "tmp_ch_x", name: "my-new-channel", active: false, unread: false, pending: true }
+ const html = renderToStaticMarkup(createElement(PendingChannelRow, { ch }))
+
+ it("renders the channel name", () => {
+ expect(html).toContain("my-new-channel")
+ })
+ it("shows a spinner instead of an entity icon", () => {
+ expect(html).toContain("animate-spin")
+ })
+ it("is non-interactive — disabled and cursor-default, no context menu", () => {
+ expect(html).toContain("aria-disabled")
+ expect(html).toContain("cursor-default")
+ })
+})
diff --git a/src/web/src/components/community/sortable-channel.tsx b/src/web/src/components/community/sortable-channel.tsx
index dad1a889e..c26543d37 100644
--- a/src/web/src/components/community/sortable-channel.tsx
+++ b/src/web/src/components/community/sortable-channel.tsx
@@ -1,7 +1,7 @@
"use client"
import { useState } from "react"
-import { BellOff, Pencil, Trash2, Users } from "lucide-react"
+import { BellOff, Loader2, Pencil, Trash2, Users } from "lucide-react"
import { EntityIcon } from "./entity-icon"
import { useSortable } from "@dnd-kit/sortable"
import { CSS } from "@dnd-kit/utilities"
@@ -16,6 +16,23 @@ export function hasChannelMenu(h: { onEdit?: () => void; onManageMembers?: () =>
return !!(h.onEdit || h.onManageMembers || h.onDelete)
}
+// Optimistic placeholder for a channel being created. Matches SortableChannel's
+// row geometry so the temp→real swap is a reveal, not a reflow. Non-interactive:
+// no drag, no click, no context menu — a spinner sits where the entity icon goes.
+export function PendingChannelRow({ ch }: { ch: Channel }) {
+ return (
+ <div
+ aria-disabled
+ className="group relative flex h-8 w-full cursor-default items-center gap-2 rounded-md px-2 text-sm text-muted-foreground opacity-60 select-none"
+ >
+ <span className="grid size-5 shrink-0 place-items-center opacity-70">
+ <Loader2 className="size-4 animate-spin" />
+ </span>
+ <span className="truncate font-semibold">{ch.name}</span>
+ </div>
+ )
+}
+
// A single drag-sortable channel row. The whole row is the drag surface (no handle);
// a 5px activation distance keeps a tap = "switch channel" and a drag = reorder.
// Right-click opens an edit/mute/delete menu.
diff --git a/src/web/src/components/community/use-channel-tree.test.ts b/src/web/src/components/community/use-channel-tree.test.ts
index eb92465aa..8b77db962 100644
--- a/src/web/src/components/community/use-channel-tree.test.ts
+++ b/src/web/src/components/community/use-channel-tree.test.ts
@@ -118,4 +118,20 @@ describe("mergeChannelMetadata", () => {
expect(result.changed).toBe(false)
expect(result.next).toBe(order)
})
+
+ // An optimistic pending row that survives an id-set-unchanged metadata merge
+ // (e.g. a sibling WS unread patch) must keep its `pending` flag — the merge
+ // spreads the existing row and only overwrites unread/name.
+ it("preserves the pending flag when only unread changes underneath it", () => {
+ const pendingOrder: ChannelOrder = {
+ cat_A: [{ ...ch("tmp_ch_x"), pending: true }],
+ }
+ const result = mergeChannelMetadata(pendingOrder, [
+ cat("cat_A", [{ ...ch("tmp_ch_x"), unread: true }]),
+ ])
+ expect(result.changed).toBe(true)
+ const row = result.next.cat_A.find((c) => c.id === "tmp_ch_x")
+ expect(row?.pending).toBe(true)
+ expect(row?.unread).toBe(true)
+ })
})
diff --git a/src/web/src/components/community/use-channel-tree.ts b/src/web/src/components/community/use-channel-tree.ts
index 6871656dd..0599f9227 100644
--- a/src/web/src/components/community/use-channel-tree.ts
+++ b/src/web/src/components/community/use-channel-tree.ts
@@ -115,6 +115,11 @@ export function useChannelTree(categories: Category[]) {
const [catPrivate, setCatPrivate] = useState<Record<string, boolean>>(() =>
Object.fromEntries(categories.map((c) => [c.id, !!c.private])),
)
+ // per-category optimistic-pending flag — a category being created (temp id).
+ // Non-interactive until the create resolves.
+ const [catPending, setCatPending] = useState<Record<string, boolean>>(() =>
+ Object.fromEntries(categories.map((c) => [c.id, !!c.pending])),
+ )
// per-category creator ID
const [catCreators, setCatCreators] = useState<Record<string, string | null>>(() =>
Object.fromEntries(categories.map((c) => [c.id, c.creatorId ?? null])),
@@ -134,6 +139,7 @@ export function useChannelTree(categories: Category[]) {
setOrder({})
setCatNames({})
setCatPrivate({})
+ setCatPending({})
setCatCreators({})
return
}
@@ -155,6 +161,7 @@ export function useChannelTree(categories: Category[]) {
setOrder(Object.fromEntries(categories.map((c) => [c.id, c.channels])))
setCatNames(Object.fromEntries(categories.map((c) => [c.id, c.name])))
setCatPrivate(Object.fromEntries(categories.map((c) => [c.id, !!c.private])))
+ setCatPending(Object.fromEntries(categories.map((c) => [c.id, !!c.pending])))
setCatCreators(Object.fromEntries(categories.map((c) => [c.id, c.creatorId ?? null])))
}, [categories])
@@ -180,25 +187,9 @@ export function useChannelTree(categories: Category[]) {
if (!cat) return prev
return { ...prev, [cat]: prev[cat].map((c) => c.id === id ? { ...c, unread: false } : c) }
}), [])
- // Refs for removeCategory — depends on current catNames/catOrder but we don't want
- // its identity to churn every time those change.
- const catNamesRef = useRef(catNames)
- catNamesRef.current = catNames
- const catOrderRef = useRef(catOrder)
- catOrderRef.current = catOrder
- const removeCategory = useCallback((id: string) => {
- const names = catNamesRef.current
- const order = catOrderRef.current
- const noneCatId = Object.keys(names).find((k) => names[k] === "") ?? order[0]
- setCatOrder((prev) => prev.filter((cid) => cid !== id))
- setOrder((prev) => {
- const { [id]: channels, ...rest } = prev
- if (channels?.length && noneCatId) rest[noneCatId] = [...(rest[noneCatId] ?? []), ...channels]
- return rest
- })
- setCatNames((prev) => Object.fromEntries(Object.entries(prev).filter(([k]) => k !== id)))
- setCatPrivate((prev) => Object.fromEntries(Object.entries(prev).filter(([k]) => k !== id)))
- }, [])
+ // Category delete is driven by the query cache (useDeleteCategory's optimistic
+ // onMutate/onError), so the tree resettles from `categories` — no local
+ // removal helper (a local one had no rollback path; see the mutation hook).
const renameCategory = useCallback((id: string, name: string) =>
setCatNames((prev) => (prev[id] === name ? prev : { ...prev, [id]: name })), [])
@@ -234,12 +225,12 @@ export function useChannelTree(categories: Category[]) {
}, [])
return useMemo(() => ({
- collapsed, catOrder, order, catNames, catPrivate, catCreators,
- toggleCat, removeChannel, renameChannel, markRead, removeCategory,
+ collapsed, catOrder, order, catNames, catPrivate, catPending, catCreators,
+ toggleCat, removeChannel, renameChannel, markRead,
renameCategory, onDragOver, onDragEnd,
}), [
- collapsed, catOrder, order, catNames, catPrivate, catCreators,
- toggleCat, removeChannel, renameChannel, markRead, removeCategory,
+ collapsed, catOrder, order, catNames, catPrivate, catPending, catCreators,
+ toggleCat, removeChannel, renameChannel, markRead,
renameCategory, onDragOver, onDragEnd,
])
}
diff --git a/src/web/src/hooks/community/mutations/channels.test.ts b/src/web/src/hooks/community/mutations/channels.test.ts
index 6657fb438..3b278256d 100644
--- a/src/web/src/hooks/community/mutations/channels.test.ts
+++ b/src/web/src/hooks/community/mutations/channels.test.ts
@@ -4,6 +4,7 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
import { QueryClient } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
+import { UNCATEGORIZED_CATEGORY_ID } from "@alook/shared"
vi.mock("react", () => ({
useRef: (initial: unknown) => ({ current: initial }),
@@ -22,6 +23,7 @@ type MutConfig<Args, Ctx> = {
onMutate?: (args: Args) => Promise<Ctx> | Ctx
onSuccess?: (data: unknown, args: Args, ctx: Ctx) => unknown
onError?: (err: unknown, args: Args, ctx: Ctx) => unknown
+ onSettled?: (data: unknown, err: unknown, args: Args, ctx: Ctx) => unknown
}
let capturedConfig: MutConfig<unknown, unknown> | null = null
let capturedQc: QueryClient
@@ -37,15 +39,19 @@ vi.mock("@tanstack/react-query", async () => {
}
})
+// Mirrors React Query's lifecycle order: onMutate → mutationFn →
+// (onSuccess | onError) → onSettled (always, on both paths).
async function runMutation<Args>(args: Args) {
const cfg = capturedConfig as MutConfig<Args, unknown>
const ctx = cfg.onMutate ? await cfg.onMutate(args) : undefined
try {
const data = cfg.mutationFn ? await cfg.mutationFn(args) : undefined
cfg.onSuccess?.(data, args, ctx)
+ cfg.onSettled?.(data, undefined, args, ctx)
return { data, ctx }
} catch (err) {
cfg.onError?.(err, args, ctx)
+ cfg.onSettled?.(undefined, err, args, ctx)
throw err
}
}
@@ -155,3 +161,243 @@ describe("useMoveChannel", () => {
)
})
})
+
+describe("useCreateChannel — optimistic pending row", () => {
+ type Ch = { id: string; name: string; type?: string; pending?: boolean }
+ type Cat = { id: string; name: string; channels: Ch[] }
+ const seed = (categories: Cat[]) =>
+ capturedQc.setQueryData(communityKeys.server("s1"), {
+ id: "s1", name: "S", description: "", icon: null, ownerId: "u1", categories,
+ })
+ const channels = (catId: string): Ch[] => {
+ const detail = capturedQc.getQueryData<{ categories: Cat[] }>(communityKeys.server("s1"))
+ return detail?.categories.find((c) => c.id === catId)?.channels ?? []
+ }
+
+ it("inserts a pending channel into the matching category", async () => {
+ seed([{ id: "cat_1", name: "General", channels: [] }])
+ apiFetchMock.mockResolvedValueOnce({ channel: { id: "ch_real" } })
+ const mod = await load()
+ mod.useCreateChannel()
+
+ // Observe the cache right after onMutate, before mutationFn resolves.
+ const cfg = capturedConfig!
+ const ctx = await cfg.onMutate!({ serverId: "s1", categoryId: "cat_1", name: " hi ", type: "text" })
+ const pending = channels("cat_1")[0]
+ expect(pending.id).toMatch(/^tmp_ch_/)
+ expect(pending.pending).toBe(true)
+ expect(pending.name).toBe("hi")
+ expect(pending.type).toBe("text")
+ expect((ctx as { tempId: string }).tempId).toBe(pending.id)
+ })
+
+ it("cancels in-flight server refetches before the optimistic write", async () => {
+ seed([{ id: "cat_1", name: "General", channels: [] }])
+ apiFetchMock.mockResolvedValueOnce({ channel: { id: "ch_real" } })
+ const mod = await load()
+ mod.useCreateChannel()
+
+ const cancelSpy = vi.spyOn(capturedQc, "cancelQueries")
+ let cancelledBeforeWrite = false
+ const originalSetQueryData = capturedQc.setQueryData.bind(capturedQc)
+ vi.spyOn(capturedQc, "setQueryData").mockImplementation(((...args: Parameters<typeof capturedQc.setQueryData>) => {
+ if (cancelSpy.mock.calls.length > 0) cancelledBeforeWrite = true
+ return originalSetQueryData(...args)
+ }) as typeof capturedQc.setQueryData)
+
+ await runMutation({ serverId: "s1", categoryId: "cat_1", name: "hi", type: "text" })
+ expect(
+ cancelSpy.mock.calls.some((c) => {
+ const k = c[0]?.queryKey as unknown[] | undefined
+ return Array.isArray(k) && k[0] === "community" && k[1] === "servers" && k[2] === "s1"
+ }),
+ ).toBe(true)
+ expect(cancelledBeforeWrite).toBe(true)
+ })
+
+ it("is a no-op write when the target category is not in the cache", async () => {
+ seed([{ id: "cat_1", name: "General", channels: [{ id: "ch_a", name: "a" }] }])
+ apiFetchMock.mockResolvedValueOnce({ channel: { id: "ch_real" } })
+ const mod = await load()
+ mod.useCreateChannel()
+ const ctx = await capturedConfig!.onMutate!({ serverId: "s1", categoryId: "cat_missing", name: "hi", type: "text" })
+ expect(channels("cat_1")).toHaveLength(1)
+ expect((ctx as { tempId: string }).tempId).toMatch(/^tmp_ch_/)
+ })
+
+ it("rolls back to the snapshot on failure", async () => {
+ seed([{ id: "cat_1", name: "General", channels: [] }])
+ apiFetchMock.mockRejectedValueOnce(new Error("boom"))
+ const mod = await load()
+ mod.useCreateChannel()
+ await runMutation({ serverId: "s1", categoryId: "cat_1", name: "hi", type: "text" }).catch(() => {})
+ expect(channels("cat_1")).toHaveLength(0)
+ })
+
+ it("swaps the temp id to the real id and clears pending on success", async () => {
+ seed([{ id: "cat_1", name: "General", channels: [] }])
+ apiFetchMock.mockResolvedValueOnce({ channel: { id: "ch_real" } })
+ const mod = await load()
+ mod.useCreateChannel()
+ await runMutation({ serverId: "s1", categoryId: "cat_1", name: "hi", type: "text" })
+ const row = channels("cat_1")[0]
+ expect(row.id).toBe("ch_real")
+ expect(row.pending).toBe(false)
+ })
+
+ it("invalidates the server tree on both success and failure", async () => {
+ const matchesServerKey = (c: { queryKey?: unknown }) => {
+ const k = c.queryKey as unknown[] | undefined
+ return Array.isArray(k) && k[0] === "community" && k[1] === "servers" && k[2] === "s1"
+ }
+
+ seed([{ id: "cat_1", name: "General", channels: [] }])
+ apiFetchMock.mockResolvedValueOnce({ channel: { id: "ch_real" } })
+ let mod = await load()
+ mod.useCreateChannel()
+ let invalidateSpy = vi.spyOn(capturedQc, "invalidateQueries")
+ await runMutation({ serverId: "s1", categoryId: "cat_1", name: "hi", type: "text" })
+ expect(invalidateSpy.mock.calls.some((c) => matchesServerKey(c[0] ?? {}))).toBe(true)
+
+ capturedQc = new QueryClient()
+ seed([{ id: "cat_1", name: "General", channels: [] }])
+ apiFetchMock.mockRejectedValueOnce(new Error("boom"))
+ mod = await load()
+ mod.useCreateChannel()
+ invalidateSpy = vi.spyOn(capturedQc, "invalidateQueries")
+ await runMutation({ serverId: "s1", categoryId: "cat_1", name: "hi", type: "text" }).catch(() => {})
+ expect(invalidateSpy.mock.calls.some((c) => matchesServerKey(c[0] ?? {}))).toBe(true)
+ })
+
+ it("POSTs { categoryId, name, type } to the channels endpoint", async () => {
+ seed([{ id: "cat_1", name: "General", channels: [] }])
+ apiFetchMock.mockResolvedValueOnce({ channel: { id: "ch_real" } })
+ const mod = await load()
+ mod.useCreateChannel()
+ await runMutation({ serverId: "s1", categoryId: "cat_1", name: "hi", type: "text" })
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/servers/s1/channels",
+ { method: "POST", body: JSON.stringify({ categoryId: "cat_1", name: "hi", type: "text" }) },
+ )
+ })
+
+ it("synthesizes an uncategorized bucket for the first top-level channel (categoryId empty, no bucket yet)", async () => {
+ seed([{ id: "cat_1", name: "General", channels: [] }])
+ apiFetchMock.mockResolvedValueOnce({ channel: { id: "ch_real" } })
+ const mod = await load()
+ mod.useCreateChannel()
+
+ const ctx = await capturedConfig!.onMutate!({ serverId: "s1", categoryId: "", name: "top", type: "text" })
+ const bucket = channels(UNCATEGORIZED_CATEGORY_ID)
+ expect(bucket).toHaveLength(1)
+ expect(bucket[0].id).toBe((ctx as { tempId: string }).tempId)
+ expect(bucket[0].pending).toBe(true)
+
+ await capturedConfig!.mutationFn!({ serverId: "s1", categoryId: "", name: "top", type: "text" })
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/servers/s1/channels",
+ { method: "POST", body: JSON.stringify({ categoryId: null, name: "top", type: "text" }) },
+ )
+ })
+
+ it("attaches to an existing empty-name bucket even when its id is not the synthetic constant", async () => {
+ seed([{ id: "cat_none", name: "", channels: [] }])
+ apiFetchMock.mockResolvedValueOnce({ channel: { id: "ch_real" } })
+ const mod = await load()
+ mod.useCreateChannel()
+ await capturedConfig!.onMutate!({ serverId: "s1", categoryId: "", name: "top", type: "text" })
+ // No duplicate synthetic bucket — the pending row lands in the existing one.
+ const detail = capturedQc.getQueryData<{ categories: Cat[] }>(communityKeys.server("s1"))
+ expect(detail?.categories).toHaveLength(1)
+ expect(detail?.categories[0].channels).toHaveLength(1)
+ })
+
+ it("translates the synthetic uncategorized bucket id to null for the API, but still writes the optimistic row into that bucket", async () => {
+ seed([{ id: UNCATEGORIZED_CATEGORY_ID, name: "", channels: [] }])
+ apiFetchMock.mockResolvedValueOnce({ channel: { id: "ch_real" } })
+ const mod = await load()
+ mod.useCreateChannel()
+
+ const ctx = await capturedConfig!.onMutate!({ serverId: "s1", categoryId: UNCATEGORIZED_CATEGORY_ID, name: "top", type: "text" })
+ // Optimistic row landed in the synthetic bucket by its bucket id.
+ expect(channels(UNCATEGORIZED_CATEGORY_ID)[0].id).toBe((ctx as { tempId: string }).tempId)
+
+ await capturedConfig!.mutationFn!({ serverId: "s1", categoryId: UNCATEGORIZED_CATEGORY_ID, name: "top", type: "text" })
+ // But the wire request sends categoryId: null — never the synthetic id.
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/servers/s1/channels",
+ { method: "POST", body: JSON.stringify({ categoryId: null, name: "top", type: "text" }) },
+ )
+ })
+})
+
+describe("useCreateCategory — optimistic pending category", () => {
+ type Cat = { id: string; name: string; pending?: boolean; channels: unknown[] }
+ const seed = (categories: Cat[]) =>
+ capturedQc.setQueryData(communityKeys.server("s1"), {
+ id: "s1", name: "S", description: "", icon: null, ownerId: "u1", categories,
+ })
+ const cats = (): Cat[] =>
+ capturedQc.getQueryData<{ categories: Cat[] }>(communityKeys.server("s1"))?.categories ?? []
+
+ it("appends a pending category with a tmp_cat_ id", async () => {
+ seed([{ id: "cat_1", name: "General", channels: [] }])
+ apiFetchMock.mockResolvedValueOnce({ category: { id: "cat_real" } })
+ const mod = await load()
+ mod.useCreateCategory()
+ const ctx = await capturedConfig!.onMutate!({ serverId: "s1", name: " Ideas " })
+ const added = cats().find((c) => c.pending)
+ expect(added?.id).toMatch(/^tmp_cat_/)
+ expect(added?.name).toBe("Ideas")
+ expect((ctx as { tempId: string }).tempId).toBe(added?.id)
+ })
+
+ it("swaps the temp id to the real id and clears pending on success", async () => {
+ seed([{ id: "cat_1", name: "General", channels: [] }])
+ apiFetchMock.mockResolvedValueOnce({ category: { id: "cat_real" } })
+ const mod = await load()
+ mod.useCreateCategory()
+ await runMutation({ serverId: "s1", name: "Ideas" })
+ const added = cats().find((c) => c.name === "Ideas")
+ expect(added?.id).toBe("cat_real")
+ expect(added?.pending).toBe(false)
+ })
+
+ it("rolls back on failure", async () => {
+ seed([{ id: "cat_1", name: "General", channels: [] }])
+ apiFetchMock.mockRejectedValueOnce(new Error("boom"))
+ const mod = await load()
+ mod.useCreateCategory()
+ await runMutation({ serverId: "s1", name: "Ideas" }).catch(() => {})
+ expect(cats()).toHaveLength(1)
+ expect(cats()[0].id).toBe("cat_1")
+ })
+})
+
+describe("useDeleteCategory — optimistic removal with rollback", () => {
+ type Cat = { id: string; name: string; channels: unknown[] }
+ const seed = (categories: Cat[]) =>
+ capturedQc.setQueryData(communityKeys.server("s1"), {
+ id: "s1", name: "S", description: "", icon: null, ownerId: "u1", categories,
+ })
+ const cats = (): Cat[] =>
+ capturedQc.getQueryData<{ categories: Cat[] }>(communityKeys.server("s1"))?.categories ?? []
+
+ it("removes the category from the cache optimistically", async () => {
+ seed([{ id: "cat_1", name: "General", channels: [] }, { id: "cat_2", name: "Ideas", channels: [] }])
+ apiFetchMock.mockResolvedValueOnce(undefined)
+ const mod = await load()
+ mod.useDeleteCategory()
+ await capturedConfig!.onMutate!({ serverId: "s1", categoryId: "cat_2" })
+ expect(cats().map((c) => c.id)).toEqual(["cat_1"])
+ })
+
+ it("restores the category on a rejected delete (e.g. 409 non-empty)", async () => {
+ seed([{ id: "cat_1", name: "General", channels: [] }, { id: "cat_2", name: "Ideas", channels: [] }])
+ apiFetchMock.mockRejectedValueOnce(new Error("Move or delete its channels first"))
+ const mod = await load()
+ mod.useDeleteCategory()
+ await runMutation({ serverId: "s1", categoryId: "cat_2" }).catch(() => {})
+ expect(cats().map((c) => c.id)).toEqual(["cat_1", "cat_2"])
+ })
+})
diff --git a/src/web/src/hooks/community/mutations/channels.ts b/src/web/src/hooks/community/mutations/channels.ts
index ea30486ec..9921242d9 100644
--- a/src/web/src/hooks/community/mutations/channels.ts
+++ b/src/web/src/hooks/community/mutations/channels.ts
@@ -1,9 +1,21 @@
"use client"
import { useMutation, useQueryClient } from "@tanstack/react-query"
+import { nanoid } from "nanoid"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
-import type { ChannelType } from "@alook/shared"
+import type { ServerDetail } from "@/hooks/community/use-servers"
+import { UNCATEGORIZED_CATEGORY_ID, type ChannelType } from "@alook/shared"
+
+// Prefix marks an optimistic row so every consumer can tell it from a real
+// `ch_…` id without a separate flag, and guarantees it never collides with one.
+const tempChannelId = () => `tmp_ch_${nanoid()}`
+
+// A create can name the uncategorized target three ways: `null`, `""` (the
+// sidebar's fallback when no synthetic bucket exists yet), or the synthetic
+// bucket id itself (once one does). All mean "top level".
+const isUncategorizedTarget = (categoryId: string | null) =>
+ !categoryId || categoryId === UNCATEGORIZED_CATEGORY_ID
/**
* Channel / category CRUD + reorders. These all invalidate `server(serverId)`
@@ -23,16 +35,97 @@ export type CreateChannelArgs = {
}
export type CreateChannelResult = { channel: { id: string } }
+type CreateChannelCtx = { snapshot?: ServerDetail; tempId: string }
+
+/**
+ * Optimistically inserts a pending channel row into the target category so the
+ * sidebar shows immediate feedback, then reconciles on settle. `onMutate`
+ * writes a `tmp_ch_…` row; `onSuccess` swaps its id for the real one (so
+ * auto-navigation highlights the active row before the refetch lands);
+ * `onError` rolls back; `onSettled` invalidates so the tree resettles to server
+ * truth (real ids, positions, slug-normalized name). The WS `channel.create`
+ * broadcast also invalidates `server(serverId)` — TanStack de-dupes the
+ * concurrent refetch, so no duplicate row.
+ */
export function useCreateChannel() {
const queryClient = useQueryClient()
- return useMutation<CreateChannelResult, Error, CreateChannelArgs>({
+ return useMutation<CreateChannelResult, Error, CreateChannelArgs, CreateChannelCtx>({
mutationFn: async ({ serverId, categoryId, name, type }) => {
+ // The uncategorized bucket is a synthetic id, not a real category row —
+ // send `null` so the server doesn't 404 on `getCategory`. onMutate still
+ // uses the bucket to place the optimistic row in the cache.
+ const apiCategoryId = isUncategorizedTarget(categoryId) ? null : categoryId
return apiFetch<CreateChannelResult>(
`/api/community/servers/${serverId}/channels`,
- { method: "POST", body: JSON.stringify({ categoryId, name, type }) },
+ { method: "POST", body: JSON.stringify({ categoryId: apiCategoryId, name, type }) },
)
},
- onSuccess: (_data, args) => {
+ onMutate: async (args) => {
+ const key = communityKeys.server(args.serverId)
+ await queryClient.cancelQueries({ queryKey: key })
+ const snapshot = queryClient.getQueryData<ServerDetail>(key)
+ const tempId = tempChannelId()
+ const pending = {
+ id: tempId,
+ name: args.name.trim(),
+ active: false,
+ unread: false,
+ type: args.type,
+ creatorId: null,
+ pending: true,
+ }
+ queryClient.setQueryData<ServerDetail>(key, (prev) => {
+ if (!prev) return prev
+ const uncategorized = isUncategorizedTarget(args.categoryId)
+ // Resolve which cache category to attach to: the named one, or the
+ // synthetic uncategorized bucket (matched by id OR the empty-name
+ // convention the server-detail response uses).
+ const target = prev.categories.find((c) =>
+ uncategorized ? (c.id === UNCATEGORIZED_CATEGORY_ID || c.name === "") : c.id === args.categoryId,
+ )
+ if (target) {
+ return {
+ ...prev,
+ categories: prev.categories.map((c) =>
+ c === target ? { ...c, channels: [...c.channels, pending] } : c,
+ ),
+ }
+ }
+ // First top-level channel: no synthetic bucket exists yet. Synthesize
+ // one so the pending row shows immediately; the settle refetch replaces
+ // it with the server's real uncategorized bucket.
+ if (uncategorized) {
+ return {
+ ...prev,
+ categories: [
+ ...prev.categories,
+ { id: UNCATEGORIZED_CATEGORY_ID, name: "", channels: [pending] } as ServerDetail["categories"][number],
+ ],
+ }
+ }
+ return prev
+ })
+ return { snapshot, tempId }
+ },
+ onSuccess: (data, args, ctx) => {
+ const key = communityKeys.server(args.serverId)
+ queryClient.setQueryData<ServerDetail>(key, (prev) => {
+ if (!prev) return prev
+ return {
+ ...prev,
+ categories: prev.categories.map((c) => ({
+ ...c,
+ channels: c.channels.map((ch) =>
+ ch.id === ctx.tempId ? { ...ch, id: data.channel.id, pending: false } : ch,
+ ),
+ })),
+ }
+ })
+ },
+ onError: (_err, args, ctx) => {
+ if (ctx?.snapshot) queryClient.setQueryData(communityKeys.server(args.serverId), ctx.snapshot)
+ },
+ onSettled: (_data, _err, args) => {
void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId) })
},
})
@@ -91,16 +184,63 @@ export type CreateCategoryArgs = {
}
export type CreateCategoryResult = { category: { id: string } }
+const tempCategoryId = () => `tmp_cat_${nanoid()}`
+
+type CreateCategoryCtx = { snapshot?: ServerDetail; tempId: string }
+
+/**
+ * Optimistically appends a pending category so the sidebar shows it
+ * immediately, then reconciles on settle — mirrors `useCreateChannel`.
+ * `onSuccess` swaps the temp id for the real one; `onError` rolls back;
+ * `onSettled` invalidates so the tree resettles to server truth.
+ */
export function useCreateCategory() {
const queryClient = useQueryClient()
- return useMutation<CreateCategoryResult, Error, CreateCategoryArgs>({
+ return useMutation<CreateCategoryResult, Error, CreateCategoryArgs, CreateCategoryCtx>({
mutationFn: async ({ serverId, name, private: isPrivate }) => {
return apiFetch<CreateCategoryResult>(
`/api/community/servers/${serverId}/categories`,
{ method: "POST", body: JSON.stringify({ name, private: isPrivate }) },
)
},
- onSuccess: (_data, args) => {
+ onMutate: async (args) => {
+ const key = communityKeys.server(args.serverId)
+ await queryClient.cancelQueries({ queryKey: key })
+ const snapshot = queryClient.getQueryData<ServerDetail>(key)
+ const tempId = tempCategoryId()
+ queryClient.setQueryData<ServerDetail>(key, (prev) => {
+ if (!prev) return prev
+ return {
+ ...prev,
+ categories: [
+ ...prev.categories,
+ {
+ id: tempId,
+ name: args.name.trim(),
+ private: args.private ? 1 : 0,
+ channels: [],
+ pending: true,
+ } as ServerDetail["categories"][number],
+ ],
+ }
+ })
+ return { snapshot, tempId }
+ },
+ onSuccess: (data, args, ctx) => {
+ queryClient.setQueryData<ServerDetail>(communityKeys.server(args.serverId), (prev) => {
+ if (!prev) return prev
+ return {
+ ...prev,
+ categories: prev.categories.map((c) =>
+ c.id === ctx.tempId ? { ...c, id: data.category.id, pending: false } : c,
+ ),
+ }
+ })
+ },
+ onError: (_err, args, ctx) => {
+ if (ctx?.snapshot) queryClient.setQueryData(communityKeys.server(args.serverId), ctx.snapshot)
+ },
+ onSettled: (_data, _err, args) => {
void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId) })
},
})
@@ -130,15 +270,36 @@ export function useUpdateCategory() {
export type DeleteCategoryArgs = { serverId: string; categoryId: string }
+/**
+ * Optimistically drops the category from the cache, then reconciles on settle.
+ * Rollback on error is essential here: the server rejects deleting a non-empty
+ * category (409 "Move or delete its channels first"), and without a rollback
+ * the still-existing category would vanish from the sidebar until an unrelated
+ * refetch. The tree is cache-derived, so the cache removal IS the optimistic UI
+ * — the sidebar no longer mutates local tree state for a delete.
+ */
export function useDeleteCategory() {
const queryClient = useQueryClient()
- return useMutation<void, Error, DeleteCategoryArgs>({
+ return useMutation<void, Error, DeleteCategoryArgs, { snapshot?: ServerDetail }>({
mutationFn: async ({ serverId, categoryId }) => {
await apiFetch(`/api/community/servers/${serverId}/categories/${categoryId}`, {
method: "DELETE",
})
},
- onSuccess: (_data, args) => {
+ onMutate: async (args) => {
+ const key = communityKeys.server(args.serverId)
+ await queryClient.cancelQueries({ queryKey: key })
+ const snapshot = queryClient.getQueryData<ServerDetail>(key)
+ queryClient.setQueryData<ServerDetail>(key, (prev) => {
+ if (!prev) return prev
+ return { ...prev, categories: prev.categories.filter((c) => c.id !== args.categoryId) }
+ })
+ return { snapshot }
+ },
+ onError: (_err, args, ctx) => {
+ if (ctx?.snapshot) queryClient.setQueryData(communityKeys.server(args.serverId), ctx.snapshot)
+ },
+ onSettled: (_data, _err, args) => {
void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId) })
},
})