Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
0.5.6: recognize and restore private backups without rescanning
Browse filesFiles changed (15)
- CHANGELOG.md+7
- README.md+8-2
- VALIDATION.md+10-1
- assets/bootstrap.js+1-1
- assets/calendar.html+1-1
- assets/calendar.js+4-4
- assets/locales.json+16-3
- contrib/collection.py+2
- contrib/config.py+1-1
- contrib/storage.py+14-5
- contrib/ui/events.py+27
- releases/HF-Contrib-v2-0.5.6.zipAdded+3
- tests/check_private_upgrade.cjs+25-1
- tests/preview_private_upgrade.py+3-1
- tests/test_storage.py+74-1
12345# Changelog## 0.5.5 — reuse saved public activity when adding private history- Seed the first private scan from the owner's actual public checkpoint, including the complete event ledger and per-repository heads. Keep public cells/counts visible and animate only incoming activity.123456789101112# Changelog## 0.5.6 — recognize and restore saved private activity- Discover the owner's private backup from the existing year listing, with no extra availability request. Keep public/private file filtering and pruning separate; public opening does not preload private records when a public result exists.- Show Private activity saved and Load saved private activity in EN/FR after opting into private visibility. Replace misleading scan wording for the generic private load action.- Restore an advertised private backup through a read-only path. Preserve complete, partial and interrupted states; never start a scan after a missing/corrupt/slow read. Retain the displayed graph on failure and release the session reservation.- Add cold-session, scope, no-extra-listing, missing/timeout and no-collection regression checks. Verify real bucket reads and desktop/mobile Gradio reload/restore with synthetic UI data. No dependency, OAuth-scope or animation changes.## 0.5.5 — reuse saved public activity when adding private history- Seed the first private scan from the owner's actual public checkpoint, including the complete event ledger and per-repository heads. Keep public cells/counts visible and animate only incoming activity.
14 unmodified lines151617181920215 unmodified lines27282930313233343514 unmodified linesshort_description: Your Hugging Face activity, by day and contribution type.---# HF Contrib · 0.5.5A contribution explorer for your own Hugging Face account. Signed-out visitors have one sign-in button in the welcome screen; the header account action appears only after authentication, for signing out. The server selects the signed-in account. The Space maintainer can also inspect the public activity of another profile. One annual calendar changes with the selected activity family. The annual calendar shows incoming activity as it is collected. Repository stars lead, followed by timeline stars. Each incoming batch reveals its dates from oldest to newest. Choose English or French and a light, dark or system theme. Select a day for its contribution breakdown, timestamps, titles and direct Hub links. Completed results can be exported as an overview PNG with all twelve activity categories.5 unmodified linesThe Publications view includes Daily Papers submissions, authored research papers, published blog articles and social posts. Posts and blog articles share the publication family’s cyan palette and triangular pending marker. Post replies appear in Community with turquoise diamonds; emoji reactions appear in Reactions with coral circles. Export height follows the twelve categories (currently 2800 × 4032 px).## Add private activity to a saved public scan (0.5.5)When **Scan private activity** has no saved private result, it starts from the same owner's saved public event ledger. Public counts and cells remain visible; only incoming contributions animate. An authenticated repository listing discovers private repositories, but already covered public repository histories and completed public timeline sources are reused. An unknown repository or changed visibility still requires its history to be read.For a past year, reuse requires coverage through the year's end. For the current year, coverage must reach the current UTC day. Older coverage keeps the existing incremental update: recent timeline pages with a 48-hour overlap and repository commits back to the saved head. Interrupted, failed or invalidated sources are retried while completed sources remain available. Public coverage never certifies that private history has been scanned, and skipped sources retain their actual coverage timestamps.14 unmodified lines151617181920215 unmodified lines27282930313233343536373839404114 unmodified linesshort_description: Your Hugging Face activity, by day and contribution type.---# HF Contrib · 0.5.6A contribution explorer for your own Hugging Face account. Signed-out visitors have one sign-in button in the welcome screen; the header account action appears only after authentication, for signing out. The server selects the signed-in account. The Space maintainer can also inspect the public activity of another profile. One annual calendar changes with the selected activity family. The annual calendar shows incoming activity as it is collected. Repository stars lead, followed by timeline stars. Each incoming batch reveals its dates from oldest to newest. Choose English or French and a light, dark or system theme. Select a day for its contribution breakdown, timestamps, titles and direct Hub links. Completed results can be exported as an overview PNG with all twelve activity categories.5 unmodified linesThe Publications view includes Daily Papers submissions, authored research papers, published blog articles and social posts. Posts and blog articles share the publication family’s cyan palette and triangular pending marker. Post replies appear in Community with turquoise diamonds; emoji reactions appear in Reactions with coral circles. Export height follows the twelve categories (currently 2800 × 4032 px).## Restore saved private activity (0.5.6)Reopening the app initially restores the public view. If the owner's private backup exists for that year, **Include private** now shows **Private activity saved** and **Load saved private activity**. This action reads the saved result without starting collection; complete, partial and interrupted backups retain their actual state. A missing or unreadable backup keeps the current graph and offers a separate retry/scan instead of silently rescanning.Backup discovery uses the existing year listing: public and private files stay in separate prefixes, and only the existence of the private backup enters the public snapshot. When a public checkpoint exists, discovery does not download private events. No extra availability request or activity API request is added. Existing session caches and local visibility toggles remain unchanged. **Refresh** is still the explicit update action.## Add private activity to a saved public scan (0.5.5)When **Load private activity** has no saved private result, it starts from the same owner's saved public event ledger. Public counts and cells remain visible; only incoming contributions animate. An authenticated repository listing discovers private repositories, but already covered public repository histories and completed public timeline sources are reused. An unknown repository or changed visibility still requires its history to be read.For a past year, reuse requires coverage through the year's end. For the current year, coverage must reach the current UTC day. Older coverage keeps the existing incremental update: recent timeline pages with a 48-hour overlap and repository commits back to the saved head. Interrupted, failed or invalidated sources are retried while completed sources remain available. Public coverage never certifies that private history has been scanned, and skipped sources retain their actual coverage timestamps.
1234# Release validation · 0.5.5## v0.5.5 — public checkpoint reuse for private collection12345678910111213# Release validation · 0.5.6## v0.5.6 — explicit private backup restorationBase revision `4edcc7649ea00c05480b0063bf5277d7ed74376c` (0.5.5).- **207 Python tests and all five Node suites pass.** New cold-session regressions identify an owner's private backup through one year listing, without reading its contents during public restoration. The explicit saved-private action restores complete, partial and cancelled snapshots while the collection entry point is forbidden. Year/profile isolation, unchanged saved bundles, missing/timeout recovery, retained public counts and reservation cleanup pass.- **Real authenticated bucket reads:** owner-authorized CPU probes confirmed existing public/private checkpoints are readable by the deployed reader, then verified the new year-level listing and private-backup flag with both complete and partial results. Probes used the account Job secret, performed no activity collection and made no bucket writes. No private event content or account counts are included in this repository. This does not establish a new production OAuth login test.- **Actual Gradio and production controller, synthetic owner/bucket/activity:** at 1200px/light/English and 390px/dark/French, the first private upgrade preserves the public cell and animates only the incoming private day. After a full browser reload, the public view recognizes the private backup and shows the translated saved-result action. Loading restores exact counts without entering queued/loading collection states; the fixture rejects all activity API calls after the initial save. Private visibility remains local, and no browser errors occur. Both saved-state screenshots were reviewed. Mobile motion checks explicitly keep the fixture's March date within the visible strip because offscreen stars are intentionally skipped.- No additional availability request, dependency, OAuth-scope, hardware or animation change. Gradio/sdk_version remain 6.31.0 and huggingface_hub remains 2.4.0. Existing backups require no migration or rescan. Physical Safari and a fresh end-to-end production OAuth session were not tested. No GPU inference.## v0.5.5 — public checkpoint reuse for private collection
118 unmodified lines119120121122123124125118 unmodified lines}else if(button.dataset.action==='load-private'){if(button.disabled)return;beginLaunch();privatePending=true;renderToolbar();renderYearNavigation();trigger('load_private',{revision:++visibilityRevision,run_id:data.run_id});}else if(['refresh','full-refresh'].includes(button.dataset.action)){if(button.disabled)return;stopReplay();setSyncOptions(false);refreshPending=true;renderToolbar();renderYearNavigation();q('.notice').hidden=true;118 unmodified lines119120121122123124125118 unmodified lines}else if(button.dataset.action==='load-private'){if(button.disabled)return;beginLaunch();privatePending=true;renderToolbar();renderYearNavigation();trigger('load_private',{revision:++visibilityRevision,run_id:data.run_id,restore:data.private_backup_available===true});}else if(['refresh','full-refresh'].includes(button.dataset.action)){if(button.disabled)return;stopReplay();setSyncOptions(false);refreshPending=true;renderToolbar();renderYearNavigation();q('.notice').hidden=true;
6 unmodified lines789101112136 unmodified lines<span id="private-hint" class="private-hint" hidden></span></div><div class="private-setup" hidden><div><strong class="private-setup-title"></strong><p class="private-setup-copy"></p></div><button type="button" class="action load-private" data-action="load-private" data-i18n="Scan private activity" hidden></button><button type="button" class="action private-login" data-action="private-login" data-i18n="Sign in with Hugging Face" hidden></button></div></div></div><div class="unloaded-year" role="status" hidden><strong class="unloaded-title"></strong><p data-i18n="Load this year to see your contributions. Nothing is fetched when you change years."></p></div><p class="year-gesture-hint" data-i18n="Swipe past either edge to change year."></p>6 unmodified lines789101112136 unmodified lines<span id="private-hint" class="private-hint" hidden></span></div><div class="private-setup" hidden><div><strong class="private-setup-title"></strong><p class="private-setup-copy"></p></div><button type="button" class="action load-private" data-action="load-private" data-i18n="Load private activity" hidden></button><button type="button" class="action private-login" data-action="private-login" data-i18n="Sign in with Hugging Face" hidden></button></div></div></div><div class="unloaded-year" role="status" hidden><strong class="unloaded-title"></strong><p data-i18n="Load this year to see your contributions. Nothing is fetched when you change years."></p></div><p class="year-gesture-hint" data-i18n="Swipe past either edge to change year."></p>
316 unmodified lines3173183193203213223231 unmodified line325326327328329330331332333334335316 unmodified linesq('.empty-note').hidden=!authenticated;setText(q('.empty-note'),t('Nothing is collected until you press Load.'));q('.cache-control').hidden=isWelcome();const loaded=!!data.private,on=data.allow_private && (loaded?showPrivate():privateIntent);button.disabled=locked||external||privatePending||refreshPending;button.setAttribute('aria-checked',String(on));const privateKey=loaded?'Show private':'Include private',privateLabel=t(privateKey);1 unmodified lineq('.private-label-full').dataset.i18n=privateKey;setText(q('.private-label-full'),privateLabel);const n=Object.values(data.private_bins||{}).reduce((total,values)=>total+sum(values),0);q('.private-hint').hidden=!loaded&&!on&&!privatePending;setText(q('.private-hint'),privatePending?t('Requesting private activity…'):loaded?t(showPrivate()?'{n} private contributions included':'{n} private contributions hidden',{n:fmt.format(n)}):t(on?'Private not loaded':'Public only'));q('.private-setup').hidden=idle||!on||loaded||busy||privatePending;setText(q('.private-setup-title'),data.allow_private?t('Private activity for @{username}',{username:data.viewer||data.username}):t(!data.viewer?'Your private activity stays yours':'Use your own profile'));setText(q('.private-setup-copy'),t(data.allow_private?'Scan the selected year for your own profile, including private repositories.':!data.viewer?'Sign in, then choose when to scan your private repositories. Nothing is fetched by this switch.':'Private activity is only available on your own profile. Enter your username above to scan it.'));const load=q('.load-private');setText(load,t(idle?'Scan public + private':'Scan private activity'));load.hidden=idle||!on||!data.allow_private||loaded;load.disabled=locked||privatePending||refreshPending;q('.private-login').hidden=!on||!!data.viewer||!!data.allow_private||props.oauth_enabled===false;q('.refresh-activity').disabled=locked||refreshPending||privatePending;q('.refresh-activity').title=t('Fetch updated activity for this year from Hugging Face.');316 unmodified lines3173183193203213223231 unmodified line325326327328329330331332333334335316 unmodified linesq('.empty-note').hidden=!authenticated;setText(q('.empty-note'),t('Nothing is collected until you press Load.'));q('.cache-control').hidden=isWelcome();const loaded=!!data.private,savedPrivate=data.private_backup_available===true,on=data.allow_private && (loaded?showPrivate():privateIntent);button.disabled=locked||external||privatePending||refreshPending;button.setAttribute('aria-checked',String(on));const privateKey=loaded?'Show private':'Include private',privateLabel=t(privateKey);1 unmodified lineq('.private-label-full').dataset.i18n=privateKey;setText(q('.private-label-full'),privateLabel);const n=Object.values(data.private_bins||{}).reduce((total,values)=>total+sum(values),0);q('.private-hint').hidden=!loaded&&!on&&!privatePending;setText(q('.private-hint'),privatePending?t('Requesting private activity…'):loaded?t(showPrivate()?'{n} private contributions included':'{n} private contributions hidden',{n:fmt.format(n)}):t(on?(savedPrivate?'Private activity saved':'Private not loaded'):'Public only'));q('.private-setup').hidden=idle||!on||loaded||busy||privatePending;setText(q('.private-setup-title'),data.allow_private?t('Private activity for @{username}',{username:data.viewer||data.username}):t(!data.viewer?'Your private activity stays yours':'Use your own profile'));setText(q('.private-setup-copy'),t(data.allow_private?(savedPrivate?'Your private activity is saved in your bucket. Load it without starting a new scan.':'Load a saved private result, or scan this year if no backup is available.'):!data.viewer?'Sign in, then choose when to scan your private repositories. Nothing is fetched by this switch.':'Private activity is only available on your own profile. Enter your username above to scan it.'));const load=q('.load-private');setText(load,t(idle?'Load public + private':savedPrivate?'Load saved private activity':'Load private activity'));load.hidden=idle||!on||!data.allow_private||loaded;load.disabled=locked||privatePending||refreshPending;q('.private-login').hidden=!on||!!data.viewer||!!data.allow_private||props.oauth_enabled===false;q('.refresh-activity').disabled=locked||refreshPending||privatePending;q('.refresh-activity').title=t('Fetch updated activity for this year from Hugging Face.');
199 unmodified lines200201202203204205206166 unmodified lines37337437537637737837918 unmodified lines398399400401402403199 unmodified lines"Refresh requested. Your current view stays available.": "Actualisation demandée. Votre vue actuelle reste disponible.","This year is cached. Use Refresh only to collect newer activity from Hugging Face.": "Cette année est en cache. Actualisez uniquement pour récupérer les nouvelles contributions depuis Hugging Face.","Refresh requested.": "Actualisation demandée.","Load private activity": "Charger le privé","Not loaded · use Load private activity": "Non chargé · utilisez « Charger le privé »","Hugging Face rate limit: waiting for the allowed retry time. You can stop this collection.": "Quota Hugging Face atteint : attente du délai de reprise autorisé. Vous pouvez arrêter la collecte.","Hugging Face rate limit reached (HTTP 429). Keep this result and refresh later.": "Quota Hugging Face atteint (HTTP 429). Conservez ce résultat et actualisez plus tard.",166 unmodified lines"An activity record has incomplete data.": "Une activité contient des données incomplètes.","Some data could not be checked for this day.": "Certaines données n’ont pas pu être vérifiées pour ce jour.","Reading saved activity timed out. You can still load this year.": "La lecture des activités sauvegardées a dépassé le délai. Vous pouvez quand même charger cette année.","The saved-year listing could not finish. Please retry.": "La liste des sauvegardes n’a pas pu être chargée. Réessayez."},"en": {"Include private": "Include private",18 unmodified lines"Load public + private": "Load public + private","Request sent…": "Request sent…","Waiting…": "Waiting…","Collecting activity…": "Collecting activity…"}}199 unmodified lines200201202203204205206166 unmodified lines37337437537637737837938038138238338438518 unmodified lines404405406407408409410411412413414415416199 unmodified lines"Refresh requested. Your current view stays available.": "Actualisation demandée. Votre vue actuelle reste disponible.","This year is cached. Use Refresh only to collect newer activity from Hugging Face.": "Cette année est en cache. Actualisez uniquement pour récupérer les nouvelles contributions depuis Hugging Face.","Refresh requested.": "Actualisation demandée.","Load private activity": "Charger l’activité privée","Not loaded · use Load private activity": "Non chargé · utilisez « Charger le privé »","Hugging Face rate limit: waiting for the allowed retry time. You can stop this collection.": "Quota Hugging Face atteint : attente du délai de reprise autorisé. Vous pouvez arrêter la collecte.","Hugging Face rate limit reached (HTTP 429). Keep this result and refresh later.": "Quota Hugging Face atteint (HTTP 429). Conservez ce résultat et actualisez plus tard.",166 unmodified lines"An activity record has incomplete data.": "Une activité contient des données incomplètes.","Some data could not be checked for this day.": "Certaines données n’ont pas pu être vérifiées pour ce jour.","Reading saved activity timed out. You can still load this year.": "La lecture des activités sauvegardées a dépassé le délai. Vous pouvez quand même charger cette année.","The saved-year listing could not finish. Please retry.": "La liste des sauvegardes n’a pas pu être chargée. Réessayez.","Load saved private activity": "Charger le privé sauvegardé","Private activity saved": "Activité privée sauvegardée","Your private activity is saved in your bucket. Load it without starting a new scan.": "Votre activité privée est sauvegardée dans votre bucket. Chargez-la sans lancer de nouveau scan.","Load a saved private result, or scan this year if no backup is available.": "Chargez une sauvegarde privée, ou scannez cette année si aucune sauvegarde n’est disponible.","No saved private activity was found. You can start a private scan.": "Aucune sauvegarde privée n’a été trouvée. Vous pouvez lancer un scan privé.","Saved private activity could not be loaded. Your displayed result is retained; please retry.": "L’activité privée sauvegardée n’a pas pu être chargée. Le résultat affiché est conservé ; réessayez."},"en": {"Include private": "Include private",18 unmodified lines"Load public + private": "Load public + private","Request sent…": "Request sent…","Waiting…": "Waiting…","Collecting activity…": "Collecting activity…","Load private activity": "Load private activity","Load saved private activity": "Load saved private activity","Private activity saved": "Private activity saved","Your private activity is saved in your bucket. Load it without starting a new scan.": "Your private activity is saved in your bucket. Load it without starting a new scan.","Load a saved private result, or scan this year if no backup is available.": "Load a saved private result, or scan this year if no backup is available.","No saved private activity was found. You can start a private scan.": "No saved private activity was found. You can start a private scan.","Saved private activity could not be loaded. Your displayed result is retained; please retry.": "Saved private activity could not be loaded. Your displayed result is retained; please retry."}}
89 unmodified lines90919293949573 unmodified lines16917017117217317489 unmodified linesaccumulator.finish(saved['phase'] == 'cancelled')value = storage.decorate_restored(accumulator.copy(), request)value.update(cached=True, cache_source='bucket', fetched_at=saved['saved_at'], storage_status='saved', storage_bucket=store.bucket_id)with _lock:_previous[session] = deepcopy(value)yield value73 unmodified linestry:bucket_id = store.save(checkpoint)result.update(storage_status='saved', storage_bucket=bucket_id, storage_notice='')except Exception as error:result.update(storage_status='error', storage_notice=str(error) if isinstance(error, HubError) else'Your scan is available, but private backup failed. Sign in again or retry the backup.')89 unmodified lines9091929394959673 unmodified lines17017117217317417517689 unmodified linesaccumulator.finish(saved['phase'] == 'cancelled')value = storage.decorate_restored(accumulator.copy(), request)value.update(cached=True, cache_source='bucket', fetched_at=saved['saved_at'], storage_status='saved', storage_bucket=store.bucket_id)value['private_backup_available'] = getattr(store, 'private_backup_available', False)with _lock:_previous[session] = deepcopy(value)yield value73 unmodified linestry:bucket_id = store.save(checkpoint)result.update(storage_status='saved', storage_bucket=bucket_id, storage_notice='')result['private_backup_available'] = request.private or getattr(store, 'private_backup_available', False)except Exception as error:result.update(storage_status='error', storage_notice=str(error) if isinstance(error, HubError) else'Your scan is available, but private backup failed. Sign in again or retry the backup.')
123456from datetime import datetime, timezoneVERSION = "0.5.5"FIRST_YEAR = 2022DATA_VERSION = 1SOURCE_VERSIONS = {s: 1 for s in ("repositories", "community", "likes", "upvotes", "papers", "blogs", "posts")}123456from datetime import datetime, timezoneVERSION = "0.5.6"FIRST_YEAR = 2022DATA_VERSION = 1SOURCE_VERSIONS = {s: 1 for s in ("repositories", "community", "likes", "upvotes", "papers", "blogs", "posts")}
115 unmodified lines11611711811912012112246 unmodified lines1691701711721731741751761771782 unmodified lines181182183184185186103 unmodified lines290291292293294295296297298299300301302303115 unmodified linestarget = validate_username(request.username).lower()if request.private and target != request.owner.lower():raise ValueError('Private checkpoints belong to their owner')self.prefix = f'v1/{request.owner_id}/{target}/{request.year}/{"private" if request.private else "public"}/'self._api_override = apiself.api = api or HfApi(token=request.storage_token)self._read_deadline = None46 unmodified linesdef files(self):if self._api_override is not None:items = self.api.list_bucket_tree(self.bucket_id, prefix=self.prefix, recursive=True, token=self.token)else:root = 'https://huggingface.co/api/buckets/' + self.bucket_id + '/tree/'url, items, visited = root + quote(self.prefix, safe=''), [], set()while url:if not url.startswith(root) or url in visited or len(visited) >= 16:raise HubError('The saved-year listing could not finish. Please retry.')2 unmodified linesif not isinstance(page, list):raise ValueError('Invalid bucket listing')items.extend(SimpleNamespace(path=f['path'], size=f['size']) for f in page if f.get('type') == 'file')return sorted((f for f in items if f.path.startswith(self.prefix) and FILE_NAME.fullmatch(f.path[len(self.prefix):])),key=lambda f: f.path, reverse=True)103 unmodified linesif not storage_enabled(request):return Nonefrom .aggregation import Accumulatorsaved = BucketStore(request).load()if saved is None:return Noneacc = Accumulator(request, saved)acc.finish(saved['phase'] == 'cancelled')result = decorate_restored(acc.copy(), request)result.update(cached=True, cache_source='bucket', fetched_at=saved['saved_at'], storage_status='saved',storage_bucket=validate_username(request.owner) + '/' + BUCKET_NAME)result['coverage_until'] = min((v.get('covered_until', '') for v in acc.sync.values()), default='')return result115 unmodified lines11611711811912012112212312446 unmodified lines1711721731741751761771781791802 unmodified lines183184185186187188189190191192193103 unmodified lines297298299300301302303304305306307308309310311312115 unmodified linestarget = validate_username(request.username).lower()if request.private and target != request.owner.lower():raise ValueError('Private checkpoints belong to their owner')self.listing_prefix = f'v1/{request.owner_id}/{target}/{request.year}/'self.prefix = self.listing_prefix + ('private/' if request.private else 'public/')self.private_backup_available = Falseself._api_override = apiself.api = api or HfApi(token=request.storage_token)self._read_deadline = None46 unmodified linesdef files(self):if self._api_override is not None:items = list(self.api.list_bucket_tree(self.bucket_id, prefix=self.listing_prefix, recursive=True, token=self.token))else:root = 'https://huggingface.co/api/buckets/' + self.bucket_id + '/tree/'url, items, visited = root + quote(self.listing_prefix, safe=''), [], set()while url:if not url.startswith(root) or url in visited or len(visited) >= 16:raise HubError('The saved-year listing could not finish. Please retry.')2 unmodified linesif not isinstance(page, list):raise ValueError('Invalid bucket listing')items.extend(SimpleNamespace(path=f['path'], size=f['size']) for f in page if f.get('type') == 'file')# One year listing discovers both scopes; no extra request or private# event download is needed to offer restoration in the public view.private_prefix = self.listing_prefix + 'private/'self.private_backup_available = self.request.username.lower() == self.request.owner.lower() and any(f.path.startswith(private_prefix) and FILE_NAME.fullmatch(f.path[len(private_prefix):]) for f in items)return sorted((f for f in items if f.path.startswith(self.prefix) and FILE_NAME.fullmatch(f.path[len(self.prefix):])),key=lambda f: f.path, reverse=True)103 unmodified linesif not storage_enabled(request):return Nonefrom .aggregation import Accumulatorstore = BucketStore(request)saved = store.load()if saved is None:return Noneacc = Accumulator(request, saved)acc.finish(saved['phase'] == 'cancelled')result = decorate_restored(acc.copy(), request)result.update(cached=True, cache_source='bucket', fetched_at=saved['saved_at'], storage_status='saved',storage_bucket=validate_username(request.owner) + '/' + BUCKET_NAME,private_backup_available=store.private_backup_available)result['coverage_until'] = min((v.get('covered_until', '') for v in acc.sync.values()), default='')return result
342 unmodified lines343344345346347348342 unmodified linesif prefs.collecting(session) or stale or (current and current["phase"] in {"queued", "loading"}) or not prefs.accept_visibility_request(session, payload.get("revision")):yield (gr.skip(),) * 5returnyield from toggle_private(username, year, True, False, session, request, profile, oauth_token)342 unmodified lines343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375342 unmodified linesif prefs.collecting(session) or stale or (current and current["phase"] in {"queued", "loading"}) or not prefs.accept_visibility_request(session, payload.get("revision")):yield (gr.skip(),) * 5returnif payload.get('restore') is True:# A saved-result button is read-only, even if its backup disappeared or# is interrupted. An update remains a separate explicit action.if not current or current['year'] != year or current['username'].lower() != username.strip().lower():yield (gr.skip(),) * 5returnticket = prefs.begin_collection(session, profile.username)if ticket is None:yield (gr.skip(),) * 5returntry:saved = prefs.cached(session, username, int(year), True, True)if saved is None:saved = storage.saved_snapshot(storage_request(username, year, True, profile, oauth_token))if saved is not None:yield ui_result(saved, session, profile, oauth_token)else:current.update(private_backup_available=False, revision=current['revision']+1,notice='No saved private activity was found. You can start a private scan.')yield ui_result(current, session, profile, oauth_token)except Exception as error:current.update(revision=current['revision']+1, notice=str(error) if isinstance(error, HubError) else'Saved private activity could not be loaded. Your displayed result is retained; please retry.')yield ui_result(current, session, profile, oauth_token)finally:prefs.end_collection(session, ticket)returnyield from toggle_private(username, year, True, False, session, request, profile, oauth_token)
123version https://git-lfs.github.com/spec/v1oid sha256:530b610517cc3044a104983e2e01bc9e743bff24b344fd4191845f66da072a48size 29140029 unmodified lines3031323334355 unmodified lines4142434445464729 unmodified linesawait page.locator('[data-action=load-private]').click();await page.waitForFunction(()=>document.querySelector('.scan-status')?.dataset.state==='loading');assert.equal(await page.locator('.total').getAttribute('data-value'),'1','public total remains while private history loads');await page.waitForFunction(()=>document.querySelector('.total')?.dataset.value==='2');await page.waitForFunction(()=>document.querySelector('.scan-status')?.dataset.state==='complete');await page.waitForFunction(()=>document.querySelector('.main-calendar .cell[data-day="69"]')?.dataset.count==='1');5 unmodified linesassert.equal(await page.locator('.total').getAttribute('data-value'),'1');await page.locator('[data-action=private]').click();assert.equal(await page.locator('.total').getAttribute('data-value'),'2');assert.deepEqual(errors,[]);console.log(JSON.stringify({width,minimumPublic:probe.minimumPublic,starDays:probe.stars,total:2,errors}));}finally{await browser.close();}})().catch(error=>{console.error(error);process.exitCode=1;});29 unmodified lines303132333435363738395 unmodified lines45464748495051525354555657585960616263646566676869707129 unmodified linesawait page.locator('[data-action=load-private]').click();await page.waitForFunction(()=>document.querySelector('.scan-status')?.dataset.state==='loading');assert.equal(await page.locator('.total').getAttribute('data-value'),'1','public total remains while private history loads');await page.locator('.main-calendar .cell[data-day="69"]').evaluate(cell=>{const scroll=cell.closest('.calendar-scroll'),rect=cell.getBoundingClientRect(),view=scroll.getBoundingClientRect();scroll.scrollLeft+=rect.left-view.left-view.width/2;});await page.waitForFunction(()=>document.querySelector('.total')?.dataset.value==='2');await page.waitForFunction(()=>document.querySelector('.scan-status')?.dataset.state==='complete');await page.waitForFunction(()=>document.querySelector('.main-calendar .cell[data-day="69"]')?.dataset.count==='1');5 unmodified linesassert.equal(await page.locator('.total').getAttribute('data-value'),'1');await page.locator('[data-action=private]').click();assert.equal(await page.locator('.total').getAttribute('data-value'),'2');// Reload creates a cold Gradio session. The fixture now rejects activity API calls.await page.reload({waitUntil:'domcontentloaded'});await page.waitForFunction(()=>document.querySelector('.total')?.dataset.value==='1');await page.locator('[data-language='+(width<600?'fr':'en')+']').click();await page.locator('[data-action=private]').click();assert.equal(await page.locator('[data-action=load-private]').innerText(),width<600?'Charger le privé sauvegardé':'Load saved private activity');assert.equal(await page.locator('.private-hint').innerText(),width<600?'Activité privée sauvegardée':'Private activity saved');const path=require('path'),output=path.resolve(__dirname,'../dist/private-restore');require('fs').mkdirSync(output,{recursive:true});await page.screenshot({path:path.join(output,'saved-'+width+'.png')});await page.evaluate(()=>{window.restoreStates=[];new MutationObserver(()=>restoreStates.push(document.querySelector('.scan-status')?.dataset.state)).observe(document.querySelector('.scan-status'),{attributes:true});});await page.locator('[data-action=load-private]').click();await page.waitForFunction(()=>document.querySelector('.total')?.dataset.value==='2');assert.equal(await page.locator('[data-action=load-private]').isVisible(),false);assert.equal(await page.locator('.scan-status').getAttribute('data-state'),'complete');assert(!(await page.evaluate(()=>restoreStates)).some(state=>['queued','loading'].includes(state)),'restoration must not enter collection');await page.locator('[data-action=private]:not(:disabled)').click();assert.equal(await page.locator('.total').getAttribute('data-value'),'1');assert.deepEqual(errors,[]);console.log(JSON.stringify({width,minimumPublic:probe.minimumPublic,starDays:probe.stars,total:2,coldPrivateRestore:true,errors}));}finally{await browser.close();}})().catch(error=>{console.error(error);process.exitCode=1;});
24 unmodified lines25262728293031323324 unmodified linesif __name__ == '__main__':patches = MonkeyPatch()patches.setattr(storage.BucketStore, 'read_bytes', lambda self, item: self.api.data[item.path])_, _, calls = upgrade_setup(patches)get = repositories.HubClient.getdef delayed_private(self, path, params=None):if '/fffiloni/secret/commits/' in path:time.sleep(1.2)return get(self, path, params)24 unmodified lines252627282930313233343524 unmodified linesif __name__ == '__main__':patches = MonkeyPatch()patches.setattr(storage.BucketStore, 'read_bytes', lambda self, item: self.api.data[item.path])api, _, calls = upgrade_setup(patches)get = repositories.HubClient.getdef delayed_private(self, path, params=None):if any('/private/' in name for name in api.data):raise AssertionError('A saved private result must restore without activity API calls')if '/fffiloni/secret/commits/' in path:time.sleep(1.2)return get(self, path, params)
360 unmodified lines361362363364365366367272 unmodified lines640641642360 unmodified linesassert 0 < req.extensions['timeout']['read'] <= 4if '/tree/' not in req.url.path:return httpx.Response(200, json={'private': True})assert req.url.path.split('/tree/')[1] == store.prefixif 'cursor' not in req.url.params:assert req.url.params['recursive'] == 'true'return httpx.Response(200, json=[{'type':'directory', 'path':store.prefix}],272 unmodified linesassert '/api/spaces/fffiloni/app/commits/main' not in callsfinally:ui.cleanup_ui(session)360 unmodified lines361362363364365366367272 unmodified lines640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715360 unmodified linesassert 0 < req.extensions['timeout']['read'] <= 4if '/tree/' not in req.url.path:return httpx.Response(200, json={'private': True})assert req.url.path.split('/tree/')[1] == store.listing_prefixif 'cursor' not in req.url.params:assert req.url.params['recursive'] == 'true'return httpx.Response(200, json=[{'type':'directory', 'path':store.prefix}],272 unmodified linesassert '/api/spaces/fffiloni/app/commits/main' not in callsfinally:ui.cleanup_ui(session)@pytest.mark.parametrize('phase', ['complete', 'partial', 'cancelled'])def test_cold_session_discovers_and_restores_private_backup_without_collection(monkeypatch, phase):import gradio as grfrom contrib.ui import events as uiapi, _, _ = upgrade_setup(monkeypatch)private = bundle(request(private=True), [event(), event(identity='private', private=True)])private['phase'] = phaseif phase != 'complete': private['sources']['posts']['status'] = phasestorage.BucketStore(request(private=True)).save(private)profile = gr.OAuthProfile(dict(sub=OWNER_ID,preferred_username='fffiloni',name='Fixture',profile='',picture=''))token = SimpleNamespace(token='synthetic-owner-token')session = 'cold-private-'+phasereq = gr.Request(session_hash=session)reads, listings = [], []def read(self, item): reads.append(item.path); return self.api.data[item.path]original = api.list_bucket_treedef listing(*args, **kwargs): listings.append(kwargs['prefix']); return original(*args, **kwargs)monkeypatch.setattr(storage.BucketStore, 'read_bytes', read)monkeypatch.setattr(api, 'list_bucket_tree', listing)monkeypatch.setattr(collection, 'stream', lambda *args: (_ for _ in ()).throw(AssertionError('Restoration must never collect')))try:initial = ui.hydrate('fffiloni',2026,req,profile,token)[3]assert initial['private_backup_available'] and not initial['private']assert not any('/private/' in path for path in reads), 'public opening only discovers metadata'assert len(listings) == 1 and listings[0].endswith('/2026/'), 'no extra availability request'evt = gr.EventData(None,dict(run_id=initial['run_id'],revision=1,restore=True))values = list(ui.load_private_event('fffiloni',2026,evt,req,profile,token))assert len(values) == 1result = values[0][0]assert result['phase'] == phase and result['cached'] and result['cache_source'] == 'bucket'assert result['private'] and result['show_private'] and result['storage_status'] == 'saved'assert sum(result['bins']['space.commit']) == 2 and sum(result['private_bins']['space.commit']) == 1assert private == storage.BucketStore(request(private=True)).load(), 'restoration never rewrites the backup'finally: ui.cleanup_ui(session)@pytest.mark.parametrize('failure', ['missing','timeout'])def test_saved_private_restore_failure_retains_public_without_starting_scan(monkeypatch, failure):import gradio as grimport httpxfrom contrib.ui import events as ui, preferences as prefsapi, _, _ = upgrade_setup(monkeypatch)storage.BucketStore(request(private=True)).save(bundle(request(private=True)))profile = gr.OAuthProfile(dict(sub=OWNER_ID,preferred_username='fffiloni',name='Fixture',profile='',picture=''))token = SimpleNamespace(token='synthetic-owner-token')session = 'private-restore-'+failure;req = gr.Request(session_hash=session)try:initial = ui.hydrate('fffiloni',2026,req,profile,token)[3]assert initial['private_backup_available']if failure == 'missing': api.data = {k:v for k,v in api.data.items() if '/private/' not in k}else:def timeout(query): raise httpx.ReadTimeout('Synthetic timeout')monkeypatch.setattr(storage,'saved_snapshot',timeout)monkeypatch.setattr(collection,'stream',lambda *args: (_ for _ in ()).throw(AssertionError('Unexpected scan')))evt = gr.EventData(None,dict(run_id=initial['run_id'],revision=1,restore=True))result = list(ui.load_private_event('fffiloni',2026,evt,req,profile,token))[-1][0]assert not result['private'] and result['bins'] == initial['bins'] and result['notice']assert not prefs.collecting(session)if failure == 'missing': assert not result['private_backup_available']finally: ui.cleanup_ui(session)def test_private_presence_is_scoped_to_the_owner_and_selected_year(monkeypatch):_, _, _ = upgrade_setup(monkeypatch)storage.BucketStore(request(private=True)).save(bundle(request(private=True)))assert storage.saved_snapshot(request())['private_backup_available']storage.BucketStore(request(2025)).save(bundle(request(2025),[]))assert not storage.saved_snapshot(request(2025))['private_backup_available']external = request();external.username = 'another-profile'storage.BucketStore(external).save(bundle(external,[]))assert not storage.saved_snapshot(external)['private_backup_available']
CHANGELOG.md+7
README.md+8-2
VALIDATION.md+10-1
assets/bootstrap.js+1-1
assets/calendar.html+1-1
assets/calendar.js+4-4
assets/locales.json+16-3
contrib/collection.py+2
contrib/config.py+1-1
contrib/storage.py+14-5
contrib/ui/events.py+27
releases/HF-Contrib-v2-0.5.6.zipAdded+3
tests/check_private_upgrade.cjs+25-1
tests/preview_private_upgrade.py+3-1
tests/test_storage.py+74-1