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 lines19719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824915 unmodified lines26526626726826927027110 unmodified lines28228328428528628728810 unmodified lines2993003013023033043053063072 unmodified lines310311312313314315316317318319320321322323324325326327212 unmodified lines54054154254354454554615 unmodified lines5625635645655665675684 unmodified lines573574575576577578579580581582196 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 winsif (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)`);// Sort: official first, then by likesuniqueApps.sort((a, b) => {if (a.isOfficial !== b.isOfficial) {return a.isOfficial ? -1 : 1;}return (b.extra.likes || 0) - (a.extra.likes || 0);});return uniqueApps;} catch (err) {console.error('[Cache] Error fetching apps:', err);throw err;}}// Get apps with cachingasync function getApps() {const now = Date.now();// Return cache if valid15 unmodified linesconst apps = await fetchAppsFromHF();appsCache.data = apps;appsCache.lastFetch = now;console.log(`[Cache] Cache updated with ${apps.length} apps`);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();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`:// 1. Filter on the `reachy_mini_js_app` tag (the mobile-embeddable subset).// 2. 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).*/async function getJsApps() {const apps = await getApps();const jsApps = apps.filter((a) => {const tags = a?.extra?.tags;return Array.isArray(tags) && tags.includes(JS_APP_TAG);});return jsApps.map((app) => {const cached = categoryCache.get(app.id);return {...app,212 unmodified linesapp.post('/api/refresh', async (req, res) => {try {appsCache.lastFetch = null; // Invalidate cacheconst apps = await getApps();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();console.log('[Startup] Cache warmed successfully');// Categorization warm-up: fire the JS-app batch in the4 unmodified linesvoid (async () => {try {await categoryCache.load();const jsApps = 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...`,);196 unmodified lines19719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128215 unmodified lines29829930030130230330410 unmodified lines31531631731831932032132210 unmodified lines3333343353363373383393403413423433442 unmodified lines347348349350351352353354355356357358359360361362363364365366212 unmodified lines57958058158258358458515 unmodified lines6016026036046056066074 unmodified lines612613614615616617618619620621622623196 unmodified lines};});console.log(`[Cache] Built ${allApps.length} raw app entries from HF.`);// 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 allApps;} catch (err) {console.error('[Cache] Error fetching apps:', err);throw err;}}/*** 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 linesconst apps = await fetchAppsFromHF();appsCache.data = apps;appsCache.lastFetch = now;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 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 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`.// 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 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 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 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 cacheconst 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 getRawApps();console.log('[Startup] Cache warmed successfully');// Categorization warm-up: fire the JS-app batch in the4 unmodified linesvoid (async () => {try {await categoryCache.load();const jsApps = dedupJsApps(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