Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(community): loading states for member management + fix kick id
Gener64c8ba771691
diff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsxindex ba581e5f1..99052f5c3 100644--- a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx@@ -718,14 +718,13 @@ function ChannelView() {? {viewerUserId: currentUser.id,viewerIsCreator: viewerIsUnitCreator,+ unitLabel: currentChannelMeta?.name ?? channelName,+ // Return the promise so the confirm dialog can show a loading state and+ // surface errors from ONE place (MemberList's confirm catch).onLeave: (userId: string) =>- (isThread ? removeThreadParticipantMut : removeChannelMemberMut).mutate(userId, {- onError: (e) => toastApiError(e, "Failed to leave"),- }),+ (isThread ? removeThreadParticipantMut : removeChannelMemberMut).mutateAsync(userId),onRemove: (userId: string) =>- (isThread ? removeThreadParticipantMut : removeChannelMemberMut).mutate(userId, {- onError: (e) => toastApiError(e, "Failed to remove"),- }),+ (isThread ? removeThreadParticipantMut : removeChannelMemberMut).mutateAsync(userId),}: undefinedconst panelProps = {@@ -755,12 +754,11 @@ function ChannelView() {onError: (e) => toastApiError(e, "Failed to update role"),})},- onKickMember: (memberId: string) => {- kickMemberMut.mutate({ serverId, memberId }, {- onSuccess: () => toast("Member kicked"),- onError: (e) => toastApiError(e, "Failed to kick member"),- })- },+ // Return the promise (and success toast) so MemberList's confirm dialog can+ // show a loading state; the error is surfaced from MemberList's catch (one+ // toast source).+ onKickMember: (memberId: string) =>+ kickMemberMut.mutateAsync({ serverId, memberId }).then(() => toast("Member kicked")),onJumpToMessage: (id: string) => {setScrollToMessageId(id)setTimeout(() => setScrollToMessageId(null), 100)@@ -787,8 +785,7 @@ function ChannelView() {title={`Add participants to /${currentChannelMeta?.name ?? channelName}`}subtitle="Added people are notified of new replies. Anyone with access can already read the thread."candidates={candidates}- addPending={addThreadParticipantMut.isPending}- onAdd={async (userId) => { await addThreadParticipantMut.mutateAsync(userId) }}+ onAdd={(userId) => addThreadParticipantMut.mutateAsync(userId)}onClose={() => setManageMembersOpen(false)}/>)@@ -803,8 +800,7 @@ function ChannelView() {title={`Add members to /${channelName}`}subtitle="Added members can see and post in this channel."candidates={candidates}- addPending={addChannelMemberMut.isPending}- onAdd={async (userId) => { await addChannelMemberMut.mutateAsync(userId) }}+ onAdd={(userId) => addChannelMemberMut.mutateAsync(userId)}onClose={() => setManageMembersOpen(false)}/>)diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.tsindex bb9832834..42140f08b 100644--- a/src/web/src/components/community/_types.ts+++ b/src/web/src/components/community/_types.ts@@ -348,6 +348,12 @@ export type MemberManageContext = {// The viewer created this unit → their own row shows no Leave (owners keep// the unit), and they may Remove other explicit members.viewerIsCreator: boolean- onLeave: (userId: string) => void- onRemove: (userId: string) => void+ // The unit's display name (channel/post/thread), used in the Leave confirm+ // dialog title ("Leave /general?"). Optional for back-compat.+ unitLabel?: string+ // Return a promise so the confirm dialog can show a loading state until the+ // remove settles. Resolved value is ignored (mutateAsync resolves to the API+ // payload) — the dialog only awaits settlement.+ onLeave: (userId: string) => Promise<unknown> | void+ onRemove: (userId: string) => Promise<unknown> | void}diff --git a/src/web/src/components/community/add-members-dialog.test.ts b/src/web/src/components/community/add-members-dialog.test.tsnew file mode 100644index 000000000..d24f599e7--- /dev/null+++ b/src/web/src/components/community/add-members-dialog.test.ts@@ -0,0 +1,76 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { createElement } from "react"+import { renderToStaticMarkup } from "react-dom/server"++// Spy on toastApiError so the reject path can be asserted without a real DOM+// (sonner injects a <style> at import time). Mock before importing the module.+const toastApiErrorSpy = vi.fn()+vi.mock("@/lib/api/client", () => ({+ toastApiError: (...args: unknown[]) => toastApiErrorSpy(...args),+}))++import { AddMemberRow, runAdd, type AddableCandidate } from "./add-members-dialog"++const candidate: AddableCandidate = { userId: "u_1", name: "Alice", avatar: "A" }++function render(adding: boolean): string {+ return renderToStaticMarkup(+ createElement(AddMemberRow, { candidate, adding, onAdd: () => {} }),+ )+}++describe("AddMemberRow", () => {+ it("shows a spinner and disables the button while adding", () => {+ const html = render(true)+ expect(html).toContain("animate-spin")+ expect(html).toContain("disabled")+ // The literal label is replaced by the spinner while in flight.+ expect(html).not.toContain(">Add<")+ })++ it("shows the Add label and no spinner when idle", () => {+ const html = render(false)+ expect(html).toContain("Add")+ expect(html).not.toContain("animate-spin")+ })++ it("renders the candidate's display name", () => {+ expect(render(false)).toContain("Alice")+ })+})++describe("runAdd", () => {+ beforeEach(() => {+ toastApiErrorSpy.mockClear()+ })++ // Capture the sequence of set-state updater results so we can assert the id+ // enters then leaves the in-flight set.+ function trackingSetter() {+ let set = new Set<string>()+ const calls: string[][] = []+ const setAddingIds = (updater: Set<string> | ((s: Set<string>) => Set<string>)) => {+ set = typeof updater === "function" ? updater(set) : updater+ calls.push([...set])+ }+ return { setAddingIds: setAddingIds as never, snapshots: () => calls, current: () => [...set] }+ }++ it("marks the id in flight and KEEPS it on success (spinner persists until the row unmounts)", async () => {+ const t = trackingSetter()+ await runAdd("u_1", async () => {}, t.setAddingIds)+ // Added once, never cleared — the row leaves the candidate list on refetch,+ // so clearing here would flash the button back to "Add" for a frame.+ expect(t.snapshots()).toEqual([["u_1"]])+ expect(t.current()).toEqual(["u_1"])+ expect(toastApiErrorSpy).not.toHaveBeenCalled()+ })++ it("clears the id AND toasts on failure (row reverts to a clickable Add)", async () => {+ const t = trackingSetter()+ await runAdd("u_1", async () => { throw new Error("nope") }, t.setAddingIds)+ expect(t.current()).toEqual([])+ expect(toastApiErrorSpy).toHaveBeenCalledTimes(1)+ expect(toastApiErrorSpy).toHaveBeenCalledWith(expect.any(Error), "Couldn't add member")+ })+})diff --git a/src/web/src/components/community/add-members-dialog.tsx b/src/web/src/components/community/add-members-dialog.tsxindex 7348746e4..3bc8a5317 100644--- a/src/web/src/components/community/add-members-dialog.tsx+++ b/src/web/src/components/community/add-members-dialog.tsx@@ -1,13 +1,14 @@"use client"+import type React from "react"import { useMemo, useState } from "react"-import { Search } from "lucide-react"-import { toast } from "sonner"+import { Search, Loader2 } from "lucide-react"import { Dialog, DialogContent } from "@/components/ui/dialog"import { Input } from "@/components/ui/input"import { Button } from "@/components/ui/button"import { Avatar } from "./avatar"import { displayName } from "@/lib/community/display-name"+import { toastApiError } from "@/lib/api/client"export type AddableCandidate = {userId: string@@ -15,6 +16,61 @@ export type AddableCandidate = {avatar: string}+/**+ * A single candidate row with its own in-flight state. Exported so the+ * spinner-vs-"Add" + disabled behaviour is unit-testable without mounting the+ * Portal-rendered Dialog (the node test env's `renderToStaticMarkup` doesn't+ * render portal children).+ */+export function AddMemberRow({+ candidate,+ adding,+ onAdd,+}: {+ candidate: AddableCandidate+ adding: boolean+ onAdd: (userId: string) => void+}) {+ return (+ <div className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent/40">+ <Avatar label={candidate.avatar || candidate.name || ""} seed={candidate.userId} size={32} />+ <div className="min-w-0 flex-1 truncate text-sm font-medium">{displayName(candidate)}</div>+ <Button size="sm" disabled={adding} onClick={() => onAdd(candidate.userId)}>+ {adding ? <Loader2 className="size-4 animate-spin" /> : "Add"}+ </Button>+ </div>+ )+}++/**+ * Drive one add through its in-flight lifecycle: mark the id in flight, await+ * the caller's `onAdd`, and toast on failure. Exported for unit-testing the+ * reject path without React.+ *+ * On SUCCESS the id is intentionally kept in flight: `onAdd`'s mutation resolves+ * before its candidate-pool refetch lands, so clearing here would flash the+ * button back to "Add" for a frame before the row unmounts. Keeping the spinner+ * until the row leaves the list is seamless. On FAILURE the id is cleared so the+ * row reverts to a clickable "Add" for retry.+ */+export async function runAdd(+ userId: string,+ onAdd: (userId: string) => Promise<unknown> | void,+ setAddingIds: React.Dispatch<React.SetStateAction<Set<string>>>,+): Promise<void> {+ setAddingIds((s) => new Set(s).add(userId))+ try {+ await onAdd(userId)+ } catch (err) {+ toastApiError(err, "Couldn't add member")+ setAddingIds((s) => {+ const next = new Set(s)+ next.delete(userId)+ return next+ })+ }+}+/*** Shared "add members" picker for every private unit — a channel/post roster or* a thread participant set. Pure add: the current-member list and its@@ -28,18 +84,19 @@ export function AddMembersDialog({title,subtitle,candidates,- addPending,onAdd,onClose,}: {title: stringsubtitle: stringcandidates: AddableCandidate[]- addPending: boolean- onAdd: (userId: string) => Promise<void> | void+ onAdd: (userId: string) => Promise<unknown> | voidonClose: () => void}) {const [query, setQuery] = useState("")+ // In-flight adds, keyed by userId — each row spins independently, so adding+ // multiple people in a row doesn't disable the others.+ const [addingIds, setAddingIds] = useState<Set<string>>(new Set())const filtered = useMemo(() => {const q = query.trim().toLowerCase()@@ -47,13 +104,7 @@ export function AddMembersDialog({return candidates.filter((m) => (m.name ?? "").toLowerCase().includes(q))}, [candidates, query])- const add = async (userId: string) => {- try {- await onAdd(userId)- } catch (err) {- toast(err instanceof Error ? err.message : "Couldn't add member")- }- }+ const add = (userId: string) => void runAdd(userId, onAdd, setAddingIds)return (<Dialog open onOpenChange={(o) => { if (!o) onClose() }}>@@ -79,13 +130,12 @@ export function AddMembersDialog({</p>) : (filtered.map((m) => (- <div key={m.userId} className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent/40">- <Avatar label={m.avatar || m.name || ""} seed={m.userId} size={32} />- <div className="min-w-0 flex-1 truncate text-sm font-medium">{displayName(m)}</div>- <Button size="sm" disabled={addPending} onClick={() => add(m.userId)}>- Add- </Button>- </div>+ <AddMemberRow+ key={m.userId}+ candidate={m}+ adding={addingIds.has(m.userId)}+ onAdd={add}+ />)))}</div>diff --git a/src/web/src/components/community/channel-add-members-dialog.tsx b/src/web/src/components/community/channel-add-members-dialog.tsxindex 118227aee..cd2369406 100644--- a/src/web/src/components/community/channel-add-members-dialog.tsx+++ b/src/web/src/components/community/channel-add-members-dialog.tsx@@ -1,6 +1,5 @@"use client"-import { toast } from "sonner"import { AddMembersDialog } from "./add-members-dialog"import {useAddableMembers,@@ -36,14 +35,7 @@ export function ChannelAddMembersDialog({title={`Add members to /${channelName}`}subtitle="Added members can see and post in this channel."candidates={candidates}- addPending={addMember.isPending}- onAdd={async (userId) => {- try {- await addMember.mutateAsync(userId)- } catch (err) {- toast(err instanceof Error ? err.message : "Couldn't add member")- }- }}+ onAdd={(userId) => addMember.mutateAsync(userId)}onClose={onClose}/>)diff --git a/src/web/src/components/community/community-panel-sheet.tsx b/src/web/src/components/community/community-panel-sheet.tsxindex 1cc56dd08..711eaca4b 100644--- a/src/web/src/components/community/community-panel-sheet.tsx+++ b/src/web/src/components/community/community-panel-sheet.tsx@@ -55,7 +55,7 @@ export function CommunityPanelSheet({onOpenThread: (id: string) => voidonOpenProfile?: OpenProfileonSetRole?: (name: string, role: Role) => void- onKickMember?: (name: string) => void+ onKickMember?: (memberId: string) => Promise<unknown> | voidmyRole?: RoleonJumpToMessage?: (id: string) => voidonSearch?: (query: string) => voiddiff --git a/src/web/src/components/community/member-list.tsx b/src/web/src/components/community/member-list.tsxindex 53e955b4b..54632c3c4 100644--- a/src/web/src/components/community/member-list.tsx+++ b/src/web/src/components/community/member-list.tsx@@ -11,11 +11,15 @@ import { Skeleton } from "@/components/ui/skeleton"import { Input } from "@/components/ui/input"import { Avatar } from "./avatar"import { ConfirmDialog } from "@/components/ui/confirm-dialog"+import { toastApiError } from "@/lib/api/client"import { hasStatus } from "./status-presets"import { tid } from "@/lib/community/testids"import type { Member, Role, OpenProfile, MemberManageContext } from "./_types"import { canManageServer, isServerOwner, ROLES, isPresenceOnline, isPresenceOffline } from "./_types"+// The Leave/Remove confirm flow the row menu opens (private channel/post/thread).+type ManageConfirm = { kind: "leave" | "remove"; member: Member }+const SETTABLE_ROLES: Role[] = ["admin", "member"]// Fixed row heights used by the virtualizer. Slight over-estimation is safer@@ -110,9 +114,16 @@ export function MemberList({myRole?: RoleonOpenProfile?: OpenProfileonSetRole?: (name: string, role: Role) => void- onKick?: (name: string) => void+ onKick?: (memberId: string) => Promise<unknown> | void}) {- const [kickTarget, setKickTarget] = useState<string | null>(null)+ // Kick target stores BOTH the display name (for the confirm title) and the+ // member row id (what the DELETE route keys on — passing the name here was a+ // latent 404 bug on the community right-panel kick path).+ const [kickTarget, setKickTarget] = useState<{ name: string; memberId: string } | null>(null)+ const [kicking, setKicking] = useState(false)+ // Leave/Remove confirm (private channel/post/thread roster).+ const [manageConfirm, setManageConfirm] = useState<ManageConfirm | null>(null)+ const [actioning, setActioning] = useState(false)const [query, setQuery] = useState("")const canManage = canManageServer(myRole)@@ -166,13 +177,59 @@ export function MemberList({<><ConfirmDialogopen={!!kickTarget}- onOpenChange={(o) => { if (!o) setKickTarget(null) }}- title={`Kick ${kickTarget}?`}+ onOpenChange={(o) => { if (!o && !kicking) setKickTarget(null) }}+ title={`Kick ${kickTarget?.name}?`}description="They will be removed from this server but can rejoin with an invite."confirmLabel="Kick"+ loadingLabel="Kicking…"+ loading={kicking}confirmVariant="destructive"- onConfirm={() => { if (kickTarget) onKick?.(kickTarget); setKickTarget(null) }}+ onConfirm={async () => {+ if (!kickTarget) return+ setKicking(true)+ try {+ await onKick?.(kickTarget.memberId)+ setKickTarget(null)+ } catch (e) {+ toastApiError(e, "Failed to kick member")+ } finally {+ setKicking(false)+ }+ }}/>+ {manageConfirm && (+ <ConfirmDialog+ open+ onOpenChange={(o) => { if (!o && !actioning) setManageConfirm(null) }}+ title={+ manageConfirm.kind === "leave"+ ? `Leave /${manageContext?.unitLabel ?? ""}?`+ : `Remove ${manageConfirm.member.name}?`+ }+ description={+ manageConfirm.kind === "leave"+ ? "You'll lose access until you're added back."+ : "They'll lose access until they're added back."+ }+ confirmLabel={manageConfirm.kind === "leave" ? "Leave" : "Remove"}+ loadingLabel={manageConfirm.kind === "leave" ? "Leaving…" : "Removing…"}+ loading={actioning}+ confirmVariant="destructive"+ onConfirm={async () => {+ if (!manageContext) return+ setActioning(true)+ try {+ const fn = manageConfirm.kind === "leave" ? manageContext.onLeave : manageContext.onRemove+ await fn(manageConfirm.member.userId)+ setManageConfirm(null)+ } catch (e) {+ toastApiError(e, manageConfirm.kind === "leave" ? "Failed to leave" : "Failed to remove")+ } finally {+ setActioning(false)+ }+ }}+ />+ )}<aside className="flex h-full flex-col bg-background">{(onSearch || onAddMember) && (<div className="flex shrink-0 items-center gap-2 border-b border-border px-4 py-3">@@ -232,7 +289,8 @@ export function MemberList({showDiscriminator={duplicateNames.has(item.member.name.toLowerCase())}onOpenProfile={onOpenProfile}onSetRole={onSetRole}- onKick={setKickTarget}+ onKick={(mem) => setKickTarget({ name: mem.name, memberId: mem.id })}+ onRequestManage={(kind, mem) => setManageConfirm({ kind, member: mem })}manageContext={manageContext}/>)}@@ -266,6 +324,7 @@ function MemberRow({onOpenProfile,onSetRole,onKick,+ onRequestManage,manageContext,}: {mem: Member@@ -277,7 +336,11 @@ function MemberRow({showDiscriminator: booleanonOpenProfile?: OpenProfileonSetRole?: (name: string, role: Role) => void- onKick: (name: string) => void+ // Opens the server-kick confirm — receives the member so the caller can key+ // the DELETE on the member row id (not the display name).+ onKick: (mem: Member) => void+ // Opens the Leave/Remove confirm for a private channel/post/thread row.+ onRequestManage: (kind: "leave" | "remove", mem: Member) => voidmanageContext?: MemberManageContext}) {const button = (@@ -325,11 +388,11 @@ function MemberRow({<ContextMenuContent className="w-48"><div className="truncate px-2 py-1 text-xs font-semibold text-muted-foreground">{mem.name}</div>{canLeave ? (- <ContextMenuItem onClick={() => manageContext.onLeave(mem.userId)} className="text-destructive data-highlighted:bg-destructive/10 data-highlighted:text-destructive">+ <ContextMenuItem onClick={() => onRequestManage("leave", mem)} className="text-destructive data-highlighted:bg-destructive/10 data-highlighted:text-destructive"><LogOut className="size-4" /> Leave</ContextMenuItem>) : (- <ContextMenuItem onClick={() => manageContext.onRemove(mem.userId)} className="text-destructive data-highlighted:bg-destructive/10 data-highlighted:text-destructive">+ <ContextMenuItem onClick={() => onRequestManage("remove", mem)} className="text-destructive data-highlighted:bg-destructive/10 data-highlighted:text-destructive"><UserMinus className="size-4" /> Remove {mem.name}</ContextMenuItem>)}@@ -359,7 +422,7 @@ function MemberRow({</ContextMenuSubContent></ContextMenuSub><ContextMenuSeparator />- <ContextMenuItem onClick={() => onKick(mem.name)} className="text-destructive data-highlighted:bg-destructive/10 data-highlighted:text-destructive">+ <ContextMenuItem onClick={() => onKick(mem)} className="text-destructive data-highlighted:bg-destructive/10 data-highlighted:text-destructive"><UserMinus className="size-4" /> Kick {mem.name}</ContextMenuItem></ContextMenuContent>diff --git a/src/web/src/components/community/right-panel.tsx b/src/web/src/components/community/right-panel.tsxindex 50a84747f..926b315c3 100644--- a/src/web/src/components/community/right-panel.tsx+++ b/src/web/src/components/community/right-panel.tsx@@ -42,7 +42,7 @@ export function RightPanelContent({onOpenThread: (id: string) => voidonOpenProfile?: OpenProfileonSetRole?: (name: string, role: Role) => void- onKickMember?: (name: string) => void+ onKickMember?: (memberId: string) => Promise<unknown> | voidmyRole?: RoleonJumpToMessage?: (id: string) => voidonSearch?: (query: string) => void