Spaces:
Running
Running
fix: replace programmatic like with redirect to HF Space page
Browse filesHuggingFace intentionally blocks programmatic likes via API tokens to
prevent spam. Replace the failing POST /api/spaces/{id}/like call with
a redirect to the Space page on huggingface.co where users can like
natively. Likes are refreshed automatically when the tab regains focus.
Also remove the now-unnecessary write-discussions OAuth scope.
Co-authored-by: Cursor <cursoragent@cursor.com>
Files changed (4)
5 unmodified lines678910910115 unmodified linessdk: dockerpinned: truehf_oauth: truehf_oauth_scopes: - write-discussionsthumbnail: >- https://cdn-uploads.huggingface.co/production/uploads/671faa3a541a76b548647676/XWNDlOu0R4fHXR0kCW3Wd.pngshort_description: All about Reachy Mini, from building to getting started20 unmodified lines2122232424252627143 unmodified lines17117217317417417517617717717817918118018118218318418518618718818920 unmodified linesimport { useAuth } from '../context/AuthContext';
function InstallModal({ open, onClose, app }) { const { isLoggedIn, isSpaceLiked, toggleLike } = useAuth(); const { isLoggedIn, isSpaceLiked, openSpaceForLike, login } = useAuth(); // Detect Linux users const isLinux = useMemo(() => { if (typeof navigator === 'undefined') return false;143 unmodified lines {/* Stats row */} <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mt: 1 }}> <Tooltip title={isLoggedIn ? '' : 'Sign in to like this app'} title={isLoggedIn ? 'Like on Hugging Face' : 'Sign in to like this app'} arrow placement="top" disableHoverListener={isLoggedIn} > <Box component="button" onClick={() => toggleLike(app.id)} onClick={() => { if (!isLoggedIn) { login(); return; } openSpaceForLike(app.id); }} sx={{ display: 'flex', alignItems: 'center',1123438 unmodified lines43444546464748495050515211 unmodified lines6465666867686970717372737447 unmodified lines1221231241271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821251261271281291301311321331341351361841371381391401411421431441451461471481491501511525 unmodified lines158159160198161162163164165import { createContext, useContext, useState, useEffect, useCallback, useRef } from 'react';import { createContext, useContext, useState, useEffect, useCallback } from 'react';import { oauthLoginUrl, oauthHandleRedirectIfPresent } from '@huggingface/hub';
const AuthContext = createContext(null);38 unmodified lines
// Provider componentexport function AuthProvider({ children }) { const [user, setUser] = useState(null); // { name, avatarUrl, accessToken } const [user, setUser] = useState(null); // { name, avatarUrl } const [likedSpaceIds, setLikedSpaceIds] = useState(new Set()); const [isLoading, setIsLoading] = useState(true); const [oauthConfig, setOauthConfig] = useState(null); // { clientId, scopes } const pendingLikes = useRef(new Set()); // Track in-flight like/unlike requests
// On mount: fetch OAuth config + check if user just completed OAuth redirect useEffect(() => {11 unmodified lines // Check if user just completed OAuth redirect const oauthResult = await oauthHandleRedirectIfPresent(); if (oauthResult) { const { accessToken, userInfo } = oauthResult; const { userInfo } = oauthResult; const userData = { name: userInfo.name, preferredUsername: userInfo.preferred_username || userInfo.name, avatarUrl: userInfo.picture, accessToken: accessToken, }; setUser(userData);
47 unmodified lines [likedSpaceIds] );
// Toggle like/unlike with optimistic update const toggleLike = useCallback( async (spaceId) => { if (!user) { // Not logged in -> trigger login login(); return; }
const spaceIdLower = spaceId?.toLowerCase(); if (!spaceIdLower) return;
// Prevent duplicate requests for the same space if (pendingLikes.current.has(spaceIdLower)) return; pendingLikes.current.add(spaceIdLower);
const wasLiked = likedSpaceIds.has(spaceIdLower); const method = wasLiked ? 'DELETE' : 'POST';
// Optimistic update setLikedSpaceIds((prev) => { const next = new Set(prev); if (wasLiked) { next.delete(spaceIdLower); } else { next.add(spaceIdLower); } return next; });
try { const response = await fetch(`${HF_API}/api/spaces/${spaceId}/like`, { method, headers: { Authorization: `Bearer ${user.accessToken}`, }, });
if (!response.ok) { throw new Error(`Like API returned ${response.status}`); } } catch (err) { console.error(`[Auth] Failed to ${wasLiked ? 'unlike' : 'like'} ${spaceId}:`, err); // Revert optimistic update on error setLikedSpaceIds((prev) => { const reverted = new Set(prev); if (wasLiked) { reverted.add(spaceIdLower); } else { reverted.delete(spaceIdLower); } return reverted; }); } finally { pendingLikes.current.delete(spaceIdLower); } /** * Open the HF Space page so the user can like it natively. * HuggingFace intentionally blocks programmatic likes via API tokens * to prevent spam ("To prevent spam usage, it is not possible to like a * repository from a script." — huggingface_hub SDK). * Reading likes works fine; writing requires the native HF session. */ const openSpaceForLike = useCallback( (spaceId) => { if (!spaceId) return; window.open(`${HF_API}/spaces/${spaceId}`, '_blank', 'noopener,noreferrer'); }, [user, likedSpaceIds, login] [] );
/** * Re-fetch user's liked spaces (call after user returns from HF page). */ const refreshLikes = useCallback(async () => { if (!user?.preferredUsername) return; const likes = await fetchUserLikedSpaces(user.preferredUsername); setLikedSpaceIds(likes); console.log(`[Auth] Refreshed likes: ${likes.size} liked spaces`); }, [user]);
return ( <AuthContext.Provider value={{5 unmodified lines login, logout, isSpaceLiked, toggleLike, openSpaceForLike, refreshLikes, }} > {children}1123425 unmodified lines3031323333343536138 unmodified lines175176177178178179180180181182183183184185186187188190189190191192140 unmodified lines33333433533733633733833911 unmodified lines351352353354355355356357358359360357361362359363364365366367368369370371372373374375376377378379380333 unmodified lines714715716701717718719720import { useState, useMemo, useCallback } from 'react';import { useState, useMemo, useCallback, useEffect } from 'react';import { Box, Container,25 unmodified linesimport InstallModal from '../components/InstallModal';
// App Card Componentfunction AppCard({ app, onInstallClick, isLiked, onToggleLike, isLoggedIn }) {function AppCard({ app, onInstallClick, isLiked, onLikeClick, isLoggedIn }) { const isOfficial = app.isOfficial; const isPythonApp = app.extra?.isPythonApp !== false; // Default to true for backwards compatibility const cardData = app.extra?.cardData || {};138 unmodified lines )} </Box> {/* Likes - Interactive */} {/* Likes - Click opens HF Space page to like natively */} <Tooltip title={isLoggedIn ? '' : 'Sign in to like this app'} title={isLoggedIn ? 'Like on Hugging Face' : 'Sign in to like this app'} arrow placement="top" disableHoverListener={isLoggedIn} > <Box component="button" onClick={(e) => { e.preventDefault(); e.stopPropagation(); onToggleLike?.(app.id); onLikeClick?.(app.id); }} sx={{ display: 'flex',140 unmodified linesexport default function Apps() { // Get apps from context (cached globally) const { apps, loading, error } = useApps(); const { user, isLoggedIn, isOAuthAvailable, login, logout, isSpaceLiked, toggleLike } = useAuth(); const { user, isLoggedIn, isOAuthAvailable, login, logout, isSpaceLiked, openSpaceForLike, refreshLikes } = useAuth(); const [searchQuery, setSearchQuery] = useState(''); const [officialOnly, setOfficialOnly] = useState(false); 11 unmodified lines setSelectedApp(null); };
// Handle like click: if logged in, open HF page; if not, prompt login const handleToggleLike = useCallback( const handleLikeClick = useCallback( (spaceId) => { if (!isLoggedIn) { login(); return; } toggleLike(spaceId); openSpaceForLike(spaceId); }, [toggleLike] [isLoggedIn, login, openSpaceForLike] );
// Refresh likes when the tab regains focus (user may have liked on HF) useEffect(() => { if (!isLoggedIn) return; const handleVisibilityChange = () => { if (document.visibilityState === 'visible') { refreshLikes(); } }; document.addEventListener('visibilitychange', handleVisibilityChange); return () => document.removeEventListener('visibilitychange', handleVisibilityChange); }, [isLoggedIn, refreshLikes]);
// Filter apps based on search and official toggle const filteredApps = useMemo(() => { let result = apps;333 unmodified lines app={app} onInstallClick={handleInstallClick} isLiked={isSpaceLiked(app.id)} onToggleLike={handleToggleLike} onLikeClick={handleLikeClick} isLoggedIn={isLoggedIn} /> ))}README.md-2
src/components/InstallModal.jsx+9-4
src/context/AuthContext.jsx+27-63
src/pages/Apps.jsx+27-11