🙌 OpenHands: AI-Driven Development
feat: budgets and usage monitoring UI (#15186)
Saurya Velagapudi03cf3faac3c3
diff --git a/AGENTS.md b/AGENTS.mdindex e3f7950c28..91086a971e 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -134,6 +134,8 @@ Backend:Frontend:- Located in the `frontend` directory+- UI refactors: Budgets UI is split into `budgets.tsx` + `budgets-tabs.tsx`, `budgets-components.tsx`, `budgets-constants.ts`. Usage monitoring dashboard is split into `usage-dashboard.tsx` with `usage-dashboard-tabs.tsx`, `usage-dashboard-widgets.tsx`, and `usage-dashboard-utils.ts`. Shared inline SVGs live in `frontend/src/components/shared/icons/inline-icons.tsx`.+- Prerequisites: A recent version of NodeJS / NPM- Setup: Run `npm install` in the frontend directory- Testing:diff --git a/frontend/__tests__/components/features/budgets/budgets.test.tsx b/frontend/__tests__/components/features/budgets/budgets.test.tsxnew file mode 100644index 0000000000..97a7e99d51--- /dev/null+++ b/frontend/__tests__/components/features/budgets/budgets.test.tsx@@ -0,0 +1,184 @@+import { render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { MemoryRouter } from "react-router";+import { describe, expect, it, vi, beforeEach } from "vitest";+import { Budgets } from "#/components/features/budgets/budgets";+import { organizationService } from "#/api/organization-service/organization-service.api";++vi.mock("#/api/organization-service/organization-service.api", () => ({+ organizationService: {+ getBudgetSettings: vi.fn(),+ updateBudgetSettings: vi.fn(),+ upsertBudgetOverride: vi.fn(),+ deleteBudgetOverride: vi.fn(),+ },+}));++vi.mock("#/hooks/query/use-config", () => ({+ useConfig: () => ({+ data: {+ slack_enabled: true,+ email_enabled: true,+ },+ }),+}));++vi.mock("#/context/use-selected-organization", () => ({+ useSelectedOrganizationId: () => ({+ organizationId: "org-123",+ setOrganizationId: vi.fn(),+ }),+}));++vi.mock("#/hooks/use-debounce", () => ({+ useDebounce: (value: string) => value,+}));++const budgetResponse = {+ enabled: true,+ monthly_limit: 1000,+ reset_day: 1,+ slack_channel: "alerts",+ slack_team_id: "T123",+ default_user_monthly_limit: 250,+ cycle_start_at: "2024-01-01T00:00:00Z",+ cycle_end_at: "2024-01-31T00:00:00Z",+ current_spend: 200,+ current_spend_percentage: 20,+ thresholds: [+ {+ id: 1,+ percentage: 75,+ email_enabled: true,+ slack_enabled: false,+ },+ ],+ users: [+ {+ user_id: "user-1",+ user_email: "[email protected]",+ user_name: "User One",+ current_spend: 25,+ monthly_limit: null,+ effective_monthly_limit: 50,+ is_disabled: false,+ is_override: true,+ },+ ],+ users_total: 1,+ users_page: 1,+ users_per_page: 50,+};++const renderBudgets = async () => {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ });+ render(+ <MemoryRouter>+ <QueryClientProvider client={queryClient}>+ <Budgets />+ </QueryClientProvider>+ </MemoryRouter>,+ );++ await screen.findByText("Organization monthly budget");+};++describe("Budgets", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(organizationService.getBudgetSettings).mockResolvedValue(+ budgetResponse,+ );+ vi.mocked(organizationService.updateBudgetSettings).mockResolvedValue(+ budgetResponse,+ );+ vi.mocked(organizationService.upsertBudgetOverride).mockResolvedValue(+ budgetResponse.users[0],+ );+ vi.mocked(organizationService.deleteBudgetOverride).mockResolvedValue();+ });++ it("adds and removes thresholds, then saves updated settings", async () => {+ const user = userEvent.setup();+ await renderBudgets();++ await user.click(+ screen.getByRole("button", { name: /\+ Add threshold/i }),+ );++ expect(await screen.findByText("50%")).toBeInTheDocument();++ await user.click(screen.getByRole("button", { name: "Save changes" }));++ await waitFor(() => {+ expect(organizationService.updateBudgetSettings).toHaveBeenCalled();+ });++ const firstSave = vi+ .mocked(organizationService.updateBudgetSettings)+ .mock.calls.at(-1)?.[0];++ expect(firstSave?.payload.thresholds?.map((item) => item.percentage)).toEqual(+ [50, 75],+ );++ await user.click(screen.getByLabelText("Delete 50% threshold"));+ await user.click(screen.getByRole("button", { name: "Save changes" }));++ await waitFor(() => {+ const lastSave = vi+ .mocked(organizationService.updateBudgetSettings)+ .mock.calls.at(-1)?.[0];+ expect(lastSave?.payload.thresholds?.map((item) => item.percentage)).toEqual(+ [75],+ );+ });+ });++ it("saves and removes user overrides", async () => {+ const user = userEvent.setup();+ await renderBudgets();++ await user.click(+ screen.getByRole("button", { name: "User overrides" }),+ );++ await screen.findByText("User One");++ await user.click(screen.getByRole("button", { name: "Edit" }));++ const overrideInput = screen.getByRole("spinbutton");+ await user.clear(overrideInput);+ await user.type(overrideInput, "75");++ await user.click(screen.getByRole("button", { name: "Save" }));++ await waitFor(() => {+ expect(organizationService.upsertBudgetOverride).toHaveBeenCalledWith({+ orgId: "org-123",+ userId: "user-1",+ payload: {+ monthly_limit: 75,+ is_disabled: false,+ },+ });+ });++ await user.click(+ screen.getByLabelText("Remove override for User One"),+ );++ await waitFor(() => {+ expect(organizationService.deleteBudgetOverride).toHaveBeenCalledWith({+ orgId: "org-123",+ userId: "user-1",+ });+ });+ });+});diff --git a/frontend/__tests__/components/features/user/user-context-menu.test.tsx b/frontend/__tests__/components/features/user/user-context-menu.test.tsxindex 5a30e54a96..4624335b04 100644--- a/frontend/__tests__/components/features/user/user-context-menu.test.tsx+++ b/frontend/__tests__/components/features/user/user-context-menu.test.tsx@@ -196,9 +196,9 @@ describe("UserContextMenu", () => {// In SaaS, personal LLM/Condenser/Verification routes are hidden in favor// of /settings/org-defaults/* (visible only when an org is selected, which// this test does not seed). Org-only and billing routes are also filtered.- // The usage & monitoring link is also hidden because the test renders as a- // non-admin "member" user; useSettingsNavItems() suppresses it for members- // and personal orgs (see use-settings-nav-items.ts).+ // The Usage & Monitoring and Budgets links are hidden because the test+ // renders as a non-admin "member" user; useSettingsNavItems() suppresses+ // them for members and personal orgs (see use-settings-nav-items.ts).const personalLlmPaths = new Set(["/settings","/settings/condenser",@@ -210,6 +210,7 @@ describe("UserContextMenu", () => {item.to !== "/settings/org" &&item.to !== "/settings/billing" &&item.to !== "/settings/usage-monitoring" &&+ item.to !== "/settings/budgets" &&!item.to.startsWith("/settings/org-defaults") &&!personalLlmPaths.has(item.to),);diff --git a/frontend/__tests__/hooks/query/use-org-usage-stats.test.tsx b/frontend/__tests__/hooks/query/use-org-usage-stats.test.tsxnew file mode 100644index 0000000000..bbac7ea4ae--- /dev/null+++ b/frontend/__tests__/hooks/query/use-org-usage-stats.test.tsx@@ -0,0 +1,70 @@+import { renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { ReactNode } from "react";+import { describe, expect, it, vi, beforeEach } from "vitest";+import { useOrgUsageStats } from "#/hooks/query/use-org-usage-stats";+import { organizationService } from "#/api/organization-service/organization-service.api";++vi.mock("#/api/organization-service/organization-service.api", () => ({+ organizationService: {+ getUsageStats: vi.fn(),+ },+}));++vi.mock("#/context/use-selected-organization", () => ({+ useSelectedOrganizationId: vi.fn(),+}));++import { useSelectedOrganizationId } from "#/context/use-selected-organization";++const createWrapper = () => {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ },+ });++ return ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+};++const mockUsageStats = {+ active_users: 0,+ agent_runs: 0,+ total_tokens: 0,+ estimated_spend: 0,+ daily_usage: [],+ team_usage: [],+ model_usage: [],+ agent_usage: [],+};++describe("useOrgUsageStats", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("passes timeWindow through without setting days", async () => {+ vi.mocked(useSelectedOrganizationId).mockReturnValue({+ organizationId: "org-123",+ setOrganizationId: vi.fn(),+ });+ vi.mocked(organizationService.getUsageStats).mockResolvedValue(+ mockUsageStats,+ );++ const { result } = renderHook(+ () => useOrgUsageStats({ timeWindow: "ytd" }),+ { wrapper: createWrapper() },+ );++ await waitFor(() => expect(result.current.isSuccess).toBe(true));++ expect(organizationService.getUsageStats).toHaveBeenCalledWith({+ orgId: "org-123",+ days: undefined,+ timeWindow: "ytd",+ });+ });+});diff --git a/frontend/__tests__/hooks/use-settings-nav-items.test.tsx b/frontend/__tests__/hooks/use-settings-nav-items.test.tsxindex 28ceb94439..3ab919eb9a 100644--- a/frontend/__tests__/hooks/use-settings-nav-items.test.tsx+++ b/frontend/__tests__/hooks/use-settings-nav-items.test.tsx@@ -177,6 +177,10 @@ describe("useSettingsNavItems", () => {expect(findItemByPath(result.current, "/settings/org-members"),).toBeDefined();+ expect(+ findItemByPath(result.current, "/settings/usage-monitoring"),+ ).toBeDefined();+ expect(findItemByPath(result.current, "/settings/budgets")).toBeDefined();});it("should hide org routes when isPersonalOrg is true", async () => {@@ -202,6 +206,10 @@ describe("useSettingsNavItems", () => {expect(findItemByPath(result.current, "/settings/org-members"),).toBeUndefined();+ expect(+ findItemByPath(result.current, "/settings/usage-monitoring"),+ ).toBeUndefined();+ expect(findItemByPath(result.current, "/settings/budgets")).toBeUndefined();});it("should hide org routes when user role is member", async () => {@@ -227,6 +235,10 @@ describe("useSettingsNavItems", () => {expect(findItemByPath(result.current, "/settings/org-members"),).toBeUndefined();+ expect(+ findItemByPath(result.current, "/settings/usage-monitoring"),+ ).toBeUndefined();+ expect(findItemByPath(result.current, "/settings/budgets")).toBeUndefined();});it("should hide org routes when no organization is selected", async () => {@@ -253,6 +265,10 @@ describe("useSettingsNavItems", () => {expect(findItemByPath(result.current, "/settings/org-members"),).toBeUndefined();+ expect(+ findItemByPath(result.current, "/settings/usage-monitoring"),+ ).toBeUndefined();+ expect(findItemByPath(result.current, "/settings/budgets")).toBeUndefined();});it("should hide billing route when isTeamOrg is true", async () => {diff --git a/frontend/__tests__/routes/settings.test.tsx b/frontend/__tests__/routes/settings.test.tsxindex 337ca5d79f..a72c49eba3 100644--- a/frontend/__tests__/routes/settings.test.tsx+++ b/frontend/__tests__/routes/settings.test.tsx@@ -1193,6 +1193,49 @@ describe("clientLoader redirect behavior", () => {expect(result?.headers.get("Location")).toBe("/settings/mcp");});+ it("should redirect non-admins away from /settings/budgets", async () => {+ const config = {+ app_mode: "saas",+ feature_flags: {+ enable_billing: false,+ hide_llm_settings: false,+ enable_jira: false,+ enable_jira_dc: false,+ enable_linear: false,+ hide_users_page: false,+ hide_billing_page: false,+ hide_integrations_page: false,+ enable_onboarding: false,+ },+ };+ mockQueryClient.setQueryData(["web-client-config"], config);+ mockQueryClient.setQueryData(["organizations"], {+ items: [MOCK_TEAM_ORG_ACME],+ currentOrgId: MOCK_TEAM_ORG_ACME.id,+ });+ useSelectedOrganizationStore.setState({ organizationId: "2" });++ vi.spyOn(organizationService, "getMe").mockResolvedValue({+ org_id: "2",+ user_id: "99",+ email: "[email protected]",+ role: "member",+ llm_api_key: "**********",+ max_iterations: 20,+ llm_model: "gpt-4",+ llm_base_url: "https://api.openai.com",+ status: "active",+ });++ const result = await clientLoader(+ createMockRequest("/settings/budgets") as any,+ );++ expect(result).toBeDefined();+ expect(result?.status).toBe(302);+ expect(result?.headers.get("Location")).toBe("/settings");+ });+it("should not redirect when accessing a non-hidden page", async () => {const config = {app_mode: "saas",diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex 7e4e65dd4d..1c8b5c0c25 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -254,6 +254,7 @@"integrity": "sha512-H3mcG6ZDLTlYfaSNi0iOKkigqMFvkTKlGUYlD8GW7nNOYRrevuA46iTypPyv+06V3fEmvvazfntkBU34L0azAw==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@babel/code-frame": "^7.28.6","@babel/generator": "^7.28.6",@@ -793,6 +794,7 @@}],"license": "MIT",+ "peer": true,"engines": {"node": ">=18"},@@ -833,6 +835,7 @@}],"license": "MIT",+ "peer": true,"engines": {"node": ">=18"}@@ -2482,6 +2485,7 @@"resolved": "https://registry.npmjs.org/@heroui/system/-/system-2.4.26.tgz","integrity": "sha512-XqcsMmygWKcJYaviexO+FnZQBt2bd8z1vKIegRPsOmZytJXO/xJavbcwcuKP8A2Csk7fwYQANVx8qtN/r/wFOg==","license": "MIT",+ "peer": true,"dependencies": {"@heroui/react-utils": "2.1.14","@heroui/system-rsc": "2.3.22",@@ -2565,6 +2569,7 @@"resolved": "https://registry.npmjs.org/@heroui/theme/-/theme-2.4.26.tgz","integrity": "sha512-TYatChq7YyGDcPJytgOMqQwK72qWYb+vIa7mLmX3Cu9+JzFs2VSHu2QqzdhnOHoK0uJr8giDMy0gvJEDuu31vw==","license": "MIT",+ "peer": true,"dependencies": {"@heroui/shared-utils": "2.1.12","color": "^4.2.3",@@ -3346,6 +3351,7 @@"resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz","integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==","license": "Apache-2.0",+ "peer": true,"engines": {"node": ">=8.0.0"}@@ -4492,6 +4498,7 @@"resolved": "https://registry.npmjs.org/@react-router/serve/-/serve-7.17.0.tgz","integrity": "sha512-cjVz/HiZbkZe4urdImO6V+KFYDIGJk59DJXGnJ5XeDoltRi+buba0K6oTHIh0G0uoYJMm3gKqHKSiCN/a0dhJw==","license": "MIT",+ "peer": true,"dependencies": {"@mjackson/node-fetch-server": "^0.2.0","@react-router/express": "7.17.0",@@ -5909,6 +5916,7 @@"integrity": "sha512-8QqtOQT5ACVlmsvKOJNEaWmRPmcojMOzCz4Hs2BGG/toAp/K38LcsMRyLp349glq5AzJbCEeimEoxaX6v/fLrA==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@babel/core": "^7.21.3","@svgr/babel-preset": "8.1.0",@@ -6392,6 +6400,7 @@"integrity": "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@babel/code-frame": "^7.10.4","@babel/runtime": "^7.12.5",@@ -6587,6 +6596,7 @@"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz","integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==","license": "MIT",+ "peer": true,"dependencies": {"csstype": "^3.2.2"}@@ -6597,6 +6607,7 @@"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==","dev": true,"license": "MIT",+ "peer": true,"peerDependencies": {"@types/react": "^19.2.0"}@@ -6637,6 +6648,7 @@"integrity": "sha512-94EQTWZ40mzBc42ATNIBimBEDltSJ9RQHCC8vc/PDbxi4k8dVwUAv4o98dk50M1zB+JGFxp43FP7f8+FP8R6Sw==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@eslint-community/regexpp": "^4.10.0","@typescript-eslint/scope-manager": "7.18.0",@@ -6694,6 +6706,7 @@"integrity": "sha512-4Z+L8I2OqhZV8qA132M4wNL30ypZGYOQVBfMgxDH/K5UX0PNqTu1c6za9ST5r9+tavvHiTWmBnKzpCJ/GlVFtg==","dev": true,"license": "BSD-2-Clause",+ "peer": true,"dependencies": {"@typescript-eslint/scope-manager": "7.18.0","@typescript-eslint/types": "7.18.0",@@ -7079,6 +7092,7 @@"integrity": "sha512-lt3kovsyHwYe00wq4D1ti0Z974fWj4NLp6siqiyEufUpyFwK9Yhi7rBhac9JL5aA0zoMrJqc4vYPZRUnI7l7nw==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@bcoe/v8-coverage": "^1.0.2","@vitest/utils": "4.1.8",@@ -7274,6 +7288,7 @@"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==","dev": true,"license": "MIT",+ "peer": true,"bin": {"acorn": "bin/acorn"},@@ -7827,6 +7842,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"baseline-browser-mapping": "^2.9.0","caniuse-lite": "^1.0.30001759",@@ -8540,7 +8556,8 @@"version": "3.2.3","resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz","integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",- "license": "MIT"+ "license": "MIT",+ "peer": true},"node_modules/damerau-levenshtein": {"version": "1.0.8",@@ -9246,6 +9263,7 @@"deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@eslint-community/eslint-utils": "^4.2.0","@eslint-community/regexpp": "^4.6.1",@@ -9369,6 +9387,7 @@"integrity": "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==","dev": true,"license": "MIT",+ "peer": true,"bin": {"eslint-config-prettier": "bin/cli.js"},@@ -9448,6 +9467,7 @@"integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@rtsao/scc": "^1.1.0","array-includes": "^3.1.9",@@ -9538,6 +9558,7 @@"integrity": "sha512-scB3nz4WmG75pV8+3eRUQOHZlNSUhFNq37xnpgRkCCELU3XMvXAxLk1eqWWyE22Ki4Q01Fnsw9BA3cJHDPgn2Q==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"aria-query": "^5.3.2","array-includes": "^3.1.8",@@ -9632,6 +9653,7 @@"integrity": "sha512-Qteup0SqU15kdocexFNAJMvCJEfa2xUKNV4CC1xsVMrIIqEy3SQ/rqyxCWNzfrd3/ldy6HMlD2e0JDVpDg2qIA==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"array-includes": "^3.1.8","array.prototype.findlast": "^1.2.5",@@ -9665,6 +9687,7 @@"integrity": "sha512-QzliNJq4GinDBcD8gPB5v0wh6g8q3SUi6EFF0x8N/BL9PoVs0atuGc47ozMRyOWAKdwaZ5OnbOEa3WR+dSGKuQ==","dev": true,"license": "MIT",+ "peer": true,"engines": {"node": ">=10"},@@ -9932,6 +9955,7 @@"resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz","integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==","license": "MIT",+ "peer": true,"dependencies": {"accepts": "~1.3.8","array-flatten": "1.1.1",@@ -10259,6 +10283,7 @@"resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-12.38.0.tgz","integrity": "sha512-rFYkY/pigbcswl1XQSb7q424kSTQ8q6eAC+YUsSKooHQYuLdzdHjrt6uxUC+PRAO++q5IS7+TamgIw1AphxR+g==","license": "MIT",+ "peer": true,"dependencies": {"motion-dom": "^12.38.0","motion-utils": "^12.36.0",@@ -10929,6 +10954,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"@babel/runtime": "^7.29.2"},@@ -11696,6 +11722,7 @@"integrity": "sha512-mjzqwWRD9Y1J1KUi7W97Gja1bwOOM5Ug0EZ6UDK3xS7j7mndrkwozHtSblfomlzyB4NepioNt+B2sOSzczVgtQ==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@acemir/cssom": "^0.9.28","@asamuzakjp/dom-selector": "^6.7.6",@@ -13406,6 +13433,7 @@"resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.55.1.tgz","integrity": "sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A==","license": "MIT",+ "peer": true,"dependencies": {"dompurify": "3.2.7","marked": "14.0.0"@@ -13500,6 +13528,7 @@"dev": true,"hasInstallScript": true,"license": "MIT",+ "peer": true,"dependencies": {"@inquirer/confirm": "^5.0.0","@mswjs/interceptors": "^0.40.0",@@ -14296,6 +14325,7 @@"integrity": "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg==","dev": true,"license": "MIT",+ "peer": true,"bin": {"prettier": "bin/prettier.cjs"},@@ -14528,6 +14558,7 @@"resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz","integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==","license": "MIT",+ "peer": true,"engines": {"node": ">=0.10.0"}@@ -14652,6 +14683,7 @@"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz","integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==","license": "MIT",+ "peer": true,"dependencies": {"scheduler": "^0.27.0"},@@ -14766,6 +14798,7 @@"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.17.0.tgz","integrity": "sha512-FDELK7rTMlCHO5+reyXsPlmfr7N1F91lPHsWYfMEGQm/KQ+F4JFM8jGoeQDmDvdTs93Fw9aSilH+uKRb4/jXvQ==","license": "MIT",+ "peer": true,"dependencies": {"cookie": "^1.0.1","set-cookie-parser": "^2.6.0"@@ -15177,6 +15210,7 @@"version": "4.59.0","resolved": "https://registry.npmjs.org/rollup/-/rollup-4.59.0.tgz","integrity": "sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg==",+ "peer": true,"dependencies": {"@types/estree": "1.0.8"},@@ -16148,6 +16182,7 @@"resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.4.0.tgz","integrity": "sha512-uSaO4gnW+b3Y2aWoWfFpX62vn2sR3skfhbjsEnaBI81WD1wBLlHZe5sWf0AqjksNdYTbGBEd0UasQMT3SNV15g==","license": "MIT",+ "peer": true,"funding": {"type": "github","url": "https://github.com/sponsors/dcastil"@@ -16276,6 +16311,7 @@"version": "4.0.4","resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz","integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",+ "peer": true,"engines": {"node": ">=12"},@@ -16579,6 +16615,7 @@"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==","devOptional": true,"license": "Apache-2.0",+ "peer": true,"bin": {"tsc": "bin/tsc","tsserver": "bin/tsserver"@@ -16885,6 +16922,7 @@"version": "7.3.2","resolved": "https://registry.npmjs.org/vite/-/vite-7.3.2.tgz","integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==",+ "peer": true,"dependencies": {"esbuild": "^0.27.0","fdir": "^6.5.0",@@ -17049,6 +17087,7 @@"version": "4.0.4","resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz","integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",+ "peer": true,"engines": {"node": ">=12"},@@ -17062,6 +17101,7 @@"integrity": "sha512-flY6ScbCIt9HThs+C5HS7jvGOB560DJtk/Z15IQROTA6zEy49Nh8T/dofWTQL+n3vswqn87sbJNiuqw1SDp5Ig==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@vitest/expect": "4.1.8","@vitest/mocker": "4.1.8",diff --git a/frontend/src/api/option-service/option.types.ts b/frontend/src/api/option-service/option.types.tsindex 07819a07e8..9ddf3f2880 100644--- a/frontend/src/api/option-service/option.types.ts+++ b/frontend/src/api/option-service/option.types.ts@@ -77,6 +77,7 @@ export interface WebClientConfig {gitlab_enabled?: boolean;provider_default_hosts?: Partial<Record<Provider, string>>;slack_enabled?: boolean;+ email_enabled?: boolean;acp_providers?: ACPProviderConfig[];/** Jira DC host when DC OAuth is configured; used to pre-fill + lock the* configure form's host field. Null/absent in email-match mode. */diff --git a/frontend/src/api/organization-service/organization-service.api.ts b/frontend/src/api/organization-service/organization-service.api.tsindex 16b980dcef..006c9cb064 100644--- a/frontend/src/api/organization-service/organization-service.api.ts+++ b/frontend/src/api/organization-service/organization-service.api.ts@@ -293,18 +293,131 @@ export const organizationService = {getUsageStats: async ({orgId,- days = 7,+ days,+ timeWindow,}: {orgId: string;days?: number;+ timeWindow?: string;}) => {+ let resolvedDays: number | undefined;+ if (typeof days === "number") {+ resolvedDays = days;+ } else if (!timeWindow) {+ resolvedDays = 7;+ }+ const params: Record<string, number | string> = {};+ if (typeof resolvedDays === "number") {+ params.days = resolvedDays;+ }+ if (timeWindow) {+ params.time_window = timeWindow;+ }const { data } = await openHands.get<OrgUsageStats>(`/api/organizations/${orgId}/conversations/usage-stats`,- { params: { days } },+ { params },+ );+ return data;+ },++ getUserUsageStats: async ({+ orgId,+ limit,+ offset,+ }: {+ orgId: string;+ limit?: number;+ offset?: number;+ }) => {+ const params: Record<string, number> = {};+ if (typeof limit === "number") {+ params.limit = limit;+ }+ if (typeof offset === "number") {+ params.offset = offset;+ }+ const { data } = await openHands.get<OrgUserUsageStats>(+ `/api/organizations/${orgId}/conversations/user-usage`,+ { params },+ );+ return data;+ },++ getBudgetSettings: async ({+ orgId,+ usersPage,+ usersPerPage,+ usersSearch,+ usersStatus,+ }: {+ orgId: string;+ usersPage?: number;+ usersPerPage?: number;+ usersSearch?: string;+ usersStatus?: string;+ }) => {+ const params: Record<string, number | string> = {};+ if (typeof usersPage === "number") {+ params.users_page = usersPage;+ }+ if (typeof usersPerPage === "number") {+ params.users_per_page = usersPerPage;+ }+ if (usersSearch) {+ params.users_search = usersSearch;+ }+ if (usersStatus) {+ params.users_status = usersStatus;+ }+ const { data } = await openHands.get<OrgBudgetSettings>(+ `/api/organizations/${orgId}/budgets`,+ { params },+ );+ return data;+ },++ updateBudgetSettings: async ({+ orgId,+ payload,+ }: {+ orgId: string;+ payload: OrgBudgetSettingsUpdate;+ }) => {+ const { data } = await openHands.patch<OrgBudgetSettings>(+ `/api/organizations/${orgId}/budgets`,+ payload,+ );+ return data;+ },++ upsertBudgetOverride: async ({+ orgId,+ userId,+ payload,+ }: {+ orgId: string;+ userId: string;+ payload: OrgBudgetUserOverrideUpdate;+ }) => {+ const { data } = await openHands.put<OrgBudgetUser>(+ `/api/organizations/${orgId}/budgets/overrides/${userId}`,+ payload,);return data;},+ deleteBudgetOverride: async ({+ orgId,+ userId,+ }: {+ orgId: string;+ userId: string;+ }) => {+ await openHands.delete(+ `/api/organizations/${orgId}/budgets/overrides/${userId}`,+ );+ },+getConversations: async ({orgId,page = 1,@@ -397,6 +510,7 @@ export const organizationService = {params.set("sort_order", sortOrder);if (search) params.set("search", search);if (executionStatus) params.set("execution_status", executionStatus);+if (sandboxStatus) params.set("sandbox_status", sandboxStatus);if (timeWindow) params.set("time_window", timeWindow);return `/api/organizations/${orgId}/conversations/export?${params.toString()}`;@@ -431,6 +545,41 @@ interface TeamUsageData {percentage: number;}+interface OrgUserUsageRow {+ user_id: string;+ user_email: string | null;+ user_name: string | null;+ conversation_count: number;+ first_conversation_at: string | null;+ last_conversation_at: string | null;+ first_login_at: string | null;+ last_login_at: string | null;+ spend_mtd: number;+ spend_ytd: number;+ spend_lifetime: number;+ budget_monthly_limit: number | null;+ budget_is_disabled: boolean;+ prs_merged: number | null;+}++interface OrgUserUsageStats {+ items: OrgUserUsageRow[];+ has_more: boolean;+}++interface ModelUsageData {+ model_name: string;+ conversation_count: number;+ total_tokens: number;+ total_cost: number;+}++interface AgentUsageData {+ agent_name: string;+ conversation_count: number;+ total_cost: number;+}+interface OrgUsageStats {active_users: number;agent_runs: number;@@ -438,6 +587,65 @@ interface OrgUsageStats {estimated_spend: number;daily_usage: DailyUsageData[];team_usage: TeamUsageData[];+ model_usage: ModelUsageData[];+ agent_usage: AgentUsageData[];+}++interface OrgBudgetThreshold {+ id: number;+ percentage: number;+ email_enabled: boolean;+ slack_enabled: boolean;+}++interface OrgBudgetUser {+ user_id: string;+ user_email: string | null;+ user_name: string | null;+ current_spend: number;+ monthly_limit: number | null;+ effective_monthly_limit: number | null;+ is_disabled: boolean;+ is_override: boolean;+}++interface OrgBudgetSettings {+ enabled: boolean;+ monthly_limit: number | null;+ reset_day: number;+ slack_channel: string | null;+ slack_team_id: string | null;+ default_user_monthly_limit: number | null;+ cycle_start_at: string;+ cycle_end_at: string;+ current_spend: number;+ current_spend_percentage: number;+ thresholds: OrgBudgetThreshold[];+ users: OrgBudgetUser[];+ users_total: number;+ users_page: number;+ users_per_page: number;+}++interface OrgBudgetSettingsUpdate {+ enabled?: boolean | null;+ monthly_limit?: number | null;+ reset_day?: number | null;+ default_user_monthly_limit?: number | null;+ slack_channel?: string | null;+ slack_team_id?: string | null;+ thresholds?:+ | {+ percentage: number;+ email_enabled: boolean;+ slack_enabled: boolean;+ }[]+ | null;+}++interface OrgBudgetUserOverrideUpdate {+ monthly_limit?: number | null;+ is_disabled: boolean;}interface OrgConversationResponse {@@ -455,7 +663,10 @@ interface OrgConversationResponse {execution_status: string | null;selected_repository: string | null;selected_branch: string | null;+ git_provider: string | null;trigger: string | null;+ pr_number: number[];+ pr_merged: boolean | null;tags: Record<string, string>;accumulated_cost: number;prompt_tokens: number;diff --git a/frontend/src/components/features/admin-dashboard/admin-dashboard.tsx b/frontend/src/components/features/admin-dashboard/admin-dashboard.tsxindex a49ad1244c..1b62580a27 100644--- a/frontend/src/components/features/admin-dashboard/admin-dashboard.tsx+++ b/frontend/src/components/features/admin-dashboard/admin-dashboard.tsx@@ -1,1155 +1,18 @@/* eslint-disable i18next/no-literal-string */-import React, { useMemo, useState } from "react";-import { useSearchParams } from "react-router";-import toast from "react-hot-toast";+import React from "react";import { useSelectedOrganizationId } from "#/context/use-selected-organization";-import { useOrganizations } from "#/hooks/query/use-organizations";-import { useOrgConversationStats } from "#/hooks/query/use-org-conversation-stats";-import { useOrgConversations } from "#/hooks/query/use-org-conversations";-import { useOrgUsageStats } from "#/hooks/query/use-org-usage-stats";-import { useStopConversation } from "#/hooks/mutation/use-stop-conversation";-import { ConfirmationModal } from "#/components/shared/modals/confirmation-modal";-import { organizationService } from "#/api/organization-service/organization-service.api";--// Conversation statuses from which the user can no longer stop a running-// agent. Mirrors the terminal-status set used by OrgConversationService.-const TERMINAL_EXECUTION_STATUSES = new Set([- "finished",- "error",- "stuck",- "deleting",-]);--const isStoppable = (status: string | null | undefined) =>- !TERMINAL_EXECUTION_STATUSES.has((status ?? "").toLowerCase());--// Icons as inline SVGs for simplicity-function SearchIcon() {- return (- <svg- width="16"- height="16"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- >- <circle cx="11" cy="11" r="8" />- <path d="m21 21-4.35-4.35" />- </svg>- );-}--function ExportIcon() {- return (- <svg- width="14"- height="14"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- >- <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />- <polyline points="7,10 12,15 17,10" />- <line x1="12" y1="15" x2="12" y2="3" />- </svg>- );-}--function CopyIcon() {- return (- <svg- width="14"- height="14"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- >- <rect x="9" y="9" width="13" height="13" rx="2" ry="2" />- <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />- </svg>- );-}--function ExternalLinkIcon() {- return (- <svg- width="14"- height="14"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- >- <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />- <polyline points="15,3 21,3 21,9" />- <line x1="10" y1="14" x2="21" y2="3" />- </svg>- );-}--function StopIcon() {- return (- <svg- width="14"- height="14"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- >- <circle cx="12" cy="12" r="10" />- <rect x="9" y="9" width="6" height="6" />- </svg>- );-}--function ChevronLeftIcon() {- return (- <svg- width="16"- height="16"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- >- <polyline points="15,18 9,12 15,6" />- </svg>- );-}--function ChevronRightIcon() {- return (- <svg- width="16"- height="16"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- >- <polyline points="9,18 15,12 9,6" />- </svg>- );-}--function ActivityIcon() {- return (- <svg- width="20"- height="20"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- >- <polyline points="22,12 18,12 15,21 9,3 6,12 2,12" />- </svg>- );-}--function ServerIcon() {- return (- <svg- width="20"- height="20"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- >- <rect x="2" y="2" width="20" height="8" rx="2" ry="2" />- <rect x="2" y="14" width="20" height="8" rx="2" ry="2" />- <line x1="6" y1="6" x2="6.01" y2="6" />- <line x1="6" y1="18" x2="6.01" y2="18" />- </svg>- );-}--function CheckCircleIcon() {- return (- <svg- width="20"- height="20"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- >- <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />- <polyline points="22,4 12,14.01 9,11.01" />- </svg>- );-}--function DollarIcon() {- return (- <svg- width="20"- height="20"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- >- <line x1="12" y1="1" x2="12" y2="23" />- <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" />- </svg>- );-}--// Status badge component-function StatusBadge({ status }: { status: string | null }) {- const getStatusStyle = () => {- switch (status) {- case "running":- return "bg-blue-500/10 text-blue-400 border-blue-500/30";- case "idle":- case "paused":- return "bg-yellow-500/10 text-yellow-400 border-yellow-500/30";- case "finished":- return "bg-green-500/10 text-green-400 border-green-500/30";- case "error":- case "stuck":- return "bg-red-500/10 text-red-400 border-red-500/30";- default:- return "bg-gray-500/10 text-gray-400 border-gray-500/30";- }- };-- return (- <span- className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border ${getStatusStyle()}`}- >- {status || "unknown"}- </span>- );-}--// Runtime status badge-function RuntimeBadge({ status }: { status: string | null }) {- const getStatusStyle = () => {- switch (status) {- case "RUNNING":- return "bg-blue-500/10 text-blue-400 border-blue-500/30";- case "STARTING":- return "bg-yellow-500/10 text-yellow-400 border-yellow-500/30";- case "ERROR":- case "MISSING":- return "bg-red-500/10 text-red-400 border-red-500/30";- case "PAUSED":- return "bg-gray-500/10 text-gray-400 border-gray-500/30";- default:- return "bg-gray-500/10 text-gray-400 border-gray-500/30";- }- };-- return (- <span- className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border ${getStatusStyle()}`}- >- {status || "N/A"}- </span>- );-}--// KPI Card component-function KPICard({- label,- value,- subtext,- icon,-}: {- label: string;- value: string | number;- subtext?: string;- icon: React.ReactNode;-}) {- return (- <div className="bg-[#1E1E1E] border border-[#262626] rounded-lg p-4">- <div className="flex items-center justify-between mb-3">- <span className="text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">- {label}- </span>- <span className="text-[#8C8C8C]">{icon}</span>- </div>- <div className="text-white text-2xl font-bold mb-1">{value}</div>- {subtext && <div className="text-[#8C8C8C] text-xs">{subtext}</div>}- </div>- );-}--// Format tokens-const formatTokens = (tokens: number) => {- if (tokens >= 1000000) return `${(tokens / 1000000).toFixed(1)}M`;- if (tokens >= 1000) return `${(tokens / 1000).toFixed(1)}k`;- return tokens.toString();-};--// Format cost-const formatCost = (cost: number) => {- if (cost >= 1000) return `$${(cost / 1000).toFixed(1)}k`;- return `$${cost.toFixed(2)}`;-};--// Format date-const formatDate = (dateStr: string) => {- const date = new Date(dateStr);- return date.toLocaleDateString("en-US", {- month: "short",- day: "numeric",- year: "numeric",- hour: "numeric",- minute: "2-digit",- });-};--// Copy to clipboard-const copyToClipboard = (text: string) => {- navigator.clipboard.writeText(text);-};--// Get number of days from time window string-const getDaysFromTimeWindow = (timeWindow: string): number => {- if (timeWindow === "90d") return 90;- if (timeWindow === "30d") return 30;- return 7;-};+import { UsageDashboard } from "./usage-dashboard";export function AdminDashboard() {const { organizationId } = useSelectedOrganizationId();- const { data: orgData } = useOrganizations();- const [activeTab, setActiveTab] = useState<"conversations" | "usage">(- "conversations",- );- const [searchParams, setSearchParams] = useSearchParams();- // Use the currently selected org (from the org switcher) rather than- // deriving from the org list — avoids mismatches when the user belongs- // to multiple orgs and has different roles in each.- const orgId = organizationId ?? undefined;- const currentOrg = orgData?.organizations?.find(- (org) => org.id === organizationId,- );-- // Filter state from URL params- const page = parseInt(searchParams.get("page") || "1", 10);- const perPage = parseInt(searchParams.get("per_page") || "20", 10);- const search = searchParams.get("search") || "";- const sortBy = searchParams.get("sort_by") || "updated_at";- const sortOrder = searchParams.get("sort_order") || "desc";- const executionStatus = searchParams.get("execution_status") || "";- const sandboxStatus = searchParams.get("sandbox_status") || "";- const timeWindow = searchParams.get("time_window") || "";-- // Fetch stats- const { data: stats } = useOrgConversationStats();-- // Fetch usage stats for Usage tab- const { data: usageStats } = useOrgUsageStats({- days: getDaysFromTimeWindow(timeWindow),- });-- // Fetch conversations- const { data: conversationsData, isLoading: conversationsLoading } =- useOrgConversations({- page,- perPage,- search,- sortBy,- sortOrder,- executionStatus,- sandboxStatus,- timeWindow,- });-- const [stoppingIds, setStoppingIds] = useState<Set<string>>(new Set());- const [pendingStop, setPendingStop] = useState<{- id: string;- title: string | null;- } | null>(null);- const stopConversation = useStopConversation();-- const handleStop = (conversation: { id: string; title: string | null }) => {- setPendingStop(conversation);- };-- const confirmStop = () => {- if (!pendingStop) return;- const conversation = pendingStop;- setPendingStop(null);- setStoppingIds((prev) => {- const next = new Set(prev);- next.add(conversation.id);- return next;- });- const toastId = toast.loading("Stopping conversation…");- stopConversation.mutate(- { conversationId: conversation.id },- {- onSettled: () => {- setStoppingIds((prev) => {- if (!prev.has(conversation.id)) return prev;- const next = new Set(prev);- next.delete(conversation.id);- return next;- });- toast.dismiss(toastId);- },- },- );- };-- const cancelStop = () => {- setPendingStop(null);- };-- const updateFilter = (key: string, value: string | string[] | null) => {- const newParams = new URLSearchParams(searchParams);- if (value === null || value === "") {- newParams.delete(key);- } else if (Array.isArray(value)) {- newParams.delete(key);- value.forEach((v) => newParams.append(key, v));- } else {- newParams.set(key, value);- }- newParams.set("page", "1"); // Reset to first page on filter change- setSearchParams(newParams);- };-- const handlePageChange = (newPage: number) => {- const newParams = new URLSearchParams(searchParams);- newParams.set("page", String(newPage));- setSearchParams(newParams);- };-- const totalPages = conversationsData?.total_pages || 1;- const totalItems = conversationsData?.total_items || 0;- const pendingStopLabel = pendingStop?.title?.trim();- const stopConfirmationText = pendingStopLabel- ? `Stop "${pendingStopLabel}"? This will cancel any in-progress agent run.`- : "Stop this conversation? This will cancel any in-progress agent run.";-- const exportUrl = useMemo(() => {- if (!orgId) return "#";- return organizationService.exportConversationsUrl({- orgId,- search: search || undefined,- sortBy,- sortOrder,- executionStatus: executionStatus.length ? executionStatus : undefined,- sandboxStatus: sandboxStatus.length ? sandboxStatus : undefined,- timeWindow: timeWindow || undefined,- });- }, [- orgId,- search,- sortBy,- sortOrder,- executionStatus,- sandboxStatus,- timeWindow,- ]);-- if (!orgId) {+ if (!organizationId) {return (<div className="p-8 text-center text-[#8C8C8C]">- Please select an organization to view usage & monitoring.+ Please select an organization to view Usage & Monitoring.</div>);}- return (- <div className="min-h-screen bg-[#0B0B0B] text-white flex flex-col">- {/* Top Header with Tabs */}- <header className="border-b border-white/10 px-6 py-4">- <div className="flex items-center justify-between mb-4">- <div>- <h1 className="text-white font-bold text-lg">Admin dashboard</h1>- <p className="text-[#888888] text-sm mt-1">- {currentOrg?.name || "your organization"}- </p>- </div>- </div>-- {/* Tabs */}- <div className="flex gap-1 border-b border-white/10 -mb-4">- <button- type="button"- onClick={() => setActiveTab("usage")}- className={`px-4 py-2 text-sm font-medium transition-colors border-b-2 ${- activeTab === "usage"- ? "border-white text-white"- : "border-transparent text-[#888888] hover:text-white"- }`}- >- Usage- </button>- <button- type="button"- onClick={() => setActiveTab("conversations")}- className={`px-4 py-2 text-sm font-medium transition-colors border-b-2 ${- activeTab === "conversations"- ? "border-white text-white"- : "border-transparent text-[#888888] hover:text-white"- }`}- >- Conversations- </button>- </div>- </header>-- {/* Main Content */}- <main className="flex-1 overflow-auto">- {activeTab === "usage" ? (- <>- {/* Usage Page Header */}- <div className="p-8 border-b border-white/10">- <div className="flex items-start justify-between mb-2">- <div>- <p className="text-[#888888] text-sm">- At-a-glance OpenHands usage for{" "}- {currentOrg?.name || "your organization"}.- </p>- </div>- <button- type="button"- className="flex items-center gap-2 px-4 py-2 rounded-full border border-white/20 text-sm text-[#888888] hover:text-white hover:border-white/40 transition-colors"- >- Last 7 days- <svg- width="14"- height="14"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- >- <path d="M6 9l6 6 6-6" />- </svg>- </button>- </div>- </div>-- {/* Usage Content */}- <div className="p-8">- {/* Top Metrics Row - 3 cards */}- <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">- {/* Active Users */}- <div className="bg-[#1A1A1A] p-6 rounded-xl border border-white/5">- <div className="flex items-center justify-between mb-4">- <span className="text-[#888888] text-xs font-medium uppercase tracking-wide">- Active Users- </span>- <div className="w-8 h-8 rounded-lg bg-white/10 flex items-center justify-center">- <svg- width="16"- height="16"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- >- <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />- <circle cx="9" cy="7" r="4" />- <path d="M23 21v-2a4 4 0 0 0-3-3.87" />- <path d="M16 3.13a4 4 0 0 1 0 7.75" />- </svg>- </div>- </div>- <div className="text-white text-3xl font-bold tracking-tight mb-2">- {usageStats?.active_users ?? 0}- </div>- <div className="text-[#888888] text-sm">- users in last 7 days- </div>- </div>-- {/* Agent Runs */}- <div className="bg-[#1A1A1A] p-6 rounded-xl border border-white/5">- <div className="flex items-center justify-between mb-4">- <span className="text-[#888888] text-xs font-medium uppercase tracking-wide">- Agent Runs- </span>- <div className="w-8 h-8 rounded-lg bg-white/10 flex items-center justify-center">- <svg- width="16"- height="16"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- >- <polyline points="22,12 18,12 15,21 9,3 6,12 2,12" />- </svg>- </div>- </div>- <div className="text-white text-3xl font-bold tracking-tight mb-2">- {usageStats?.agent_runs ?? 0}- </div>- <div className="text-[#888888] text-sm">- {(() => {- const days = getDaysFromTimeWindow(timeWindow);- if (usageStats?.agent_runs && usageStats.agent_runs > 0) {- return `${Math.round(usageStats.agent_runs / days)} daily average`;- }- return `No runs in ${days} days`;- })()}- </div>- </div>-- {/* Token Usage */}- <div className="bg-[#1A1A1A] p-6 rounded-xl border border-white/5">- <div className="flex items-center justify-between mb-4">- <span className="text-[#888888] text-xs font-medium uppercase tracking-wide">- Token Usage- </span>- <div className="w-8 h-8 rounded-lg bg-white/10 flex items-center justify-center">- <svg- width="16"- height="16"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- >- <circle cx="12" cy="12" r="10" />- <path d="M12 6v6l4 2" />- </svg>- </div>- </div>- <div className="text-white text-3xl font-bold tracking-tight mb-2">- {formatTokens(usageStats?.total_tokens ?? 0)}- </div>- <div className="text-[#888888] text-sm">- ${(usageStats?.estimated_spend ?? 0).toFixed(2)} estimated- spend- </div>- </div>- </div>-- {/* Bottom Row - Chart and Team Usage */}- <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">- {/* Daily Usage Chart */}- <div className="lg:col-span-2 bg-[#1A1A1A] p-6 rounded-xl border border-white/5">- <div className="mb-6">- <h2 className="text-white font-medium text-lg">- Daily usage- </h2>- <p className="text-[#888888] text-sm">- Tokens and conversations by day- </p>- </div>-- {/* Simple Bar Chart */}- <div className="h-48 flex items-end justify-between gap-4 px-2">- {(usageStats?.daily_usage ?? []).map((day) => {- // Find max tokens for scaling- const maxTokens = Math.max(- ...(usageStats?.daily_usage?.map((d) => d.tokens) ?? [- 1,- ]),- 1,- );- const tokenHeight =- day.tokens > 0 ? (day.tokens / maxTokens) * 100 : 5;- const convoHeight =- day.conversations > 0- ? Math.min(- (day.conversations /- Math.max(- ...(usageStats?.daily_usage?.map(- (d) => d.conversations,- ) ?? [1]),- 1,- )) *- 100,- 80,- )- : 5;-- // Get day name from date- const date = new Date(day.date);- const dayName = date.toLocaleDateString("en-US", {- weekday: "short",- });-- return (- <div- key={day.date}- className="flex-1 flex flex-col items-center gap-2"- >- <div className="w-full flex items-end justify-center gap-1 h-36">- <div- className="w-4 bg-white rounded-sm transition-all"- style={{ height: `${tokenHeight}%` }}- title={`${day.tokens.toLocaleString()} tokens`}- />- <div- className="w-4 bg-zinc-600 rounded-sm transition-all"- style={{ height: `${convoHeight}%` }}- title={`${day.conversations} conversations`}- />- </div>- <span className="text-[#888888] text-xs">- {dayName}- </span>- </div>- );- })}- </div>-- {/* Legend */}- <div className="flex items-center gap-6 mt-6 pt-4 border-t border-white/10">- <div className="flex items-center gap-2">- <div className="w-3 h-3 rounded-sm bg-white" />- <span className="text-[#888888] text-sm">Tokens</span>- </div>- <div className="flex items-center gap-2">- <div className="w-3 h-3 rounded-sm bg-zinc-600" />- <span className="text-[#888888] text-sm">- Conversations- </span>- </div>- </div>- </div>-- {/* Usage by Team (User) */}- <div className="bg-[#1A1A1A] p-6 rounded-xl border border-white/5">- <div className="mb-6">- <h2 className="text-white font-medium text-lg">- Usage by user- </h2>- <p className="text-[#888888] text-sm">- Share of total runs- </p>- </div>-- <div className="space-y-5">- {(usageStats?.team_usage ?? []).slice(0, 6).map((user) => (- <div key={user.user_id}>- <div className="flex items-center justify-between mb-2">- <span- className="text-white text-sm truncate max-w-[120px]"- title={- user.user_email || user.user_name || user.user_id- }- >- {user.user_name || user.user_email || "Unknown"}- </span>- <span className="text-[#888888] text-sm">- {user.percentage}%- </span>- </div>- <div className="w-full h-1.5 bg-zinc-800 rounded-full overflow-hidden">- <div- className="h-full bg-white rounded-full transition-all"- style={{ width: `${user.percentage}%` }}- />- </div>- </div>- ))}- {(!usageStats?.team_usage ||- usageStats.team_usage.length === 0) && (- <div className="text-[#888888] text-sm text-center py-4">- No usage data available- </div>- )}- </div>- </div>- </div>- </div>- </>- ) : (- <>- {/* KPI Cards */}- <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6 px-8 pt-6">- <KPICard- label="Active Conversations"- value={stats?.active_conversations ?? "-"}- subtext="In-flight agent work"- icon={<ActivityIcon />}- />- <KPICard- label="Running Runtimes"- value={stats?.running_runtimes ?? "-"}- subtext="Connected execution cells"- icon={<ServerIcon />}- />- <KPICard- label="Completed (24H)"- value={stats?.completed_24h ?? "-"}- subtext="Finished in last day"- icon={<CheckCircleIcon />}- />- <KPICard- label="Estimated Spend"- value={formatCost(stats?.total_cost ?? 0)}- subtext={`~${formatTokens(stats?.total_tokens ?? 0)} tokens in dataset`}- icon={<DollarIcon />}- />- </div>-- {/* Filter Bar */}-- <div className="bg-[#161616] border border-[#262626] rounded-lg p-4 mb-4">- <div className="flex items-center justify-between mb-4">- <span className="text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">- Filters- </span>- <a- href={exportUrl}- className="flex items-center gap-2 px-3 py-1.5 bg-[#1E1E1E] border border-[#262626] rounded text-sm text-[#8C8C8C] hover:text-white hover:border-[#404040] transition-colors"- >- <ExportIcon />- Export CSV- </a>- </div>-- <div className="flex flex-wrap gap-3">- {/* Search */}- <div className="relative flex-1 min-w-[200px]">- <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-[#8C8C8C]">- <SearchIcon />- </div>- <input- type="text"- placeholder="Name, creator, email..."- value={search}- onChange={(e) => updateFilter("search", e.target.value)}- className="w-full pl-10 pr-4 py-2 bg-[#0D0D0D] border border-[#262626] rounded text-white text-sm placeholder-[#6B6B6B] focus:outline-none focus:border-[#404040]"- />- </div>-- {/* Sort By */}- <select- value={sortBy}- onChange={(e) => updateFilter("sort_by", e.target.value)}- className="px-3 py-2 bg-[#0D0D0D] border border-[#262626] rounded text-sm text-white focus:outline-none focus:border-[#404040] appearance-none cursor-pointer"- >- <option value="updated_at">Last updated</option>- <option value="created_at">Created</option>- <option value="title">Title</option>- <option value="llm_model">Model</option>- <option value="accumulated_cost">Cost</option>- </select>-- {/* Order */}- <select- value={sortOrder}- onChange={(e) => updateFilter("sort_order", e.target.value)}- className="px-3 py-2 bg-[#0D0D0D] border border-[#262626] rounded text-sm text-white focus:outline-none focus:border-[#404040] appearance-none cursor-pointer"- >- <option value="desc">Descending</option>- <option value="asc">Ascending</option>- </select>-- {/* Conversation Status */}- <select- value={executionStatus}- onChange={(e) =>- updateFilter("execution_status", e.target.value || null)- }- className="px-3 py-2 bg-[#0D0D0D] border border-[#262626] rounded text-sm text-white focus:outline-none focus:border-[#404040] appearance-none cursor-pointer"- >- <option value="">Conversation status: All</option>- <option value="running">Running</option>- <option value="idle">Idle</option>- <option value="paused">Paused</option>- <option value="finished">Finished</option>- <option value="error">Error</option>- <option value="stuck">Stuck</option>- </select>-- {/* Runtime Status */}- <select- value={sandboxStatus}- onChange={(e) =>- updateFilter("sandbox_status", e.target.value || null)- }- className="px-3 py-2 bg-[#0D0D0D] border border-[#262626] rounded text-sm text-white focus:outline-none focus:border-[#404040] appearance-none cursor-pointer"- >- <option value="">Runtime status: All</option>- <option value="RUNNING">Running</option>- <option value="STARTING">Starting</option>- <option value="PAUSED">Paused</option>- <option value="ERROR">Error</option>- <option value="MISSING">Missing</option>- </select>-- {/* Time Window */}- <select- value={timeWindow}- onChange={(e) =>- updateFilter("time_window", e.target.value || null)- }- className="px-3 py-2 bg-[#0D0D0D] border border-[#262626] rounded text-sm text-white focus:outline-none focus:border-[#404040] appearance-none cursor-pointer"- >- <option value="">All time</option>- <option value="7d">Last 7 days</option>- <option value="30d">Last 30 days</option>- <option value="90d">Last 90 days</option>- </select>- </div>- </div>-- {/* Table */}- <div className="bg-[#161616] border border-[#262626] rounded-lg overflow-hidden">- <div className="overflow-x-auto">- <table className="w-full">- <thead>- <tr className="border-b border-[#262626]">- <th className="px-4 py-3 text-left text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">- Conversation- </th>- <th className="px-4 py-3 text-left text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">- Model- </th>- <th className="px-4 py-3 text-left text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">- Created by- </th>- <th className="px-4 py-3 text-left text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">- Status- </th>- <th className="px-4 py-3 text-left text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">- Runtime- </th>- <th className="px-4 py-3 text-left text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">- Runtime URL / GUID- </th>- <th className="px-4 py-3 text-left text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">- Created / Updated- </th>- <th className="px-4 py-3 text-left text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">- Tokens / Cost- </th>- <th className="px-4 py-3 text-left text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">- Actions- </th>- </tr>- </thead>- <tbody>- {conversationsLoading && (- <tr>- <td- colSpan={9}- className="px-4 py-8 text-center text-[#8C8C8C]"- >- Loading...- </td>- </tr>- )}- {!conversationsLoading &&- conversationsData?.items.length === 0 && (- <tr>- <td- colSpan={9}- className="px-4 py-8 text-center text-[#8C8C8C]"- >- No conversations found- </td>- </tr>- )}- {!conversationsLoading &&- conversationsData?.items.map((conversation, index) => (- <tr- key={conversation.id}- className={`border-b border-[#262626] hover:bg-[#1E1E1E]/50 transition-colors ${- index % 2 === 0 ? "" : "bg-[#0D0D0D]/30"- }`}- >- <td className="px-4 py-3">- <div className="font-medium text-white text-sm">- {conversation.title || "Untitled"}- </div>- </td>- <td className="px-4 py-3">- <span className="font-mono text-xs text-[#8C8C8C]">- {conversation.llm_model || "N/A"}- </span>- </td>- <td className="px-4 py-3">- <div className="text-sm">- <div className="text-white">- {conversation.user_email?.split("@")[0] ||- "Unknown"}- </div>- <div className="text-[#8C8C8C] text-xs">- {conversation.user_email || ""}- </div>- </div>- </td>- <td className="px-4 py-3">- <StatusBadge- status={conversation.execution_status}- />- </td>- <td className="px-4 py-3">- <RuntimeBadge- status={conversation.sandbox_status}- />- </td>- <td className="px-4 py-3">- {conversation.sandbox_id ? (- <div className="flex items-center gap-2">- <span className="font-mono text-xs text-[#8C8C8C] truncate max-w-[120px]">- {conversation.sandbox_id.slice(0, 12)}...- </span>- <button- type="button"- onClick={() =>- copyToClipboard(conversation.sandbox_id!)- }- className="text-[#6B6B6B] hover:text-white transition-colors"- title="Copy GUID"- >- <CopyIcon />- </button>- {conversation.runtime_url && (- <a- href={conversation.runtime_url}- target="_blank"- rel="noopener noreferrer"- className="text-[#6B6B6B] hover:text-white transition-colors"- title="Open in new tab"- >- <ExternalLinkIcon />- </a>- )}- </div>- ) : (- <span className="text-[#6B6B6B] text-xs">- N/A- </span>- )}- </td>- <td className="px-4 py-3">- <div className="text-xs">- <div className="text-[#8C8C8C] uppercase mb-0.5">- Created- </div>- <div className="text-white mb-1">- {formatDate(conversation.created_at)}- </div>- <div className="text-[#8C8C8C] uppercase mb-0.5">- Updated- </div>- <div className="text-white">- {formatDate(conversation.updated_at)}- </div>- </div>- </td>- <td className="px-4 py-3">- <div className="text-xs text-right">- <div className="text-white font-mono">- {formatTokens(conversation.total_tokens)}- </div>- <div className="text-white font-medium">- ${conversation.accumulated_cost.toFixed(2)}- </div>- </div>- </td>- <td className="px-4 py-3">- <div className="flex flex-col gap-1">- <button- type="button"- onClick={() => handleStop(conversation)}- disabled={- !isStoppable(conversation.execution_status) ||- stoppingIds.has(conversation.id)- }- className="flex items-center gap-1.5 px-2 py-1 text-xs text-[#8C8C8C] hover:text-white hover:bg-[#262626] rounded transition-colors disabled:opacity-40 disabled:hover:bg-transparent disabled:hover:text-[#8C8C8C] disabled:cursor-not-allowed"- title={- isStoppable(conversation.execution_status)- ? "Stop conversation"- : "Conversation is not running"- }- aria-label="Stop conversation"- >- <StopIcon />- {stoppingIds.has(conversation.id)- ? "Stopping…"- : "Stop"}- </button>- </div>- </td>- </tr>- ))}- </tbody>- </table>- </div>-- {/* Pagination Footer */}- <div className="flex items-center justify-between px-4 py-3 border-t border-[#262626]">- <div className="flex items-center gap-2">- <button- type="button"- onClick={() => handlePageChange(page - 1)}- disabled={page <= 1}- className={`flex items-center gap-1 px-2 py-1 text-sm rounded transition-colors ${- page <= 1- ? "text-[#6B6B6B] cursor-not-allowed"- : "text-[#8C8C8C] hover:text-white hover:bg-[#262626]"- }`}- >- <ChevronLeftIcon />- Previous- </button>- <button- type="button"- onClick={() => handlePageChange(page + 1)}- disabled={page >= totalPages}- className={`flex items-center gap-1 px-2 py-1 text-sm rounded transition-colors ${- page >= totalPages- ? "text-[#6B6B6B] cursor-not-allowed"- : "text-[#8C8C8C] hover:text-white hover:bg-[#262626]"- }`}- >- Next- <ChevronRightIcon />- </button>- </div>-- <div className="flex items-center gap-4">- <div className="flex items-center gap-2">- <span className="text-[#8C8C8C] text-sm">Per page</span>- <select- value={perPage}- onChange={(e) => {- const newParams = new URLSearchParams(searchParams);- newParams.set("per_page", e.target.value);- newParams.set("page", "1");- setSearchParams(newParams);- }}- className="px-2 py-1 bg-[#0D0D0D] border border-[#262626] rounded text-sm text-white focus:outline-none"- >- <option value="5">5</option>- <option value="10">10</option>- <option value="20">20</option>- <option value="50">50</option>- </select>- </div>- <span className="text-[#8C8C8C] text-sm">- Page {page} of {totalPages} · {totalItems} conversations- </span>- </div>- </div>- </div>- </>- )}- </main>-- {pendingStop && (- <ConfirmationModal- text={stopConfirmationText}- onConfirm={confirmStop}- onCancel={cancelStop}- />- )}- </div>- );+ return <UsageDashboard />;}diff --git a/frontend/src/components/features/admin-dashboard/usage-dashboard-tabs.tsx b/frontend/src/components/features/admin-dashboard/usage-dashboard-tabs.tsxnew file mode 100644index 0000000000..5064a787f3--- /dev/null+++ b/frontend/src/components/features/admin-dashboard/usage-dashboard-tabs.tsx@@ -0,0 +1,744 @@+/* eslint-disable i18next/no-literal-string */+import React from "react";+import { ConfirmationModal } from "#/components/shared/modals/confirmation-modal";+import {+ ExportIcon,+ SearchIcon,+ StopIcon,+} from "#/components/shared/icons/inline-icons";+import { AreaChart, KPICard, PieChart } from "./usage-dashboard-widgets";+import {+ formatAgentLabel,+ formatAssociatedPr,+ formatBudget,+ formatCost,+ formatDateTimeOrDash,+ formatDuration,+ formatMergedStatus,+ formatTokens,+} from "./usage-dashboard-utils";++export type ChartPoint = { date: string; value: number };++export type AgentSpendRow = {+ agent_name: string;+ total_cost: number;+ percent: number;+ color: string;+};++export function OverviewTab({+ totalConversations,+ activeConversations,+ avgCostPerConversation,+ totalSpend,+ timeWindowLabel,+ chartData,+ agentSpendRows,+ agentSpendTotal,+}: {+ totalConversations: number;+ activeConversations: number;+ avgCostPerConversation: number;+ totalSpend: string;+ timeWindowLabel: string;+ chartData: ChartPoint[];+ agentSpendRows: AgentSpendRow[];+ agentSpendTotal: number;+}) {+ return (+ <div className="space-y-6">+ <div className="grid grid-cols-4 gap-4">+ <KPICard+ label="Total Conversations"+ value={totalConversations.toLocaleString()}+ />+ <KPICard+ label="Active Conversations"+ value={activeConversations.toLocaleString()}+ />+ <KPICard+ label="Avg Cost / Conversation"+ value={`$${avgCostPerConversation.toFixed(2)}`}+ />+ <KPICard+ label={`Total Spend (${timeWindowLabel})`}+ value={totalSpend}+ />+ </div>++ <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">+ <div className="bg-zinc-900 border border-zinc-800 rounded-lg p-6 lg:col-span-2">+ <div className="flex items-start justify-between mb-6">+ <div>+ <h2 className="text-lg font-medium text-white">+ Conversations per day+ </h2>+ <p className="text-sm text-zinc-500">+ {timeWindowLabel} · all users+ </p>+ </div>+ <button+ type="button"+ className="flex items-center gap-2 px-3 py-1.5 text-sm text-zinc-400 border border-zinc-700 rounded-lg hover:text-white hover:border-zinc-600 transition-colors"+ >+ <ExportIcon />+ Export CSV+ </button>+ </div>+ {chartData.length > 0 ? (+ <AreaChart data={chartData} />+ ) : (+ <div className="py-10 text-center text-sm text-zinc-500">+ No usage data available yet.+ </div>+ )}+ </div>+ <div className="bg-zinc-900 border border-zinc-800 rounded-lg p-6">+ <div className="flex items-start justify-between mb-6">+ <div>+ <h2 className="text-lg font-medium text-white">Spend by agent</h2>+ <p className="text-sm text-zinc-500">+ {timeWindowLabel} · total spend+ </p>+ </div>+ </div>+ {agentSpendTotal > 0 ? (+ <div className="flex flex-col items-center gap-6 lg:flex-row">+ <PieChart+ data={agentSpendRows.map((row) => ({+ value: row.total_cost,+ color: row.color,+ }))}+ total={agentSpendTotal}+ />+ <div className="w-full space-y-3">+ {agentSpendRows.map((row) => (+ <div+ key={row.agent_name}+ className="flex items-center justify-between text-sm"+ >+ <div className="flex items-center gap-2">+ <span+ className="h-2 w-2 rounded-full"+ style={{ backgroundColor: row.color }}+ />+ <span className="text-zinc-300">{row.agent_name}</span>+ </div>+ <span className="text-zinc-400">+ {formatCost(row.total_cost)} · {row.percent.toFixed(1)}%+ </span>+ </div>+ ))}+ </div>+ </div>+ ) : (+ <div className="py-10 text-center text-sm text-zinc-500">+ No agent spend data available yet.+ </div>+ )}+ </div>+ </div>+ </div>+ );+}++export type ConversationRow = {+ id: string;+ user_email?: string | null;+ total_tokens: number;+ accumulated_cost: number;+ created_at?: string | null;+ updated_at?: string | null;+ pr_number?: number[];+ selected_repository?: string | null;+ pr_merged?: boolean | null;+ agent_kind?: string | null;+ llm_model?: string | null;+ trigger?: string | null;+ execution_status?: string | null;+ title?: string | null;+};++export type ConversationsResponse = {+ items: ConversationRow[];+ total_pages?: number;+ total_items?: number;+};++export function ConversationsTab({+ conversationSearch,+ conversationStatus,+ conversationSortBy,+ conversationSortOrder,+ conversationSandboxStatus,+ exportUrl,+ conversationPage,+ conversationPerPage,+ conversationTotalPages,+ conversationTotalItems,+ conversationsLoading,+ conversationsData,+ stoppingIds,+ onSearchChange,+ onStatusChange,+ onSortByChange,+ onSortOrderChange,+ onSandboxStatusChange,+ onPageChange,+ onPerPageChange,+ onStopConversation,+ pendingStop,+ stopConfirmationText,+ onConfirmStop,+ onCancelStop,+}: {+ conversationSearch: string;+ conversationStatus: string;+ conversationSortBy: string;+ conversationSortOrder: string;+ conversationSandboxStatus: string;+ exportUrl: string;+ conversationPage: number;+ conversationPerPage: number;+ conversationTotalPages: number;+ conversationTotalItems: number;+ conversationsLoading: boolean;+ conversationsData?: ConversationsResponse;+ stoppingIds: Set<string>;+ onSearchChange: (value: string) => void;+ onStatusChange: (value: string) => void;+ onSortByChange: (value: string) => void;+ onSortOrderChange: (value: string) => void;+ onSandboxStatusChange: (value: string) => void;+ onPageChange: (page: number) => void;+ onPerPageChange: (value: number) => void;+ onStopConversation: (conversation: {+ id: string;+ title: string | null;+ }) => void;+ pendingStop: { id: string; title: string | null } | null;+ stopConfirmationText: string;+ onConfirmStop: () => void;+ onCancelStop: () => void;+}) {+ return (+ <div className="space-y-4">+ <div className="flex flex-wrap items-center gap-4">+ <div className="relative flex-1 max-w-md">+ <span className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-500">+ <SearchIcon />+ </span>+ <input+ type="text"+ placeholder="Search by title or user..."+ value={conversationSearch}+ onChange={(event) => onSearchChange(event.target.value)}+ className="w-full pl-10 pr-4 py-2 bg-zinc-900 border border-zinc-800 rounded-lg text-white placeholder-zinc-500 focus:outline-none focus:border-zinc-700"+ />+ </div>+ <select+ value={conversationStatus}+ onChange={(event) => onStatusChange(event.target.value)}+ className="px-3 py-2 bg-zinc-900 border border-zinc-800 rounded-lg text-sm text-zinc-400 focus:outline-none focus:border-zinc-700"+ >+ <option value="">All statuses</option>+ <option value="running">Running</option>+ <option value="idle">Idle</option>+ <option value="paused">Paused</option>+ <option value="finished">Finished</option>+ <option value="error">Error</option>+ <option value="stuck">Stuck</option>+ </select>+ <select+ value={conversationSortBy}+ onChange={(event) => onSortByChange(event.target.value)}+ className="px-3 py-2 bg-zinc-900 border border-zinc-800 rounded-lg text-sm text-zinc-400 focus:outline-none focus:border-zinc-700"+ >+ <option value="updated_at">Last updated</option>+ <option value="created_at">Created</option>+ <option value="title">Title</option>+ <option value="llm_model">Model</option>+ <option value="accumulated_cost">Cost</option>+ </select>+ <select+ value={conversationSortOrder}+ onChange={(event) => onSortOrderChange(event.target.value)}+ className="px-3 py-2 bg-zinc-900 border border-zinc-800 rounded-lg text-sm text-zinc-400 focus:outline-none focus:border-zinc-700"+ >+ <option value="desc">Descending</option>+ <option value="asc">Ascending</option>+ </select>+ <select+ value={conversationSandboxStatus}+ onChange={(event) => onSandboxStatusChange(event.target.value)}+ className="px-3 py-2 bg-zinc-900 border border-zinc-800 rounded-lg text-sm text-zinc-400 focus:outline-none focus:border-zinc-700"+ >+ <option value="">Runtime status: All</option>+ <option value="RUNNING">Running</option>+ <option value="STARTING">Starting</option>+ <option value="PAUSED">Paused</option>+ <option value="ERROR">Error</option>+ <option value="MISSING">Missing</option>+ </select>++ <a+ href={exportUrl}+ className="flex items-center gap-2 px-3 py-2 text-sm text-zinc-400 border border-zinc-700 rounded-lg hover:text-white hover:border-zinc-600 transition-colors"+ >+ <ExportIcon />+ Export CSV+ </a>+ </div>++ <div className="bg-zinc-900 border border-zinc-800 rounded-lg overflow-hidden">+ <table className="w-full">+ <thead>+ <tr className="border-b border-zinc-800">+ <th className="px-4 py-3 text-left text-xs font-medium text-zinc-500 uppercase tracking-wider">+ User+ </th>+ <th className="px-4 py-3 text-right text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Tokens+ </th>+ <th className="px-4 py-3 text-right text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Spend+ </th>+ <th className="px-4 py-3 text-left text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Duration+ </th>+ <th className="px-4 py-3 text-left text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Started+ </th>+ <th className="px-4 py-3 text-left text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Last update+ </th>+ <th className="px-4 py-3 text-left text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Associated PR+ </th>+ <th className="px-4 py-3 text-left text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Merged?+ </th>+ <th className="px-4 py-3 text-left text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Agent+ </th>+ <th className="px-4 py-3 text-left text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Type+ </th>+ <th className="px-4 py-3 text-right text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Stop+ </th>+ </tr>+ </thead>+ <tbody>+ {conversationsLoading && (+ <tr>+ <td+ colSpan={11}+ className="px-4 py-8 text-center text-zinc-500"+ >+ Loading conversations...+ </td>+ </tr>+ )}+ {!conversationsLoading &&+ (conversationsData?.items.length ?? 0) === 0 && (+ <tr>+ <td+ colSpan={11}+ className="px-4 py-8 text-center text-zinc-500"+ >+ No conversations found for this time window.+ </td>+ </tr>+ )}+ {conversationsData?.items.map((conversation) => {+ const isRunning =+ conversation.execution_status?.toLowerCase() === "running";+ return (+ <tr+ key={conversation.id}+ className="border-b border-zinc-800/50 hover:bg-zinc-800/50 transition-colors"+ >+ <td className="px-4 py-4">+ <div className="text-white text-sm font-medium">+ {conversation.user_email?.split("@")[0] || "Unknown"}+ </div>+ <div className="text-xs text-zinc-500">+ {conversation.user_email || "-"}+ </div>+ </td>+ <td className="px-4 py-4 text-right text-sm font-mono text-white">+ {formatTokens(conversation.total_tokens)}+ </td>+ <td className="px-4 py-4 text-right text-sm text-white">+ {formatCost(conversation.accumulated_cost)}+ </td>+ <td className="px-4 py-4 text-sm text-zinc-400">+ {formatDuration(+ conversation.created_at,+ conversation.updated_at,+ )}+ </td>+ <td className="px-4 py-4 text-sm text-zinc-400">+ {formatDateTimeOrDash(conversation.created_at)}+ </td>+ <td className="px-4 py-4 text-sm text-zinc-400">+ {formatDateTimeOrDash(conversation.updated_at)}+ </td>+ <td className="px-4 py-4 text-sm text-zinc-400">+ {formatAssociatedPr(conversation)}+ </td>+ <td className="px-4 py-4 text-sm text-zinc-400">+ {formatMergedStatus(conversation.pr_merged)}+ </td>+ <td className="px-4 py-4 text-sm text-zinc-400">+ {formatAgentLabel(conversation)}+ </td>+ <td className="px-4 py-4 text-sm text-zinc-400 capitalize">+ {conversation.trigger || "-"}+ </td>+ <td className="px-4 py-4 text-right text-sm">+ {isRunning && (+ <button+ type="button"+ onClick={() =>+ onStopConversation({+ id: conversation.id,+ title: conversation.title ?? null,+ })+ }+ disabled={stoppingIds.has(conversation.id)}+ className="inline-flex items-center gap-1.5 px-2 py-1 text-xs text-zinc-400 hover:text-white hover:bg-zinc-800 rounded transition-colors disabled:opacity-40 disabled:hover:bg-transparent disabled:hover:text-zinc-400 disabled:cursor-not-allowed"+ title="Stop conversation"+ aria-label="Stop conversation"+ >+ <StopIcon />+ {stoppingIds.has(conversation.id)+ ? "Stopping…"+ : "Stop"}+ </button>+ )}+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ <div className="flex items-center justify-between px-4 py-3 border-t border-zinc-800">+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={() => onPageChange(Math.max(1, conversationPage - 1))}+ disabled={conversationPage <= 1}+ className={`flex items-center gap-1 px-2 py-1 text-sm rounded transition-colors ${+ conversationPage <= 1+ ? "text-zinc-600 cursor-not-allowed"+ : "text-zinc-400 hover:text-white hover:bg-zinc-800"+ }`}+ >+ Previous+ </button>+ <button+ type="button"+ onClick={() =>+ onPageChange(+ Math.min(conversationTotalPages, conversationPage + 1),+ )+ }+ disabled={conversationPage >= conversationTotalPages}+ className={`flex items-center gap-1 px-2 py-1 text-sm rounded transition-colors ${+ conversationPage >= conversationTotalPages+ ? "text-zinc-600 cursor-not-allowed"+ : "text-zinc-400 hover:text-white hover:bg-zinc-800"+ }`}+ >+ Next+ </button>+ </div>+ <div className="flex items-center gap-4">+ <div className="flex items-center gap-2">+ <span className="text-zinc-500 text-sm">Per page</span>+ <select+ value={conversationPerPage}+ onChange={(event) =>+ onPerPageChange(Number(event.target.value))+ }+ className="px-2 py-1 bg-zinc-900 border border-zinc-800 rounded text-sm text-white focus:outline-none"+ >+ <option value="10">10</option>+ <option value="20">20</option>+ <option value="50">50</option>+ </select>+ </div>+ <span className="text-zinc-500 text-sm">+ Page {conversationPage} of {conversationTotalPages} ·{" "}+ {conversationTotalItems} conversations+ </span>+ </div>+ </div>+ </div>++ {pendingStop && (+ <ConfirmationModal+ text={stopConfirmationText}+ onConfirm={onConfirmStop}+ onCancel={onCancelStop}+ />+ )}+ </div>+ );+}++export type UserUsageRow = {+ user_id: string;+ user_name?: string | null;+ user_email?: string | null;+ conversation_count: number;+ first_conversation_at?: string | null;+ last_conversation_at?: string | null;+ first_login_at?: string | null;+ last_login_at?: string | null;+ spend_mtd: number;+ spend_ytd: number;+ spend_lifetime: number;+ budget_monthly_limit?: number | null;+ budget_is_disabled?: boolean;+ prs_merged?: number | null;+};++export type UserUsageResponse = {+ items: UserUsageRow[];+};++export function UsersTab({+ userUsage,+ userUsageLoading,+}: {+ userUsage?: UserUsageResponse;+ userUsageLoading: boolean;+}) {+ return (+ <div className="space-y-4">+ <div className="bg-zinc-900 border border-zinc-800 rounded-lg overflow-hidden">+ <table className="w-full">+ <thead>+ <tr className="border-b border-zinc-800">+ <th className="px-4 py-3 text-left text-xs font-medium text-zinc-500 uppercase tracking-wider">+ User+ </th>+ <th className="px-4 py-3 text-right text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Convos+ </th>+ <th className="px-4 py-3 text-left text-xs font-medium text-zinc-500 uppercase tracking-wider">+ First convo+ </th>+ <th className="px-4 py-3 text-left text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Last convo+ </th>+ <th className="px-4 py-3 text-left text-xs font-medium text-zinc-500 uppercase tracking-wider">+ First login+ </th>+ <th className="px-4 py-3 text-left text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Last login+ </th>+ <th className="px-4 py-3 text-right text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Spend MTD+ </th>+ <th className="px-4 py-3 text-right text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Spend YTD+ </th>+ <th className="px-4 py-3 text-right text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Lifetime+ </th>+ <th className="px-4 py-3 text-left text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Budget+ </th>+ <th className="px-4 py-3 text-right text-xs font-medium text-zinc-500 uppercase tracking-wider">+ PRs merged+ </th>+ </tr>+ </thead>+ <tbody>+ {userUsageLoading && (+ <tr>+ <td+ colSpan={11}+ className="px-4 py-8 text-center text-zinc-500"+ >+ Loading user usage...+ </td>+ </tr>+ )}+ {!userUsageLoading && (userUsage?.items.length ?? 0) === 0 && (+ <tr>+ <td+ colSpan={11}+ className="px-4 py-8 text-center text-zinc-500"+ >+ No user usage data available yet.+ </td>+ </tr>+ )}+ {userUsage?.items.map((user) => (+ <tr+ key={user.user_id}+ className="border-b border-zinc-800/50 hover:bg-zinc-800/50 transition-colors"+ >+ <td className="px-4 py-4">+ <div className="text-white text-sm font-medium">+ {user.user_name ??+ user.user_email?.split("@")[0] ??+ "Unknown"}+ </div>+ <div className="text-xs text-zinc-500">+ {user.user_email || "-"}+ </div>+ </td>+ <td className="px-4 py-4 text-right text-sm text-white">+ {user.conversation_count.toLocaleString()}+ </td>+ <td className="px-4 py-4 text-sm text-zinc-400">+ {formatDateTimeOrDash(user.first_conversation_at)}+ </td>+ <td className="px-4 py-4 text-sm text-zinc-400">+ {formatDateTimeOrDash(user.last_conversation_at)}+ </td>+ <td className="px-4 py-4 text-sm text-zinc-400">+ {formatDateTimeOrDash(user.first_login_at)}+ </td>+ <td className="px-4 py-4 text-sm text-zinc-400">+ {formatDateTimeOrDash(user.last_login_at)}+ </td>+ <td className="px-4 py-4 text-right text-sm text-white">+ {formatCost(user.spend_mtd)}+ </td>+ <td className="px-4 py-4 text-right text-sm text-white">+ {formatCost(user.spend_ytd)}+ </td>+ <td className="px-4 py-4 text-right text-sm text-white">+ {formatCost(user.spend_lifetime)}+ </td>+ <td className="px-4 py-4 text-sm text-zinc-400">+ {formatBudget(user)}+ </td>+ <td className="px-4 py-4 text-right text-sm text-zinc-400">+ {user.prs_merged ?? "-"}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ );+}++export type ModelUsageRow = {+ model_name: string;+ conversation_count: number;+ total_tokens: number;+ avgTokens: number;+ avgCost: number;+ total_cost: number;+};++export function ModelsTab({+ modelSearch,+ onModelSearchChange,+ filteredModels,+}: {+ modelSearch: string;+ onModelSearchChange: (value: string) => void;+ filteredModels: ModelUsageRow[];+}) {+ return (+ <div className="space-y-4">+ <div className="flex items-center justify-between">+ <div className="relative w-64">+ <span className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-500">+ <SearchIcon />+ </span>+ <input+ type="text"+ placeholder="Search models..."+ value={modelSearch}+ onChange={(event) => onModelSearchChange(event.target.value)}+ className="w-full pl-10 pr-4 py-2 bg-zinc-900 border border-zinc-800 rounded-lg text-white placeholder-zinc-500 focus:outline-none focus:border-zinc-700"+ />+ </div>+ <button+ type="button"+ className="flex items-center gap-2 px-3 py-2 text-sm text-zinc-400 border border-zinc-700 rounded-lg hover:text-white hover:border-zinc-600 transition-colors"+ >+ <ExportIcon />+ Export CSV+ </button>+ </div>++ <div className="bg-zinc-900 border border-zinc-800 rounded-lg overflow-hidden">+ <table className="w-full">+ <thead>+ <tr className="border-b border-zinc-800">+ <th className="px-4 py-3 text-left text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Model+ </th>+ <th className="px-4 py-3 text-right text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Conversations+ </th>+ <th className="px-4 py-3 text-right text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Tokens Used+ </th>+ <th className="px-4 py-3 text-right text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Avg Tokens / Convo+ </th>+ <th className="px-4 py-3 text-right text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Avg Cost / Convo+ </th>+ <th className="px-4 py-3 text-right text-xs font-medium text-zinc-500 uppercase tracking-wider">+ Total Cost+ </th>+ </tr>+ </thead>+ <tbody>+ {filteredModels.map((model) => (+ <tr+ key={model.model_name}+ className="border-b border-zinc-800/50 hover:bg-zinc-800/50 transition-colors"+ >+ <td className="px-4 py-5">+ <div className="text-white font-medium">+ {model.model_name}+ </div>+ </td>+ <td className="px-4 py-5 text-white text-sm font-mono text-right">+ {model.conversation_count.toLocaleString()}+ </td>+ <td className="px-4 py-5 text-white text-sm font-mono text-right">+ {formatTokens(model.total_tokens)}+ </td>+ <td className="px-4 py-5 text-white text-sm font-mono text-right">+ {formatTokens(model.avgTokens)}+ </td>+ <td className="px-4 py-5 text-white text-sm font-mono text-right">+ ${model.avgCost.toFixed(2)}+ </td>+ <td className="px-4 py-5 text-white text-sm font-mono text-right font-medium">+ ${model.total_cost.toFixed(2)}+ </td>+ </tr>+ ))}++ {filteredModels.length === 0 && (+ <tr>+ <td colSpan={6} className="px-4 py-8 text-center text-zinc-500">+ No model usage data available for this time window.+ </td>+ </tr>+ )}+ </tbody>+ </table>+ </div>+ </div>+ );+}diff --git a/frontend/src/components/features/admin-dashboard/usage-dashboard-utils.ts b/frontend/src/components/features/admin-dashboard/usage-dashboard-utils.tsnew file mode 100644index 0000000000..e05e619137--- /dev/null+++ b/frontend/src/components/features/admin-dashboard/usage-dashboard-utils.ts@@ -0,0 +1,116 @@+/* eslint-disable i18next/no-literal-string */++export const TIME_WINDOWS = [+ { label: "7d", value: "7d" },+ { label: "30d", value: "30d" },+ { label: "90d", value: "90d" },+ { label: "YTD", value: "ytd" },+];++export const AGENT_COLORS = [+ "#3B82F6",+ "#F59E0B",+ "#10B981",+ "#8B5CF6",+ "#EF4444",+ "#06B6D4",+ "#F97316",+];++export const formatTokens = (tokens: number) => {+ if (tokens >= 1000000) return `${(tokens / 1000000).toFixed(1)}M`;+ if (tokens >= 1000) return `${(tokens / 1000).toFixed(1)}K`;+ return tokens.toString();+};++export const formatCost = (cost: number) => {+ if (cost >= 1000) return `$${(cost / 1000).toFixed(1)}k`;+ return `$${cost.toFixed(2)}`;+};++export const formatShortDate = (dateStr: string) => {+ const date = new Date(dateStr);+ return date.toLocaleDateString("en-US", {+ month: "short",+ day: "numeric",+ });+};++export const formatDateTime = (dateStr: string) => {+ const date = new Date(dateStr);+ return date.toLocaleDateString("en-US", {+ month: "short",+ day: "numeric",+ year: "numeric",+ hour: "numeric",+ minute: "2-digit",+ });+};++export const formatDateTimeOrDash = (value?: string | null) =>+ value ? formatDateTime(value) : "-";++export const formatDuration = (start?: string | null, end?: string | null) => {+ if (!start || !end) return "-";+ const startMs = new Date(start).getTime();+ const endMs = new Date(end).getTime();+ if (Number.isNaN(startMs) || Number.isNaN(endMs)) return "-";+ const diffMs = Math.max(0, endMs - startMs);+ const totalMinutes = Math.floor(diffMs / 60000);+ const totalHours = Math.floor(totalMinutes / 60);+ if (totalHours >= 24) {+ const days = Math.floor(totalHours / 24);+ const hours = totalHours % 24;+ return `${days}d ${hours}h`;+ }+ if (totalHours > 0) {+ return `${totalHours}h ${totalMinutes % 60}m`;+ }+ return `${totalMinutes}m`;+};++export const formatAssociatedPr = (conversation: {+ pr_number?: number[];+ selected_repository?: string | null;+}) => {+ const prNumbers = conversation.pr_number ?? [];+ if (prNumbers.length === 0) return "-";+ const repo = conversation.selected_repository;+ return prNumbers.map((pr) => (repo ? `${repo}#${pr}` : `#${pr}`)).join(", ");+};++export const formatBudget = (user: {+ budget_monthly_limit?: number | null;+ budget_is_disabled?: boolean;+}) => {+ if (user.budget_is_disabled) return "Disabled";+ if (user.budget_monthly_limit == null) return "-";+ return formatCost(user.budget_monthly_limit);+};++export const formatAgentLabel = (conversation: {+ agent_kind?: string | null;+ llm_model?: string | null;+}) => {+ const agentKind = conversation.agent_kind ?? null;+ if (agentKind === "acp") {+ const llmModel = conversation.llm_model ?? "";+ const llmModelLower = llmModel.toLowerCase();+ if (!llmModel) return "ACP";+ if (llmModelLower.includes("claude")) return "Claude";+ if (llmModelLower.includes("codex")) return "Codex";+ if (llmModelLower.includes("gpt") || llmModelLower.includes("openai")) {+ return "OpenAI";+ }+ if (llmModelLower.includes("gemini")) return "Gemini";+ return llmModel;+ }+ if (agentKind === "openhands") return "OpenHands";+ return agentKind || "-";+};++export const formatMergedStatus = (merged?: boolean | null) => {+ if (merged === true) return "Yes";+ if (merged === false) return "No";+ return "-";+};diff --git a/frontend/src/components/features/admin-dashboard/usage-dashboard-widgets.tsx b/frontend/src/components/features/admin-dashboard/usage-dashboard-widgets.tsxnew file mode 100644index 0000000000..0a1335223f--- /dev/null+++ b/frontend/src/components/features/admin-dashboard/usage-dashboard-widgets.tsx@@ -0,0 +1,151 @@+/* eslint-disable i18next/no-literal-string */+import React from "react";+import {+ TrendDownIcon,+ TrendUpIcon,+} from "#/components/shared/icons/inline-icons";+import { formatShortDate } from "./usage-dashboard-utils";++export function KPICard({+ label,+ value,+ trend,+ trendUp,+}: {+ label: string;+ value: string | number;+ trend?: string;+ trendUp?: boolean;+}) {+ return (+ <div className="bg-zinc-900 border border-zinc-800 rounded-lg p-5">+ <span className="text-zinc-500 text-xs font-medium uppercase tracking-wide">+ {label}+ </span>+ <div className="text-white text-2xl font-bold mt-2">{value}</div>+ {trend && (+ <div+ className={`flex items-center gap-1 mt-2 text-xs ${trendUp ? "text-green-400" : "text-red-400"}`}+ >+ {trendUp ? <TrendUpIcon /> : <TrendDownIcon />}+ {trend}+ </div>+ )}+ </div>+ );+}++export function AreaChart({+ data,+}: {+ data: { date: string; value: number }[];+}) {+ const maxValue = Math.max(...data.map((d) => d.value), 1);+ const minValue = Math.min(...data.map((d) => d.value), 0);+ const range = maxValue - minValue || 1;++ const width = 100;+ const height = 100;+ const points = data.map((d, i) => {+ const x = (i / (data.length - 1)) * width;+ const y = height - ((d.value - minValue) / range) * height;+ return `${x},${y}`;+ });++ const pathD = `M ${points.join(" L ")}`;+ const areaD = `${pathD} L ${width},${height} L 0,${height} Z`;++ return (+ <div className="relative h-48 w-full">+ <svg+ viewBox={`0 0 ${width} ${height}`}+ className="w-full h-full"+ preserveAspectRatio="none"+ >+ {[0, 25, 50, 75, 100].map((pct) => (+ <line+ key={pct}+ x1="0"+ y1={`${pct}%`}+ x2="100%"+ y2={`${pct}%`}+ stroke="rgba(255,255,255,0.05)"+ strokeWidth="0.5"+ />+ ))}+ <path d={areaD} fill="url(#blueGradient)" opacity="0.3" />+ <path d={pathD} fill="none" stroke="#3B82F6" strokeWidth="2" />+ <defs>+ <linearGradient id="blueGradient" x1="0%" y1="0%" x2="0%" y2="100%">+ <stop offset="0%" stopColor="#3B82F6" stopOpacity="0.5" />+ <stop offset="100%" stopColor="#3B82F6" stopOpacity="0" />+ </linearGradient>+ </defs>+ </svg>+ <div className="absolute left-0 top-0 bottom-0 flex flex-col justify-between text-xs text-zinc-600 -ml-2">+ <span>{maxValue.toLocaleString()}</span>+ <span>{Math.round((maxValue + minValue) / 2).toLocaleString()}</span>+ <span>{minValue.toLocaleString()}</span>+ </div>+ <div className="absolute bottom-0 left-0 right-0 flex justify-between text-xs text-zinc-600 mt-2">+ {data+ .filter((_, i) => i % Math.ceil(data.length / 7) === 0)+ .map((d) => (+ <span key={d.date}>{formatShortDate(d.date)}</span>+ ))}+ </div>+ </div>+ );+}++export function PieChart({+ data,+ total,+}: {+ data: { value: number; color: string }[];+ total: number;+}) {+ const size = 160;+ const strokeWidth = 18;+ const radius = (size - strokeWidth) / 2;+ const circumference = 2 * Math.PI * radius;+ let offset = 0;++ return (+ <div className="relative h-40 w-40">+ <svg viewBox={`0 0 ${size} ${size}`} className="h-full w-full">+ <g transform={`rotate(-90 ${size / 2} ${size / 2})`}>+ <circle+ cx={size / 2}+ cy={size / 2}+ r={radius}+ fill="transparent"+ stroke="rgba(255,255,255,0.08)"+ strokeWidth={strokeWidth}+ />+ {data.map((segment, index) => {+ const portion = total > 0 ? segment.value / total : 0;+ const segmentLength = circumference * portion;+ const dashArray = `${segmentLength} ${circumference - segmentLength}`;+ const segmentOffset = offset;+ offset += segmentLength;+ return (+ <circle+ key={`${segment.color}-${index}`}+ cx={size / 2}+ cy={size / 2}+ r={radius}+ fill="transparent"+ stroke={segment.color}+ strokeWidth={strokeWidth}+ strokeDasharray={dashArray}+ strokeDashoffset={-segmentOffset}+ strokeLinecap="round"+ />+ );+ })}+ </g>+ </svg>+ </div>+ );+}diff --git a/frontend/src/components/features/admin-dashboard/usage-dashboard.tsx b/frontend/src/components/features/admin-dashboard/usage-dashboard.tsxnew file mode 100644index 0000000000..84f0750557--- /dev/null+++ b/frontend/src/components/features/admin-dashboard/usage-dashboard.tsx@@ -0,0 +1,346 @@+/* eslint-disable i18next/no-literal-string */+import React, { useMemo, useState } from "react";+import { useSelectedOrganizationId } from "#/context/use-selected-organization";+import { useStopConversation } from "#/hooks/mutation/use-stop-conversation";+import { useOrgConversationStats } from "#/hooks/query/use-org-conversation-stats";+import { useOrgConversations } from "#/hooks/query/use-org-conversations";+import { useOrgUsageStats } from "#/hooks/query/use-org-usage-stats";+import { useOrgUserUsage } from "#/hooks/query/use-org-user-usage";+import { useOrganizations } from "#/hooks/query/use-organizations";+import { organizationService } from "#/api/organization-service/organization-service.api";+import {+ ConversationsTab,+ ModelsTab,+ OverviewTab,+ UsersTab,+} from "./usage-dashboard-tabs";+import {+ AGENT_COLORS,+ TIME_WINDOWS,+ formatCost,+} from "./usage-dashboard-utils";++// Tabs+const TABS = ["overview", "users", "models", "conversations"] as const;+type TabType = (typeof TABS)[number];++export function UsageDashboard() {+ const [activeTab, setActiveTab] = useState<TabType>("overview");+ const [timeWindow, setTimeWindow] = useState("30d");+ const [modelSearch, setModelSearch] = useState("");+ const [conversationSearch, setConversationSearch] = useState("");+ const [conversationStatus, setConversationStatus] = useState("running");++ const [conversationSortBy, setConversationSortBy] = useState("updated_at");+ const [conversationSortOrder, setConversationSortOrder] = useState("desc");+ const [conversationSandboxStatus, setConversationSandboxStatus] =+ useState("");++ const [conversationPage, setConversationPage] = useState(1);+ const [conversationPerPage, setConversationPerPage] = useState(20);++ const { organizationId } = useSelectedOrganizationId();+ const { data: orgData } = useOrganizations();++ const { data: stats } = useOrgConversationStats();+ const { data: usageStats } = useOrgUsageStats({ timeWindow });+ const { data: userUsage, isLoading: userUsageLoading } = useOrgUserUsage();++ const conversationTimeWindow = timeWindow === "ytd" ? "" : timeWindow;++ const { data: conversationsData, isLoading: conversationsLoading } =+ useOrgConversations({+ page: conversationPage,+ perPage: conversationPerPage,+ search: conversationSearch,+ sortBy: conversationSortBy,+ sortOrder: conversationSortOrder,+ executionStatus: conversationStatus,+ sandboxStatus: conversationSandboxStatus,+ timeWindow: conversationTimeWindow,+ });++ const [stoppingIds, setStoppingIds] = useState<Set<string>>(new Set());+ const [pendingStop, setPendingStop] = useState<{+ id: string;+ title: string | null;+ } | null>(null);+ const stopConversation = useStopConversation();++ const handleStop = (conversation: { id: string; title: string | null }) => {+ setPendingStop(conversation);+ };++ const confirmStop = () => {+ if (!pendingStop) return;+ const conversation = pendingStop;+ setPendingStop(null);+ setStoppingIds((prev) => {+ const next = new Set(prev);+ next.add(conversation.id);+ return next;+ });+ stopConversation.mutate(+ { conversationId: conversation.id },+ {+ onSettled: () => {+ setStoppingIds((prev) => {+ if (!prev.has(conversation.id)) return prev;+ const next = new Set(prev);+ next.delete(conversation.id);+ return next;+ });+ },+ },+ );+ };++ const cancelStop = () => {+ setPendingStop(null);+ };++ const currentOrg = orgData?.organizations?.find(+ (org) => org.id === organizationId,+ );++ const totalConversations = usageStats?.agent_runs ?? 0;+ const activeConversations = stats?.active_conversations ?? 0;+ const avgCostPerConversation =+ totalConversations > 0+ ? (usageStats?.estimated_spend ?? 0) / totalConversations+ : 0;+ const totalSpend = formatCost(usageStats?.estimated_spend ?? 0);++ const modelRows = useMemo(+ () =>+ (usageStats?.model_usage ?? []).map((model) => {+ const avgTokens =+ model.conversation_count > 0+ ? Math.round(model.total_tokens / model.conversation_count)+ : 0;+ const avgCost =+ model.conversation_count > 0+ ? model.total_cost / model.conversation_count+ : 0;+ return {+ ...model,+ avgTokens,+ avgCost,+ };+ }),+ [usageStats?.model_usage],+ );++ const filteredModels = useMemo(+ () =>+ modelRows.filter((model) =>+ model.model_name.toLowerCase().includes(modelSearch.toLowerCase()),+ ),+ [modelRows, modelSearch],+ );++ const chartData = useMemo(+ () =>+ (usageStats?.daily_usage ?? []).map((d) => ({+ date: d.date,+ value: d.conversations,+ })),+ [usageStats?.daily_usage],+ );++ const agentSpendRows = useMemo(() => {+ const rows = usageStats?.agent_usage ?? [];+ const total = rows.reduce((sum, row) => sum + row.total_cost, 0);+ return rows.map((row, index) => ({+ ...row,+ percent: total > 0 ? (row.total_cost / total) * 100 : 0,+ color: AGENT_COLORS[index % AGENT_COLORS.length],+ }));+ }, [usageStats?.agent_usage]);++ const agentSpendTotal = agentSpendRows.reduce(+ (sum, row) => sum + row.total_cost,+ 0,+ );++ const tabCounts = {+ overview: null,+ users: userUsage?.items.length ?? 0,+ models: modelRows.length,+ conversations: conversationsData?.total_items ?? 0,+ };++ const timeWindowLabel =+ timeWindow === "ytd" ? "YTD" : timeWindow.toUpperCase();++ const conversationTotalPages = conversationsData?.total_pages ?? 1;+ const conversationTotalItems = conversationsData?.total_items ?? 0;++ const pendingStopLabel = pendingStop?.title?.trim();+ const stopConfirmationText = pendingStopLabel+ ? `Stop "${pendingStopLabel}"? This will cancel any in-progress agent run.`+ : "Stop this conversation? This will cancel any in-progress agent run.";++ const exportUrl = useMemo(() => {+ if (!organizationId) return "#";+ return organizationService.exportConversationsUrl({+ orgId: organizationId,+ search: conversationSearch || undefined,+ sortBy: conversationSortBy,+ sortOrder: conversationSortOrder,+ executionStatus: conversationStatus || undefined,+ sandboxStatus: conversationSandboxStatus || undefined,+ timeWindow: conversationTimeWindow || undefined,+ });+ }, [+ organizationId,+ conversationSearch,+ conversationSortBy,+ conversationSortOrder,+ conversationStatus,+ conversationSandboxStatus,+ conversationTimeWindow,+ ]);++ return (+ <div className="min-h-screen bg-zinc-950 text-white">+ {/* Header */}+ <div className="px-8 py-6 border-b border-zinc-800">+ <div className="flex items-start justify-between mb-6">+ <div>+ <h1 className="text-2xl font-bold text-white mb-1">+ Usage & Monitoring+ </h1>+ <p className="text-zinc-400">+ Monitor adoption, spend, and ROI across{" "}+ {currentOrg?.name || "your organization"}.+ </p>+ </div>+ {/* Time window selector */}+ <div className="flex items-center gap-1 bg-zinc-900 border border-zinc-800 rounded-lg p-1">+ {TIME_WINDOWS.map((tw) => (+ <button+ key={tw.value}+ type="button"+ onClick={() => {+ setTimeWindow(tw.value);+ setConversationPage(1);+ }}+ className={`px-3 py-1.5 text-sm rounded-md transition-colors ${+ timeWindow === tw.value+ ? "bg-zinc-800 text-white"+ : "text-zinc-400 hover:text-white"+ }`}+ >+ {tw.label}+ </button>+ ))}+ </div>+ </div>++ {/* Tabs */}+ <div className="flex gap-6 border-b border-zinc-800 -mb-6">+ {TABS.map((tab) => (+ <button+ key={tab}+ type="button"+ onClick={() => setActiveTab(tab)}+ className={`flex items-center gap-2 px-1 py-3 text-sm font-medium transition-colors border-b-2 ${+ activeTab === tab+ ? "border-blue-500 text-white"+ : "border-transparent text-zinc-400 hover:text-white"+ }`}+ >+ {tab.charAt(0).toUpperCase() + tab.slice(1)}+ {typeof tabCounts[tab] === "number" && (+ <span className="px-2 py-0.5 text-xs bg-zinc-800 text-zinc-400 rounded-full">+ {tabCounts[tab].toLocaleString()}+ </span>+ )}+ </button>+ ))}+ </div>+ </div>++ {/* Main Content */}+ <div className="p-8">+ {/* Overview Tab */}+ {activeTab === "overview" && (+ <OverviewTab+ totalConversations={totalConversations}+ activeConversations={activeConversations}+ avgCostPerConversation={avgCostPerConversation}+ totalSpend={totalSpend}+ timeWindowLabel={timeWindowLabel}+ chartData={chartData}+ agentSpendRows={agentSpendRows}+ agentSpendTotal={agentSpendTotal}+ />+ )}++ {/* Conversations Tab */}+ {activeTab === "conversations" && (+ <ConversationsTab+ conversationSearch={conversationSearch}+ conversationStatus={conversationStatus}+ conversationSortBy={conversationSortBy}+ conversationSortOrder={conversationSortOrder}+ conversationSandboxStatus={conversationSandboxStatus}+ exportUrl={exportUrl}+ conversationPage={conversationPage}+ conversationPerPage={conversationPerPage}+ conversationTotalPages={conversationTotalPages}+ conversationTotalItems={conversationTotalItems}+ conversationsLoading={conversationsLoading}+ conversationsData={conversationsData}+ stoppingIds={stoppingIds}+ onSearchChange={(value) => {+ setConversationSearch(value);+ setConversationPage(1);+ }}+ onStatusChange={(value) => {+ setConversationStatus(value);+ setConversationPage(1);+ }}+ onSortByChange={(value) => {+ setConversationSortBy(value);+ setConversationPage(1);+ }}+ onSortOrderChange={(value) => {+ setConversationSortOrder(value);+ setConversationPage(1);+ }}+ onSandboxStatusChange={(value) => {+ setConversationSandboxStatus(value);+ setConversationPage(1);+ }}+ onPageChange={setConversationPage}+ onPerPageChange={(value) => {+ setConversationPerPage(value);+ setConversationPage(1);+ }}+ onStopConversation={handleStop}+ pendingStop={pendingStop}+ stopConfirmationText={stopConfirmationText}+ onConfirmStop={confirmStop}+ onCancelStop={cancelStop}+ />+ )}++ {/* Users Tab */}+ {activeTab === "users" && (+ <UsersTab userUsage={userUsage} userUsageLoading={userUsageLoading} />+ )}++ {/* Models Tab */}+ {activeTab === "models" && (+ <ModelsTab+ modelSearch={modelSearch}+ onModelSearchChange={setModelSearch}+ filteredModels={filteredModels}+ />+ )}+ </div>+ </div>+ );+}diff --git a/frontend/src/components/features/budgets/budgets-components.tsx b/frontend/src/components/features/budgets/budgets-components.tsxnew file mode 100644index 0000000000..69bf2fecdf--- /dev/null+++ b/frontend/src/components/features/budgets/budgets-components.tsx@@ -0,0 +1,179 @@+/* eslint-disable i18next/no-literal-string */+import React from "react";++export function Toggle({+ enabled,+ onChange,+ label,+}: {+ enabled: boolean;+ onChange: (value: boolean) => void;+ label: string;+}) {+ return (+ <button+ type="button"+ role="switch"+ aria-checked={enabled}+ aria-label={label}+ onClick={() => onChange(!enabled)}+ className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${+ enabled ? "bg-blue-500" : "bg-[#262626]"+ }`}+ >+ <span+ className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${+ enabled ? "translate-x-6" : "translate-x-1"+ }`}+ />+ </button>+ );+}++export function PillBadge({+ active,+ icon,+ label,+ disabled = false,+}: {+ active: boolean;+ icon: React.ReactNode;+ label: string;+ disabled?: boolean;+}) {+ return (+ <span+ className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border transition-colors ${+ active+ ? "bg-blue-500/10 text-blue-400 border-blue-500/30"+ : "bg-[#151D2A] text-[#6B6B6B] border-[#262626]"+ } ${disabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer"}`}+ >+ {active && <span className="text-blue-400">✓</span>}+ {icon}+ {label}+ </span>+ );+}++export function SpendMeter({+ percentage,+ showTicks = true,+}: {+ percentage: number;+ showTicks?: boolean;+}) {+ const getBarColor = () => {+ if (percentage >= 90)+ return "bg-gradient-to-r from-green-500 via-yellow-500 to-red-500";+ if (percentage >= 80)+ return "bg-gradient-to-r from-green-500 via-yellow-500 to-orange-500";+ return "bg-gradient-to-r from-green-500 to-yellow-500";+ };++ return (+ <div className="w-full">+ <div className="relative w-full h-3 bg-[#0B0F17] rounded-full overflow-hidden">+ <div+ className={`absolute inset-y-0 left-0 rounded-full ${getBarColor()}`}+ style={{ width: `${Math.min(percentage, 100)}%` }}+ />+ </div>+ {showTicks && (+ <div className="relative mt-1">+ <div className="flex justify-between text-[10px] text-[#6B6B6B]">+ <span>0%</span>+ <span>80%</span>+ <span>90%</span>+ <span>100%</span>+ </div>+ <div className="absolute top-0 left-[80%] w-px h-2 bg-[#6B6B6B]" />+ <div className="absolute top-0 left-[90%] w-px h-2 bg-[#6B6B6B]" />+ <div className="absolute top-0 left-[100%] w-px h-2 bg-[#6B6B6B]" />+ </div>+ )}+ </div>+ );+}++export function UserProgressBar({+ value,+ max,+ status,+}: {+ value: number;+ max: number;+ status: "green" | "yellow" | "red";+}) {+ const percentage = max > 0 ? (value / max) * 100 : 0;+ const colorClass = {+ red: "bg-red-500",+ yellow: "bg-yellow-500",+ green: "bg-green-500",+ }[status];++ return (+ <div className="w-full">+ <div className="relative w-full h-1.5 bg-[#0B0F17] rounded-full overflow-hidden">+ <div+ className={`absolute inset-y-0 left-0 rounded-full ${colorClass}`}+ style={{ width: `${Math.min(percentage, 100)}%` }}+ />+ </div>+ <div className="text-xs text-[#8C8C8C] mt-1">+ ${value.toLocaleString()} / ${max.toLocaleString()}+ </div>+ </div>+ );+}++export function Avatar({+ name,+ size = "md",+}: {+ name: string;+ size?: "sm" | "md";+}) {+ const initials = name+ .split(" ")+ .map((n) => n[0])+ .join("")+ .toUpperCase()+ .slice(0, 2);++ const sizeClass = size === "sm" ? "w-7 h-7 text-xs" : "w-9 h-9 text-sm";++ return (+ <div+ className={`${sizeClass} rounded-full bg-[#262626] text-white flex items-center justify-center font-medium`}+ >+ {initials}+ </div>+ );+}++export function StatusPill({ status }: { status: string }) {+ const getStyle = () => {+ if (status.includes("Over cap")) {+ return "bg-red-500/20 text-red-400 border-red-500/30";+ }+ if (status.includes("> 90%")) {+ return "bg-red-500/10 text-red-400 border-red-500/30";+ }+ if (status.includes("> 80%")) {+ return "bg-yellow-500/10 text-yellow-400 border-yellow-500/30";+ }+ if (status.includes("On track")) {+ return "bg-green-500/10 text-green-400 border-green-500/30";+ }+ return "bg-[#151D2A] text-[#6B6B6B] border-[#262626]";+ };++ return (+ <span+ className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border ${getStyle()}`}+ >+ {status}+ </span>+ );+}diff --git a/frontend/src/components/features/budgets/budgets-constants.ts b/frontend/src/components/features/budgets/budgets-constants.tsnew file mode 100644index 0000000000..b54ddd85b3--- /dev/null+++ b/frontend/src/components/features/budgets/budgets-constants.ts@@ -0,0 +1,9 @@+export const BUDGET_TABS = [+ { value: "organization", label: "Organization budget" },+ { value: "defaults", label: "Default budgets" },+ { value: "overrides", label: "User overrides" },+] as const;++export const USERS_PER_PAGE = 50;++export type BudgetTab = (typeof BUDGET_TABS)[number]["value"];diff --git a/frontend/src/components/features/budgets/budgets-tabs.tsx b/frontend/src/components/features/budgets/budgets-tabs.tsxnew file mode 100644index 0000000000..60cb911b4b--- /dev/null+++ b/frontend/src/components/features/budgets/budgets-tabs.tsx@@ -0,0 +1,740 @@+/* eslint-disable i18next/no-literal-string */+import React from "react";+import { Link } from "react-router";+import {+ EmailIcon,+ HashIcon,+ SearchIcon,+ SlackIcon,+ TrashIcon,+} from "#/components/shared/icons/inline-icons";+import {+ Avatar,+ PillBadge,+ SpendMeter,+ StatusPill,+ Toggle,+ UserProgressBar,+} from "./budgets-components";++export type BudgetThreshold = {+ percentage: number;+ email_enabled: boolean;+ slack_enabled: boolean;+};++export type BudgetUserRow = {+ user_id: string;+ name: string;+ email: string;+ is_override: boolean;+ is_disabled: boolean;+ effective_monthly_limit?: number | null;+ budgetLabel: string;+ budgetNote: string;+ hasLimit: boolean;+ usage: number;+ maxUsage: number;+ status: string;+ statusColor: "green" | "yellow" | "red";+};++interface OrganizationBudgetTabProps {+ orgBudgetEnabled: boolean;+ onToggleOrgBudget: (value: boolean) => void;+ currentSpend: number;+ monthlyLimitValue: number | null;+ cycleLabel: string;+ percentage: number;+ monthlyLimit: string;+ onMonthlyLimitChange: (value: string) => void;+ billingCycle: string;+ onBillingCycleChange: (value: string) => void;+ thresholds: BudgetThreshold[];+ onAddThreshold: () => void;+ onDeleteThreshold: (index: number) => void;+ onToggleEmail: (index: number) => void;+ onToggleSlack: (index: number) => void;+ emailIntegrationEnabled: boolean;+ slackIntegrationEnabled: boolean;+ slackChannel: string;+ onSlackChannelChange: (value: string) => void;+ onReset: () => void;+ onSave: () => void;+ isSaving: boolean;+ isMonthlyLimitValid: boolean;+}++export function OrganizationBudgetTab({+ orgBudgetEnabled,+ onToggleOrgBudget,+ currentSpend,+ monthlyLimitValue,+ cycleLabel,+ percentage,+ monthlyLimit,+ onMonthlyLimitChange,+ billingCycle,+ onBillingCycleChange,+ thresholds,+ onAddThreshold,+ onDeleteThreshold,+ onToggleEmail,+ onToggleSlack,+ emailIntegrationEnabled,+ slackIntegrationEnabled,+ slackChannel,+ onSlackChannelChange,+ onReset,+ onSave,+ isSaving,+ isMonthlyLimitValid,+}: OrganizationBudgetTabProps) {+ return (+ <div className="bg-[#151D2A] border border-[#262626] rounded-lg p-6">+ <div className="flex items-start justify-between mb-6">+ <div>+ <h2 className="text-lg font-medium text-white mb-1">+ Organization monthly budget+ </h2>+ <p className="text-sm text-[#8C8C8C]">+ Track total spend across your org and get alerted before you hit+ your cap.+ </p>+ </div>+ <div className="flex items-center gap-3">+ <span className="text-sm text-[#8C8C8C]">Enable budget</span>+ <Toggle+ enabled={orgBudgetEnabled}+ onChange={onToggleOrgBudget}+ label="Enable organization budget"+ />+ </div>+ </div>++ <div className="mb-6">+ <div className="flex items-baseline justify-between mb-3">+ <div>+ <span className="text-3xl font-bold text-white">+ {`$${currentSpend.toLocaleString("en-US", {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })}`}+ </span>+ <span className="text-[#8C8C8C] ml-2">+ {monthlyLimitValue+ ? `of $${monthlyLimitValue.toLocaleString()} spent in ${cycleLabel}`+ : `spent in ${cycleLabel}`}+ </span>+ </div>+ <span className="text-xl font-semibold text-yellow-400">+ {monthlyLimitValue ? `${percentage.toFixed(1)}%` : "—"}+ </span>+ </div>+ <SpendMeter percentage={percentage} />+ </div>++ <div className="grid grid-cols-2 gap-4 mb-6">+ <div>+ <label+ htmlFor="org-monthly-limit"+ className="block text-sm text-[#8C8C8C] mb-2"+ >+ Monthly limit+ </label>+ <div className="relative">+ <span className="absolute left-3 top-1/2 -translate-y-1/2 text-[#6B6B6B]">+ $+ </span>+ <input+ id="org-monthly-limit"+ type="number"+ value={monthlyLimit}+ onChange={(event) => onMonthlyLimitChange(event.target.value)}+ className="w-full pl-7 pr-4 py-2 bg-[#0B0F17] border border-[#262626] rounded-lg text-white focus:outline-none focus:border-blue-500"+ />+ </div>+ </div>+ <div>+ <label+ htmlFor="org-billing-cycle"+ className="block text-sm text-[#8C8C8C] mb-2"+ >+ Billing cycle resets+ </label>+ <select+ id="org-billing-cycle"+ value={billingCycle}+ onChange={(event) => onBillingCycleChange(event.target.value)}+ className="w-full px-4 py-2 bg-[#0B0F17] border border-[#262626] rounded-lg text-white focus:outline-none focus:border-blue-500"+ >+ <option value="1st">1st of each month</option>+ <option value="15th">15th of each month</option>+ </select>+ </div>+ </div>++ <div className="mb-6">+ <div className="flex items-center justify-between mb-3">+ <div>+ <h3 className="text-sm font-medium text-white mb-1">+ Alert thresholds+ </h3>+ <p className="text-xs text-[#6B6B6B]">+ Add one or more thresholds. Each can email admins, post to Slack,+ or both.+ </p>+ {(!emailIntegrationEnabled || !slackIntegrationEnabled) && (+ <div className="mt-2 space-y-1 text-xs text-amber-400">+ {!emailIntegrationEnabled && (+ <p>+ Email alerts require RESEND_API_KEY set in the deployment+ environment and a restart.+ </p>+ )}+ {!slackIntegrationEnabled && (+ <p>+ Slack alerts require the Slack app to be configured in the+ deployment (SLACK_* env vars). After a restart, connect it+ in{" "}+ <Link+ to="/settings/integrations"+ className="underline underline-offset-2"+ >+ Settings → Integrations+ </Link>+ .+ </p>+ )}+ </div>+ )}+ </div>+ <button+ type="button"+ onClick={onAddThreshold}+ className="px-3 py-1.5 text-sm text-blue-400 border border-blue-400/30 rounded-lg hover:bg-blue-500/10 transition-colors"+ >+ + Add threshold+ </button>+ </div>++ <div className="space-y-3">+ {thresholds.map((threshold, index) => {+ const thresholdAmount = monthlyLimitValue+ ? (monthlyLimitValue * threshold.percentage) / 100+ : null;+ return (+ <div+ key={threshold.percentage}+ className="flex items-center gap-4 p-3 bg-[#0B0F17] rounded-lg border border-[#262626]"+ >+ <div className="w-16">+ <span className="text-white font-medium">+ {threshold.percentage}%+ </span>+ </div>+ <div className="w-28">+ <span className="text-[#8C8C8C] text-sm">+ {thresholdAmount !== null+ ? `Triggers at $${thresholdAmount.toLocaleString()}`+ : "Set a monthly limit to calculate"}+ </span>+ </div>+ <div className="flex items-center gap-2 flex-1">+ <button+ type="button"+ onClick={() => onToggleEmail(index)}+ disabled={!emailIntegrationEnabled}+ className="flex items-center gap-1.5 disabled:cursor-not-allowed"+ title={+ emailIntegrationEnabled+ ? "Email org admins"+ : "Email alerts require RESEND_API_KEY in deployment (restart required)"+ }+ >+ <PillBadge+ active={+ emailIntegrationEnabled && threshold.email_enabled+ }+ icon={<EmailIcon />}+ label="Email org admins"+ disabled={!emailIntegrationEnabled}+ />+ </button>+ <button+ type="button"+ onClick={() => onToggleSlack(index)}+ disabled={!slackIntegrationEnabled}+ className="flex items-center gap-1.5 disabled:cursor-not-allowed"+ title={+ slackIntegrationEnabled+ ? "Post to Slack"+ : "Slack integration must be configured in deployment (restart required)"+ }+ >+ <PillBadge+ active={+ slackIntegrationEnabled && threshold.slack_enabled+ }+ icon={<SlackIcon />}+ label="# Post to Slack"+ disabled={!slackIntegrationEnabled}+ />+ </button>+ </div>+ <button+ type="button"+ onClick={() => onDeleteThreshold(index)}+ aria-label={`Delete ${threshold.percentage}% threshold`}+ className="p-1.5 text-[#6B6B6B] hover:text-red-400 hover:bg-red-500/10 rounded transition-colors"+ >+ <TrashIcon />+ </button>+ </div>+ );+ })}+ </div>+ </div>++ <div className="mb-6 p-4 bg-[#0B0F17] rounded-lg border border-[#262626]">+ <label+ htmlFor="slack-channel"+ className="block text-sm text-[#8C8C8C] mb-2"+ >+ Slack channel+ </label>+ <div className="relative">+ <span className="absolute left-3 top-1/2 -translate-y-1/2 text-[#6B6B6B]">+ <HashIcon />+ </span>+ <input+ id="slack-channel"+ type="text"+ value={slackChannel}+ onChange={(event) => {+ if (!slackIntegrationEnabled) return;+ onSlackChannelChange(event.target.value);+ }}+ disabled={!slackIntegrationEnabled}+ placeholder={+ slackIntegrationEnabled+ ? "#budget-alerts"+ : "Connect Slack to set a channel"+ }+ className="w-full pl-9 pr-4 py-2 bg-[#151D2A] border border-[#262626] rounded-lg text-white focus:outline-none focus:border-blue-500 disabled:opacity-60 disabled:cursor-not-allowed"+ />+ </div>+ {slackIntegrationEnabled ? (+ <p className="text-xs text-[#6B6B6B] mt-2">+ Used by any threshold with 'Post to Slack' enabled.+ </p>+ ) : (+ <p className="text-xs text-amber-400 mt-2">+ Slack alerts are disabled. Please integrate Slack to select a+ channel.+ </p>+ )}+ </div>++ <div className="flex justify-end gap-3">+ <button+ type="button"+ onClick={onReset}+ className="px-4 py-2 text-sm text-[#8C8C8C] bg-[#0B0F17] border border-[#262626] rounded-lg hover:bg-[#1E1E1E] transition-colors"+ >+ Reset+ </button>+ <button+ type="button"+ onClick={onSave}+ disabled={isSaving || !isMonthlyLimitValid}+ className="px-4 py-2 text-sm text-white bg-blue-500 rounded-lg hover:bg-blue-600 transition-colors disabled:opacity-60"+ >+ Save changes+ </button>+ </div>+ </div>+ );+}++interface DefaultBudgetsTabProps {+ defaultAmount: string;+ defaultAmountLabel: string;+ onDefaultAmountChange: (value: string) => void;+ onSave: () => void;+ isSaving: boolean;+}++export function DefaultBudgetsTab({+ defaultAmount,+ defaultAmountLabel,+ onDefaultAmountChange,+ onSave,+ isSaving,+}: DefaultBudgetsTabProps) {+ return (+ <div className="bg-[#151D2A] border border-[#262626] rounded-lg p-6">+ <div className="mb-6">+ <h2 className="text-lg font-medium text-white mb-1">+ Default budget for new users+ </h2>+ <p className="text-sm text-[#8C8C8C]">+ Applied automatically when a user joins your organization. Existing+ users keep their current budgets.+ </p>+ </div>++ <div className="grid grid-cols-2 gap-6">+ <div>+ <div className="block text-sm text-[#8C8C8C] mb-2">+ Budget cadence+ </div>+ <div className="px-4 py-2 bg-[#0B0F17] border border-[#262626] rounded-lg text-sm text-white">+ Monthly+ </div>+ </div>+ <div>+ <label+ htmlFor="default-budget-amount"+ className="block text-sm text-[#8C8C8C] mb-2"+ >+ Default amount+ </label>+ <div className="relative">+ <span className="absolute left-3 top-1/2 -translate-y-1/2 text-[#6B6B6B]">+ $+ </span>+ <input+ id="default-budget-amount"+ type="number"+ value={defaultAmount}+ onChange={(event) => onDefaultAmountChange(event.target.value)}+ className="w-full pl-7 pr-4 py-2 bg-[#0B0F17] border border-[#262626] rounded-lg text-white focus:outline-none focus:border-blue-500"+ />+ </div>+ </div>+ </div>++ <div className="mt-6">+ <div className="block text-sm text-[#8C8C8C] mb-2">Preview</div>+ <div className="p-4 bg-[#0B0F17] rounded-lg border border-[#262626]">+ <p className="text-sm text-[#8C8C8C]">+ {`New users get up to $${defaultAmountLabel} per month before requiring an increase.`}+ </p>+ </div>+ </div>++ <div className="flex justify-end mt-6">+ <button+ type="button"+ onClick={onSave}+ disabled={isSaving}+ className="px-4 py-2 text-sm text-white bg-blue-500 rounded-lg hover:bg-blue-600 transition-colors disabled:opacity-60"+ >+ Save default+ </button>+ </div>+ </div>+ );+}++interface UserOverridesTabProps {+ searchQuery: string;+ statusFilter: string;+ onSearchChange: (value: string) => void;+ onStatusFilterChange: (value: string) => void;+ userRows: BudgetUserRow[];+ editingUserId: string | null;+ overrideAmount: string;+ overrideDisabled: boolean;+ onOverrideAmountChange: (value: string) => void;+ onOverrideDisabledChange: (value: boolean) => void;+ onStartEditing: (user: BudgetUserRow) => void;+ onCancelEditing: () => void;+ onSaveOverride: (userId: string) => void;+ onRemoveOverride: (userId: string) => void;+ isSavingOverride: boolean;+ isDeletingOverride: boolean;+ usersTotal: number;+ usersStart: number;+ usersEnd: number;+ usersPage: number;+ totalPages: number;+ isLoading: boolean;+ onPageChange: (page: number) => void;+}++export function UserOverridesTab({+ searchQuery,+ statusFilter,+ onSearchChange,+ onStatusFilterChange,+ userRows,+ editingUserId,+ overrideAmount,+ overrideDisabled,+ onOverrideAmountChange,+ onOverrideDisabledChange,+ onStartEditing,+ onCancelEditing,+ onSaveOverride,+ onRemoveOverride,+ isSavingOverride,+ isDeletingOverride,+ usersTotal,+ usersStart,+ usersEnd,+ usersPage,+ totalPages,+ isLoading,+ onPageChange,+}: UserOverridesTabProps) {+ return (+ <div className="bg-[#151D2A] border border-[#262626] rounded-lg p-6">+ <div className="flex items-start justify-between mb-6">+ <div>+ <h2 className="text-lg font-medium text-white mb-1">+ User budget overrides+ </h2>+ <p className="text-sm text-[#8C8C8C]">+ Override the default for individual users — increase, decrease, or+ disable.+ </p>+ </div>+ </div>++ <div className="flex gap-4 mb-6">+ <div className="relative flex-1">+ <span className="absolute left-3 top-1/2 -translate-y-1/2 text-[#6B6B6B]">+ <SearchIcon />+ </span>+ <input+ type="text"+ placeholder="Search users by name or email..."+ value={searchQuery}+ onChange={(event) => onSearchChange(event.target.value)}+ className="w-full pl-10 pr-4 py-2 bg-[#0B0F17] border border-[#262626] rounded-lg text-white placeholder-[#6B6B6B] focus:outline-none focus:border-blue-500"+ />+ </div>+ <select+ value={statusFilter}+ onChange={(event) => onStatusFilterChange(event.target.value)}+ className="px-4 py-2 bg-[#0B0F17] border border-[#262626] rounded-lg text-white focus:outline-none focus:border-blue-500"+ >+ <option value="all">All statuses</option>+ <option value="over80">Over 80%</option>+ <option value="over90">Over 90%</option>+ <option value="overCap">Over cap</option>+ <option value="onTrack">On track</option>+ <option value="noCap">No cap</option>+ <option value="disabled">Disabled</option>+ </select>+ </div>++ <div className="overflow-x-auto">+ <table className="w-full">+ <thead>+ <tr className="border-b border-[#262626]">+ <th className="px-4 py-3 text-left text-xs font-medium text-[#6B6B6B] uppercase tracking-wider">+ User+ </th>+ <th className="px-4 py-3 text-left text-xs font-medium text-[#6B6B6B] uppercase tracking-wider">+ Budget+ </th>+ <th className="px-4 py-3 text-left text-xs font-medium text-[#6B6B6B] uppercase tracking-wider">+ Usage+ </th>+ <th className="px-4 py-3 text-left text-xs font-medium text-[#6B6B6B] uppercase tracking-wider">+ Status+ </th>+ <th className="px-4 py-3 text-right text-xs font-medium text-[#6B6B6B] uppercase tracking-wider">+ Actions+ </th>+ </tr>+ </thead>+ <tbody>+ {userRows.map((user) => {+ const isEditing = editingUserId === user.user_id;+ const overrideValue = Number(overrideAmount);+ const canSaveOverride =+ overrideDisabled ||+ (!!overrideAmount &&+ !Number.isNaN(overrideValue) &&+ overrideValue > 0);++ return (+ <tr+ key={user.user_id}+ className="border-b border-[#262626] hover:bg-[#1E1E1E]/50 transition-colors"+ >+ <td className="px-4 py-4">+ <div className="flex items-center gap-3">+ <Avatar name={user.name} />+ <div>+ <div className="text-white font-medium">+ {user.name}+ </div>+ <div className="text-sm text-[#6B6B6B]">+ {user.email || "-"}+ </div>+ </div>+ </div>+ </td>+ <td className="px-4 py-4">+ {isEditing ? (+ <div className="space-y-2">+ <div className="flex items-center gap-2">+ <span className="text-[#6B6B6B]">$</span>+ <input+ type="number"+ min="0"+ step="0.01"+ value={overrideAmount}+ onChange={(event) =>+ onOverrideAmountChange(event.target.value)+ }+ disabled={overrideDisabled}+ className="w-28 px-2 py-1 bg-[#0B0F17] border border-[#262626] rounded text-white focus:outline-none focus:border-blue-500 disabled:opacity-60"+ />+ <span className="text-xs text-[#6B6B6B]">+ / month+ </span>+ </div>+ <label className="flex items-center gap-2 text-xs text-[#8C8C8C]">+ <input+ type="checkbox"+ checked={overrideDisabled}+ onChange={(event) =>+ onOverrideDisabledChange(event.target.checked)+ }+ className="accent-blue-500"+ />+ Disable budget for this user+ </label>+ </div>+ ) : (+ <>+ <div className="text-white">{user.budgetLabel}</div>+ <div className="flex items-center gap-1.5 text-xs text-[#6B6B6B]">+ {user.is_override && (+ <span className="w-1.5 h-1.5 rounded-full bg-blue-400" />+ )}+ {user.budgetNote}+ </div>+ </>+ )}+ </td>+ <td className="px-4 py-4 min-w-[180px]">+ {user.hasLimit ? (+ <div>+ <UserProgressBar+ value={user.usage}+ max={user.maxUsage}+ status={user.statusColor}+ />+ <div className="mt-1 text-xs text-[#6B6B6B]">+ {`$${user.usage.toLocaleString("en-US", {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })} of $${user.maxUsage.toLocaleString("en-US", {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })}`}+ </div>+ </div>+ ) : (+ <div className="text-sm text-[#8C8C8C]">+ {`$${user.usage.toLocaleString("en-US", {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })} spent`}+ </div>+ )}+ </td>+ <td className="px-4 py-4">+ <StatusPill status={user.status} />+ </td>+ <td className="px-4 py-4 text-right">+ {isEditing ? (+ <div className="flex items-center justify-end gap-2">+ <button+ type="button"+ onClick={() => onSaveOverride(user.user_id)}+ disabled={!canSaveOverride || isSavingOverride}+ className="px-3 py-1.5 text-sm text-white bg-blue-500 rounded hover:bg-blue-600 transition-colors disabled:opacity-60"+ >+ Save+ </button>+ <button+ type="button"+ onClick={onCancelEditing}+ className="px-3 py-1.5 text-sm text-[#8C8C8C] hover:text-white hover:bg-[#262626] rounded transition-colors"+ >+ Cancel+ </button>+ </div>+ ) : (+ <div className="flex items-center justify-end gap-2">+ <button+ type="button"+ onClick={() => onStartEditing(user)}+ className="px-3 py-1.5 text-sm text-[#8C8C8C] hover:text-white hover:bg-[#262626] rounded transition-colors"+ >+ Edit+ </button>+ {user.is_override && (+ <button+ type="button"+ onClick={() => onRemoveOverride(user.user_id)}+ disabled={isDeletingOverride}+ aria-label={`Remove override for ${user.name}`}+ className="p-1.5 text-[#6B6B6B] hover:text-red-400 hover:bg-red-500/10 rounded transition-colors disabled:opacity-60"+ >+ <TrashIcon />+ </button>+ )}+ </div>+ )}+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>++ {usersTotal > 0 && (+ <div className="mt-4 flex flex-col gap-3 text-sm text-[#6B6B6B] sm:flex-row sm:items-center sm:justify-between">+ <span>{`Showing ${usersStart}-${usersEnd} of ${usersTotal}`}</span>+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={() => onPageChange(Math.max(1, usersPage - 1))}+ disabled={usersPage <= 1 || isLoading}+ className="px-3 py-1.5 text-sm text-[#8C8C8C] hover:text-white hover:bg-[#262626] rounded transition-colors disabled:opacity-60"+ >+ Previous+ </button>+ <span className="text-xs text-[#6B6B6B]">+ {`${usersPage} / ${totalPages}`}+ </span>+ <button+ type="button"+ onClick={() => onPageChange(Math.min(totalPages, usersPage + 1))}+ disabled={usersPage >= totalPages || isLoading}+ className="px-3 py-1.5 text-sm text-[#8C8C8C] hover:text-white hover:bg-[#262626] rounded transition-colors disabled:opacity-60"+ >+ Next+ </button>+ </div>+ </div>+ )}++ {userRows.length === 0 && (+ <div className="py-12 text-center text-[#6B6B6B]">+ No users found matching your criteria.+ </div>+ )}+ </div>+ );+}diff --git a/frontend/src/components/features/budgets/budgets.tsx b/frontend/src/components/features/budgets/budgets.tsxnew file mode 100644index 0000000000..87bc811400--- /dev/null+++ b/frontend/src/components/features/budgets/budgets.tsx@@ -0,0 +1,465 @@+/* eslint-disable i18next/no-literal-string */+import React, { useEffect, useMemo, useState } from "react";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { organizationService } from "#/api/organization-service/organization-service.api";+import { useSelectedOrganizationId } from "#/context/use-selected-organization";+import { useConfig } from "#/hooks/query/use-config";+import { useDebounce } from "#/hooks/use-debounce";+import { BUDGET_TABS, BudgetTab, USERS_PER_PAGE } from "./budgets-constants";+import {+ DefaultBudgetsTab,+ OrganizationBudgetTab,+ UserOverridesTab,+} from "./budgets-tabs";+import type { BudgetThreshold, BudgetUserRow } from "./budgets-tabs";++export function Budgets() {+ const { organizationId } = useSelectedOrganizationId();+ const queryClient = useQueryClient();++ const { data: config } = useConfig();+ const slackIntegrationEnabled = Boolean(config?.slack_enabled);+ const [usersPage, setUsersPage] = useState(1);++ const emailIntegrationEnabled = Boolean(config?.email_enabled);++ const [activeTab, setActiveTab] = useState<BudgetTab>("organization");++ const [searchQuery, setSearchQuery] = useState("");+ const debouncedSearchQuery = useDebounce(searchQuery, 300);+ const [statusFilter, setStatusFilter] = useState("all");+ const usersSearch = debouncedSearchQuery.trim();+ const usersStatus = statusFilter === "all" ? undefined : statusFilter;++ const { data: budgetData, isLoading } = useQuery({+ queryKey: [+ "organizations",+ "budgets",+ organizationId,+ usersPage,+ usersSearch,+ usersStatus,+ ],+ queryFn: () =>+ organizationService.getBudgetSettings({+ orgId: organizationId!,+ usersPage,+ usersPerPage: USERS_PER_PAGE,+ usersSearch: usersSearch || undefined,+ usersStatus,+ }),+ enabled: !!organizationId,+ });++ useEffect(() => {+ setUsersPage(1);+ }, [organizationId]);++ useEffect(() => {+ setUsersPage(1);+ }, [debouncedSearchQuery, statusFilter]);++ const updateBudgets = useMutation({+ mutationFn: (payload: {+ enabled?: boolean | null;+ monthly_limit?: number | null;+ reset_day?: number | null;+ default_user_monthly_limit?: number | null;+ slack_channel?: string | null;+ slack_team_id?: string | null;+ thresholds?:+ | {+ percentage: number;+ email_enabled: boolean;+ slack_enabled: boolean;+ }[]+ | null;+ }) =>+ organizationService.updateBudgetSettings({+ orgId: organizationId!,+ payload,+ }),+ onSuccess: () =>+ queryClient.invalidateQueries({+ queryKey: ["organizations", "budgets", organizationId],+ }),+ });++ const upsertOverride = useMutation({+ mutationFn: (params: {+ userId: string;+ payload: { monthly_limit?: number | null; is_disabled: boolean };+ }) =>+ organizationService.upsertBudgetOverride({+ orgId: organizationId!,+ userId: params.userId,+ payload: params.payload,+ }),+ onSuccess: () =>+ queryClient.invalidateQueries({+ queryKey: ["organizations", "budgets", organizationId],+ }),+ });++ const deleteOverride = useMutation({+ mutationFn: (userId: string) =>+ organizationService.deleteBudgetOverride({+ orgId: organizationId!,+ userId,+ }),+ onSuccess: () =>+ queryClient.invalidateQueries({+ queryKey: ["organizations", "budgets", organizationId],+ }),+ });++ const [orgBudgetEnabled, setOrgBudgetEnabled] = useState(false);+ const [monthlyLimit, setMonthlyLimit] = useState("");+ const [billingCycle, setBillingCycle] = useState("1st");+ const [slackChannel, setSlackChannel] = useState("");+ const [thresholds, setThresholds] = useState<BudgetThreshold[]>([]);+ const [defaultAmount, setDefaultAmount] = useState("");+ const [editingUserId, setEditingUserId] = useState<string | null>(null);+ const [overrideAmount, setOverrideAmount] = useState("");+ const [overrideDisabled, setOverrideDisabled] = useState(false);++ useEffect(() => {+ if (!budgetData) return;+ setOrgBudgetEnabled(budgetData.enabled);+ setMonthlyLimit(+ budgetData.monthly_limit ? budgetData.monthly_limit.toString() : "",+ );+ setBillingCycle(budgetData.reset_day === 15 ? "15th" : "1st");+ setSlackChannel(budgetData.slack_channel ?? "");+ setThresholds(+ budgetData.thresholds.map((threshold) => ({+ percentage: threshold.percentage,+ email_enabled: threshold.email_enabled,+ slack_enabled: threshold.slack_enabled,+ })),+ );+ setDefaultAmount(+ budgetData.default_user_monthly_limit+ ? budgetData.default_user_monthly_limit.toString()+ : "",+ );+ }, [budgetData]);++ const monthlyLimitValue = monthlyLimit ? Number(monthlyLimit) : null;+ const isMonthlyLimitValid =+ !orgBudgetEnabled ||+ (typeof monthlyLimitValue === "number" && monthlyLimitValue > 0);++ const currentSpend = budgetData?.current_spend ?? 0;+ const percentage = budgetData?.current_spend_percentage ?? 0;+ const cycleLabel = budgetData?.cycle_start_at+ ? new Date(budgetData.cycle_start_at).toLocaleDateString("en-US", {+ month: "long",+ })+ : "this cycle";+ const defaultUserLimit = budgetData?.default_user_monthly_limit ?? null;++ const usersTotal = budgetData?.users_total ?? 0;+ const usersPerPage = budgetData?.users_per_page ?? USERS_PER_PAGE;+ const totalPages = Math.max(1, Math.ceil(usersTotal / usersPerPage));+ const usersStart = usersTotal === 0 ? 0 : (usersPage - 1) * usersPerPage + 1;+ const usersEnd =+ usersTotal === 0 ? 0 : usersStart + (budgetData?.users.length ?? 0) - 1;++ useEffect(() => {+ if (usersPage > totalPages) {+ setUsersPage(totalPages);+ }+ }, [totalPages, usersPage]);++ const defaultAmountLabel = defaultAmount+ ? parseFloat(defaultAmount).toLocaleString()+ : "0";++ const handleReset = () => {+ if (!budgetData) return;+ setOrgBudgetEnabled(budgetData.enabled);+ setMonthlyLimit(+ budgetData.monthly_limit ? budgetData.monthly_limit.toString() : "",+ );+ setBillingCycle(budgetData.reset_day === 15 ? "15th" : "1st");+ setSlackChannel(budgetData.slack_channel ?? "");+ setThresholds(+ budgetData.thresholds.map((threshold) => ({+ percentage: threshold.percentage,+ email_enabled: threshold.email_enabled,+ slack_enabled: threshold.slack_enabled,+ })),+ );+ setDefaultAmount(+ budgetData.default_user_monthly_limit+ ? budgetData.default_user_monthly_limit.toString()+ : "",+ );+ };++ const handleSaveOrgBudget = () => {+ if (!organizationId || !isMonthlyLimitValid) return;+ updateBudgets.mutate({+ enabled: orgBudgetEnabled,+ monthly_limit: monthlyLimitValue,+ reset_day: billingCycle === "15th" ? 15 : 1,+ slack_channel: slackIntegrationEnabled+ ? slackChannel.trim() || null+ : null,+ thresholds: thresholds.map((threshold) => ({+ percentage: threshold.percentage,+ email_enabled: emailIntegrationEnabled+ ? threshold.email_enabled+ : false,+ slack_enabled: slackIntegrationEnabled+ ? threshold.slack_enabled+ : false,+ })),+ });+ };++ const handleSaveDefault = () => {+ if (!organizationId) return;+ const defaultValue = defaultAmount ? Number(defaultAmount) : null;+ updateBudgets.mutate({+ default_user_monthly_limit: defaultValue,+ });+ };++ const handleAddThreshold = () => {+ const used = new Set(thresholds.map((t) => t.percentage));+ const candidates = [50, 60, 70, 75, 85, 95];+ const next = candidates.find((value) => !used.has(value));+ if (!next) return;+ setThresholds((prev) =>+ [+ ...prev,+ { percentage: next, email_enabled: true, slack_enabled: false },+ ].sort((a, b) => a.percentage - b.percentage),+ );+ };++ const handleDeleteThreshold = (index: number) => {+ setThresholds(thresholds.filter((_, i) => i !== index));+ };++ const handleToggleEmail = (index: number) => {+ if (!emailIntegrationEnabled) return;+ setThresholds(+ thresholds.map((t, i) =>+ i === index ? { ...t, email_enabled: !t.email_enabled } : t,+ ),+ );+ };++ const handleToggleSlack = (index: number) => {+ if (!slackIntegrationEnabled) return;+ setThresholds(+ thresholds.map((t, i) =>+ i === index ? { ...t, slack_enabled: !t.slack_enabled } : t,+ ),+ );+ };++ const userRows = useMemo(+ () =>+ (budgetData?.users ?? []).map((user) => {+ const limit = user.is_disabled ? null : user.effective_monthly_limit;+ const hasLimit = typeof limit === "number" && limit > 0;+ const usagePercent = hasLimit ? (user.current_spend / limit) * 100 : 0;+ let status = "No cap";+ let statusColor: "green" | "yellow" | "red" = "green";++ if (user.is_disabled) {+ status = "Disabled";+ } else if (hasLimit) {+ if (usagePercent > 100) {+ status = "Over cap";+ statusColor = "red";+ } else if (usagePercent >= 90) {+ status = "> 90% used";+ statusColor = "red";+ } else if (usagePercent >= 80) {+ status = "> 80% used";+ statusColor = "yellow";+ } else {+ status = "On track";+ statusColor = "green";+ }+ }++ let budgetLabel = "No limit";+ if (user.is_disabled) {+ budgetLabel = "Disabled";+ } else if (hasLimit) {+ budgetLabel = `$${limit.toLocaleString()} / month`;+ }++ let budgetNote = "No default";+ if (user.is_override) {+ budgetNote = "Override";+ } else if (defaultUserLimit) {+ budgetNote = "Inherits default";+ }++ return {+ ...user,+ name: user.user_name || user.user_email || "Unknown user",+ email: user.user_email || "",+ hasLimit,+ budgetLabel,+ budgetNote,+ status,+ statusColor,+ usage: user.current_spend,+ maxUsage: limit ?? 0,+ };+ }),+ [budgetData, defaultUserLimit],+ );++ const startEditingUser = (user: BudgetUserRow) => {+ setEditingUserId(user.user_id);+ setOverrideDisabled(user.is_disabled);+ setOverrideAmount(+ user.effective_monthly_limit+ ? user.effective_monthly_limit.toString()+ : "",+ );+ };++ const cancelEditing = () => {+ setEditingUserId(null);+ setOverrideAmount("");+ setOverrideDisabled(false);+ };++ const saveOverride = (userId: string) => {+ if (!organizationId) return;+ const overrideValue = overrideAmount ? Number(overrideAmount) : null;+ upsertOverride.mutate({+ userId,+ payload: {+ monthly_limit: overrideDisabled ? null : overrideValue,+ is_disabled: overrideDisabled,+ },+ });+ cancelEditing();+ };++ const removeOverride = (userId: string) => {+ if (!organizationId) return;+ deleteOverride.mutate(userId);+ };++ if (!organizationId) {+ return (+ <div className="text-[#8C8C8C]">+ Select an organization to manage budgets.+ </div>+ );+ }++ if (isLoading) {+ return <div className="text-[#8C8C8C]">Loading budgets...</div>;+ }++ return (+ <div className="space-y-8">+ {/* Page Header */}+ <div className="space-y-6">+ <div>+ <h1 className="text-2xl font-semibold text-white mb-1">+ Budget settings+ </h1>+ <p className="text-[#8C8C8C]">+ Control your AI spend at the organization and user level.+ </p>+ </div>+ <div className="flex gap-6 border-b border-[#262626]">+ {BUDGET_TABS.map((tab) => (+ <button+ key={tab.value}+ type="button"+ onClick={() => setActiveTab(tab.value)}+ className={`flex items-center px-1 py-3 text-sm font-medium transition-colors border-b-2 ${+ activeTab === tab.value+ ? "border-blue-500 text-white"+ : "border-transparent text-[#8C8C8C] hover:text-white"+ }`}+ >+ {tab.label}+ </button>+ ))}+ </div>+ </div>++ {activeTab === "organization" && (+ <OrganizationBudgetTab+ orgBudgetEnabled={orgBudgetEnabled}+ onToggleOrgBudget={setOrgBudgetEnabled}+ currentSpend={currentSpend}+ monthlyLimitValue={monthlyLimitValue}+ cycleLabel={cycleLabel}+ percentage={percentage}+ monthlyLimit={monthlyLimit}+ onMonthlyLimitChange={setMonthlyLimit}+ billingCycle={billingCycle}+ onBillingCycleChange={setBillingCycle}+ thresholds={thresholds}+ onAddThreshold={handleAddThreshold}+ onDeleteThreshold={handleDeleteThreshold}+ onToggleEmail={handleToggleEmail}+ onToggleSlack={handleToggleSlack}+ emailIntegrationEnabled={emailIntegrationEnabled}+ slackIntegrationEnabled={slackIntegrationEnabled}+ slackChannel={slackChannel}+ onSlackChannelChange={setSlackChannel}+ onReset={handleReset}+ onSave={handleSaveOrgBudget}+ isSaving={updateBudgets.isPending}+ isMonthlyLimitValid={isMonthlyLimitValid}+ />+ )}++ {activeTab === "defaults" && (+ <DefaultBudgetsTab+ defaultAmount={defaultAmount}+ defaultAmountLabel={defaultAmountLabel}+ onDefaultAmountChange={setDefaultAmount}+ onSave={handleSaveDefault}+ isSaving={updateBudgets.isPending}+ />+ )}++ {activeTab === "overrides" && (+ <UserOverridesTab+ searchQuery={searchQuery}+ statusFilter={statusFilter}+ onSearchChange={setSearchQuery}+ onStatusFilterChange={setStatusFilter}+ userRows={userRows}+ editingUserId={editingUserId}+ overrideAmount={overrideAmount}+ overrideDisabled={overrideDisabled}+ onOverrideAmountChange={setOverrideAmount}+ onOverrideDisabledChange={setOverrideDisabled}+ onStartEditing={startEditingUser}+ onCancelEditing={cancelEditing}+ onSaveOverride={saveOverride}+ onRemoveOverride={removeOverride}+ isSavingOverride={upsertOverride.isPending}+ isDeletingOverride={deleteOverride.isPending}+ usersTotal={usersTotal}+ usersStart={usersStart}+ usersEnd={usersEnd}+ usersPage={usersPage}+ totalPages={totalPages}+ isLoading={isLoading}+ onPageChange={setUsersPage}+ />+ )}+ </div>+ );+}diff --git a/frontend/src/components/features/settings/settings-layout.tsx b/frontend/src/components/features/settings/settings-layout.tsxindex 38d8a2d819..476c8561e9 100644--- a/frontend/src/components/features/settings/settings-layout.tsx+++ b/frontend/src/components/features/settings/settings-layout.tsx@@ -18,14 +18,14 @@ export function SettingsLayout({const closeMobileMenu = () => setIsMobileMenuOpen(false);return (- <div className="flex flex-col h-full min-h-0 px-[14px] pt-8">+ <div className="flex flex-col h-full px-[14px] pt-8">{/* Mobile header */}<MobileHeaderisMobileMenuOpen={isMobileMenuOpen}onToggleMenu={toggleMobileMenu}/>{/* Desktop layout with navigation and main content */}- <div className="flex flex-1 min-h-0 overflow-hidden gap-10">+ <div className="flex flex-1 overflow-hidden gap-10">{/* Navigation */}<SettingsNavigationisMobileMenuOpen={isMobileMenuOpen}@@ -33,7 +33,7 @@ export function SettingsLayout({navigationItems={navigationItems}/>{/* Main content */}- <main className="flex-1 min-w-0 min-h-0 overflow-auto custom-scrollbar-always">+ <main className="flex-1 min-w-0 overflow-auto custom-scrollbar-always">{children}</main></div>diff --git a/frontend/src/components/features/settings/settings-navigation.tsx b/frontend/src/components/features/settings/settings-navigation.tsxindex d973dbf59a..beb1a28e0d 100644--- a/frontend/src/components/features/settings/settings-navigation.tsx+++ b/frontend/src/components/features/settings/settings-navigation.tsx@@ -38,7 +38,7 @@ export function SettingsNavigation({<navdata-testid="settings-navbar"className={cn(- "flex flex-col gap-6 min-h-0 transition-transform duration-300 ease-in-out",+ "flex flex-col gap-6 transition-transform duration-300 ease-in-out",// Mobile: full screen overlay with dark background matching desktop"fixed inset-0 z-50 w-full bg-[#050505] p-4 transform md:transform-none",isMobileMenuOpen ? "translate-x-0" : "-translate-x-full",diff --git a/frontend/src/components/shared/icons/inline-icons.tsx b/frontend/src/components/shared/icons/inline-icons.tsxnew file mode 100644index 0000000000..545bc44fd3--- /dev/null+++ b/frontend/src/components/shared/icons/inline-icons.tsx@@ -0,0 +1,155 @@+/* eslint-disable i18next/no-literal-string */+import React from "react";++export function SearchIcon() {+ return (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ >+ <circle cx="11" cy="11" r="8" />+ <path d="m21 21-4.35-4.35" />+ </svg>+ );+}++export function ExportIcon() {+ return (+ <svg+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ >+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />+ <polyline points="7,10 12,15 17,10" />+ <line x1="12" y1="15" x2="12" y2="3" />+ </svg>+ );+}++export function StopIcon() {+ return (+ <svg+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ >+ <circle cx="12" cy="12" r="10" />+ <rect x="9" y="9" width="6" height="6" />+ </svg>+ );+}++export function TrendUpIcon() {+ return (+ <svg+ width="12"+ height="12"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ >+ <polyline points="23,6 13.5,15.5 8.5,10.5 1,18" />+ <polyline points="17,6 23,6 23,12" />+ </svg>+ );+}++export function TrendDownIcon() {+ return (+ <svg+ width="12"+ height="12"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ >+ <polyline points="23,18 13.5,8.5 8.5,13.5 1,6" />+ <polyline points="17,18 23,18 23,12" />+ </svg>+ );+}++export function EmailIcon() {+ return (+ <svg+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ >+ <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" />+ <polyline points="22,6 12,13 2,6" />+ </svg>+ );+}++export function SlackIcon() {+ return (+ <svg+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ >+ <path d="M14.5 10c-.83 0-1.5-.67-1.5-1.5v-5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5v5c0 .83-.67 1.5-1.5 1.5z" />+ <path d="M20.5 10H19V8.5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5-.67 1.5-1.5 1.5z" />+ <path d="M9.5 14c.83 0 1.5.67 1.5 1.5v5c0 .83-.67 1.5-1.5 1.5S8 21.33 8 20.5v-5c0-.83.67-1.5 1.5-1.5z" />+ <path d="M3.5 14H5v1.5c0 .83-.67 1.5-1.5 1.5S2 16.33 2 15.5 2.67 14 3.5 14z" />+ <path d="M14 14.5c0-.83.67-1.5 1.5-1.5h5c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5h-5c-.83 0-1.5-.67-1.5-1.5z" />+ <path d="M15.5 19H14v1.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5-.67-1.5-1.5-1.5z" />+ <path d="M10 9.5C10 8.67 9.33 8 8.5 8h-5C2.67 8 2 8.67 2 9.5S2.67 11 3.5 11h5c.83 0 1.5-.67 1.5-1.5z" />+ <path d="M8.5 5H10V3.5C10 2.67 9.33 2 8.5 2S7 2.67 7 3.5 7.67 5 8.5 5z" />+ </svg>+ );+}++export function TrashIcon() {+ return (+ <svg+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ >+ <polyline points="3,6 5,6 21,6" />+ <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />+ </svg>+ );+}++export function HashIcon() {+ return (+ <svg+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ >+ <line x1="4" y1="9" x2="20" y2="9" />+ <line x1="4" y1="15" x2="20" y2="15" />+ <line x1="10" y1="3" x2="8" y2="21" />+ <line x1="16" y1="3" x2="14" y2="21" />+ </svg>+ );+}diff --git a/frontend/src/constants/settings-nav.tsx b/frontend/src/constants/settings-nav.tsxindex d5f4c1a389..2edc074cbf 100644--- a/frontend/src/constants/settings-nav.tsx+++ b/frontend/src/constants/settings-nav.tsx@@ -1,4 +1,9 @@-import { FiUsers, FiBriefcase, FiBarChart2 } from "react-icons/fi";+import {+ FiUsers,+ FiBriefcase,+ FiBarChart2,+ FiDollarSign,+} from "react-icons/fi";import CreditCardIcon from "#/icons/credit-card.svg?react";import KeyIcon from "#/icons/key.svg?react";import LightbulbIcon from "#/icons/lightbulb.svg?react";@@ -53,6 +58,12 @@ export const SAAS_NAV_ITEMS: SettingsNavItem[] = [text: "SETTINGS$NAV_ADMIN_DASHBOARD",section: "org",},+ {+ icon: <FiDollarSign size={22} />,+ to: "/settings/budgets",+ text: "SETTINGS$NAV_BUDGETS",+ section: "org",+ },{icon: <CircuitIcon width={22} height={22} />,to: "/settings/org-defaults",diff --git a/frontend/src/hooks/query/use-org-usage-stats.ts b/frontend/src/hooks/query/use-org-usage-stats.tsindex 95be794812..dcde98e0fa 100644--- a/frontend/src/hooks/query/use-org-usage-stats.ts+++ b/frontend/src/hooks/query/use-org-usage-stats.ts@@ -4,15 +4,28 @@ import { useSelectedOrganizationId } from "#/context/use-selected-organization";interface UseOrgUsageStatsParams {days?: number;+ timeWindow?: string;}-export const useOrgUsageStats = ({ days = 7 }: UseOrgUsageStatsParams = {}) => {+export const useOrgUsageStats = ({+ days,+ timeWindow,+}: UseOrgUsageStatsParams = {}) => {const { organizationId } = useSelectedOrganizationId();-return useQuery({- queryKey: ["organizations", "usage-stats", organizationId, days],+ queryKey: [+ "organizations",+ "usage-stats",+ organizationId,+ days ?? null,+ timeWindow ?? null,+ ],queryFn: () =>- organizationService.getUsageStats({ orgId: organizationId!, days }),+ organizationService.getUsageStats({+ orgId: organizationId!,+ days,+ timeWindow,+ }),enabled: !!organizationId,});};diff --git a/frontend/src/hooks/query/use-org-user-usage.ts b/frontend/src/hooks/query/use-org-user-usage.tsnew file mode 100644index 0000000000..245e46ef29--- /dev/null+++ b/frontend/src/hooks/query/use-org-user-usage.ts@@ -0,0 +1,24 @@+import { useQuery } from "@tanstack/react-query";+import { organizationService } from "#/api/organization-service/organization-service.api";+import { useSelectedOrganizationId } from "#/context/use-selected-organization";++export const useOrgUserUsage = ({+ limit,+ offset,+}: {+ limit?: number;+ offset?: number;+} = {}) => {+ const { organizationId } = useSelectedOrganizationId();++ return useQuery({+ queryKey: ["organizations", "user-usage", organizationId, limit, offset],+ queryFn: () =>+ organizationService.getUserUsageStats({+ orgId: organizationId!,+ limit,+ offset,+ }),+ enabled: !!organizationId,+ });+};diff --git a/frontend/src/hooks/use-settings-nav-items.ts b/frontend/src/hooks/use-settings-nav-items.tsindex 1091bf0872..e06d7fdee5 100644--- a/frontend/src/hooks/use-settings-nav-items.ts+++ b/frontend/src/hooks/use-settings-nav-items.ts@@ -7,7 +7,10 @@ import {} from "#/constants/settings-nav";import { OrganizationUserRole } from "#/types/org";import { isBillingHidden } from "#/utils/org/billing-visibility";-import { isSettingsPageHidden } from "#/utils/settings-utils";+import {+ ADMIN_ONLY_SETTINGS_PATHS,+ isSettingsPageHidden,+} from "#/utils/settings-utils";import { useMe } from "./query/use-me";import { usePermission } from "./organizations/use-permissions";import { useOrgTypeAndAccess } from "./use-org-type-and-access";@@ -90,9 +93,9 @@ export function useSettingsNavItems(): SettingsNavRenderedItem[] {);}- // Hide admin dashboard for non-admins/owners or personal orgs+ // Hide admin-only settings pages for non-admins/owners or personal orgsif (!isAdminOrOwner || !organizationId || isPersonalOrg) {- items = items.filter((item) => item.to !== "/settings/usage-monitoring");+ items = items.filter((item) => !ADMIN_ONLY_SETTINGS_PATHS.has(item.to));}const PERSONAL_LLM_PATHS = new Set([diff --git a/frontend/src/i18n/declaration.ts b/frontend/src/i18n/declaration.tsindex ec9207f8a5..6fa5158acf 100644--- a/frontend/src/i18n/declaration.ts+++ b/frontend/src/i18n/declaration.ts@@ -292,6 +292,7 @@ export enum I18nKey {SETTINGS$NAV_API_KEYS = "SETTINGS$NAV_API_KEYS",SETTINGS$NAV_ORGANIZATION = "SETTINGS$NAV_ORGANIZATION",SETTINGS$NAV_ADMIN_DASHBOARD = "SETTINGS$NAV_ADMIN_DASHBOARD",+ SETTINGS$NAV_BUDGETS = "SETTINGS$NAV_BUDGETS",SETTINGS$NAV_ORG_MEMBERS = "SETTINGS$NAV_ORG_MEMBERS",SETTINGS$ORG_SETTINGS_HEADER = "SETTINGS$ORG_SETTINGS_HEADER",SETTINGS$PERSONAL_SETTINGS_HEADER = "SETTINGS$PERSONAL_SETTINGS_HEADER",diff --git a/frontend/src/i18n/translation.json b/frontend/src/i18n/translation.jsonindex e243c4b0eb..4b2299fa80 100644--- a/frontend/src/i18n/translation.json+++ b/frontend/src/i18n/translation.json@@ -4963,6 +4963,23 @@"uk": "Використання та моніторинг","ca": "Ús i monitoratge"},+ "SETTINGS$NAV_BUDGETS": {+ "en": "Budgets",+ "ja": "予算",+ "zh-CN": "预算",+ "zh-TW": "預算",+ "ko-KR": "예산",+ "no": "Budjetter",+ "it": "Budget",+ "pt": "Orçamentos",+ "es": "Presupuestos",+ "ar": "الميزانيات",+ "fr": "Budgets",+ "tr": "Bütçeler",+ "de": "Budgets",+ "uk": "Бюджети",+ "ca": "Pressupostos"+ },"SETTINGS$NAV_ORG_MEMBERS": {"en": "Org Members","ja": "組織メンバー",diff --git a/frontend/src/routes.ts b/frontend/src/routes.tsindex 40806f7841..0f2f60e6f1 100644--- a/frontend/src/routes.ts+++ b/frontend/src/routes.ts@@ -39,6 +39,7 @@ export default [route("org", "routes/manage-org.tsx"),route("usage-monitoring", "routes/usage-monitoring.tsx"),route("admin-dashboard", "routes/admin-dashboard.tsx"),+ route("budgets", "routes/budgets.tsx"),]),route("conversations/:conversationId", "routes/conversation.tsx"),route("oauth/device/verify", "routes/device-verify.tsx"),diff --git a/frontend/src/routes/budgets.tsx b/frontend/src/routes/budgets.tsxnew file mode 100644index 0000000000..0f371673e4--- /dev/null+++ b/frontend/src/routes/budgets.tsx@@ -0,0 +1,6 @@+import React from "react";+import { Budgets } from "#/components/features/budgets/budgets";++export default function BudgetsPage() {+ return <Budgets />;+}diff --git a/frontend/src/routes/settings.tsx b/frontend/src/routes/settings.tsxindex 49474f0926..bf8c70f519 100644--- a/frontend/src/routes/settings.tsx+++ b/frontend/src/routes/settings.tsx@@ -21,6 +21,7 @@ import { getSelectedOrganizationIdFromStore } from "#/stores/selected-organizatiimport { rolePermissions } from "#/utils/org/permissions";import { isBillingHidden } from "#/utils/org/billing-visibility";import {+ ADMIN_ONLY_SETTINGS_PATHS,isSettingsPageHidden,getFirstAvailablePath,} from "#/utils/settings-utils";@@ -40,6 +41,7 @@ const SAAS_ONLY_PATHS = ["/settings/org-defaults/condenser","/settings/org-defaults/verification","/settings/usage-monitoring",+ "/settings/budgets",];const ORG_WIDE_BADGE_PATHS = new Set<string>([@@ -52,6 +54,8 @@ export const clientLoader = async ({ request }: Route.ClientLoaderArgs) => {const url = new URL(request.url);const { pathname } = url;+ const isAdminOnlyPath = ADMIN_ONLY_SETTINGS_PATHS.has(pathname);+// Step 1: Get config first (needed for all checks, no user data required)const config = await queryClient.fetchQuery<WebClientConfig>({queryKey: QUERY_KEYS.WEB_CLIENT_CONFIG,@@ -116,17 +120,14 @@ export const clientLoader = async ({ request }: Route.ClientLoaderArgs) => {}}- // Step 4: For routes that need permission checks, get user data- // Only fetch user data for billing and org routes that need permission validationif (pathname === "/settings/billing" ||pathname === "/settings/org" ||pathname === "/settings/org-members" ||- pathname === "/settings/usage-monitoring"+ isAdminOnlyPath) {const user = await getActiveOrganizationUser();- // Org-type detection for route protectionconst orgId = getSelectedOrganizationIdFromStore();const organizationsData = queryClient.getQueryData<{items: Organization[];@@ -138,7 +139,6 @@ export const clientLoader = async ({ request }: Route.ClientLoaderArgs) => {const isPersonalOrg = selectedOrg?.is_personal === true;const isTeamOrg = !!selectedOrg && !selectedOrg.is_personal;- // Billing route protectionif (pathname === "/settings/billing") {if (!user ||@@ -155,7 +155,6 @@ export const clientLoader = async ({ request }: Route.ClientLoaderArgs) => {}}- // Org route protection: redirect if user lacks required permissions or personal orgif (pathname === "/settings/org") {const role = user?.role ?? "member";if (@@ -178,8 +177,7 @@ export const clientLoader = async ({ request }: Route.ClientLoaderArgs) => {}}- // Usage & Monitoring route protection: only admins and owners can access- if (pathname === "/settings/usage-monitoring") {+ if (isAdminOnlyPath) {const role = user?.role ?? "member";if (!user || (role !== "admin" && role !== "owner") || isPersonalOrg) {return redirect("/settings");@@ -230,7 +228,7 @@ function SettingsScreen() {return (<main data-testid="settings-screen" className="h-full"><SettingsLayout navigationItems={navItems}>- <div className="flex flex-col gap-6 h-full">+ <div className="flex flex-col gap-6 h-full min-h-0">{!shouldHideTitle && (<div className="flex items-center gap-3 flex-wrap"><Typography.H2>{t(currentSectionTitle)}</Typography.H2>@@ -239,7 +237,7 @@ function SettingsScreen() {)}</div>)}- <div className="flex-1 overflow-auto custom-scrollbar-always">+ <div className="flex-1 min-h-0 overflow-auto custom-scrollbar-always"><Outlet /></div></div>diff --git a/frontend/src/utils/settings-utils.ts b/frontend/src/utils/settings-utils.tsindex 4346a90986..95d734c0fd 100644--- a/frontend/src/utils/settings-utils.ts+++ b/frontend/src/utils/settings-utils.ts@@ -55,6 +55,11 @@ export const extractSettings = (};};+export const ADMIN_ONLY_SETTINGS_PATHS = new Set<string>([+ "/settings/usage-monitoring",+ "/settings/budgets",+]);+/*** Checks if a settings page should be hidden based on feature flags.* Used by both the route loader and navigation hook to keep logic in sync.