Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

refactor(ui): move dashboard toasts from antd message/notification onto sonner (#37207)

ryan-crabbe-berri68d4ba5da521
diff --git a/ui/litellm-dashboard/eslint-suppressions.json b/ui/litellm-dashboard/eslint-suppressions.json
index bd8b6457262..c3b2bb03f11 100644
--- a/ui/litellm-dashboard/eslint-suppressions.json
+++ b/ui/litellm-dashboard/eslint-suppressions.json
@@ -9,11 +9,6 @@
"count": 2
}
},
- "src/app/(dashboard)/access-groups/_components/AccessGroupsModal/AccessGroupCreateModal.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"src/app/(dashboard)/access-groups/_components/AccessGroupsModal/AccessGroupEditModal.tsx": {
"no-restricted-imports": {
"count": 1
@@ -238,11 +233,6 @@
"count": 1
}
},
- "src/app/(dashboard)/cost-tracking/_components/pricing_calculator/multi_cost_results.test.tsx": {
- "unused-imports/no-unused-imports": {
- "count": 1
- }
- },
"src/app/(dashboard)/cost-tracking/_components/pricing_calculator/multi_cost_results.tsx": {
"local/filename-pascal-case": {
"count": 1
@@ -258,11 +248,6 @@
"count": 1
}
},
- "src/app/(dashboard)/cost-tracking/_components/provider_discount_table.test.tsx": {
- "unused-imports/no-unused-imports": {
- "count": 1
- }
- },
"src/app/(dashboard)/cost-tracking/_components/provider_discount_table.tsx": {
"local/filename-pascal-case": {
"count": 1
@@ -492,11 +477,6 @@
"count": 1
}
},
- "src/app/(dashboard)/hooks/accessGroups/useCreateAccessGroup.ts": {
- "no-restricted-syntax": {
- "count": 1
- }
- },
"src/app/(dashboard)/hooks/accessGroups/useDeleteAccessGroup.ts": {
"no-restricted-syntax": {
"count": 1
@@ -681,11 +661,6 @@
"count": 1
}
},
- "src/app/(dashboard)/mcp-servers/_components/MCPLogoSelector.test.tsx": {
- "unused-imports/no-unused-imports": {
- "count": 1
- }
- },
"src/app/(dashboard)/mcp-servers/_components/MCPNetworkSettings.tsx": {
"react-hooks/immutability": {
"count": 2
@@ -1724,14 +1699,9 @@
"count": 1
}
},
- "src/components/HelpLink.test.tsx": {
- "unused-imports/no-unused-imports": {
- "count": 1
- }
- },
"src/components/Navbar/BlogDropdown/BlogDropdown.test.tsx": {
"max-nested-callbacks": {
- "count": 12
+ "count": 10
}
},
"src/components/Navbar/UserDropdown/UserDropdown.tsx": {
@@ -1867,9 +1837,6 @@
"src/components/Teams.test.tsx": {
"max-nested-callbacks": {
"count": 4
- },
- "prefer-const": {
- "count": 6
}
},
"src/components/Teams.tsx": {
@@ -2533,27 +2500,11 @@
"src/components/molecules/message_manager.tsx": {
"local/filename-pascal-case": {
"count": 1
- },
- "no-restricted-imports": {
- "count": 2
- }
- },
- "src/components/molecules/notifications_manager.test.tsx": {
- "no-restricted-imports": {
- "count": 1
}
},
"src/components/molecules/notifications_manager.tsx": {
"local/filename-pascal-case": {
"count": 1
- },
- "no-restricted-imports": {
- "count": 3
- }
- },
- "src/components/navbar.test.tsx": {
- "prefer-const": {
- "count": 1
}
},
"src/components/navbar.tsx": {
@@ -2932,11 +2883,6 @@
"count": 2
}
},
- "src/components/templates/key_info_view.test.tsx": {
- "unused-imports/no-unused-imports": {
- "count": 2
- }
- },
"src/components/templates/key_info_view.tsx": {
"local/filename-pascal-case": {
"count": 1
@@ -3086,6 +3032,11 @@
"count": 1
}
},
+ "src/components/ui/sonner.tsx": {
+ "local/filename-pascal-case": {
+ "count": 1
+ }
+ },
"src/components/ui/switch.tsx": {
"local/filename-pascal-case": {
"count": 1
@@ -3189,11 +3140,6 @@
"count": 2
}
},
- "src/components/view_logs/LogDetailsDrawer/RealtimePrettyView.test.tsx": {
- "unused-imports/no-unused-imports": {
- "count": 2
- }
- },
"src/components/view_logs/LogDetailsDrawer/useKeyboardNavigation.ts": {
"react-hooks/immutability": {
"count": 2
@@ -3324,4 +3270,4 @@
"count": 1
}
}
-}
+}
\ No newline at end of file
diff --git a/ui/litellm-dashboard/package-lock.json b/ui/litellm-dashboard/package-lock.json
index 92fc37c959c..93ee979f37d 100644
--- a/ui/litellm-dashboard/package-lock.json
+++ b/ui/litellm-dashboard/package-lock.json
@@ -42,6 +42,7 @@
"react-syntax-highlighter": "15.6.6",
"recharts": "3.9.2",
"remark-gfm": "4.0.1",
+ "sonner": "2.0.8",
"tailwind-merge": "3.4.0",
"uuid": "14.0.0",
"zod": "3.25.76"
@@ -12860,6 +12861,22 @@
"url": "https://github.com/sponsors/cyyynthia"
}
},
+ "node_modules/sonner": {
+ "version": "2.0.8",
+ "resolved": "https://registry.npmjs.org/sonner/-/sonner-2.0.8.tgz",
+ "integrity": "sha512-UM/ByIoFra8yzV75n1o0Puu0bw5U/9UNnDacrJNspekBewIfsQ3D6ez1nvlWpt7aTsO6rujQtifBpycwIivqlg==",
+ "license": "MIT",
+ "peerDependencies": {
+ "@types/react": "^18.0.0 || ^19.0.0",
+ "react": "^18.0.0 || ^19.0.0 || ^19.0.0-rc",
+ "react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
diff --git a/ui/litellm-dashboard/package.json b/ui/litellm-dashboard/package.json
index 67e85783f9f..483ab39c336 100644
--- a/ui/litellm-dashboard/package.json
+++ b/ui/litellm-dashboard/package.json
@@ -55,6 +55,7 @@
"react-syntax-highlighter": "15.6.6",
"recharts": "3.9.2",
"remark-gfm": "4.0.1",
+ "sonner": "2.0.8",
"tailwind-merge": "3.4.0",
"uuid": "14.0.0",
"zod": "3.25.76"
diff --git a/ui/litellm-dashboard/src/app/layout.tsx b/ui/litellm-dashboard/src/app/layout.tsx
index 3d6c6e4c2eb..bf32dd7109f 100644
--- a/ui/litellm-dashboard/src/app/layout.tsx
+++ b/ui/litellm-dashboard/src/app/layout.tsx
@@ -7,6 +7,7 @@ import { NuqsAdapter } from "nuqs/adapters/next/app";
import AntdGlobalProvider from "@/contexts/AntdGlobalProvider";
import { AuthProvider } from "@/contexts/AuthContext";
import ReactQueryProvider from "@/contexts/ReactQueryProvider";
+import { Toaster } from "@/components/ui/sonner";
const inter = Inter({ subsets: ["latin"] });
@@ -28,6 +29,7 @@ export default function RootLayout({
<ReactQueryProvider>
<AntdGlobalProvider>
<AuthProvider>{children}</AuthProvider>
+ <Toaster />
</AntdGlobalProvider>
</ReactQueryProvider>
</NuqsAdapter>
diff --git a/ui/litellm-dashboard/src/components/Settings/RouterSettings/Fallbacks/AddFallbacks.test.tsx b/ui/litellm-dashboard/src/components/Settings/RouterSettings/Fallbacks/AddFallbacks.test.tsx
index 1cdb57335ce..eaced9e22b0 100644
--- a/ui/litellm-dashboard/src/components/Settings/RouterSettings/Fallbacks/AddFallbacks.test.tsx
+++ b/ui/litellm-dashboard/src/components/Settings/RouterSettings/Fallbacks/AddFallbacks.test.tsx
@@ -3,20 +3,15 @@ import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
import AddFallbacks, { Fallbacks } from "./AddFallbacks";
import * as fetchModelsModule from "@/components/llm_calls/fetch_models";
+import MessageManager from "@/components/molecules/message_manager";
vi.mock("@/components/llm_calls/fetch_models", () => ({
fetchAvailableModels: vi.fn(),
}));
-vi.mock("antd", async (importOriginal) => {
- const actual = await importOriginal<typeof import("antd")>();
- return {
- ...actual,
- message: {
- error: vi.fn(),
- },
- };
-});
+vi.mock("@/components/molecules/message_manager", () => ({
+ default: { error: vi.fn(), success: vi.fn(), warning: vi.fn(), info: vi.fn(), destroy: vi.fn() },
+}));
vi.mock("./FallbackSelectionForm", () => ({
FallbackSelectionForm: ({ groups, onGroupsChange }: any) => {
@@ -122,7 +117,6 @@ describe("AddFallbacks", () => {
it("should show error when saving incomplete groups", async () => {
const user = userEvent.setup();
- const antd = await import("antd");
render(<AddFallbacks {...defaultProps} />);
const addButton = screen.getByRole("button", { name: /add fallbacks/i });
@@ -141,13 +135,12 @@ describe("AddFallbacks", () => {
await user.click(saveButton);
await waitFor(() => {
- expect(antd.message.error).toHaveBeenCalled();
+ expect(MessageManager.error).toHaveBeenCalled();
});
});
it("should show error message when saving incomplete groups", async () => {
const user = userEvent.setup();
- const antd = await import("antd");
render(<AddFallbacks {...defaultProps} />);
const addButton = screen.getByRole("button", { name: /add fallbacks/i });
@@ -161,7 +154,7 @@ describe("AddFallbacks", () => {
await user.click(saveButton);
await waitFor(() => {
- expect(antd.message.error).toHaveBeenCalled();
+ expect(MessageManager.error).toHaveBeenCalled();
});
});
diff --git a/ui/litellm-dashboard/src/components/Settings/RouterSettings/Fallbacks/FallbackSelectionForm.test.tsx b/ui/litellm-dashboard/src/components/Settings/RouterSettings/Fallbacks/FallbackSelectionForm.test.tsx
index 21ce50dda01..7f013a56229 100644
--- a/ui/litellm-dashboard/src/components/Settings/RouterSettings/Fallbacks/FallbackSelectionForm.test.tsx
+++ b/ui/litellm-dashboard/src/components/Settings/RouterSettings/Fallbacks/FallbackSelectionForm.test.tsx
@@ -3,20 +3,14 @@ import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { FallbackSelectionForm } from "./FallbackSelectionForm";
import type { FallbackGroup } from "./FallbackGroupConfig";
+import MessageManager from "@/components/molecules/message_manager";
const mockOnGroupsChange = vi.fn();
const AVAILABLE_MODELS = ["gpt-4", "gpt-3.5-turbo", "claude-3-opus"];
-vi.mock("antd", async (importOriginal) => {
- const actual = await importOriginal<typeof import("antd")>();
- return {
- ...actual,
- message: {
- ...actual.message,
- warning: vi.fn(),
- },
- };
-});
+vi.mock("@/components/molecules/message_manager", () => ({
+ default: { error: vi.fn(), success: vi.fn(), warning: vi.fn(), info: vi.fn(), destroy: vi.fn() },
+}));
describe("FallbackSelectionForm", () => {
beforeEach(() => {
@@ -126,7 +120,6 @@ describe("FallbackSelectionForm", () => {
it("should call onGroupsChange when a group is removed", async () => {
const user = userEvent.setup();
- const antd = await import("antd");
const groups: FallbackGroup[] = [
{ id: "1", primaryModel: "gpt-4", fallbackModels: [] },
{ id: "2", primaryModel: "gpt-3.5-turbo", fallbackModels: [] },
@@ -142,7 +135,7 @@ describe("FallbackSelectionForm", () => {
const [newGroups] = mockOnGroupsChange.mock.calls[0];
expect(newGroups).toHaveLength(1);
expect(newGroups[0].id).toBe("2");
- expect(antd.message.warning).not.toHaveBeenCalled();
+ expect(MessageManager.warning).not.toHaveBeenCalled();
});
it("should render FallbackGroupConfig for each group", () => {
diff --git a/ui/litellm-dashboard/src/components/molecules/message_manager.test.ts b/ui/litellm-dashboard/src/components/molecules/message_manager.test.ts
index 541efcbc4cb..197a7442978 100644
--- a/ui/litellm-dashboard/src/components/molecules/message_manager.test.ts
+++ b/ui/litellm-dashboard/src/components/molecules/message_manager.test.ts
@@ -1,107 +1,73 @@
-import { describe, expect, it, vi, beforeEach } from "vitest";
+import { createElement } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
-// Use vi.hoisted so the mock object is available when vi.mock is hoisted
-const mockStaticMessage = vi.hoisted(() => ({
+const sonner = vi.hoisted(() => ({
success: vi.fn(),
- error: vi.fn(),
- warning: vi.fn(),
info: vi.fn(),
- loading: vi.fn(),
- destroy: vi.fn(),
+ warning: vi.fn(),
+ error: vi.fn(),
+ dismiss: vi.fn(),
}));
-vi.mock("antd", () => ({
- message: mockStaticMessage,
-}));
+vi.mock("sonner", () => ({ toast: sonner }));
+vi.mock("@/components/molecules/notifications_manager", () =>
+ vi.importActual<typeof import("./notifications_manager")>("./notifications_manager"),
+);
-import MessageManager, { setMessageInstance } from "./message_manager";
+import MessageManager from "./message_manager";
+import NotificationManager from "./notifications_manager";
-describe("MessageManager", () => {
+describe("legacy toast facades", () => {
beforeEach(() => {
vi.clearAllMocks();
});
- describe("when no instance is set (falls back to static message)", () => {
- it("delegates success to static message", () => {
- MessageManager.success("done!");
- expect(mockStaticMessage.success).toHaveBeenCalledWith("done!", undefined);
- });
-
- it("delegates error to static message", () => {
- MessageManager.error("failed!", 5);
- expect(mockStaticMessage.error).toHaveBeenCalledWith("failed!", 5);
- });
-
- it("delegates warning to static message", () => {
- MessageManager.warning("watch out");
- expect(mockStaticMessage.warning).toHaveBeenCalledWith("watch out", undefined);
- });
-
- it("delegates info to static message", () => {
- MessageManager.info("fyi");
- expect(mockStaticMessage.info).toHaveBeenCalledWith("fyi", undefined);
- });
-
- it("delegates loading to static message", () => {
- MessageManager.loading("loading...", 3);
- expect(mockStaticMessage.loading).toHaveBeenCalledWith("loading...", 3);
- });
-
- it("delegates destroy to static message", () => {
- MessageManager.destroy();
- expect(mockStaticMessage.destroy).toHaveBeenCalled();
- });
+ it("MessageManager converts antd-era seconds into milliseconds", () => {
+ MessageManager.error("failed!", 5);
+ expect(sonner.error).toHaveBeenCalledWith("failed!", { description: undefined, duration: 5000 });
});
- describe("when a custom instance is set", () => {
- const mockInstance = {
- success: vi.fn(),
- error: vi.fn(),
- warning: vi.fn(),
- info: vi.fn(),
- loading: vi.fn(),
- destroy: vi.fn(),
- open: vi.fn(),
- };
+ it("MessageManager falls back to the kind default when no duration is given", () => {
+ MessageManager.success("done!");
+ expect(sonner.success).toHaveBeenCalledWith("done!", { description: undefined, duration: 4000 });
+ });
- beforeEach(() => {
- vi.clearAllMocks();
- setMessageInstance(mockInstance as any);
- });
+ it("MessageManager.destroy and NotificationManager.clear both dismiss", () => {
+ MessageManager.destroy();
+ NotificationManager.clear();
+ expect(sonner.dismiss).toHaveBeenCalledTimes(2);
+ });
- it("delegates success to custom instance", () => {
- MessageManager.success("done!");
- expect(mockInstance.success).toHaveBeenCalledWith("done!", undefined);
- expect(mockStaticMessage.success).not.toHaveBeenCalled();
- });
+ it("NotificationManager.fromBackend routes through toast.fromError", () => {
+ NotificationManager.fromBackend({ message: "Team not found", type: "not_found_error", code: "404" });
+ expect(sonner.error).toHaveBeenCalledWith("Not Found", { description: "Team not found", duration: 6000 });
+ });
- it("delegates error with duration to custom instance", () => {
- MessageManager.error("failed!", 5);
- expect(mockInstance.error).toHaveBeenCalledWith("failed!", 5);
- expect(mockStaticMessage.error).not.toHaveBeenCalled();
- });
+ it("NotificationManager.fromBackend converts the antd-era extra.duration seconds", () => {
+ NotificationManager.fromBackend("boom", { duration: 8 });
+ expect(sonner.error).toHaveBeenCalledWith("Error", { description: "boom", duration: 8000 });
+ });
- it("delegates warning to custom instance", () => {
- MessageManager.warning("watch out");
- expect(mockInstance.warning).toHaveBeenCalledWith("watch out", undefined);
+ it("NotificationManager keeps the antd config-object form: message is the title, description below it", () => {
+ NotificationManager.success({
+ message: "MCP Server submitted for admin review",
+ description: "Once an admin approves it, the server will appear in your MCP Servers list.",
+ duration: 10,
});
-
- it("delegates info to custom instance", () => {
- MessageManager.info("fyi", 2);
- expect(mockInstance.info).toHaveBeenCalledWith("fyi", 2);
+ expect(sonner.success).toHaveBeenCalledWith("MCP Server submitted for admin review", {
+ description: "Once an admin approves it, the server will appear in your MCP Servers list.",
+ duration: 10000,
});
+ });
- it("delegates loading to custom instance and returns result", () => {
- const mockReturn = { then: vi.fn() };
- mockInstance.loading.mockReturnValue(mockReturn);
- const result = MessageManager.loading("loading...", 3);
- expect(mockInstance.loading).toHaveBeenCalledWith("loading...", 3);
- expect(result).toBe(mockReturn);
- });
+ it("NotificationManager falls back to the kind's title when a config object has no message", () => {
+ NotificationManager.warning({ description: "Heads up" });
+ expect(sonner.warning).toHaveBeenCalledWith("Warning", { description: "Heads up", duration: 6000 });
+ });
- it("delegates destroy to custom instance", () => {
- MessageManager.destroy();
- expect(mockInstance.destroy).toHaveBeenCalled();
- });
+ it("NotificationManager treats a React element as the message, not a config object", () => {
+ const element = createElement("span", null, "done");
+ NotificationManager.info(element);
+ expect(sonner.info).toHaveBeenCalledWith(element, { description: undefined, duration: 4000 });
});
});
diff --git a/ui/litellm-dashboard/src/components/molecules/message_manager.tsx b/ui/litellm-dashboard/src/components/molecules/message_manager.tsx
index e4c1552d5ee..36ed0b52496 100644
--- a/ui/litellm-dashboard/src/components/molecules/message_manager.tsx
+++ b/ui/litellm-dashboard/src/components/molecules/message_manager.tsx
@@ -1,38 +1,14 @@
-import { message as staticMessage } from "antd";
-import type { MessageInstance } from "antd/es/message/interface";
+import { toast } from "@/lib/toast";
-let messageInstance: MessageInstance | null = null;
-
-export const setMessageInstance = (instance: MessageInstance) => {
- messageInstance = instance;
-};
-
-const getMessageApi = () => messageInstance || staticMessage;
+const secondsToMs = (seconds: number | undefined): number | undefined =>
+ seconds === undefined ? undefined : seconds * 1000;
const MessageManager = {
- success(content: string, duration?: number) {
- getMessageApi().success(content, duration);
- },
-
- error(content: string, duration?: number) {
- getMessageApi().error(content, duration);
- },
-
- warning(content: string, duration?: number) {
- getMessageApi().warning(content, duration);
- },
-
- info(content: string, duration?: number) {
- getMessageApi().info(content, duration);
- },
-
- loading(content: string, duration?: number) {
- return getMessageApi().loading(content, duration);
- },
-
- destroy() {
- getMessageApi().destroy();
- },
+ success: (content: string, duration?: number): void => toast.success(content, { durationMs: secondsToMs(duration) }),
+ error: (content: string, duration?: number): void => toast.error(content, { durationMs: secondsToMs(duration) }),
+ warning: (content: string, duration?: number): void => toast.warning(content, { durationMs: secondsToMs(duration) }),
+ info: (content: string, duration?: number): void => toast.info(content, { durationMs: secondsToMs(duration) }),
+ destroy: (): void => toast.dismiss(),
};
export default MessageManager;
diff --git a/ui/litellm-dashboard/src/components/molecules/notifications_manager.test.tsx b/ui/litellm-dashboard/src/components/molecules/notifications_manager.test.tsx
deleted file mode 100644
index c886f78b4b1..00000000000
--- a/ui/litellm-dashboard/src/components/molecules/notifications_manager.test.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-import { notification } from "antd";
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import NotificationManager, { COMMON_NOTIFICATION_PROPS } from "./notifications_manager";
-
-vi.mock("@/components/molecules/notifications_manager", async () => {
- const actual = await vi.importActual<typeof import("@/components/molecules/notifications_manager")>(
- "@/components/molecules/notifications_manager",
- );
-
- return actual;
-});
-
-// Mock the antd notification module
-vi.mock("antd", () => ({
- notification: {
- error: vi.fn(),
- warning: vi.fn(),
- info: vi.fn(),
- success: vi.fn(),
- destroy: vi.fn(),
- },
-}));
-
-describe("NotificationManager", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- describe("Already Exists case", () => {
- it("should show error notification for 'already exists' message", () => {
- const error = {
- message: "Key with alias 'test10' already exists.",
- type: "bad_request_error",
- code: "400",
- };
-
- NotificationManager.fromBackend(error);
-
- expect(notification.error).toHaveBeenCalledWith(
- expect.objectContaining({
- message: "Already Exists",
- description: "Key with alias 'test10' already exists.",
- duration: 6,
- placement: "topRight",
- }),
- );
- });
- });
-
- describe("COMMON_NOTIFICATION_PROPS", () => {
- const notificationTypes = [
- { type: "error", method: NotificationManager.error, mockFn: notification.error },
- { type: "warning", method: NotificationManager.warning, mockFn: notification.warning },
- { type: "info", method: NotificationManager.info, mockFn: notification.info },
- { type: "success", method: NotificationManager.success, mockFn: notification.success },
- ];
-
- notificationTypes.forEach(({ type, method, mockFn }) => {
- it(`should pass COMMON_NOTIFICATION_PROPS to ${type} notifications`, () => {
- method(`Test ${type}`);
-
- expect(mockFn).toHaveBeenCalledWith(
- expect.objectContaining({
- ...COMMON_NOTIFICATION_PROPS,
- }),
- );
- });
- });
- });
-});
diff --git a/ui/litellm-dashboard/src/components/molecules/notifications_manager.tsx b/ui/litellm-dashboard/src/components/molecules/notifications_manager.tsx
index 59b048b412c..2805f22a52e 100644
--- a/ui/litellm-dashboard/src/components/molecules/notifications_manager.tsx
+++ b/ui/litellm-dashboard/src/components/molecules/notifications_manager.tsx
@@ -1,371 +1,48 @@
-import React from "react";
-import { notification as staticNotification } from "antd";
-import type { NotificationInstance } from "antd/es/notification/interface";
-import { parseErrorMessage } from "../shared/errorUtils";
-import { ArgsProps } from "antd/es/notification";
-
-let notificationInstance: NotificationInstance | null = null;
-
-export const setNotificationInstance = (instance: NotificationInstance) => {
- notificationInstance = instance;
+import { isValidElement, type ReactNode } from "react";
+import { toast, type ToastKind } from "@/lib/toast";
+
+export type NotificationConfig = {
+ readonly message?: ReactNode;
+ readonly description?: ReactNode;
+ readonly duration?: number;
+ readonly placement?: string;
+ readonly key?: string;
};
-// Helper to get the best available notification instance
-const getNotification = () => notificationInstance || staticNotification;
-
-type Placement = "top" | "topLeft" | "topRight" | "bottom" | "bottomLeft" | "bottomRight";
+type NotificationInput = ReactNode | NotificationConfig;
-type NotificationConfig = {
- message?: string | React.ReactNode;
- description?: string | React.ReactNode;
- duration?: number;
- placement?: Placement;
- key?: string;
+const FALLBACK_TITLES: Readonly<Record<ToastKind, string>> = {
+ success: "Success",
+ info: "Info",
+ warning: "Warning",
+ error: "Error",
};
-type NotificationConfigResolved = Omit<NotificationConfig, "message"> & { message: string | React.ReactNode };
-
-function defaultPlacement(): Placement {
- return "topRight";
-}
-
-function normalize(input: string | NotificationConfig, fallbackTitle: string): NotificationConfigResolved {
- if (typeof input === "string") return { message: fallbackTitle, description: input };
- return { message: input.message ?? fallbackTitle, ...input };
-}
-
-function toIntMaybe(val: any): number | undefined {
- if (typeof val === "number") return val;
- if (typeof val === "string" && /^\d+$/.test(val)) return parseInt(val, 10);
- return undefined;
-}
-
-const AUTH_MATCH = [
- "invalid api key",
- "invalid authorization header format",
- "authentication error",
- "invalid proxy server token",
- "invalid jwt token",
- "invalid jwt submitted",
- "unauthorized access to metrics endpoint",
-];
-
-const FORBIDDEN_MATCH = [
- "admin-only endpoint",
- "not allowed to access model",
- "user does not have permission",
- "access forbidden",
- "invalid credentials used to access ui",
- "user not allowed to access proxy",
-];
-
-const DB_MATCH = [
- "db not connected",
- "database not initialized",
- "no db connected",
- "prisma client not initialized",
- "service unhealthy",
-];
-
-const ROUTER_MATCH = [
- "no models configured on proxy",
- "llm router not initialized",
- "no deployments available",
- "no healthy deployment available",
- "not allowed to access model due to tags configuration",
- "invalid model name passed in",
-];
-
-const RATE_LIMIT_EXTRA = [
- "deployment over user-defined ratelimit",
- "crossed tpm / rpm / max parallel request limit",
- "max parallel request limit",
-];
-
-const BUDGET_MATCH = ["budget exceeded", "crossed budget", "provider budget"];
-
-const ENTERPRISE_MATCH = [
- "must be a litellm enterprise user",
- "only be available for liteLLM enterprise users",
- "missing litellm-enterprise package",
- "only available on the docker image",
- "enterprise feature",
- "premium user",
-];
-
-const VALIDATION_MATCH = [
- "invalid json payload",
- "invalid request type",
- "invalid key format",
- "invalid hash key",
- "invalid sort column",
- "invalid sort order",
- "invalid limit",
- "invalid file type",
- "invalid field",
- "invalid date format",
-];
-
-const NOT_FOUND_MATCH = [
- "model not found",
- "model with id",
- "credential not found",
- "user not found",
- "team not found",
- "organization not found",
- "mcp server with id",
- "tool '", // will combine with “not found” in message
-];
-
-const EXISTS_MATCH = ["already exists", "team member is already in team", "user already exists"];
-
-const GUARDRAIL_MATCH = [
- "violated openai moderation policy",
- "violated jailbreak threshold",
- "violated prompt_injection threshold",
- "violated content safety policy",
- "violated lasso guardrail policy",
- "blocked by pillar security guardrail",
- "violated azure prompt shield guardrail policy",
- "content blocked by model armor",
- "response blocked by model armor",
- "streaming response blocked by model armor",
- "guardrail",
- "moderation",
-];
-
-const FILE_UPLOAD_MATCH = [
- "invalid purpose",
- "service must be specified",
- "invalid response - response.response is none",
-];
-
-const CLOUDZERO_MATCH = [
- "cloudzero settings not configured",
- "failed to decrypt cloudzero api key",
- "cloudzero settings not found",
-];
-
-function titleFor(status?: number, desc?: string): string {
- const d = (desc || "").toLowerCase();
-
- if (AUTH_MATCH.some((s) => d.includes(s))) return "Authentication Error";
- if (FORBIDDEN_MATCH.some((s) => d.includes(s))) return "Access Denied";
- if (DB_MATCH?.some?.((s: string) => d.includes(s)) || status === 503) return "Service Unavailable";
- if (BUDGET_MATCH?.some?.((s: string) => d.includes(s))) return "Budget Exceeded";
- if (ENTERPRISE_MATCH?.some?.((s: string) => d.includes(s))) return "Feature Unavailable";
- if (ROUTER_MATCH?.some?.((s: string) => d.includes(s))) return "Routing Error";
-
- if (EXISTS_MATCH.some((s) => d.includes(s))) return "Already Exists";
- if (GUARDRAIL_MATCH.some((s) => d.includes(s))) return "Content Blocked";
-
- if (FILE_UPLOAD_MATCH.some((s) => d.includes(s))) return "Validation Error";
- if (CLOUDZERO_MATCH.some((s) => d.includes(s))) return "Integration Error";
-
- if (VALIDATION_MATCH.some((s) => d.includes(s))) return "Validation Error";
- if (status === 404 || d.includes("not found") || NOT_FOUND_MATCH.some((s) => d.includes(s))) return "Not Found";
- if (
- status === 429 ||
- d.includes("rate limit") ||
- d.includes("tpm") ||
- d.includes("rpm") ||
- RATE_LIMIT_EXTRA?.some?.((s: string) => d.includes(s))
- )
- return "Rate Limit Exceeded";
- if (status && status >= 500) return "Server Error";
- if (status === 401) return "Authentication Error";
- if (status === 403) return "Access Denied";
- if (d.includes("enterprise") || d.includes("premium")) return "Info";
- if (status && status >= 400) return "Request Error";
- return "Error";
-}
-
-const SUCCESS_MATCH = [
- "created successfully",
- "updated successfully",
- "deleted successfully",
- "credential created successfully",
- "model added successfully",
- "team created successfully",
- "user created successfully",
- "organization created successfully",
- "cloudzero settings initialized successfully",
- "cloudzero settings updated successfully",
- "cloudzero export completed successfully",
- "mock llm request made",
- "mock slack alert sent",
- "mock email alert sent",
- "spend for all api keys and teams reset successfully",
- "monthlyglobalspend view refreshed",
- "cache cleared successfully",
- "cache set successfully",
- "ip ",
- "deleted successfully",
-];
-
-const INFO_MATCH = ["rate limit reached for deployment", "deployment cooldown period active"];
-
-const DEPRECATION_FEATURE_WARN_MATCH = [
- "this feature is only available for litellm enterprise users",
- "enterprise features are not available",
- "regenerating virtual keys is an enterprise feature",
- "trying to set allowed_routes. this is an enterprise feature",
-];
-
-const CONFIG_WARN_MATCH = [
- "invalid maximum_spend_logs_retention_interval value",
- "error has invalid or non-convertible code",
- "failed to save health check to database",
-];
-
-function classifyGeneralMessage(desc?: string): { kind: "success" | "info" | "warning"; title: string } | null {
- const d = (desc || "").toLowerCase();
-
- if (SUCCESS_MATCH.some((s) => d.includes(s))) return { kind: "success", title: "Success" };
- if (DEPRECATION_FEATURE_WARN_MATCH.some((s) => d.includes(s))) return { kind: "warning", title: "Feature Notice" };
- if (CONFIG_WARN_MATCH.some((s) => d.includes(s))) return { kind: "warning", title: "Configuration Warning" };
- if (INFO_MATCH.some((s) => d.includes(s))) return { kind: "warning", title: "Rate Limit" }; // show as warning for visibility
-
- return null;
-}
-
-function extractStatus(input: any): number | undefined {
- return toIntMaybe(input?.response?.status) ?? toIntMaybe(input?.status_code) ?? toIntMaybe(input?.code);
-}
-
-function extractDescription(input: any): string {
- if (typeof input === "string") return input; // raw error string
- const backendMsg =
- input?.response?.data?.error?.message ??
- input?.response?.data?.message ??
- input?.response?.data?.error ??
- input?.detail ??
- input?.message ??
- input;
- return parseErrorMessage(backendMsg);
-}
-
-export const COMMON_NOTIFICATION_PROPS: Partial<ArgsProps> = {
- showProgress: true,
- pauseOnHover: true,
+const secondsToMs = (seconds: number | undefined): number | undefined =>
+ seconds === undefined ? undefined : seconds * 1000;
+
+const isConfig = (input: NotificationInput): input is NotificationConfig =>
+ input !== null && typeof input === "object" && !isValidElement(input) && !(Symbol.iterator in input);
+
+const show = (kind: ToastKind, input: NotificationInput): void => {
+ if (!isConfig(input)) {
+ toast[kind](input);
+ return;
+ }
+ toast[kind](input.message ?? FALLBACK_TITLES[kind], {
+ description: input.description,
+ durationMs: secondsToMs(input.duration),
+ });
};
-function looksErrorPayload(input: any, status?: number): boolean {
- if (status !== undefined) return true;
- if (input instanceof Error) return true;
- if (typeof input === "string") return true; // treat raw strings passed to fromBackend as errors
- if (input && typeof input === "object" && ("error" in input || "detail" in input)) return true;
- return false;
-}
-
const NotificationManager = {
- error(input: string | NotificationConfig) {
- const cfg = normalize(input, "Error");
- getNotification().error({
- ...COMMON_NOTIFICATION_PROPS,
- ...cfg,
- placement: cfg.placement ?? defaultPlacement(),
- duration: cfg.duration ?? 6,
- });
- },
-
- warning(input: string | NotificationConfig) {
- const cfg = normalize(input, "Warning");
- getNotification().warning({
- ...COMMON_NOTIFICATION_PROPS,
- ...cfg,
- placement: cfg.placement ?? defaultPlacement(),
- duration: cfg.duration ?? 5,
- });
- },
-
- info(input: string | NotificationConfig) {
- const cfg = normalize(input, "Info");
- getNotification().info({
- ...COMMON_NOTIFICATION_PROPS,
- ...cfg,
- placement: cfg.placement ?? defaultPlacement(),
- duration: cfg.duration ?? 4,
- });
- },
-
- success(input: string | React.ReactNode | NotificationConfig) {
- if (React.isValidElement(input)) {
- getNotification().success({
- ...COMMON_NOTIFICATION_PROPS,
- message: "Success",
- description: input,
- placement: defaultPlacement(),
- duration: 3.5,
- });
- return;
- }
- const cfg = normalize(input as string | NotificationConfig, "Success");
- getNotification().success({
- ...COMMON_NOTIFICATION_PROPS,
- ...cfg,
- placement: cfg.placement ?? defaultPlacement(),
- duration: cfg.duration ?? 3.5,
- });
- },
-
- fromBackend(input: any, extra?: Omit<NotificationConfig, "message" | "description">) {
- const status = extractStatus(input);
- const description = extractDescription(input);
- const base = { ...(extra ?? {}), description, placement: extra?.placement ?? defaultPlacement() };
-
- if (looksErrorPayload(input, status)) {
- const title = titleFor(status, description);
- const payload = { ...base, message: title };
-
- if (
- title === "Rate Limit Exceeded" ||
- title === "Info" ||
- title === "Budget Exceeded" ||
- title === "Feature Unavailable" ||
- title === "Content Blocked" ||
- title === "Integration Error"
- ) {
- getNotification().warning({ ...COMMON_NOTIFICATION_PROPS, ...payload, duration: extra?.duration ?? 7 });
- return;
- }
- if (title === "Server Error") {
- getNotification().error({ ...COMMON_NOTIFICATION_PROPS, ...payload, duration: extra?.duration ?? 8 });
- return;
- }
- if (
- title === "Request Error" ||
- title === "Authentication Error" ||
- title === "Access Denied" ||
- title === "Not Found" ||
- title === "Error" ||
- title === "Already Exists"
- ) {
- getNotification().error({ ...COMMON_NOTIFICATION_PROPS, ...payload, duration: extra?.duration ?? 6 });
- return;
- }
- getNotification().info({ ...COMMON_NOTIFICATION_PROPS, ...payload, duration: extra?.duration ?? 4 });
- return;
- }
-
- // Non-error: success/info/warning classifier
- const cls = classifyGeneralMessage(description);
- const payload = { ...base, message: cls?.title ?? "Info" };
-
- if (cls?.kind === "success") {
- getNotification().success({ ...COMMON_NOTIFICATION_PROPS, ...payload, duration: extra?.duration ?? 3.5 });
- return;
- }
- if (cls?.kind === "warning") {
- getNotification().warning({ ...COMMON_NOTIFICATION_PROPS, ...payload, duration: extra?.duration ?? 6 });
- return;
- }
- getNotification().info({ ...COMMON_NOTIFICATION_PROPS, ...payload, duration: extra?.duration ?? 4 });
- },
-
- clear() {
- getNotification().destroy();
- },
+ success: (input: NotificationInput): void => show("success", input),
+ info: (input: NotificationInput): void => show("info", input),
+ warning: (input: NotificationInput): void => show("warning", input),
+ error: (input: NotificationInput): void => show("error", input),
+ fromBackend: (input: unknown, extra?: Omit<NotificationConfig, "message" | "description">): void =>
+ toast.fromError(input, { durationMs: secondsToMs(extra?.duration) }),
+ clear: (): void => toast.dismiss(),
};
export default NotificationManager;
diff --git a/ui/litellm-dashboard/src/components/ui/sonner.tsx b/ui/litellm-dashboard/src/components/ui/sonner.tsx
new file mode 100644
index 00000000000..034e093a118
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/ui/sonner.tsx
@@ -0,0 +1,34 @@
+"use client";
+
+import { CircleCheckIcon, InfoIcon, Loader2Icon, OctagonXIcon, TriangleAlertIcon } from "lucide-react";
+import { Toaster as Sonner, type ToasterProps } from "sonner";
+
+function Toaster({ ...props }: ToasterProps) {
+ return (
+ <Sonner
+ theme="light"
+ position="top-right"
+ closeButton
+ className="toaster group"
+ icons={{
+ success: <CircleCheckIcon className="size-4" />,
+ info: <InfoIcon className="size-4" />,
+ warning: <TriangleAlertIcon className="size-4" />,
+ error: <OctagonXIcon className="size-4" />,
+ loading: <Loader2Icon className="size-4 animate-spin" />,
+ }}
+ style={
+ {
+ "--normal-bg": "var(--popover)",
+ "--normal-text": "var(--popover-foreground)",
+ "--normal-border": "var(--border)",
+ "--border-radius": "var(--radius)",
+ } as React.CSSProperties
+ }
+ toastOptions={{ classNames: { toast: "cn-toast" } }}
+ {...props}
+ />
+ );
+}
+
+export { Toaster };
diff --git a/ui/litellm-dashboard/src/contexts/AntdGlobalProvider.tsx b/ui/litellm-dashboard/src/contexts/AntdGlobalProvider.tsx
index 3cb1bce444b..90370e3b00b 100644
--- a/ui/litellm-dashboard/src/contexts/AntdGlobalProvider.tsx
+++ b/ui/litellm-dashboard/src/contexts/AntdGlobalProvider.tsx
@@ -1,31 +1,13 @@
"use client";
-import React, { useEffect, useRef } from "react";
-import { ConfigProvider, notification, message } from "antd";
+import React from "react";
+import { ConfigProvider } from "antd";
import { StyleProvider } from "@ant-design/cssinjs";
-import { setNotificationInstance } from "@/components/molecules/notifications_manager";
-import { setMessageInstance } from "@/components/molecules/message_manager";
export default function AntdGlobalProvider({ children }: { children: React.ReactNode }) {
- const [notificationApi, notificationContextHolder] = notification.useNotification();
- const [messageApi, messageContextHolder] = message.useMessage();
- const initialized = useRef(false);
-
- useEffect(() => {
- if (!initialized.current) {
- setNotificationInstance(notificationApi);
- setMessageInstance(messageApi);
- initialized.current = true;
- }
- }, [notificationApi, messageApi]);
-
return (
<StyleProvider layer>
- <ConfigProvider theme={{ cssVar: true }}>
- {notificationContextHolder}
- {messageContextHolder}
- {children}
- </ConfigProvider>
+ <ConfigProvider theme={{ cssVar: true }}>{children}</ConfigProvider>
</StyleProvider>
);
}
diff --git a/ui/litellm-dashboard/src/lib/toast.test.ts b/ui/litellm-dashboard/src/lib/toast.test.ts
new file mode 100644
index 00000000000..fb22c9039bf
--- /dev/null
+++ b/ui/litellm-dashboard/src/lib/toast.test.ts
@@ -0,0 +1,177 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { ApiError } from "@/lib/http/client";
+
+const sonner = vi.hoisted(() => ({
+ success: vi.fn(),
+ info: vi.fn(),
+ warning: vi.fn(),
+ error: vi.fn(),
+ dismiss: vi.fn(),
+}));
+
+vi.mock("sonner", () => ({ toast: sonner }));
+
+import { toast } from "./toast";
+
+const lastCall = (fn: ReturnType<typeof vi.fn>) => fn.mock.calls.at(-1) as [unknown, Record<string, unknown>];
+
+describe("toast", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe("plain kinds", () => {
+ it.each([
+ ["success", sonner.success, 4000],
+ ["info", sonner.info, 4000],
+ ["warning", sonner.warning, 6000],
+ ["error", sonner.error, 6000],
+ ] as const)("%s forwards the message with its default duration", (kind, fn, duration) => {
+ toast[kind]("hello");
+ expect(fn).toHaveBeenCalledWith("hello", { description: undefined, duration });
+ });
+
+ it("lets callers override duration and add a description", () => {
+ toast.success("saved", { description: "Model x", durationMs: 1500 });
+ expect(sonner.success).toHaveBeenCalledWith("saved", { description: "Model x", duration: 1500 });
+ });
+
+ it("dismiss clears every toast", () => {
+ toast.dismiss();
+ expect(sonner.dismiss).toHaveBeenCalledWith();
+ });
+ });
+
+ describe("fromError title from the proxy error type", () => {
+ it("reads the type out of an ApiError body envelope", () => {
+ toast.fromError(
+ new ApiError("Budget has been exceeded", 400, {
+ error: { message: "Budget has been exceeded", type: "budget_exceeded", code: "400" },
+ }),
+ );
+ expect(sonner.warning).toHaveBeenCalledWith("Budget Exceeded", {
+ description: "Budget has been exceeded",
+ duration: 6000,
+ });
+ expect(sonner.error).not.toHaveBeenCalled();
+ });
+
+ it("maps every *_access_denied type to Access Denied", () => {
+ toast.fromError({ message: "no", type: "team_model_access_denied", code: "401" });
+ expect(lastCall(sonner.error)[0]).toBe("Access Denied");
+ });
+
+ it("prefers a deliberate type over the HTTP status", () => {
+ toast.fromError(new ApiError("expired", 400, { error: { message: "expired", type: "expired_key" } }));
+ expect(lastCall(sonner.error)[0]).toBe("Authentication Error");
+ });
+
+ it.each(["auth_error", "internal_server_error"])(
+ "ignores the proxy's catch-all type %s and trusts the status",
+ (type) => {
+ toast.fromError(
+ new ApiError("Model with id=abc not found in db", 400, { error: { message: "x", type, code: "400" } }),
+ );
+ expect(lastCall(sonner.error)[0]).toBe("Request Error");
+ },
+ );
+
+ it("reads type and code from a bare proxy payload object", () => {
+ toast.fromError({ message: "Key with alias 'k' already exists.", type: "bad_request_error", code: "400" });
+ expect(sonner.error).toHaveBeenCalledWith("Request Error", {
+ description: "Key with alias 'k' already exists.",
+ duration: 6000,
+ });
+ });
+
+ it("parses a JSON envelope carried inside an Error message", () => {
+ toast.fromError(
+ new Error(JSON.stringify({ error: { message: "Team not found", type: "not_found_error", code: "404" } })),
+ );
+ expect(sonner.error).toHaveBeenCalledWith("Not Found", { description: "Team not found", duration: 6000 });
+ });
+
+ it("reads type and code from a JSON envelope embedded after a caller's prefix, keeping the prefix", () => {
+ const envelope = JSON.stringify({
+ error: { message: "Key with alias 'k' already exists.", type: "bad_request_error", code: "400" },
+ });
+ toast.fromError(`Error creating the key: Error: ${envelope}`);
+ expect(sonner.error).toHaveBeenCalledWith("Request Error", {
+ description: "Error creating the key: Error: Key with alias 'k' already exists.",
+ duration: 6000,
+ });
+ });
+
+ it("leaves a string alone when its braces are not a JSON envelope", () => {
+ toast.fromError("Template {name} is invalid");
+ expect(sonner.error).toHaveBeenCalledWith("Error", {
+ description: "Template {name} is invalid",
+ duration: 6000,
+ });
+ });
+ });
+
+ describe("fromError title from the HTTP status", () => {
+ it.each([
+ [400, "Request Error", sonner.error],
+ [401, "Authentication Error", sonner.error],
+ [403, "Access Denied", sonner.error],
+ [404, "Not Found", sonner.error],
+ [409, "Already Exists", sonner.error],
+ [422, "Validation Error", sonner.error],
+ [429, "Rate Limit Exceeded", sonner.warning],
+ [418, "Request Error", sonner.error],
+ [500, "Server Error", sonner.error],
+ [503, "Service Unavailable", sonner.error],
+ [502, "Server Error", sonner.error],
+ ])("status %i becomes %s", (status, title, fn) => {
+ toast.fromError(new ApiError("boom", status, "boom"));
+ expect(fn).toHaveBeenCalledWith(title, { description: "boom", duration: 6000 });
+ });
+
+ it("reads an axios-style response status and nested data message", () => {
+ toast.fromError({ response: { status: 403, data: { error: { message: "nope" } } } });
+ expect(sonner.error).toHaveBeenCalledWith("Access Denied", { description: "nope", duration: 6000 });
+ });
+
+ it("reads a numeric status_code field", () => {
+ toast.fromError({ status_code: 429, message: "slow down" });
+ expect(sonner.warning).toHaveBeenCalledWith("Rate Limit Exceeded", { description: "slow down", duration: 6000 });
+ });
+
+ it("ignores non-HTTP code strings", () => {
+ toast.fromError({ code: "ECONNREFUSED", message: "connection refused" });
+ expect(sonner.error).toHaveBeenCalledWith("Error", { description: "connection refused", duration: 6000 });
+ });
+ });
+
+ describe("fromError message extraction", () => {
+ it("shows a raw string as an error with the generic title", () => {
+ toast.fromError("Please select at least one model");
+ expect(sonner.error).toHaveBeenCalledWith("Error", {
+ description: "Please select at least one model",
+ duration: 6000,
+ });
+ });
+
+ it("unwraps the proxy's python-dict string form", () => {
+ toast.fromError(new Error("{'error': 'Model not found'}"));
+ expect(lastCall(sonner.error)[1].description).toBe("Model not found");
+ });
+
+ it("unwraps a JSON string envelope passed directly", () => {
+ toast.fromError('{"error": {"message": "invalid json payload"}}');
+ expect(lastCall(sonner.error)[1].description).toBe("invalid json payload");
+ });
+
+ it("joins FastAPI detail arrays", () => {
+ toast.fromError({ detail: [{ msg: "field a required" }, { msg: "field b required" }] });
+ expect(lastCall(sonner.error)[1].description).toBe("field a required; field b required");
+ });
+
+ it("lets a caller override the duration", () => {
+ toast.fromError(new ApiError("x", 500, "x"), { durationMs: 10000 });
+ expect(lastCall(sonner.error)[1].duration).toBe(10000);
+ });
+ });
+});
diff --git a/ui/litellm-dashboard/src/lib/toast.ts b/ui/litellm-dashboard/src/lib/toast.ts
new file mode 100644
index 00000000000..a057d144e6f
--- /dev/null
+++ b/ui/litellm-dashboard/src/lib/toast.ts
@@ -0,0 +1,148 @@
+import type { ReactNode } from "react";
+import { toast as sonner } from "sonner";
+import { ApiError, deriveErrorMessage, unwrapProxyErrorMessage } from "@/lib/http/client";
+
+export type ToastKind = "success" | "info" | "warning" | "error";
+
+export type ToastOptions = {
+ readonly description?: ReactNode;
+ readonly durationMs?: number;
+};
+
+type ErrorFacts = {
+ readonly status: number | undefined;
+ readonly proxyType: string | undefined;
+ readonly text: string;
+};
+
+const DEFAULT_DURATION_MS: Readonly<Record<ToastKind, number>> = {
+ success: 4000,
+ info: 4000,
+ warning: 6000,
+ error: 6000,
+};
+
+const PROXY_TYPE_TITLES: Readonly<Record<string, string>> = {
+ budget_exceeded: "Budget Exceeded",
+ no_db_connection: "Service Unavailable",
+ expired_key: "Authentication Error",
+ token_not_found_in_db: "Authentication Error",
+ team_member_permission_error: "Access Denied",
+ not_found_error: "Not Found",
+ validation_error: "Validation Error",
+ bad_request_error: "Request Error",
+ team_member_already_in_team: "Already Exists",
+};
+
+const STATUS_TITLES: Readonly<Record<number, string>> = {
+ 400: "Request Error",
+ 401: "Authentication Error",
+ 403: "Access Denied",
+ 404: "Not Found",
+ 409: "Already Exists",
+ 422: "Validation Error",
+ 429: "Rate Limit Exceeded",
+ 503: "Service Unavailable",
+};
+
+const WARNING_TITLES: ReadonlySet<string> = new Set(["Budget Exceeded", "Rate Limit Exceeded"]);
+
+const asRecord = (value: unknown): Record<string, unknown> | undefined =>
+ value !== null && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
+
+const parseJson = (raw: string): unknown => {
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return undefined;
+ }
+};
+
+const toStatus = (value: unknown): number | undefined => {
+ if (typeof value === "number") return value;
+ if (typeof value === "string" && /^\d{3}$/.test(value)) return Number(value);
+ return undefined;
+};
+
+const proxyEnvelope = (payload: unknown): Record<string, unknown> | undefined => {
+ const record = asRecord(payload);
+ return asRecord(record?.error) ?? record;
+};
+
+const proxyTypeOf = (payload: unknown): string | undefined => {
+ const type = proxyEnvelope(payload)?.type;
+ return typeof type === "string" ? type : undefined;
+};
+
+const EMBEDDED_JSON = /\{[\s\S]*\}/;
+
+const describeText = (text: string): ErrorFacts => {
+ const embedded = text.match(EMBEDDED_JSON)?.[0];
+ const parsed = embedded === undefined ? undefined : parseJson(embedded);
+ if (embedded === undefined || asRecord(parsed) === undefined) {
+ return { status: undefined, proxyType: undefined, text: unwrapProxyErrorMessage(text) };
+ }
+ return {
+ status: toStatus(proxyEnvelope(parsed)?.code),
+ proxyType: proxyTypeOf(parsed),
+ text: text.replace(embedded, unwrapProxyErrorMessage(deriveErrorMessage(parsed))).trim(),
+ };
+};
+
+const describeError = (input: unknown): ErrorFacts => {
+ if (input instanceof ApiError) {
+ return { status: input.status, proxyType: proxyTypeOf(input.body), text: unwrapProxyErrorMessage(input.message) };
+ }
+ if (input instanceof Error || typeof input === "string") {
+ return describeText(input instanceof Error ? input.message : input);
+ }
+ const record = asRecord(input) ?? {};
+ const response = asRecord(record.response);
+ const payload = asRecord(response?.data) ?? record;
+ return {
+ status:
+ toStatus(response?.status) ??
+ toStatus(record.status_code) ??
+ toStatus(record.code) ??
+ toStatus(proxyEnvelope(payload)?.code),
+ proxyType: proxyTypeOf(payload),
+ text: unwrapProxyErrorMessage(deriveErrorMessage(payload)),
+ };
+};
+
+const titleForStatus = (status: number): string => {
+ const known = STATUS_TITLES[status];
+ if (known !== undefined) return known;
+ if (status >= 500) return "Server Error";
+ if (status >= 400) return "Request Error";
+ return "Error";
+};
+
+const titleFor = ({ status, proxyType }: ErrorFacts): string => {
+ if (proxyType?.endsWith("_access_denied")) return "Access Denied";
+ const byType = proxyType === undefined ? undefined : PROXY_TYPE_TITLES[proxyType];
+ if (byType !== undefined) return byType;
+ return status === undefined ? "Error" : titleForStatus(status);
+};
+
+const show = (kind: ToastKind, message: ReactNode, options?: ToastOptions): void => {
+ sonner[kind](message, {
+ description: options?.description,
+ duration: options?.durationMs ?? DEFAULT_DURATION_MS[kind],
+ });
+};
+
+export const toast = {
+ success: (message: ReactNode, options?: ToastOptions): void => show("success", message, options),
+ info: (message: ReactNode, options?: ToastOptions): void => show("info", message, options),
+ warning: (message: ReactNode, options?: ToastOptions): void => show("warning", message, options),
+ error: (message: ReactNode, options?: ToastOptions): void => show("error", message, options),
+ fromError: (input: unknown, options?: ToastOptions): void => {
+ const facts = describeError(input);
+ const title = titleFor(facts);
+ show(WARNING_TITLES.has(title) ? "warning" : "error", title, { description: facts.text, ...options });
+ },
+ dismiss: (): void => {
+ sonner.dismiss();
+ },
+} as const;