Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): surface real error messages instead of generic "Failed to X"

Guseb8a45c05198
diff --git a/src/web/src/app/api/community/daemon/activate/route.test.ts b/src/web/src/app/api/community/daemon/activate/route.test.ts
index d30c7fb82..1529e59ae 100644
--- a/src/web/src/app/api/community/daemon/activate/route.test.ts
+++ b/src/web/src/app/api/community/daemon/activate/route.test.ts
@@ -9,7 +9,7 @@ vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
// The activate route also broadcasts machine.created — stub that.
vi.mock("@/lib/broadcast", () => ({
- broadcastToUser: vi.fn(async () => {}),
+ broadcastToUser: vi.fn(async () => { }),
}))
const mockActivate = vi.fn()
@@ -138,4 +138,13 @@ describe("POST /api/community/daemon/activate", () => {
const res = await POST(jsonReq(goodBody, { Authorization: "Bearer cmt_old" }))
expect(res.status).toBe(410)
})
+
+ it("500 body includes the underlying exception's message for an unhandled failure", async () => {
+ mockActivate.mockRejectedValue(new Error("D1_ERROR: database is locked"))
+ const res = await POST(jsonReq(goodBody, { Authorization: "Bearer cmt_boom" }))
+ expect(res.status).toBe(500)
+ expect(await res.json()).toEqual({
+ error: "activate failed: D1_ERROR: database is locked",
+ })
+ })
})
diff --git a/src/web/src/app/api/community/daemon/activate/route.ts b/src/web/src/app/api/community/daemon/activate/route.ts
index afbeb40f8..21d38b23a 100644
--- a/src/web/src/app/api/community/daemon/activate/route.ts
+++ b/src/web/src/app/api/community/daemon/activate/route.ts
@@ -95,6 +95,9 @@ export const POST = withCommunityPairingToken(async (req, ctx) => {
}
}
log.error("activate failed", { err: err instanceof Error ? err.message : String(err) })
- return NextResponse.json({ error: "activate failed" }, { status: 500 })
+ return NextResponse.json(
+ { error: err instanceof Error ? `activate failed: ${err.message}` : "activate failed" },
+ { status: 500 }
+ )
}
})
diff --git a/src/web/src/app/api/community/servers/[id]/bots/route.test.ts b/src/web/src/app/api/community/servers/[id]/bots/route.test.ts
new file mode 100644
index 000000000..6e5e3fc6a
--- /dev/null
+++ b/src/web/src/app/api/community/servers/[id]/bots/route.test.ts
@@ -0,0 +1,142 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { NextRequest } from "next/server"
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}))
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+
+const mockGetMember = vi.fn()
+const mockGetUserInternal = vi.fn()
+const mockAddMember = vi.fn()
+const mockGetUserSelf = vi.fn()
+const mockAreFriends = vi.fn()
+const mockFindPendingJoinRequest = vi.fn()
+const mockCreateOrGetDM = vi.fn()
+const mockCreateApprovalRequestStatement = vi.fn()
+const mockHardDeleteMessage = vi.fn()
+const mockLogError = vi.fn()
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ createLogger: () => ({
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: (...a: unknown[]) => mockLogError(...a),
+ debug: vi.fn(),
+ }),
+ queries: {
+ communityMember: {
+ getMember: (...a: unknown[]) => mockGetMember(...a),
+ addMember: (...a: unknown[]) => mockAddMember(...a),
+ },
+ user: {
+ getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),
+ getUserSelf: (...a: unknown[]) => mockGetUserSelf(...a),
+ },
+ communityFriendship: {
+ areFriends: (...a: unknown[]) => mockAreFriends(...a),
+ },
+ communityBot: {
+ findPendingJoinRequest: (...a: unknown[]) => mockFindPendingJoinRequest(...a),
+ createApprovalRequestStatement: (...a: unknown[]) => mockCreateApprovalRequestStatement(...a),
+ },
+ communityDm: {
+ createOrGetDM: (...a: unknown[]) => mockCreateOrGetDM(...a),
+ },
+ communityMessage: {
+ hardDeleteMessage: (...a: unknown[]) => mockHardDeleteMessage(...a),
+ },
+ },
+ }
+})
+
+vi.mock("@/lib/community/fanout", () => ({
+ fanOutToServerMembers: vi.fn(),
+ broadcastToUserSafe: vi.fn(),
+}))
+
+vi.mock("@/lib/community/audit", async () => {
+ const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")
+ return { ...actual, logAudit: vi.fn() }
+})
+
+const mockCreateCommunityMessage = vi.fn()
+vi.mock("@/lib/community/message-handler", () => ({
+ createCommunityMessage: (...a: unknown[]) => mockCreateCommunityMessage(...a),
+}))
+
+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: "u1", email: "[email protected]", params })
+ }),
+}))
+
+import { POST } from "./route"
+
+const ctx = { params: { id: "s1" } } as any
+function req(body: unknown) {
+ return new NextRequest("http://localhost/api/community/servers/s1/bots", {
+ method: "POST",
+ body: JSON.stringify(body),
+ })
+}
+
+describe("POST /servers/[id]/bots — approval-request rollback failure", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ // Friend-of-bot-add (Path B): caller is a member, target is a bot owned
+ // by someone else, caller is friends with the bot.
+ mockGetMember.mockResolvedValue({ id: "m1", nickname: "Casey" })
+ mockGetUserInternal.mockResolvedValue({
+ id: "bot1",
+ isBot: true,
+ deletedAt: null,
+ ownerUserId: "owner1",
+ name: "Bot",
+ })
+ mockAreFriends.mockResolvedValue(true)
+ mockFindPendingJoinRequest.mockResolvedValue(null)
+ mockCreateOrGetDM.mockResolvedValue({ id: "dm1" })
+ mockCreateCommunityMessage.mockResolvedValue({
+ ok: true,
+ row: { id: "msg1", content: "Casey wants to add me to a server. Approve?", createdAt: "2026-01-01T00:00:00Z" },
+ })
+ })
+
+ it("returns 500 with the rollback exception's message when both the approval-request insert AND the compensating delete fail", async () => {
+ mockCreateApprovalRequestStatement.mockRejectedValue(new Error("insert failed"))
+ mockHardDeleteMessage.mockRejectedValue(new Error("delete failed"))
+
+ const res = await POST(req({ botId: "bot1" }), ctx)
+
+ expect(res.status).toBe(500)
+ const body = await res.json()
+ expect(body.error).toContain("delete failed")
+ expect(body.error).toContain("approval request write failed")
+ expect(mockLogError).toHaveBeenCalledWith(
+ "approval_request_rollback_failed",
+ expect.objectContaining({
+ botId: "bot1",
+ serverId: "s1",
+ messageId: "msg1",
+ insertErr: expect.stringContaining("insert failed"),
+ rollbackErr: expect.stringContaining("delete failed"),
+ }),
+ )
+ })
+
+ it("returns 200 pending when the insert fails but the compensating delete succeeds (race lost, not a rollback failure)", async () => {
+ mockCreateApprovalRequestStatement.mockRejectedValue(new Error("insert failed"))
+ mockHardDeleteMessage.mockResolvedValue(undefined)
+
+ const res = await POST(req({ botId: "bot1" }), ctx)
+
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ status: "pending" })
+ })
+})
diff --git a/src/web/src/app/api/community/servers/[id]/bots/route.ts b/src/web/src/app/api/community/servers/[id]/bots/route.ts
index 7e6862c2f..e59d55989 100644
--- a/src/web/src/app/api/community/servers/[id]/bots/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/bots/route.ts
@@ -145,7 +145,10 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
insertErr: String(err),
rollbackErr: String(rollbackErr),
})
- return writeError("approval request write failed", 500)
+ return writeError(
+ `approval request write failed: ${rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr)}`,
+ 500
+ )
}
// Race lost — the peer request already exists. Report pending to keep
// the caller-facing shape identical to the idempotent case above.
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 ff8353131..71c8323c7 100644
--- a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx
+++ b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx
@@ -3,7 +3,7 @@
import { useCallback, useEffect, useMemo, useState } from "react"
import { useParams, useRouter } from "next/navigation"
import { toast } from "sonner"
-import { apiFetch } from "@/lib/api/client"
+import { apiFetch, toastApiError } from "@/lib/api/client"
import { useBreakpoint } from "@/hooks/use-mobile"
import { ChannelHeader, ChannelHeaderSkeleton, type ChannelNotifLevel } from "@/components/community/channel-header"
import { MessageList } from "@/components/community/message-list"
@@ -272,7 +272,10 @@ function ChannelView() {
parentMessageId: data.parentMessageId,
}),
)
- .catch(() => useCommunityStore.getState().setCurrentChannelMeta(null))
+ .catch((e) => {
+ useCommunityStore.getState().setCurrentChannelMeta(null)
+ toastApiError(e, "Failed to load thread")
+ })
} else {
useCommunityStore.getState().setCurrentChannelMeta(null)
}
@@ -314,7 +317,10 @@ function ChannelView() {
content: r.message.content,
createdAt: r.message.createdAt,
})))
- } catch { setSearchResults([]) }
+ } catch (e) {
+ setSearchResults([])
+ toastApiError(e, "Search failed")
+ }
}, [channelId])
// Find the channel name
@@ -389,12 +395,12 @@ function ChannelView() {
if (isPinned) {
unpinMessageMut.mutate({ channelId, messageId: id }, {
onSuccess: () => toast("Message unpinned"),
- onError: () => toast("Failed to unpin message"),
+ onError: (e) => toastApiError(e, "Failed to unpin message"),
})
} else {
pinMessageMut.mutate({ channelId, messageId: id }, {
onSuccess: () => toast("Message pinned"),
- onError: () => toast("Failed to pin message"),
+ onError: (e) => toastApiError(e, "Failed to pin message"),
})
setRightPanel("pinned")
}
@@ -405,8 +411,8 @@ function ChannelView() {
try {
const data = await createThreadMut.mutateAsync({ channelId, messageId: id, name })
router.push(`/community/channels/${params.serverId}/${data.id}`)
- } catch {
- toast("Failed to create thread")
+ } catch (e) {
+ toastApiError(e, "Failed to create thread")
}
},
onCopy: (id: string) => {
@@ -443,7 +449,10 @@ function ChannelView() {
if (attachments?.length) {
const results = await Promise.all(
attachments.map((a) =>
- uploadFileMut.mutateAsync({ target: { channelId }, file: a.file }).catch(() => null),
+ uploadFileMut.mutateAsync({ target: { channelId }, file: a.file }).catch((e) => {
+ toastApiError(e, "Failed to attach file")
+ return null
+ }),
),
)
uploadedAttachments = zipUploadResultsWithDimensions(results, attachments)
@@ -464,7 +473,7 @@ function ChannelView() {
const createForumPost = (post: { name: string; content: string; tags: string[] }) => {
createForumPostMut.mutate({ channelId, ...post }, {
- onError: () => toast("Failed to create post"),
+ onError: (e) => toastApiError(e, "Failed to create post"),
})
}
@@ -488,13 +497,13 @@ function ChannelView() {
onSetRole: (memberId: string, role: Role) => {
setMemberRoleMut.mutate({ serverId, memberId, role }, {
onSuccess: () => toast("Role updated"),
- onError: () => toast("Failed to update role"),
+ onError: (e) => toastApiError(e, "Failed to update role"),
})
},
onKickMember: (memberId: string) => {
kickMemberMut.mutate({ serverId, memberId }, {
onSuccess: () => toast("Member kicked"),
- onError: () => toast("Failed to kick member"),
+ onError: (e) => toastApiError(e, "Failed to kick member"),
})
},
onJumpToMessage: (id: string) => {
@@ -583,7 +592,7 @@ function ChannelView() {
body: JSON.stringify({ name }),
})
setLocalName(name)
- } catch { toast("Failed to rename") }
+ } catch (e) { toastApiError(e, "Failed to rename") }
} : undefined,
}}
/>
@@ -652,7 +661,9 @@ function ChannelView() {
rightPanel={rightPanel}
onToggle={togglePanel}
notifLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? "Use Server Default"}
- onSetNotifLevel={(l) => setChannelNotifMut.mutate({ channelId, level: l })}
+ onSetNotifLevel={(l) => setChannelNotifMut.mutate({ channelId, level: l }, {
+ onError: (e) => toastApiError(e, "Failed to update notification level"),
+ })}
onBack={bp === "mobile" ? goBack : undefined}
server={bp === "mobile" && currentServer ? { id: currentServer.id, name: currentServer.name, icon: currentServer.icon } : undefined}
tools={{ threads: false, pinned: false }}
@@ -669,7 +680,7 @@ function ChannelView() {
apiFetch(`/api/community/channels/${channelId}`, {
method: "PATCH",
body: JSON.stringify({ forumTags: JSON.stringify(tags) }),
- }).catch(() => toast("Failed to save tags"))
+ }).catch((e) => toastApiError(e, "Failed to save tags"))
} : undefined}
/>
</main>
@@ -695,7 +706,9 @@ function ChannelView() {
rightPanel={rightPanel}
onToggle={togglePanel}
notifLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? "Use Server Default"}
- onSetNotifLevel={(l) => setChannelNotifMut.mutate({ channelId, level: l })}
+ onSetNotifLevel={(l) => setChannelNotifMut.mutate({ channelId, level: l }, {
+ onError: (e) => toastApiError(e, "Failed to update notification level"),
+ })}
onBack={bp === "mobile" ? goBack : undefined}
server={bp === "mobile" && currentServer ? { id: currentServer.id, name: currentServer.name, icon: currentServer.icon } : undefined}
/>
diff --git a/src/web/src/app/community/channels/layout.tsx b/src/web/src/app/community/channels/layout.tsx
index bca2a3325..e290c615f 100644
--- a/src/web/src/app/community/channels/layout.tsx
+++ b/src/web/src/app/community/channels/layout.tsx
@@ -4,7 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } fro
import { useParams, useRouter, useSearchParams } from "next/navigation"
import { useQueryClient } from "@tanstack/react-query"
import { toast } from "sonner"
-import { apiFetch } from "@/lib/api/client"
+import { apiFetch, toastApiError } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import { Dialog, DialogContent } from "@/components/ui/dialog"
import { useBreakpoint } from "@/hooks/use-mobile"
@@ -287,13 +287,13 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
const onCreateChannelInSidebar = useCallback((categoryId: string, name: string, type: ChannelType) => {
createChannelMut.mutate(
{ serverId, categoryId, name, type },
- { onError: (e) => toast(e instanceof Error ? e.message : "Failed to create channel") },
+ { onError: (e) => toastApiError(e, "Failed to create channel") },
)
}, [createChannelMut, serverId])
const onCreateCategoryInSidebar = useCallback((name: string, opts?: { private?: boolean }) => {
createCategoryMut.mutate(
{ serverId, name, private: opts?.private },
- { onError: (e) => toast(e instanceof Error ? e.message : "Failed to create category") },
+ { onError: (e) => toastApiError(e, "Failed to create category") },
)
}, [createCategoryMut, serverId])
const onRenameChannel = useCallback(async (channelId: string, name: string) => {
@@ -303,26 +303,26 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
body: JSON.stringify({ name }),
})
} catch (e) {
- toast(e instanceof Error ? e.message : "Failed to rename channel")
+ toastApiError(e, "Failed to rename channel")
}
}, [])
const onDeleteChannelInSidebar = useCallback((channelId: string) => {
- deleteChannelMut.mutate({ serverId, channelId }, { onError: () => toast("Failed to delete channel") })
+ deleteChannelMut.mutate({ serverId, channelId }, { onError: (e) => toastApiError(e, "Failed to delete channel") })
}, [deleteChannelMut, serverId])
const onDeleteCategoryInSidebar = useCallback((categoryId: string) => {
- deleteCategoryMut.mutate({ serverId, categoryId }, { onError: () => toast("Failed to delete category") })
+ deleteCategoryMut.mutate({ serverId, categoryId }, { onError: (e) => toastApiError(e, "Failed to delete category") })
}, [deleteCategoryMut, serverId])
const onUpdateCategoryInSidebar = useCallback((categoryId: string, opts: { name?: string }) => {
- updateCategoryMut.mutate({ serverId, categoryId, name: opts.name }, { onError: () => toast("Failed to update category") })
+ updateCategoryMut.mutate({ serverId, categoryId, name: opts.name }, { onError: (e) => toastApiError(e, "Failed to update category") })
}, [updateCategoryMut, serverId])
const onReorderCategoriesInSidebar = useCallback((categoryIds: string[]) => {
- reorderCategoriesMut.mutate({ serverId, categoryIds }, { onError: () => toast("Failed to save category order") })
+ reorderCategoriesMut.mutate({ serverId, categoryIds }, { onError: (e) => toastApiError(e, "Failed to save category order") })
}, [reorderCategoriesMut, serverId])
const onReorderChannelsInSidebar = useCallback((channelIds: string[]) => {
- reorderChannelsMut.mutate({ serverId, channelIds }, { onError: () => toast("Failed to save channel order") })
+ reorderChannelsMut.mutate({ serverId, channelIds }, { onError: (e) => toastApiError(e, "Failed to save channel order") })
}, [reorderChannelsMut, serverId])
const onMoveChannelInSidebar = useCallback((channelId: string, categoryId: string | null) => {
- moveChannelMut.mutate({ serverId, channelId, categoryId }, { onError: () => toast("Failed to move channel") })
+ moveChannelMut.mutate({ serverId, channelId, categoryId }, { onError: (e) => toastApiError(e, "Failed to move channel") })
}, [moveChannelMut, serverId])
const onBlockedMove = useCallback(() => {
toast("Can't move a channel between public and private categories")
@@ -399,18 +399,18 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
onKickMember={(memberId) => {
kickMemberMut.mutate({ serverId, memberId }, {
onSuccess: () => toast("Member kicked"),
- onError: () => toast("Failed to kick member"),
+ onError: (e) => toastApiError(e, "Failed to kick member"),
})
}}
onSetRole={(memberId, role) => {
setMemberRoleMut.mutate({ serverId, memberId, role }, {
onSuccess: () => toast("Role updated"),
- onError: () => toast("Failed to update role"),
+ onError: (e) => toastApiError(e, "Failed to update role"),
})
}}
onRevokeInvite={(code) => revokeInviteMut.mutate({ serverId, code }, {
onSuccess: () => toast("Invite revoked"),
- onError: () => toast("Failed to revoke invite"),
+ onError: (e) => toastApiError(e, "Failed to revoke invite"),
})}
onCopyInvite={(code) => { navigator.clipboard?.writeText(`${window.location.origin}/community/invite/${code}`); toast("Invite copied") }}
onDeleteServer={async () => {
@@ -421,7 +421,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
useCommunityStore.getState().setCurrentServerId(null)
router.push("/community/me")
},
- onError: () => toast("Failed to delete server"),
+ onError: (e) => toastApiError(e, "Failed to delete server"),
})
}}
onUploadIcon={() => {
@@ -443,12 +443,12 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
onUpdateServer={(name, desc) =>
updateServerMut.mutate({ serverId, name, description: desc }, {
onSuccess: () => toast("Server updated"),
- onError: () => toast("Failed to update server"),
+ onError: (e) => toastApiError(e, "Failed to update server"),
})
}
notifLevel={notifLevel}
onSetNotifLevel={(level) => setServerNotifMut.mutate({ serverId, level }, {
- onError: () => toast("Failed to update notification level"),
+ onError: (e) => toastApiError(e, "Failed to update notification level"),
})}
onOpenProfile={openProfile}
/>
@@ -464,7 +464,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
onCropped={(file) => {
uploadServerIconMut.mutate({ serverId, file }, {
onSuccess: () => toast("Server icon updated"),
- onError: () => toast("Failed to upload icon"),
+ onError: (e) => toastApiError(e, "Failed to upload icon"),
})
URL.revokeObjectURL(pendingIconCrop.src)
setPendingIconCrop(null)
diff --git a/src/web/src/app/community/me/[dmId]/page.tsx b/src/web/src/app/community/me/[dmId]/page.tsx
index 9ea5783ca..b920c96b1 100644
--- a/src/web/src/app/community/me/[dmId]/page.tsx
+++ b/src/web/src/app/community/me/[dmId]/page.tsx
@@ -3,6 +3,7 @@
import { useCallback, useEffect, useMemo, useState } from "react"
import { useParams } from "next/navigation"
import { toast } from "sonner"
+import { toastApiError } from "@/lib/api/client"
import { useBreakpoint } from "@/hooks/use-mobile"
import { DmHeader, DmHeaderSkeleton } from "@/components/community/dm-header"
import { Avatar } from "@/components/community/avatar"
@@ -253,7 +254,10 @@ function DmView() {
if (attachments?.length) {
const results = await Promise.all(
attachments.map((a) =>
- uploadFile.mutateAsync({ target: { dmId }, file: a.file }).catch(() => null),
+ uploadFile.mutateAsync({ target: { dmId }, file: a.file }).catch((e) => {
+ toastApiError(e, "Failed to attach file")
+ return null
+ }),
),
)
uploadedAttachments = zipUploadResultsWithDimensions(results, attachments)
@@ -292,7 +296,7 @@ function DmView() {
reconciliation fix as the channel page (see its equivalent
comment). `variant="dm"` now drives the skeleton shape
explicitly instead of the removed `dm={!!hero}` inference. */}
- <MessageList key={dmId} channel="" messages={[]} loading={true} onOpenThread={() => {}} variant="dm" />
+ <MessageList key={dmId} channel="" messages={[]} loading={true} onOpenThread={() => { }} variant="dm" />
<ComposerSkeleton />
</main>
</>
@@ -328,7 +332,7 @@ function DmView() {
if (dm && id === dm.userId) return dm.name
return friends.find((f) => f.userId === id)?.name ?? id
})}
- onOpenThread={() => {}}
+ onOpenThread={() => { }}
onToggleReaction={dmBlocked ? undefined : messageActions.onToggleReaction}
onReact={dmBlocked ? undefined : messageActions.onReact}
onReply={dmBlocked ? undefined : messageActions.onReply}
diff --git a/src/web/src/app/community/me/page.tsx b/src/web/src/app/community/me/page.tsx
index 5c885f41f..77a4e78de 100644
--- a/src/web/src/app/community/me/page.tsx
+++ b/src/web/src/app/community/me/page.tsx
@@ -17,6 +17,7 @@ import {
useCreateOrGetDm,
} from "@/hooks/community/mutations"
import { toast } from "sonner"
+import { toastApiError } from "@/lib/api/client"
export default function MeFriendsPage() {
const router = useRouter()
@@ -61,25 +62,28 @@ export default function MeFriendsPage() {
{ friendshipId: id },
{
onSuccess: () => toast("Friend request accepted"),
- onError: () => toast("Failed to accept request"),
+ onError: (e) => toastApiError(e, "Failed to accept request"),
},
)
}
onReject={(id) =>
rejectFriendRequest.mutate(
{ friendshipId: id },
- { onError: () => toast("Failed to reject request") },
+ { onError: (e) => toastApiError(e, "Failed to reject request") },
)
}
onCancelRequest={(id) =>
- rejectFriendRequest.mutate({ friendshipId: id })
+ rejectFriendRequest.mutate(
+ { friendshipId: id },
+ { onError: (e) => toastApiError(e, "Failed to cancel request") },
+ )
}
onUnblock={(id) =>
unblockUser.mutate(
{ userId: id },
{
onSuccess: () => toast("User unblocked"),
- onError: () => toast("Failed to unblock user"),
+ onError: (e) => toastApiError(e, "Failed to unblock user"),
},
)
}
@@ -87,10 +91,8 @@ export default function MeFriendsPage() {
try {
await sendFriendRequest.mutateAsync({ username })
toast("Friend request sent")
- } catch (err) {
- const msg =
- err instanceof Error ? err.message : "Failed to send friend request"
- toast(msg)
+ } catch (e) {
+ toastApiError(e, "Failed to send friend request")
}
}}
onRemoveFriend={(id) =>
@@ -98,7 +100,7 @@ export default function MeFriendsPage() {
{ friendshipId: id },
{
onSuccess: () => toast("Friend removed"),
- onError: () => toast("Failed to remove friend"),
+ onError: (e) => toastApiError(e, "Failed to remove friend"),
},
)
}
@@ -107,7 +109,7 @@ export default function MeFriendsPage() {
{ userId: id },
{
onSuccess: () => toast("User blocked"),
- onError: () => toast("Failed to block user"),
+ onError: (e) => toastApiError(e, "Failed to block user"),
},
)
}
@@ -115,8 +117,8 @@ export default function MeFriendsPage() {
try {
const data = await createOrGetDm.mutateAsync({ userId })
if (data.conversation.id) router.push(`/community/me/${data.conversation.id}`)
- } catch {
- toast("Failed to open DM")
+ } catch (e) {
+ toastApiError(e, "Failed to open DM")
}
}}
/>
diff --git a/src/web/src/components/community/bots/bot-list.tsx b/src/web/src/components/community/bots/bot-list.tsx
index f7bc8863d..3c8afb82a 100644
--- a/src/web/src/components/community/bots/bot-list.tsx
+++ b/src/web/src/components/community/bots/bot-list.tsx
@@ -4,6 +4,7 @@ import { useEffect, useMemo, useRef, useState } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { ChevronLeft, Bot as BotIcon, Monitor, MoreVertical, Plus } from "lucide-react"
import { toast } from "sonner"
+import { toastApiError } from "@/lib/api/client"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import {
@@ -66,8 +67,8 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {
try {
const data = await createOrGetDm.mutateAsync({ userId: bot.id })
router.push(`/community/me/${data.conversation.id}`)
- } catch {
- toast.error("Failed to open chat")
+ } catch (e) {
+ toastApiError(e, "Failed to open chat")
}
}
@@ -328,8 +329,8 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {
try {
await del.mutateAsync(confirmDelete.id)
toast.success(`Deleted ${name}`)
- } catch (err) {
- toast.error(err instanceof Error ? err.message : "Couldn't delete the bot")
+ } catch (e) {
+ toastApiError(e, "Couldn't delete the bot")
} finally {
setConfirmDelete(null)
}
diff --git a/src/web/src/components/community/bots/create-bot-sheet.tsx b/src/web/src/components/community/bots/create-bot-sheet.tsx
index 74c2c5deb..896a6e64b 100644
--- a/src/web/src/components/community/bots/create-bot-sheet.tsx
+++ b/src/web/src/components/community/bots/create-bot-sheet.tsx
@@ -2,6 +2,7 @@
import { useEffect, useMemo, useRef, useState } from "react"
import { toast } from "sonner"
+import { toastApiError } from "@/lib/api/client"
import {
Sheet,
SheetBody,
@@ -151,15 +152,15 @@ export function CreateBotSheet({
if (avatarDraft.kind === "photo" && avatarDraft.file) {
try {
await uploadBotAvatar.mutateAsync({ botId: data.bot.id, file: avatarDraft.file })
- } catch {
+ } catch (e) {
avatarFailed = true
- toast.error("Bot created, but the avatar photo failed to upload")
+ toastApiError(e, "Bot created, but the avatar photo failed to upload")
}
}
if (!avatarFailed) toast.success(`Created ${name.trim()}`)
onOpenChange(false)
- } catch (err) {
- toast.error(err instanceof Error ? err.message : "Couldn't create the bot")
+ } catch (e) {
+ toastApiError(e, "Couldn't create the bot")
}
}
diff --git a/src/web/src/components/community/bots/edit-bot-sheet.tsx b/src/web/src/components/community/bots/edit-bot-sheet.tsx
index 934b1ee18..9f53f5f67 100644
--- a/src/web/src/components/community/bots/edit-bot-sheet.tsx
+++ b/src/web/src/components/community/bots/edit-bot-sheet.tsx
@@ -2,6 +2,7 @@
import { useEffect, useRef, useState } from "react"
import { toast } from "sonner"
+import { toastApiError } from "@/lib/api/client"
import {
Sheet,
SheetBody,
@@ -103,15 +104,15 @@ export function EditBotSheet({
if (avatarDraft.kind === "photo" && avatarDraft.file) {
try {
await uploadBotAvatar.mutateAsync({ botId: bot.id, file: avatarDraft.file })
- } catch {
+ } catch (e) {
avatarFailed = true
- toast.error("Bot updated, but the avatar photo failed to upload")
+ toastApiError(e, "Bot updated, but the avatar photo failed to upload")
}
}
if (!avatarFailed) toast.success("Bot updated")
onOpenChange(false)
- } catch (err) {
- toast.error(err instanceof Error ? err.message : "Update failed")
+ } catch (e) {
+ toastApiError(e, "Update failed")
}
}
diff --git a/src/web/src/components/community/edit-profile-dialog.tsx b/src/web/src/components/community/edit-profile-dialog.tsx
index 4535d37ae..fdf307073 100644
--- a/src/web/src/components/community/edit-profile-dialog.tsx
+++ b/src/web/src/components/community/edit-profile-dialog.tsx
@@ -2,6 +2,7 @@
import { useCallback, useEffect, useRef, useState } from "react"
import { toast } from "sonner"
+import { toastApiError } from "@/lib/api/client"
import { User, LogOut, X, Palette, Sun, Moon, Monitor, Database } from "lucide-react"
import { useTheme } from "next-themes"
import { Button } from "@/components/ui/button"
@@ -81,8 +82,8 @@ function AdvancedSettings({ userId }: { userId: string | null }) {
// Hard reload so the QueryClient starts fresh without racing an
// in-flight persister write.
window.location.reload()
- } catch {
- toast("Failed to clear cache")
+ } catch (e) {
+ toastApiError(e, "Failed to clear cache")
setClearing(false)
setConfirmOpen(false)
}
diff --git a/src/web/src/components/community/friends-page.tsx b/src/web/src/components/community/friends-page.tsx
index 70da03493..d9a687bfa 100644
--- a/src/web/src/components/community/friends-page.tsx
+++ b/src/web/src/components/community/friends-page.tsx
@@ -3,7 +3,7 @@
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 } from "@/lib/api/client"
+import { apiFetch, toastApiError } from "@/lib/api/client"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"
@@ -72,7 +72,10 @@ export function FriendsPage({
try {
const data = await apiFetch<{ users: { id: string; name: string; image: string | null; discriminator: string }[] }>(`/api/community/users/search?q=${encodeURIComponent(q)}`)
setSearchResults(data.users)
- } catch { setSearchResults([]) }
+ } catch (e) {
+ setSearchResults([])
+ toastApiError(e, "Search failed")
+ }
}, 300)
return () => { if (debounceRef.current) clearTimeout(debounceRef.current) }
}, [addValue])
diff --git a/src/web/src/components/community/image-crop-dialog.tsx b/src/web/src/components/community/image-crop-dialog.tsx
index bf8ab5ad9..a0fe32f5c 100644
--- a/src/web/src/components/community/image-crop-dialog.tsx
+++ b/src/web/src/components/community/image-crop-dialog.tsx
@@ -3,6 +3,7 @@
import { useCallback, useState } from "react"
import Cropper, { type Area } from "react-easy-crop"
import { toast } from "sonner"
+import { getErrorMessage } from "@/lib/api/client"
import {
Dialog,
DialogContent,
@@ -53,8 +54,8 @@ export function ImageCropDialog({
return
}
onCropped(buildCroppedIconFile(blob, originalFileName))
- } catch {
- toast.error("Failed to process image — please try again")
+ } catch (e) {
+ toast.error(getErrorMessage(e, "Failed to process image — please try again"))
} finally {
setSaving(false)
}
diff --git a/src/web/src/components/community/machines/pair-machine-sheet.tsx b/src/web/src/components/community/machines/pair-machine-sheet.tsx
index f79364126..41c61fba4 100644
--- a/src/web/src/components/community/machines/pair-machine-sheet.tsx
+++ b/src/web/src/components/community/machines/pair-machine-sheet.tsx
@@ -14,7 +14,7 @@ import {
SheetClose,
} from "@/components/ui/sheet"
import { Button } from "@/components/ui/button"
-import { apiFetch } from "@/lib/api/client"
+import { apiFetch, toastApiError } from "@/lib/api/client"
import { isLocalMode, WS_DO_PORT_DEFAULT } from "@/lib/utils"
// Community daemon HTTP/WS endpoints live on the same worker + ws-do as the
@@ -70,7 +70,7 @@ export function PairMachineSheet({
)
setPendingTokenId(res.tokenId)
} catch (err) {
- toast.error("Couldn't generate a key — try again.")
+ toastApiError(err, "Couldn't generate a key — try again.")
console.error(err)
} finally {
setGenerating(false)
diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsx
index c1426a7c5..000eb0c41 100644
--- a/src/web/src/components/community/shell-frame.tsx
+++ b/src/web/src/components/community/shell-frame.tsx
@@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } fro
import { useRouter } from "next/navigation"
import { useQueryClient } from "@tanstack/react-query"
import { toast } from "sonner"
+import { toastApiError } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import { userProfileQueryFn, PROFILE_STALE_TIME_MS } from "@/hooks/community/use-user-profile"
import { useDefaultLayout } from "react-resizable-panels"
@@ -177,10 +178,15 @@ export function ShellFrame({
const data = await createServer.mutateAsync({ name })
const newId = data.server.id
toast(`Server "${name}" created`)
- if (icon) uploadServerIcon.mutate({ serverId: newId, file: icon })
+ if (icon) {
+ uploadServerIcon.mutate(
+ { serverId: newId, file: icon },
+ { onError: (e) => toastApiError(e, "Server created, but the icon failed to upload") },
+ )
+ }
router.push(`/community/channels/${newId}`)
- } catch {
- toast("Failed to create server")
+ } catch (e) {
+ toastApiError(e, "Failed to create server")
}
},
[createServer, uploadServerIcon, router],
@@ -191,8 +197,8 @@ export function ShellFrame({
const data = await joinServer.mutateAsync({ inviteCode: invite })
toast("Joined server")
router.push(`/community/channels/${data.serverId}`)
- } catch {
- toast("Failed to join server")
+ } catch (e) {
+ toastApiError(e, "Failed to join server")
}
},
[joinServer, router],
@@ -213,7 +219,7 @@ export function ShellFrame({
router.replace(pickPostEjectDestination(servers, id))
}
},
- onError: () => toast("Failed to leave server"),
+ onError: (e) => toastApiError(e, "Failed to leave server"),
},
)
},
@@ -237,7 +243,7 @@ export function ShellFrame({
{ folderId: fId },
{
onSuccess: () => toast("Group removed"),
- onError: () => toast("Failed to remove group"),
+ onError: (e) => toastApiError(e, "Failed to remove group"),
},
)
},
@@ -247,7 +253,7 @@ export function ShellFrame({
(ids: string[]) => {
reorderServers.mutate(
{ serverIds: ids },
- { onError: () => toast("Failed to save server order") },
+ { onError: (e) => toastApiError(e, "Failed to save server order") },
)
},
[reorderServers],
@@ -256,7 +262,7 @@ export function ShellFrame({
(ids: string[]) => {
reorderFolders.mutate(
{ folderIds: ids },
- { onError: () => toast("Failed to reorder groups") },
+ { onError: (e) => toastApiError(e, "Failed to reorder groups") },
)
},
[reorderFolders],
@@ -265,7 +271,7 @@ export function ShellFrame({
(fId: string, ids: string[]) => {
updateFolderItems.mutate(
{ folderId: fId, serverIds: ids },
- { onError: () => toast("Failed to update group") },
+ { onError: (e) => toastApiError(e, "Failed to update group") },
)
},
[updateFolderItems],
@@ -274,7 +280,7 @@ export function ShellFrame({
(a: string, b: string) => {
createFolderWith.mutate(
{ serverIdA: a, serverIdB: b },
- { onError: () => toast("Failed to create group") },
+ { onError: (e) => toastApiError(e, "Failed to create group") },
)
},
[createFolderWith],
@@ -377,7 +383,7 @@ export function ShellFrame({
: prev,
)
})
- .catch(() => { })
+ .catch((e) => toastApiError(e, "Failed to load profile"))
}
},
[currentUser, members, friends, queryClient, onlineUserIds],
@@ -405,8 +411,8 @@ export function ShellFrame({
setProfile((prev) =>
prev ? { ...prev, data: { ...prev.data, statusEmoji, statusText } } : prev,
)
- } catch {
- toast("Failed to update status")
+ } catch (e) {
+ toastApiError(e, "Failed to update status")
}
}
@@ -419,8 +425,8 @@ export function ShellFrame({
try {
const data = await createOrGetDm.mutateAsync({ userId })
dmId = data.conversation.id
- } catch {
- toast("Failed to open DM")
+ } catch (e) {
+ toastApiError(e, "Failed to open DM")
return
}
// Await the send BEFORE navigating so the server row exists by the time
@@ -441,8 +447,8 @@ export function ShellFrame({
avatar: currentUser.avatar,
},
})
- } catch {
- toast("Failed to send message")
+ } catch (e) {
+ toastApiError(e, "Failed to send message")
}
}
router.push(`/community/me/${dmId}`)
@@ -544,7 +550,7 @@ export function ShellFrame({
data.statusText ?? null,
)
}
- } catch { toast("Failed to save profile") }
+ } catch (e) { toastApiError(e, "Failed to save profile") }
}}
onLogout={async () => {
// Clear community-local state (timers, subscription, presence)
@@ -576,7 +582,7 @@ export function ShellFrame({
setCurrentUser((u) => ({ ...u, avatar: `${data.url}?t=${Date.now()}` }))
toast("Avatar updated")
},
- onError: () => toast("Failed to upload avatar"),
+ onError: (e) => toastApiError(e, "Failed to upload avatar"),
})
URL.revokeObjectURL(pendingAvatarCrop.src)
setPendingAvatarCrop(null)
diff --git a/src/web/src/hooks/community/mutations/messages.test.ts b/src/web/src/hooks/community/mutations/messages.test.ts
index 7231e1cbe..64ff55bb2 100644
--- a/src/web/src/hooks/community/mutations/messages.test.ts
+++ b/src/web/src/hooks/community/mutations/messages.test.ts
@@ -32,17 +32,25 @@ vi.mock("react", () => ({
callbackMemo.set(id, { fn, deps })
return fn
},
- useEffect: () => {},
- useState: (initial: unknown) => [initial, () => {}],
+ useEffect: () => { },
+ useState: (initial: unknown) => [initial, () => { }],
}))
const apiFetchMock = vi.fn()
+
+// Sonner toast — we assert on the string arg for the blocked-DM test.
+const toastMock = vi.fn()
+
vi.mock("@/lib/api/client", () => ({
apiFetch: (...args: unknown[]) => apiFetchMock(...args),
+ // Mirrors the real `toastApiError` (ApiError/Error message, else fallback)
+ // while routing through the same `toastMock` sonner assertions below use.
+ toastApiError: (err: unknown, fallback: string) => {
+ const msg = err instanceof Error && err.message ? err.message : fallback
+ toastMock(msg)
+ },
}))
-// Sonner toast — we assert on the string arg for the blocked-DM test.
-const toastMock = vi.fn()
vi.mock("sonner", () => ({
toast: Object.assign((...args: unknown[]) => toastMock(...args), {
error: (...args: unknown[]) => toastMock(...args),
@@ -139,7 +147,7 @@ describe("useSendMessage — rollback", () => {
channelId: "ch_1",
content: "hi",
author: { id: "u_me", name: "me", avatar: "M" },
- }).catch(() => {})
+ }).catch(() => { })
const cache = capturedQc.getQueryData<{ pages: { messages: { id: string; failed?: boolean }[] }[] }>(
communityKeys.channelMessages("ch_1"),
)
@@ -156,7 +164,7 @@ describe("useSendMessage — stamps authorId on optimistic row", () => {
it("optimistic row carries the sender's authorId", async () => {
capturedQc.setQueryData(communityKeys.channelMessages("ch_1"), makeCache([]))
// Never resolves — we only care about the optimistic write from onMutate.
- apiFetchMock.mockImplementation(() => new Promise(() => {}))
+ apiFetchMock.mockImplementation(() => new Promise(() => { }))
const mod = await loadMod()
mod.useSendMessage()
const cfg = capturedConfig!
@@ -180,7 +188,7 @@ describe("useSendDmMessage — stamps authorId on optimistic row", () => {
// in <MessageList> because `undefined !== viewerUserId`. Pin the field.
it("optimistic DM row carries the sender's authorId", async () => {
capturedQc.setQueryData(communityKeys.dmMessages("dm_1"), makeCache([]))
- apiFetchMock.mockImplementation(() => new Promise(() => {}))
+ apiFetchMock.mockImplementation(() => new Promise(() => { }))
const mod = await loadMod()
mod.useSendDmMessage()
const cfg = capturedConfig!
@@ -207,7 +215,7 @@ describe("useSendDmMessage — rollback", () => {
dmId: "dm_1",
content: "hi",
author: { id: "u_me", name: "me", avatar: "M" },
- }).catch(() => {})
+ }).catch(() => { })
const cache = capturedQc.getQueryData<{ pages: { messages: { failed?: boolean }[] }[] }>(
communityKeys.dmMessages("dm_1"),
)
@@ -228,7 +236,7 @@ describe("useSendDmMessage — 403 blocked special-case", () => {
dmId: "dm_1",
content: "hi",
author: { id: "u_me", name: "me", avatar: "M" },
- }).catch(() => {})
+ }).catch(() => { })
const cache = capturedQc.getQueryData<{ pages: { messages: unknown[] }[] }>(
communityKeys.dmMessages("dm_1"),
)
@@ -237,7 +245,7 @@ describe("useSendDmMessage — 403 blocked special-case", () => {
expect(toastMock).toHaveBeenCalledWith("You cannot send messages to this user")
})
- it("regression: a generic 500 still marks the row failed and fires no blocked toast", async () => {
+ it("regression: a generic 500 still marks the row failed and fires the generic send-failed toast (not the blocked toast)", async () => {
capturedQc.setQueryData(communityKeys.dmMessages("dm_1"), makeCache([]))
const mod = await loadMod()
const { ApiError } = await import("@/lib/errors")
@@ -247,13 +255,16 @@ describe("useSendDmMessage — 403 blocked special-case", () => {
dmId: "dm_1",
content: "hi",
author: { id: "u_me", name: "me", avatar: "M" },
- }).catch(() => {})
+ }).catch(() => { })
const cache = capturedQc.getQueryData<{ pages: { messages: { failed?: boolean }[] }[] }>(
communityKeys.dmMessages("dm_1"),
)
expect(cache?.pages[0].messages).toHaveLength(1)
expect(cache?.pages[0].messages[0].failed).toBe(true)
- expect(toastMock).not.toHaveBeenCalled()
+ // Not the blocked-specific copy — any other error falls through to the
+ // generic send-failed toast (see `useSendDmMessage`'s `onError` fallback).
+ expect(toastMock).not.toHaveBeenCalledWith("You cannot send messages to this user")
+ expect(toastMock).toHaveBeenCalledWith("boom")
})
})
@@ -271,7 +282,7 @@ describe("useSendMessage — 429 rate limit fires a toast + marks failed", () =>
channelId: "ch_1",
content: "hi",
author: { id: "u_me", name: "me", avatar: "M" },
- }).catch(() => {})
+ }).catch(() => { })
const cache = capturedQc.getQueryData<{ pages: { messages: { failed?: boolean }[] }[] }>(
communityKeys.channelMessages("ch_1"),
)
@@ -291,7 +302,7 @@ describe("useSendDmMessage — 429 rate limit fires a toast + marks failed", ()
dmId: "dm_1",
content: "hi",
author: { id: "u_me", name: "me", avatar: "M" },
- }).catch(() => {})
+ }).catch(() => { })
const cache = capturedQc.getQueryData<{ pages: { messages: { failed?: boolean }[] }[] }>(
communityKeys.dmMessages("dm_1"),
)
@@ -301,11 +312,13 @@ describe("useSendDmMessage — 429 rate limit fires a toast + marks failed", ()
})
})
-// Regression guard — channel path stays generic-error, never fires the blocked
-// toast even on 403 blocked (that shouldn't happen on channels; ensure the
-// hook doesn't accidentally add DM's onBlocked branch to `useSendMessage`).
+// Regression guard — channel path stays generic-error, never fires the DM's
+// specific blocked toast even on 403 (that shouldn't happen on channels;
+// ensure the hook doesn't accidentally add DM's onBlocked branch to
+// `useSendMessage`). It still falls through to the generic send-failed
+// toast, same as any other non-429 error.
describe("useSendMessage — no blocked branch on channel path", () => {
- it("403 blocked on channel POST still marks failed:true and skips the DM toast", async () => {
+ it("403 blocked on channel POST still marks failed:true and skips the DM-specific toast", async () => {
capturedQc.setQueryData(communityKeys.channelMessages("ch_1"), makeCache([]))
const mod = await loadMod()
const { ApiError } = await import("@/lib/errors")
@@ -315,13 +328,14 @@ describe("useSendMessage — no blocked branch on channel path", () => {
channelId: "ch_1",
content: "hi",
author: { id: "u_me", name: "me", avatar: "M" },
- }).catch(() => {})
+ }).catch(() => { })
const cache = capturedQc.getQueryData<{ pages: { messages: { failed?: boolean }[] }[] }>(
communityKeys.channelMessages("ch_1"),
)
expect(cache?.pages[0].messages).toHaveLength(1)
expect(cache?.pages[0].messages[0].failed).toBe(true)
- expect(toastMock).not.toHaveBeenCalled()
+ expect(toastMock).not.toHaveBeenCalledWith("You cannot send messages to this user")
+ expect(toastMock).toHaveBeenCalledWith("blocked")
})
})
@@ -362,7 +376,7 @@ describe("useToggleReaction — optimistic flip + rollback", () => {
messageId: "m_1",
emoji: "👍",
userId: "u_me",
- }).catch(() => {})
+ }).catch(() => { })
const cache = capturedQc.getQueryData<{ pages: { messages: { reactions: unknown[] }[] }[] }>(
communityKeys.channelMessages("ch_1"),
)
@@ -502,7 +516,7 @@ describe("useUnpinMessage — rollback", () => {
apiFetchMock.mockRejectedValueOnce(new Error("boom"))
const mod = await loadMod()
mod.useUnpinMessage()
- await runMutation({ channelId: "ch_1", messageId: "m_1" }).catch(() => {})
+ await runMutation({ channelId: "ch_1", messageId: "m_1" }).catch(() => { })
const cache = capturedQc.getQueryData<{ pins: unknown[] }>(communityKeys.pins("ch_1"))
expect(cache?.pins).toHaveLength(1)
})
@@ -708,7 +722,7 @@ describe("scheduleMarkRead — with messageId body", () => {
apiFetchMock.mockResolvedValue(undefined)
const mod = await loadMod()
mod._resetPendingReads_forTesting()
- mod.scheduleMarkRead("ch_1", { messageId: "m_42", onDone: () => {} })
+ mod.scheduleMarkRead("ch_1", { messageId: "m_42", onDone: () => { } })
await vi.advanceTimersByTimeAsync(500)
const put = apiFetchMock.mock.calls.find(
(c) => (c[1] as { method?: string })?.method === "PUT",
@@ -726,9 +740,9 @@ describe("scheduleMarkRead — with messageId body", () => {
apiFetchMock.mockResolvedValue(undefined)
const mod = await loadMod()
mod._resetPendingReads_forTesting()
- mod.scheduleMarkRead("ch_1", { messageId: "m_stale", onDone: () => {} })
+ mod.scheduleMarkRead("ch_1", { messageId: "m_stale", onDone: () => { } })
// Fresh call within the window — the latest messageId wins.
- mod.scheduleMarkRead("ch_1", { messageId: "m_fresh", onDone: () => {} })
+ mod.scheduleMarkRead("ch_1", { messageId: "m_fresh", onDone: () => { } })
await vi.advanceTimersByTimeAsync(500)
const puts = apiFetchMock.mock.calls.filter(
(c) => (c[1] as { method?: string })?.method === "PUT",
@@ -746,7 +760,7 @@ describe("scheduleMarkRead — with messageId body", () => {
apiFetchMock.mockResolvedValue(undefined)
const mod = await loadMod()
mod._resetPendingReads_forTesting()
- mod.scheduleMarkRead("ch_1", { onDone: () => {} })
+ mod.scheduleMarkRead("ch_1", { onDone: () => { } })
await vi.advanceTimersByTimeAsync(500)
const put = apiFetchMock.mock.calls.find(
(c) => (c[1] as { method?: string })?.method === "PUT",
@@ -898,7 +912,7 @@ describe("useMarkDmRead — rollback", () => {
apiFetchMock.mockRejectedValueOnce(new Error("boom"))
const mod = await loadMod()
mod.useMarkDmRead()
- await runMutation({ dmId: "dm_1" }).catch(() => {})
+ await runMutation({ dmId: "dm_1" }).catch(() => { })
const cache = capturedQc.getQueryData<{ conversations: { id: string; unread?: boolean }[] }>(
communityKeys.dms(),
)
@@ -957,6 +971,14 @@ describe("useMarkAllInboxRead", () => {
})
expect(serversInvalidates.length).toBeGreaterThanOrEqual(1)
})
+
+ it("toasts the failure reason when one of the three read-all POSTs fails", async () => {
+ apiFetchMock.mockRejectedValueOnce(new Error("boom"))
+ const mod = await loadMod()
+ mod.useMarkAllInboxRead()
+ await runMutation<void>(undefined as unknown as void).catch(() => { })
+ expect(toastMock).toHaveBeenCalledWith("boom")
+ })
})
// ── useDeleteMention — rollback ──────────────────────────────────────────
@@ -969,13 +991,24 @@ describe("useDeleteMention — rollback", () => {
apiFetchMock.mockRejectedValueOnce(new Error("boom"))
const mod = await loadMod()
mod.useDeleteMention()
- await runMutation({ mentionId: "men_1" }).catch(() => {})
+ await runMutation({ mentionId: "men_1" }).catch(() => { })
const cache = capturedQc.getQueryData<{ mentions: { id: string }[] }>(
communityKeys.inboxMentions(),
)
expect(cache?.mentions).toHaveLength(1)
})
+ it("toasts the failure reason on delete failure", async () => {
+ capturedQc.setQueryData(communityKeys.inboxMentions(), {
+ mentions: [{ id: "men_1" }],
+ })
+ apiFetchMock.mockRejectedValueOnce(new Error("boom"))
+ const mod = await loadMod()
+ mod.useDeleteMention()
+ await runMutation({ mentionId: "men_1" }).catch(() => { })
+ expect(toastMock).toHaveBeenCalledWith("boom")
+ })
+
it("invalidates communityKeys.servers() on success so the rail badge decrements", async () => {
capturedQc.setQueryData(communityKeys.inboxMentions(), {
mentions: [{ id: "men_1" }],
diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.ts
index a9bd31348..58a344c93 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -6,7 +6,7 @@ import {
type InfiniteData,
} from "@tanstack/react-query"
import { toast } from "sonner"
-import { apiFetch } from "@/lib/api/client"
+import { apiFetch, toastApiError } from "@/lib/api/client"
import { ApiError } from "@/lib/errors"
import { communityKeys } from "@/lib/query-keys"
import { useCommunityStore } from "@/stores/community"
@@ -226,6 +226,12 @@ export function useSendMessage() {
// still gets marked failed so the retry affordance stays available.
if (err instanceof ApiError && err.status === 429) {
toast.error("Rate limited — please wait a moment before trying again")
+ } else {
+ // Any other failure (validation error, forbidden, 500, etc.) — the
+ // `failed: true` pill below is a retry affordance, not a reason.
+ // Without this the user sees no explanation at all for send
+ // failures outside the 429 case.
+ toastApiError(err, "Failed to send message")
}
queryClient.setQueryData<PageCache>(ctx.key as ReturnType<typeof communityKeys.channelMessages>, (c) =>
markFailedById(c, ctx.tempId),
@@ -307,6 +313,10 @@ export function useSendDmMessage() {
// retry pill is available (mirrors the channel path).
if (err instanceof ApiError && err.status === 429) {
toast.error("Rate limited — please wait a moment before trying again")
+ } else {
+ // Any other failure besides 429/blocked (handled above) — the
+ // `failed: true` pill is a retry affordance, not a reason.
+ toastApiError(err, "Failed to send message")
}
queryClient.setQueryData<PageCache>(ctx.key as ReturnType<typeof communityKeys.dmMessages>, (c) =>
markFailedById(c, ctx.tempId),
@@ -415,8 +425,8 @@ export function useToggleReaction() {
const key = args.channelId
? communityKeys.channelMessages(args.channelId)
: args.dmId
- ? communityKeys.dmMessages(args.dmId)
- : communityKeys.channelMessages("__none__")
+ ? communityKeys.dmMessages(args.dmId)
+ : communityKeys.channelMessages("__none__")
// The cache at this point reflects the optimistic flip. Reverse-derive:
// if the current `me` after flip is TRUE, we're adding; ELSE removing.
const cache = queryClient.getQueryData<PageCache>(key)
@@ -429,8 +439,8 @@ export function useToggleReaction() {
const key = args.channelId
? communityKeys.channelMessages(args.channelId)
: args.dmId
- ? communityKeys.dmMessages(args.dmId)
- : communityKeys.channelMessages("__none__")
+ ? communityKeys.dmMessages(args.dmId)
+ : communityKeys.channelMessages("__none__")
await queryClient.cancelQueries({ queryKey: key })
const cache = queryClient.getQueryData<PageCache>(key)
const originalMe = currentMeStatus(cache, args.messageId, args.emoji)
@@ -481,8 +491,8 @@ export function useToggleReactionApi(): (args: ToggleReactionArgs) => void {
const key = args.channelId
? communityKeys.channelMessages(args.channelId)
: args.dmId
- ? communityKeys.dmMessages(args.dmId)
- : communityKeys.channelMessages("__none__")
+ ? communityKeys.dmMessages(args.dmId)
+ : communityKeys.channelMessages("__none__")
const cache = queryClient.getQueryData<PageCache>(key)
const wasMe = currentMeStatus(cache, args.messageId, args.emoji)
const nextMe = !wasMe
@@ -929,7 +939,8 @@ export function useMarkAllInboxRead() {
// badges across all servers must fall to 0 in one refetch.
void queryClient.invalidateQueries({ queryKey: communityKeys.servers() })
},
- onError: () => {
+ onError: (e) => {
+ toastApiError(e, "Failed to mark inbox read")
void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })
// A partial write is possible (one of the two POSTs may have succeeded
// before the other failed) — refresh the rail badges too so the UI
@@ -960,8 +971,9 @@ export function useDeleteMention() {
// that feeds the server rail badge — refresh so the count drops.
void queryClient.invalidateQueries({ queryKey: communityKeys.servers() })
},
- onError: (_err, _args, ctx) => {
+ onError: (err, _args, ctx) => {
if (ctx?.snapshot) queryClient.setQueryData(communityKeys.inboxMentions(), ctx.snapshot)
+ toastApiError(err, "Failed to remove mention")
},
})
}
diff --git a/src/web/src/hooks/community/mutations/profile.ts b/src/web/src/hooks/community/mutations/profile.ts
index a24df53c0..17bfc06d8 100644
--- a/src/web/src/hooks/community/mutations/profile.ts
+++ b/src/web/src/hooks/community/mutations/profile.ts
@@ -1,7 +1,7 @@
"use client"
import { useMutation } from "@tanstack/react-query"
-import { apiFetch } from "@/lib/api/client"
+import { apiFetch, readUploadError } from "@/lib/api/client"
export type UpdateProfileArgs = {
name?: string
@@ -45,7 +45,7 @@ export function useUploadUserAvatar() {
body: formData,
credentials: "include",
})
- if (!res.ok) throw new Error("Upload failed")
+ if (!res.ok) throw await readUploadError(res, "Upload failed")
return (await res.json()) as UploadUserAvatarResult
},
})
diff --git a/src/web/src/hooks/community/mutations/servers.ts b/src/web/src/hooks/community/mutations/servers.ts
index cd2db7c32..6c80b66af 100644
--- a/src/web/src/hooks/community/mutations/servers.ts
+++ b/src/web/src/hooks/community/mutations/servers.ts
@@ -1,7 +1,7 @@
"use client"
import { useMutation, useQueryClient } from "@tanstack/react-query"
-import { apiFetch } from "@/lib/api/client"
+import { apiFetch, readUploadError } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import { avatarInitial } from "@/lib/community/avatar"
import type { ServersResponse, ServerDetail } from "@/hooks/community/use-servers"
@@ -148,11 +148,11 @@ export function useUpdateServer() {
queryClient.setQueryData<ServersResponse | undefined>(listKey, (prev) =>
prev
? {
- ...prev,
- servers: prev.servers.map((s) =>
- s.id === args.serverId ? { ...s, name: args.name, initial: avatarInitial(args.name) } : s,
- ),
- }
+ ...prev,
+ servers: prev.servers.map((s) =>
+ s.id === args.serverId ? { ...s, name: args.name, initial: avatarInitial(args.name) } : s,
+ ),
+ }
: prev,
)
return { serverSnap, listSnap }
@@ -180,7 +180,7 @@ export function useUploadServerIcon() {
body: formData,
credentials: "include",
})
- if (!res.ok) throw new Error("Upload failed")
+ if (!res.ok) throw await readUploadError(res, "Upload failed")
return (await res.json()) as UploadServerIconResult
},
onSuccess: (data, args) => {
@@ -194,11 +194,11 @@ export function useUploadServerIcon() {
(prev) =>
prev
? {
- ...prev,
- servers: prev.servers.map((s) =>
- s.id === args.serverId ? { ...s, icon: bustUrl } : s,
- ),
- }
+ ...prev,
+ servers: prev.servers.map((s) =>
+ s.id === args.serverId ? { ...s, icon: bustUrl } : s,
+ ),
+ }
: prev,
)
},
diff --git a/src/web/src/hooks/community/mutations/uploads.ts b/src/web/src/hooks/community/mutations/uploads.ts
index 9dbcab04a..c2a86d745 100644
--- a/src/web/src/hooks/community/mutations/uploads.ts
+++ b/src/web/src/hooks/community/mutations/uploads.ts
@@ -1,6 +1,7 @@
"use client"
import { useMutation } from "@tanstack/react-query"
+import { readUploadError } from "@/lib/api/client"
/**
* File upload mutations. These POST multipart to the channel/dm/thread upload
@@ -69,7 +70,7 @@ export function useUploadFile() {
body: formData,
credentials: "include",
})
- if (!res.ok) throw new Error("Upload failed")
+ if (!res.ok) throw await readUploadError(res, "Upload failed")
return (await res.json()) as UploadFileResult
},
})
diff --git a/src/web/src/hooks/community/use-bots.ts b/src/web/src/hooks/community/use-bots.ts
index f9a546e28..3372739d9 100644
--- a/src/web/src/hooks/community/use-bots.ts
+++ b/src/web/src/hooks/community/use-bots.ts
@@ -1,7 +1,7 @@
"use client"
import { useQuery, useMutation, useQueryClient, type UseQueryResult } from "@tanstack/react-query"
-import { apiFetch } from "@/lib/api/client"
+import { apiFetch, readUploadError } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
export type BotSummary = {
@@ -103,7 +103,7 @@ export function useUploadBotAvatar() {
body: formData,
credentials: "include",
})
- if (!res.ok) throw new Error("Upload failed")
+ if (!res.ok) throw await readUploadError(res, "Upload failed")
return (await res.json()) as UploadBotAvatarResult
},
onSuccess: (_data, variables) => invalidateBotSurfaces(qc, variables.botId),
diff --git a/src/web/src/hooks/community/use-server-members.ts b/src/web/src/hooks/community/use-server-members.ts
index 44ee69ba4..cc27bafd9 100644
--- a/src/web/src/hooks/community/use-server-members.ts
+++ b/src/web/src/hooks/community/use-server-members.ts
@@ -6,7 +6,7 @@ import {
useQueryClient,
type InfiniteData,
} from "@tanstack/react-query"
-import { apiFetch } from "@/lib/api/client"
+import { apiFetch, toastApiError } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import type { Member } from "@/components/community/_types"
import type {
@@ -414,8 +414,11 @@ export function useServerMembers(serverId: string | null): UseServerMembers {
// Guard against out-of-order responses.
if (searchSeq.current !== seq) return
setSearchResults(data.members)
- } catch {
- if (searchSeq.current === seq) setSearchResults([])
+ } catch (e) {
+ if (searchSeq.current === seq) {
+ setSearchResults([])
+ toastApiError(e, "Search failed")
+ }
}
},
[enabled, serverId],
diff --git a/src/web/src/lib/api/client.test.ts b/src/web/src/lib/api/client.test.ts
new file mode 100644
index 000000000..24798a120
--- /dev/null
+++ b/src/web/src/lib/api/client.test.ts
@@ -0,0 +1,88 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { ApiError } from "@/lib/errors"
+
+const toastErrorMock = vi.fn()
+vi.mock("sonner", () => ({
+ toast: {
+ error: (...args: unknown[]) => toastErrorMock(...args),
+ },
+}))
+
+import { getErrorMessage, toastApiError, readUploadError } from "./client"
+
+describe("getErrorMessage", () => {
+ it("returns the ApiError's message when non-empty", () => {
+ const err = new ApiError("File too large", 413)
+ expect(getErrorMessage(err, "Upload failed")).toBe("File too large")
+ })
+
+ it("returns the fallback when the ApiError's message is empty", () => {
+ const err = new ApiError("", 500)
+ expect(getErrorMessage(err, "Something went wrong")).toBe("Something went wrong")
+ })
+
+ it("returns a plain Error's message when non-empty", () => {
+ const err = new Error("network hiccup")
+ expect(getErrorMessage(err, "Failed to save")).toBe("network hiccup")
+ })
+
+ it("returns the fallback when the plain Error's message is empty", () => {
+ const err = new Error("")
+ expect(getErrorMessage(err, "Failed to save")).toBe("Failed to save")
+ })
+
+ it("returns the fallback for non-Error values", () => {
+ expect(getErrorMessage(undefined, "fallback")).toBe("fallback")
+ expect(getErrorMessage(null, "fallback")).toBe("fallback")
+ expect(getErrorMessage("just a string", "fallback")).toBe("fallback")
+ expect(getErrorMessage({ message: "not an Error instance" }, "fallback")).toBe("fallback")
+ })
+})
+
+describe("toastApiError", () => {
+ beforeEach(() => toastErrorMock.mockReset())
+
+ // `toastApiError` lazily `import("sonner")`s (see client.ts's doc comment
+ // on why) — flush the microtask queue before asserting.
+ it("calls toast.error with the resolved message from an ApiError", async () => {
+ toastApiError(new ApiError("Name already taken", 409), "Failed to create server")
+ await new Promise((r) => setTimeout(r, 0))
+ expect(toastErrorMock).toHaveBeenCalledWith("Name already taken")
+ })
+
+ it("calls toast.error with the fallback when the error carries no message", async () => {
+ toastApiError(new ApiError("", 500), "Failed to create server")
+ await new Promise((r) => setTimeout(r, 0))
+ expect(toastErrorMock).toHaveBeenCalledWith("Failed to create server")
+ })
+
+ it("calls toast.error with the fallback for a non-Error value", async () => {
+ toastApiError(undefined, "Failed to create server")
+ await new Promise((r) => setTimeout(r, 0))
+ expect(toastErrorMock).toHaveBeenCalledWith("Failed to create server")
+ })
+})
+
+describe("readUploadError", () => {
+ it("parses a JSON { error } body and returns an ApiError with that message and status", async () => {
+ const res = new Response(JSON.stringify({ error: "File exceeds 8MB limit" }), { status: 413 })
+ const err = await readUploadError(res, "Upload failed")
+ expect(err).toBeInstanceOf(ApiError)
+ expect(err.message).toBe("File exceeds 8MB limit")
+ expect(err.status).toBe(413)
+ })
+
+ it("falls back to the provided message when the body is not valid JSON", async () => {
+ const res = new Response("<html>not json</html>", { status: 500 })
+ const err = await readUploadError(res, "Upload failed")
+ expect(err.message).toBe("Upload failed")
+ expect(err.status).toBe(500)
+ })
+
+ it("falls back to the provided message when the body has no error field", async () => {
+ const res = new Response(JSON.stringify({ ok: false }), { status: 400 })
+ const err = await readUploadError(res, "Upload failed")
+ expect(err.message).toBe("Upload failed")
+ expect(err.status).toBe(400)
+ })
+})
diff --git a/src/web/src/lib/api/client.ts b/src/web/src/lib/api/client.ts
index f251023d4..a6995e771 100644
--- a/src/web/src/lib/api/client.ts
+++ b/src/web/src/lib/api/client.ts
@@ -85,7 +85,7 @@ export async function apiFetch<T>(path: string, options?: RequestInit): Promise<
if (res.status >= 500) {
throw new ApiError(
getReadableErrorMessage(serverError, details) ||
- "Something went wrong — please try again",
+ "Something went wrong — please try again",
res.status,
details,
);
@@ -102,6 +102,35 @@ export async function apiFetch<T>(path: string, options?: RequestInit): Promise<
return res.json();
}
+export function getErrorMessage(err: unknown, fallback: string): string {
+ if (err instanceof ApiError) return err.message || fallback;
+ if (err instanceof Error && err.message) return err.message;
+ return fallback;
+}
+
+// Lazy import — this module is imported by every `src/lib/api/*` consumer
+// (including non-community, server-agnostic callers under `src/lib/api.ts`'s
+// re-exports), many of which run in plain-node test environments with no
+// `document`. `sonner` injects a `<style>` tag at import time, which throws
+// outside a real DOM. A top-level `import { toast } from "sonner"` would
+// break every one of those call sites just for this optional feature.
+export function toastApiError(err: unknown, fallback: string): void {
+ void import("sonner")
+ .then(({ toast }) => toast.error(getErrorMessage(err, fallback)))
+ .catch(() => {});
+}
+
+export async function readUploadError(res: Response, fallback: string): Promise<ApiError> {
+ let serverError: string | undefined;
+ try {
+ const body = (await res.json()) as { error?: string };
+ serverError = body.error;
+ } catch {
+ // non-JSON body
+ }
+ return new ApiError(serverError || fallback, res.status);
+}
+
export function wsQuery(workspaceId: string, extra?: Record<string, string>): string {
const params = new URLSearchParams({ workspace_id: workspaceId, ...extra });
return `?${params.toString()}`;