From 99e481610239aa63ce06b17a6eee226db9c17e7b Mon Sep 17 00:00:00 2001 From: ishaan-j-berri Date: Tue, 3 Nov 2026 23:36:10 -0800 Subject: [PATCH] feat(ui): show recent model deprecations in notification bell --- .../DeprecationAlertItem.integration.test.tsx | 109 ++++++++++++++ .../DeprecationAlertItem.tsx | 133 ++++++++++++++++++ .../NotificationsBell.test.tsx | 90 ++++++++++++ .../NotificationsBell/NotificationsBell.tsx | 97 ++++++++++++- .../deprecationAlerts.test.ts | 78 ++++++++++ .../NotificationsBell/deprecationAlerts.ts | 53 +++++++ .../NotificationsBell/useDeprecationAlerts.ts | 40 ++++++ 7 files changed, 593 insertions(+), 7 deletions(-) create mode 100644 ui/litellm-dashboard/src/components/Navbar/NotificationsBell/DeprecationAlertItem.integration.test.tsx create mode 100644 ui/litellm-dashboard/src/components/Navbar/NotificationsBell/DeprecationAlertItem.tsx create mode 100644 ui/litellm-dashboard/src/components/Navbar/NotificationsBell/deprecationAlerts.test.ts create mode 100644 ui/litellm-dashboard/src/components/Navbar/NotificationsBell/deprecationAlerts.ts create mode 100644 ui/litellm-dashboard/src/components/Navbar/NotificationsBell/useDeprecationAlerts.ts diff --git a/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/DeprecationAlertItem.integration.test.tsx b/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/DeprecationAlertItem.integration.test.tsx new file mode 100644 index 00000000000..1de017d7449 --- /dev/null +++ b/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/DeprecationAlertItem.integration.test.tsx @@ -0,0 +1,109 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import userEvent from "@testing-library/user-event"; +import { renderWithProviders, screen, testQueryClient } from "../../../../tests/test-utils"; +import { backgroundFetchClient } from "@/lib/http/api"; +import DeprecationAlertItem from "./DeprecationAlertItem"; +import { useDeprecationAlerts } from "./useDeprecationAlerts"; +import { useCurrentUser } from "@/app/(dashboard)/hooks/currentUser/useCurrentUser"; + +vi.mock("@/lib/http/api", () => ({ backgroundFetchClient: { GET: vi.fn() } })); +vi.mock("@/app/(dashboard)/hooks/currentUser/useCurrentUser", () => ({ useCurrentUser: vi.fn() })); + +const alert = { + id: "sonnet", + usageModel: "anthropic/claude-sonnet-4-5", + requests: 123, + lastUsedDate: "2026-11-04", + model: { + model_name: "support", + deprecation_date: "2026-11-30", + days_until_deprecation: 26, + status: "imminent" as const, + }, +}; +const range = { start_date: "2026-10-06", end_date: "2026-11-04" }; +function AlertsHost() { + const { data, isError, fetchStatus } = useDeprecationAlerts("test-session"); + if (isError) return
Unavailable
; + if (fetchStatus !== "idle") return
Loading
; + return
{data?.length ?? 0} alerts
; +} + +describe("deprecation alert API wiring", () => { + beforeEach(() => { + vi.clearAllMocks(); + testQueryClient.clear(); + }); + it("should render the alert before fetching key details", () => { + renderWithProviders( + , + ); + expect(screen.getByRole("article", { name: /retires in 26 days/ })).toHaveTextContent("123 requests"); + expect(backgroundFetchClient.GET).not.toHaveBeenCalled(); + }); + it("should fetch affected keys for the underlying model and link to the matching key and team", async () => { + vi.mocked(backgroundFetchClient.GET).mockResolvedValue({ + data: { + api_keys: [ + { + api_key: "reporting-key-1", + metadata: { key_alias: "support-production", team_id: "support-team" }, + metrics: { api_requests: 123 }, + }, + ], + }, + } as never); + const user = userEvent.setup(); + renderWithProviders( + , + ); + await user.click(screen.getByRole("button", { name: "Review affected keys" })); + expect(await screen.findByRole("link", { name: "support-production" })).toHaveAttribute( + "href", + "/ui/api-keys?key=reporting-key-1", + ); + expect(screen.getByRole("link", { name: "Team: support-team" })).toHaveAttribute( + "href", + "/ui/teams?team=support-team", + ); + expect(backgroundFetchClient.GET).toHaveBeenCalledWith( + "/user/daily/activity/aggregated/model_top_keys", + expect.objectContaining({ + params: { query: { ...range, model_group: alert.usageModel, by_model_group: false, limit: 10, timezone: 0 } }, + }), + ); + }); + it("should offer retry when affected keys cannot load", async () => { + vi.mocked(backgroundFetchClient.GET).mockRejectedValue(new Error("Unavailable")); + const user = userEvent.setup(); + renderWithProviders( + , + ); + await user.click(screen.getByRole("button", { name: "Review affected keys" })); + expect(await screen.findByText("Could not load affected keys.")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Retry" })).toBeInTheDocument(); + }); + it("should avoid querying gateway-wide usage for non-admins", () => { + vi.mocked(useCurrentUser).mockReturnValue({ + data: { user_id: "internal", user_role: "internal_user" }, + } as ReturnType); + renderWithProviders(); + expect(screen.getByText("0 alerts")).toBeInTheDocument(); + expect(backgroundFetchClient.GET).not.toHaveBeenCalled(); + }); + it("should skip the usage query when no configured models need attention", async () => { + vi.mocked(useCurrentUser).mockReturnValue({ data: { user_id: "admin", user_role: "proxy_admin" } } as ReturnType< + typeof useCurrentUser + >); + vi.mocked(backgroundFetchClient.GET).mockResolvedValue({ + data: { deprecated: [], imminent: [], upcoming: [] }, + } as never); + renderWithProviders(); + expect(await screen.findByText("0 alerts")).toBeInTheDocument(); + expect(backgroundFetchClient.GET).toHaveBeenCalledTimes(1); + expect(backgroundFetchClient.GET).toHaveBeenCalledWith( + "/model/deprecations", + expect.objectContaining({ params: { query: { warn_within_days: 30 } } }), + ); + }); +}); diff --git a/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/DeprecationAlertItem.tsx b/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/DeprecationAlertItem.tsx new file mode 100644 index 00000000000..720c4613cb1 --- /dev/null +++ b/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/DeprecationAlertItem.tsx @@ -0,0 +1,133 @@ +"use client"; + +import { useState } from "react"; +import { useQuery } from "@tanstack/react-query"; +import { AlertTriangle, ArrowUpRight, Check, KeyRound } from "lucide-react"; +import { Button, buttonVariants } from "@/components/ui/button"; +import { backgroundFetchClient } from "@/lib/http/api"; +import { keyDetailHref, modelGroupHref, teamDetailHref } from "@/utils/entityLinks"; +import { cn } from "@/lib/cva.config"; +import type { DeprecationAlert } from "./deprecationAlerts"; +import type { deprecationUsageRange } from "./deprecationAlerts"; + +export default function DeprecationAlertItem({ + alert, + dismissed, + onDismiss, + scope, + range, +}: { + alert: DeprecationAlert; + dismissed: boolean; + onDismiss: () => void; + scope: string; + range: ReturnType; +}) { + const [showKeys, setShowKeys] = useState(false); + const keyOptions = { + queryKey: ["deprecationAlertKeys", scope, alert.usageModel, range], + enabled: showKeys, + queryFn: async ({ signal }: { signal: AbortSignal }) => { + const query = { ...range, model_group: alert.usageModel, by_model_group: false, limit: 10, timezone: 0 }; + const { data } = await backgroundFetchClient.GET("/user/daily/activity/aggregated/model_top_keys", { + params: { query }, + signal, + }); + if (!data) throw new Error("Affected keys are unavailable"); + return data.api_keys; + }, + staleTime: 5 * 60 * 1000, + retry: false, + }; + const keys = useQuery(keyOptions); + const retired = alert.model.status === "deprecated"; + const title = retired + ? `${alert.usageModel} is deprecated` + : `${alert.usageModel} retires in ${alert.model.days_until_deprecation} days`; + const modelHref = modelGroupHref(alert.model.model_name); + function renderAffectedKeys() { + if (keys.isPending) return

Loading affected keys…

; + if (keys.isError) + return ( +
+

Could not load affected keys.

+ +
+ ); + if (keys.data?.length) + return ( + <> +

Top affected keys by spend · Last 30 days

+ + + ); + return

No attributable keys found in this period.

; + } + return ( +
+
+ + + +
+

{title}

+

+ {alert.requests.toLocaleString()} requests in the last 30 days · Last used {alert.lastUsedDate} UTC +

+

+ {retired ? "Deprecated" : "Deprecates"} {alert.model.deprecation_date} + {alert.model.successor_model ? ` · Suggested replacement: ${alert.model.successor_model}` : ""} +

+
+
+
+ + {modelHref && ( + + Resolve in model settings + + )} + {dismissed ? ( + + + Dismissed + + ) : ( + + )} +
+ {showKeys &&
{renderAffectedKeys()}
} +
+ ); +} diff --git a/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/NotificationsBell.test.tsx b/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/NotificationsBell.test.tsx index 93d9b6018ac..b472b972a34 100644 --- a/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/NotificationsBell.test.tsx +++ b/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/NotificationsBell.test.tsx @@ -5,6 +5,14 @@ import React from "react"; import userEvent from "@testing-library/user-event"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +vi.mock("./useDeprecationAlerts", () => ({ + useDeprecationAlerts: () => ({ + data: [], + scope: "test", + range: { start_date: "2026-10-06", end_date: "2026-11-04" }, + }), +})); + vi.mock("@/app/(dashboard)/hooks/healthReadiness/useHealthReadinessDetails", () => ({ useHealthReadinessDetails: vi.fn(), })); @@ -173,3 +181,85 @@ describe("NotificationsBell", () => { expect(announcement("LiteLLM v1.103.0 is available")).toHaveTextContent("Your current version is v1.102.0"); }); }); + +const DEPRECATION = { + id: "sonnet:2026-11-30:imminent", + usageModel: "anthropic/claude-sonnet-4-5", + requests: 18432, + lastUsedDate: "2026-11-04", + model: { + model_name: "support", + litellm_model: "anthropic/claude-sonnet-4-5", + deprecation_date: "2026-11-30", + days_until_deprecation: 26, + status: "imminent" as const, + }, +}; + +describe("model deprecation notifications", () => { + beforeEach(() => localStorage.clear()); + afterEach(() => localStorage.clear()); + it("should show an actionable deprecation alert with recent usage", async () => { + const user = userEvent.setup(); + renderWithProviders( + , + ); + await user.click(screen.getByRole("button", { name: "Notifications, 1 model deprecation alert needs attention" })); + expect(screen.getByRole("article", { name: "anthropic/claude-sonnet-4-5 retires in 26 days" })).toHaveTextContent( + "18,432 requests in the last 30 days", + ); + expect(screen.getByText(/Last used 2026-11-04 UTC/)).toBeInTheDocument(); + expect(screen.getByRole("link", { name: /Resolve in model settings/ })).toHaveAttribute( + "href", + "/ui/models-and-endpoints?model_group=support", + ); + expect(screen.getByRole("button", { name: "Review affected keys" })).toBeInTheDocument(); + }); + it("should dismiss a warning without claiming the model usage is resolved", async () => { + const user = userEvent.setup(); + renderWithProviders( + , + ); + await user.click(screen.getByRole("button", { name: /1 model deprecation alert/ })); + await user.click(screen.getByRole("button", { name: "Dismiss", exact: true })); + expect(bell(1)).toBeInTheDocument(); + expect(screen.getByText("Dismissed")).toBeInTheDocument(); + expect(screen.getByRole("link", { name: /Resolve in model settings/ })).toBeInTheDocument(); + }); + it("should resurface a warning when a dismissed model becomes deprecated", async () => { + const user = userEvent.setup(); + const props = { currentVersion: null, latestRelease: null, scope: "gateway-admin" }; + const view = renderWithProviders(); + await user.click(screen.getByRole("button", { name: /1 model deprecation alert/ })); + await user.click(screen.getByRole("button", { name: "Dismiss", exact: true })); + view.rerender( + , + ); + expect(screen.getByRole("button", { name: /1 model deprecation alert/ })).toBeInTheDocument(); + expect(screen.getByRole("article", { name: "anthropic/claude-sonnet-4-5 is deprecated" })).toBeInTheDocument(); + }); + it("should keep dismissals separate for different gateway users", async () => { + const user = userEvent.setup(); + const props = { currentVersion: null, latestRelease: null, deprecationAlerts: [DEPRECATION] }; + const view = renderWithProviders(); + await user.click(screen.getByRole("button", { name: /1 model deprecation alert/ })); + await user.click(screen.getByRole("button", { name: "Dismiss", exact: true })); + view.rerender(); + expect(screen.getByRole("button", { name: /1 model deprecation alert/ })).toBeInTheDocument(); + }); +}); diff --git a/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/NotificationsBell.tsx b/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/NotificationsBell.tsx index 4cb9f851153..3cdf3a0f7dd 100644 --- a/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/NotificationsBell.tsx +++ b/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/NotificationsBell.tsx @@ -16,7 +16,10 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover import { Separator } from "@/components/ui/separator"; import { cn } from "@/lib/cva.config"; import { isNewerVersion } from "@/utils/versionUtils"; -import { Bell } from "lucide-react"; +import { Bell, AlertTriangle } from "lucide-react"; +import DeprecationAlertItem from "./DeprecationAlertItem"; +import { deprecationUsageRange, type DeprecationAlert } from "./deprecationAlerts"; +import { useDeprecationAlerts } from "./useDeprecationAlerts"; import React, { Fragment } from "react"; export const AUTO_ROUTER_DOCS_URL = "https://docs.litellm.ai/docs/proxy/auto_routing"; @@ -88,28 +91,99 @@ const AnnouncementItem: React.FC<{ announcement: Announcement }> = ({ announceme ); }; +const deprecationReadKey = (scope: string, id: string) => JSON.stringify(["litellm:deprecationAlert", scope, id]); + +function DeprecationNotification({ + alert, + scope, + range, +}: { + alert: DeprecationAlert; + scope: string; + range: ReturnType; +}) { + const readKey = deprecationReadKey(scope, alert.id); + const dismissed = useAnnouncementRead(readKey); + return ( + markAnnouncementRead(readKey)} + /> + ); +} + interface NotificationsBellViewProps { currentVersion: string | null | undefined; latestRelease: LatestReleaseInfo | null | undefined; + deprecationAlerts?: readonly DeprecationAlert[]; + scope?: string; + range?: ReturnType; } -export const NotificationsBellView: React.FC = ({ currentVersion, latestRelease }) => { +export const NotificationsBellView: React.FC = ({ + currentVersion, + latestRelease, + deprecationAlerts = [], + scope = "", + range = deprecationUsageRange(new Date()), +}) => { const upgrade = upgradeAnnouncement(currentVersion, latestRelease); const announcements = upgrade ? [upgrade, AUTO_ROUTER_ANNOUNCEMENT] : [AUTO_ROUTER_ANNOUNCEMENT]; const unreadCount = useUnreadAnnouncementCount(announcements.map((announcement) => announcement.readKey)); + const openDeprecations = useUnreadAnnouncementCount( + deprecationAlerts.map((alert) => deprecationReadKey(scope, alert.id)), + ); + let label = unreadCount > 0 ? `Notifications, ${unreadCount} unread` : "Notifications"; + if (openDeprecations > 0) { + label = `Notifications, ${openDeprecations} model deprecation ${openDeprecations === 1 ? "alert needs" : "alerts need"} attention`; + } + return ( 0 ? `Notifications, ${unreadCount} unread` : "Notifications"} + aria-label={label} > - - {unreadCount > 0 ? : null} + 0 && "text-amber-700")} aria-hidden /> + {openDeprecations > 0 ? ( + + + + ) : null} + {openDeprecations === 0 && unreadCount > 0 ? ( + + ) : null} - + + {deprecationAlerts.length > 0 && ( + <> +
+

Model deprecation alerts

+

+ Recently used models that need migration. Dismissing hides the warning in this browser; it does not + resolve usage. +

+
+ {deprecationAlerts.map((alert) => ( + + + + + ))} + +

Announcements

+ + )} {announcements.map((announcement, index) => ( {index > 0 ? : null} @@ -124,5 +198,14 @@ export const NotificationsBellView: React.FC = ({ cu export const NotificationsBell: React.FC<{ accessToken: string | null }> = ({ accessToken }) => { const { data: healthData } = useHealthReadinessDetails(accessToken); const { data: latestRelease } = useLatestReleaseInfo(accessToken); - return ; + const { data: deprecationAlerts, scope, range } = useDeprecationAlerts(accessToken); + return ( + + ); }; diff --git a/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/deprecationAlerts.test.ts b/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/deprecationAlerts.test.ts new file mode 100644 index 00000000000..f38eee7fccf --- /dev/null +++ b/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/deprecationAlerts.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, it } from "vitest"; +import type { components } from "@/lib/http/schema"; +import { deprecationUsageRange, usedDeprecationAlerts } from "./deprecationAlerts"; + +type Model = components["schemas"]["ModelDeprecationInfo"]; +type Day = components["schemas"]["DailySpendData"]; +const model: Model = { + model_name: "support", + litellm_model: "anthropic/claude-sonnet-4-5", + deprecation_date: "2026-11-30", + days_until_deprecation: 26, + status: "imminent", +}; +// Use the API's defaults for the unrelated aggregate metrics. +const metrics: components["schemas"]["SpendMetrics"] = { + spend: 0, + api_requests: 0, + successful_requests: 0, + failed_requests: 0, + prompt_tokens: 0, + completion_tokens: 0, + total_tokens: 0, + cache_read_input_tokens: 0, + cache_creation_input_tokens: 0, +}; +function day(date: string, count: number, name = model.litellm_model!): Day { + return { date, metrics, breakdown: { models: { [name]: { metrics: { ...metrics, api_requests: count } } } } }; +} + +describe("usedDeprecationAlerts", () => { + it("should aggregate requests and report the latest day of actual model usage", () => { + const result = usedDeprecationAlerts([model], [day("2026-11-04", 12), day("2026-10-20", 8)]); + expect(result).toHaveLength(1); + expect(result[0]).toMatchObject({ usageModel: model.litellm_model, requests: 20, lastUsedDate: "2026-11-04" }); + }); + it("should omit configured models without observed requests", () => { + expect(usedDeprecationAlerts([model], [])).toEqual([]); + expect(usedDeprecationAlerts([model], [day("2026-11-04", 0)])).toEqual([]); + }); + it("should avoid attributing healthy deployments in the same group to a deprecated model", () => { + const activity = day("2026-11-04", 100, "anthropic/claude-sonnet-4-6"); + activity.breakdown!.model_groups = { support: { metrics: { ...metrics, api_requests: 100 } } }; + expect(usedDeprecationAlerts([model], [activity])).toEqual([]); + }); + it("should match provider-qualified usage when the cost map names an unqualified model", () => { + const entry = { ...model, litellm_model: "claude-sonnet-4-5", litellm_provider: "anthropic" }; + const result = usedDeprecationAlerts([entry], [day("2026-11-04", 12)]); + expect(result[0]).toMatchObject({ usageModel: "anthropic/claude-sonnet-4-5", requests: 12 }); + }); + it("should keep usage for different providers separate", () => { + const entry = { ...model, litellm_provider: "anthropic" }; + expect(usedDeprecationAlerts([entry], [day("2026-11-04", 12, "bedrock/claude-sonnet-4-5")])).toEqual([]); + }); + it("should deduplicate deployments and put the earliest retirement first", () => { + const retired = { ...model, deprecation_date: "2026-10-23", status: "deprecated" as const }; + const result = usedDeprecationAlerts([model, retired, model], [day("2026-11-04", 10)]); + expect(result.map((alert) => alert.model.deprecation_date)).toEqual(["2026-10-23", "2026-11-30"]); + }); + it("should give an escalated alert a new dismissal identity", () => { + const activity = [day("2026-11-04", 10)]; + const imminent = usedDeprecationAlerts([model], activity)[0]; + const retired = usedDeprecationAlerts([{ ...model, status: "deprecated" }], activity)[0]; + expect(retired.id).not.toBe(imminent.id); + }); + it("should use the public model name when underlying model metadata is unavailable", () => { + const result = usedDeprecationAlerts([{ ...model, litellm_model: null }], [day("2026-11-04", 10, "support")]); + expect(result[0].requests).toBe(10); + }); +}); + +describe("deprecationUsageRange", () => { + it("should include exactly 30 UTC calendar dates across month boundaries", () => { + expect(deprecationUsageRange(new Date("2026-11-04T23:00:00Z"))).toEqual({ + start_date: "2026-10-06", + end_date: "2026-11-04", + }); + }); +}); diff --git a/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/deprecationAlerts.ts b/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/deprecationAlerts.ts new file mode 100644 index 00000000000..77510f6171c --- /dev/null +++ b/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/deprecationAlerts.ts @@ -0,0 +1,53 @@ +import type { components } from "@/lib/http/schema"; + +type ModelDeprecation = components["schemas"]["ModelDeprecationInfo"]; +type DailySpendData = components["schemas"]["DailySpendData"]; + +export interface DeprecationAlert { + id: string; + model: ModelDeprecation; + usageModel: string; + requests: number; + lastUsedDate: string; +} + +export function deprecationUsageRange(today: Date) { + const end = new Date(today); + const start = new Date(today); + start.setUTCDate(start.getUTCDate() - 29); + return { start_date: start.toISOString().slice(0, 10), end_date: end.toISOString().slice(0, 10) }; +} + +/** Match actual model usage, rather than model-group totals that may include healthy deployments. */ +export function usedDeprecationAlerts( + models: readonly ModelDeprecation[], + days: readonly DailySpendData[], +): DeprecationAlert[] { + const alerts: DeprecationAlert[] = []; + const seen = new Set(); + for (const model of models) { + const baseModel = model.litellm_model ?? model.model_name; + const candidates = new Set([baseModel]); + if (model.litellm_provider && !baseModel.startsWith(`${model.litellm_provider}/`)) { + candidates.add(`${model.litellm_provider}/${baseModel}`); + } + for (const usageModel of candidates) { + const id = JSON.stringify([usageModel, model.deprecation_date, model.status]); + if (seen.has(id)) continue; + seen.add(id); + let requests = 0; + let lastUsedDate = ""; + for (const day of days) { + const metrics = day.breakdown?.models?.[usageModel]?.metrics; + if (!metrics || metrics.api_requests <= 0) continue; + requests += metrics.api_requests; + if (day.date > lastUsedDate) lastUsedDate = day.date; + } + if (requests > 0) { + const alert = { id, model, usageModel, requests, lastUsedDate }; + alerts.push(alert); + } + } + } + return alerts.sort((a, b) => a.model.deprecation_date.localeCompare(b.model.deprecation_date)); +} diff --git a/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/useDeprecationAlerts.ts b/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/useDeprecationAlerts.ts new file mode 100644 index 00000000000..f3bd353ced3 --- /dev/null +++ b/ui/litellm-dashboard/src/components/Navbar/NotificationsBell/useDeprecationAlerts.ts @@ -0,0 +1,40 @@ +import { useQuery } from "@tanstack/react-query"; +import { useCurrentUser } from "@/app/(dashboard)/hooks/currentUser/useCurrentUser"; +import { backgroundFetchClient } from "@/lib/http/api"; +import { getProxyBaseUrl } from "@/components/networking"; +import { hasCapability } from "@/utils/capabilities"; +import { deprecationUsageRange, usedDeprecationAlerts } from "./deprecationAlerts"; + +const POLL_INTERVAL = 5 * 60 * 1000; + +export function useDeprecationAlerts(accessToken: string | null) { + const { data: currentUser } = useCurrentUser(accessToken); + const userId = currentUser?.user_id; + const enabled = Boolean(accessToken && userId && hasCapability(currentUser?.user_role, "viewGlobalSpend")); + const scope = JSON.stringify([getProxyBaseUrl(), userId]); + const range = deprecationUsageRange(new Date()); + const options = { + queryKey: ["deprecationAlerts", scope, range], + enabled, + queryFn: async ({ signal }: { signal: AbortSignal }) => { + const { data: schedule } = await backgroundFetchClient.GET("/model/deprecations", { + params: { query: { warn_within_days: 30 } }, + signal, + }); + if (!schedule) throw new Error("Model deprecation information is unavailable"); + const models = [...(schedule.deprecated ?? []), ...(schedule.imminent ?? [])]; + if (models.length === 0) return []; + const { data: activity } = await backgroundFetchClient.GET("/user/daily/activity/aggregated", { + params: { query: { ...range, timezone: 0, api_key_limit: 1 } }, + signal, + }); + if (!activity) throw new Error("Model usage is unavailable"); + return usedDeprecationAlerts(models, activity.results ?? []); + }, + staleTime: POLL_INTERVAL, + refetchInterval: POLL_INTERVAL, + retry: false, + }; + const query = useQuery(options); + return { ...query, data: enabled ? query.data : undefined, scope, range }; +}