Spaces:
Running
Running
refactor(api): scope dedup per route to surface JS-only same-name apps
Browse filesMove the name-based dedup out of `fetchAppsFromHF` so each route can
apply its own policy on top of a single raw cache:
- `/api/apps` (showcase site) keeps the original global dedup, so
Python forks of `reachy_mini_conversation_app` etc. still collapse
to a single tile.
- `/api/js-apps` (mobile shell) now dedups within the JS subset only,
so a JS Space like `tfrere/emotions` no longer loses a name fight
against an unrelated Python Space (`RemiFabre/emotions`) and
surfaces correctly in the store.
`getApps()` is renamed to `getRawApps()` to make the cache contract
explicit, and `dedupAppsByName` is shared between `dedupGlobalApps`
and `dedupJsApps` so the policies can diverge later without churn.
Co-authored-by: Cursor <cursoragent@cursor.com>
196 unmodified lines19719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722820020123023120220320420520620720820921023821121221321421521621724524621821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128215 unmodified lines29829930026830130230330410 unmodified lines31531631728531831932032132210 unmodified lines3333343353023363373383393403043413423433442 unmodified lines347348349313314315350351352353354355318319356357358359360361362324363364365366212 unmodified lines57958058154358258358458515 unmodified lines6016026035656046056066074 unmodified lines612613614615576577578579616617618619620621622623196 unmodified lines }; });
// Deduplicate by name: forks keep the same repo name (e.g. 4 spaces // named "reachy_mini_conversation_app" from different authors). // Priority: 1) official, 2) oldest (original), 3) most likes as tiebreaker. const deduped = new Map(); for (const app of allApps) { const key = app.name.toLowerCase(); const existing = deduped.get(key); if (!existing) { deduped.set(key, app); continue; } // Official always wins if (app.isOfficial && !existing.isOfficial) { deduped.set(key, app); continue; } if (existing.isOfficial) continue; // Oldest wins (the original is created before its forks) const appDate = app.extra.createdAt ? new Date(app.extra.createdAt).getTime() : Infinity; const existingDate = existing.extra.createdAt ? new Date(existing.extra.createdAt).getTime() : Infinity; if (appDate < existingDate) { deduped.set(key, app); } else if (appDate === existingDate && (app.extra.likes || 0) > (existing.extra.likes || 0)) { deduped.set(key, app); } } const uniqueApps = [...deduped.values()];
console.log(`[Cache] Deduplicated ${allApps.length} → ${uniqueApps.length} apps (removed ${allApps.length - uniqueApps.length} forks with duplicate names)`); console.log(`[Cache] Built ${allApps.length} raw app entries from HF.`);
// Sort: official first, then by likes uniqueApps.sort((a, b) => { // Sort: official first, then by likes. Dedup is route-specific // and applied downstream (see `dedupGlobalApps` and `dedupJsApps`). allApps.sort((a, b) => { if (a.isOfficial !== b.isOfficial) { return a.isOfficial ? -1 : 1; } return (b.extra.likes || 0) - (a.extra.likes || 0); });
return uniqueApps; return allApps; } catch (err) { console.error('[Cache] Error fetching apps:', err); throw err; }}
// Get apps with cachingasync function getApps() {/** * Pick a winner among Spaces sharing the same repo name. Forks * keep the upstream name (e.g. several `reachy_mini_conversation_app` * from different authors); we surface only one in the store to * avoid drowning the original under a dozen near-identical tiles. * * Priority: 1) official, 2) oldest (likely original), 3) most likes * as tiebreaker. */function dedupAppsByName(apps) { const deduped = new Map(); for (const app of apps) { const key = app.name.toLowerCase(); const existing = deduped.get(key); if (!existing) { deduped.set(key, app); continue; } if (app.isOfficial && !existing.isOfficial) { deduped.set(key, app); continue; } if (existing.isOfficial) continue; const appDate = app.extra?.createdAt ? new Date(app.extra.createdAt).getTime() : Infinity; const existingDate = existing.extra?.createdAt ? new Date(existing.extra.createdAt).getTime() : Infinity; if (appDate < existingDate) { deduped.set(key, app); } else if (appDate === existingDate && (app.extra?.likes || 0) > (existing.extra?.likes || 0)) { deduped.set(key, app); } } return [...deduped.values()];}
/** * Dedup applied to the full `/api/apps` payload (Python + JS + others * mixed). Same-name collisions across SDKs collapse here too, by design: * the showcase site favours a clean catalog over completeness, and * SDK-aware variants of the same idea live as separate Spaces only * by accident in practice. */function dedupGlobalApps(apps) { return dedupAppsByName(apps);}
/** * Dedup applied to the `/api/js-apps` route only. We restrict the * comparison to entries already filtered to the JS subset, so a JS * Space (e.g. `tfrere/emotions`) does not lose a name fight against * an unrelated Python Space sharing the same repo name (e.g. * `RemiFabre/emotions`). The mobile shell only sees JS apps anyway, * so confining dedup to that scope is what matches the user model. */function dedupJsApps(jsApps) { return dedupAppsByName(jsApps);}
// Get raw apps with caching. Dedup is NOT applied here - each// route owns its own dedup policy (see `dedupGlobalApps` and// `dedupJsApps`) so they can disagree without paying for two// upstream fetches.async function getRawApps() { const now = Date.now(); // Return cache if valid15 unmodified lines const apps = await fetchAppsFromHF(); appsCache.data = apps; appsCache.lastFetch = now; console.log(`[Cache] Cache updated with ${apps.length} apps`); console.log(`[Cache] Cache updated with ${apps.length} raw entries`); return apps; } catch (err) { // On error, return stale cache if available10 unmodified lines// API endpointapp.get('/api/apps', async (req, res) => { try { const apps = await getApps(); const raw = await getRawApps(); const apps = dedupGlobalApps(raw); res.json({ apps, cached: true,10 unmodified lines// JS apps + LLM-inferred categories// =====================================================================//// `/api/js-apps` is a curated view on top of `/api/apps`:// `/api/js-apps` is a curated view on the JS-only subset:// 1. Filter on the `reachy_mini_js_app` tag (the mobile-embeddable subset).// 2. Dedup name collisions among JS apps only (`dedupJsApps`),// so a JS app does not get knocked out by a same-named Python// Space surfaced through `/api/apps`.// 2. Enrich each entry with `categories` + `categories_source`,// 3. Enrich each entry with `categories` + `categories_source`,// sourced from a persistent dataset cache (see categoryCache.js).//// Categories are inferred lazily by an LLM from each Space's2 unmodified lines// flight; subsequent requests pick them up as the cache fills.
/** * Pull the JS-app subset out of the global apps cache and fold * in cached categories. Pure, synchronous-ish (the only async * call is to the upstream `getApps()` which has its own cache). * Pull the JS-app subset out of the raw apps cache, dedup it * within the JS scope, and fold in cached categories. Pure, * synchronous-ish (the only async call is to `getRawApps()` which * has its own cache). */async function getJsApps() { const apps = await getApps(); const jsApps = apps.filter((a) => { const raw = await getRawApps(); const jsApps = raw.filter((a) => { const tags = a?.extra?.tags; return Array.isArray(tags) && tags.includes(JS_APP_TAG); }); const deduped = dedupJsApps(jsApps);
return jsApps.map((app) => { return deduped.map((app) => { const cached = categoryCache.get(app.id); return { ...app,212 unmodified linesapp.post('/api/refresh', async (req, res) => { try { appsCache.lastFetch = null; // Invalidate cache const apps = await getApps(); const apps = await getRawApps(); res.json({ success: true, count: apps.length }); } catch (err) { res.status(500).json({ error: 'Failed to refresh cache' });15 unmodified linesasync function warmCache() { console.log('[Startup] Pre-warming cache...'); try { const apps = await getApps(); const apps = await getRawApps(); console.log('[Startup] Cache warmed successfully');
// Categorization warm-up: fire the JS-app batch in the4 unmodified lines void (async () => { try { await categoryCache.load(); const jsApps = dedupJsApps( const jsApps = apps.filter((a) => { const tags = a?.extra?.tags; return Array.isArray(tags) && tags.includes(JS_APP_TAG); }); apps.filter((a) => { const tags = a?.extra?.tags; return Array.isArray(tags) && tags.includes(JS_APP_TAG); }), ); console.log( `[Startup] Found ${jsApps.length} JS apps; checking categories...`, );server/index.js+91-50