Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Commit Β·
1d590c5
1
Parent(s): 8e0a54d
feat: require org membership to create sessions
Browse filesGate session creation behind ml-agent-explorers org membership.
Shows a join step on the welcome screen for users not yet in the org.
backend/dependencies.py
CHANGED
|
@@ -22,6 +22,9 @@ AUTH_ENABLED = bool(os.environ.get("OAUTH_CLIENT_ID", ""))
|
|
| 22 |
_token_cache: dict[str, tuple[dict[str, Any], float]] = {}
|
| 23 |
TOKEN_CACHE_TTL = 300 # 5 minutes
|
| 24 |
|
|
|
|
|
|
|
|
|
|
| 25 |
DEV_USER: dict[str, Any] = {
|
| 26 |
"user_id": "dev",
|
| 27 |
"username": "dev",
|
|
@@ -80,6 +83,31 @@ async def _extract_user_from_token(token: str) -> dict[str, Any] | None:
|
|
| 80 |
return None
|
| 81 |
|
| 82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
async def get_current_user(request: Request) -> dict[str, Any]:
|
| 84 |
"""FastAPI dependency: extract and validate the current user.
|
| 85 |
|
|
|
|
| 22 |
_token_cache: dict[str, tuple[dict[str, Any], float]] = {}
|
| 23 |
TOKEN_CACHE_TTL = 300 # 5 minutes
|
| 24 |
|
| 25 |
+
# Org membership cache: key -> expiry_time (only caches positive results)
|
| 26 |
+
_org_member_cache: dict[str, float] = {}
|
| 27 |
+
|
| 28 |
DEV_USER: dict[str, Any] = {
|
| 29 |
"user_id": "dev",
|
| 30 |
"username": "dev",
|
|
|
|
| 83 |
return None
|
| 84 |
|
| 85 |
|
| 86 |
+
async def check_org_membership(token: str, org_name: str) -> bool:
|
| 87 |
+
"""Check if the token owner belongs to an HF org. Only caches positive results."""
|
| 88 |
+
now = time.time()
|
| 89 |
+
key = token + org_name
|
| 90 |
+
cached = _org_member_cache.get(key)
|
| 91 |
+
if cached and cached > now:
|
| 92 |
+
return True
|
| 93 |
+
|
| 94 |
+
async with httpx.AsyncClient(timeout=10.0) as client:
|
| 95 |
+
try:
|
| 96 |
+
resp = await client.get(
|
| 97 |
+
f"{OPENID_PROVIDER_URL}/api/whoami-v2",
|
| 98 |
+
headers={"Authorization": f"Bearer {token}"},
|
| 99 |
+
)
|
| 100 |
+
if resp.status_code != 200:
|
| 101 |
+
return False
|
| 102 |
+
orgs = {o.get("name") for o in resp.json().get("orgs", [])}
|
| 103 |
+
if org_name in orgs:
|
| 104 |
+
_org_member_cache[key] = now + TOKEN_CACHE_TTL
|
| 105 |
+
return True
|
| 106 |
+
return False
|
| 107 |
+
except httpx.HTTPError:
|
| 108 |
+
return False
|
| 109 |
+
|
| 110 |
+
|
| 111 |
async def get_current_user(request: Request) -> dict[str, Any]:
|
| 112 |
"""FastAPI dependency: extract and validate the current user.
|
| 113 |
|
backend/routes/agent.py
CHANGED
|
@@ -8,7 +8,7 @@ import logging
|
|
| 8 |
import os
|
| 9 |
from typing import Any
|
| 10 |
|
| 11 |
-
from dependencies import get_current_user, get_ws_user
|
| 12 |
from fastapi import (
|
| 13 |
APIRouter,
|
| 14 |
Depends,
|
|
@@ -35,6 +35,9 @@ logger = logging.getLogger(__name__)
|
|
| 35 |
|
| 36 |
router = APIRouter(prefix="/api", tags=["agent"])
|
| 37 |
|
|
|
|
|
|
|
|
|
|
| 38 |
AVAILABLE_MODELS = [
|
| 39 |
{
|
| 40 |
"id": "anthropic/claude-opus-4-6",
|
|
@@ -214,6 +217,14 @@ async def create_session(
|
|
| 214 |
if not hf_token:
|
| 215 |
hf_token = request.cookies.get("hf_access_token")
|
| 216 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
try:
|
| 218 |
session_id = await session_manager.create_session(
|
| 219 |
user_id=user["user_id"], hf_token=hf_token
|
|
|
|
| 8 |
import os
|
| 9 |
from typing import Any
|
| 10 |
|
| 11 |
+
from dependencies import AUTH_ENABLED, check_org_membership, get_current_user, get_ws_user
|
| 12 |
from fastapi import (
|
| 13 |
APIRouter,
|
| 14 |
Depends,
|
|
|
|
| 35 |
|
| 36 |
router = APIRouter(prefix="/api", tags=["agent"])
|
| 37 |
|
| 38 |
+
REQUIRED_ORG = "ml-agent-explorers"
|
| 39 |
+
ORG_JOIN_URL = "https://huggingface.co/organizations/ml-agent-explorers/share/GzPMJUivoFPlfkvFtIqEouZKSytatKQSZT"
|
| 40 |
+
|
| 41 |
AVAILABLE_MODELS = [
|
| 42 |
{
|
| 43 |
"id": "anthropic/claude-opus-4-6",
|
|
|
|
| 217 |
if not hf_token:
|
| 218 |
hf_token = request.cookies.get("hf_access_token")
|
| 219 |
|
| 220 |
+
# Gate access behind org membership
|
| 221 |
+
if AUTH_ENABLED and hf_token:
|
| 222 |
+
if not await check_org_membership(hf_token, REQUIRED_ORG):
|
| 223 |
+
raise HTTPException(
|
| 224 |
+
status_code=403,
|
| 225 |
+
detail={"error": "org_required", "join_url": ORG_JOIN_URL},
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
try:
|
| 229 |
session_id = await session_manager.create_session(
|
| 230 |
user_id=user["user_id"], hf_token=hf_token
|
frontend/src/components/WelcomeScreen/WelcomeScreen.tsx
CHANGED
|
@@ -7,6 +7,7 @@ import {
|
|
| 7 |
Alert,
|
| 8 |
} from '@mui/material';
|
| 9 |
import OpenInNewIcon from '@mui/icons-material/OpenInNew';
|
|
|
|
| 10 |
import { useSessionStore } from '@/store/sessionStore';
|
| 11 |
import { useAgentStore } from '@/store/agentStore';
|
| 12 |
import { apiFetch } from '@/utils/api';
|
|
@@ -15,34 +16,34 @@ import { isInIframe, triggerLogin } from '@/hooks/useAuth';
|
|
| 15 |
/** HF brand orange */
|
| 16 |
const HF_ORANGE = '#FF9D00';
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
export default function WelcomeScreen() {
|
| 19 |
const { createSession } = useSessionStore();
|
| 20 |
const { setPlan, clearPanel, user } = useAgentStore();
|
| 21 |
const [isCreating, setIsCreating] = useState(false);
|
| 22 |
const [error, setError] = useState<string | null>(null);
|
|
|
|
| 23 |
|
| 24 |
const inIframe = isInIframe();
|
| 25 |
const isAuthenticated = user?.authenticated;
|
| 26 |
const isDevUser = user?.username === 'dev';
|
| 27 |
|
| 28 |
-
const
|
| 29 |
-
if (isCreating) return;
|
| 30 |
-
|
| 31 |
-
// Not authenticated and not dev β need to login
|
| 32 |
-
if (!isAuthenticated && !isDevUser) {
|
| 33 |
-
// In iframe: can't redirect (cookies blocked) β user needs to open in new tab
|
| 34 |
-
// This shouldn't happen because we show a different button in iframe
|
| 35 |
-
// But just in case:
|
| 36 |
-
if (inIframe) return;
|
| 37 |
-
triggerLogin();
|
| 38 |
-
return;
|
| 39 |
-
}
|
| 40 |
-
|
| 41 |
setIsCreating(true);
|
| 42 |
setError(null);
|
| 43 |
|
| 44 |
try {
|
| 45 |
const response = await apiFetch('/api/session', { method: 'POST' });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
if (response.status === 503) {
|
| 47 |
const data = await response.json();
|
| 48 |
setError(data.detail || 'Server is at capacity. Please try again later.');
|
|
@@ -57,6 +58,7 @@ export default function WelcomeScreen() {
|
|
| 57 |
return;
|
| 58 |
}
|
| 59 |
const data = await response.json();
|
|
|
|
| 60 |
createSession(data.session_id);
|
| 61 |
setPlan([]);
|
| 62 |
clearPanel();
|
|
@@ -65,7 +67,19 @@ export default function WelcomeScreen() {
|
|
| 65 |
} finally {
|
| 66 |
setIsCreating(false);
|
| 67 |
}
|
| 68 |
-
}, [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
// Build the direct Space URL for the "open in new tab" link
|
| 71 |
const spaceHost = typeof window !== 'undefined'
|
|
@@ -129,8 +143,67 @@ export default function WelcomeScreen() {
|
|
| 129 |
and explores <strong>datasets</strong> β all through natural conversation.
|
| 130 |
</Typography>
|
| 131 |
|
| 132 |
-
{/* Action
|
| 133 |
-
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
// In iframe + not logged in β link to open Space directly
|
| 135 |
<Button
|
| 136 |
variant="contained"
|
|
|
|
| 7 |
Alert,
|
| 8 |
} from '@mui/material';
|
| 9 |
import OpenInNewIcon from '@mui/icons-material/OpenInNew';
|
| 10 |
+
import GroupAddIcon from '@mui/icons-material/GroupAdd';
|
| 11 |
import { useSessionStore } from '@/store/sessionStore';
|
| 12 |
import { useAgentStore } from '@/store/agentStore';
|
| 13 |
import { apiFetch } from '@/utils/api';
|
|
|
|
| 16 |
/** HF brand orange */
|
| 17 |
const HF_ORANGE = '#FF9D00';
|
| 18 |
|
| 19 |
+
interface OrgGate {
|
| 20 |
+
joinUrl: string;
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
export default function WelcomeScreen() {
|
| 24 |
const { createSession } = useSessionStore();
|
| 25 |
const { setPlan, clearPanel, user } = useAgentStore();
|
| 26 |
const [isCreating, setIsCreating] = useState(false);
|
| 27 |
const [error, setError] = useState<string | null>(null);
|
| 28 |
+
const [orgGate, setOrgGate] = useState<OrgGate | null>(null);
|
| 29 |
|
| 30 |
const inIframe = isInIframe();
|
| 31 |
const isAuthenticated = user?.authenticated;
|
| 32 |
const isDevUser = user?.username === 'dev';
|
| 33 |
|
| 34 |
+
const tryCreateSession = useCallback(async () => {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
setIsCreating(true);
|
| 36 |
setError(null);
|
| 37 |
|
| 38 |
try {
|
| 39 |
const response = await apiFetch('/api/session', { method: 'POST' });
|
| 40 |
+
if (response.status === 403) {
|
| 41 |
+
const data = await response.json();
|
| 42 |
+
if (data.detail?.error === 'org_required') {
|
| 43 |
+
setOrgGate({ joinUrl: data.detail.join_url });
|
| 44 |
+
return;
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
if (response.status === 503) {
|
| 48 |
const data = await response.json();
|
| 49 |
setError(data.detail || 'Server is at capacity. Please try again later.');
|
|
|
|
| 58 |
return;
|
| 59 |
}
|
| 60 |
const data = await response.json();
|
| 61 |
+
setOrgGate(null);
|
| 62 |
createSession(data.session_id);
|
| 63 |
setPlan([]);
|
| 64 |
clearPanel();
|
|
|
|
| 67 |
} finally {
|
| 68 |
setIsCreating(false);
|
| 69 |
}
|
| 70 |
+
}, [createSession, setPlan, clearPanel]);
|
| 71 |
+
|
| 72 |
+
const handleStart = useCallback(async () => {
|
| 73 |
+
if (isCreating) return;
|
| 74 |
+
|
| 75 |
+
if (!isAuthenticated && !isDevUser) {
|
| 76 |
+
if (inIframe) return;
|
| 77 |
+
triggerLogin();
|
| 78 |
+
return;
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
await tryCreateSession();
|
| 82 |
+
}, [isCreating, isAuthenticated, isDevUser, inIframe, tryCreateSession]);
|
| 83 |
|
| 84 |
// Build the direct Space URL for the "open in new tab" link
|
| 85 |
const spaceHost = typeof window !== 'undefined'
|
|
|
|
| 143 |
and explores <strong>datasets</strong> β all through natural conversation.
|
| 144 |
</Typography>
|
| 145 |
|
| 146 |
+
{/* Action area β depends on context */}
|
| 147 |
+
{orgGate ? (
|
| 148 |
+
// Authenticated but not in org β join step
|
| 149 |
+
<Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2, maxWidth: 480, px: 2 }}>
|
| 150 |
+
<Typography
|
| 151 |
+
variant="body2"
|
| 152 |
+
sx={{
|
| 153 |
+
color: 'var(--muted-text)',
|
| 154 |
+
textAlign: 'center',
|
| 155 |
+
lineHeight: 1.7,
|
| 156 |
+
fontSize: '0.88rem',
|
| 157 |
+
'& strong': { color: 'var(--text)', fontWeight: 600 },
|
| 158 |
+
}}
|
| 159 |
+
>
|
| 160 |
+
Under the hood, this agent uses GPUs, inference APIs, and other paid Hub goodies β but we made them all free for you.
|
| 161 |
+
Just join <strong>ML Agent Explorers</strong> and you're in!
|
| 162 |
+
</Typography>
|
| 163 |
+
<Button
|
| 164 |
+
variant="contained"
|
| 165 |
+
size="large"
|
| 166 |
+
component="a"
|
| 167 |
+
href={orgGate.joinUrl}
|
| 168 |
+
target="_blank"
|
| 169 |
+
rel="noopener noreferrer"
|
| 170 |
+
startIcon={<GroupAddIcon />}
|
| 171 |
+
sx={{
|
| 172 |
+
px: 5,
|
| 173 |
+
py: 1.5,
|
| 174 |
+
fontSize: '1rem',
|
| 175 |
+
fontWeight: 700,
|
| 176 |
+
textTransform: 'none',
|
| 177 |
+
borderRadius: '12px',
|
| 178 |
+
bgcolor: HF_ORANGE,
|
| 179 |
+
color: '#000',
|
| 180 |
+
boxShadow: '0 4px 24px rgba(255, 157, 0, 0.3)',
|
| 181 |
+
textDecoration: 'none',
|
| 182 |
+
'&:hover': {
|
| 183 |
+
bgcolor: '#FFB340',
|
| 184 |
+
boxShadow: '0 6px 32px rgba(255, 157, 0, 0.45)',
|
| 185 |
+
},
|
| 186 |
+
}}
|
| 187 |
+
>
|
| 188 |
+
Join ML Agent Explorers
|
| 189 |
+
</Button>
|
| 190 |
+
<Button
|
| 191 |
+
variant="text"
|
| 192 |
+
size="small"
|
| 193 |
+
onClick={tryCreateSession}
|
| 194 |
+
disabled={isCreating}
|
| 195 |
+
startIcon={isCreating ? <CircularProgress size={16} color="inherit" /> : null}
|
| 196 |
+
sx={{
|
| 197 |
+
color: 'var(--muted-text)',
|
| 198 |
+
textTransform: 'none',
|
| 199 |
+
fontSize: '0.85rem',
|
| 200 |
+
'&:hover': { color: 'var(--text)' },
|
| 201 |
+
}}
|
| 202 |
+
>
|
| 203 |
+
{isCreating ? 'Checking...' : "I've joined β let's go"}
|
| 204 |
+
</Button>
|
| 205 |
+
</Box>
|
| 206 |
+
) : inIframe && !isAuthenticated && !isDevUser ? (
|
| 207 |
// In iframe + not logged in β link to open Space directly
|
| 208 |
<Button
|
| 209 |
variant="contained"
|