Fix Pro entitlement checks (#239)
Browse files* Fix Pro entitlement checks
Normalize HF Pro and paid org plan detection, allow premium model selection with quota enforcement, and clarify HF Jobs credit billing copy.
Co-authored-by: OpenAI Codex <codex@openai.com>
* Limit premium quota to personal Pro
Ignore org membership for premium-model quota so users need personal HF Pro for the higher cap, while dev mode uses the Pro tier for local testing.
Co-authored-by: OpenAI Codex <codex@openai.com>
* Scope model switch errors to model picker
Show model switch failures through local ChatInput state instead of rendering the shared agent error field globally.
Co-authored-by: OpenAI Codex <codex@openai.com>
* Restrict premium quota detection to Pro accounts
Co-authored-by: OpenAI Codex <codex@openai.com>
* Use boolean Pro signal for premium quota
Co-authored-by: OpenAI Codex <codex@openai.com>
* Use documented isPro field for quota tier
Co-authored-by: OpenAI Codex <codex@openai.com>
* Remove dead global chat error state
Co-authored-by: OpenAI Codex <codex@openai.com>
---------
Co-authored-by: OpenAI Codex <codex@openai.com>
Files changed (14)
- agent/tools/jobs_tool.py+5-4
- backend/dependencies.py+17-27
- backend/routes/agent.py+37-63
- backend/user_quotas.py+2-2
- frontend/src/components/Chat/ChatInput.tsx+49-2
- frontend/src/components/ClaudeCapDialog.tsx+57-53
- frontend/src/components/JobsUpgradeDialog.tsx+1-1
- frontend/src/hooks/useAgentChat.ts-6
- frontend/src/hooks/useUserQuota.ts+1-1
- frontend/src/lib/sse-chat-transport.ts+2-2
- frontend/src/store/agentStore.ts+4-9
- tests/unit/test_agent_model_gating.py+143-79
- tests/unit/test_plan_normalization.pyAdded+57
- tests/unit/test_user_quotas.py+2-5
630 unmodified lines631632633634635636637638639640630 unmodified lines"formatted": (f"Hugging Face Jobs rejected this run because the "f"namespace `{self.namespace}` has no available credits. ""Tell the user to add credits at ""https://huggingface.co/settings/billing — once topped up, ""re-run this same job. (Switching namespaces is fine if ""another wallet has credits.)"),"totalResults": 0,"resultsShared": 0,630 unmodified lines631632633634635636637638639640641630 unmodified lines"formatted": (f"Hugging Face Jobs rejected this run because the "f"namespace `{self.namespace}` has no available credits. ""HF Jobs are billed with namespace credits, which are ""separate from HF Pro membership. Tell the user to add ""credits at https://huggingface.co/settings/billing — ""once topped up, re-run this same job. (Switching ""namespaces is fine if another wallet has credits.)"),"totalResults": 0,"resultsShared": 0,
34 unmodified lines3536373839404111 unmodified lines535455565758596075 unmodified lines1361371381391401411421431441455 unmodified lines15115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418534 unmodified lines"user_id": "dev","username": "dev","authenticated": True,"plan": "org", # Dev runs at the Pro/Org quota tier so local testing isn't capped.}INTERNAL_HF_TOKEN_KEY = "_hf_token"11 unmodified lines"write-discussions",)# Plan field discovery — log the whoami-v2 shape once at DEBUG so we can# confirm the actual key in production without hammering the HF API._WHOAMI_SHAPE_LOGGED = False75 unmodified lines}async def _fetch_user_plan(token: str) -> str:"""Look up the user's HF plan via /api/whoami-v2.Returns 'free' | 'pro' | 'org'. Non-200, network errors, or an unknownpayload shape all collapse to 'free' — safe default; we'd rather under-grant the Pro cap than over-grant it on bad data."""5 unmodified linesif not _WHOAMI_SHAPE_LOGGED:_WHOAMI_SHAPE_LOGGED = Truelogger.debug("whoami-v2 payload keys: %s (sample values: plan=%r type=%r isPro=%r)",sorted(whoami.keys())if isinstance(whoami, dict)else type(whoami).__name__,whoami.get("plan") if isinstance(whoami, dict) else None,whoami.get("type") if isinstance(whoami, dict) else None,whoami.get("isPro") if isinstance(whoami, dict) else None,)if not isinstance(whoami, dict):return "free"# OAuth whoami sets `type: "user"` and surfaces Pro via the `isPro` boolean# — see Space discussion #21. HF-Jobs eligibility (PR #172) ignores plan# entirely; the premium-model daily-cap tier is still a free vs pro/org split.if whoami.get("isPro") is True or whoami.get("is_pro") is True:return "pro"plan_str = ""for key in ("plan", "type", "accountType"):value = whoami.get(key)if isinstance(value, str) and value:plan_str = value.lower()breakif any(tag in plan_str for tag in ("pro", "enterprise", "team")):return "pro"orgs = whoami.get("orgs") or []if isinstance(orgs, list) and orgs:return "org"return "free"async def _extract_user_from_token(token: str) -> dict[str, Any] | None:34 unmodified lines3536373839404111 unmodified lines535455565758596075 unmodified lines1361371381391401411421431441451461471481491501511521531541551565 unmodified lines16216316416516616716816917017117217317417534 unmodified lines"user_id": "dev","username": "dev","authenticated": True,"plan": "pro", # Dev runs at the Pro quota tier so local testing isn't capped.}INTERNAL_HF_TOKEN_KEY = "_hf_token"11 unmodified lines"write-discussions",)# Log the whoami-v2 shape once at DEBUG so we can confirm the production Pro# signal without hammering the HF API._WHOAMI_SHAPE_LOGGED = False75 unmodified lines}def _normalize_user_plan(whoami: Any) -> str:"""Normalize a whoami-v2 payload to the app's personal quota tiers."""if not isinstance(whoami, dict):return "free"if whoami.get("isPro") is True:return "pro"return "free"async def _fetch_user_plan(token: str) -> str:"""Look up the user's HF plan via /api/whoami-v2.Returns 'free' | 'pro'. Non-200, network errors, or an unknownpayload shape all collapse to 'free' — safe default; we'd rather under-grant the Pro cap than over-grant it on bad data."""5 unmodified linesif not _WHOAMI_SHAPE_LOGGED:_WHOAMI_SHAPE_LOGGED = Truelogger.debug("whoami-v2 payload keys: %s (sample values: isPro=%r)",sorted(whoami.keys())if isinstance(whoami, dict)else type(whoami).__name__,whoami.get("isPro") if isinstance(whoami, dict) else None,)return _normalize_user_plan(whoami)async def _extract_user_from_token(token: str) -> dict[str, Any] | None:
11 unmodified lines1213141516171836 unmodified lines5556575859606158 unmodified lines1201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531542 unmodified lines1571581591601611621631641651661671681691701711721731741751761771 unmodified line179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218186 unmodified lines40540640740840941041114 unmodified lines42642742842943043143243324 unmodified lines45845946046146246346459 unmodified lines5245255265275285295305315325332 unmodified lines536537538539540541542143 unmodified lines68668768868969069169245 unmodified lines73873974074174274374474574674774874911 unmodified linesfrom dependencies import (INTERNAL_HF_TOKEN_KEY,get_current_user,require_huggingface_org_member,)from fastapi import (APIRouter,36 unmodified linesDEFAULT_CLAUDE_MODEL_ID = "bedrock/us.anthropic.claude-opus-4-6-v1"DEFAULT_FREE_MODEL_ID = "moonshotai/Kimi-K2.6"GATED_MODEL_IDS = {DEFAULT_CLAUDE_MODEL_ID,"openai/gpt-5.5",}58 unmodified linesAVAILABLE_MODELS = _available_models()def _is_gated_model(model_id: str) -> bool:return model_id in GATED_MODEL_IDSdef _premium_model_restricted_error() -> HTTPException:return HTTPException(status_code=403,detail={"error": "premium_model_restricted","message": ("Premium models are gated to HF staff. Pick a free model — ""Kimi K2.6, MiniMax M2.7, GLM 5.1, or DeepSeek V4 Pro — ""instead."),},)async def _require_hf_for_gated_model(request: Request, model_id: str) -> None:"""403 if a non-``huggingface``-org user tries to select a gated model.Gated models are deployed paid endpoints backed by service-ownedcredentials. The gate only fires for deployed paid models so non-HF userscan still freely switch between the free models."""if not _is_gated_model(model_id):returnif not await require_huggingface_org_member(request):raise _premium_model_restricted_error()async def _model_override_for_new_session(2 unmodified lines) -> str | None:"""Return the model override to use when creating a new session.Explicit gated-model requests keep the hard membership gate. Implicitdefault sessions are more forgiving: when the configured default is gatedand the user lacks access, start them on the first free model instead ofblocking session creation."""resolved_model = requested_model or session_manager.config.model_nameif not _is_gated_model(resolved_model):return requested_modelif await require_huggingface_org_member(request):return requested_modelif requested_model:raise _premium_model_restricted_error()logger.info("Default gated model %s is unavailable to this user; ""creating session with free fallback %s",resolved_model,DEFAULT_FREE_MODEL_ID,1 unmodified linereturn DEFAULT_FREE_MODEL_IDasync def _enforce_gated_model_quota(user: dict[str, Any],agent_session: AgentSession,) -> None:"""Charge the user's daily gated-model quota on first use in a session.Runs at *message-submit* time, not session-create time — so spinning up agated-model session to look around doesn't burn quota. The``claude_counted`` flag on ``AgentSession`` guards against re-counting thesame session; the stored field name is kept for persistence compatibility.No-ops when the session's current model isn't gated, or when thissession has already been charged. Raises 429 when the user has hittheir daily cap."""if agent_session.claude_counted:returnmodel_name = agent_session.session.config.model_nameif not _is_gated_model(model_name):returnuser_id = user["user_id"]cap = user_quotas.daily_cap_for(user.get("plan"))new_count = await user_quotas.try_increment_claude(user_id, cap)if new_count is None:raise HTTPException(status_code=429,detail={"error": "premium_model_daily_cap","plan": user.get("plan", "free"),"cap": cap,"message": ("Daily premium model limit reached. Upgrade to HF Pro for "f"{user_quotas.CLAUDE_PRO_DAILY}/day or use a free model."),},)agent_session.claude_counted = True186 unmodified linesbehalf of the user.Optional body ``{"model"?: <id>}`` selects the session's LLM; unknownids are rejected (400). The gated-model quota runs at message-submittime, not here — spinning up a session to look around is free.Returns 503 if the server or user has reached the session limit.14 unmodified linesif model and model not in valid_ids:raise HTTPException(status_code=400, detail=f"Unknown model: {model}")# Explicit premium selections remain gated. If the implicit configured# default is unavailable, start the session on a free model instead.model = await _model_override_for_new_session(request, model)try:24 unmodified linessession's context as a user-role system note.Optional ``"model"`` in the body overrides the session's LLM. Thegated-model quota runs at message-submit time, not here."""messages = body.get("messages")if not isinstance(messages, list) or not messages:59 unmodified linesTakes effect on the next LLM call in that session — other sessions(including other browser tabs) are unaffected. Model switches don'tcharge quota — the gated-model quota only fires at message-submit time.Switching TO a gated deployed model requires HF org membership; free-modeland local-dev direct provider switches are unrestricted."""agent_session = await _check_session_access(session_id, user, request)model_id = body.get("model")2 unmodified linesvalid_ids = {m["id"] for m in AVAILABLE_MODELS}if model_id not in valid_ids:raise HTTPException(status_code=400, detail=f"Unknown model: {model_id}")await _require_hf_for_gated_model(request, model_id)if not agent_session:raise HTTPException(status_code=404, detail="Session not found")await session_manager.update_session_model(session_id, model_id)143 unmodified linesbody = SubmitRequest(**payload)except ValidationError as exc:raise RequestValidationError(exc.errors()) from excawait _enforce_gated_model_quota(user, agent_session)success = await session_manager.submit_user_input(body.session_id, body.text)if not success:raise HTTPException(status_code=404, detail="Session not found or inactive")45 unmodified linestext = body.get("text")approvals = body.get("approvals")# Gate user-message sends against the daily gated-model quota. Approvals are# continuations of an in-progress turn — the session was already charged# on its first message, so we skip the gate there.if text is not None and not approvals:try:await _enforce_gated_model_quota(user, agent_session)except HTTPException:broadcaster.unsubscribe(sub_id)raise11 unmodified lines12131415161736 unmodified lines5455565758596058 unmodified lines1191201211221231241251262 unmodified lines1291301311321331341351361371381391401411421431441451461471 unmodified line149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196186 unmodified lines38338438538638738838914 unmodified lines40440540640740840941041124 unmodified lines43643743843944044144259 unmodified lines5025035045055065075082 unmodified lines511512513514515516143 unmodified lines66066166266366466566645 unmodified lines71271371471571671771871972072172272311 unmodified linesfrom dependencies import (INTERNAL_HF_TOKEN_KEY,get_current_user,)from fastapi import (APIRouter,36 unmodified linesDEFAULT_CLAUDE_MODEL_ID = "bedrock/us.anthropic.claude-opus-4-6-v1"DEFAULT_FREE_MODEL_ID = "moonshotai/Kimi-K2.6"PREMIUM_MODEL_IDS = {DEFAULT_CLAUDE_MODEL_ID,"openai/gpt-5.5",}58 unmodified linesAVAILABLE_MODELS = _available_models()def _is_premium_model(model_id: str) -> bool:return model_id in PREMIUM_MODEL_IDSasync def _model_override_for_new_session(2 unmodified lines) -> str | None:"""Return the model override to use when creating a new session.Explicit premium model requests are allowed and charged at message-submittime. Implicit default sessions are more forgiving: when the configureddefault is premium, start them on the first free model instead of spendingpremium quota accidentally."""resolved_model = requested_model or session_manager.config.model_nameif not _is_premium_model(resolved_model):return requested_modelif requested_model:return requested_modellogger.info("Default premium model %s would spend quota; ""creating session with free fallback %s",resolved_model,DEFAULT_FREE_MODEL_ID,1 unmodified linereturn DEFAULT_FREE_MODEL_IDasync def _enforce_premium_model_quota(user: dict[str, Any],agent_session: AgentSession,) -> None:"""Charge the user's daily premium-model quota on first use in a session.Runs at *message-submit* time, not session-create time — so spinning up apremium-model session to look around doesn't burn quota. The``claude_counted`` flag on ``AgentSession`` guards against re-counting thesame session; the stored field name is kept for persistence compatibility.No-ops when the session's current model isn't premium, or when thissession has already been charged. Raises 429 when the user has hittheir daily cap."""if agent_session.claude_counted:returnmodel_name = agent_session.session.config.model_nameif not _is_premium_model(model_name):returnuser_id = user["user_id"]plan = user.get("plan", "free")cap = user_quotas.daily_cap_for(plan)new_count = await user_quotas.try_increment_claude(user_id, cap)if new_count is None:if plan == "pro":message = ("Daily premium model limit reached. Use a free model and try ""premium models again tomorrow.")else:message = ("Daily premium model limit reached. Upgrade to HF Pro for "f"{user_quotas.CLAUDE_PRO_DAILY}/day or use a free model.")raise HTTPException(status_code=429,detail={"error": "premium_model_daily_cap","plan": plan,"cap": cap,"message": message,},)agent_session.claude_counted = True186 unmodified linesbehalf of the user.Optional body ``{"model"?: <id>}`` selects the session's LLM; unknownids are rejected (400). The premium-model quota runs at message-submittime, not here — spinning up a session to look around is free.Returns 503 if the server or user has reached the session limit.14 unmodified linesif model and model not in valid_ids:raise HTTPException(status_code=400, detail=f"Unknown model: {model}")# Explicit premium selections are allowed. If the implicit configured# default is premium, start the session on a free model instead.model = await _model_override_for_new_session(request, model)try:24 unmodified linessession's context as a user-role system note.Optional ``"model"`` in the body overrides the session's LLM. Thepremium-model quota runs at message-submit time, not here."""messages = body.get("messages")if not isinstance(messages, list) or not messages:59 unmodified linesTakes effect on the next LLM call in that session — other sessions(including other browser tabs) are unaffected. Model switches don'tcharge quota — the premium-model quota only fires at message-submit time."""agent_session = await _check_session_access(session_id, user, request)model_id = body.get("model")2 unmodified linesvalid_ids = {m["id"] for m in AVAILABLE_MODELS}if model_id not in valid_ids:raise HTTPException(status_code=400, detail=f"Unknown model: {model_id}")if not agent_session:raise HTTPException(status_code=404, detail="Session not found")await session_manager.update_session_model(session_id, model_id)143 unmodified linesbody = SubmitRequest(**payload)except ValidationError as exc:raise RequestValidationError(exc.errors()) from excawait _enforce_premium_model_quota(user, agent_session)success = await session_manager.submit_user_input(body.session_id, body.text)if not success:raise HTTPException(status_code=404, detail="Session not found or inactive")45 unmodified linestext = body.get("text")approvals = body.get("approvals")# Gate user-message sends against the daily premium-model quota. Approvals are# continuations of an in-progress turn — the session was already charged# on its first message, so we skip the gate there.if text is not None and not approvals:try:await _enforce_premium_model_quota(user, agent_session)except HTTPException:broadcaster.unsubscribe(sub_id)raise
12 unmodified lines1314151617181920 unmodified lines4041424344454612 unmodified linesCap tiers:free user → CLAUDE_FREE_DAILY (1)pro / org → CLAUDE_PRO_DAILY (20)"""import asyncio20 unmodified linesdef daily_cap_for(plan: str | None) -> int:"""Return the daily Claude-session cap for the given plan."""return CLAUDE_FREE_DAILY if (plan or "free") == "free" else CLAUDE_PRO_DAILYasync def get_claude_used_today(user_id: str) -> int:12 unmodified lines1314151617181920 unmodified lines4041424344454612 unmodified linesCap tiers:free user → CLAUDE_FREE_DAILY (1)pro user → CLAUDE_PRO_DAILY (20)"""import asyncio20 unmodified linesdef daily_cap_for(plan: str | None) -> int:"""Return the daily Claude-session cap for the given plan."""return CLAUDE_PRO_DAILY if plan == "pro" else CLAUDE_FREE_DAILYasync def get_claude_used_today(user_id: str) -> int:
1234581 unmodified lines87888990919230 unmodified lines123124125126127128111 unmodified lines240241242243244245246247327 unmodified lines575576577578579580import { useState, useCallback, useEffect, useRef, KeyboardEvent } from 'react';import { Box, TextField, IconButton, CircularProgress, Typography, Menu, MenuItem, ListItemIcon, ListItemText, Chip } from '@mui/material';import ArrowUpwardIcon from '@mui/icons-material/ArrowUpward';import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown';import StopIcon from '@mui/icons-material/Stop';81 unmodified linesreturn options.find(m => m.modelPath === path || path?.includes(m.id));};interface ChatInputProps {sessionId?: string;initialModelPath?: string | null;30 unmodified linesconst setJobsUpgradeRequired = useAgentStore((s) => s.setJobsUpgradeRequired);const updateSessionModel = useSessionStore((s) => s.updateSessionModel);const [awaitingTopUp, setAwaitingTopUp] = useState(false);const lastSentRef = useRef<string>('');useEffect(() => {111 unmodified linesif (res.ok) {setSelectedModelId(model.id);updateSessionModel(sessionId, model.modelPath);}} catch { /* ignore */ }};// Dialog close: just clear the flag. The typed text is already restored.327 unmodified linesonUpgrade={handleJobsUpgradeClick}onRetry={handleJobsRetry}/></Box></Box>);12345678910111213141516171881 unmodified lines10010110210310410510610710810911011111211311411511611711830 unmodified lines149150151152153154155111 unmodified lines267268269270271272273274275276277278279327 unmodified lines607608609610611612613614615616617618619620621622623624625626627import { useState, useCallback, useEffect, useRef, KeyboardEvent } from 'react';import {Alert,Box,TextField,IconButton,CircularProgress,Typography,Menu,MenuItem,ListItemIcon,ListItemText,Chip,Snackbar,} from '@mui/material';import ArrowUpwardIcon from '@mui/icons-material/ArrowUpward';import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown';import StopIcon from '@mui/icons-material/Stop';81 unmodified linesreturn options.find(m => m.modelPath === path || path?.includes(m.id));};const readApiErrorMessage = async (res: Response, fallback: string): Promise<string> => {try {const data = await res.json();const detail = data?.detail;if (typeof detail === 'string') return detail;if (detail && typeof detail.message === 'string') return detail.message;if (detail && typeof detail.error === 'string') return detail.error;} catch {/* ignore malformed error bodies */}return fallback;};interface ChatInputProps {sessionId?: string;initialModelPath?: string | null;30 unmodified linesconst setJobsUpgradeRequired = useAgentStore((s) => s.setJobsUpgradeRequired);const updateSessionModel = useSessionStore((s) => s.updateSessionModel);const [awaitingTopUp, setAwaitingTopUp] = useState(false);const [modelSwitchError, setModelSwitchError] = useState<string | null>(null);const lastSentRef = useRef<string>('');useEffect(() => {111 unmodified linesif (res.ok) {setSelectedModelId(model.id);updateSessionModel(sessionId, model.modelPath);setModelSwitchError(null);return;}setModelSwitchError(await readApiErrorMessage(res, 'Could not switch model.'));} catch (error) {setModelSwitchError(error instanceof Error ? error.message : 'Could not switch model.');}};// Dialog close: just clear the flag. The typed text is already restored.327 unmodified linesonUpgrade={handleJobsUpgradeClick}onRetry={handleJobsRetry}/><Snackbaropen={!!modelSwitchError}anchorOrigin={{ vertical: 'top', horizontal: 'center' }}onClose={() => setModelSwitchError(null)}autoHideDuration={6000}><Alertseverity="error"variant="filled"onClose={() => setModelSwitchError(null)}sx={{ fontSize: '0.8rem', maxWidth: 480 }}>{modelSwitchError}</Alert></Snackbar></Box></Box>);
29 unmodified lines30313233343536373823 unmodified lines626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212329 unmodified linesonUseFreeModel,onUpgrade,}: ClaudeCapDialogProps) {// plan not surfaced in copy right now — Pro users see the same dialog and// can upgrade their org if they're also capped.void plan;return (<Dialog23 unmodified linessx={{ color: 'var(--muted-text)', fontSize: '0.85rem', lineHeight: 1.6 }}>Opus and GPT-5.5 are expensive to run, so we cap premium models at {cap}{' '}{cap === 1 ? 'session' : 'sessions'} a day. Give Kimi, MiniMax, GLM,or DeepSeek a spin instead.</DialogContentText><Boxsx={{mt: 2,p: 1.5,borderRadius: '8px',bgcolor: 'var(--accent-yellow-weak)',border: '1px solid var(--border)',}}><Typographyvariant="caption"sx={{display: 'block',fontWeight: 700,color: 'var(--text)',fontSize: '0.78rem',mb: 0.5,letterSpacing: '0.02em',}}>HF Pro ($9/mo) — more premium model sessions</Typography><Typographyvariant="caption"sx={{ display: 'block', color: 'var(--muted-text)', fontSize: '0.78rem', lineHeight: 1.55 }}>{PRO_CAP} premium model sessions/day here, 20× HF Inference credits,ZeroGPU access, and priority on Spaces hardware.</Typography></Box></DialogContent><DialogActions sx={{ px: 3, pb: 2.5, pt: 2, gap: 1 }}><Buttoncomponent="a"href={HF_PRICING_URL}target="_blank"rel="noopener noreferrer"onClick={onUpgrade}variant="contained"size="small"sx={{fontSize: '0.82rem',px: 2.5,bgcolor: 'var(--accent-yellow)',color: '#000',textTransform: 'none',fontWeight: 700,boxShadow: 'none','&:hover': { bgcolor: '#FFB340', boxShadow: 'none' },}}>Upgrade to Pro</Button><ButtononClick={onUseFreeModel}size="small"29 unmodified lines3031323334353623 unmodified lines6061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612729 unmodified linesonUseFreeModel,onUpgrade,}: ClaudeCapDialogProps) {const isFreePlan = plan === 'free';return (<Dialog23 unmodified linessx={{ color: 'var(--muted-text)', fontSize: '0.85rem', lineHeight: 1.6 }}>Opus and GPT-5.5 are expensive to run, so we cap premium models at {cap}{' '}{cap === 1 ? 'session' : 'sessions'} a day. {isFreePlan? 'HF Pro raises the daily premium-model limit.': 'Your plan has used today’s premium-model allowance.'}{' '}Give Kimi, MiniMax, GLM, or DeepSeek a spin instead.</DialogContentText>{isFreePlan && (<Boxsx={{mt: 2,p: 1.5,borderRadius: '8px',bgcolor: 'var(--accent-yellow-weak)',border: '1px solid var(--border)',}}><Typographyvariant="caption"sx={{display: 'block',fontWeight: 700,color: 'var(--text)',fontSize: '0.78rem',mb: 0.5,letterSpacing: '0.02em',}}>HF Pro ($9/mo) — more premium model sessions</Typography><Typographyvariant="caption"sx={{ display: 'block', color: 'var(--muted-text)', fontSize: '0.78rem', lineHeight: 1.55 }}>{PRO_CAP} premium model sessions/day here, 20× HF Inference credits,ZeroGPU access, and priority on Spaces hardware.</Typography></Box>)}</DialogContent><DialogActions sx={{ px: 3, pb: 2.5, pt: 2, gap: 1 }}>{isFreePlan && (<Buttoncomponent="a"href={HF_PRICING_URL}target="_blank"rel="noopener noreferrer"onClick={onUpgrade}variant="contained"size="small"sx={{fontSize: '0.82rem',px: 2.5,bgcolor: 'var(--accent-yellow)',color: '#000',textTransform: 'none',fontWeight: 700,boxShadow: 'none','&:hover': { bgcolor: '#FFB340', boxShadow: 'none' },}}>Upgrade to Pro</Button>)}<ButtononClick={onUseFreeModel}size="small"
147 unmodified lines148149150151152153154147 unmodified lines{awaitingTopUp? 'Once your top-up is through, click below to resume — the agent will pick the run back up where it left off.': message ||'Hugging Face Jobs need credits on the namespace running them. Add some, then resume — the agent waits here in the meantime.'}</Typography><Box147 unmodified lines148149150151152153154147 unmodified lines{awaitingTopUp? 'Once your top-up is through, click below to resume — the agent will pick the run back up where it left off.': message ||'Hugging Face Jobs need credits on the namespace running them. Job credits are separate from HF Pro membership. Add some, then resume.'}</Typography><Box
59 unmodified lines606162636465666768300 unmodified lines36937037137237337437537637759 unmodified lines},onError: (error: string) => {updateSession(sessionId, { isProcessing: false });if (isActiveRef.current) {useAgentStore.getState().setError(error);}callbacksRef.current.onError?.(error);},onProcessing: () => {300 unmodified linesreturn;}logger.error('useChat error:', error);if (isActiveRef.current) {useAgentStore.getState().setError(error.message);}},});59 unmodified lines606162636465300 unmodified lines36636736836937037159 unmodified lines},onError: (error: string) => {updateSession(sessionId, { isProcessing: false });callbacksRef.current.onError?.(error);},onProcessing: () => {300 unmodified linesreturn;}logger.error('useChat error:', error);},});
8 unmodified lines91011121314158 unmodified linesimport { useAgentStore } from '@/store/agentStore';import { apiFetch } from '@/utils/api';export type PlanTier = 'free' | 'pro' | 'org';export interface UserQuota {plan: PlanTier;8 unmodified lines91011121314158 unmodified linesimport { useAgentStore } from '@/store/agentStore';import { apiFetch } from '@/utils/api';export type PlanTier = 'free' | 'pro';export interface UserQuota {plan: PlanTier;
293 unmodified lines294295296297298299300301293 unmodified linesuseAgentStore.getState().setJobsUpgradeRequired({namespace: namespace || null,message: namespace? `Hugging Face Jobs need credits on the "${namespace}" namespace. Add some, then re-run the same job — the agent will pick it back up.`: 'Hugging Face Jobs need credits on this namespace. Add some, then re-run the same job — the agent will pick it back up.',});}break;293 unmodified lines294295296297298299300301293 unmodified linesuseAgentStore.getState().setJobsUpgradeRequired({namespace: namespace || null,message: namespace? `Hugging Face Jobs need credits on the "${namespace}" namespace. Job credits are separate from HF Pro membership; add credits, then re-run the same job.`: 'Hugging Face Jobs need namespace credits, which are separate from HF Pro membership. Add credits, then re-run the same job.',});}break;
5 unmodified lines6789101112104 unmodified lines11711811912012112212349 unmodified lines173174175176177178179115 unmodified lines29529629729829930030133 unmodified lines33533633733833934034146 unmodified lines3883893903913923933943953963973983994004018 unmodified lines4104114124134144154165 unmodified lines* - Connection / processing flags* - Panel state (right panel — single-artifact pattern)* - Plan state* - User info / error banners* - Edited scripts (for hf_jobs code editing)** Per-session state:104 unmodified linesisConnected: boolean;activityStatus: ActivityStatus;user: User | null;error: string | null;llmHealthError: LLMHealthError | null;/** Set when a premium-model send hits the daily quota; ChatInput opens the cap dialog. */claudeQuotaExhausted: boolean;49 unmodified linessetConnected: (isConnected: boolean) => void;setActivityStatus: (status: ActivityStatus) => void;setUser: (user: User | null) => void;setError: (error: string | null) => void;setLlmHealthError: (error: LLMHealthError | null) => void;setClaudeQuotaExhausted: (exhausted: boolean) => void;setJobsUpgradeRequired: (state: JobsUpgradeState | null) => void;115 unmodified linesisConnected: false,activityStatus: { type: 'idle' },user: null,error: null,llmHealthError: null,claudeQuotaExhausted: false,jobsUpgradeRequired: null,33 unmodified lines// (plus activityStatus when the processing→idle side-effect fires).// This prevents overwriting flat fields changed by global setters// (e.g. setPanelView called from CodePanel) with stale snapshot values.let flatMirror: Record<string, unknown> = {};if (isActive) {for (const key of Object.keys(updates)) {flatMirror[key] = updated[key as keyof PerSessionState];46 unmodified linespanelView: incoming.panelView,panelEditable: incoming.panelEditable,plan: incoming.plan,// Clear transient error on switcherror: null,});},clearSessionState: (sessionId) => {set((state) => {const { [sessionId]: _, ...rest } = state.sessionStates;return { sessionStates: rest };});},8 unmodified linessetConnected: (isConnected) => set({ isConnected }),setActivityStatus: (status) => set({ activityStatus: status }),setUser: (user) => set({ user }),setError: (error) => set({ error }),setLlmHealthError: (error) => set({ llmHealthError: error }),setClaudeQuotaExhausted: (exhausted) => set({ claudeQuotaExhausted: exhausted }),setJobsUpgradeRequired: (state) => set({ jobsUpgradeRequired: state }),5 unmodified lines6789101112104 unmodified lines11711811912012112249 unmodified lines172173174175176177115 unmodified lines29329429529629729833 unmodified lines33233333433533633733846 unmodified lines3853863873883893903913923933943953963978 unmodified lines4064074084094104115 unmodified lines* - Connection / processing flags* - Panel state (right panel — single-artifact pattern)* - Plan state* - User info / health and quota banners* - Edited scripts (for hf_jobs code editing)** Per-session state:104 unmodified linesisConnected: boolean;activityStatus: ActivityStatus;user: User | null;llmHealthError: LLMHealthError | null;/** Set when a premium-model send hits the daily quota; ChatInput opens the cap dialog. */claudeQuotaExhausted: boolean;49 unmodified linessetConnected: (isConnected: boolean) => void;setActivityStatus: (status: ActivityStatus) => void;setUser: (user: User | null) => void;setLlmHealthError: (error: LLMHealthError | null) => void;setClaudeQuotaExhausted: (exhausted: boolean) => void;setJobsUpgradeRequired: (state: JobsUpgradeState | null) => void;115 unmodified linesisConnected: false,activityStatus: { type: 'idle' },user: null,llmHealthError: null,claudeQuotaExhausted: false,jobsUpgradeRequired: null,33 unmodified lines// (plus activityStatus when the processing→idle side-effect fires).// This prevents overwriting flat fields changed by global setters// (e.g. setPanelView called from CodePanel) with stale snapshot values.const flatMirror: Record<string, unknown> = {};if (isActive) {for (const key of Object.keys(updates)) {flatMirror[key] = updated[key as keyof PerSessionState];46 unmodified linespanelView: incoming.panelView,panelEditable: incoming.panelEditable,plan: incoming.plan,});},clearSessionState: (sessionId) => {set((state) => {const rest = { ...state.sessionStates };delete rest[sessionId];return { sessionStates: rest };});},8 unmodified linessetConnected: (isConnected) => set({ isConnected }),setActivityStatus: (status) => set({ activityStatus: status }),setUser: (user) => set({ user }),setLlmHealthError: (error) => set({ llmHealthError: error }),setClaudeQuotaExhausted: (exhausted) => set({ claudeQuotaExhausted: exhausted }),setJobsUpgradeRequired: (state) => set({ jobsUpgradeRequired: state }),
123417 unmodified lines222324252627282930313233343536373839404142434445464748495051525354555657585960616263646 unmodified lines717273747576777879808182838485868788892 unmodified lines92939495969798991001011021031041051061073 unmodified lines11111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314412 unmodified lines1571581591601611621634 unmodified lines1681691701711721731741751768 unmodified lines185186187188189190191"""Tests for gated model handling in backend/routes/agent.py."""import asyncioimport sys17 unmodified linesagent.user_quotas._reset_for_tests()def test_gated_model_predicate_includes_bedrock_claude_and_gpt55_only():assert agent._is_gated_model("bedrock/us.anthropic.claude-opus-4-6-v1")assert agent._is_gated_model("openai/gpt-5.5")assert not agent._is_gated_model("anthropic/claude-opus-4-6")assert not agent._is_gated_model("moonshotai/Kimi-K2.6")@pytest.mark.asyncioasync def test_gated_model_gate_rejects_gpt55_for_non_hf_user(monkeypatch):async def fake_require_hf_org_member(_request):return Falsemonkeypatch.setattr(agent,"require_huggingface_org_member",fake_require_hf_org_member,)with pytest.raises(HTTPException) as exc_info:await agent._require_hf_for_gated_model(None, "openai/gpt-5.5")assert exc_info.value.status_code == 403assert exc_info.value.detail["error"] == "premium_model_restricted"@pytest.mark.asyncioasync def test_default_gated_session_falls_back_to_free_model_for_non_hf_user(monkeypatch,):async def fake_require_hf_org_member(_request):return Falsemonkeypatch.setattr(agent,"require_huggingface_org_member",fake_require_hf_org_member,)monkeypatch.setattr(agent.session_manager.config,"model_name",6 unmodified lines@pytest.mark.asyncioasync def test_default_gated_session_stays_default_for_hf_user(monkeypatch):async def fake_require_hf_org_member(_request):return Truemonkeypatch.setattr(agent,"require_huggingface_org_member",fake_require_hf_org_member,)monkeypatch.setattr(agent.session_manager.config,"model_name",agent.DEFAULT_CLAUDE_MODEL_ID,)model = await agent._model_override_for_new_session(None, None)2 unmodified lines@pytest.mark.asyncioasync def test_explicit_gated_session_allowed_for_hf_user(monkeypatch):async def fake_require_hf_org_member(_request):return Truemonkeypatch.setattr(agent,"require_huggingface_org_member",fake_require_hf_org_member,)model = await agent._model_override_for_new_session(None,agent.DEFAULT_CLAUDE_MODEL_ID,3 unmodified lines@pytest.mark.asyncioasync def test_explicit_gated_session_request_still_rejects_non_hf_user(monkeypatch):async def fake_require_hf_org_member(_request):return Falsemonkeypatch.setattr(agent, "require_huggingface_org_member", fake_require_hf_org_member)with pytest.raises(HTTPException) as exc_info:await agent._model_override_for_new_session(None, agent.DEFAULT_CLAUDE_MODEL_ID)assert exc_info.value.status_code == 403assert exc_info.value.detail["error"] == "premium_model_restricted"@pytest.mark.asyncioasync def test_ungated_models_skip_hf_membership_check(monkeypatch):async def fail_if_called(_request):raise AssertionError("ungated models must not require HF org membership")monkeypatch.setattr(agent, "require_huggingface_org_member", fail_if_called)await agent._require_hf_for_gated_model(None, "moonshotai/Kimi-K2.6")await agent._require_hf_for_gated_model(None, "anthropic/claude-opus-4-6")@pytest.mark.asyncioasync def test_gated_quota_charges_gpt55(monkeypatch):persisted = []async def fake_persist_session_snapshot(agent_session):12 unmodified lines),)await agent._enforce_gated_model_quota({"user_id": "u1", "plan": "free"},agent_session,)4 unmodified lines@pytest.mark.asyncioasync def test_gated_quota_skips_direct_anthropic(monkeypatch):async def fail_if_persisted(_agent_session):raise AssertionError("direct Anthropic should not consume deployed gated quota")monkeypatch.setattr(agent.session_manager,8 unmodified lines),)await agent._enforce_gated_model_quota({"user_id": "u1", "plan": "free"},agent_session,)123417 unmodified lines2223242526272829303132333435366 unmodified lines43444546474849505152532 unmodified lines565758596061623 unmodified lines6667686970717273747576777879808182838485868788899091929394959697989910010110210310412 unmodified lines1171181191201211221234 unmodified lines1281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392408 unmodified lines249250251252253254255"""Tests for premium model handling in backend/routes/agent.py."""import asyncioimport sys17 unmodified linesagent.user_quotas._reset_for_tests()def test_premium_model_predicate_includes_bedrock_claude_and_gpt55_only():assert agent._is_premium_model("bedrock/us.anthropic.claude-opus-4-6-v1")assert agent._is_premium_model("openai/gpt-5.5")assert not agent._is_premium_model("anthropic/claude-opus-4-6")assert not agent._is_premium_model("moonshotai/Kimi-K2.6")@pytest.mark.asyncioasync def test_default_premium_session_falls_back_to_free_model(monkeypatch):monkeypatch.setattr(agent.session_manager.config,"model_name",6 unmodified lines@pytest.mark.asyncioasync def test_default_free_session_keeps_config_default(monkeypatch):monkeypatch.setattr(agent.session_manager.config,"model_name",agent.DEFAULT_FREE_MODEL_ID,)model = await agent._model_override_for_new_session(None, None)2 unmodified lines@pytest.mark.asyncioasync def test_explicit_premium_session_allowed_for_authenticated_user():model = await agent._model_override_for_new_session(None,agent.DEFAULT_CLAUDE_MODEL_ID,3 unmodified lines@pytest.mark.asyncioasync def test_switching_to_premium_model_is_allowed_for_authenticated_user(monkeypatch,):updated = []async def fake_check_session_access(session_id, user, request=None):assert session_id == "s1"assert user["user_id"] == "u1"return SimpleNamespace(user_id="u1")async def fake_update_session_model(session_id, model_id):updated.append((session_id, model_id))monkeypatch.setattr(agent, "_check_session_access", fake_check_session_access)monkeypatch.setattr(agent.session_manager,"update_session_model",fake_update_session_model,)response = await agent.set_session_model("s1",{"model": "openai/gpt-5.5"},request=None,user={"user_id": "u1", "plan": "free"},)assert response == {"session_id": "s1", "model": "openai/gpt-5.5"}assert updated == [("s1", "openai/gpt-5.5")]@pytest.mark.asyncioasync def test_premium_quota_charges_gpt55(monkeypatch):persisted = []async def fake_persist_session_snapshot(agent_session):12 unmodified lines),)await agent._enforce_premium_model_quota({"user_id": "u1", "plan": "free"},agent_session,)4 unmodified lines@pytest.mark.asyncioasync def test_free_user_premium_quota_rejects_second_session(monkeypatch):async def fake_persist_session_snapshot(_agent_session):return Nonemonkeypatch.setattr(agent.session_manager,"persist_session_snapshot",fake_persist_session_snapshot,)first_session = SimpleNamespace(claude_counted=False,session=SimpleNamespace(config=SimpleNamespace(model_name="openai/gpt-5.5"),),)second_session = SimpleNamespace(claude_counted=False,session=SimpleNamespace(config=SimpleNamespace(model_name="openai/gpt-5.5"),),)await agent._enforce_premium_model_quota({"user_id": "free-user", "plan": "free"},first_session,)with pytest.raises(HTTPException) as exc_info:await agent._enforce_premium_model_quota({"user_id": "free-user", "plan": "free"},second_session,)assert exc_info.value.status_code == 429assert exc_info.value.detail["error"] == "premium_model_daily_cap"assert exc_info.value.detail["plan"] == "free"@pytest.mark.asyncioasync def test_pro_user_uses_pro_premium_quota(monkeypatch):async def fake_persist_session_snapshot(_agent_session):return Nonemonkeypatch.setattr(agent.session_manager,"persist_session_snapshot",fake_persist_session_snapshot,)for index in range(2):agent_session = SimpleNamespace(claude_counted=False,session=SimpleNamespace(config=SimpleNamespace(model_name="openai/gpt-5.5"),),)await agent._enforce_premium_model_quota({"user_id": "pro-user", "plan": "pro"},agent_session,)assert agent_session.claude_counted is Trueassert await agent.user_quotas.get_claude_used_today("pro-user") == index + 1@pytest.mark.asyncioasync def test_org_plan_uses_free_premium_quota(monkeypatch):async def fake_persist_session_snapshot(_agent_session):return Nonemonkeypatch.setattr(agent.session_manager,"persist_session_snapshot",fake_persist_session_snapshot,)first_session = SimpleNamespace(claude_counted=False,session=SimpleNamespace(config=SimpleNamespace(model_name="openai/gpt-5.5"),),)second_session = SimpleNamespace(claude_counted=False,session=SimpleNamespace(config=SimpleNamespace(model_name="openai/gpt-5.5"),),)await agent._enforce_premium_model_quota({"user_id": "org-user", "plan": "org"},first_session,)with pytest.raises(HTTPException) as exc_info:await agent._enforce_premium_model_quota({"user_id": "org-user", "plan": "org"},second_session,)assert exc_info.value.status_code == 429assert exc_info.value.detail["plan"] == "org"assert "Upgrade to HF Pro" in exc_info.value.detail["message"]@pytest.mark.asyncioasync def test_premium_quota_skips_direct_anthropic(monkeypatch):async def fail_if_persisted(_agent_session):raise AssertionError("direct Anthropic should not consume premium quota")monkeypatch.setattr(agent.session_manager,8 unmodified lines),)await agent._enforce_premium_model_quota({"user_id": "u1", "plan": "free"},agent_session,)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657"""Tests for Hugging Face plan normalization."""
import sysfrom pathlib import Path
import pytest
_BACKEND_DIR = Path(__file__).resolve().parent.parent.parent / "backend"if str(_BACKEND_DIR) not in sys.path: sys.path.insert(0, str(_BACKEND_DIR))
import dependencies # noqa: E402
def test_oauth_is_pro_flag_takes_priority_over_user_type(): assert dependencies._normalize_user_plan({"type": "user", "isPro": True}) == "pro"
@pytest.mark.parametrize( "payload", [ {"is_pro": True}, {"accountType": "pro"}, {"plan": "HF Pro"}, {"subscription": "hf_pro"}, {"accountType": "team"}, {"plan": "enterprise"}, {"tier": "promotional"}, ],)def test_non_ispro_signals_stay_free(payload): assert dependencies._normalize_user_plan(payload) == "free"
def test_free_user_with_free_org_stays_free(): whoami = { "name": "alice", "type": "user", "orgs": [{"name": "oss-friends", "plan": "free"}], }
assert dependencies._normalize_user_plan(whoami) == "free"
def test_user_with_paid_org_without_personal_pro_stays_free(): whoami = { "name": "alice", "type": "user", "orgs": [{"name": "team-a", "plan": "team"}], }
assert dependencies._normalize_user_plan(whoami) == "free"
@pytest.mark.parametrize("payload", [None, [], {"type": "user"}, {"plan": "free"}])def test_unknown_or_malformed_payload_defaults_to_free(payload): assert dependencies._normalize_user_plan(payload) == "free"26 unmodified lines2728293031323334353637383940414226 unmodified linesdef test_daily_cap_for_known_plans():assert user_quotas.daily_cap_for("free") == user_quotas.CLAUDE_FREE_DAILYassert user_quotas.daily_cap_for("pro") == user_quotas.CLAUDE_PRO_DAILYassert user_quotas.daily_cap_for("org") == user_quotas.CLAUDE_PRO_DAILYdef test_daily_cap_for_unknown_or_missing_defaults_to_free():assert user_quotas.daily_cap_for(None) == user_quotas.CLAUDE_FREE_DAILYassert user_quotas.daily_cap_for("") == user_quotas.CLAUDE_FREE_DAILY# Anything we don't recognize as the Pro/Org tier gets the Pro cap because# the function's contract is "free" is the only downgraded tier. If that# ever flips, this test will flip too — adjust consciously.assert user_quotas.daily_cap_for("mystery") == user_quotas.CLAUDE_PRO_DAILY@pytest.mark.asyncio26 unmodified lines2728293031323334353637383926 unmodified linesdef test_daily_cap_for_known_plans():assert user_quotas.daily_cap_for("free") == user_quotas.CLAUDE_FREE_DAILYassert user_quotas.daily_cap_for("pro") == user_quotas.CLAUDE_PRO_DAILYassert user_quotas.daily_cap_for("org") == user_quotas.CLAUDE_FREE_DAILYdef test_daily_cap_for_unknown_or_missing_defaults_to_free():assert user_quotas.daily_cap_for(None) == user_quotas.CLAUDE_FREE_DAILYassert user_quotas.daily_cap_for("") == user_quotas.CLAUDE_FREE_DAILYassert user_quotas.daily_cap_for("mystery") == user_quotas.CLAUDE_FREE_DAILY@pytest.mark.asyncio