From d4ad20f569916e5ccd9b5c9628536639547d8523 Mon Sep 17 00:00:00 2001 From: neubig Date: Wed, 19 Aug 2026 04:30:03 +0000 Subject: [PATCH 1/6] feat: add read-only quota usage page with reset countdown Add GET /api/quota/status returning the authenticated user's effective daily limit, used count, remaining, and next UTC-midnight reset_at. Add a SaaS-only settings page at /settings/quota showing a progress bar and a live HH:MM:SS countdown to the next reset. Includes focused tests for the quota status service covering unlimited, partial, exhausted, and no-usage-today cases. Stacked on feat/daily-conversation-limit (PR #180). Co-authored-by: openhands --- enterprise/saas_server.py | 2 + enterprise/server/routes/quota.py | 37 +++++ .../daily_conversation_quota_service.py | 77 ++++++++++ .../test_daily_conversation_quota_service.py | 84 +++++++++++ .../api/quota-service/quota-service.api.ts | 15 ++ frontend/src/constants/settings-nav.tsx | 6 + frontend/src/hooks/query/use-quota-status.ts | 13 ++ frontend/src/i18n/declaration.ts | 7 + frontend/src/i18n/translation.json | 119 +++++++++++++++ frontend/src/routes.ts | 1 + frontend/src/routes/quota-settings.tsx | 136 ++++++++++++++++++ 11 files changed, 497 insertions(+) create mode 100644 enterprise/server/routes/quota.py create mode 100644 enterprise/server/services/daily_conversation_quota_service.py create mode 100644 enterprise/tests/unit/test_daily_conversation_quota_service.py create mode 100644 frontend/src/api/quota-service/quota-service.api.ts create mode 100644 frontend/src/hooks/query/use-quota-status.ts create mode 100644 frontend/src/routes/quota-settings.tsx diff --git a/enterprise/saas_server.py b/enterprise/saas_server.py index fe1ca19672..c731ecb6e3 100644 --- a/enterprise/saas_server.py +++ b/enterprise/saas_server.py @@ -51,6 +51,7 @@ from server.routes.org_invitations import ( # noqa: E402 invitation_router, ) +from server.routes.quota import quota_router # noqa: E402 from server.routes.org_profiles import router as org_profiles_router # noqa: E402 from server.routes.orgs import org_router # noqa: E402 from server.routes.readiness import readiness_router # noqa: E402 @@ -209,6 +210,7 @@ def is_saas(): base_app.include_router( analytics_events_router ) # Add routes for client-initiated analytics events +base_app.include_router(quota_router) # Add routes for quota status base_app.add_middleware( diff --git a/enterprise/server/routes/quota.py b/enterprise/server/routes/quota.py new file mode 100644 index 0000000000..652dc35dc9 --- /dev/null +++ b/enterprise/server/routes/quota.py @@ -0,0 +1,37 @@ +"""Quota status API for the settings page.""" + +from fastapi import APIRouter, Depends +from pydantic import BaseModel +from server.services.daily_conversation_quota_service import ( + DailyConversationQuotaService, +) +from sqlalchemy.ext.asyncio import AsyncSession + +from openhands.app_server.user_auth import get_user_id +from openhands.app_server.utils.dependencies import get_dependencies +from storage.database import a_session_maker + +quota_router = APIRouter( + prefix='/api/quota', tags=['Quota'], dependencies=get_dependencies() +) + + +class QuotaStatusResponse(BaseModel): + daily_limit: int | None + used_today: int + remaining: int | None + reset_at: str + + +@quota_router.get('/status', response_model=QuotaStatusResponse) +async def get_quota_status(user_id: str = Depends(get_user_id)) -> QuotaStatusResponse: + """Return the authenticated user's daily conversation quota status.""" + async with a_session_maker() as session: + service = DailyConversationQuotaService(session) + status = await service.get_status(user_id) + return QuotaStatusResponse( + daily_limit=status.daily_limit, + used_today=status.used_today, + remaining=status.remaining, + reset_at=status.reset_at, + ) diff --git a/enterprise/server/services/daily_conversation_quota_service.py b/enterprise/server/services/daily_conversation_quota_service.py new file mode 100644 index 0000000000..9f7cc16c42 --- /dev/null +++ b/enterprise/server/services/daily_conversation_quota_service.py @@ -0,0 +1,77 @@ +"""Read-only daily conversation quota status for the authenticated user.""" + +from __future__ import annotations + +import os +from datetime import UTC, date, datetime, timedelta +from uuid import UUID + +from pydantic import BaseModel +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession +from storage.daily_conversation_usage import DailyConversationUsage +from storage.user import User + +DEFAULT_ENV_VAR = 'OH_DAILY_CONVERSATION_LIMIT' + + +def configured_daily_limit() -> int | None: + """Read the deployment default; unset and blank mean unlimited.""" + raw = os.getenv(DEFAULT_ENV_VAR) + if raw is None or not raw.strip(): + return None + return int(raw) + + +class QuotaStatus(BaseModel): + """Current daily quota snapshot for the settings page.""" + + daily_limit: int | None + used_today: int + remaining: int | None + reset_at: str + + +class DailyConversationQuotaService: + """Read-only quota status. Enforcement is added in a later stacked PR.""" + + def __init__(self, db_session: AsyncSession) -> None: + self.db_session = db_session + + async def get_status(self, user_id: str) -> QuotaStatus: + limit = await self.get_limit(user_id) + used = await self._used(user_id, datetime.now(UTC).date()) + remaining = None if limit is None else max(limit - used, 0) + reset_at = self._next_reset_iso() + return QuotaStatus( + daily_limit=limit, + used_today=used, + remaining=remaining, + reset_at=reset_at, + ) + + async def get_limit(self, user_id: str) -> int | None: + user = await self.db_session.scalar( + select(User).where(User.id == UUID(user_id)) + ) + if user is None or user.daily_conversation_limit is None: + return configured_daily_limit() + return user.daily_conversation_limit + + @staticmethod + def _next_reset_iso() -> str: + """ISO timestamp of the next UTC midnight.""" + today = datetime.now(UTC).date() + reset = datetime.combine( + today + timedelta(days=1), datetime.min.time(), tzinfo=UTC + ) + return reset.isoformat() + + async def _used(self, user_id: str, usage_date: date) -> int: + usage = await self.db_session.scalar( + select(DailyConversationUsage).where( + DailyConversationUsage.user_id == UUID(user_id), + DailyConversationUsage.usage_date == usage_date, + ) + ) + return usage.conversation_count if usage else 0 diff --git a/enterprise/tests/unit/test_daily_conversation_quota_service.py b/enterprise/tests/unit/test_daily_conversation_quota_service.py new file mode 100644 index 0000000000..0a9615d0a7 --- /dev/null +++ b/enterprise/tests/unit/test_daily_conversation_quota_service.py @@ -0,0 +1,84 @@ +from types import SimpleNamespace +from unittest.mock import AsyncMock, patch +from uuid import uuid4 + +import pytest +from server.services.daily_conversation_quota_service import ( + DailyConversationQuotaService, + QuotaStatus, +) + +USER_ID = str(uuid4()) + + +@pytest.mark.asyncio +async def test_get_status_unlimited(): + """When limit is None (unlimited), remaining is None and reset_at is next UTC midnight.""" + session = AsyncMock() + session.scalar.side_effect = [ + SimpleNamespace(daily_conversation_limit=None), + None, # no usage record for today + ] + + service = DailyConversationQuotaService(session) + result = await service.get_status(USER_ID) + + assert isinstance(result, QuotaStatus) + assert result.daily_limit is None + assert result.remaining is None + assert result.reset_at.endswith('T00:00:00+00:00') + + +@pytest.mark.asyncio +async def test_get_status_with_limit_and_usage(): + """When limit is set and some conversations used, remaining is limit - used.""" + session = AsyncMock() + + # First scalar call: User lookup returns a user with limit 20 + # Second scalar call: DailyConversationUsage lookup returns count 5 + session.scalar.side_effect = [ + SimpleNamespace(daily_conversation_limit=20), + SimpleNamespace(conversation_count=5), + ] + + service = DailyConversationQuotaService(session) + result = await service.get_status(USER_ID) + + assert result.daily_limit == 20 + assert result.used_today == 5 + assert result.remaining == 15 + assert result.reset_at.endswith('T00:00:00+00:00') + + +@pytest.mark.asyncio +async def test_get_status_remaining_floor_zero(): + """Remaining never goes below zero even if usage exceeds limit.""" + session = AsyncMock() + session.scalar.side_effect = [ + SimpleNamespace(daily_conversation_limit=10), + SimpleNamespace(conversation_count=12), + ] + + service = DailyConversationQuotaService(session) + result = await service.get_status(USER_ID) + + assert result.daily_limit == 10 + assert result.used_today == 12 + assert result.remaining == 0 + + +@pytest.mark.asyncio +async def test_get_status_no_usage_today(): + """When no usage record exists for today, used_today is 0.""" + session = AsyncMock() + session.scalar.side_effect = [ + SimpleNamespace(daily_conversation_limit=20), + None, + ] + + service = DailyConversationQuotaService(session) + result = await service.get_status(USER_ID) + + assert result.daily_limit == 20 + assert result.used_today == 0 + assert result.remaining == 20 diff --git a/frontend/src/api/quota-service/quota-service.api.ts b/frontend/src/api/quota-service/quota-service.api.ts new file mode 100644 index 0000000000..146a1c6881 --- /dev/null +++ b/frontend/src/api/quota-service/quota-service.api.ts @@ -0,0 +1,15 @@ +import { openHands } from "#/api/open-hands-axios"; + +export interface QuotaStatus { + daily_limit: number | null; + used_today: number; + remaining: number | null; + reset_at: string; +} + +export const quotaService = { + getStatus: async (): Promise => { + const { data } = await openHands.get("/api/quota/status"); + return data; + }, +}; diff --git a/frontend/src/constants/settings-nav.tsx b/frontend/src/constants/settings-nav.tsx index 2edc074cbf..7495d9b7f0 100644 --- a/frontend/src/constants/settings-nav.tsx +++ b/frontend/src/constants/settings-nav.tsx @@ -144,6 +144,12 @@ export const SAAS_NAV_ITEMS: SettingsNavItem[] = [ text: "SETTINGS$NAV_BILLING", section: "billing", }, + { + icon: , + to: "/settings/quota", + text: "SETTINGS$NAV_QUOTA", + section: "user", + }, { icon: , to: "/settings/integrations", diff --git a/frontend/src/hooks/query/use-quota-status.ts b/frontend/src/hooks/query/use-quota-status.ts new file mode 100644 index 0000000000..9f49e42ee2 --- /dev/null +++ b/frontend/src/hooks/query/use-quota-status.ts @@ -0,0 +1,13 @@ +import { useQuery } from "@tanstack/react-query"; +import { quotaService } from "#/api/quota-service/quota-service.api"; + +export const QUOTA_QUERY_KEYS = { + status: ["quota", "status"] as const, +}; + +export const useQuotaStatus = () => + useQuery({ + queryKey: QUOTA_QUERY_KEYS.status, + queryFn: quotaService.getStatus, + refetchInterval: 60_000, // refresh every minute so the countdown stays live + }); diff --git a/frontend/src/i18n/declaration.ts b/frontend/src/i18n/declaration.ts index 16df9948e1..61703ab50c 100644 --- a/frontend/src/i18n/declaration.ts +++ b/frontend/src/i18n/declaration.ts @@ -1718,4 +1718,11 @@ export enum I18nKey { SETTINGS$DELETE_CONFIRMATION_MESSAGE = "SETTINGS$DELETE_CONFIRMATION_MESSAGE", BUTTON$EDIT = "BUTTON$EDIT", SETTINGS$MARKETPLACE_SOURCE_REQUIRED = "SETTINGS$MARKETPLACE_SOURCE_REQUIRED", + SETTINGS$NAV_QUOTA = "SETTINGS$NAV_QUOTA", + SETTINGS$QUOTA_DAILY_LIMIT = "SETTINGS$QUOTA_DAILY_LIMIT", + SETTINGS$QUOTA_USED_TODAY = "SETTINGS$QUOTA_USED_TODAY", + SETTINGS$QUOTA_REMAINING = "SETTINGS$QUOTA_REMAINING", + SETTINGS$QUOTA_UNLIMITED = "SETTINGS$QUOTA_UNLIMITED", + SETTINGS$QUOTA_RESETS_IN = "SETTINGS$QUOTA_RESETS_IN", + SETTINGS$QUOTA_SALES_ONLY = "SETTINGS$QUOTA_SALES_ONLY", } diff --git a/frontend/src/i18n/translation.json b/frontend/src/i18n/translation.json index 867161943b..9a1a752c34 100644 --- a/frontend/src/i18n/translation.json +++ b/frontend/src/i18n/translation.json @@ -29204,5 +29204,124 @@ "ca": "L'origen és obligatori", "tr": "Kaynak gereklidir", "uk": "Джерело є обов'язковим" + }, + "SETTINGS$NAV_QUOTA": { + "en": "Quota", + "ja": "クオータ", + "zh-CN": "配额", + "zh-TW": "配額", + "ko-KR": "할당량", + "no": "Kvote", + "it": "Quota", + "pt": "Cota", + "es": "Cuota", + "ar": "الحصة", + "fr": "Quota", + "tr": "Kota", + "de": "Kontingent", + "uk": "Квота", + "pt-BR": "Cota" + }, + "SETTINGS$QUOTA_DAILY_LIMIT": { + "en": "Daily limit", + "ja": "1日の制限", + "zh-CN": "每日限制", + "zh-TW": "每日限制", + "ko-KR": "일일 한도", + "no": "Daglig grense", + "it": "Limite giornaliero", + "pt": "Limite diário", + "es": "Límite diario", + "ar": "الحد اليومي", + "fr": "Limite quotidienne", + "tr": "Günlük limit", + "de": "Tageslimit", + "uk": "Денний ліміт", + "pt-BR": "Limite diário" + }, + "SETTINGS$QUOTA_USED_TODAY": { + "en": "Used today", + "ja": "今日の使用量", + "zh-CN": "今日已用", + "zh-TW": "今日已用", + "ko-KR": "오늘 사용량", + "no": "Brukt i dag", + "it": "Usato oggi", + "pt": "Usado hoje", + "es": "Usado hoy", + "ar": "المستخدم اليوم", + "fr": "Utilisé aujourd hui", + "tr": "Bugün kullanılan", + "de": "Heute verwendet", + "uk": "Використано сьогодні", + "pt-BR": "Usado hoje" + }, + "SETTINGS$QUOTA_REMAINING": { + "en": "Remaining", + "ja": "残り", + "zh-CN": "剩余", + "zh-TW": "剩餘", + "ko-KR": "남은 횟수", + "no": "Gjenværende", + "it": "Rimanente", + "pt": "Restante", + "es": "Restante", + "ar": "المتبقي", + "fr": "Restant", + "tr": "Kalan", + "de": "Verbleibend", + "uk": "Залишилось", + "pt-BR": "Restante" + }, + "SETTINGS$QUOTA_UNLIMITED": { + "en": "Unlimited", + "ja": "無制限", + "zh-CN": "无限", + "zh-TW": "無限", + "ko-KR": "무제한", + "no": "Ubegrenset", + "it": "Illimitato", + "pt": "Ilimitado", + "es": "Ilimitado", + "ar": "غير محدود", + "fr": "Illimité", + "tr": "Sınırsız", + "de": "Unbegrenzt", + "uk": "Безлімітний", + "pt-BR": "Ilimitado" + }, + "SETTINGS$QUOTA_RESETS_IN": { + "en": "Resets in", + "ja": "リセットまで", + "zh-CN": "重置于", + "zh-TW": "重置於", + "ko-KR": "재설정까지", + "no": "Tilbakestilles om", + "it": "Reimposta tra", + "pt": "Redefinir em", + "es": "Se reinicia en", + "ar": "إعادة التعيين في", + "fr": "Réinitialisé dans", + "tr": "Sıfırlanmaya", + "de": "Zurücksetzen in", + "uk": "Скидається через", + "pt-BR": "Redefinir em" + }, + "SETTINGS$QUOTA_SALES_ONLY": { + "en": "Quota management is only available in SaaS mode.", + "ja": "クオータ管理はSaaSモードでのみ利用できます。", + "zh-CN": "配额管理仅在SaaS模式下可用。", + "zh-TW": "配額管理僅在SaaS模式下可用。", + "ko-KR": "할당량 관리는 SaaS 모드에서만 사용할 수 있습니다.", + "no": "Kvotestyring er kun tilgjengelig i SaaS-modus.", + "it": "La gestione della quota è disponibile solo in modalità SaaS.", + "pt": "O gerenciamento de cota está disponível apenas no modo SaaS.", + "es": "La gestión de cuota solo está disponible en modo SaaS.", + "ar": "إدارة الحصة متاحة فقط في وضع SaaS.", + "fr": "La gestion du quota est disponible uniquement en mode SaaS.", + "tr": "Kota yönetimi yalnızca SaaS modunda kullanılabilir.", + "de": "Kontingentverwaltung ist nur im SaaS-Modus verfügbar.", + "uk": "Управління квотою доступне лише в режимі SaaS.", + "pt-BR": "O gerenciamento de cota está disponível apenas no modo SaaS." } } diff --git a/frontend/src/routes.ts b/frontend/src/routes.ts index 1956c209a1..5f381cab2b 100644 --- a/frontend/src/routes.ts +++ b/frontend/src/routes.ts @@ -47,6 +47,7 @@ export default [ route("usage-monitoring", "routes/usage-monitoring.tsx"), route("admin-dashboard", "routes/admin-dashboard.tsx"), route("budgets", "routes/budgets.tsx"), + route("quota", "routes/quota-settings.tsx"), ]), route("conversations/:conversationId", "routes/conversation.tsx"), route("oauth/device/verify", "routes/device-verify.tsx"), diff --git a/frontend/src/routes/quota-settings.tsx b/frontend/src/routes/quota-settings.tsx new file mode 100644 index 0000000000..0758f4dada --- /dev/null +++ b/frontend/src/routes/quota-settings.tsx @@ -0,0 +1,136 @@ +import React, { useEffect, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { useQuotaStatus } from "#/hooks/query/use-quota-status"; +import { useConfig } from "#/hooks/query/use-config"; +import { I18nKey } from "#/i18n/declaration"; + +function useCountdown(resetAt: string | null) { + const [remaining, setRemaining] = useState(""); + + useEffect(() => { + if (!resetAt) { + setRemaining(""); + return; + } + + const update = () => { + const diff = new Date(resetAt).getTime() - Date.now(); + if (diff <= 0) { + setRemaining("00:00:00"); + return; + } + const h = Math.floor(diff / 3_600_000); + const m = Math.floor((diff % 3_600_000) / 60_000); + const s = Math.floor((diff % 60_000) / 1_000); + setRemaining( + `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`, + ); + }; + + update(); + const id = setInterval(update, 1_000); + return () => clearInterval(id); + }, [resetAt]); + + return remaining; +} + +function QuotaSettingsScreen() { + const { t } = useTranslation(); + const { data: config } = useConfig(); + const { data: quota, isLoading } = useQuotaStatus(); + const countdown = useCountdown(quota?.reset_at ?? null); + + const isSaas = config?.app_mode === "saas"; + + if (!isSaas) { + return ( +
+

+ {t(I18nKey.SETTINGS$QUOTA_SALES_ONLY)} +

+
+ ); + } + + if (isLoading || !quota) { + return ( +
+
+
+ ); + } + + const unlimited = quota.daily_limit === null; + const pct = + unlimited || quota.daily_limit === 0 + ? 0 + : Math.min((quota.used_today / quota.daily_limit) * 100, 100); + + return ( +
+

+ {t(I18nKey.SETTINGS$NAV_QUOTA)} +

+ +
+
+ + {t(I18nKey.SETTINGS$QUOTA_DAILY_LIMIT)} + + + {unlimited + ? t(I18nKey.SETTINGS$QUOTA_UNLIMITED) + : quota.daily_limit} + +
+ +
+ + {t(I18nKey.SETTINGS$QUOTA_USED_TODAY)} + + + {quota.used_today} + +
+ +
+ + {t(I18nKey.SETTINGS$QUOTA_REMAINING)} + + + {unlimited ? t(I18nKey.SETTINGS$QUOTA_UNLIMITED) : quota.remaining} + +
+ + {!unlimited && ( +
+
+
+ )} +
+ +
+ {t(I18nKey.SETTINGS$QUOTA_RESETS_IN)} + + {countdown} + +
+
+ ); +} + +export default QuotaSettingsScreen; From 45376daec71bc6961b69e7c1632ad93b265e3306 Mon Sep 17 00:00:00 2001 From: neubig Date: Wed, 19 Aug 2026 05:02:40 +0000 Subject: [PATCH 2/6] fix: handle nullable daily_limit in TypeScript for quota settings Co-authored-by: openhands --- frontend/src/routes/quota-settings.tsx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/frontend/src/routes/quota-settings.tsx b/frontend/src/routes/quota-settings.tsx index 0758f4dada..bf8a9e4d96 100644 --- a/frontend/src/routes/quota-settings.tsx +++ b/frontend/src/routes/quota-settings.tsx @@ -65,10 +65,11 @@ function QuotaSettingsScreen() { } const unlimited = quota.daily_limit === null; + const limit = quota.daily_limit ?? 0; const pct = - unlimited || quota.daily_limit === 0 + unlimited || limit === 0 ? 0 - : Math.min((quota.used_today / quota.daily_limit) * 100, 100); + : Math.min((quota.used_today / limit) * 100, 100); return (
From f95878f2523ceffef601d5f923d581034f044f3c Mon Sep 17 00:00:00 2001 From: hieptl Date: Thu, 20 Aug 2026 22:36:14 +0700 Subject: [PATCH 3/6] fix: resolve frontend lint and translation errors on quota page Return undefined explicitly from the countdown effect's no-op branch (consistent-return alongside the interval cleanup return), apply Prettier formatting to the SaaS-only message and countdown span, and swap the unsupported pt-BR translations of the quota keys for the required Catalan (ca) entries. --- frontend/src/i18n/translation.json | 14 +++++++------- frontend/src/routes/quota-settings.tsx | 11 ++++++----- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/frontend/src/i18n/translation.json b/frontend/src/i18n/translation.json index 9a1a752c34..089e4f9ba3 100644 --- a/frontend/src/i18n/translation.json +++ b/frontend/src/i18n/translation.json @@ -29220,7 +29220,7 @@ "tr": "Kota", "de": "Kontingent", "uk": "Квота", - "pt-BR": "Cota" + "ca": "Quota" }, "SETTINGS$QUOTA_DAILY_LIMIT": { "en": "Daily limit", @@ -29237,7 +29237,7 @@ "tr": "Günlük limit", "de": "Tageslimit", "uk": "Денний ліміт", - "pt-BR": "Limite diário" + "ca": "Límit diari" }, "SETTINGS$QUOTA_USED_TODAY": { "en": "Used today", @@ -29254,7 +29254,7 @@ "tr": "Bugün kullanılan", "de": "Heute verwendet", "uk": "Використано сьогодні", - "pt-BR": "Usado hoje" + "ca": "Utilitzat avui" }, "SETTINGS$QUOTA_REMAINING": { "en": "Remaining", @@ -29271,7 +29271,7 @@ "tr": "Kalan", "de": "Verbleibend", "uk": "Залишилось", - "pt-BR": "Restante" + "ca": "Restant" }, "SETTINGS$QUOTA_UNLIMITED": { "en": "Unlimited", @@ -29288,7 +29288,7 @@ "tr": "Sınırsız", "de": "Unbegrenzt", "uk": "Безлімітний", - "pt-BR": "Ilimitado" + "ca": "Il·limitat" }, "SETTINGS$QUOTA_RESETS_IN": { "en": "Resets in", @@ -29305,7 +29305,7 @@ "tr": "Sıfırlanmaya", "de": "Zurücksetzen in", "uk": "Скидається через", - "pt-BR": "Redefinir em" + "ca": "Es restableix en" }, "SETTINGS$QUOTA_SALES_ONLY": { "en": "Quota management is only available in SaaS mode.", @@ -29322,6 +29322,6 @@ "tr": "Kota yönetimi yalnızca SaaS modunda kullanılabilir.", "de": "Kontingentverwaltung ist nur im SaaS-Modus verfügbar.", "uk": "Управління квотою доступне лише в режимі SaaS.", - "pt-BR": "O gerenciamento de cota está disponível apenas no modo SaaS." + "ca": "La gestió de quotes només està disponible en mode SaaS." } } diff --git a/frontend/src/routes/quota-settings.tsx b/frontend/src/routes/quota-settings.tsx index bf8a9e4d96..3868a5b5e5 100644 --- a/frontend/src/routes/quota-settings.tsx +++ b/frontend/src/routes/quota-settings.tsx @@ -10,7 +10,7 @@ function useCountdown(resetAt: string | null) { useEffect(() => { if (!resetAt) { setRemaining(""); - return; + return undefined; } const update = () => { @@ -46,9 +46,7 @@ function QuotaSettingsScreen() { if (!isSaas) { return (
-

- {t(I18nKey.SETTINGS$QUOTA_SALES_ONLY)} -

+

{t(I18nKey.SETTINGS$QUOTA_SALES_ONLY)}

); } @@ -126,7 +124,10 @@ function QuotaSettingsScreen() { data-testid="quota-reset-countdown" > {t(I18nKey.SETTINGS$QUOTA_RESETS_IN)} - + {countdown}
From 4326cc66dc78c4cb2d57c50fd691a874abb4c39e Mon Sep 17 00:00:00 2001 From: hieptl Date: Thu, 20 Aug 2026 23:08:44 +0700 Subject: [PATCH 4/6] fix: satisfy enterprise ruff on quota status files Sort the quota router imports, drop the unused AsyncSession and patch imports. These were previously masked in CI because the enterprise lint job failed to build its mypy environment before ruff could report. --- enterprise/saas_server.py | 2 +- enterprise/server/routes/quota.py | 3 +-- enterprise/tests/unit/test_daily_conversation_quota_service.py | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/enterprise/saas_server.py b/enterprise/saas_server.py index c731ecb6e3..9443f147b0 100644 --- a/enterprise/saas_server.py +++ b/enterprise/saas_server.py @@ -51,9 +51,9 @@ from server.routes.org_invitations import ( # noqa: E402 invitation_router, ) -from server.routes.quota import quota_router # noqa: E402 from server.routes.org_profiles import router as org_profiles_router # noqa: E402 from server.routes.orgs import org_router # noqa: E402 +from server.routes.quota import quota_router # noqa: E402 from server.routes.readiness import readiness_router # noqa: E402 from server.routes.service import service_router # noqa: E402 from server.routes.super_admins import super_admin_router # noqa: E402 diff --git a/enterprise/server/routes/quota.py b/enterprise/server/routes/quota.py index 652dc35dc9..9d431705d8 100644 --- a/enterprise/server/routes/quota.py +++ b/enterprise/server/routes/quota.py @@ -5,11 +5,10 @@ from server.services.daily_conversation_quota_service import ( DailyConversationQuotaService, ) -from sqlalchemy.ext.asyncio import AsyncSession +from storage.database import a_session_maker from openhands.app_server.user_auth import get_user_id from openhands.app_server.utils.dependencies import get_dependencies -from storage.database import a_session_maker quota_router = APIRouter( prefix='/api/quota', tags=['Quota'], dependencies=get_dependencies() diff --git a/enterprise/tests/unit/test_daily_conversation_quota_service.py b/enterprise/tests/unit/test_daily_conversation_quota_service.py index 0a9615d0a7..598c088434 100644 --- a/enterprise/tests/unit/test_daily_conversation_quota_service.py +++ b/enterprise/tests/unit/test_daily_conversation_quota_service.py @@ -1,5 +1,5 @@ from types import SimpleNamespace -from unittest.mock import AsyncMock, patch +from unittest.mock import AsyncMock from uuid import uuid4 import pytest From 0ec8c2cbc94068bd17c876a50c57af694d26d6d8 Mon Sep 17 00:00:00 2001 From: openhands Date: Wed, 9 Sep 2026 18:12:53 +0000 Subject: [PATCH 5/6] fix: hide unlimited daily quota setting Co-authored-by: openhands --- .../hooks/use-settings-nav-items.test.tsx | 33 +++++++++++++++++++ frontend/src/hooks/query/use-quota-status.ts | 3 +- frontend/src/hooks/use-settings-nav-items.ts | 9 ++++- 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/frontend/__tests__/hooks/use-settings-nav-items.test.tsx b/frontend/__tests__/hooks/use-settings-nav-items.test.tsx index 3ab919eb9a..88b944d6f8 100644 --- a/frontend/__tests__/hooks/use-settings-nav-items.test.tsx +++ b/frontend/__tests__/hooks/use-settings-nav-items.test.tsx @@ -42,6 +42,14 @@ vi.mock("#/hooks/query/use-me", () => ({ useMe: () => mockMe, })); +const mockQuotaStatus = vi.hoisted(() => ({ + data: { daily_limit: 100 } as { daily_limit: number | null } | undefined, +})); + +vi.mock("#/hooks/query/use-quota-status", () => ({ + useQuotaStatus: () => mockQuotaStatus, +})); + const queryClient = new QueryClient(); const wrapper = ({ children }: { children: React.ReactNode }) => ( {children} @@ -99,6 +107,31 @@ describe("useSettingsNavItems", () => { mockOrgTypeAndAccess.selectedOrg = null; mockOrgTypeAndAccess.canViewOrgRoutes = false; mockMe.data = null; + mockQuotaStatus.data = { daily_limit: 100 }; + }); + + it("should show quota route when a daily limit is configured", async () => { + mockConfig("saas"); + mockMe.data = { role: "member" }; + mockQuotaStatus.data = { daily_limit: 100 }; + + const { result } = renderHook(() => useSettingsNavItems(), { wrapper }); + + await waitFor(() => { + expect(findItemByPath(result.current, "/settings/quota")).toBeDefined(); + }); + }); + + it("should hide quota route when the daily limit is unlimited", async () => { + mockConfig("saas"); + mockMe.data = { role: "member" }; + mockQuotaStatus.data = { daily_limit: null }; + + const { result } = renderHook(() => useSettingsNavItems(), { wrapper }); + + await waitFor(() => { + expect(findItemByPath(result.current, "/settings/quota")).toBeUndefined(); + }); }); it("should return SAAS_NAV_ITEMS minus billing/org/org-members when userRole is 'member'", async () => { diff --git a/frontend/src/hooks/query/use-quota-status.ts b/frontend/src/hooks/query/use-quota-status.ts index 9f49e42ee2..e637b23a90 100644 --- a/frontend/src/hooks/query/use-quota-status.ts +++ b/frontend/src/hooks/query/use-quota-status.ts @@ -5,9 +5,10 @@ export const QUOTA_QUERY_KEYS = { status: ["quota", "status"] as const, }; -export const useQuotaStatus = () => +export const useQuotaStatus = (options?: { enabled?: boolean }) => useQuery({ queryKey: QUOTA_QUERY_KEYS.status, queryFn: quotaService.getStatus, refetchInterval: 60_000, // refresh every minute so the countdown stays live + enabled: options?.enabled, }); diff --git a/frontend/src/hooks/use-settings-nav-items.ts b/frontend/src/hooks/use-settings-nav-items.ts index e06d7fdee5..44832718fd 100644 --- a/frontend/src/hooks/use-settings-nav-items.ts +++ b/frontend/src/hooks/use-settings-nav-items.ts @@ -15,6 +15,7 @@ import { useMe } from "./query/use-me"; import { usePermission } from "./organizations/use-permissions"; import { useOrgTypeAndAccess } from "./use-org-type-and-access"; import { useSettings } from "./query/use-settings"; +import { useQuotaStatus } from "./query/use-quota-status"; import { I18nKey } from "#/i18n/declaration"; // Rendered navigation item types @@ -46,6 +47,8 @@ export function useSettingsNavItems(): SettingsNavRenderedItem[] { const { data: config } = useConfig(); const { data: user } = useMe(); const { data: settings } = useSettings(); + const isSaasMode = config?.app_mode === "saas"; + const { data: quota } = useQuotaStatus({ enabled: isSaasMode }); const userRole: OrganizationUserRole = user?.role ?? "member"; const { hasPermission } = usePermission(userRole); const { isPersonalOrg, isTeamOrg, organizationId } = useOrgTypeAndAccess(); @@ -54,7 +57,6 @@ export function useSettingsNavItems(): SettingsNavRenderedItem[] { config, hasPermission("view_billing"), ); - const isSaasMode = config?.app_mode === "saas"; const featureFlags = config?.feature_flags; const isAdminOrOwner = userRole === "admin" || userRole === "owner"; const isAcpAgent = settings?.agent_settings?.agent_kind === "acp"; @@ -69,6 +71,11 @@ export function useSettingsNavItems(): SettingsNavRenderedItem[] { // First apply feature flag-based hiding items = items.filter((item) => !isSettingsPageHidden(item.to, featureFlags)); + // The quota page is only useful when a daily limit is configured. + if (isSaasMode && quota?.daily_limit === null) { + items = items.filter((item) => item.to !== "/settings/quota"); + } + // Hide billing when billing is not accessible OR when in team org if (shouldHideBilling || isTeamOrg) { items = items.filter((item) => item.to !== "/settings/billing"); From 61222e04ebd738aeb12eb21b52c8cfa5a3a4c1e1 Mon Sep 17 00:00:00 2001 From: openhands Date: Mon, 28 Sep 2026 16:18:09 +0000 Subject: [PATCH 6/6] test(frontend): stop user-actions suite deadlocking on quota polling `UserActions` renders `UserContextMenu`, which calls `useSettingsNavItems()`. This branch added a `useQuotaStatus` query there with `refetchInterval: 60_000` and `enabled: isSaasMode`. The suite mocks config as saas, so the interval was live and each test's `await vi.runAllTimersAsync()` could never drain it - vitest aborted with "Aborting after running 10000 timers, assuming an infinite loop!". These tests never assert on quota, so stub the hook with a settled value. Co-authored-by: openhands --- frontend/__tests__/components/user-actions.test.tsx | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/frontend/__tests__/components/user-actions.test.tsx b/frontend/__tests__/components/user-actions.test.tsx index fa42dbe1f7..f52fbbd1b8 100644 --- a/frontend/__tests__/components/user-actions.test.tsx +++ b/frontend/__tests__/components/user-actions.test.tsx @@ -102,6 +102,14 @@ vi.mock("#/hooks/use-user-providers", () => ({ useUserProviders: () => useUserProvidersMock(), })); +// useSettingsNavItems (rendered via UserContextMenu) polls the quota +// endpoint on an interval. In saas mode that interval is enabled, so +// `runAllTimersAsync` below would never drain and abort. These tests do not +// care about quota, so stub the hook out with a settled value. +vi.mock("#/hooks/query/use-quota-status", () => ({ + useQuotaStatus: () => ({ data: { daily_limit: 100 }, isLoading: false }), +})); + describe("UserActions", () => { const user = userEvent.setup(); const onClickAccountSettingsMock = vi.fn();