Skip to content

🙌 OpenHands: AI-Driven Development

feat: Upgrade banner for unsubscribed SaaS users (#10890)

sp.wackd3f3378a4c80
diff --git a/enterprise/migrations/versions/075_add_cancellation_fields_to_subscription_access.py b/enterprise/migrations/versions/075_add_cancellation_fields_to_subscription_access.py
new file mode 100644
index 0000000000..e77a873408
--- /dev/null
+++ b/enterprise/migrations/versions/075_add_cancellation_fields_to_subscription_access.py
@@ -0,0 +1,50 @@
+"""add cancellation fields to subscription_access
+
+Revision ID: 075
+Revises: 074
+Create Date: 2025-01-11
+
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = '075'
+down_revision: Union[str, None] = '074'
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ # Add cancelled_at field to track cancellation timestamp
+ op.add_column(
+ 'subscription_access',
+ sa.Column('cancelled_at', sa.DateTime(timezone=True), nullable=True),
+ )
+
+ # Add stripe_subscription_id field to enable cancellation via Stripe API
+ op.add_column(
+ 'subscription_access',
+ sa.Column('stripe_subscription_id', sa.String(), nullable=True),
+ )
+
+ # Create index on stripe_subscription_id for efficient lookups
+ op.create_index(
+ 'ix_subscription_access_stripe_subscription_id',
+ 'subscription_access',
+ ['stripe_subscription_id'],
+ )
+
+
+def downgrade() -> None:
+ # Drop index
+ op.drop_index(
+ 'ix_subscription_access_stripe_subscription_id', 'subscription_access'
+ )
+
+ # Drop columns
+ op.drop_column('subscription_access', 'stripe_subscription_id')
+ op.drop_column('subscription_access', 'cancelled_at')
diff --git a/enterprise/server/routes/billing.py b/enterprise/server/routes/billing.py
index 5c37df2100..5688cd94e3 100644
--- a/enterprise/server/routes/billing.py
+++ b/enterprise/server/routes/billing.py
@@ -17,11 +17,13 @@ from server.constants import (
STRIPE_API_KEY,
STRIPE_WEBHOOK_SECRET,
SUBSCRIPTION_PRICE_DATA,
+ get_default_litellm_model,
)
from server.logger import logger
from storage.billing_session import BillingSession
from storage.database import session_maker
from storage.subscription_access import SubscriptionAccess
+from storage.user_settings import UserSettings
from openhands.server.user_auth import get_user_id
@@ -42,6 +44,8 @@ class SubscriptionAccessResponse(BaseModel):
start_at: datetime
end_at: datetime
created_at: datetime
+ cancelled_at: datetime | None = None
+ stripe_subscription_id: str | None = None
class CreateCheckoutSessionRequest(BaseModel):
@@ -85,7 +89,7 @@ async def get_credits(user_id: str = Depends(get_user_id)) -> GetCreditsResponse
async def get_subscription_access(
user_id: str = Depends(get_user_id),
) -> SubscriptionAccessResponse | None:
- """Get details of the currently valid subscription for the user"""
+ """Get details of the currently valid subscription for the user."""
with session_maker() as session:
now = datetime.now(UTC)
subscription_access = (
@@ -102,6 +106,8 @@ async def get_subscription_access(
start_at=subscription_access.start_at,
end_at=subscription_access.end_at,
created_at=subscription_access.created_at,
+ cancelled_at=subscription_access.cancelled_at,
+ stripe_subscription_id=subscription_access.stripe_subscription_id,
)
@@ -113,6 +119,78 @@ async def has_payment_method(user_id: str = Depends(get_user_id)) -> bool:
return await stripe_service.has_payment_method(user_id)
+# Endpoint to cancel user's subscription
+@billing_router.post('/cancel-subscription')
+async def cancel_subscription(user_id: str = Depends(get_user_id)) -> JSONResponse:
+ """Cancel user's active subscription at the end of the current billing period."""
+ if not user_id:
+ raise HTTPException(status.HTTP_401_UNAUTHORIZED)
+
+ with session_maker() as session:
+ # Find the user's active subscription
+ now = datetime.now(UTC)
+ subscription_access = (
+ session.query(SubscriptionAccess)
+ .filter(SubscriptionAccess.status == 'ACTIVE')
+ .filter(SubscriptionAccess.user_id == user_id)
+ .filter(SubscriptionAccess.start_at <= now)
+ .filter(SubscriptionAccess.end_at >= now)
+ .filter(SubscriptionAccess.cancelled_at.is_(None)) # Not already cancelled
+ .first()
+ )
+
+ if not subscription_access:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail='No active subscription found',
+ )
+
+ if not subscription_access.stripe_subscription_id:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail='Cannot cancel subscription: missing Stripe subscription ID',
+ )
+
+ try:
+ # Cancel the subscription in Stripe at period end
+ await stripe.Subscription.modify_async(
+ subscription_access.stripe_subscription_id, cancel_at_period_end=True
+ )
+
+ # Update local database
+ subscription_access.cancelled_at = datetime.now(UTC)
+ session.merge(subscription_access)
+ session.commit()
+
+ logger.info(
+ 'subscription_cancelled',
+ extra={
+ 'user_id': user_id,
+ 'stripe_subscription_id': subscription_access.stripe_subscription_id,
+ 'subscription_access_id': subscription_access.id,
+ 'end_at': subscription_access.end_at,
+ },
+ )
+
+ return JSONResponse(
+ {'status': 'success', 'message': 'Subscription cancelled successfully'}
+ )
+
+ except stripe.StripeError as e:
+ logger.error(
+ 'stripe_cancellation_failed',
+ extra={
+ 'user_id': user_id,
+ 'stripe_subscription_id': subscription_access.stripe_subscription_id,
+ 'error': str(e),
+ },
+ )
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail=f'Failed to cancel subscription: {str(e)}',
+ )
+
+
# Endpoint to create a new setup intent in stripe
@billing_router.post('/create-customer-setup-session')
async def create_customer_setup_session(
@@ -190,9 +268,27 @@ async def create_subscription_checkout_session(
billing_session_type: BillingSessionType = BillingSessionType.MONTHLY_SUBSCRIPTION,
user_id: str = Depends(get_user_id),
) -> CreateBillingSessionResponse:
+ # Prevent duplicate subscriptions for the same user
+ with session_maker() as session:
+ now = datetime.now(UTC)
+ existing_active_subscription = (
+ session.query(SubscriptionAccess)
+ .filter(SubscriptionAccess.status == 'ACTIVE')
+ .filter(SubscriptionAccess.user_id == user_id)
+ .filter(SubscriptionAccess.start_at <= now)
+ .filter(SubscriptionAccess.end_at >= now)
+ .filter(SubscriptionAccess.cancelled_at.is_(None)) # Not cancelled
+ .first()
+ )
+
+ if existing_active_subscription:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail='Cannot create subscription: User already has an active subscription that has not been cancelled',
+ )
+
customer_id = await stripe_service.find_or_create_customer(user_id)
subscription_price_data = SUBSCRIPTION_PRICE_DATA[billing_session_type.value]
- # TODO: Prevent duplicate subscriptions for the same user
checkout_session = await stripe.checkout.Session.create_async(
customer=customer_id,
line_items=[
@@ -246,7 +342,7 @@ async def create_subscription_checkout_session_via_get(
billing_session_type: BillingSessionType = BillingSessionType.MONTHLY_SUBSCRIPTION,
user_id: str = Depends(get_user_id),
) -> RedirectResponse:
- """Create a subscription checkout session using a GET request (For easier copy / paste to URL bar)"""
+ """Create a subscription checkout session using a GET request (For easier copy / paste to URL bar)."""
response = await create_subscription_checkout_session(
request, billing_session_type, user_id
)
@@ -278,7 +374,7 @@ async def success_callback(session_id: str, request: Request):
!= BillingSessionType.DIRECT_PAYMENT.value
):
return RedirectResponse(
- f'{request.base_url}settings/billing?checkout=success', status_code=302
+ f'{request.base_url}settings?checkout=success', status_code=302
)
stripe_session = stripe.checkout.Session.retrieve(session_id)
@@ -321,7 +417,7 @@ async def success_callback(session_id: str, request: Request):
session.commit()
return RedirectResponse(
- f'{request.base_url}settings/billing?checkout=success', status_code=302
+ f'{request.base_url}settings?checkout=success', status_code=302
)
@@ -349,13 +445,13 @@ async def cancel_callback(session_id: str, request: Request):
session.commit()
return RedirectResponse(
- f'{request.base_url}settings/billing?checkout=cancel', status_code=302
+ f'{request.base_url}settings?checkout=cancel', status_code=302
)
@billing_router.post('/stripe-webhook')
async def stripe_webhook(request: Request) -> JSONResponse:
- """Endpoint for stripe webhooks"""
+ """Endpoint for stripe webhooks."""
payload = await request.body()
sig_header = request.headers.get('stripe-signature')
@@ -397,15 +493,111 @@ async def stripe_webhook(request: Request) -> JSONResponse:
end_at=end_at,
amount_paid=amount_paid,
stripe_invoice_payment_id=invoice.payment_intent,
+ stripe_subscription_id=invoice.subscription, # Store Stripe subscription ID
)
session.add(subscription_access)
session.commit()
+ elif event_type == 'customer.subscription.updated':
+ subscription = event['data']['object']
+ subscription_id = subscription['id']
+
+ # Handle subscription cancellation
+ if subscription.get('cancel_at_period_end') is True:
+ with session_maker() as session:
+ subscription_access = (
+ session.query(SubscriptionAccess)
+ .filter(
+ SubscriptionAccess.stripe_subscription_id == subscription_id
+ )
+ .filter(SubscriptionAccess.status == 'ACTIVE')
+ .first()
+ )
+
+ if subscription_access and not subscription_access.cancelled_at:
+ subscription_access.cancelled_at = datetime.now(UTC)
+ session.merge(subscription_access)
+ session.commit()
+
+ logger.info(
+ 'subscription_cancelled_via_webhook',
+ extra={
+ 'stripe_subscription_id': subscription_id,
+ 'user_id': subscription_access.user_id,
+ 'subscription_access_id': subscription_access.id,
+ },
+ )
+ elif event_type == 'customer.subscription.deleted':
+ subscription = event['data']['object']
+ subscription_id = subscription['id']
+
+ with session_maker() as session:
+ subscription_access = (
+ session.query(SubscriptionAccess)
+ .filter(SubscriptionAccess.stripe_subscription_id == subscription_id)
+ .filter(SubscriptionAccess.status == 'ACTIVE')
+ .first()
+ )
+
+ if subscription_access:
+ subscription_access.status = 'DISABLED'
+ subscription_access.updated_at = datetime.now(UTC)
+ session.merge(subscription_access)
+ session.commit()
+
+ # Reset user settings to free tier defaults
+ reset_user_to_free_tier_settings(subscription_access.user_id)
+
+ logger.info(
+ 'subscription_expired_reset_to_free_tier',
+ extra={
+ 'stripe_subscription_id': subscription_id,
+ 'user_id': subscription_access.user_id,
+ 'subscription_access_id': subscription_access.id,
+ },
+ )
else:
logger.info('stripe_webhook_unhandled_event_type', extra={'type': event_type})
return JSONResponse({'status': 'success'})
+def reset_user_to_free_tier_settings(user_id: str) -> None:
+ """Reset user settings to free tier defaults when subscription ends."""
+ with session_maker() as session:
+ user_settings = (
+ session.query(UserSettings)
+ .filter(UserSettings.keycloak_user_id == user_id)
+ .first()
+ )
+
+ if user_settings:
+ user_settings.llm_model = get_default_litellm_model()
+ user_settings.llm_api_key = None
+ user_settings.llm_api_key_for_byor = None
+ user_settings.llm_base_url = LITE_LLM_API_URL
+ user_settings.max_budget_per_task = None
+ user_settings.confirmation_mode = False
+ user_settings.enable_solvability_analysis = False
+ user_settings.security_analyzer = 'llm'
+ user_settings.agent = 'CodeActAgent'
+ user_settings.language = 'en'
+ user_settings.enable_default_condenser = True
+ user_settings.enable_sound_notifications = False
+ user_settings.enable_proactive_conversation_starters = True
+ user_settings.user_consents_to_analytics = False
+
+ session.merge(user_settings)
+ session.commit()
+
+ logger.info(
+ 'user_settings_reset_to_free_tier',
+ extra={
+ 'user_id': user_id,
+ 'reset_timestamp': datetime.now(UTC).isoformat(),
+ },
+ )
+
+
async def _get_litellm_user(client: httpx.AsyncClient, user_id: str) -> dict:
"""Get a user from litellm with the id matching that given.
diff --git a/enterprise/storage/subscription_access.py b/enterprise/storage/subscription_access.py
index 5c102abf63..38051995b1 100644
--- a/enterprise/storage/subscription_access.py
+++ b/enterprise/storage/subscription_access.py
@@ -7,7 +7,7 @@ from storage.base import Base
class SubscriptionAccess(Base): # type: ignore
"""
Represents a user's subscription access record.
- Tracks subscription status, duration, and payment information.
+ Tracks subscription status, duration, payment information, and cancellation status.
"""
__tablename__ = 'subscription_access'
@@ -27,6 +27,8 @@ class SubscriptionAccess(Base): # type: ignore
end_at = Column(DateTime(timezone=True), nullable=True)
amount_paid = Column(DECIMAL(19, 4), nullable=True)
stripe_invoice_payment_id = Column(String, nullable=False)
+ cancelled_at = Column(DateTime(timezone=True), nullable=True)
+ stripe_subscription_id = Column(String, nullable=True, index=True)
created_at = Column(
DateTime(timezone=True),
default=lambda: datetime.now(UTC), # type: ignore[attr-defined]
diff --git a/enterprise/tests/unit/test_billing.py b/enterprise/tests/unit/test_billing.py
index 5f717251bb..9947e32479 100644
--- a/enterprise/tests/unit/test_billing.py
+++ b/enterprise/tests/unit/test_billing.py
@@ -5,16 +5,16 @@ import pytest
import stripe
from fastapi import HTTPException, Request, status
from httpx import HTTPStatusError, Response
-from server.routes import billing
+from integrations.stripe_service import has_payment_method
from server.routes.billing import (
CreateBillingSessionResponse,
CreateCheckoutSessionRequest,
GetCreditsResponse,
cancel_callback,
+ cancel_subscription,
create_checkout_session,
- create_customer_setup_session,
+ create_subscription_checkout_session,
get_credits,
- has_payment_method,
success_callback,
)
from sqlalchemy import create_engine
@@ -288,8 +288,7 @@ async def test_success_callback_success():
assert response.status_code == 302
assert (
- response.headers['location']
- == 'http://test.com/settings/billing?checkout=success'
+ response.headers['location'] == 'http://test.com/settings?checkout=success'
)
# Verify LiteLLM API calls
@@ -362,8 +361,7 @@ async def test_cancel_callback_session_not_found():
response = await cancel_callback('test_session_id', mock_request)
assert response.status_code == 302
assert (
- response.headers['location']
- == 'http://test.com/settings/billing?checkout=cancel'
+ response.headers['location'] == 'http://test.com/settings?checkout=cancel'
)
# Verify no database updates occurred
@@ -389,8 +387,7 @@ async def test_cancel_callback_success():
assert response.status_code == 302
assert (
- response.headers['location']
- == 'http://test.com/settings/billing?checkout=cancel'
+ response.headers['location'] == 'http://test.com/settings?checkout=cancel'
)
# Verify database updates
@@ -402,51 +399,312 @@ async def test_cancel_callback_success():
@pytest.mark.asyncio
async def test_has_payment_method_with_payment_method():
"""Test has_payment_method returns True when user has a payment method."""
-
- mock_has_payment_method = AsyncMock(return_value=True)
- with patch(
- 'integrations.stripe_service.has_payment_method', mock_has_payment_method
+ with (
+ patch('integrations.stripe_service.session_maker') as mock_session_maker,
+ patch(
+ 'stripe.Customer.list_payment_methods_async',
+ AsyncMock(return_value=MagicMock(data=[MagicMock()])),
+ ) as mock_list_payment_methods,
):
+ # Setup mock session
+ mock_session = MagicMock()
+ mock_session_maker.return_value.__enter__.return_value = mock_session
+ mock_session.query.return_value.filter.return_value.first.return_value = (
+ MagicMock(stripe_customer_id='cus_test123')
+ )
+
result = await has_payment_method('mock_user')
assert result is True
- mock_has_payment_method.assert_called_once_with('mock_user')
+ mock_list_payment_methods.assert_called_once_with('cus_test123')
@pytest.mark.asyncio
async def test_has_payment_method_without_payment_method():
"""Test has_payment_method returns False when user has no payment method."""
- mock_has_payment_method = AsyncMock(return_value=False)
- with patch(
- 'integrations.stripe_service.has_payment_method', mock_has_payment_method
+ with (
+ patch('integrations.stripe_service.session_maker') as mock_session_maker,
+ patch(
+ 'stripe.Customer.list_payment_methods_async',
+ AsyncMock(return_value=MagicMock(data=[])),
+ ) as mock_list_payment_methods,
):
- mock_has_payment_method.return_value = False
+ # Setup mock session
+ mock_session = MagicMock()
+ mock_session_maker.return_value.__enter__.return_value = mock_session
+ mock_session.query.return_value.filter.return_value.first.return_value = (
+ MagicMock(stripe_customer_id='cus_test123')
+ )
+
result = await has_payment_method('mock_user')
assert result is False
- mock_has_payment_method.assert_called_once_with('mock_user')
+ mock_list_payment_methods.assert_called_once_with('cus_test123')
@pytest.mark.asyncio
-async def test_create_customer_setup_session_success():
- """Test successful creation of customer setup session."""
- mock_request = Request(
- scope={'type': 'http', 'state': {'user_id': 'mock_user'}, 'headers': []}
+async def test_cancel_subscription_success():
+ """Test successful subscription cancellation."""
+ from datetime import UTC, datetime
+
+ from storage.subscription_access import SubscriptionAccess
+
+ # Mock active subscription
+ mock_subscription_access = SubscriptionAccess(
+ id=1,
+ status='ACTIVE',
+ user_id='test_user',
+ start_at=datetime.now(UTC),
+ end_at=datetime.now(UTC),
+ amount_paid=2000,
+ stripe_invoice_payment_id='pi_test',
+ stripe_subscription_id='sub_test123',
+ cancelled_at=None,
)
- mock_customer = stripe.Customer(
- id='mock-customer', metadata={'user_id': 'mock-user'}
+ # Mock Stripe subscription response
+ mock_stripe_subscription = MagicMock()
+ mock_stripe_subscription.cancel_at_period_end = True
+
+ with (
+ patch('server.routes.billing.session_maker') as mock_session_maker,
+ patch(
+ 'stripe.Subscription.modify_async',
+ AsyncMock(return_value=mock_stripe_subscription),
+ ) as mock_stripe_modify,
+ ):
+ # Setup mock session
+ mock_session = MagicMock()
+ mock_session_maker.return_value.__enter__.return_value = mock_session
+ mock_session.query.return_value.filter.return_value.filter.return_value.filter.return_value.filter.return_value.filter.return_value.first.return_value = mock_subscription_access
+
+ # Call the function
+ result = await cancel_subscription('test_user')
+
+ # Verify Stripe API was called
+ mock_stripe_modify.assert_called_once_with(
+ 'sub_test123', cancel_at_period_end=True
+ )
+
+ # Verify database was updated
+ assert mock_subscription_access.cancelled_at is not None
+ mock_session.merge.assert_called_once_with(mock_subscription_access)
+ mock_session.commit.assert_called_once()
+
+ # Verify response
+ assert result.status_code == 200
+
+
+async def test_cancel_subscription_no_active_subscription():
+ """Test cancellation when no active subscription exists."""
+ with (
+ patch('server.routes.billing.session_maker') as mock_session_maker,
+ ):
+ # Setup mock session with no subscription found
+ mock_session = MagicMock()
+ mock_session_maker.return_value.__enter__.return_value = mock_session
+ mock_session.query.return_value.filter.return_value.filter.return_value.filter.return_value.filter.return_value.filter.return_value.first.return_value = None
+
+ # Call the function and expect HTTPException
+ with pytest.raises(HTTPException) as exc_info:
+ await cancel_subscription('test_user')
+
+ assert exc_info.value.status_code == 404
+ assert 'No active subscription found' in str(exc_info.value.detail)
+
+
+async def test_cancel_subscription_missing_stripe_id():
+ """Test cancellation when subscription has no Stripe ID."""
+ from datetime import UTC, datetime
+
+ from storage.subscription_access import SubscriptionAccess
+
+ # Mock subscription without Stripe ID
+ mock_subscription_access = SubscriptionAccess(
+ id=1,
+ status='ACTIVE',
+ user_id='test_user',
+ start_at=datetime.now(UTC),
+ end_at=datetime.now(UTC),
+ amount_paid=2000,
+ stripe_invoice_payment_id='pi_test',
+ stripe_subscription_id=None, # Missing Stripe ID
+ cancelled_at=None,
)
- mock_session = MagicMock()
- mock_session.url = 'https://checkout.stripe.com/test-session'
- mock_create = AsyncMock(return_value=mock_session)
with (
+ patch('server.routes.billing.session_maker') as mock_session_maker,
+ ):
+ # Setup mock session
+ mock_session = MagicMock()
+ mock_session_maker.return_value.__enter__.return_value = mock_session
+ mock_session.query.return_value.filter.return_value.filter.return_value.filter.return_value.filter.return_value.filter.return_value.first.return_value = mock_subscription_access
+
+ # Call the function and expect HTTPException
+ with pytest.raises(HTTPException) as exc_info:
+ await cancel_subscription('test_user')
+
+ assert exc_info.value.status_code == 400
+ assert 'missing Stripe subscription ID' in str(exc_info.value.detail)
+
+
+async def test_cancel_subscription_stripe_error():
+ """Test cancellation when Stripe API fails."""
+ from datetime import UTC, datetime
+
+ from storage.subscription_access import SubscriptionAccess
+
+ # Mock active subscription
+ mock_subscription_access = SubscriptionAccess(
+ id=1,
+ status='ACTIVE',
+ user_id='test_user',
+ start_at=datetime.now(UTC),
+ end_at=datetime.now(UTC),
+ amount_paid=2000,
+ stripe_invoice_payment_id='pi_test',
+ stripe_subscription_id='sub_test123',
+ cancelled_at=None,
+ )
+
+ with (
+ patch('server.routes.billing.session_maker') as mock_session_maker,
+ patch(
+ 'stripe.Subscription.modify_async',
+ AsyncMock(side_effect=stripe.StripeError('API Error')),
+ ),
+ ):
+ # Setup mock session
+ mock_session = MagicMock()
+ mock_session_maker.return_value.__enter__.return_value = mock_session
+ mock_session.query.return_value.filter.return_value.filter.return_value.filter.return_value.filter.return_value.filter.return_value.first.return_value = mock_subscription_access
+
+ # Call the function and expect HTTPException
+ with pytest.raises(HTTPException) as exc_info:
+ await cancel_subscription('test_user')
+
+ assert exc_info.value.status_code == 500
+ assert 'Failed to cancel subscription' in str(exc_info.value.detail)
+
+
+async def test_create_subscription_checkout_session_duplicate_prevention():
+ """Test that creating a subscription when user already has active subscription raises error."""
+ from datetime import UTC, datetime
+
+ from storage.subscription_access import SubscriptionAccess
+
+ # Mock active subscription
+ mock_subscription_access = SubscriptionAccess(
+ id=1,
+ status='ACTIVE',
+ user_id='test_user',
+ start_at=datetime.now(UTC),
+ end_at=datetime.now(UTC),
+ amount_paid=2000,
+ stripe_invoice_payment_id='pi_test',
+ stripe_subscription_id='sub_test123',
+ cancelled_at=None,
+ )
+
+ mock_request = Request(scope={'type': 'http'})
+ mock_request._base_url = URL('http://test.com/')
+
+ with (
+ patch('server.routes.billing.session_maker') as mock_session_maker,
+ ):
+ # Setup mock session to return existing active subscription
+ mock_session = MagicMock()
+ mock_session_maker.return_value.__enter__.return_value = mock_session
+ mock_session.query.return_value.filter.return_value.filter.return_value.filter.return_value.filter.return_value.filter.return_value.first.return_value = mock_subscription_access
+
+ # Call the function and expect HTTPException
+ with pytest.raises(HTTPException) as exc_info:
+ await create_subscription_checkout_session(
+ mock_request, user_id='test_user'
+ )
+
+ assert exc_info.value.status_code == 400
+ assert (
+ 'user already has an active subscription'
+ in str(exc_info.value.detail).lower()
+ )
+
+
+async def test_create_subscription_checkout_session_allows_after_cancellation():
+ """Test that creating a subscription is allowed when previous subscription was cancelled."""
+ mock_request = Request(scope={'type': 'http'})
+ mock_request._base_url = URL('http://test.com/')
+
+ mock_session_obj = MagicMock()
+ mock_session_obj.url = 'https://checkout.stripe.com/test-session'
+ mock_session_obj.id = 'test_session_id'
+
+ with (
+ patch('server.routes.billing.session_maker') as mock_session_maker,
patch(
'integrations.stripe_service.find_or_create_customer',
- AsyncMock(return_value=mock_customer),
+ AsyncMock(return_value='cus_test123'),
+ ),
+ patch(
+ 'stripe.checkout.Session.create_async',
+ AsyncMock(return_value=mock_session_obj),
+ ),
+ patch(
+ 'server.routes.billing.SUBSCRIPTION_PRICE_DATA',
+ {'MONTHLY_SUBSCRIPTION': {'unit_amount': 2000}},
),
- patch('stripe.checkout.Session.create_async', mock_create),
):
- result = await create_customer_setup_session(mock_request)
+ # Setup mock session - the query should return None because cancelled subscriptions are filtered out
+ mock_session = MagicMock()
+ mock_session_maker.return_value.__enter__.return_value = mock_session
+ mock_session.query.return_value.filter.return_value.filter.return_value.filter.return_value.filter.return_value.filter.return_value.first.return_value = None
+
+ # Should succeed
+ result = await create_subscription_checkout_session(
+ mock_request, user_id='test_user'
+ )
+
+ assert isinstance(result, CreateBillingSessionResponse)
+ assert result.redirect_url == 'https://checkout.stripe.com/test-session'
- assert isinstance(result, billing.CreateBillingSessionResponse)
+
+async def test_create_subscription_checkout_session_success_no_existing():
+ """Test successful subscription creation when no existing subscription."""
+ mock_request = Request(scope={'type': 'http'})
+ mock_request._base_url = URL('http://test.com/')
+
+ mock_session_obj = MagicMock()
+ mock_session_obj.url = 'https://checkout.stripe.com/test-session'
+ mock_session_obj.id = 'test_session_id'
+
+ with (
+ patch('server.routes.billing.session_maker') as mock_session_maker,
+ patch(
+ 'integrations.stripe_service.find_or_create_customer',
+ AsyncMock(return_value='cus_test123'),
+ ),
+ patch(
+ 'stripe.checkout.Session.create_async',
+ AsyncMock(return_value=mock_session_obj),
+ ),
+ patch(
+ 'server.routes.billing.SUBSCRIPTION_PRICE_DATA',
+ {'MONTHLY_SUBSCRIPTION': {'unit_amount': 2000}},
+ ),
+ ):
+ # Setup mock session to return no existing subscription
+ mock_session = MagicMock()
+ mock_session_maker.return_value.__enter__.return_value = mock_session
+ mock_session.query.return_value.filter.return_value.filter.return_value.filter.return_value.filter.return_value.filter.return_value.first.return_value = None
+
+ # Should succeed
+ result = await create_subscription_checkout_session(
+ mock_request, user_id='test_user'
+ )
+
+ assert isinstance(result, CreateBillingSessionResponse)
assert result.redirect_url == 'https://checkout.stripe.com/test-session'
diff --git a/frontend/__tests__/components/features/payment/payment-form.test.tsx b/frontend/__tests__/components/features/payment/payment-form.test.tsx
index 8c9f510a0e..068f1bf640 100644
--- a/frontend/__tests__/components/features/payment/payment-form.test.tsx
+++ b/frontend/__tests__/components/features/payment/payment-form.test.tsx
@@ -1,10 +1,20 @@
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { render, screen, waitFor } from "@testing-library/react";
+import { screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, test, vi } from "vitest";
import BillingService from "#/api/billing-service/billing-service.api";
import OptionService from "#/api/option-service/option-service.api";
import { PaymentForm } from "#/components/features/payment/payment-form";
+import { renderWithProviders } from "../../../../test-utils";
+
+// Mock the stripe checkout hook to avoid JSDOM navigation issues
+const mockMutate = vi.fn().mockResolvedValue(undefined);
+vi.mock("#/hooks/mutation/stripe/use-create-stripe-checkout-session", () => ({
+ useCreateStripeCheckoutSession: () => ({
+ mutate: mockMutate,
+ mutateAsync: vi.fn().mockResolvedValue(undefined),
+ isPending: false,
+ }),
+}));
describe("PaymentForm", () => {
const getBalanceSpy = vi.spyOn(BillingService, "getBalance");
@@ -14,14 +24,7 @@ describe("PaymentForm", () => {
);
const getConfigSpy = vi.spyOn(OptionService, "getConfig");
- const renderPaymentForm = () =>
- render(<PaymentForm />, {
- wrapper: ({ children }) => (
- <QueryClientProvider client={new QueryClient()}>
- {children}
- </QueryClientProvider>
- ),
- });
+ const renderPaymentForm = () => renderWithProviders(<PaymentForm />);
beforeEach(() => {
// useBalance hook will return the balance only if the APP_MODE is "saas" and the billing feature is enabled
@@ -41,6 +44,7 @@ describe("PaymentForm", () => {
afterEach(() => {
vi.clearAllMocks();
+ mockMutate.mockClear();
});
it("should render the users current balance", async () => {
@@ -73,7 +77,7 @@ describe("PaymentForm", () => {
const topUpButton = screen.getByText("PAYMENT$ADD_CREDIT");
await user.click(topUpButton);
- expect(createCheckoutSessionSpy).toHaveBeenCalledWith(50);
+ expect(mockMutate).toHaveBeenCalledWith({ amount: 50 });
});
it("should only accept integer values", async () => {
@@ -86,7 +90,7 @@ describe("PaymentForm", () => {
const topUpButton = screen.getByText("PAYMENT$ADD_CREDIT");
await user.click(topUpButton);
- expect(createCheckoutSessionSpy).toHaveBeenCalledWith(50);
+ expect(mockMutate).toHaveBeenCalledWith({ amount: 50 });
});
it("should disable the top-up button if the user enters an invalid amount", async () => {
@@ -126,7 +130,7 @@ describe("PaymentForm", () => {
const topUpButton = screen.getByText("PAYMENT$ADD_CREDIT");
await user.click(topUpButton);
- expect(createCheckoutSessionSpy).not.toHaveBeenCalled();
+ expect(mockMutate).not.toHaveBeenCalled();
});
test("user enters an empty string", async () => {
@@ -139,7 +143,7 @@ describe("PaymentForm", () => {
const topUpButton = screen.getByText("PAYMENT$ADD_CREDIT");
await user.click(topUpButton);
- expect(createCheckoutSessionSpy).not.toHaveBeenCalled();
+ expect(mockMutate).not.toHaveBeenCalled();
});
test("user enters a non-numeric value", async () => {
@@ -154,7 +158,7 @@ describe("PaymentForm", () => {
const topUpButton = screen.getByText("PAYMENT$ADD_CREDIT");
await user.click(topUpButton);
- expect(createCheckoutSessionSpy).not.toHaveBeenCalled();
+ expect(mockMutate).not.toHaveBeenCalled();
});
test("user enters less than the minimum amount", async () => {
@@ -167,7 +171,7 @@ describe("PaymentForm", () => {
const topUpButton = screen.getByText("PAYMENT$ADD_CREDIT");
await user.click(topUpButton);
- expect(createCheckoutSessionSpy).not.toHaveBeenCalled();
+ expect(mockMutate).not.toHaveBeenCalled();
});
test("user enters a decimal value", async () => {
@@ -181,7 +185,175 @@ describe("PaymentForm", () => {
const topUpButton = screen.getByText("PAYMENT$ADD_CREDIT");
await user.click(topUpButton);
- expect(createCheckoutSessionSpy).not.toHaveBeenCalled();
+ expect(mockMutate).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("Cancel Subscription", () => {
+ const getSubscriptionAccessSpy = vi.spyOn(
+ BillingService,
+ "getSubscriptionAccess",
+ );
+ const cancelSubscriptionSpy = vi.spyOn(
+ BillingService,
+ "cancelSubscription",
+ );
+
+ beforeEach(() => {
+ // Mock active subscription
+ getSubscriptionAccessSpy.mockResolvedValue({
+ start_at: "2024-01-01T00:00:00Z",
+ end_at: "2024-12-31T23:59:59Z",
+ created_at: "2024-01-01T00:00:00Z",
+ });
+ });
+
+ it("should render cancel subscription button when user has active subscription", async () => {
+ renderPaymentForm();
+
+ await waitFor(() => {
+ const cancelButton = screen.getByTestId("cancel-subscription-button");
+ expect(cancelButton).toBeInTheDocument();
+ expect(cancelButton).toHaveTextContent("PAYMENT$CANCEL_SUBSCRIPTION");
+ });
+ });
+
+ it("should not render cancel subscription button when user has no subscription", async () => {
+ getSubscriptionAccessSpy.mockResolvedValue(null);
+ renderPaymentForm();
+
+ await waitFor(() => {
+ const cancelButton = screen.queryByTestId("cancel-subscription-button");
+ expect(cancelButton).not.toBeInTheDocument();
+ });
+ });
+
+ it("should show confirmation modal when cancel subscription button is clicked", async () => {
+ const user = userEvent.setup();
+ renderPaymentForm();
+
+ const cancelButton = await screen.findByTestId(
+ "cancel-subscription-button",
+ );
+ await user.click(cancelButton);
+
+ // Should show confirmation modal
+ expect(
+ screen.getByTestId("cancel-subscription-modal"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText("PAYMENT$CANCEL_SUBSCRIPTION_TITLE"),
+ ).toBeInTheDocument();
+ // The message should be rendered (either with Trans component or regular text)
+ const modalContent = screen.getByTestId("cancel-subscription-modal");
+ expect(modalContent).toBeInTheDocument();
+ expect(screen.getByTestId("confirm-cancel-button")).toBeInTheDocument();
+ expect(screen.getByTestId("modal-cancel-button")).toBeInTheDocument();
+ });
+
+ it("should close modal when cancel button in modal is clicked", async () => {
+ const user = userEvent.setup();
+ renderPaymentForm();
+
+ const cancelButton = await screen.findByTestId(
+ "cancel-subscription-button",
+ );
+ await user.click(cancelButton);
+
+ // Modal should be visible
+ expect(
+ screen.getByTestId("cancel-subscription-modal"),
+ ).toBeInTheDocument();
+
+ // Click cancel in modal
+ const modalCancelButton = screen.getByTestId("modal-cancel-button");
+ await user.click(modalCancelButton);
+
+ // Modal should be closed
+ expect(
+ screen.queryByTestId("cancel-subscription-modal"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should call cancel subscription API when confirm button is clicked", async () => {
+ const user = userEvent.setup();
+ renderPaymentForm();
+
+ const cancelButton = await screen.findByTestId(
+ "cancel-subscription-button",
+ );
+ await user.click(cancelButton);
+
+ // Click confirm in modal
+ const confirmButton = screen.getByTestId("confirm-cancel-button");
+ await user.click(confirmButton);
+
+ // Should call the cancel subscription API
+ expect(cancelSubscriptionSpy).toHaveBeenCalled();
+ });
+
+ it("should close modal after successful cancellation", async () => {
+ const user = userEvent.setup();
+ cancelSubscriptionSpy.mockResolvedValue({
+ status: "success",
+ message: "Subscription cancelled successfully",
+ });
+ renderPaymentForm();
+
+ const cancelButton = await screen.findByTestId(
+ "cancel-subscription-button",
+ );
+ await user.click(cancelButton);
+
+ const confirmButton = screen.getByTestId("confirm-cancel-button");
+ await user.click(confirmButton);
+
+ // Wait for API call to complete and modal to close
+ await waitFor(() => {
+ expect(
+ screen.queryByTestId("cancel-subscription-modal"),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ it("should show next billing date for active subscription", async () => {
+ // Mock active subscription with end_at as next billing date
+ getSubscriptionAccessSpy.mockResolvedValue({
+ start_at: "2024-01-01T00:00:00Z",
+ end_at: "2025-01-01T00:00:00Z",
+ created_at: "2024-01-01T00:00:00Z",
+ cancelled_at: null,
+ stripe_subscription_id: "sub_123",
+ });
+
+ renderPaymentForm();
+
+ await waitFor(() => {
+ const nextBillingInfo = screen.getByTestId("next-billing-date");
+ expect(nextBillingInfo).toBeInTheDocument();
+ // Check that it contains some date-related content (translation key or actual date)
+ expect(nextBillingInfo).toHaveTextContent(
+ /2025|PAYMENT.*BILLING.*DATE/,
+ );
+ });
+ });
+
+ it("should not show next billing date when subscription is cancelled", async () => {
+ // Mock cancelled subscription
+ getSubscriptionAccessSpy.mockResolvedValue({
+ start_at: "2024-01-01T00:00:00Z",
+ end_at: "2025-01-01T00:00:00Z",
+ created_at: "2024-01-01T00:00:00Z",
+ cancelled_at: "2024-06-15T10:30:00Z",
+ stripe_subscription_id: "sub_123",
+ });
+
+ renderPaymentForm();
+
+ await waitFor(() => {
+ const nextBillingInfo = screen.queryByTestId("next-billing-date");
+ expect(nextBillingInfo).not.toBeInTheDocument();
+ });
});
});
});
diff --git a/frontend/__tests__/routes/llm-settings.test.tsx b/frontend/__tests__/routes/llm-settings.test.tsx
index 0662fea5cb..efb1197f0e 100644
--- a/frontend/__tests__/routes/llm-settings.test.tsx
+++ b/frontend/__tests__/routes/llm-settings.test.tsx
@@ -11,6 +11,19 @@ import {
} from "#/mocks/handlers";
import * as AdvancedSettingsUtlls from "#/utils/has-advanced-settings-set";
import * as ToastHandlers from "#/utils/custom-toast-handlers";
+import BillingService from "#/api/billing-service/billing-service.api";
+
+// Mock react-router hooks
+const mockUseSearchParams = vi.fn();
+vi.mock("react-router", () => ({
+ useSearchParams: () => mockUseSearchParams(),
+}));
+
+// Mock useIsAuthed hook
+const mockUseIsAuthed = vi.fn();
+vi.mock("#/hooks/query/use-is-authed", () => ({
+ useIsAuthed: () => mockUseIsAuthed(),
+}));
const renderLlmSettingsScreen = () =>
render(<LlmSettingsScreen />, {
@@ -24,6 +37,17 @@ const renderLlmSettingsScreen = () =>
beforeEach(() => {
vi.resetAllMocks();
resetTestHandlersMockSettings();
+
+ // Default mock for useSearchParams - returns empty params
+ mockUseSearchParams.mockReturnValue([
+ {
+ get: () => null,
+ },
+ vi.fn(),
+ ]);
+
+ // Default mock for useIsAuthed - returns authenticated by default
+ mockUseIsAuthed.mockReturnValue({ data: true, isLoading: false });
});
describe("Content", () => {
@@ -721,6 +745,17 @@ describe("SaaS mode", () => {
APP_MODE: "saas",
});
+ // Mock subscription access to return valid subscription (so advanced switch is enabled)
+ const getSubscriptionAccessSpy = vi.spyOn(
+ BillingService,
+ "getSubscriptionAccess",
+ );
+ getSubscriptionAccessSpy.mockResolvedValue({
+ start_at: "2024-01-01T00:00:00Z",
+ end_at: "2024-12-31T23:59:59Z",
+ created_at: "2024-01-01T00:00:00Z",
+ });
+
renderLlmSettingsScreen();
await screen.findByTestId("llm-settings-screen");
@@ -739,6 +774,17 @@ describe("SaaS mode", () => {
APP_MODE: "saas",
});
+ // Mock subscription access to return valid subscription (so advanced switch is enabled)
+ const getSubscriptionAccessSpy = vi.spyOn(
+ BillingService,
+ "getSubscriptionAccess",
+ );
+ getSubscriptionAccessSpy.mockResolvedValue({
+ start_at: "2024-01-01T00:00:00Z",
+ end_at: "2024-12-31T23:59:59Z",
+ created_at: "2024-01-01T00:00:00Z",
+ });
+
renderLlmSettingsScreen();
await screen.findByTestId("llm-settings-screen");
@@ -750,4 +796,402 @@ describe("SaaS mode", () => {
expect(runtimeSettingsInput).toBeInTheDocument();
expect(runtimeSettingsInput).toBeDisabled();
});
+
+ describe("SaaS subscription", () => {
+ // Common mock configurations
+ const MOCK_SAAS_CONFIG = {
+ APP_MODE: "saas" as const,
+ GITHUB_CLIENT_ID: "fake-github-client-id",
+ POSTHOG_CLIENT_KEY: "fake-posthog-client-key",
+ FEATURE_FLAGS: {
+ ENABLE_BILLING: true,
+ HIDE_LLM_SETTINGS: false,
+ ENABLE_JIRA: false,
+ ENABLE_JIRA_DC: false,
+ ENABLE_LINEAR: false,
+ },
+ };
+
+ const MOCK_ACTIVE_SUBSCRIPTION = {
+ start_at: "2024-01-01",
+ end_at: "2024-12-31",
+ created_at: "2024-01-01",
+ };
+
+ it("should show upgrade banner and prevent all interactions for unsubscribed SaaS users", async () => {
+ // Mock SaaS mode without subscription
+ const getConfigSpy = vi.spyOn(OptionService, "getConfig");
+ getConfigSpy.mockResolvedValue(MOCK_SAAS_CONFIG);
+
+ // Mock subscription access to return null (no subscription)
+ const getSubscriptionAccessSpy = vi.spyOn(
+ BillingService,
+ "getSubscriptionAccess",
+ );
+ getSubscriptionAccessSpy.mockResolvedValue(null);
+
+ // Mock saveSettings to ensure it's not called
+ const saveSettingsSpy = vi.spyOn(SettingsService, "saveSettings");
+
+ renderLlmSettingsScreen();
+ await screen.findByTestId("llm-settings-screen");
+
+ // Should show upgrade banner
+ expect(screen.getByTestId("upgrade-banner")).toBeInTheDocument();
+
+ // Should have a clickable upgrade button
+ const upgradeButton = screen.getByRole("button", { name: /upgrade/i });
+ expect(upgradeButton).toBeInTheDocument();
+ expect(upgradeButton).not.toBeDisabled();
+
+ // Form should be disabled
+ const form = screen.getByTestId("llm-settings-form-basic");
+ expect(form).toHaveAttribute("aria-disabled", "true");
+
+ // All form inputs should be disabled or non-interactive
+ const providerInput = screen.getByTestId("llm-provider-input");
+ const modelInput = screen.getByTestId("llm-model-input");
+ const apiKeyInput = screen.getByTestId("llm-api-key-input");
+ const advancedSwitch = screen.getByTestId("advanced-settings-switch");
+ const confirmationModeSwitch = screen.getByTestId(
+ "enable-confirmation-mode-switch",
+ );
+ const submitButton = screen.getByTestId("submit-button");
+
+ // Inputs should be disabled
+ expect(providerInput).toBeDisabled();
+ expect(modelInput).toBeDisabled();
+ expect(apiKeyInput).toBeDisabled();
+ expect(advancedSwitch).toBeDisabled();
+ expect(confirmationModeSwitch).toBeDisabled();
+ expect(submitButton).toBeDisabled();
+
+ // Try to interact with inputs - they should not respond
+ await userEvent.click(providerInput);
+ await userEvent.type(apiKeyInput, "test-key");
+
+ // Values should not change
+ expect(apiKeyInput).toHaveValue("");
+
+ // Try to submit form - should not call API
+ await userEvent.click(submitButton);
+ expect(saveSettingsSpy).not.toHaveBeenCalled();
+ });
+
+ it("should call subscription checkout API when upgrade button is clicked", async () => {
+ // Mock SaaS mode without subscription
+ const getConfigSpy = vi.spyOn(OptionService, "getConfig");
+ getConfigSpy.mockResolvedValue(MOCK_SAAS_CONFIG);
+
+ // Mock subscription access to return null (no subscription)
+ const getSubscriptionAccessSpy = vi.spyOn(
+ BillingService,
+ "getSubscriptionAccess",
+ );
+ getSubscriptionAccessSpy.mockResolvedValue(null);
+
+ // Mock the subscription checkout API call
+ const createSubscriptionCheckoutSessionSpy = vi.spyOn(
+ BillingService,
+ "createSubscriptionCheckoutSession",
+ );
+ createSubscriptionCheckoutSessionSpy.mockResolvedValue({});
+
+ renderLlmSettingsScreen();
+ await screen.findByTestId("llm-settings-screen");
+
+ // Click the upgrade button
+ const upgradeButton = screen.getByRole("button", { name: /upgrade/i });
+ await userEvent.click(upgradeButton);
+
+ // Should call the subscription checkout API
+ expect(createSubscriptionCheckoutSessionSpy).toHaveBeenCalled();
+ });
+
+ it("should disable upgrade button for unauthenticated users in SaaS mode", async () => {
+ // Mock SaaS mode without subscription
+ const getConfigSpy = vi.spyOn(OptionService, "getConfig");
+ getConfigSpy.mockResolvedValue(MOCK_SAAS_CONFIG);
+
+ // Mock subscription access to return null (no subscription)
+ const getSubscriptionAccessSpy = vi.spyOn(
+ BillingService,
+ "getSubscriptionAccess",
+ );
+ getSubscriptionAccessSpy.mockResolvedValue(null);
+
+ // Mock subscription checkout API
+ const createSubscriptionCheckoutSessionSpy = vi.spyOn(
+ BillingService,
+ "createSubscriptionCheckoutSession",
+ );
+
+ // Mock authentication to return false (unauthenticated) from the start
+ mockUseIsAuthed.mockReturnValue({ data: false, isLoading: false });
+
+ // Mock settings to return default settings even when unauthenticated
+ // This is necessary because the useSettings hook is disabled when user is not authenticated
+ const getSettingsSpy = vi.spyOn(SettingsService, "getSettings");
+ getSettingsSpy.mockResolvedValue(MOCK_DEFAULT_USER_SETTINGS);
+
+ renderLlmSettingsScreen();
+
+ // Wait for either the settings screen or skeleton to appear
+ await waitFor(() => {
+ const settingsScreen = screen.queryByTestId("llm-settings-screen");
+ const skeleton = screen.queryByTestId("app-settings-skeleton");
+ expect(settingsScreen || skeleton).toBeInTheDocument();
+ });
+
+ // If we get the skeleton, the test scenario isn't valid - skip the rest
+ if (screen.queryByTestId("app-settings-skeleton")) {
+ // For unauthenticated users, the settings don't load, so no upgrade banner is shown
+ // This is the expected behavior - unauthenticated users see a skeleton loading state
+ expect(screen.queryByTestId("upgrade-banner")).not.toBeInTheDocument();
+ return;
+ }
+
+ await screen.findByTestId("llm-settings-screen");
+
+ // Should show upgrade banner
+ expect(screen.getByTestId("upgrade-banner")).toBeInTheDocument();
+
+ // Upgrade button should be disabled for unauthenticated users
+ const upgradeButton = screen.getByRole("button", { name: /upgrade/i });
+ expect(upgradeButton).toBeInTheDocument();
+ expect(upgradeButton).toBeDisabled();
+
+ // Clicking disabled button should not call the API
+ await userEvent.click(upgradeButton);
+ expect(createSubscriptionCheckoutSessionSpy).not.toHaveBeenCalled();
+ });
+
+ it("should not show upgrade banner and allow form interaction for subscribed SaaS users", async () => {
+ // Mock SaaS mode with subscription
+ const getConfigSpy = vi.spyOn(OptionService, "getConfig");
+ getConfigSpy.mockResolvedValue(MOCK_SAAS_CONFIG);
+
+ // Mock subscription access to return active subscription
+ const getSubscriptionAccessSpy = vi.spyOn(
+ BillingService,
+ "getSubscriptionAccess",
+ );
+ getSubscriptionAccessSpy.mockResolvedValue(MOCK_ACTIVE_SUBSCRIPTION);
+
+ renderLlmSettingsScreen();
+ await screen.findByTestId("llm-settings-screen");
+
+ // Wait for subscription data to load
+ await waitFor(() => {
+ expect(getSubscriptionAccessSpy).toHaveBeenCalled();
+ });
+
+ // Should NOT show upgrade banner
+ expect(screen.queryByTestId("upgrade-banner")).not.toBeInTheDocument();
+
+ // Form should NOT be disabled
+ const form = screen.getByTestId("llm-settings-form-basic");
+ expect(form).not.toHaveAttribute("aria-disabled", "true");
+ });
+
+ it("should not call save settings API when making changes in disabled form for unsubscribed users", async () => {
+ // Mock SaaS mode without subscription
+ const getConfigSpy = vi.spyOn(OptionService, "getConfig");
+ getConfigSpy.mockResolvedValue(MOCK_SAAS_CONFIG);
+
+ // Mock subscription access to return null (no subscription)
+ const getSubscriptionAccessSpy = vi.spyOn(
+ BillingService,
+ "getSubscriptionAccess",
+ );
+ getSubscriptionAccessSpy.mockResolvedValue(null);
+
+ // Mock saveSettings to track calls
+ const saveSettingsSpy = vi.spyOn(SettingsService, "saveSettings");
+
+ renderLlmSettingsScreen();
+ await screen.findByTestId("llm-settings-screen");
+
+ // Verify that form elements are disabled for unsubscribed users
+ const confirmationModeSwitch = screen.getByTestId(
+ "enable-confirmation-mode-switch",
+ );
+ const submitButton = screen.getByTestId("submit-button");
+
+ expect(confirmationModeSwitch).not.toBeChecked();
+ expect(confirmationModeSwitch).toBeDisabled();
+ expect(submitButton).toBeDisabled();
+
+ // Try to click the disabled confirmation mode switch - it should not change state
+ await userEvent.click(confirmationModeSwitch);
+ expect(confirmationModeSwitch).not.toBeChecked(); // Should remain unchecked
+
+ // Try to submit the form - button should remain disabled
+ await userEvent.click(submitButton);
+
+ // Should NOT call save settings API for unsubscribed users
+ expect(saveSettingsSpy).not.toHaveBeenCalled();
+ });
+
+ it("should show backdrop overlay for unsubscribed users", async () => {
+ // Mock SaaS mode without subscription
+ const getConfigSpy = vi.spyOn(OptionService, "getConfig");
+ getConfigSpy.mockResolvedValue(MOCK_SAAS_CONFIG);
+
+ // Mock subscription access to return null (no subscription)
+ const getSubscriptionAccessSpy = vi.spyOn(
+ BillingService,
+ "getSubscriptionAccess",
+ );
+ getSubscriptionAccessSpy.mockResolvedValue(null);
+
+ renderLlmSettingsScreen();
+ await screen.findByTestId("llm-settings-screen");
+
+ // Wait for subscription data to load
+ await waitFor(() => {
+ expect(getSubscriptionAccessSpy).toHaveBeenCalled();
+ });
+
+ // Should show upgrade banner
+ expect(screen.getByTestId("upgrade-banner")).toBeInTheDocument();
+
+ // Should show backdrop overlay
+ const backdrop = screen.getByTestId("settings-backdrop");
+ expect(backdrop).toBeInTheDocument();
+ });
+
+ it("should not show backdrop overlay for subscribed users", async () => {
+ // Mock SaaS mode with subscription
+ const getConfigSpy = vi.spyOn(OptionService, "getConfig");
+ getConfigSpy.mockResolvedValue(MOCK_SAAS_CONFIG);
+
+ // Mock subscription access to return active subscription
+ const getSubscriptionAccessSpy = vi.spyOn(
+ BillingService,
+ "getSubscriptionAccess",
+ );
+ getSubscriptionAccessSpy.mockResolvedValue(MOCK_ACTIVE_SUBSCRIPTION);
+
+ renderLlmSettingsScreen();
+ await screen.findByTestId("llm-settings-screen");
+
+ // Wait for subscription data to load
+ await waitFor(() => {
+ expect(getSubscriptionAccessSpy).toHaveBeenCalled();
+ });
+
+ // Should NOT show backdrop overlay
+ expect(screen.queryByTestId("settings-backdrop")).not.toBeInTheDocument();
+ });
+
+ it("should display success toast when redirected back with ?checkout=success parameter", async () => {
+ // Mock SaaS mode
+ const getConfigSpy = vi.spyOn(OptionService, "getConfig");
+ getConfigSpy.mockResolvedValue(MOCK_SAAS_CONFIG);
+
+ // Mock subscription access
+ const getSubscriptionAccessSpy = vi.spyOn(
+ BillingService,
+ "getSubscriptionAccess",
+ );
+ getSubscriptionAccessSpy.mockResolvedValue(MOCK_ACTIVE_SUBSCRIPTION);
+
+ // Mock toast handler
+ const displaySuccessToastSpy = vi.spyOn(
+ ToastHandlers,
+ "displaySuccessToast",
+ );
+
+ // Mock URL search params with ?checkout=success
+ mockUseSearchParams.mockReturnValue([
+ {
+ get: (param: string) => (param === "checkout" ? "success" : null),
+ },
+ vi.fn(),
+ ]);
+
+ // Render component with checkout=success parameter
+ renderLlmSettingsScreen();
+ await screen.findByTestId("llm-settings-screen");
+
+ // Verify success toast is displayed with correct message
+ expect(displaySuccessToastSpy).toHaveBeenCalledWith(
+ "SUBSCRIPTION$SUCCESS",
+ );
+ });
+
+ it("should display error toast when redirected back with ?checkout=cancel parameter", async () => {
+ // Mock SaaS mode
+ const getConfigSpy = vi.spyOn(OptionService, "getConfig");
+ getConfigSpy.mockResolvedValue(MOCK_SAAS_CONFIG);
+
+ // Mock subscription access
+ const getSubscriptionAccessSpy = vi.spyOn(
+ BillingService,
+ "getSubscriptionAccess",
+ );
+ getSubscriptionAccessSpy.mockResolvedValue(MOCK_ACTIVE_SUBSCRIPTION);
+
+ // Mock toast handler
+ const displayErrorToastSpy = vi.spyOn(ToastHandlers, "displayErrorToast");
+
+ // Mock URL search params with ?checkout=cancel
+ mockUseSearchParams.mockReturnValue([
+ {
+ get: (param: string) => (param === "checkout" ? "cancel" : null),
+ },
+ vi.fn(),
+ ]);
+
+ // Render component with checkout=cancel parameter
+ renderLlmSettingsScreen();
+ await screen.findByTestId("llm-settings-screen");
+
+ // Verify error toast is displayed with correct message
+ expect(displayErrorToastSpy).toHaveBeenCalledWith("SUBSCRIPTION$FAILURE");
+ });
+
+ it("should show upgrade banner when subscription is expired or disabled", async () => {
+ // Mock SaaS mode
+ const getConfigSpy = vi.spyOn(OptionService, "getConfig");
+ getConfigSpy.mockResolvedValue(MOCK_SAAS_CONFIG);
+
+ // Mock subscription access to return null (expired/disabled subscriptions return null from backend)
+ // The backend only returns active subscriptions within their validity period
+ const getSubscriptionAccessSpy = vi.spyOn(
+ BillingService,
+ "getSubscriptionAccess",
+ );
+ getSubscriptionAccessSpy.mockResolvedValue(null);
+
+ renderLlmSettingsScreen();
+ await screen.findByTestId("llm-settings-screen");
+
+ // Wait for subscription data to load
+ await waitFor(() => {
+ expect(getSubscriptionAccessSpy).toHaveBeenCalled();
+ });
+
+ // Should show upgrade banner for expired/disabled subscriptions (when API returns null)
+ expect(screen.getByTestId("upgrade-banner")).toBeInTheDocument();
+
+ // Form should be disabled
+ const form = screen.getByTestId("llm-settings-form-basic");
+ expect(form).toHaveAttribute("aria-disabled", "true");
+
+ // All form inputs should be disabled
+ const providerInput = screen.getByTestId("llm-provider-input");
+ const modelInput = screen.getByTestId("llm-model-input");
+ const apiKeyInput = screen.getByTestId("llm-api-key-input");
+ const confirmationModeSwitch = screen.getByTestId(
+ "enable-confirmation-mode-switch",
+ );
+
+ expect(providerInput).toBeDisabled();
+ expect(modelInput).toBeDisabled();
+ expect(apiKeyInput).toBeDisabled();
+ expect(confirmationModeSwitch).toBeDisabled();
+ });
+ });
});
diff --git a/frontend/__tests__/routes/settings-with-payment.test.tsx b/frontend/__tests__/routes/settings-with-payment.test.tsx
index e373d3dc98..d07567c905 100644
--- a/frontend/__tests__/routes/settings-with-payment.test.tsx
+++ b/frontend/__tests__/routes/settings-with-payment.test.tsx
@@ -5,7 +5,6 @@ import { createRoutesStub } from "react-router";
import { renderWithProviders } from "test-utils";
import SettingsScreen from "#/routes/settings";
import { PaymentForm } from "#/components/features/payment/payment-form";
-import * as useSettingsModule from "#/hooks/query/use-settings";
// Mock the useSettings hook
vi.mock("#/hooks/query/use-settings", async () => {
@@ -35,6 +34,7 @@ vi.mock("react-i18next", async () => {
SETTINGS$NAV_INTEGRATIONS: "Integrations",
SETTINGS$NAV_APPLICATION: "Application",
SETTINGS$NAV_CREDITS: "Credits",
+ SETTINGS$NAV_BILLING: "Billing",
SETTINGS$NAV_API_KEYS: "API Keys",
SETTINGS$NAV_LLM: "LLM",
SETTINGS$NAV_USER: "User",
@@ -107,16 +107,16 @@ describe("Settings Billing", () => {
vi.clearAllMocks();
});
- it("should not render the credits tab if OSS mode", async () => {
+ it("should not render the billing tab if OSS mode", async () => {
// OSS mode is set by default in beforeEach
renderSettingsScreen();
const navbar = await screen.findByTestId("settings-navbar");
- const credits = within(navbar).queryByText("Credits");
+ const credits = within(navbar).queryByText("Billing");
expect(credits).not.toBeInTheDocument();
});
- it("should render the credits tab if SaaS mode and billing is enabled", async () => {
+ it("should render the billing tab if SaaS mode and billing is enabled", async () => {
mockUseConfig.mockReturnValue({
data: {
APP_MODE: "saas",
@@ -136,10 +136,10 @@ describe("Settings Billing", () => {
renderSettingsScreen();
const navbar = await screen.findByTestId("settings-navbar");
- within(navbar).getByText("Credits");
+ within(navbar).getByText("Billing");
});
- it("should render the billing settings if clicking the credits item", async () => {
+ it("should render the billing settings if clicking the billing item", async () => {
const user = userEvent.setup();
mockUseConfig.mockReturnValue({
data: {
@@ -160,7 +160,7 @@ describe("Settings Billing", () => {
renderSettingsScreen();
const navbar = await screen.findByTestId("settings-navbar");
- const credits = within(navbar).getByText("Credits");
+ const credits = within(navbar).getByText("Billing");
await user.click(credits);
const billingSection = await screen.findByTestId("billing-settings");
diff --git a/frontend/__tests__/routes/settings.test.tsx b/frontend/__tests__/routes/settings.test.tsx
index f960f18ecb..c433e091aa 100644
--- a/frontend/__tests__/routes/settings.test.tsx
+++ b/frontend/__tests__/routes/settings.test.tsx
@@ -129,14 +129,15 @@ describe("Settings Screen", () => {
mockQueryClient.setQueryData(["config"], saasConfig);
const sectionsToInclude = [
+ "llm", // LLM settings are now always shown in SaaS mode
"user",
"integrations",
"application",
- "credits", // The nav item shows "credits" text but routes to /billing
+ "billing", // The nav item shows "billing" text and routes to /billing
"secrets",
"api keys",
];
- const sectionsToExclude = ["llm"];
+ const sectionsToExclude: string[] = []; // No sections are excluded in SaaS mode now
renderSettingsScreen();
diff --git a/frontend/src/api/billing-service/billing-service.api.ts b/frontend/src/api/billing-service/billing-service.api.ts
index 0cfb692dcc..2f78b910f6 100644
--- a/frontend/src/api/billing-service/billing-service.api.ts
+++ b/frontend/src/api/billing-service/billing-service.api.ts
@@ -1,5 +1,8 @@
import { openHands } from "../open-hands-axios";
-import { SubscriptionAccess } from "./billing.types";
+import {
+ CancelSubscriptionResponse,
+ SubscriptionAccess,
+} from "./billing.types";
/**
* Billing Service API - Handles all billing-related API endpoints
@@ -52,6 +55,30 @@ class BillingService {
);
return data;
}
+
+ /**
+ * Create a subscription checkout session for subscribing to a plan
+ * @returns The redirect URL for the subscription checkout session
+ */
+ static async createSubscriptionCheckoutSession(): Promise<{
+ redirect_url?: string;
+ }> {
+ const { data } = await openHands.post(
+ "/api/billing/subscription-checkout-session",
+ );
+ return data;
+ }
+
+ /**
+ * Cancel the user's subscription
+ * @returns The response indicating the result of the cancellation request
+ */
+ static async cancelSubscription(): Promise<CancelSubscriptionResponse> {
+ const { data } = await openHands.post<CancelSubscriptionResponse>(
+ "/api/billing/cancel-subscription",
+ );
+ return data;
+ }
}
export default BillingService;
diff --git a/frontend/src/api/billing-service/billing.types.ts b/frontend/src/api/billing-service/billing.types.ts
index 28827597e3..b6b05cfb0c 100644
--- a/frontend/src/api/billing-service/billing.types.ts
+++ b/frontend/src/api/billing-service/billing.types.ts
@@ -1,6 +1,12 @@
export type SubscriptionAccess = {
- status: "ACTIVE" | "DISABLED";
start_at: string;
end_at: string;
created_at: string;
+ cancelled_at?: string | null;
+ stripe_subscription_id?: string | null;
};
+
+export interface CancelSubscriptionResponse {
+ status: string;
+ message: string;
+}
diff --git a/frontend/src/components/features/context-menu/account-settings-context-menu.tsx b/frontend/src/components/features/context-menu/account-settings-context-menu.tsx
index b2fa06ce57..b3040f4896 100644
--- a/frontend/src/components/features/context-menu/account-settings-context-menu.tsx
+++ b/frontend/src/components/features/context-menu/account-settings-context-menu.tsx
@@ -36,10 +36,15 @@ const SAAS_NAV_ITEMS = [
to: "/settings/app",
text: "COMMON$APPLICATION_SETTINGS",
},
+ {
+ icon: <CircuitIcon width={16} height={16} />,
+ to: "/settings",
+ text: "COMMON$LANGUAGE_MODEL_LLM",
+ },
{
icon: <CreditCardIcon width={16} height={16} />,
to: "/settings/billing",
- text: "SETTINGS$NAV_CREDITS",
+ text: "SETTINGS$NAV_BILLING",
},
{
icon: <KeyIcon width={16} height={16} />,
@@ -51,6 +56,11 @@ const SAAS_NAV_ITEMS = [
to: "/settings/api-keys",
text: "SETTINGS$NAV_API_KEYS",
},
+ {
+ icon: <ServerProcessIcon width={16} height={16} />,
+ to: "/settings/mcp",
+ text: "SETTINGS$NAV_MCP",
+ },
];
const OSS_NAV_ITEMS = [
diff --git a/frontend/src/components/features/payment/cancel-subscription-modal.tsx b/frontend/src/components/features/payment/cancel-subscription-modal.tsx
new file mode 100644
index 0000000000..b479f94f44
--- /dev/null
+++ b/frontend/src/components/features/payment/cancel-subscription-modal.tsx
@@ -0,0 +1,83 @@
+import React from "react";
+import { useTranslation, Trans } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
+import { useCancelSubscription } from "#/hooks/mutation/use-cancel-subscription";
+import {
+ displayErrorToast,
+ displaySuccessToast,
+} from "#/utils/custom-toast-handlers";
+
+interface CancelSubscriptionModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+ endDate?: string;
+}
+
+export function CancelSubscriptionModal({
+ isOpen,
+ onClose,
+ endDate,
+}: CancelSubscriptionModalProps) {
+ const { t } = useTranslation();
+ const cancelSubscriptionMutation = useCancelSubscription();
+
+ const handleCancelSubscription = async () => {
+ try {
+ await cancelSubscriptionMutation.mutateAsync();
+ displaySuccessToast(t(I18nKey.PAYMENT$SUBSCRIPTION_CANCELLED));
+ onClose();
+ } catch (error) {
+ displayErrorToast(t(I18nKey.ERROR$GENERIC));
+ }
+ };
+
+ if (!isOpen) return null;
+
+ return (
+ <ModalBackdrop>
+ <div
+ data-testid="cancel-subscription-modal"
+ className="bg-base-secondary p-6 rounded-xl flex flex-col gap-4 border border-tertiary w-[500px]"
+ >
+ <h3 className="text-xl font-bold">
+ {t(I18nKey.PAYMENT$CANCEL_SUBSCRIPTION_TITLE)}
+ </h3>
+ <p className="text-sm">
+ {endDate ? (
+ <Trans
+ i18nKey={I18nKey.PAYMENT$CANCEL_SUBSCRIPTION_MESSAGE_WITH_DATE}
+ values={{ date: endDate }}
+ components={{ date: <span className="underline" /> }}
+ />
+ ) : (
+ t(I18nKey.PAYMENT$CANCEL_SUBSCRIPTION_MESSAGE)
+ )}
+ </p>
+ <div className="w-full flex gap-2 mt-2">
+ <BrandButton
+ testId="confirm-cancel-button"
+ type="button"
+ variant="primary"
+ className="grow"
+ onClick={handleCancelSubscription}
+ isDisabled={cancelSubscriptionMutation.isPending}
+ >
+ {t(I18nKey.BUTTON$CONFIRM)}
+ </BrandButton>
+ <BrandButton
+ testId="modal-cancel-button"
+ type="button"
+ variant="secondary"
+ className="grow"
+ onClick={onClose}
+ isDisabled={cancelSubscriptionMutation.isPending}
+ >
+ {t(I18nKey.BUTTON$CANCEL)}
+ </BrandButton>
+ </div>
+ </div>
+ </ModalBackdrop>
+ );
+}
diff --git a/frontend/src/components/features/payment/payment-form.tsx b/frontend/src/components/features/payment/payment-form.tsx
index 8452345ab1..9f82e38e5f 100644
--- a/frontend/src/components/features/payment/payment-form.tsx
+++ b/frontend/src/components/features/payment/payment-form.tsx
@@ -1,7 +1,8 @@
import React from "react";
-import { useTranslation } from "react-i18next";
+import { useTranslation, Trans } from "react-i18next";
import { useCreateStripeCheckoutSession } from "#/hooks/mutation/stripe/use-create-stripe-checkout-session";
import { useBalance } from "#/hooks/query/use-balance";
+import { useSubscriptionAccess } from "#/hooks/query/use-subscription-access";
import { cn } from "#/utils/utils";
import MoneyIcon from "#/icons/money.svg?react";
import { SettingsInput } from "../settings/settings-input";
@@ -10,13 +11,24 @@ import { LoadingSpinner } from "#/components/shared/loading-spinner";
import { amountIsValid } from "#/utils/amount-is-valid";
import { I18nKey } from "#/i18n/declaration";
import { PoweredByStripeTag } from "./powered-by-stripe-tag";
+import { CancelSubscriptionModal } from "./cancel-subscription-modal";
export function PaymentForm() {
const { t } = useTranslation();
const { data: balance, isLoading } = useBalance();
+ const { data: subscriptionAccess } = useSubscriptionAccess();
const { mutate: addBalance, isPending } = useCreateStripeCheckoutSession();
const [buttonIsDisabled, setButtonIsDisabled] = React.useState(true);
+ const [showCancelModal, setShowCancelModal] = React.useState(false);
+
+ const subscriptionExpiredDate =
+ subscriptionAccess?.end_at &&
+ new Date(subscriptionAccess.end_at).toLocaleDateString("en-US", {
+ year: "numeric",
+ month: "long",
+ day: "numeric",
+ });
const billingFormAction = async (formData: FormData) => {
const amount = formData.get("top-up-input")?.toString();
@@ -82,7 +94,50 @@ export function PaymentForm() {
{isPending && <LoadingSpinner size="small" />}
<PoweredByStripeTag />
</div>
+
+ {/* Cancel Subscription Button or Cancellation Message */}
+ {subscriptionAccess && (
+ <div className="flex flex-col w-[680px] gap-2 mt-4">
+ {subscriptionAccess.cancelled_at ? (
+ <div className="text-red-500 text-sm">
+ <Trans
+ i18nKey={I18nKey.PAYMENT$SUBSCRIPTION_CANCELLED_EXPIRES}
+ values={{ date: subscriptionExpiredDate }}
+ components={{ date: <span className="underline" /> }}
+ />
+ </div>
+ ) : (
+ <div className="flex items-center gap-4">
+ <BrandButton
+ testId="cancel-subscription-button"
+ variant="ghost-danger"
+ type="button"
+ onClick={() => setShowCancelModal(true)}
+ >
+ {t(I18nKey.PAYMENT$CANCEL_SUBSCRIPTION)}
+ </BrandButton>
+ <div
+ className="text-sm text-gray-300"
+ data-testid="next-billing-date"
+ >
+ <Trans
+ i18nKey={I18nKey.PAYMENT$NEXT_BILLING_DATE}
+ values={{ date: subscriptionExpiredDate }}
+ components={{ date: <span className="underline" /> }}
+ />
+ </div>
+ </div>
+ )}
+ </div>
+ )}
</div>
+
+ {/* Cancel Subscription Modal */}
+ <CancelSubscriptionModal
+ isOpen={showCancelModal}
+ onClose={() => setShowCancelModal(false)}
+ endDate={subscriptionExpiredDate}
+ />
</form>
);
}
diff --git a/frontend/src/components/features/settings/banner-message.tsx b/frontend/src/components/features/settings/banner-message.tsx
new file mode 100644
index 0000000000..819ad204e5
--- /dev/null
+++ b/frontend/src/components/features/settings/banner-message.tsx
@@ -0,0 +1,12 @@
+import { cn } from "#/utils/utils";
+
+interface BannerMessageProps {
+ message: string;
+ className?: string;
+}
+
+export function BannerMessage({ message, className }: BannerMessageProps) {
+ return (
+ <p className={cn("text-xs font-medium text-black", className)}>{message}</p>
+ );
+}
diff --git a/frontend/src/components/features/settings/brand-button.tsx b/frontend/src/components/features/settings/brand-button.tsx
index b0857b3cac..624a03e915 100644
--- a/frontend/src/components/features/settings/brand-button.tsx
+++ b/frontend/src/components/features/settings/brand-button.tsx
@@ -3,7 +3,7 @@ import { cn } from "#/utils/utils";
interface BrandButtonProps {
testId?: string;
name?: string;
- variant: "primary" | "secondary" | "danger";
+ variant: "primary" | "secondary" | "danger" | "ghost-danger";
type: React.ButtonHTMLAttributes<HTMLButtonElement>["type"];
isDisabled?: boolean;
className?: string;
@@ -36,6 +36,8 @@ export function BrandButton({
variant === "primary" && "bg-primary text-[#0D0F11]",
variant === "secondary" && "border border-primary text-primary",
variant === "danger" && "bg-red-600 text-white hover:bg-red-700",
+ variant === "ghost-danger" &&
+ "bg-transparent text-red-600 underline hover:text-red-700 hover:no-underline font-medium",
startContent && "flex items-center justify-center gap-2",
className,
)}
diff --git a/frontend/src/components/features/settings/index.ts b/frontend/src/components/features/settings/index.ts
new file mode 100644
index 0000000000..b26e66fddb
--- /dev/null
+++ b/frontend/src/components/features/settings/index.ts
@@ -0,0 +1,3 @@
+export { UpgradeBanner } from "./upgrade-banner";
+export { UpgradeButton } from "./upgrade-button";
+export { BannerMessage } from "./banner-message";
diff --git a/frontend/src/components/features/settings/pro-pill.tsx b/frontend/src/components/features/settings/pro-pill.tsx
new file mode 100644
index 0000000000..6cb26c3009
--- /dev/null
+++ b/frontend/src/components/features/settings/pro-pill.tsx
@@ -0,0 +1,22 @@
+import { useTranslation } from "react-i18next";
+import { cn } from "#/utils/utils";
+import { I18nKey } from "#/i18n/declaration";
+
+interface ProPillProps {
+ className?: string;
+}
+
+export function ProPill({ className }: ProPillProps) {
+ const { t } = useTranslation();
+
+ return (
+ <span
+ className={cn(
+ "bg-[#3a3c45] border border-[#ffeeaa] text-[#ffeeaa] text-[8px] font-medium px-1.5 py-0.5 rounded-full whitespace-nowrap",
+ className,
+ )}
+ >
+ {t(I18nKey.SETTINGS$PRO_PILL)}
+ </span>
+ );
+}
diff --git a/frontend/src/components/features/settings/settings-switch.tsx b/frontend/src/components/features/settings/settings-switch.tsx
index 9ae1784708..8df764bbb7 100644
--- a/frontend/src/components/features/settings/settings-switch.tsx
+++ b/frontend/src/components/features/settings/settings-switch.tsx
@@ -1,6 +1,7 @@
import React from "react";
import { useTranslation } from "react-i18next";
import { I18nKey } from "#/i18n/declaration";
+import { cn } from "#/utils/utils";
import { StyledSwitchComponent } from "./styled-switch-component";
interface SettingsSwitchProps {
@@ -10,6 +11,7 @@ interface SettingsSwitchProps {
defaultIsToggled?: boolean;
isToggled?: boolean;
isBeta?: boolean;
+ isDisabled?: boolean;
}
export function SettingsSwitch({
@@ -20,17 +22,24 @@ export function SettingsSwitch({
defaultIsToggled,
isToggled: controlledIsToggled,
isBeta,
+ isDisabled,
}: React.PropsWithChildren<SettingsSwitchProps>) {
const { t } = useTranslation();
const [isToggled, setIsToggled] = React.useState(defaultIsToggled ?? false);
const handleToggle = (value: boolean) => {
+ if (isDisabled) return;
setIsToggled(value);
onToggle?.(value);
};
return (
- <label className="flex items-center gap-2 w-fit cursor-pointer">
+ <label
+ className={cn(
+ "flex items-center gap-2 w-fit",
+ isDisabled ? "cursor-not-allowed opacity-50" : "cursor-pointer",
+ )}
+ >
<input
hidden
data-testid={testId}
@@ -38,6 +47,7 @@ export function SettingsSwitch({
type="checkbox"
onChange={(e) => handleToggle(e.target.checked)}
checked={controlledIsToggled ?? isToggled}
+ disabled={isDisabled}
/>
<StyledSwitchComponent isToggled={controlledIsToggled ?? isToggled} />
diff --git a/frontend/src/components/features/settings/upgrade-banner-with-backdrop.tsx b/frontend/src/components/features/settings/upgrade-banner-with-backdrop.tsx
new file mode 100644
index 0000000000..369869aa92
--- /dev/null
+++ b/frontend/src/components/features/settings/upgrade-banner-with-backdrop.tsx
@@ -0,0 +1,30 @@
+import React from "react";
+import { useTranslation } from "react-i18next";
+import { UpgradeBanner } from "#/components/features/settings";
+
+interface UpgradeBannerWithBackdropProps {
+ onUpgradeClick: () => void;
+ isDisabled?: boolean;
+}
+
+export function UpgradeBannerWithBackdrop({
+ onUpgradeClick,
+ isDisabled,
+}: UpgradeBannerWithBackdropProps) {
+ const { t } = useTranslation();
+
+ return (
+ <>
+ <UpgradeBanner
+ message={t("SETTINGS$UPGRADE_BANNER_MESSAGE")}
+ onUpgradeClick={onUpgradeClick}
+ className="sticky top-0 z-30"
+ isDisabled={isDisabled}
+ />
+ <div
+ data-testid="settings-backdrop"
+ className="absolute inset-0 z-20 opacity-50 bg-[#26282D]"
+ />
+ </>
+ );
+}
diff --git a/frontend/src/components/features/settings/upgrade-banner.tsx b/frontend/src/components/features/settings/upgrade-banner.tsx
new file mode 100644
index 0000000000..11d6f86eb1
--- /dev/null
+++ b/frontend/src/components/features/settings/upgrade-banner.tsx
@@ -0,0 +1,30 @@
+import { UpgradeButton } from "./upgrade-button";
+import { BannerMessage } from "./banner-message";
+import { cn } from "#/utils/utils";
+
+interface UpgradeBannerProps {
+ message: string;
+ onUpgradeClick?: () => void;
+ className?: string;
+ isDisabled?: boolean;
+}
+
+export function UpgradeBanner({
+ message,
+ onUpgradeClick,
+ className,
+ isDisabled,
+}: UpgradeBannerProps) {
+ return (
+ <div
+ className={cn(
+ "bg-primary text-base flex items-center justify-center gap-3 p-2 w-full",
+ className,
+ )}
+ data-testid="upgrade-banner"
+ >
+ <BannerMessage message={message} />
+ <UpgradeButton onClick={onUpgradeClick} isDisabled={isDisabled} />
+ </div>
+ );
+}
diff --git a/frontend/src/components/features/settings/upgrade-button.tsx b/frontend/src/components/features/settings/upgrade-button.tsx
new file mode 100644
index 0000000000..82e632f3f3
--- /dev/null
+++ b/frontend/src/components/features/settings/upgrade-button.tsx
@@ -0,0 +1,30 @@
+import { useTranslation } from "react-i18next";
+import { cn } from "#/utils/utils";
+
+interface UpgradeButtonProps {
+ onClick?: () => void;
+ className?: string;
+ isDisabled?: boolean;
+}
+
+export function UpgradeButton({
+ onClick,
+ className,
+ isDisabled,
+}: UpgradeButtonProps) {
+ const { t } = useTranslation();
+
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ disabled={isDisabled}
+ className={cn(
+ "bg-neutral-500 text-white text-[9px] font-medium w-16 h-4 rounded-[100px] mix-blend-multiply hover:opacity-80 transition-opacity cursor-pointer",
+ className,
+ )}
+ >
+ {t("SETTINGS$UPGRADE_BUTTON")}
+ </button>
+ );
+}
diff --git a/frontend/src/hooks/mutation/stripe/use-create-subscription-checkout-session.ts b/frontend/src/hooks/mutation/stripe/use-create-subscription-checkout-session.ts
new file mode 100644
index 0000000000..e70e0d4295
--- /dev/null
+++ b/frontend/src/hooks/mutation/stripe/use-create-subscription-checkout-session.ts
@@ -0,0 +1,12 @@
+import { useMutation } from "@tanstack/react-query";
+import BillingService from "#/api/billing-service/billing-service.api";
+
+export const useCreateSubscriptionCheckoutSession = () =>
+ useMutation({
+ mutationFn: BillingService.createSubscriptionCheckoutSession,
+ onSuccess: (data) => {
+ if (data.redirect_url) {
+ window.location.href = data.redirect_url;
+ }
+ },
+ });
diff --git a/frontend/src/hooks/mutation/use-cancel-subscription.ts b/frontend/src/hooks/mutation/use-cancel-subscription.ts
new file mode 100644
index 0000000000..291d4e38bf
--- /dev/null
+++ b/frontend/src/hooks/mutation/use-cancel-subscription.ts
@@ -0,0 +1,16 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import BillingService from "#/api/billing-service/billing-service.api";
+
+export const useCancelSubscription = () => {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: BillingService.cancelSubscription,
+ onSuccess: () => {
+ // Invalidate subscription access query to refresh the UI
+ queryClient.invalidateQueries({
+ queryKey: ["user", "subscription_access"],
+ });
+ },
+ });
+};
diff --git a/frontend/src/i18n/declaration.ts b/frontend/src/i18n/declaration.ts
index 49f7325ae9..74305b584f 100644
--- a/frontend/src/i18n/declaration.ts
+++ b/frontend/src/i18n/declaration.ts
@@ -113,7 +113,7 @@ export enum I18nKey {
SETTINGS$SAVE_CHANGES = "SETTINGS$SAVE_CHANGES",
SETTINGS$NAV_INTEGRATIONS = "SETTINGS$NAV_INTEGRATIONS",
SETTINGS$NAV_APPLICATION = "SETTINGS$NAV_APPLICATION",
- SETTINGS$NAV_CREDITS = "SETTINGS$NAV_CREDITS",
+ SETTINGS$NAV_BILLING = "SETTINGS$NAV_BILLING",
SETTINGS$NAV_SECRETS = "SETTINGS$NAV_SECRETS",
SETTINGS$NAV_API_KEYS = "SETTINGS$NAV_API_KEYS",
SETTINGS$GITHUB = "SETTINGS$GITHUB",
@@ -543,13 +543,20 @@ export enum I18nKey {
PAYMENT$ADD_FUNDS = "PAYMENT$ADD_FUNDS",
PAYMENT$ADD_CREDIT = "PAYMENT$ADD_CREDIT",
PAYMENT$MANAGE_CREDITS = "PAYMENT$MANAGE_CREDITS",
- AUTH$SIGN_IN_WITH_GITHUB = "AUTH$SIGN_IN_WITH_GITHUB",
- WAITLIST$JOIN = "WAITLIST$JOIN",
+ PAYMENT$CANCEL_SUBSCRIPTION = "PAYMENT$CANCEL_SUBSCRIPTION",
+ PAYMENT$CANCEL_SUBSCRIPTION_TITLE = "PAYMENT$CANCEL_SUBSCRIPTION_TITLE",
+ PAYMENT$CANCEL_SUBSCRIPTION_MESSAGE = "PAYMENT$CANCEL_SUBSCRIPTION_MESSAGE",
+ PAYMENT$CANCEL_SUBSCRIPTION_MESSAGE_WITH_DATE = "PAYMENT$CANCEL_SUBSCRIPTION_MESSAGE_WITH_DATE",
+ PAYMENT$SUBSCRIPTION_CANCELLED = "PAYMENT$SUBSCRIPTION_CANCELLED",
+ PAYMENT$SUBSCRIPTION_CANCELLED_EXPIRES = "PAYMENT$SUBSCRIPTION_CANCELLED_EXPIRES",
+ PAYMENT$NEXT_BILLING_DATE = "PAYMENT$NEXT_BILLING_DATE",
WAITLIST$IF_NOT_JOINED = "WAITLIST$IF_NOT_JOINED",
WAITLIST$PATIENCE_MESSAGE = "WAITLIST$PATIENCE_MESSAGE",
WAITLIST$ALMOST_THERE = "WAITLIST$ALMOST_THERE",
PAYMENT$SUCCESS = "PAYMENT$SUCCESS",
PAYMENT$CANCELLED = "PAYMENT$CANCELLED",
+ SUBSCRIPTION$SUCCESS = "SUBSCRIPTION$SUCCESS",
+ SUBSCRIPTION$FAILURE = "SUBSCRIPTION$FAILURE",
SERVED_APP$TITLE = "SERVED_APP$TITLE",
CONVERSATION$UNKNOWN = "CONVERSATION$UNKNOWN",
SETTINGS$RUNTIME_OPTION_1X = "SETTINGS$RUNTIME_OPTION_1X",
@@ -898,6 +905,9 @@ export enum I18nKey {
MICROAGENT$DEFINITION = "MICROAGENT$DEFINITION",
MICROAGENT$ADD_TO_MEMORY = "MICROAGENT$ADD_TO_MEMORY",
COMMON$IN_PROGRESS = "COMMON$IN_PROGRESS",
+ SETTINGS$UPGRADE_BANNER_MESSAGE = "SETTINGS$UPGRADE_BANNER_MESSAGE",
+ SETTINGS$UPGRADE_BUTTON = "SETTINGS$UPGRADE_BUTTON",
+ SETTINGS$PRO_PILL = "SETTINGS$PRO_PILL",
COMMON$STOP_RUNTIME = "COMMON$STOP_RUNTIME",
COMMON$START_RUNTIME = "COMMON$START_RUNTIME",
COMMON$JUPYTER_EMPTY_MESSAGE = "COMMON$JUPYTER_EMPTY_MESSAGE",
diff --git a/frontend/src/i18n/translation.json b/frontend/src/i18n/translation.json
index e27201e077..07866f9b04 100644
--- a/frontend/src/i18n/translation.json
+++ b/frontend/src/i18n/translation.json
@@ -1807,21 +1807,21 @@
"de": "Anwendung",
"uk": "Додаток"
},
- "SETTINGS$NAV_CREDITS": {
- "en": "Credits",
- "ja": "クレジット",
- "zh-CN": "积分",
- "zh-TW": "點數",
- "ko-KR": "크레딧",
- "no": "Kreditter",
- "it": "Crediti",
- "pt": "Créditos",
- "es": "Créditos",
- "ar": "الرصيد",
- "fr": "Crédits",
- "tr": "Krediler",
- "de": "Guthaben",
- "uk": "Кредити"
+ "SETTINGS$NAV_BILLING": {
+ "en": "Billing",
+ "ja": "請求",
+ "zh-CN": "账单",
+ "zh-TW": "帳單",
+ "ko-KR": "결제",
+ "no": "Fakturering",
+ "it": "Fatturazione",
+ "pt": "Faturamento",
+ "es": "Facturación",
+ "ar": "الفواتير",
+ "fr": "Facturation",
+ "tr": "Faturalama",
+ "de": "Abrechnung",
+ "uk": "Виставлення рахунків"
},
"SETTINGS$NAV_SECRETS": {
"en": "Secrets",
@@ -8687,37 +8687,117 @@
"de": "Guthaben verwalten",
"uk": "Керування кредитами"
},
- "AUTH$SIGN_IN_WITH_GITHUB": {
- "en": "Sign in with GitHub",
- "ja": "GitHubでサインイン",
- "zh-CN": "使用GitHub登录",
- "zh-TW": "使用GitHub登入",
- "ko-KR": "GitHub로 로그인",
- "no": "Logg inn med GitHub",
- "it": "Accedi con GitHub",
- "pt": "Entrar com GitHub",
- "es": "Iniciar sesión con GitHub",
- "ar": "تسجيل الدخول باستخدام GitHub",
- "fr": "Se connecter avec GitHub",
- "tr": "GitHub ile giriş yap",
- "de": "Mit GitHub anmelden",
- "uk": "Увійти за допомогою GitHub"
- },
- "WAITLIST$JOIN": {
- "en": "Join the waitlist",
- "ja": "ウェイトリストに参加",
- "zh-CN": "加入等待名单",
- "zh-TW": "加入等待名單",
- "ko-KR": "대기자 명단에 참여",
- "no": "Bli med på ventelisten",
- "it": "Unisciti alla lista d'attesa",
- "pt": "Entrar na lista de espera",
- "es": "Unirse a la lista de espera",
- "ar": "الانضمام إلى قائمة الانتظار",
- "fr": "Rejoindre la liste d'attente",
- "tr": "Bekleme listesine katıl",
- "de": "Der Warteliste beitreten",
- "uk": "Приєднатися до списку очікування"
+ "PAYMENT$CANCEL_SUBSCRIPTION": {
+ "en": "Cancel Subscription",
+ "ja": "サブスクリプションをキャンセル",
+ "zh-CN": "取消订阅",
+ "zh-TW": "取消訂閱",
+ "ko-KR": "구독 취소",
+ "no": "Avbryt abonnement",
+ "it": "Annulla abbonamento",
+ "pt": "Cancelar assinatura",
+ "es": "Cancelar suscripción",
+ "ar": "إلغاء الاشتراك",
+ "fr": "Annuler l'abonnement",
+ "tr": "Aboneliği iptal et",
+ "de": "Abonnement kündigen",
+ "uk": "Скасувати підписку"
+ },
+ "PAYMENT$CANCEL_SUBSCRIPTION_TITLE": {
+ "en": "Cancel Subscription",
+ "ja": "サブスクリプションのキャンセル",
+ "zh-CN": "取消订阅",
+ "zh-TW": "取消訂閱",
+ "ko-KR": "구독 취소",
+ "no": "Avbryt abonnement",
+ "it": "Annulla abbonamento",
+ "pt": "Cancelar assinatura",
+ "es": "Cancelar suscripción",
+ "ar": "إلغاء الاشتراك",
+ "fr": "Annuler l'abonnement",
+ "tr": "Aboneliği iptal et",
+ "de": "Abonnement kündigen",
+ "uk": "Скасувати підписку"
+ },
+ "PAYMENT$CANCEL_SUBSCRIPTION_MESSAGE": {
+ "en": "Are you sure you want to cancel your subscription? You will lose access to premium features at the end of your current billing period.",
+ "ja": "サブスクリプションをキャンセルしてもよろしいですか?現在の請求期間の終了時にプレミアム機能へのアクセスを失います。",
+ "zh-CN": "您确定要取消订阅吗?您将在当前计费周期结束时失去对高级功能的访问权限。",
+ "zh-TW": "您確定要取消訂閱嗎?您將在當前計費週期結束時失去對高級功能的訪問權限。",
+ "ko-KR": "구독을 취소하시겠습니까? 현재 결제 기간이 끝나면 프리미엄 기능에 대한 액세스를 잃게 됩니다.",
+ "no": "Er du sikker på at du vil avbryte abonnementet? Du vil miste tilgang til premium-funksjoner ved slutten av gjeldende faktureringsperiode.",
+ "it": "Sei sicuro di voler annullare l'abbonamento? Perderai l'accesso alle funzionalità premium alla fine del periodo di fatturazione corrente.",
+ "pt": "Tem certeza de que deseja cancelar sua assinatura? Você perderá o acesso aos recursos premium no final do período de cobrança atual.",
+ "es": "¿Estás seguro de que quieres cancelar tu suscripción? Perderás el acceso a las funciones premium al final de tu período de facturación actual.",
+ "ar": "هل أنت متأكد من أنك تريد إلغاء اشتراكك؟ ستفقد الوصول إلى الميزات المميزة في نهاية فترة الفوترة الحالية.",
+ "fr": "Êtes-vous sûr de vouloir annuler votre abonnement ? Vous perdrez l'accès aux fonctionnalités premium à la fin de votre période de facturation actuelle.",
+ "tr": "Aboneliğinizi iptal etmek istediğinizden emin misiniz? Mevcut faturalama döneminizin sonunda premium özelliklere erişiminizi kaybedeceksiniz.",
+ "de": "Sind Sie sicher, dass Sie Ihr Abonnement kündigen möchten? Sie verlieren den Zugang zu Premium-Funktionen am Ende Ihres aktuellen Abrechnungszeitraums.",
+ "uk": "Ві впевнені, що хочете скасувати підписку? Ви втратите доступ до преміум-функцій наприкінці поточного розрахункового періоду."
+ },
+ "PAYMENT$CANCEL_SUBSCRIPTION_MESSAGE_WITH_DATE": {
+ "en": "Are you sure you want to cancel your subscription? You will lose access to premium features on {{date}}.",
+ "ja": "サブスクリプションをキャンセルしてもよろしいですか?{{date}}にプレミアム機能へのアクセスを失います。",
+ "zh-CN": "您确定要取消订阅吗?您将在{{date}}失去对高级功能的访问权限。",
+ "zh-TW": "您確定要取消訂閱嗎?您將在{{date}}失去對高級功能的訪問權限。",
+ "ko-KR": "구독을 취소하시겠습니까? {{date}}에 프리미엄 기능에 대한 액세스를 잃게 됩니다.",
+ "no": "Er du sikker på at du vil avbryte abonnementet? Du vil miste tilgang til premium-funksjoner {{date}}.",
+ "it": "Sei sicuro di voler annullare l'abbonamento? Perderai l'accesso alle funzionalità premium il {{date}}.",
+ "pt": "Tem certeza de que deseja cancelar sua assinatura? Você perderá o acesso aos recursos premium em {{date}}.",
+ "es": "¿Estás seguro de que quieres cancelar tu suscripción? Perderás el acceso a las funciones premium el {{date}}.",
+ "ar": "هل أنت متأكد من أنك تريد إلغاء اشتراكك؟ ستفقد الوصول إلى الميزات المميزة في {{date}}.",
+ "fr": "Êtes-vous sûr de vouloir annuler votre abonnement ? Vous perdrez l'accès aux fonctionnalités premium le {{date}}.",
+ "tr": "Aboneliğinizi iptal etmek istediğinizden emin misiniz? {{date}} tarihinde premium özelliklere erişiminizi kaybedeceksiniz.",
+ "de": "Sind Sie sicher, dass Sie Ihr Abonnement kündigen möchten? Sie verlieren den Zugang zu Premium-Funktionen am {{date}}.",
+ "uk": "Ви впевнені, що хочете скасувати підписку? Ви втратите доступ до преміум-функцій {{date}}."
+ },
+ "PAYMENT$SUBSCRIPTION_CANCELLED": {
+ "en": "Subscription cancelled successfully",
+ "ja": "サブスクリプションが正常にキャンセルされました",
+ "zh-CN": "订阅已成功取消",
+ "zh-TW": "訂閱已成功取消",
+ "ko-KR": "구독이 성공적으로 취소되었습니다",
+ "no": "Abonnement avbrutt",
+ "it": "Abbonamento annullato con successo",
+ "pt": "Assinatura cancelada com sucesso",
+ "es": "Suscripción cancelada exitosamente",
+ "ar": "تم إلغاء الاشتراك بنجاح",
+ "fr": "Abonnement annulé avec succès",
+ "tr": "Abonelik başarıyla iptal edildi",
+ "de": "Abonnement erfolgreich gekündigt",
+ "uk": "Підписку успішно скасовано"
+ },
+ "PAYMENT$SUBSCRIPTION_CANCELLED_EXPIRES": {
+ "en": "Your subscription has been cancelled and will expire on {{date}}",
+ "ja": "サブスクリプションはキャンセルされ、{{date}}に期限切れになります",
+ "zh-CN": "您的订阅已取消,将于{{date}}到期",
+ "zh-TW": "您的訂閱已取消,將於{{date}}到期",
+ "ko-KR": "구독이 취소되었으며 {{date}}에 만료됩니다",
+ "no": "Abonnementet ditt er avbrutt og utløper {{date}}",
+ "it": "Il tuo abbonamento è stato annullato e scadrà il {{date}}",
+ "pt": "Sua assinatura foi cancelada e expirará em {{date}}",
+ "es": "Tu suscripción ha sido cancelada y expirará el {{date}}",
+ "ar": "تم إلغاء اشتراكك وسينتهي في {{date}}",
+ "fr": "Votre abonnement a été annulé et expirera le {{date}}",
+ "tr": "Aboneliğiniz iptal edildi ve {{date}} tarihinde sona erecek",
+ "de": "Ihr Abonnement wurde gekündigt und läuft am {{date}} ab",
+ "uk": "Ваша підписка скасована і закінчиться {{date}}"
+ },
+ "PAYMENT$NEXT_BILLING_DATE": {
+ "en": "Next billing date: {{date}}",
+ "ja": "次回請求日: {{date}}",
+ "zh-CN": "下次计费日期: {{date}}",
+ "zh-TW": "下次計費日期: {{date}}",
+ "ko-KR": "다음 결제일: {{date}}",
+ "no": "Neste faktureringsdato: {{date}}",
+ "it": "Prossima data di fatturazione: {{date}}",
+ "pt": "Próxima data de cobrança: {{date}}",
+ "es": "Próxima fecha de facturación: {{date}}",
+ "ar": "تاريخ الفوترة التالية: {{date}}",
+ "fr": "Prochaine date de facturation: {{date}}",
+ "tr": "Sonraki fatura tarihi: {{date}}",
+ "de": "Nächstes Abrechnungsdatum: {{date}}",
+ "uk": "Наступна дата виставлення рахунку: {{date}}"
},
"WAITLIST$IF_NOT_JOINED": {
"en": "If you haven't already joined the waitlist, please do so to get access.",
@@ -8799,6 +8879,38 @@
"de": "Zahlung abgebrochen",
"uk": "Платіж скасовано"
},
+ "SUBSCRIPTION$SUCCESS": {
+ "en": "Subscription successful! You now have access to premium features.",
+ "ja": "サブスクリプションが成功しました!プレミアム機能にアクセスできるようになりました。",
+ "zh-CN": "订阅成功!您现在可以访问高级功能。",
+ "zh-TW": "訂閱成功!您現在可以訪問高級功能。",
+ "ko-KR": "구독 성공! 이제 프리미엄 기능에 액세스할 수 있습니다.",
+ "no": "Abonnement vellykket! Du har nå tilgang til premium-funksjoner.",
+ "it": "Abbonamento riuscito! Ora hai accesso alle funzionalità premium.",
+ "pt": "Assinatura bem-sucedida! Agora você tem acesso aos recursos premium.",
+ "es": "¡Suscripción exitosa! Ahora tienes acceso a las funciones premium.",
+ "ar": "نجح الاشتراك! لديك الآن إمكانية الوصول إلى الميزات المميزة.",
+ "fr": "Abonnement réussi ! Vous avez maintenant accès aux fonctionnalités premium.",
+ "tr": "Abonelik başarılı! Artık premium özelliklere erişiminiz var.",
+ "de": "Abonnement erfolgreich! Sie haben jetzt Zugang zu Premium-Funktionen.",
+ "uk": "Підписка успішна! Тепер у вас є доступ до преміум-функцій."
+ },
+ "SUBSCRIPTION$FAILURE": {
+ "en": "Something went wrong, please try again later.",
+ "ja": "何かが間違っていました。後でもう一度お試しください。",
+ "zh-CN": "出了点问题,请稍后再试。",
+ "zh-TW": "出了點問題,請稍後再試。",
+ "ko-KR": "문제가 발생했습니다. 나중에 다시 시도해 주세요.",
+ "no": "Noe gikk galt, prøv igjen senere.",
+ "it": "Qualcosa è andato storto, riprova più tardi.",
+ "pt": "Algo deu errado, tente novamente mais tarde.",
+ "es": "Algo salió mal, inténtalo de nuevo más tarde.",
+ "ar": "حدث خطأ ما، يرجى المحاولة مرة أخرى لاحقاً.",
+ "fr": "Quelque chose s'est mal passé, veuillez réessayer plus tard.",
+ "tr": "Bir şeyler ters gitti, lütfen daha sonra tekrar deneyin.",
+ "de": "Etwas ist schief gelaufen, bitte versuchen Sie es später erneut.",
+ "uk": "Щось пішло не так, спробуйте ще раз пізніше."
+ },
"SERVED_APP$TITLE": {
"en": "Served Application",
"ja": "提供されたアプリケーション",
@@ -14367,6 +14479,54 @@
"de": "In Bearbeitung",
"uk": "В процесі"
},
+ "SETTINGS$UPGRADE_BANNER_MESSAGE": {
+ "en": "Access LLM settings when you upgrade your plan",
+ "ja": "プランをアップグレードするとLLM設定にアクセスできます",
+ "zh-CN": "升级计划后即可访问LLM设置",
+ "zh-TW": "升級計劃後即可訪問LLM設置",
+ "ko-KR": "플랜을 업그레이드하면 LLM 설정에 액세스할 수 있습니다",
+ "no": "Få tilgang til LLM-innstillinger når du oppgraderer planen din",
+ "it": "Accedi alle impostazioni LLM quando aggiorni il tuo piano",
+ "pt": "Acesse as configurações do LLM ao atualizar seu plano",
+ "es": "Accede a la configuración de LLM cuando actualices tu plan",
+ "ar": "الوصول إلى إعدادات LLM عند ترقية خطتك",
+ "fr": "Accédez aux paramètres LLM lorsque vous mettez à niveau votre plan",
+ "tr": "Planınızı yükselttiğinizde LLM ayarlarına erişin",
+ "de": "Zugriff auf LLM-Einstellungen beim Upgrade Ihres Plans",
+ "uk": "Отримайте доступ до налаштувань LLM, коли оновите свій план"
+ },
+ "SETTINGS$UPGRADE_BUTTON": {
+ "en": "Upgrade",
+ "ja": "アップグレード",
+ "zh-CN": "升级",
+ "zh-TW": "升級",
+ "ko-KR": "업그레이드",
+ "no": "Oppgrader",
+ "it": "Aggiorna",
+ "pt": "Atualizar",
+ "es": "Actualizar",
+ "ar": "ترقية",
+ "fr": "Mettre à niveau",
+ "tr": "Yükselt",
+ "de": "Upgrade",
+ "uk": "Оновити"
+ },
+ "SETTINGS$PRO_PILL": {
+ "en": "Pro",
+ "ja": "プロ",
+ "zh-CN": "专业版",
+ "zh-TW": "專業版",
+ "ko-KR": "프로",
+ "no": "Pro",
+ "it": "Pro",
+ "pt": "Pro",
+ "es": "Pro",
+ "ar": "برو",
+ "fr": "Pro",
+ "tr": "Pro",
+ "de": "Pro",
+ "uk": "Про"
+ },
"COMMON$STOP_RUNTIME": {
"en": "Stop Runtime",
"ja": "ランタイムを停止",
diff --git a/frontend/src/mocks/billing-handlers.ts b/frontend/src/mocks/billing-handlers.ts
index 4482d8eb57..ee9418081b 100644
--- a/frontend/src/mocks/billing-handlers.ts
+++ b/frontend/src/mocks/billing-handlers.ts
@@ -1,22 +1,101 @@
import { delay, http, HttpResponse } from "msw";
+import { SubscriptionAccess } from "#/api/billing-service/billing.types";
-export const STRIPE_BILLING_HANDLERS = [
- http.get("/api/billing/credits", async () => {
- await delay();
- return HttpResponse.json({ credits: "100" });
- }),
-
- http.post("/api/billing/create-checkout-session", async () => {
- await delay();
- return HttpResponse.json({
- redirect_url: "https://stripe.com/some-checkout",
- });
- }),
-
- http.post("/api/billing/create-customer-setup-session", async () => {
- await delay();
- return HttpResponse.json({
- redirect_url: "https://stripe.com/some-customer-setup",
- });
- }),
-];
+// Mock data for different subscription scenarios
+const MOCK_ACTIVE_SUBSCRIPTION: SubscriptionAccess = {
+ start_at: "2024-01-01T00:00:00Z",
+ end_at: "2024-12-31T23:59:59Z",
+ created_at: "2024-01-01T00:00:00Z",
+ cancelled_at: null,
+ stripe_subscription_id: "sub_mock123456789",
+};
+
+const MOCK_CANCELLED_SUBSCRIPTION: SubscriptionAccess = {
+ start_at: "2024-01-01T00:00:00Z",
+ end_at: "2025-01-01T23:59:59Z",
+ created_at: "2024-01-01T00:00:00Z",
+ cancelled_at: "2024-06-15T10:30:00Z",
+ stripe_subscription_id: "sub_mock123456789",
+};
+
+// Expired subscription (end_at < now) - will be filtered out by backend logic
+const MOCK_EXPIRED_SUBSCRIPTION: SubscriptionAccess = {
+ start_at: "2024-01-01T00:00:00Z",
+ end_at: "2024-06-01T00:00:00Z", // Expired
+ created_at: "2024-01-01T00:00:00Z",
+ cancelled_at: null,
+ stripe_subscription_id: "sub_mock123456789",
+};
+
+// Helper function to check if subscription is currently active (matches backend logic)
+function isSubscriptionActive(
+ subscription: SubscriptionAccess | null,
+): boolean {
+ if (!subscription) return false;
+
+ const now = new Date();
+ const startAt = new Date(subscription.start_at);
+ const endAt = new Date(subscription.end_at);
+
+ // Backend filters: status == 'ACTIVE' AND start_at <= now AND end_at >= now
+ return startAt <= now && endAt >= now;
+}
+
+// Factory function to create billing handlers with different subscription states
+function createBillingHandlers(subscriptionData: SubscriptionAccess | null) {
+ return [
+ http.get("/api/billing/credits", async () => {
+ await delay();
+ return HttpResponse.json({ credits: "100" });
+ }),
+
+ http.get("/api/billing/subscription-access", async () => {
+ await delay();
+ // Apply backend filtering logic - only return if subscription is currently active
+ const activeSubscription = isSubscriptionActive(subscriptionData)
+ ? subscriptionData
+ : null;
+ return HttpResponse.json(activeSubscription);
+ }),
+
+ http.post("/api/billing/create-checkout-session", async () => {
+ await delay();
+ return HttpResponse.json({
+ redirect_url: "https://stripe.com/some-checkout",
+ });
+ }),
+
+ http.post("/api/billing/subscription-checkout-session", async () => {
+ await delay();
+ return HttpResponse.json({
+ redirect_url: "https://stripe.com/some-subscription-checkout",
+ });
+ }),
+
+ http.post("/api/billing/create-customer-setup-session", async () => {
+ await delay();
+ return HttpResponse.json({
+ redirect_url: "https://stripe.com/some-customer-setup",
+ });
+ }),
+
+ http.post("/api/billing/cancel-subscription", async () => {
+ await delay();
+ return HttpResponse.json({
+ status: "success",
+ message: "Subscription cancelled successfully",
+ });
+ }),
+ ];
+}
+
+// Export different handler sets for different testing scenarios
+export const STRIPE_BILLING_HANDLERS = createBillingHandlers(
+ MOCK_ACTIVE_SUBSCRIPTION,
+);
+export const STRIPE_BILLING_HANDLERS_NO_SUBSCRIPTION =
+ createBillingHandlers(null);
+export const STRIPE_BILLING_HANDLERS_CANCELLED_SUBSCRIPTION =
+ createBillingHandlers(MOCK_CANCELLED_SUBSCRIPTION);
+export const STRIPE_BILLING_HANDLERS_EXPIRED_SUBSCRIPTION =
+ createBillingHandlers(MOCK_EXPIRED_SUBSCRIPTION); // This will return null due to filtering
diff --git a/frontend/src/routes/llm-settings.tsx b/frontend/src/routes/llm-settings.tsx
index 7094fa27a4..79cba5bb66 100644
--- a/frontend/src/routes/llm-settings.tsx
+++ b/frontend/src/routes/llm-settings.tsx
@@ -1,6 +1,7 @@
import React from "react";
import { useTranslation } from "react-i18next";
import { AxiosError } from "axios";
+import { useSearchParams } from "react-router";
import { ModelSelector } from "#/components/shared/modals/settings/model-selector";
import { organizeModelsAndProviders } from "#/utils/organize-models-and-providers";
import { useAIConfigOptions } from "#/hooks/query/use-ai-config-options";
@@ -27,15 +28,25 @@ import { KeyStatusIcon } from "#/components/features/settings/key-status-icon";
import { DEFAULT_SETTINGS } from "#/services/settings";
import { getProviderId } from "#/utils/map-provider";
import { DEFAULT_OPENHANDS_MODEL } from "#/utils/verified-models";
+import { useSubscriptionAccess } from "#/hooks/query/use-subscription-access";
+import { UpgradeBannerWithBackdrop } from "#/components/features/settings/upgrade-banner-with-backdrop";
+import { useCreateSubscriptionCheckoutSession } from "#/hooks/mutation/stripe/use-create-subscription-checkout-session";
+import { useIsAuthed } from "#/hooks/query/use-is-authed";
+import { cn } from "#/utils/utils";
function LlmSettingsScreen() {
const { t } = useTranslation();
+ const [searchParams, setSearchParams] = useSearchParams();
const { mutate: saveSettings, isPending } = useSaveSettings();
const { data: resources } = useAIConfigOptions();
const { data: settings, isLoading, isFetching } = useSettings();
const { data: config } = useConfig();
+ const { data: subscriptionAccess } = useSubscriptionAccess();
+ const { data: isAuthed } = useIsAuthed();
+ const { mutate: createSubscriptionCheckoutSession } =
+ useCreateSubscriptionCheckoutSession();
const [view, setView] = React.useState<"basic" | "advanced">("basic");
@@ -114,6 +125,19 @@ function LlmSettingsScreen() {
}
}, [settings?.SECURITY_ANALYZER]);
+ // Handle URL parameters for SaaS subscription redirects
+ React.useEffect(() => {
+ const checkout = searchParams.get("checkout");
+
+ if (checkout === "success") {
+ displaySuccessToast(t(I18nKey.SUBSCRIPTION$SUCCESS));
+ setSearchParams({});
+ } else if (checkout === "cancel") {
+ displayErrorToast(t(I18nKey.SUBSCRIPTION$FAILURE));
+ setSearchParams({});
+ }
+ }, [searchParams, setSearchParams, t]);
+
const handleSuccessfulMutation = () => {
displaySuccessToast(t(I18nKey.SETTINGS$SAVED_WARNING));
setDirtyInputs({
@@ -221,11 +245,6 @@ function LlmSettingsScreen() {
);
};
- const formAction = (formData: FormData) => {
- if (view === "basic") basicFormAction(formData);
- else advancedFormAction(formData);
- };
-
const handleToggleAdvancedSettings = (isToggled: boolean) => {
setView(isToggled ? "advanced" : "basic");
setDirtyInputs({
@@ -390,11 +409,41 @@ function LlmSettingsScreen() {
if (!settings || isFetching) return <LlmSettingsInputsSkeleton />;
+ // Show upgrade banner and disable form in SaaS mode when user doesn't have an active subscription
+ const shouldShowUpgradeBanner =
+ config?.APP_MODE === "saas" && !subscriptionAccess;
+
+ const formAction = (formData: FormData) => {
+ // Prevent form submission for unsubscribed SaaS users
+ if (shouldShowUpgradeBanner) return;
+
+ if (view === "basic") basicFormAction(formData);
+ else advancedFormAction(formData);
+ };
+
return (
- <div data-testid="llm-settings-screen" className="h-full">
+ <div
+ data-testid="llm-settings-screen"
+ className={cn(
+ "h-full relative",
+ shouldShowUpgradeBanner && "overflow-hidden",
+ )}
+ >
+ {shouldShowUpgradeBanner && (
+ <UpgradeBannerWithBackdrop
+ onUpgradeClick={() => {
+ createSubscriptionCheckoutSession();
+ }}
+ isDisabled={!isAuthed}
+ />
+ )}
<form
action={formAction}
- className="flex flex-col h-full justify-between"
+ className={cn(
+ "flex flex-col h-full justify-between",
+ shouldShowUpgradeBanner && "h-[calc(100%-theme(spacing.12))]",
+ )}
+ inert={shouldShowUpgradeBanner}
>
<div className="p-9 flex flex-col gap-6">
<SettingsSwitch
@@ -402,6 +451,7 @@ function LlmSettingsScreen() {
defaultIsToggled={view === "advanced"}
onToggle={handleToggleAdvancedSettings}
isToggled={view === "advanced"}
+ isDisabled={shouldShowUpgradeBanner}
>
{t(I18nKey.SETTINGS$ADVANCED)}
</SettingsSwitch>
@@ -410,6 +460,7 @@ function LlmSettingsScreen() {
<div
data-testid="llm-settings-form-basic"
className="flex flex-col gap-6"
+ aria-disabled={shouldShowUpgradeBanner ? "true" : undefined}
>
{!isLoading && !isFetching && (
<>
@@ -417,6 +468,7 @@ function LlmSettingsScreen() {
models={modelsAndProviders}
currentModel={settings.LLM_MODEL || DEFAULT_OPENHANDS_MODEL}
onChange={handleModelIsDirty}
+ isDisabled={shouldShowUpgradeBanner}
wrapperClassName="!flex-col !gap-6"
/>
{(settings.LLM_MODEL?.startsWith("openhands/") ||
@@ -440,6 +492,7 @@ function LlmSettingsScreen() {
className="w-full max-w-[680px]"
placeholder={settings.LLM_API_KEY_SET ? "<hidden>" : ""}
onChange={handleApiKeyIsDirty}
+ isDisabled={shouldShowUpgradeBanner}
startContent={
settings.LLM_API_KEY_SET && (
<KeyStatusIcon isSet={settings.LLM_API_KEY_SET} />
@@ -454,21 +507,24 @@ function LlmSettingsScreen() {
href="https://docs.all-hands.dev/usage/local-setup#getting-an-api-key"
/>
- <SettingsInput
- testId="search-api-key-input"
- name="search-api-key-input"
- label={t(I18nKey.SETTINGS$SEARCH_API_KEY)}
- type="password"
- className="w-full max-w-[680px]"
- defaultValue={settings.SEARCH_API_KEY || ""}
- onChange={handleSearchApiKeyIsDirty}
- placeholder={t(I18nKey.API$TAVILY_KEY_EXAMPLE)}
- startContent={
- settings.SEARCH_API_KEY_SET && (
- <KeyStatusIcon isSet={settings.SEARCH_API_KEY_SET} />
- )
- }
- />
+ {config?.APP_MODE !== "saas" && (
+ <SettingsInput
+ testId="search-api-key-input"
+ name="search-api-key-input"
+ label={t(I18nKey.SETTINGS$SEARCH_API_KEY)}
+ type="password"
+ className="w-full max-w-[680px]"
+ defaultValue={settings.SEARCH_API_KEY || ""}
+ onChange={handleSearchApiKeyIsDirty}
+ placeholder={t(I18nKey.API$TAVILY_KEY_EXAMPLE)}
+ isDisabled={shouldShowUpgradeBanner}
+ startContent={
+ settings.SEARCH_API_KEY_SET && (
+ <KeyStatusIcon isSet={settings.SEARCH_API_KEY_SET} />
+ )
+ }
+ />
+ )}
<HelpLink
testId="search-api-key-help-anchor"
@@ -537,44 +593,49 @@ function LlmSettingsScreen() {
href="https://docs.all-hands.dev/usage/local-setup#getting-an-api-key"
/>
- <SettingsInput
- testId="search-api-key-input"
- name="search-api-key-input"
- label={t(I18nKey.SETTINGS$SEARCH_API_KEY)}
- type="password"
- className="w-full max-w-[680px]"
- defaultValue={settings.SEARCH_API_KEY || ""}
- onChange={handleSearchApiKeyIsDirty}
- placeholder={t(I18nKey.API$TVLY_KEY_EXAMPLE)}
- startContent={
- settings.SEARCH_API_KEY_SET && (
- <KeyStatusIcon isSet={settings.SEARCH_API_KEY_SET} />
- )
- }
- />
+ {config?.APP_MODE !== "saas" && (
+ <>
+ <SettingsInput
+ testId="search-api-key-input"
+ name="search-api-key-input"
+ label={t(I18nKey.SETTINGS$SEARCH_API_KEY)}
+ type="password"
+ className="w-full max-w-[680px]"
+ defaultValue={settings.SEARCH_API_KEY || ""}
+ onChange={handleSearchApiKeyIsDirty}
+ placeholder={t(I18nKey.API$TVLY_KEY_EXAMPLE)}
+ isDisabled={shouldShowUpgradeBanner}
+ startContent={
+ settings.SEARCH_API_KEY_SET && (
+ <KeyStatusIcon isSet={settings.SEARCH_API_KEY_SET} />
+ )
+ }
+ />
- <HelpLink
- testId="search-api-key-help-anchor"
- text={t(I18nKey.SETTINGS$SEARCH_API_KEY_OPTIONAL)}
- linkText={t(I18nKey.SETTINGS$SEARCH_API_KEY_INSTRUCTIONS)}
- href="https://tavily.com/"
- />
+ <HelpLink
+ testId="search-api-key-help-anchor"
+ text={t(I18nKey.SETTINGS$SEARCH_API_KEY_OPTIONAL)}
+ linkText={t(I18nKey.SETTINGS$SEARCH_API_KEY_INSTRUCTIONS)}
+ href="https://tavily.com/"
+ />
- <SettingsDropdownInput
- testId="agent-input"
- name="agent-input"
- label={t(I18nKey.SETTINGS$AGENT)}
- items={
- resources?.agents.map((agent) => ({
- key: agent,
- label: agent, // TODO: Add i18n support for agent names
- })) || []
- }
- defaultSelectedKey={settings.AGENT}
- isClearable={false}
- onInputChange={handleAgentIsDirty}
- wrapperClassName="w-full max-w-[680px]"
- />
+ <SettingsDropdownInput
+ testId="agent-input"
+ name="agent-input"
+ label={t(I18nKey.SETTINGS$AGENT)}
+ items={
+ resources?.agents.map((agent) => ({
+ key: agent,
+ label: agent, // TODO: Add i18n support for agent names
+ })) || []
+ }
+ defaultSelectedKey={settings.AGENT}
+ isClearable={false}
+ onInputChange={handleAgentIsDirty}
+ wrapperClassName="w-full max-w-[680px]"
+ />
+ </>
+ )}
{config?.APP_MODE === "saas" && (
<SettingsDropdownInput
@@ -583,7 +644,10 @@ function LlmSettingsScreen() {
label={
<>
{t(I18nKey.SETTINGS$RUNTIME_SETTINGS)}
- <a href="mailto:[email protected]">
+ <a
+ href="mailto:[email protected]"
+ className="text-blue-500 hover:text-blue-400 underline"
+ >
{t(I18nKey.SETTINGS$GET_IN_TOUCH)}
</a>
</>
@@ -633,6 +697,7 @@ function LlmSettingsScreen() {
onToggle={handleConfirmationModeIsDirty}
defaultIsToggled={settings.CONFIRMATION_MODE}
isBeta
+ isDisabled={shouldShowUpgradeBanner}
>
{t(I18nKey.SETTINGS$CONFIRMATION_MODE)}
</SettingsSwitch>
diff --git a/frontend/src/routes/settings.tsx b/frontend/src/routes/settings.tsx
index 76b67154b2..3b3feb605f 100644
--- a/frontend/src/routes/settings.tsx
+++ b/frontend/src/routes/settings.tsx
@@ -1,4 +1,3 @@
-import { useMemo } from "react";
import { NavLink, Outlet, redirect } from "react-router";
import { useTranslation } from "react-i18next";
import SettingsIcon from "#/icons/settings.svg?react";
@@ -8,8 +7,8 @@ import { I18nKey } from "#/i18n/declaration";
import { Route } from "./+types/settings";
import OptionService from "#/api/option-service/option-service.api";
import { queryClient } from "#/query-client-config";
+import { ProPill } from "#/components/features/settings/pro-pill";
import { GetConfigResponse } from "#/api/option-service/option.types";
-import { useSubscriptionAccess } from "#/hooks/query/use-subscription-access";
const SAAS_ONLY_PATHS = [
"/settings/user",
@@ -22,7 +21,8 @@ const SAAS_NAV_ITEMS = [
{ to: "/settings/user", text: "SETTINGS$NAV_USER" },
{ to: "/settings/integrations", text: "SETTINGS$NAV_INTEGRATIONS" },
{ to: "/settings/app", text: "SETTINGS$NAV_APPLICATION" },
- { to: "/settings/billing", text: "SETTINGS$NAV_CREDITS" },
+ { to: "/settings", text: "SETTINGS$NAV_LLM" },
+ { to: "/settings/billing", text: "SETTINGS$NAV_BILLING" },
{ to: "/settings/secrets", text: "SETTINGS$NAV_SECRETS" },
{ to: "/settings/api-keys", text: "SETTINGS$NAV_API_KEYS" },
{ to: "/settings/mcp", text: "SETTINGS$NAV_MCP" },
@@ -48,11 +48,6 @@ export const clientLoader = async ({ request }: Route.ClientLoaderArgs) => {
const isSaas = config?.APP_MODE === "saas";
- if (isSaas && pathname === "/settings") {
- // no llm settings in saas mode, so redirect to user settings
- return redirect("/settings/user");
- }
-
if (!isSaas && SAAS_ONLY_PATHS.includes(pathname)) {
// if in OSS mode, do not allow access to saas-only paths
return redirect("/settings");
@@ -64,22 +59,10 @@ export const clientLoader = async ({ request }: Route.ClientLoaderArgs) => {
function SettingsScreen() {
const { t } = useTranslation();
const { data: config } = useConfig();
- const { data: subscriptionAccess } = useSubscriptionAccess();
const isSaas = config?.APP_MODE === "saas";
- // this is used to determine which settings are available in the UI
- const navItems = useMemo(() => {
- const items = [];
- if (isSaas) {
- if (subscriptionAccess) {
- items.push({ to: "/settings", text: "SETTINGS$NAV_LLM" });
- }
- items.push(...SAAS_NAV_ITEMS);
- } else {
- items.push(...OSS_NAV_ITEMS);
- }
- return items;
- }, [isSaas, !!subscriptionAccess]);
+
+ const navItems = isSaas ? SAAS_NAV_ITEMS : OSS_NAV_ITEMS;
return (
<main
@@ -102,12 +85,15 @@ function SettingsScreen() {
to={to}
className={({ isActive }) =>
cn(
- "border-b-2 border-transparent py-2.5 px-4 min-w-[40px] flex items-center justify-center",
+ "border-b-2 border-transparent py-2.5 px-4 min-w-[40px] flex items-center justify-center relative",
isActive && "border-primary",
)
}
>
<span className="text-[#F9FBFE] text-sm">{t(text)}</span>
+ {isSaas && to === "/settings" && (
+ <ProPill className="absolute top-0 -right-7" />
+ )}
</NavLink>
))}
</nav>