Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat(gateway): a Usage page for workspace budgets and spend

Petr Bauch8db1186bd957
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index 26901d9f2..38656f386 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -679,6 +679,14 @@ class TenantMembershipResponse(BaseModel):
role: str
+class CurrentTenantResponse(TenantMembershipResponse):
+ """The tenant this request is bound to. `administers` is whether the
+ caller may manage it — an `owner` or `admin` membership, or the operator
+ bit, which no membership role shows."""
+
+ administers: bool
+
+
class TenantCreateRequest(BaseModel):
name: str
diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.py
index a42bcf9c3..dd104e2a7 100644
--- a/core/switch_core/gateway/tenants.py
+++ b/core/switch_core/gateway/tenants.py
@@ -14,7 +14,13 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.bridges.agent.protocol.service import ProtocolService
from switch_core.clients.client_lifecycle_service import ClientLifecycleService
from switch_core.config import SwitchConfig
-from switch_core.db.models import Invitation, Tenant, TenantMember, User
+from switch_core.db.models import (
+ Invitation,
+ Tenant,
+ TenantMember,
+ User,
+ require_tenant_id,
+)
from switch_core.db.session_scope import tenant_session
from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.api_key_store import ApiKeyStore
@@ -34,6 +40,7 @@ from switch_core.gateway.auth import (
get_authenticated_caller,
get_authenticated_user_id,
get_current_user,
+ get_tenant_is_admin,
get_tenant_is_owner,
is_tenant_member,
list_tenant_memberships,
@@ -61,6 +68,7 @@ from switch_core.gateway.schemas import (
BudgetCreateRequest,
BudgetResponse,
BudgetUpdateRequest,
+ CurrentTenantResponse,
InvitationAcceptRequest,
InvitationCreateRequest,
InvitationCreateResponse,
@@ -214,6 +222,33 @@ async def list_tenants(
return await list_tenant_memberships(session_factory, user_store, user_id)
[email protected]("/tenants/current")
+async def current_tenant(
+ session: Annotated[AsyncSession, Depends(get_session)],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
+ user: Annotated[User, Depends(get_current_user)],
+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
+) -> CurrentTenantResponse:
+ """The tenant this request is bound to, and the caller's standing in it.
+
+ A client needs the id for every `/tenants/{tenant_id}/...` path, and the
+ binding is settled server-side (see `_resolve_tenant_id`), so this is the
+ one place it can ask rather than guess from `GET /tenants`.
+ """
+ tenant_id = require_tenant_id()
+ tenant = await session.get(Tenant, tenant_id)
+ role = await user_store.tenant_role(session, tenant_id, user.id)
+ if tenant is None or role is None:
+ raise HTTPException(status_code=404, detail="Tenant not found")
+ return CurrentTenantResponse(
+ id=tenant.id,
+ slug=tenant.slug,
+ name=tenant.name,
+ role=role,
+ administers=is_admin,
+ )
+
+
_LOCK_NOT_AVAILABLE = "55P03"
diff --git a/core/tests/switch_core/gateway/test_tenant_api_routes.py b/core/tests/switch_core/gateway/test_tenant_api_routes.py
index 2d4c048b0..1c9d7fc13 100644
--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py
+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py
@@ -1136,6 +1136,59 @@ def _window() -> dict[str, str]:
}
+class TestCurrentTenantRoute:
+ async def test_a_member_is_told_the_workspace_they_are_bound_to(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _make_tenant(session_factory, TENANT_A)
+ await _make_tenant(session_factory, TENANT_B)
+ user_id = await _make_member(
+ session_factory, name="current-member", tenant_id=TENANT_A, role="member"
+ )
+ async with session_factory() as session:
+ session.add(TenantMember(tenant_id=TENANT_B, user_id=user_id, role="owner"))
+ await session.commit()
+ token = _token(user_id, "[email protected]", TENANT_A)
+
+ async with _client(_app(session_factory), token) as client:
+ response = await client.get("/tenants/current")
+
+ assert response.status_code == 200
+ assert response.json() == {
+ "id": TENANT_A,
+ "slug": TENANT_A,
+ "name": TENANT_A,
+ "role": "member",
+ "administers": False,
+ }
+
+ @pytest.mark.parametrize(
+ ("role", "user_role"),
+ [("admin", "user"), ("owner", "user"), ("member", "admin")],
+ )
+ async def test_an_admin_owner_or_operator_is_told_they_administer_it(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ role: str,
+ user_role: str,
+ ) -> None:
+ await _make_tenant(session_factory, TENANT_A)
+ user_id = await _make_member(
+ session_factory,
+ name="current-admin",
+ tenant_id=TENANT_A,
+ role=role,
+ user_role=user_role,
+ )
+ token = _token(user_id, "[email protected]", TENANT_A)
+
+ async with _client(_app(session_factory), token) as client:
+ response = await client.get("/tenants/current")
+
+ assert response.status_code == 200
+ assert response.json()["administers"] is True
+
+
class TestUsageRoute:
async def _spend(
self,
diff --git a/gateway/src/App.tsx b/gateway/src/App.tsx
index bbb09b715..b22c07c74 100644
--- a/gateway/src/App.tsx
+++ b/gateway/src/App.tsx
@@ -19,6 +19,7 @@ import RoomDetailPage from "./pages/rooms/RoomDetailPage";
import RoomScopedDocumentView from "./pages/rooms/RoomScopedDocumentView";
import RoomsGraphPage from "./pages/rooms/RoomsGraphPage";
import RoomsPage from "./pages/rooms/RoomsPage";
+import UsagePage from "./pages/usage/UsagePage";
import UsersPage from "./pages/users/UsersPage";
function AppRoutes() {
@@ -83,6 +84,7 @@ function AppRoutes() {
<Route path="agents/:agentId" element={<AgentDetailPage />} />
<Route path="collaborations" element={<CollaborationsPage />} />
<Route path="registration-keys" element={<RegistrationKeysPage />} />
+ <Route path="usage" element={<UsagePage />} />
<Route path="users" element={<UsersPage />} />
</Route>
<Route path="/login" element={<Navigate to="/" replace />} />
diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.ts
index 423aec0e3..dede25312 100644
--- a/gateway/src/data/api.ts
+++ b/gateway/src/data/api.ts
@@ -1695,3 +1695,122 @@ export async function validateTemplate(
content,
});
}
+
+// ── Workspace usage and budgets ─────────────────────────────────────────────
+
+export interface CurrentTenant {
+ id: string;
+ slug: string;
+ name: string;
+ role: string;
+ // Whether the caller may manage the workspace: an owner or admin
+ // membership, or the operator bit.
+ administers: boolean;
+}
+
+export type UsageMetric =
+ | "messages"
+ | "turns"
+ | "input_tokens"
+ | "output_tokens"
+ | "cache_read_tokens"
+ | "cache_write_tokens";
+
+export const USAGE_METRICS: UsageMetric[] = [
+ "messages",
+ "turns",
+ "input_tokens",
+ "output_tokens",
+ "cache_read_tokens",
+ "cache_write_tokens",
+];
+
+// Messages and turns are not counted per model, so a budget on them covers
+// every model and the server refuses one that names a model.
+export const PER_MODEL_METRICS: UsageMetric[] = [
+ "input_tokens",
+ "output_tokens",
+ "cache_read_tokens",
+ "cache_write_tokens",
+];
+
+export interface UsageTotal {
+ metric: UsageMetric;
+ client_id: string;
+ // Null when the client has since been deleted; its spend still counts.
+ client_name: string | null;
+ client_type: string | null;
+ model: string;
+ amount: number;
+}
+
+export interface Budget {
+ id: string;
+ // Null covers every agent in the workspace.
+ agent_id: string | null;
+ agent_name: string | null;
+ metric: UsageMetric;
+ // Empty covers every model.
+ model: string;
+ amount_limit: number;
+ period_hours: number;
+ spent: number;
+ resets_at: string;
+ exhausted: boolean;
+}
+
+export interface BudgetCreate {
+ agent_id: string | null;
+ metric: UsageMetric;
+ model: string;
+ amount_limit: number;
+ period_hours: number;
+}
+
+export interface BudgetUpdate {
+ amount_limit: number;
+ period_hours: number;
+}
+
+export async function fetchCurrentTenant(): Promise<CurrentTenant | null> {
+ return fetchJson<CurrentTenant>("/tenants/current");
+}
+
+export async function fetchUsage(
+ tenantId: string,
+ since: Date,
+ until: Date,
+): Promise<UsageTotal[] | null> {
+ const params = new URLSearchParams({
+ since: since.toISOString(),
+ until: until.toISOString(),
+ });
+ return fetchJson<UsageTotal[]>(`/tenants/${tenantId}/usage?${params}`);
+}
+
+export async function fetchBudgets(tenantId: string): Promise<Budget[] | null> {
+ return fetchJson<Budget[]>(`/tenants/${tenantId}/budgets`);
+}
+
+export async function createBudget(tenantId: string, body: BudgetCreate): Promise<Budget> {
+ return jsonRequest<Budget>(`/tenants/${tenantId}/budgets`, "POST", body);
+}
+
+export async function updateBudget(
+ tenantId: string,
+ budgetId: string,
+ body: BudgetUpdate,
+): Promise<Budget> {
+ return jsonRequest<Budget>(`/tenants/${tenantId}/budgets/${budgetId}`, "PUT", body);
+}
+
+export async function deleteBudget(tenantId: string, budgetId: string): Promise<void> {
+ const res = await fetch(`${BASE}/tenants/${tenantId}/budgets/${budgetId}`, {
+ method: "DELETE",
+ credentials: "include",
+ });
+ if (!res.ok) {
+ const detail = await res.json().catch(() => null);
+ throw new Error(errorText(detail?.detail, `${res.status} ${res.statusText}`));
+ }
+}
diff --git a/gateway/src/data/hooks.ts b/gateway/src/data/hooks.ts
index 7f44e31ac..17409042d 100644
--- a/gateway/src/data/hooks.ts
+++ b/gateway/src/data/hooks.ts
@@ -2,6 +2,9 @@ import { useCallback, useEffect, useState } from "react";
import {
type AgentDetail,
type AgentSummary,
+ type Budget,
+ type CurrentTenant,
+ type UsageTotal,
type ApiKeyDetail,
type BridgeDetail,
type BridgeTypeInfo,
@@ -28,6 +31,9 @@ import {
fetchAgent,
fetchAgents,
fetchApiKeys,
+ fetchBudgets,
+ fetchCurrentTenant,
+ fetchUsage,
fetchAllExternalUsers,
fetchBridges,
fetchBridgeTypes,
@@ -348,3 +354,24 @@ export function useTemplates(
);
return useQuery(fetcher);
}
+
+export function useCurrentTenant(): UseQueryResult<CurrentTenant> {
+ return useQuery(fetchCurrentTenant);
+}
+
+export function useBudgets(tenantId: string): UseQueryResult<Budget[]> {
+ const fetcher = useCallback(() => fetchBudgets(tenantId), [tenantId]);
+ return useQuery(fetcher);
+}
+
+export function useUsage(
+ tenantId: string,
+ since: Date,
+ until: Date,
+): UseQueryResult<UsageTotal[]> {
+ const fetcher = useCallback(
+ () => fetchUsage(tenantId, since, until),
+ [tenantId, since, until],
+ );
+ return useQuery(fetcher);
+}
diff --git a/gateway/src/layout/NavRail.tsx b/gateway/src/layout/NavRail.tsx
index c3a161edc..8f52e412f 100644
--- a/gateway/src/layout/NavRail.tsx
+++ b/gateway/src/layout/NavRail.tsx
@@ -1,5 +1,6 @@
import AccountTreeOutlined from "@mui/icons-material/AccountTreeOutlined";
import ChatBubbleOutlineOutlined from "@mui/icons-material/ChatBubbleOutlineOutlined";
+import DataUsageOutlined from "@mui/icons-material/DataUsageOutlined";
import FolderOutlined from "@mui/icons-material/FolderOutlined";
import LockOutlined from "@mui/icons-material/LockOutlined";
import LogoutOutlined from "@mui/icons-material/LogoutOutlined";
@@ -12,6 +13,7 @@ import { memo, useState } from "react";
import { NavLink, useLocation } from "react-router";
import type { ComponentType, MouseEvent } from "react";
import { useAuth } from "../data/AuthContext";
+import { useCurrentTenant } from "../data/hooks";
import ChangePasswordDialog from "./ChangePasswordDialog";
import ThemeModeToggle from "./ThemeModeToggle";
@@ -30,6 +32,10 @@ const NAV_ITEMS: NavItem[] = [
{ label: "API Keys", path: "/registration-keys", icon: VpnKeyOutlined },
];
+const WORKSPACE_ADMIN_ITEMS: NavItem[] = [
+ { label: "Usage", path: "/usage", icon: DataUsageOutlined },
+];
+
const ADMIN_ITEMS: NavItem[] = [{ label: "Users", path: "/users", icon: PeopleOutlined }];
const TARGET = 44;
@@ -91,7 +97,13 @@ export default memo(function NavRail() {
const [anchor, setAnchor] = useState<HTMLElement | null>(null);
const [passwordDialogOpen, setPasswordDialogOpen] = useState(false);
- const items = user?.role === "admin" ? [...NAV_ITEMS, ...ADMIN_ITEMS] : NAV_ITEMS;
+ const { data: tenant } = useCurrentTenant();
+
+ const items = [
+ ...NAV_ITEMS,
+ ...(tenant?.administers ? WORKSPACE_ADMIN_ITEMS : []),
+ ...(user?.role === "admin" ? ADMIN_ITEMS : []),
+ ];
const initial = (user?.email ?? "?").charAt(0).toUpperCase();
return (
diff --git a/gateway/src/pages/usage/BudgetDialog.tsx b/gateway/src/pages/usage/BudgetDialog.tsx
new file mode 100644
index 000000000..d39847c87
--- /dev/null
+++ b/gateway/src/pages/usage/BudgetDialog.tsx
@@ -0,0 +1,185 @@
+import {
+ Alert,
+ Button,
+ CircularProgress,
+ Dialog,
+ DialogActions,
+ DialogContent,
+ DialogTitle,
+ MenuItem,
+ Stack,
+ TextField,
+} from "@mui/material";
+import { useCallback, useEffect, useState } from "react";
+import {
+ type Budget,
+ type UsageMetric,
+ PER_MODEL_METRICS,
+ USAGE_METRICS,
+ createBudget,
+ updateBudget,
+} from "../../data/api";
+import { useAgents } from "../../data/hooks";
+import { metricLabel } from "./usageFormat";
+
+const WHOLE_WORKSPACE = "";
+
+interface Props {
+ tenantId: string;
+ // The budget being edited, or null to add one.
+ budget: Budget | null;
+ open: boolean;
+ onClose: () => void;
+ onSaved: () => void;
+}
+
+export default function BudgetDialog({ tenantId, budget, open, onClose, onSaved }: Props) {
+ const { data: agents } = useAgents();
+ const [agentId, setAgentId] = useState(WHOLE_WORKSPACE);
+ const [metric, setMetric] = useState<UsageMetric>("output_tokens");
+ const [model, setModel] = useState("");
+ const [limit, setLimit] = useState("");
+ const [periodHours, setPeriodHours] = useState("24");
+ const [submitting, setSubmitting] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!open) return;
+ setAgentId(budget?.agent_id ?? WHOLE_WORKSPACE);
+ setMetric(budget?.metric ?? "output_tokens");
+ setModel(budget?.model ?? "");
+ setLimit(budget ? String(budget.amount_limit) : "");
+ setPeriodHours(budget ? String(budget.period_hours) : "24");
+ setError(null);
+ }, [open, budget]);
+
+ const perModel = PER_MODEL_METRICS.includes(metric);
+ const limitValue = Number(limit);
+ const periodValue = Number(periodHours);
+ const valid =
+ Number.isInteger(limitValue) &&
+ limitValue > 0 &&
+ Number.isInteger(periodValue) &&
+ periodValue > 0;
+
+ const handleSubmit = useCallback(async () => {
+ setSubmitting(true);
+ setError(null);
+ try {
+ if (budget) {
+ await updateBudget(tenantId, budget.id, {
+ amount_limit: limitValue,
+ period_hours: periodValue,
+ });
+ } else {
+ await createBudget(tenantId, {
+ agent_id: agentId === WHOLE_WORKSPACE ? null : agentId,
+ metric,
+ model: perModel ? model.trim() : "",
+ amount_limit: limitValue,
+ period_hours: periodValue,
+ });
+ }
+ onSaved();
+ onClose();
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Failed to save the budget.");
+ } finally {
+ setSubmitting(false);
+ }
+ }, [budget, tenantId, agentId, metric, perModel, model, limitValue, periodValue, onSaved, onClose]);
+
+ return (
+ <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
+ <DialogTitle>{budget ? "Edit budget" : "Add budget"}</DialogTitle>
+ <DialogContent>
+ <Stack spacing={2} sx={{ mt: 1 }}>
+ {error && <Alert severity="error">{error}</Alert>}
+ {budget && (
+ <Alert severity="info">
+ What a budget covers is fixed. To cover something else, add another budget.
+ </Alert>
+ )}
+ <TextField
+ select
+ label="Applies to"
+ value={agentId}
+ onChange={(e) => setAgentId(e.target.value)}
+ disabled={budget !== null}
+ helperText="A workspace budget caps what all agents spend together."
+ fullWidth
+ >
+ <MenuItem value={WHOLE_WORKSPACE}>Every agent in the workspace</MenuItem>
+ {(agents ?? []).map((agent) => (
+ <MenuItem key={agent.id} value={agent.id}>
+ {agent.name}
+ </MenuItem>
+ ))}
+ {budget?.agent_id && !(agents ?? []).some((a) => a.id === budget.agent_id) && (
+ <MenuItem value={budget.agent_id}>{budget.agent_name ?? budget.agent_id}</MenuItem>
+ )}
+ </TextField>
+ <TextField
+ select
+ label="Metric"
+ value={metric}
+ onChange={(e) => setMetric(e.target.value as UsageMetric)}
+ disabled={budget !== null}
+ fullWidth
+ >
+ {USAGE_METRICS.map((m) => (
+ <MenuItem key={m} value={m}>
+ {metricLabel(m)}
+ </MenuItem>
+ ))}
+ </TextField>
+ <TextField
+ label="Model"
+ value={perModel ? model : ""}
+ onChange={(e) => setModel(e.target.value)}
+ disabled={budget !== null || !perModel}
+ placeholder="Every model"
+ helperText={
+ perModel
+ ? "Leave empty to cover every model."
+ : `${metricLabel(metric)} are not counted per model.`
+ }
+ fullWidth
+ />
+ <Stack direction="row" spacing={2}>
+ <TextField
+ label="Limit"
+ type="number"
+ value={limit}
+ onChange={(e) => setLimit(e.target.value)}
+ required
+ fullWidth
+ slotProps={{ htmlInput: { min: 1, step: 1 } }}
+ />
+ <TextField
+ label="Period (hours)"
+ type="number"
+ value={periodHours}
+ onChange={(e) => setPeriodHours(e.target.value)}
+ required
+ fullWidth
+ helperText="24 is a day, 168 a week."
+ slotProps={{ htmlInput: { min: 1, step: 1 } }}
+ />
+ </Stack>
+ </Stack>
+ </DialogContent>
+ <DialogActions>
+ <Button onClick={onClose}>Cancel</Button>
+ <Button
+ variant="contained"
+ onClick={handleSubmit}
+ disabled={submitting || !valid}
+ startIcon={submitting ? <CircularProgress size={16} /> : undefined}
+ >
+ {budget ? "Save" : "Add"}
+ </Button>
+ </DialogActions>
+ </Dialog>
+ );
+}
diff --git a/gateway/src/pages/usage/UsagePage.tsx b/gateway/src/pages/usage/UsagePage.tsx
new file mode 100644
index 000000000..9bfa66926
--- /dev/null
+++ b/gateway/src/pages/usage/UsagePage.tsx
@@ -0,0 +1,330 @@
+import AddCircleOutline from "@mui/icons-material/AddCircleOutline";
+import DeleteOutline from "@mui/icons-material/DeleteOutline";
+import EditOutlined from "@mui/icons-material/EditOutlined";
+import {
+ Alert,
+ Box,
+ Button,
+ Chip,
+ CircularProgress,
+ Dialog,
+ DialogActions,
+ DialogContent,
+ DialogContentText,
+ DialogTitle,
+ IconButton,
+ LinearProgress,
+ MenuItem,
+ Stack,
+ TextField,
+ Tooltip,
+ Typography,
+} from "@mui/material";
+import type { GridColDef } from "@mui/x-data-grid";
+import { useCallback, useMemo, useState } from "react";
+import DataTable from "../../components/DataTable";
+import { type Budget, type CurrentTenant, type UsageTotal, deleteBudget } from "../../data/api";
+import { useBudgets, useCurrentTenant, useUsage } from "../../data/hooks";
+import { formatDateTime } from "../../theme/hootFormat";
+import BudgetDialog from "./BudgetDialog";
+import { formatAmount, formatPeriod, metricLabel } from "./usageFormat";
+
+const WINDOWS = [
+ { label: "Last 24 hours", hours: 24 },
+ { label: "Last 7 days", hours: 24 * 7 },
+ { label: "Last 30 days", hours: 24 * 30 },
+];
+
+type UsageRow = UsageTotal & { id: string };
+
+export default function UsagePage() {
+ const { data: tenant, loading, error } = useCurrentTenant();
+
+ if (loading) return <CircularProgress />;
+ if (error || !tenant) {
+ return <Alert severity="error">Could not load the current workspace.</Alert>;
+ }
+ if (!tenant.administers) {
+ return (
+ <Alert severity="info">
+ Only owners and admins of {tenant.name} can see its usage and budgets.
+ </Alert>
+ );
+ }
+ return <WorkspaceUsage tenant={tenant} />;
+}
+
+function WorkspaceUsage({ tenant }: { tenant: CurrentTenant }) {
+ return (
+ <Box sx={{ display: "flex", flexDirection: "column", flexGrow: 1, minHeight: 0, gap: 3 }}>
+ <Typography variant="h5">Usage · {tenant.name}</Typography>
+ <BudgetsSection tenantId={tenant.id} />
+ <UsageSection tenantId={tenant.id} />
+ </Box>
+ );
+}
+
+function BudgetsSection({ tenantId }: { tenantId: string }) {
+ const { data: budgets, loading, error, refetch } = useBudgets(tenantId);
+ const [dialogOpen, setDialogOpen] = useState(false);
+ const [editing, setEditing] = useState<Budget | null>(null);
+ const [deleteTarget, setDeleteTarget] = useState<Budget | null>(null);
+ const [deleting, setDeleting] = useState(false);
+ const [deleteError, setDeleteError] = useState<string | null>(null);
+
+ const openEditor = useCallback((budget: Budget | null) => {
+ setEditing(budget);
+ setDialogOpen(true);
+ }, []);
+
+ const handleDelete = useCallback(async () => {
+ if (!deleteTarget) return;
+ setDeleting(true);
+ setDeleteError(null);
+ try {
+ await deleteBudget(tenantId, deleteTarget.id);
+ setDeleteTarget(null);
+ refetch();
+ } catch (err) {
+ setDeleteError(err instanceof Error ? err.message : "Failed to remove the budget.");
+ } finally {
+ setDeleting(false);
+ }
+ }, [tenantId, deleteTarget, refetch]);
+
+ const columns = useMemo<GridColDef<Budget>[]>(
+ () => [
+ {
+ field: "agent_name",
+ headerName: "Applies to",
+ flex: 1,
+ minWidth: 180,
+ valueGetter: (_value, row) =>
+ row.agent_id === null ? "Every agent" : (row.agent_name ?? row.agent_id),
+ },
+ {
+ field: "metric",
+ headerName: "Metric",
+ width: 170,
+ valueFormatter: (value) => metricLabel(value),
+ },
+ {
+ field: "model",
+ headerName: "Model",
+ width: 160,
+ valueFormatter: (value: string) => value || "Every model",
+ },
+ {
+ field: "spent",
+ headerName: "Spent this period",
+ flex: 1,
+ minWidth: 220,
+ sortable: false,
+ renderCell: ({ row }) => (
+ <Stack justifyContent="center" sx={{ height: "100%" }} spacing={0.5}>
+ <Typography variant="body2">
+ {formatAmount(row.spent)} of {formatAmount(row.amount_limit)} per{" "}
+ {formatPeriod(row.period_hours)}
+ </Typography>
+ <LinearProgress
+ variant="determinate"
+ value={Math.min(100, (row.spent / row.amount_limit) * 100)}
+ color={row.exhausted ? "error" : "primary"}
+ />
+ </Stack>
+ ),
+ },
+ {
+ field: "resets_at",
+ headerName: "Resets",
+ width: 180,
+ valueFormatter: (value: string) => formatDateTime(value),
+ },
+ {
+ field: "exhausted",
+ headerName: "Status",
+ width: 120,
+ renderCell: ({ row }) =>
+ row.exhausted ? (
+ <Chip size="small" color="error" label="Reached" />
+ ) : (
+ <Chip size="small" variant="outlined" label="Within" />
+ ),
+ },
+ {
+ field: "actions",
+ headerName: "",
+ width: 100,
+ sortable: false,
+ filterable: false,
+ renderCell: ({ row }) => (
+ <>
+ <Tooltip title="Edit">
+ <IconButton size="small" onClick={() => openEditor(row)}>
+ <EditOutlined fontSize="small" />
+ </IconButton>
+ </Tooltip>
+ <Tooltip title="Remove">
+ <IconButton size="small" onClick={() => setDeleteTarget(row)}>
+ <DeleteOutline fontSize="small" />
+ </IconButton>
+ </Tooltip>
+ </>
+ ),
+ },
+ ],
+ [openEditor],
+ );
+
+ return (
+ <Box>
+ <Stack direction="row" alignItems="center" justifyContent="space-between" mb={1}>
+ <Box>
+ <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
+ Budgets
+ </Typography>
+ <Typography variant="body2" color="text.secondary">
+ An agent that reaches a budget stops taking work until it resets. People are
+ never stopped. No budget means no limit.
+ </Typography>
+ </Box>
+ <Button variant="contained" startIcon={<AddCircleOutline />} onClick={() => openEditor(null)}>
+ Add budget
+ </Button>
+ </Stack>
+ {loading ? (
+ <CircularProgress />
+ ) : error ? (
+ <Alert severity="error">Could not load budgets.</Alert>
+ ) : (
+ <Box sx={{ display: "flex", flexDirection: "column", height: Math.min(420, 108 + (budgets?.length ?? 0) * 56) }}>
+ <DataTable rows={budgets ?? []} columns={columns} fillHeight pageSize={10} />
+ </Box>
+ )}
+
+ <BudgetDialog
+ tenantId={tenantId}
+ budget={editing}
+ open={dialogOpen}
+ onClose={() => setDialogOpen(false)}
+ onSaved={refetch}
+ />
+
+ <Dialog open={!!deleteTarget} onClose={() => setDeleteTarget(null)}>
+ <DialogTitle>Remove budget</DialogTitle>
+ <DialogContent>
+ {deleteError && (
+ <Alert severity="error" sx={{ mb: 2 }}>
+ {deleteError}
+ </Alert>
+ )}
+ <DialogContentText>
+ Remove the {deleteTarget ? metricLabel(deleteTarget.metric).toLowerCase() : ""} budget
+ for {deleteTarget?.agent_id === null ? "every agent" : deleteTarget?.agent_name}? What
+ it covers will no longer be limited.
+ </DialogContentText>
+ </DialogContent>
+ <DialogActions>
+ <Button onClick={() => setDeleteTarget(null)}>Cancel</Button>
+ <Button
+ color="error"
+ variant="contained"
+ onClick={handleDelete}
+ disabled={deleting}
+ startIcon={deleting ? <CircularProgress size={16} /> : undefined}
+ >
+ Remove
+ </Button>
+ </DialogActions>
+ </Dialog>
+ </Box>
+ );
+}
+
+function UsageSection({ tenantId }: { tenantId: string }) {
+ const [windowHours, setWindowHours] = useState(WINDOWS[0].hours);
+ const [since, until] = useMemo(() => {
+ const end = new Date();
+ return [new Date(end.getTime() - windowHours * 3600 * 1000), end];
+ }, [windowHours]);
+ const { data: totals, loading, error } = useUsage(tenantId, since, until);
+
+ const rows = useMemo<UsageRow[]>(
+ () =>
+ (totals ?? []).map((t) => ({ ...t, id: `${t.metric}:${t.client_id}:${t.model}` })),
+ [totals],
+ );
+
+ const columns = useMemo<GridColDef<UsageRow>[]>(
+ () => [
+ {
+ field: "client_name",
+ headerName: "Consumer",
+ flex: 1,
+ minWidth: 200,
+ valueGetter: (_value, row) => row.client_name ?? `Deleted (${row.client_id})`,
+ },
+ {
+ field: "client_type",
+ headerName: "Kind",
+ width: 120,
+ valueFormatter: (value: string | null) => value ?? "—",
+ },
+ {
+ field: "metric",
+ headerName: "Metric",
+ width: 180,
+ valueFormatter: (value) => metricLabel(value),
+ },
+ {
+ field: "model",
+ headerName: "Model",
+ width: 180,
+ valueFormatter: (value: string) => value || "—",
+ },
+ {
+ field: "amount",
+ headerName: "Amount",
+ type: "number",
+ width: 140,
+ valueFormatter: (value: number) => formatAmount(value),
+ },
+ ],
+ [],
+ );
+
+ return (
+ <Box sx={{ display: "flex", flexDirection: "column", flexGrow: 1, minHeight: 320 }}>
+ <Stack direction="row" alignItems="center" justifyContent="space-between" mb={1}>
+ <Box>
+ <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
+ What was spent
+ </Typography>
+ <Typography variant="body2" color="text.secondary">
+ Counted in whole hours. Tokens appear only for sessions that report them.
+ </Typography>
+ </Box>
+ <TextField
+ select
+ size="small"
+ value={windowHours}
+ onChange={(e) => setWindowHours(Number(e.target.value))}
+ sx={{ width: 200 }}
+ >
+ {WINDOWS.map((w) => (
+ <MenuItem key={w.hours} value={w.hours}>
+ {w.label}
+ </MenuItem>
+ ))}
+ </TextField>
+ </Stack>
+ {loading ? (
+ <CircularProgress />
+ ) : error ? (
+ <Alert severity="error">Could not load usage.</Alert>
+ ) : (
+ <DataTable rows={rows} columns={columns} fillHeight pageSize={25} />
+ )}
+ </Box>
+ );
+}
diff --git a/gateway/src/pages/usage/usageFormat.ts b/gateway/src/pages/usage/usageFormat.ts
new file mode 100644
index 000000000..3ffc678c1
--- /dev/null
+++ b/gateway/src/pages/usage/usageFormat.ts
@@ -0,0 +1,26 @@
+import type { UsageMetric } from "../../data/api";
+
+const METRIC_LABELS: Record<UsageMetric, string> = {
+ messages: "Messages",
+ turns: "Turns",
+ input_tokens: "Input tokens",
+ output_tokens: "Output tokens",
+ cache_read_tokens: "Cache read tokens",
+ cache_write_tokens: "Cache write tokens",
+};
+
+export function metricLabel(metric: UsageMetric): string {
+ return METRIC_LABELS[metric];
+}
+
+export function formatAmount(value: number): string {
+ return value.toLocaleString();
+}
+
+/** `24h` → "day", `168h` → "week", anything else in hours. */
+export function formatPeriod(hours: number): string {
+ if (hours === 24) return "day";
+ if (hours === 168) return "week";
+ if (hours % 24 === 0) return `${hours / 24} days`;
+ return `${hours}h`;
+}