Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): /me New-tab click-to-add, split pending, bot avatar seed, discriminator styling (#395)

Genere2bc85022ca4
diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.ts
index 7a4b078ce..ed4af8828 100644
--- a/src/shared/src/db/queries/community/bot.ts
+++ b/src/shared/src/db/queries/community/bot.ts
@@ -750,6 +750,44 @@ export async function findPendingFriendRequest(
return (rows[0] as ApprovalRequestRow | undefined) ?? null;
}
+export type OutgoingBotFriendRequest = {
+ id: string;
+ botUserId: string;
+ name: string;
+ image: string | null;
+ createdAt: string;
+};
+
+/**
+ * A requester's outgoing pending bot friend-requests, joined to the bot's
+ * public identity. Backs the friends "Outgoing" list so a sent bot request is
+ * visible (and cancellable) instead of silently living only as an owner-side
+ * DM approval card. Covered by the partial unique index
+ * `uq_community_bot_approval_pending_friend`.
+ */
+export async function listPendingFriendRequestsByRequester(
+ db: Database,
+ requesterUserId: string
+): Promise<OutgoingBotFriendRequest[]> {
+ return (await db
+ .select({
+ id: communityBotApprovalRequest.id,
+ botUserId: user.id,
+ name: user.name,
+ image: user.image,
+ createdAt: communityBotApprovalRequest.createdAt,
+ })
+ .from(communityBotApprovalRequest)
+ .innerJoin(user, eq(user.id, communityBotApprovalRequest.botId))
+ .where(
+ and(
+ eq(communityBotApprovalRequest.requestedByUserId, requesterUserId),
+ eq(communityBotApprovalRequest.kind, "friend"),
+ eq(communityBotApprovalRequest.status, "pending")
+ )
+ )) as OutgoingBotFriendRequest[];
+}
+
/**
* Statement-returning insert. Application layer enforces the
* `kind = "join_server" ⇔ serverId != null` invariant (SQLite CHECK can't
diff --git a/src/shared/test/queries/community-bot.test.ts b/src/shared/test/queries/community-bot.test.ts
index 2e4e9b588..e56e78637 100644
--- a/src/shared/test/queries/community-bot.test.ts
+++ b/src/shared/test/queries/community-bot.test.ts
@@ -36,6 +36,7 @@ describe("community/bot exports", () => {
expect(typeof q.listPendingApprovalsForBot).toBe("function")
expect(typeof q.findPendingJoinRequest).toBe("function")
expect(typeof q.findPendingFriendRequest).toBe("function")
+ expect(typeof q.listPendingFriendRequestsByRequester).toBe("function")
expect(typeof q.createApprovalRequestStatement).toBe("function")
expect(typeof q.resolveApprovalRequest).toBe("function")
expect(typeof q.getApprovalRequestByDmMessageId).toBe("function")
diff --git a/src/web/src/app/api/community/friends/bot-request/[requestId]/cancel/route.test.ts b/src/web/src/app/api/community/friends/bot-request/[requestId]/cancel/route.test.ts
new file mode 100644
index 000000000..4c96af1b5
--- /dev/null
+++ b/src/web/src/app/api/community/friends/bot-request/[requestId]/cancel/route.test.ts
@@ -0,0 +1,93 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+
+const mockGetApprovalRequest = vi.fn()
+const mockResolveApprovalRequest = vi.fn()
+const mockLogAudit = vi.fn()
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+vi.mock("@alook/shared", () => ({
+ queries: {
+ communityBot: {
+ getApprovalRequest: (...a: unknown[]) => mockGetApprovalRequest(...a),
+ resolveApprovalRequest: (...a: unknown[]) => mockResolveApprovalRequest(...a),
+ },
+ },
+}))
+
+vi.mock("@/lib/community/audit", () => ({
+ logAudit: (...a: unknown[]) => mockLogAudit(...a),
+ COMMUNITY_AUDIT_ACTIONS: { BOT_FRIEND_CANCELLED: "bot_friend_cancelled" },
+}))
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (_req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
+ return handler(_req, { env: { DB: {} }, userId: "u_me", email: "[email protected]", params })
+ }),
+}))
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server")
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) =>
+ NextResponse.json({ error: message }, { status }),
+ }
+})
+
+import { POST } from "./route"
+
+const ctx = { params: { requestId: "bar_1" } } as any
+
+describe("POST /api/community/friends/bot-request/[requestId]/cancel", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetApprovalRequest.mockResolvedValue({
+ id: "bar_1",
+ botId: "u_bot",
+ status: "pending",
+ kind: "friend",
+ serverId: null,
+ requestedByUserId: "u_me",
+ })
+ mockResolveApprovalRequest.mockResolvedValue(undefined)
+ })
+
+ it("cancels the caller's own pending bot friend-request", async () => {
+ const res = await POST({} as any, ctx)
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ status: "cancelled" })
+ expect(mockResolveApprovalRequest).toHaveBeenCalledWith(expect.anything(), "bar_1", "denied")
+ expect(mockLogAudit).toHaveBeenCalled()
+ })
+
+ it("returns 404 when the request belongs to a different requester", async () => {
+ mockGetApprovalRequest.mockResolvedValue({
+ id: "bar_1", botId: "u_bot", status: "pending", kind: "friend",
+ serverId: null, requestedByUserId: "u_other",
+ })
+ const res = await POST({} as any, ctx)
+ expect(res.status).toBe(404)
+ expect(mockResolveApprovalRequest).not.toHaveBeenCalled()
+ })
+
+ it("returns 404 when the request is not a friend kind", async () => {
+ mockGetApprovalRequest.mockResolvedValue({
+ id: "bar_1", botId: "u_bot", status: "pending", kind: "join_server",
+ serverId: "s_1", requestedByUserId: "u_me",
+ })
+ const res = await POST({} as any, ctx)
+ expect(res.status).toBe(404)
+ })
+
+ it("returns 400 when the request is already resolved", async () => {
+ mockGetApprovalRequest.mockResolvedValue({
+ id: "bar_1", botId: "u_bot", status: "approved", kind: "friend",
+ serverId: null, requestedByUserId: "u_me",
+ })
+ const res = await POST({} as any, ctx)
+ expect(res.status).toBe(400)
+ expect(mockResolveApprovalRequest).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/app/api/community/friends/bot-request/[requestId]/cancel/route.ts b/src/web/src/app/api/community/friends/bot-request/[requestId]/cancel/route.ts
new file mode 100644
index 000000000..f70d337cb
--- /dev/null
+++ b/src/web/src/app/api/community/friends/bot-request/[requestId]/cancel/route.ts
@@ -0,0 +1,40 @@
+import { queries } from "@alook/shared"
+import { getDb } from "@/lib/db"
+import { withAuth } from "@/lib/middleware/auth"
+import { writeJSON, writeError } from "@/lib/middleware/helpers"
+import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"
+
+/**
+ * Requester-side cancel of a pending bot friend-request. Mirror of the owner's
+ * `deny` but authorized by `requestedByUserId === ctx.userId` — the requester
+ * withdraws their own outgoing request. Flipping the row out of `pending`
+ * frees the partial unique index so the requester can send again later.
+ */
+export const POST = withAuth(async (_req, ctx) => {
+ const requestId = ctx.params?.requestId as string
+ const db = getDb(ctx.env.DB)
+
+ const request = await queries.communityBot.getApprovalRequest(db, requestId)
+ if (!request || request.kind !== "friend") {
+ return writeError("friend request not found", 404)
+ }
+ if (request.requestedByUserId !== ctx.userId) {
+ return writeError("friend request not found", 404)
+ }
+ if (request.status !== "pending") {
+ return writeError("request already resolved", 400)
+ }
+
+ await queries.communityBot.resolveApprovalRequest(db, requestId, "denied")
+
+ logAudit(db, {
+ serverId: null,
+ actorId: ctx.userId,
+ action: COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_CANCELLED,
+ targetType: "user",
+ targetId: request.botId,
+ changes: JSON.stringify({ botId: request.botId, requestedByUserId: ctx.userId }),
+ })
+
+ return writeJSON({ status: "cancelled" })
+})
diff --git a/src/web/src/app/api/community/friends/pending/route.test.ts b/src/web/src/app/api/community/friends/pending/route.test.ts
index 1951301f8..6246c59ad 100644
--- a/src/web/src/app/api/community/friends/pending/route.test.ts
+++ b/src/web/src/app/api/community/friends/pending/route.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
const listPending = vi.fn()
+const listPendingBotRequests = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
@@ -13,6 +14,9 @@ vi.mock("@alook/shared", async () => {
communityFriendship: {
listPending: (...a: unknown[]) => listPending(...a),
},
+ communityBot: {
+ listPendingFriendRequestsByRequester: (...a: unknown[]) => listPendingBotRequests(...a),
+ },
},
}
})
@@ -46,10 +50,27 @@ describe("GET /api/community/friends/pending", () => {
listPending.mockResolvedValue([
{ id: "fr_1", userId: "u_person", name: "Ada", image: null, kind: "incoming" },
])
+ listPendingBotRequests.mockResolvedValue([])
const res = await GET(req, {} as never)
expect(res.status).toBe(200)
const body = await res.json() as { pending: Array<{ id: string; userId: string }> }
expect(body.pending[0].id).toBe("fr_1")
expect(body.pending[0].userId).toBe("u_person")
})
+
+ it("merges outgoing bot friend-requests tagged source:'bot' with the approval-request id", async () => {
+ listPending.mockResolvedValue([
+ { id: "fr_1", userId: "u_person", name: "Ada", image: null, kind: "outgoing" },
+ ])
+ listPendingBotRequests.mockResolvedValue([
+ { id: "bar_1", botUserId: "u_bot", name: "HelperBot", image: null, createdAt: "2026-01-01T00:00:00Z" },
+ ])
+ const res = await GET(req, {} as never)
+ expect(res.status).toBe(200)
+ const body = await res.json() as { pending: Array<{ id: string; userId: string; kind: string; source: string }> }
+ const human = body.pending.find((p) => p.id === "fr_1")!
+ const bot = body.pending.find((p) => p.id === "bar_1")!
+ expect(human.source).toBe("friend")
+ expect(bot).toMatchObject({ userId: "u_bot", kind: "outgoing", source: "bot" })
+ })
})
diff --git a/src/web/src/app/api/community/friends/pending/route.ts b/src/web/src/app/api/community/friends/pending/route.ts
index f17f0ab3c..514df81de 100644
--- a/src/web/src/app/api/community/friends/pending/route.ts
+++ b/src/web/src/app/api/community/friends/pending/route.ts
@@ -7,17 +7,35 @@ import { avatarInitial } from "@/lib/community/avatar"
export const GET = withAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
type PendingRow = Awaited<ReturnType<typeof queries.communityFriendship.listPending>>[number]
- const { value, stale } = await readOrStale<{ rows: PendingRow[] }>(
- async () => ({ rows: await queries.communityFriendship.listPending(db, ctx.userId) }),
- { rows: [] },
+ type BotRow = Awaited<ReturnType<typeof queries.communityBot.listPendingFriendRequestsByRequester>>[number]
+ const { value, stale } = await readOrStale<{ rows: PendingRow[]; botRows: BotRow[] }>(
+ async () => ({
+ rows: await queries.communityFriendship.listPending(db, ctx.userId),
+ botRows: await queries.communityBot.listPendingFriendRequestsByRequester(db, ctx.userId),
+ }),
+ { rows: [], botRows: [] },
{ route: "community/friends/pending" },
)
- const pending = value.rows.map((r) => ({
- id: r.id,
- userId: r.userId,
- name: r.name,
- avatar: r.image ?? avatarInitial(r.name),
- kind: r.kind,
- }))
+ const pending = [
+ ...value.rows.map((r) => ({
+ id: r.id,
+ userId: r.userId,
+ name: r.name,
+ avatar: r.image ?? avatarInitial(r.name),
+ kind: r.kind,
+ source: "friend" as const,
+ })),
+ // Outgoing bot friend-requests live in community_bot_approval_request (not
+ // community_friendship); `id` is the approval-request id, cancelled via the
+ // requester-side bot-cancel endpoint.
+ ...value.botRows.map((r) => ({
+ id: r.id,
+ userId: r.botUserId,
+ name: r.name,
+ avatar: r.image ?? avatarInitial(r.name),
+ kind: "outgoing" as const,
+ source: "bot" as const,
+ })),
+ ]
return writeJSON(stale ? { pending, stale: true } : { pending })
})
diff --git a/src/web/src/app/c/me/page.tsx b/src/web/src/app/c/me/page.tsx
index dcfcb5e67..4fae92a49 100644
--- a/src/web/src/app/c/me/page.tsx
+++ b/src/web/src/app/c/me/page.tsx
@@ -12,6 +12,7 @@ import {
useSendFriendRequest,
useAcceptFriendRequest,
useRejectFriendRequest,
+ useCancelBotFriendRequest,
useRemoveFriend,
useBlockUser,
useUnblockUser,
@@ -44,6 +45,7 @@ export default function MeFriendsPage() {
const sendFriendRequest = useSendFriendRequest()
const acceptFriendRequest = useAcceptFriendRequest()
const rejectFriendRequest = useRejectFriendRequest()
+ const cancelBotFriendRequest = useCancelBotFriendRequest()
const removeFriend = useRemoveFriend()
const blockUser = useBlockUser()
const unblockUser = useUnblockUser()
@@ -71,11 +73,16 @@ export default function MeFriendsPage() {
{ onError: (e) => toastApiError(e, "Failed to reject request") },
)
}
- onCancelRequest={(id) =>
- rejectFriendRequest.mutate(
- { friendshipId: id },
- { onError: (e) => toastApiError(e, "Failed to cancel request") },
- )
+ onCancelRequest={({ id, source }) =>
+ source === "bot"
+ ? cancelBotFriendRequest.mutate(
+ { requestId: id },
+ { onError: (e) => toastApiError(e, "Failed to cancel request") },
+ )
+ : rejectFriendRequest.mutate(
+ { friendshipId: id },
+ { onError: (e) => toastApiError(e, "Failed to cancel request") },
+ )
}
onUnblock={(id) =>
unblockUser.mutate(
@@ -86,9 +93,9 @@ export default function MeFriendsPage() {
},
)
}
- onSendRequest={async (username) => {
+ onSendRequest={async ({ userId, username }) => {
try {
- await sendFriendRequest.mutateAsync({ username })
+ await sendFriendRequest.mutateAsync({ userId, username })
toast("Friend request sent")
} catch (e) {
toastApiError(e, "Failed to send friend request")
diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.ts
index 42140f08b..4b4863f57 100644
--- a/src/web/src/components/community/_types.ts
+++ b/src/web/src/components/community/_types.ts
@@ -219,6 +219,10 @@ export type PendingRequest = {
name: string
avatar: string
kind: "incoming" | "outgoing"
+ // "bot" outgoing rows are bot approval-requests (id = approval-request id),
+ // cancelled via the requester-side bot-cancel endpoint. Absent/"friend" =
+ // a real community_friendship row.
+ source?: "friend" | "bot"
}
export type BlockedUser = { id: string; userId?: string; name: string; avatar: string }
diff --git a/src/web/src/components/community/bots/bot-activity-modal.tsx b/src/web/src/components/community/bots/bot-activity-modal.tsx
index 2f67c0202..6e56b16b6 100644
--- a/src/web/src/components/community/bots/bot-activity-modal.tsx
+++ b/src/web/src/components/community/bots/bot-activity-modal.tsx
@@ -164,7 +164,7 @@ export function BotActivityModal({
className="flex h-[72vh] max-h-170 w-full max-w-2xl flex-col gap-0 overflow-hidden p-0 sm:max-w-2xl"
>
<header className="flex shrink-0 items-center gap-3 border-b border-border/40 px-4 py-3">
- <AgentAvatar name={bot?.name ?? ""} avatarUrl={bot?.image ?? null} size={32} />
+ <AgentAvatar name={bot?.name ?? ""} avatarUrl={bot?.image ?? null} seed={bot?.id} size={32} />
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<DialogTitle className="truncate text-sm font-medium">
{bot?.name ?? "Bot"}
diff --git a/src/web/src/components/community/bots/bot-list.tsx b/src/web/src/components/community/bots/bot-list.tsx
index d444156b1..800c7c387 100644
--- a/src/web/src/components/community/bots/bot-list.tsx
+++ b/src/web/src/components/community/bots/bot-list.tsx
@@ -221,7 +221,7 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {
<Card key={bot.id} className="flex flex-col gap-3 p-4">
<div className="flex items-start justify-between gap-3">
<div className="flex min-w-0 items-start gap-3">
- <AgentAvatar name={bot.name} avatarUrl={bot.image} size={40} />
+ <AgentAvatar name={bot.name} avatarUrl={bot.image} seed={bot.id} size={40} />
<div className="flex min-w-0 flex-col gap-1">
<div className="flex items-center gap-2">
<span className="truncate text-[15px] font-medium text-foreground">
diff --git a/src/web/src/components/community/composer.tsx b/src/web/src/components/community/composer.tsx
index cbf066faf..22ac0c786 100644
--- a/src/web/src/components/community/composer.tsx
+++ b/src/web/src/components/community/composer.tsx
@@ -582,7 +582,16 @@ function MentionRow({ item, selected, showMembersHeader, onSelect }: {
</span>
)}
<span className="font-medium">
- {item.kind === "member" ? item.label : `@${item.label}`}
+ {item.kind === "member" ? (
+ <>
+ {item.name}
+ <span className="ml-1 text-xs font-normal tracking-wide text-muted-foreground">
+ #{item.discriminator}
+ </span>
+ </>
+ ) : (
+ `@${item.label}`
+ )}
</span>
{item.kind !== "member" && (
<span className="ml-auto text-xs text-muted-foreground">
diff --git a/src/web/src/components/community/friends-page.tsx b/src/web/src/components/community/friends-page.tsx
index 3d4c1dc0e..d0fe6ae89 100644
--- a/src/web/src/components/community/friends-page.tsx
+++ b/src/web/src/components/community/friends-page.tsx
@@ -4,7 +4,6 @@ import { useState, useEffect, useMemo, useRef } from "react"
import type React from "react"
import { Users, MessagesSquare, ChevronLeft, Check, X, AtSign, UserMinus, Ban, UserPlus, Search } from "lucide-react"
import { apiFetch, toastApiError } from "@/lib/api/client"
-import { isImeConfirming } from "@/lib/ime"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"
@@ -15,7 +14,7 @@ import { avatarInitial } from "@/lib/community/avatar"
import { EmptyState } from "./empty-state"
import { hasStatus } from "./status-presets"
import type { Friend, PendingRequest, BlockedUser, OpenProfile } from "./_types"
-import { isSelfBotFriendship, isPresenceOffline } from "@alook/shared"
+import { isSelfBotFriendship, isPresenceOffline, MIN_SEARCH_LENGTH } from "@alook/shared"
function FriendSection({ title, count, emptyLabel, children }: {
title: string
@@ -44,9 +43,9 @@ export function FriendsPage({
onOpenProfile?: OpenProfile
onAccept?: (id: string) => void
onReject?: (id: string) => void
- onCancelRequest?: (id: string) => void
+ onCancelRequest?: (req: { id: string; source?: "friend" | "bot" }) => void
onUnblock?: (id: string) => void
- onSendRequest?: (username: string) => void
+ onSendRequest?: (target: { userId: string; username: string }) => void
onRemoveFriend?: (id: string) => void
onBlock?: (id: string) => void
onDm?: (userId: string) => void
@@ -66,10 +65,27 @@ export function FriendsPage({
const [searchResults, setSearchResults] = useState<{ id: string; name: string; image: string | null; discriminator: string }[]>([])
const debounceRef = useRef<ReturnType<typeof setTimeout>>(null)
+ // Relationship state by user id, so search results can show Friends/Pending/
+ // Blocked and disable the add action. `Friend`/`BlockedUser` userId is
+ // optional (the Map's string key type forces the skip). Set pending → friend
+ // → blocked so blocked overwrites and wins precedence.
+ const relById = useMemo(() => {
+ const m = new Map<string, "friend" | "pending" | "blocked">()
+ for (const p of pending) if (p.userId) m.set(p.userId, "pending")
+ for (const f of friends) if (f.userId) m.set(f.userId, "friend")
+ for (const b of blocked) if (b.userId) m.set(b.userId, "blocked")
+ return m
+ }, [friends, pending, blocked])
+
+ const incoming = useMemo(() => pending.filter((p) => p.kind === "incoming"), [pending])
+ const outgoing = useMemo(() => pending.filter((p) => p.kind === "outgoing"), [pending])
+
useEffect(() => {
if (debounceRef.current) clearTimeout(debounceRef.current)
const q = addValue.trim()
- if (!q) { setSearchResults([]); return }
+ // Below the server minimum the API 400s ("query must be at least N
+ // characters"); don't fire — just clear results, no error toast.
+ if (q.length < MIN_SEARCH_LENGTH) { setSearchResults([]); return }
debounceRef.current = setTimeout(async () => {
try {
const data = await apiFetch<{ users: { id: string; name: string; image: string | null; discriminator: string }[] }>(`/api/community/users/search?q=${encodeURIComponent(q)}`)
@@ -82,8 +98,8 @@ export function FriendsPage({
return () => { if (debounceRef.current) clearTimeout(debounceRef.current) }
}, [addValue])
- const sendRequest = (name: string) => {
- onSendRequest?.(name)
+ const sendRequest = (u: { id: string; name: string; discriminator: string }) => {
+ onSendRequest?.({ userId: u.id, username: `${u.name}#${u.discriminator}` })
setAddValue("")
setSearchResults([])
}
@@ -196,45 +212,42 @@ export function FriendsPage({
<div className="mb-4">
<div className="text-xs font-semibold text-muted-foreground">Add a friend</div>
<div className="relative mt-2">
- <div className="relative flex items-center gap-2">
- <div className="relative flex-1">
- <AtSign className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
- <Input
- className="h-11 pl-9"
- placeholder="Search by username"
- value={addValue}
- onChange={(e) => setAddValue(e.target.value)}
- onKeyDown={(e) => { if (isImeConfirming(e)) return; if (e.key === "Enter" && addValue.trim()) sendRequest(addValue.trim()) }}
- />
- </div>
- <Button
- size="sm"
- className="h-11 px-4"
- disabled={!addValue.trim()}
- onClick={() => { if (addValue.trim()) sendRequest(addValue.trim()) }}
- >
- <UserPlus className="size-4" />
- Send request
- </Button>
+ <div className="relative">
+ <AtSign className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ className="h-11 pl-9"
+ placeholder="Search by username"
+ value={addValue}
+ onChange={(e) => setAddValue(e.target.value)}
+ />
</div>
{searchResults.length > 0 && (
<div className="mt-1 rounded-md border border-border bg-popover p-1 shadow-(--e2)">
- {searchResults.map((u) => (
- <button
- key={u.id}
- onClick={() => sendRequest(u.name)}
- className="flex w-full items-center gap-3 rounded-md px-3 py-2 text-left hover:bg-accent"
- >
- <Avatar label={u.image ?? avatarInitial(u.name)} seed={u.id} size={28} />
- <span className="flex-1 min-w-0 truncate text-sm font-medium">
- {u.name}
- <span className="ml-1 text-xs font-normal tracking-wide text-muted-foreground">
- #{u.discriminator}
+ {searchResults.map((u) => {
+ const rel = relById.get(u.id)
+ const relLabel = rel === "friend" ? "Friends" : rel === "pending" ? "Pending" : rel === "blocked" ? "Blocked" : null
+ return (
+ <button
+ key={u.id}
+ onClick={() => { if (!rel) sendRequest(u) }}
+ disabled={!!rel}
+ className="flex w-full items-center gap-3 rounded-md px-3 py-2 text-left hover:bg-accent disabled:cursor-not-allowed disabled:hover:bg-transparent"
+ >
+ <Avatar label={u.image ?? avatarInitial(u.name)} seed={u.id} size={28} />
+ <span className={`flex-1 min-w-0 truncate text-sm font-medium ${rel ? "text-muted-foreground" : ""}`}>
+ {u.name}
+ <span className="ml-1 text-xs font-normal tracking-wide text-muted-foreground">
+ #{u.discriminator}
+ </span>
</span>
- </span>
- <UserPlus className="size-4 shrink-0 text-muted-foreground" />
- </button>
- ))}
+ {relLabel ? (
+ <span className="shrink-0 text-xs text-muted-foreground">{relLabel}</span>
+ ) : (
+ <UserPlus className="size-4 shrink-0 text-muted-foreground" />
+ )}
+ </button>
+ )
+ })}
</div>
)}
</div>
@@ -245,30 +258,42 @@ export function FriendsPage({
<div className="mb-2 text-xs font-semibold text-muted-foreground">Pending — …</div>
<FriendRowsSkeleton withActions />
</div>
- ) : pending.length > 0 ? (
- <div>
- <div className="mb-2 text-xs font-semibold text-muted-foreground">Pending — {pending.length}</div>
- <div className="flex flex-col gap-1">
- {pending.map((p) => (
- <div key={p.id} className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent">
- <Avatar label={p.avatar} seed={p.userId} size={32} />
- <div className="min-w-0 flex-1">
- <div className="truncate text-sm font-medium">{p.name}</div>
- <div className="text-xs text-muted-foreground">{p.kind === "incoming" ? "Incoming request" : "Outgoing request"}</div>
- </div>
- {p.kind === "incoming" ? (
- <div className="flex gap-2">
- <Button variant="secondary" size="icon-sm" onClick={() => onAccept?.(p.id)} className="rounded-full text-status-online" aria-label="Accept"><Check className="size-4" /></Button>
- <Button variant="secondary" size="icon-sm" onClick={() => onReject?.(p.id)} className="rounded-full text-destructive" aria-label="Reject"><X className="size-4" /></Button>
+ ) : (
+ <>
+ {incoming.length > 0 && (
+ <div>
+ <div className="mb-2 text-xs font-semibold text-muted-foreground">Incoming — {incoming.length}</div>
+ <div className="flex flex-col gap-1">
+ {incoming.map((p) => (
+ <div key={p.id} className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent">
+ <Avatar label={p.avatar} seed={p.userId} size={32} />
+ <div className="min-w-0 flex-1 truncate text-sm font-medium">{p.name}</div>
+ <div className="flex gap-2">
+ <Button variant="secondary" size="icon-sm" onClick={() => onAccept?.(p.id)} className="rounded-full text-status-online" aria-label="Accept"><Check className="size-4" /></Button>
+ <Button variant="secondary" size="icon-sm" onClick={() => onReject?.(p.id)} className="rounded-full text-destructive" aria-label="Reject"><X className="size-4" /></Button>
+ </div>
</div>
- ) : (
- <Button variant="secondary" size="icon-sm" onClick={() => onCancelRequest?.(p.id)} className="rounded-full" aria-label="Cancel"><X className="size-4" /></Button>
- )}
+ ))}
</div>
- ))}
- </div>
- </div>
- ) : null}
+ </div>
+ )}
+
+ {outgoing.length > 0 && (
+ <div className={incoming.length > 0 ? "mt-8" : ""}>
+ <div className="mb-2 text-xs font-semibold text-muted-foreground">Outgoing — {outgoing.length}</div>
+ <div className="flex flex-col gap-1">
+ {outgoing.map((p) => (
+ <div key={p.id} className="flex items-center gap-3 rounded-md px-2 py-2 hover:bg-accent">
+ <Avatar label={p.avatar} seed={p.userId} size={32} />
+ <div className="min-w-0 flex-1 truncate text-sm font-medium">{p.name}</div>
+ <Button variant="secondary" size="icon-sm" onClick={() => onCancelRequest?.({ id: p.id, source: p.source })} className="rounded-full" aria-label="Cancel"><X className="size-4" /></Button>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </>
+ )}
</TabsContent>
</div>
</Tabs>
diff --git a/src/web/src/components/community/member-list.tsx b/src/web/src/components/community/member-list.tsx
index 54632c3c4..2cd5dbe62 100644
--- a/src/web/src/components/community/member-list.tsx
+++ b/src/web/src/components/community/member-list.tsx
@@ -354,7 +354,7 @@ function MemberRow({
<div className={`truncate text-sm leading-tight ${isPresenceOffline(mem.status) ? "text-muted-foreground" : ""}`}>
{mem.name}
{showDiscriminator && mem.discriminator && (
- <span className="text-muted-foreground">#{mem.discriminator}</span>
+ <span className="ml-1 text-xs font-normal tracking-wide text-muted-foreground">#{mem.discriminator}</span>
)}
</div>
{hasStatus(mem.statusEmoji, mem.statusText) && (
diff --git a/src/web/src/hooks/community/mutations/friends.test.ts b/src/web/src/hooks/community/mutations/friends.test.ts
index 51ace38f0..6874e0fba 100644
--- a/src/web/src/hooks/community/mutations/friends.test.ts
+++ b/src/web/src/hooks/community/mutations/friends.test.ts
@@ -75,6 +75,15 @@ describe("useSendFriendRequest — invalidates friends on success", () => {
}),
).toBe(true)
})
+
+ it("posts both userId and the name#discriminator handle when given both", async () => {
+ apiFetchMock.mockResolvedValueOnce(undefined)
+ const mod = await load()
+ mod.useSendFriendRequest()
+ await runMutation({ userId: "u_1", username: "alice#0042" })
+ const body = JSON.parse((apiFetchMock.mock.calls[0][1] as { body: string }).body)
+ expect(body).toEqual({ userId: "u_1", username: "alice#0042" })
+ })
})
describe("useAcceptFriendRequest — rollback", () => {
@@ -93,6 +102,40 @@ describe("useAcceptFriendRequest — rollback", () => {
})
})
+describe("useCancelBotFriendRequest — optimistic + rollback", () => {
+ it("posts to the bot-cancel route and optimistically drops the outgoing bot row", async () => {
+ capturedQc.setQueryData(communityKeys.friends(), {
+ friends: [],
+ blocked: [],
+ pending: [{ id: "bar_1", userId: "u_bot", name: "Bot", avatar: "B", kind: "outgoing", source: "bot" }],
+ })
+ apiFetchMock.mockResolvedValueOnce(undefined)
+ const mod = await load()
+ mod.useCancelBotFriendRequest()
+ await runMutation({ requestId: "bar_1" })
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/friends/bot-request/bar_1/cancel",
+ { method: "POST" },
+ )
+ const cache = capturedQc.getQueryData<{ pending: { id: string }[] }>(communityKeys.friends())
+ expect(cache?.pending).toHaveLength(0)
+ })
+
+ it("restores the outgoing row when the server rejects", async () => {
+ capturedQc.setQueryData(communityKeys.friends(), {
+ friends: [],
+ blocked: [],
+ pending: [{ id: "bar_1", userId: "u_bot", name: "Bot", avatar: "B", kind: "outgoing", source: "bot" }],
+ })
+ apiFetchMock.mockRejectedValueOnce(new Error("boom"))
+ const mod = await load()
+ mod.useCancelBotFriendRequest()
+ await runMutation({ requestId: "bar_1" }).catch(() => {})
+ const cache = capturedQc.getQueryData<{ pending: { id: string }[] }>(communityKeys.friends())
+ expect(cache?.pending).toHaveLength(1)
+ })
+})
+
describe("useRemoveFriend — optimistic + rollback", () => {
it("optimistically drops the friend and restores on failure", async () => {
capturedQc.setQueryData(communityKeys.friends(), {
diff --git a/src/web/src/hooks/community/mutations/friends.ts b/src/web/src/hooks/community/mutations/friends.ts
index 16a828fd6..c1899e2f8 100644
--- a/src/web/src/hooks/community/mutations/friends.ts
+++ b/src/web/src/hooks/community/mutations/friends.ts
@@ -19,15 +19,15 @@ import type { FriendsResponse } from "@/hooks/community/use-friends"
// ── Send friend request ────────────────────────────────────────────────────
-export type SendFriendRequestArgs = { username: string }
+export type SendFriendRequestArgs = { username?: string; userId?: string }
export function useSendFriendRequest() {
const queryClient = useQueryClient()
return useMutation<void, Error, SendFriendRequestArgs>({
- mutationFn: async ({ username }) => {
+ mutationFn: async ({ username, userId }) => {
await apiFetch("/api/community/friends/request", {
method: "POST",
- body: JSON.stringify({ username }),
+ body: JSON.stringify({ userId, username }),
})
},
onSuccess: () => {
@@ -95,6 +95,37 @@ export function useRemoveFriend() {
)
}
+// ── Cancel outgoing bot friend-request ─────────────────────────────────────
+//
+// Bot requests live in community_bot_approval_request, not community_friendship,
+// so cancel hits a dedicated requester-side endpoint keyed by the approval id.
+
+export type CancelBotFriendRequestArgs = { requestId: string }
+
+export function useCancelBotFriendRequest() {
+ const queryClient = useQueryClient()
+ return useMutation<void, Error, CancelBotFriendRequestArgs, { snapshot: FriendsResponse | undefined }>({
+ mutationFn: async ({ requestId }) => {
+ await apiFetch(`/api/community/friends/bot-request/${requestId}/cancel`, { method: "POST" })
+ },
+ onMutate: async ({ requestId }) => {
+ const key = communityKeys.friends()
+ await queryClient.cancelQueries({ queryKey: key })
+ const snapshot = queryClient.getQueryData<FriendsResponse>(key)
+ queryClient.setQueryData<FriendsResponse | undefined>(key, (prev) =>
+ prev ? { ...prev, pending: prev.pending.filter((p) => p.id !== requestId) } : prev,
+ )
+ return { snapshot }
+ },
+ onError: (_err, _args, ctx) => {
+ if (ctx?.snapshot) queryClient.setQueryData(communityKeys.friends(), ctx.snapshot)
+ },
+ onSuccess: () => {
+ void queryClient.invalidateQueries({ queryKey: communityKeys.friends() })
+ },
+ })
+}
+
// ── Block / unblock ────────────────────────────────────────────────────────
export type BlockUserArgs = { userId: string }
diff --git a/src/web/src/lib/community/audit.ts b/src/web/src/lib/community/audit.ts
index a9ffb9bac..8750d396d 100644
--- a/src/web/src/lib/community/audit.ts
+++ b/src/web/src/lib/community/audit.ts
@@ -25,6 +25,8 @@ export const COMMUNITY_AUDIT_ACTIONS = {
BOT_FRIEND_REQUESTED: "community.bot.friend_requested",
BOT_FRIEND_APPROVED: "community.bot.friend_approved",
BOT_FRIEND_DENIED: "community.bot.friend_denied",
+ /** Requester withdrew their own pending bot friend-request. */
+ BOT_FRIEND_CANCELLED: "community.bot.friend_cancelled",
MESSAGE_AUTHORED_AS_BOT: "community.message.authored_as_bot",
} as const
diff --git a/src/web/src/lib/community/mention-extension.test.ts b/src/web/src/lib/community/mention-extension.test.ts
index 32910f6ea..2a004d06e 100644
--- a/src/web/src/lib/community/mention-extension.test.ts
+++ b/src/web/src/lib/community/mention-extension.test.ts
@@ -121,6 +121,18 @@ describe("rankMentionItems", () => {
expect((item as { userId: string }).userId).toBe("u_person")
})
+ it("exposes name and discriminator separately so the popover can mute the tag", () => {
+ // The row displays `name` + a muted `#discriminator` span, but `label` must
+ // stay the concatenated `name#discriminator` token used for insertion.
+ const memberRoster: Member[] = [
+ { id: "m_row", userId: "u_person", name: "Alice", discriminator: "0042", avatar: "A", status: "online", sub: "", role: "member" },
+ ]
+ const item = rankMentionItems(memberRoster, "channel", "al").find((i) => i.kind === "member")! as { name: string; discriminator: string; label: string }
+ expect(item.name).toBe("Alice")
+ expect(item.discriminator).toBe("0042")
+ expect(item.label).toBe("Alice#0042")
+ })
+
it("ranks substring members after prefix members", () => {
const memberRoster: Member[] = [
{ id: "m_al", userId: "u_al", name: "Alberta", discriminator: "0001", avatar: "A", status: "online", sub: "", role: "member" },
diff --git a/src/web/src/lib/community/mention-extension.ts b/src/web/src/lib/community/mention-extension.ts
index 59cacf926..244e81474 100644
--- a/src/web/src/lib/community/mention-extension.ts
+++ b/src/web/src/lib/community/mention-extension.ts
@@ -8,7 +8,12 @@ type MemberMentionItem = {
kind: "member"
id: string
userId: string
+ // `label` stays name#discriminator — it's the mention token serialized into
+ // the message and used for insertion. `name`/`discriminator` are split out
+ // so the popover row can render the tag with the muted canonical styling.
label: string
+ name: string
+ discriminator: string
avatar: string
status: "online" | "offline"
}
@@ -70,6 +75,8 @@ export function rankMentionItems(
id: m.id,
userId: m.userId,
label: `${m.name}#${m.discriminator}`,
+ name: m.name,
+ discriminator: m.discriminator,
avatar: m.avatar,
status: m.status,
}