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]

Show remaining users on UI (#11568)

Krish Dholakiac569056ea85d
diff --git a/enterprise/litellm_enterprise/proxy/enterprise_routes.py b/enterprise/litellm_enterprise/proxy/enterprise_routes.py
index 1e4ed580618..f3227892bbd 100644
--- a/enterprise/litellm_enterprise/proxy/enterprise_routes.py
+++ b/enterprise/litellm_enterprise/proxy/enterprise_routes.py
@@ -6,6 +6,7 @@ from litellm_enterprise.enterprise_callbacks.send_emails.endpoints import (
from .audit_logging_endpoints import router as audit_logging_router
from .guardrails.endpoints import router as guardrails_router
+from .management_endpoints import management_endpoints_router
from .utils import _should_block_robots
from .vector_stores.endpoints import router as vector_stores_router
@@ -14,6 +15,7 @@ router.include_router(vector_stores_router)
router.include_router(guardrails_router)
router.include_router(email_events_router)
router.include_router(audit_logging_router)
+router.include_router(management_endpoints_router)
@router.get("/robots.txt")
diff --git a/enterprise/litellm_enterprise/proxy/management_endpoints/__init__.py b/enterprise/litellm_enterprise/proxy/management_endpoints/__init__.py
new file mode 100644
index 00000000000..7042dae53a6
--- /dev/null
+++ b/enterprise/litellm_enterprise/proxy/management_endpoints/__init__.py
@@ -0,0 +1,8 @@
+from fastapi import APIRouter
+
+from .internal_user_endpoints import router as internal_user_endpoints_router
+
+management_endpoints_router = APIRouter()
+management_endpoints_router.include_router(internal_user_endpoints_router)
+
+__all__ = ["management_endpoints_router"]
diff --git a/enterprise/litellm_enterprise/proxy/management_endpoints/internal_user_endpoints.py b/enterprise/litellm_enterprise/proxy/management_endpoints/internal_user_endpoints.py
new file mode 100644
index 00000000000..f28ccfd956f
--- /dev/null
+++ b/enterprise/litellm_enterprise/proxy/management_endpoints/internal_user_endpoints.py
@@ -0,0 +1,52 @@
+"""
+Enterprise internal user management endpoints
+"""
+from fastapi import APIRouter, Depends, HTTPException
+
+from litellm.proxy._types import UserAPIKeyAuth
+from litellm.proxy.management_endpoints.internal_user_endpoints import user_api_key_auth
+
+router = APIRouter()
+
+
+ "/user/available_users",
+ tags=["Internal User management"],
+ dependencies=[Depends(user_api_key_auth)],
+)
+async def available_enterprise_users(
+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
+):
+ """
+ For keys with `max_users` set, return the list of users that are allowed to use the key.
+ """
+ from litellm.proxy._types import CommonProxyErrors
+ from litellm.proxy.proxy_server import (
+ premium_user,
+ premium_user_data,
+ prisma_client,
+ )
+
+ if prisma_client is None:
+ raise HTTPException(
+ status_code=500,
+ detail={"error": CommonProxyErrors.db_not_connected_error.value},
+ )
+
+ if premium_user is None:
+ raise HTTPException(
+ status_code=500, detail={"error": CommonProxyErrors.not_premium_user.value}
+ )
+
+ # Count number of rows in LiteLLM_UserTable
+ user_count = await prisma_client.db.litellm_usertable.count()
+
+ return {
+ "total_users": premium_user_data.get("max_users")
+ if premium_user_data
+ else None,
+ "total_users_used": user_count,
+ "total_users_remaining": premium_user_data.get("max_users", 0) - user_count
+ if premium_user_data
+ else None,
+ }
diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.py
index 4a78ff6accc..079cef4631e 100644
--- a/litellm/litellm_core_utils/streaming_handler.py
+++ b/litellm/litellm_core_utils/streaming_handler.py
@@ -440,7 +440,14 @@ class CustomStreamWrapper:
else: # function/tool calling chunk - when content is None. in this case we just return the original chunk from openai
pass
if str_line.choices[0].finish_reason:
- is_finished = True
+ is_finished = (
+ True # check if str_line._hidden_params["is_finished"] is True
+ )
+ if (
+ hasattr(str_line, "_hidden_params")
+ and str_line._hidden_params.get("is_finished") is not None
+ ):
+ is_finished = str_line._hidden_params.get("is_finished")
finish_reason = str_line.choices[0].finish_reason
# checking for logprobs
@@ -1195,7 +1202,6 @@ class CustomStreamWrapper:
if response_obj is None:
return
completion_obj["content"] = response_obj["text"]
- print_verbose(f"completion obj content: {completion_obj['content']}")
if response_obj["is_finished"]:
if response_obj["finish_reason"] == "error":
raise Exception(
diff --git a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
index 53d4073e1e3..ad7bfddb02d 100644
--- a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
+++ b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
@@ -1888,6 +1888,8 @@ class ModelResponseIterator:
).web_search_requests = web_search_requests
setattr(model_response, "usage", usage) # type: ignore
+
+ model_response._hidden_params["is_finished"] = False
return model_response
except json.JSONDecodeError:
diff --git a/litellm/proxy/_new_secret_config.yaml b/litellm/proxy/_new_secret_config.yaml
index 2f605bc76c3..65b07b5f5f3 100644
--- a/litellm/proxy/_new_secret_config.yaml
+++ b/litellm/proxy/_new_secret_config.yaml
@@ -1,9 +1,4 @@
model_list:
- - model_name: "gemini-2.0-flash"
- litellm_params:
- model: vertex_ai/gemini-2.0-flash
- vertex_project: my-project-id
- vertex_location: us-central1
- model_name: "gpt-4o-mini-openai"
litellm_params:
model: gpt-4o-mini
@@ -42,9 +37,9 @@ model_list:
litellm_params:
model: text-embedding-ada-002
api_key: os.environ/OPENAI_API_KEY
- - model_name: gemini/gemini-2.0-flash
+ - model_name: gemini/*
litellm_params:
- model: gemini/gemini-2.0-flash
+ model: gemini/*
- model_name: llama-qwen
litellm_params:
model: ollama/qwen2:0.5b
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index 7b5c2dd8373..db272af34f5 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -1342,7 +1342,6 @@ class LiteLLM_BudgetTable(LiteLLMPydanticObjectBase):
class LiteLLM_BudgetTableFull(LiteLLM_BudgetTable):
"""Represents all params for a LiteLLM_BudgetTable record"""
- budget_id: str
created_at: datetime
@@ -2317,7 +2316,7 @@ class CommonProxyErrors(str, enum.Enum):
)
no_llm_router = "No models configured on proxy"
not_allowed_access = "Admin-only endpoint. Not allowed to access this."
- not_premium_user = "You must be a LiteLLM Enterprise user to use this feature. If you have a license please set `LITELLM_LICENSE` in your env. Get a 7 day trial key here: https://www.litellm.ai/#trial. \nPricing: https://www.litellm.ai/#pricing"
+ not_premium_user = "You must be a LiteLLM Enterprise user to use this feature. If you have a license please set `LITELLM_LICENSE` in your env. Get a 7 day trial key here: https://www.litellm.ai/enterprise#trial. \nPricing: https://www.litellm.ai/#pricing"
max_parallel_request_limit_reached = (
"Crossed TPM / RPM / Max Parallel Request Limit"
)
@@ -3080,3 +3079,10 @@ class LiteLLM_ManagedObjectTable(LiteLLMPydanticObjectBase):
model_object_id: str
file_purpose: Literal["batch", "fine-tune"]
file_object: Union[LiteLLMBatch, LiteLLMFineTuningJob]
+
+
+class EnterpriseLicenseData(TypedDict, total=False):
+ expiration_date: str
+ user_id: str
+ allowed_features: List[str]
+ max_users: int
diff --git a/litellm/proxy/auth/litellm_license.py b/litellm/proxy/auth/litellm_license.py
index 936f372181d..7998ea9b4b1 100644
--- a/litellm/proxy/auth/litellm_license.py
+++ b/litellm/proxy/auth/litellm_license.py
@@ -4,7 +4,7 @@ import base64
import json
import os
from datetime import datetime
-from typing import Optional
+from typing import TYPE_CHECKING, Optional
import httpx
@@ -12,6 +12,9 @@ from litellm._logging import verbose_proxy_logger
from litellm.constants import NON_LLM_CONNECTION_TIMEOUT
from litellm.llms.custom_httpx.http_handler import HTTPHandler
+if TYPE_CHECKING:
+ from litellm.proxy._types import EnterpriseLicenseData
+
class LicenseCheck:
"""
@@ -27,6 +30,7 @@ class LicenseCheck:
self.http_handler = HTTPHandler(timeout=NON_LLM_CONNECTION_TIMEOUT)
self.public_key = None
self.read_public_key()
+ self.airgapped_license_data: Optional["EnterpriseLicenseData"] = None
def read_public_key(self):
try:
@@ -125,11 +129,25 @@ class LicenseCheck:
except Exception:
return False
+ def is_over_limit(self, total_users: int) -> bool:
+ """
+ Check if the license is over the limit
+ """
+ if self.airgapped_license_data is None:
+ return False
+ if "max_users" not in self.airgapped_license_data or not isinstance(
+ self.airgapped_license_data["max_users"], int
+ ):
+ return False
+ return total_users > self.airgapped_license_data["max_users"]
+
def verify_license_without_api_request(self, public_key, license_key):
try:
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
+ from litellm.proxy._types import EnterpriseLicenseData
+
# Decode the license key
decoded = base64.b64decode(license_key)
message, signature = decoded.split(b".", 1)
@@ -148,6 +166,8 @@ class LicenseCheck:
# Decode and parse the data
license_data = json.loads(message.decode())
+ self.airgapped_license_data = EnterpriseLicenseData(**license_data)
+
# debug information provided in license data
verbose_proxy_logger.debug("License data: %s", license_data)
diff --git a/litellm/proxy/management_endpoints/customer_endpoints.py b/litellm/proxy/management_endpoints/customer_endpoints.py
index a0c090653df..dfc36bf6c4a 100644
--- a/litellm/proxy/management_endpoints/customer_endpoints.py
+++ b/litellm/proxy/management_endpoints/customer_endpoints.py
@@ -195,6 +195,7 @@ async def new_end_user(
- max_parallel_requests: Optional[int] - [Not Implemented Yet] Specify max parallel requests for a given customer.
- soft_budget: Optional[float] - [Not Implemented Yet] Get alerts when customer crosses given budget, doesn't block requests.
- spend: Optional[float] - Specify initial spend for a given customer.
+ - budget_reset_at: Optional[str] - Specify the date and time when the budget should be reset.
- Allow specifying allowed regions
diff --git a/litellm/proxy/management_endpoints/internal_user_endpoints.py b/litellm/proxy/management_endpoints/internal_user_endpoints.py
index a348c8eb840..0de01e98620 100644
--- a/litellm/proxy/management_endpoints/internal_user_endpoints.py
+++ b/litellm/proxy/management_endpoints/internal_user_endpoints.py
@@ -188,11 +188,24 @@ async def new_user(
```
"""
try:
- from litellm.proxy.proxy_server import prisma_client
+ from litellm.proxy.proxy_server import _license_check, prisma_client
+
+ if prisma_client is None:
+ raise HTTPException(
+ status_code=400, detail=CommonProxyErrors.db_not_connected_error.value
+ )
# Check for duplicate email
await _check_duplicate_user_email(data.user_email, prisma_client)
+ # Check if license is over limit
+ total_users = await prisma_client.db.litellm_usertable.count()
+ if total_users and _license_check.is_over_limit(total_users=total_users):
+ raise HTTPException(
+ status_code=403,
+ detail="License is over limit. Please contact [email protected] to upgrade your license.",
+ )
+
data_json = data.json() # type: ignore
data_json = _update_internal_new_user_params(data_json, data)
response = await generate_key_helper_fn(request_type="user", **data_json)
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index f252f8e44f6..42fc6a24228 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -417,6 +417,9 @@ except ImportError:
server_root_path = os.getenv("SERVER_ROOT_PATH", "")
_license_check = LicenseCheck()
premium_user: bool = _license_check.is_premium()
+premium_user_data: Optional[
+ "EnterpriseLicenseData"
+] = _license_check.airgapped_license_data
global_max_parallel_request_retries_env: Optional[str] = os.getenv(
"LITELLM_GLOBAL_MAX_PARALLEL_REQUEST_RETRIES"
)
diff --git a/tests/local_testing/test_amazing_vertex_completion.py b/tests/local_testing/test_amazing_vertex_completion.py
index 729f4dc5c51..6247b9816be 100644
--- a/tests/local_testing/test_amazing_vertex_completion.py
+++ b/tests/local_testing/test_amazing_vertex_completion.py
@@ -3942,3 +3942,20 @@ def test_vertex_ai_streaming_response_id():
iterator = iter(iterator)
first_chunk = next(iterator)
assert first_chunk.id == "vertex_ai_response_stream_123"
+
+
+def test_vertex_ai_gemini_2_5_pro_streaming():
+ load_vertex_ai_credentials()
+ # litellm._turn_on_debug()
+ response = completion(
+ model="vertex_ai/gemini-2.5-pro-preview-06-05",
+ messages=[{"role": "user", "content": "Hi!"}],
+ vertex_location="global",
+ stream=True,
+ )
+ has_real_content = False
+ for chunk in response:
+ print(chunk)
+ if chunk.choices[0].delta.content is not None and len(chunk.choices[0].delta.content) > 0:
+ has_real_content = True
+ assert has_real_content
\ No newline at end of file
diff --git a/tests/local_testing/test_enduser_spend_reset.py b/tests/test_enduser_spend_reset.py
similarity index 98%
rename from tests/local_testing/test_enduser_spend_reset.py
rename to tests/test_enduser_spend_reset.py
index 832ba9b3248..a182161ec82 100644
--- a/tests/local_testing/test_enduser_spend_reset.py
+++ b/tests/test_enduser_spend_reset.py
@@ -13,13 +13,6 @@ from litellm.caching.caching import DualCache
from litellm.proxy.common_utils.reset_budget_job import ResetBudgetJob
from litellm.proxy.utils import PrismaClient, ProxyLogging
-sys.path.insert(
- 0, os.path.abspath("../..")
-) # Adds the parent directory to the system path
-
-load_dotenv()
-
-
async def create_budget(session, data):
url = "http://0.0.0.0:4000/budget/new"
headers = {"Authorization": "Bearer sk-1234", "Content-Type": "application/json"}
@@ -193,7 +186,7 @@ async def budget_and_enduser_setup(prisma_client):
await delete_budget(session, id_budget_x)
await delete_budget(session, id_budget_y)
-
+# @pytest.mark.skip(reason="Skipping this test as it requires a local proxy to be running")
@pytest.mark.asyncio
async def test_reset_budget_for_endusers(
reset_budget_job, prisma_client, budget_and_enduser_setup
diff --git a/tests/test_litellm/proxy/auth/test_litellm_license.py b/tests/test_litellm/proxy/auth/test_litellm_license.py
new file mode 100644
index 00000000000..dfb17d77f71
--- /dev/null
+++ b/tests/test_litellm/proxy/auth/test_litellm_license.py
@@ -0,0 +1,29 @@
+import asyncio
+import json
+import os
+import sys
+from unittest.mock import AsyncMock, MagicMock, patch
+
+sys.path.insert(
+ 0, os.path.abspath("../../..")
+) # Adds the parent directory to the system path
+
+from litellm.proxy.auth.litellm_license import LicenseCheck
+
+
+def test_is_over_limit():
+ license_check = LicenseCheck()
+ license_check.airgapped_license_data = {"max_users": 100}
+ assert license_check.is_over_limit(101) is True
+ assert license_check.is_over_limit(100) is False
+ assert license_check.is_over_limit(99) is False
+
+ license_check.airgapped_license_data = {}
+ assert license_check.is_over_limit(101) is False
+ assert license_check.is_over_limit(100) is False
+ assert license_check.is_over_limit(99) is False
+
+ license_check.airgapped_license_data = None
+ assert license_check.is_over_limit(101) is False
+ assert license_check.is_over_limit(100) is False
+ assert license_check.is_over_limit(99) is False
diff --git a/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py
index 53653a2933c..6d14e043aca 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py
@@ -12,6 +12,8 @@ sys.path.insert(
from litellm.proxy._types import (
LiteLLM_UserTableFiltered,
+ NewUserRequest,
+ ProxyException,
UpdateUserRequest,
UserAPIKeyAuth,
)
@@ -20,6 +22,7 @@ from litellm.proxy.management_endpoints.internal_user_endpoints import (
_update_internal_user_params,
get_user_key_counts,
get_users,
+ new_user,
ui_view_users,
)
from litellm.proxy.proxy_server import app
@@ -237,3 +240,60 @@ def test_update_internal_user_params_reset_spend_and_max_budget():
assert "user_id" in non_default_values # Should not add user_id if not provided
assert non_default_values["user_id"] == "test_user_id"
assert "budget_duration" not in non_default_values # Should not add default values
+
+
+async def test_new_user_license_over_limit(mocker):
+ """
+ Test that /user/new endpoint raises an error when license is over the user limit
+ """
+ from fastapi import HTTPException
+
+ from litellm.proxy._types import NewUserRequest, UserAPIKeyAuth
+ from litellm.proxy.management_endpoints.internal_user_endpoints import new_user
+
+ # Mock the prisma client
+ mock_prisma_client = mocker.MagicMock()
+
+ # Setup the mock count response to return a high number of users
+ async def mock_count(*args, **kwargs):
+ return 1000 # High user count
+
+ mock_prisma_client.db.litellm_usertable.count = mock_count
+
+ # Mock check_duplicate_user_email to pass
+ async def mock_check_duplicate_user_email(*args, **kwargs):
+ return None # No duplicate found
+
+ mocker.patch(
+ "litellm.proxy.management_endpoints.internal_user_endpoints._check_duplicate_user_email",
+ mock_check_duplicate_user_email,
+ )
+
+ # Mock the license check to return True (over limit)
+ mock_license_check = mocker.MagicMock()
+ mock_license_check.is_over_limit.return_value = True
+
+ # Patch the imports in the endpoint
+ mocker.patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
+ mocker.patch("litellm.proxy.proxy_server._license_check", mock_license_check)
+
+ # Create test request data
+ user_request = NewUserRequest(
+ user_email="[email protected]", user_role="internal_user"
+ )
+
+ # Mock user_api_key_dict
+ mock_user_api_key_dict = UserAPIKeyAuth(user_id="test_admin")
+
+ # Call new_user function and expect HTTPException
+ with pytest.raises(ProxyException) as exc_info:
+ await new_user(data=user_request, user_api_key_dict=mock_user_api_key_dict)
+
+ # Verify the exception details
+ assert exc_info.value.code == 403 or exc_info.value.code == "403"
+ assert "License is over limit" in str(exc_info.value.message)
+ assert "[email protected]" in str(exc_info.value.message)
+
+ # Verify that the license check was called with the correct user count
+ mock_license_check.is_over_limit.assert_called_once_with(total_users=1000)
diff --git a/ui/litellm-dashboard/src/app/page.tsx b/ui/litellm-dashboard/src/app/page.tsx
index f49972fa43d..49a795528f2 100644
--- a/ui/litellm-dashboard/src/app/page.tsx
+++ b/ui/litellm-dashboard/src/app/page.tsx
@@ -274,6 +274,7 @@ export default function CreateKeyPage() {
<div className="flex flex-1 overflow-auto">
<div className="mt-8">
<Sidebar
+ accessToken={accessToken}
setPage={updatePage}
userRole={userRole}
defaultSelectedKey={page}
diff --git a/ui/litellm-dashboard/src/components/leftnav.tsx b/ui/litellm-dashboard/src/components/leftnav.tsx
index 145fe5762d4..43c29de2ab7 100644
--- a/ui/litellm-dashboard/src/components/leftnav.tsx
+++ b/ui/litellm-dashboard/src/components/leftnav.tsx
@@ -25,11 +25,12 @@ import {
TagsOutlined,
} from '@ant-design/icons';
import { old_admin_roles, v2_admin_role_names, all_admin_roles, rolesAllowedToSeeUsage, rolesWithWriteAccess, internalUserRoles } from '../utils/roles';
-
+import UsageIndicator from './usage_indicator';
const { Sider } = Layout;
// Define the props type
interface SidebarProps {
+ accessToken: string | null;
setPage: (page: string) => void;
userRole: string;
defaultSelectedKey: string;
@@ -48,6 +49,7 @@ interface MenuItem {
const Sidebar: React.FC<SidebarProps> = ({
+ accessToken,
setPage,
userRole,
defaultSelectedKey,
@@ -163,6 +165,7 @@ const Sidebar: React.FC<SidebarProps> = ({
} : undefined
}))}
/>
+ <UsageIndicator accessToken={accessToken} width={220}/>
</Sider>
</Layout>
);
diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsx
index 5e5d94e8c1b..7e8edc9f1cb 100644
--- a/ui/litellm-dashboard/src/components/networking.tsx
+++ b/ui/litellm-dashboard/src/components/networking.tsx
@@ -5468,3 +5468,36 @@ export const uiAuditLogsCall = async (
throw error;
}
};
+
+export const getRemainingUsers = async (accessToken: string): Promise<{
+ total_users: number;
+ total_users_used: number;
+ total_users_remaining: number;
+} | null> => {
+ try {
+ const url = proxyBaseUrl ? `${proxyBaseUrl}/user/available_users` : `/user/available_users`;
+
+ const response = await fetch(url, {
+ method: "GET",
+ headers: {
+ [globalLitellmHeaderName]: `Bearer ${accessToken}`,
+ },
+ });
+
+ if (!response.ok) {
+ // if 404 - return None
+ if (response.status === 404) {
+ return null;
+ }
+ const errorData = await response.text();
+ handleError(errorData);
+ throw new Error("Network response was not ok");
+ }
+
+ const data = await response.json();
+ return data;
+ } catch (error) {
+ console.error("Failed to fetch remaining users:", error);
+ throw error;
+ }
+};
\ No newline at end of file
diff --git a/ui/litellm-dashboard/src/components/usage_indicator.tsx b/ui/litellm-dashboard/src/components/usage_indicator.tsx
new file mode 100644
index 00000000000..450f6334163
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/usage_indicator.tsx
@@ -0,0 +1,370 @@
+import { useState, useEffect } from "react"
+import { Badge } from "@tremor/react"
+import { AlertTriangle, Users, TrendingUp, Loader2, ChevronDown, ChevronUp, Minus } from "lucide-react"
+import { getRemainingUsers } from "./networking"
+
+// Simple utility function to combine class names
+const cn = (...classes: (string | boolean | undefined)[]) => {
+ return classes.filter(Boolean).join(' ')
+}
+
+interface UsageIndicatorProps {
+ accessToken: string | null
+ width: number
+}
+
+interface UsageData {
+ total_users: number
+ total_users_used: number
+ total_users_remaining: number
+}
+
+export default function UsageIndicator({accessToken, width = 220}: UsageIndicatorProps) {
+ const position = "bottom-left"
+ const [isExpanded, setIsExpanded] = useState(false)
+ const [isMinimized, setIsMinimized] = useState(false)
+ const [data, setData] = useState<UsageData | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+
+ useEffect(() => {
+ const fetchData = async () => {
+ if (!accessToken) return
+
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await getRemainingUsers(accessToken)
+ setData(result)
+ } catch (err) {
+ console.error('Failed to fetch usage data:', err)
+ setError('Failed to load usage data')
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ fetchData()
+ }, [accessToken])
+
+ // Calculate derived values from data
+ const getUsageMetrics = (data: UsageData | null) => {
+ if (!data) {
+ return {
+ isOverLimit: false,
+ isNearLimit: false,
+ usagePercentage: 0
+ }
+ }
+
+ const isOverLimit = data.total_users_remaining <= 0
+ const isNearLimit = data.total_users_remaining <= 5 && data.total_users_remaining > 0
+ const usagePercentage = data.total_users > 0
+ ? (data.total_users_used / data.total_users) * 100
+ : 0
+
+ return { isOverLimit, isNearLimit, usagePercentage }
+ }
+
+ const { isOverLimit, isNearLimit, usagePercentage } = getUsageMetrics(data)
+
+ const getStatusColor = () => {
+ if (isOverLimit) return "red"
+ if (isNearLimit) return "yellow"
+ return "green"
+ }
+
+ const getStatusText = () => {
+ if (isOverLimit) return "Over Limit"
+ if (isNearLimit) return "Near Limit"
+ return "Active"
+ }
+
+ const getStatusIcon = () => {
+ if (isOverLimit) return <AlertTriangle className="h-3 w-3" />
+ if (isNearLimit) return <TrendingUp className="h-3 w-3" />
+ return null
+ }
+
+ // Minimized view - just a small restore button
+ const MinimizedView = () => {
+ const hasIssues = isOverLimit || isNearLimit
+
+ return (
+ <div
+ className="px-3 py-1"
+ style={{ maxWidth: `${width}px` }}
+ >
+ <button
+ onClick={() => setIsMinimized(false)}
+ className={cn(
+ "flex items-center gap-2 text-xs text-gray-400 hover:text-gray-600 transition-colors p-1 rounded w-full",
+ hasIssues && isOverLimit && "text-red-400 hover:text-red-600",
+ hasIssues && isNearLimit && "text-yellow-500 hover:text-yellow-700"
+ )}
+ title="Show usage details"
+ >
+ <Users className="h-3 w-3 flex-shrink-0" />
+ {hasIssues && <span className="flex-shrink-0">{getStatusIcon()}</span>}
+ <span className="truncate">{data ? `${data.total_users_used}/${data.total_users}` : "Usage"}</span>
+ </button>
+ </div>
+ )
+ }
+
+ // Sidebar/nav style component
+ const NavStyleView = () => {
+ if (isMinimized) {
+ return <MinimizedView />
+ }
+
+ if (isLoading) {
+ return (
+ <div
+ className="flex items-center gap-3 px-3 py-2 text-gray-500"
+ style={{ maxWidth: `${width}px` }}
+ >
+ <Loader2 className="h-4 w-4 animate-spin flex-shrink-0" />
+ <span className="text-sm truncate">Loading...</span>
+ </div>
+ )
+ }
+
+ if (error || !data) {
+ return (
+ <div
+ className="flex items-center justify-between gap-3 px-3 py-2 text-gray-400 group"
+ style={{ maxWidth: `${width}px` }}
+ >
+ <div className="flex items-center gap-3 min-w-0 flex-1">
+ <Users className="h-4 w-4 flex-shrink-0" />
+ <span className="text-sm truncate">{error || "No data"}</span>
+ </div>
+ <button
+ onClick={() => setIsMinimized(true)}
+ className="opacity-0 group-hover:opacity-100 p-0.5 hover:bg-gray-100 rounded transition-all flex-shrink-0"
+ title="Minimize"
+ >
+ <Minus className="h-3 w-3" />
+ </button>
+ </div>
+ )
+ }
+
+ return (
+ <div
+ className="px-3 py-2 group"
+ style={{ maxWidth: `${width}px` }}
+ >
+ {/* Main nav item style */}
+ <div className="flex items-center justify-between">
+ <button
+ onClick={() => setIsExpanded(!isExpanded)}
+ className={cn(
+ "flex items-center gap-3 text-left hover:bg-gray-50 rounded-md px-0 py-1 transition-colors flex-1 min-w-0",
+ isOverLimit && "text-red-600",
+ isNearLimit && "text-yellow-600"
+ )}
+ >
+ <Users className="h-4 w-4 flex-shrink-0" />
+ <span className="text-sm font-medium truncate">Usage Status</span>
+ {(isOverLimit || isNearLimit) && (
+ <Badge color={getStatusColor()} className="text-xs px-1.5 py-0.5 flex-shrink-0">
+ {getStatusIcon()}
+ </Badge>
+ )}
+ {isExpanded ? (
+ <ChevronUp className="h-3 w-3 text-gray-400 ml-auto flex-shrink-0" />
+ ) : (
+ <ChevronDown className="h-3 w-3 text-gray-400 ml-auto flex-shrink-0" />
+ )}
+ </button>
+
+ {/* Minimize button */}
+ <button
+ onClick={() => setIsMinimized(true)}
+ className="opacity-0 group-hover:opacity-100 p-0.5 hover:bg-gray-100 rounded transition-all ml-1 flex-shrink-0"
+ title="Minimize"
+ >
+ <Minus className="h-3 w-3 text-gray-400" />
+ </button>
+ </div>
+
+ {/* Expanded details - simple and compact */}
+ {isExpanded && (
+ <div className="mt-2 pl-7 text-xs text-gray-600">
+ <div className="mb-1">
+ <span className="font-medium">{data.total_users_used}/{data.total_users}</span>
+ <span className="text-gray-500"> users</span>
+ </div>
+
+ {/* Simple progress bar */}
+ <div className="w-full bg-gray-200 rounded-full h-1 mb-1">
+ <div
+ className={cn(
+ "h-1 rounded-full transition-all duration-300",
+ isOverLimit && "bg-red-500",
+ isNearLimit && "bg-yellow-500",
+ !isOverLimit && !isNearLimit && "bg-green-500",
+ )}
+ style={{ width: `${Math.min(usagePercentage, 100)}%` }}
+ />
+ </div>
+
+ {(isOverLimit || isNearLimit) && (
+ <div className={cn(
+ "flex items-center gap-1 text-xs",
+ isOverLimit && "text-red-600",
+ isNearLimit && "text-yellow-600"
+ )}>
+ {getStatusIcon()}
+ <span className="truncate">{getStatusText()}</span>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ )
+ }
+
+ // Optimized CardStyleView for 220px width
+ const CardStyleView = () => {
+ if (isMinimized) {
+ const hasIssues = isOverLimit || isNearLimit
+ return (
+ <button
+ onClick={() => setIsMinimized(false)}
+ className={cn(
+ "bg-white border border-gray-200 rounded-lg shadow-sm p-3 hover:shadow-md transition-all w-full",
+ hasIssues && isOverLimit && "border-red-200 bg-red-50",
+ hasIssues && isNearLimit && "border-yellow-200 bg-yellow-50"
+ )}
+ title="Show usage details"
+ >
+ <div className="flex items-center gap-2">
+ <Users className="h-4 w-4 flex-shrink-0" />
+ {hasIssues && <span className="flex-shrink-0">{getStatusIcon()}</span>}
+ {data && (
+ <span className="text-sm font-medium truncate">
+ {data.total_users_used}/{data.total_users}
+ </span>
+ )}
+ </div>
+ </button>
+ )
+ }
+
+ if (isLoading) {
+ return (
+ <div className="bg-white border border-gray-200 rounded-lg shadow-sm p-4 w-full">
+ <div className="flex items-center justify-center gap-2 py-2">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ <span className="text-sm text-gray-500 truncate">Loading...</span>
+ </div>
+ </div>
+ )
+ }
+
+ if (error || !data) {
+ return (
+ <div className="bg-white border border-gray-200 rounded-lg shadow-sm p-4 group w-full">
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex-1 min-w-0">
+ <span className="text-sm text-gray-500 truncate block">
+ {error || "No data"}
+ </span>
+ </div>
+ <button
+ onClick={() => setIsMinimized(true)}
+ className="opacity-0 group-hover:opacity-100 p-1 hover:bg-gray-100 rounded transition-all flex-shrink-0"
+ title="Minimize"
+ >
+ <Minus className="h-3 w-3 text-gray-400" />
+ </button>
+ </div>
+ </div>
+ )
+ }
+
+ return (
+ <div
+ className={cn(
+ "bg-white border rounded-lg shadow-sm p-3 transition-all duration-200 group w-full",
+ isOverLimit && "border-red-200 bg-red-50",
+ isNearLimit && "border-yellow-200 bg-yellow-50",
+ )}
+ >
+ {/* Header with title and minimize button */}
+ <div className="flex items-center justify-between gap-2 mb-3">
+ <div className="flex items-center gap-2 min-w-0 flex-1">
+ <Users className="h-4 w-4 flex-shrink-0" />
+ <span className="font-medium text-sm truncate">Usage</span>
+ {(isOverLimit || isNearLimit) && (
+ <Badge color={getStatusColor()} className="text-xs px-1.5 py-0.5 flex-shrink-0">
+ {getStatusText()}
+ </Badge>
+ )}
+ </div>
+ <button
+ onClick={() => setIsMinimized(true)}
+ className="opacity-0 group-hover:opacity-100 p-1 hover:bg-gray-100 rounded transition-all flex-shrink-0"
+ title="Minimize"
+ >
+ <Minus className="h-3 w-3 text-gray-400" />
+ </button>
+ </div>
+
+ {/* Compact stats optimized for 220px */}
+ <div className="space-y-2 text-sm">
+ <div className="flex justify-between items-center">
+ <span className="text-gray-600 text-xs">Used:</span>
+ <span className="font-medium text-right">{data.total_users_used}/{data.total_users}</span>
+ </div>
+ <div className="flex justify-between items-center">
+ <span className="text-gray-600 text-xs">Remaining:</span>
+ <span className={cn(
+ "font-medium text-right",
+ isOverLimit && "text-red-600",
+ isNearLimit && "text-yellow-600"
+ )}>
+ {data.total_users_remaining}
+ </span>
+ </div>
+ <div className="flex justify-between items-center">
+ <span className="text-gray-600 text-xs">Usage:</span>
+ <span className="font-medium text-right">{Math.round(usagePercentage)}%</span>
+ </div>
+
+ {/* Progress bar */}
+ <div className="w-full bg-gray-200 rounded-full h-2 mt-3">
+ <div
+ className={cn(
+ "h-2 rounded-full transition-all duration-300",
+ isOverLimit && "bg-red-500",
+ isNearLimit && "bg-yellow-500",
+ !isOverLimit && !isNearLimit && "bg-green-500",
+ )}
+ style={{ width: `${Math.min(usagePercentage, 100)}%` }}
+ />
+ </div>
+ </div>
+ </div>
+ )
+ }
+
+ // Don't render anything if no access token
+ if (!accessToken) {
+ return null
+ }
+
+ // Fixed positioning with proper spacing from edges
+ return (
+ <div
+ className="fixed bottom-4 left-4 z-50"
+ style={{ width: `${Math.min(width, 220)}px` }}
+ >
+ <CardStyleView />
+ </div>
+ )
+}