Skip to content

feat(ui): add stats page - #1322

Open
CodedNil wants to merge 1 commit into
sonorahq:mainfrom
CodedNil:stats
Open

CodedNil wants to merge 1 commit into
sonorahq:mainfrom
CodedNil:stats

Conversation

@CodedNil

@CodedNil CodedNil commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

For #1168 though I started working on this before that issue was created, as it is now being worked on officially this is probably redundant so feel free to ignore this but thought I'd post it in case there's ideas or design you'd like to take inspiration from.

Adds a new stats page, currently supporting local (though not well because local history is only 500 songs back so if this is to be more useful for that local history would need a change, happy to do that if you want?), spotify and last.fm
It's a modular design built on widgets due to every provider having different apis providing very different data, this tries to support any data in the best way viable, so it is a good foundation for supporting other providers and scrobblers too in future but each needs a lot of bespoke code and searching through api docs (or probing for spotify....)

Has a listening window picker for the time period, this is heavily restricted by which provider, most beautifully data rich for local.
Listening style with spotify wrapped type profiles it gives you, up to 4, like Loyalist if you listen heavily to a few core songs.
Top artists, songs, albums, songwriters, producers.
Release years, tempo.
Top genres, moods, tags.
Listening clock and milestones.

The design language needs more work, I tried to make it pretty but there is still a lot that could be done, the focus was on making it data rich.
If you do want to go with this PR I'm happy to refine the code and design further as requested. Understand if you don't want it though, hope is still comes in use a bit.
It could potentially even be merged with the history page to simplify the app? If the local section of the stats included the full history table.

These screenshots make it feel more disorganised than it actually is... It's quite tidy in app.

image image image image image image image

@sonora-buddy sonora-buddy Bot added ui rendering, layout, theming, icons, fonts, the window itself spotify the Spotify backend, its library, search and sign-in icons the icon packs library playlists, albums, artists, history, pins and the browsing screens labels Nov 8, 2026
@coderabbitai

coderabbitai Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review
Summary

Added a stats page for Spotify, Last.fm, and local listening history, with time-window controls, rankings, charts, listening-style insights, milestones, and a listening clock. Added statistics APIs and state management, navigation, and reusable UI components to support the page.

The pull request adds a statistics page for Spotify, Last.fm, and recorded plays. It introduces shared statistics types, provider and scrobble retrieval, and state for source selection and cached results. It also adds navigation, refresh handling, timeline controls, ranked sections, charts, localization, and supporting UI components.

Possibly related issues

  • sonorahq/sonora#1168: Requests top tracks and artists, listening time, and selectable ranges, which match the statistics page, rankings, and time-window controls added here.
Merge Risk: Moderate · previous review f2e70

Local all-time statistics can omit older plays, and reconnecting Last.fm can show the previous account’s data. Resolve these issues before merging.

Security architecture risk: Low · up to f2e70

Changing a linked account can leave the previous account’s statistics visible or mixed with the replacement account’s data in the same app. The identified exposure is local and limited; the inspected requests use existing services and do not introduce a remote-control interface.

Retained concerns

  • Low · security · inferred: Statistics state is scoped to a scrobbler service and period rather than the linked account. Relinking another Last.fm account without changing the provider session can reuse the previous account’s rankings during the five-minute freshness window and retain its milestones and density beyond that window. Pending requests can also complete after unlinking without checking current account identity. This creates a local account-ownership and privacy failure, not demonstrated access to private profiles or another device.
Security review details

Security Blast Radius

  • inferred — The account-isolation concern affects statistics retained in one running app when a linked scrobbler account changes without a provider session change. The inspected Last.fm methods read public-profile information, limiting confidentiality impact; no cross-device or cross-tenant compromise was established.

Security Findings and Attack Paths

  • inferred — After account A’s statistics load, a user can unlink A and link B in the same app. Settings notifications do not invalidate fresh or loading statistics, so returning to the screen can show A’s cached rankings. Later B loads can inherit A’s retained milestones and density. This requires local interaction with the running app; it is not a demonstrated remote attack.

Trust Boundaries and Controls

  • observed — New scrobbler loads require a linked account and a registered service supporting dated statistics. Last.fm and Libre.fm destinations are fixed service endpoints. Provider session changes explicitly clear statistics state, and recorded reads retain a parameterized provider/profile scope. These controls constrain exposure but do not invalidate scrobbler caches on account replacement.

Resilience and Maintainability Implications

  • observed — Catalogue matching limits candidates to ten entries per ranking category and six concurrent requests. Date-driven scrobbler requests are debounced, and recorded enrichment caps descriptor and portrait candidates. These bound ordinary enrichment work but do not establish account isolation.

Hardening Proposals

  • proposed — Scope cached windows and whole-account history to scrobbler identity. On unlink or replacement, clear account-derived state, cancel associated work, and reject completions from an obsolete account generation.
  • proposed — Make the cross-provider catalogue-enrichment behavior explicit to users and confirm whether it should be optional under the product’s privacy expectations.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Comment thread crates/state/src/stats.rs Resolved
Comment thread crates/state/src/stats.rs Resolved
Comment thread crates/ui/src/card.rs Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick comments: 1

crates/state/src/stats.rs: 1

513-514: Trivial · Functional Correctness · Low value

Provider portrait lookups run in a nondeterministic order.

collect::<HashSet<_>>().into_iter().collect() removes duplicate IDs. It also shuffles their order. The batches of 25 therefore group IDs differently on each load. Rankings are not affected. The portraits for the top-ranked credits can arrive after those for lower ranks.

Deduplicate in rank order instead. This keeps the top ranks in the first batch, so the first cards get portraits first.

Proposed fix

-                            .collect::<HashSet<_>>()
-                            .into_iter()
-                            .collect()
+                            .fold(
+                                (Vec::new(), HashSet::new()),
+                                |(mut ordered, mut seen), id| {
+                                    if seen.insert(id.clone()) {
+                                        ordered.push(id);
+                                    }
+                                    (ordered, seen)
+                                },
+                            )
+                            .0

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (2)

Minor · Constrain the peak_era windows to end at the last year with data. · mod.rs:375-378

crates/views/src/screens/stats/mod.rs:375-378
Minor · Functional Correctness · Quick win

Constrain the peak_era windows to end at the last year with data.

peak_era tries every start year from first to last. A window that starts near last extends past last and can hold the same songs as an earlier window. max_by_key returns the last maximum, so it picks that overhanging window.

Example: songs only from 2025 and 2026. Starts 2022 to 2025 all hold both years. The function picks 2025 and returns 2025–2029. The era badge then shows future years.

Limit the start years so that every window ends at or before last.

Proposed fix

-    let start = (first..=last.max(first))
+    let latest = last - ERA + 1;
+    let start = (first.min(latest)..=latest)
         .max_by_key(|start| held(*start))
         .filter(|start| held(*start) > 0)?;
Minor · Restore the account milestones when select reuses a cached scrobbler window. · stats.rs:358-364

crates/state/src/stats.rs:358-364
Minor · Functional Correctness · Quick win

Restore the account milestones when select reuses a cached scrobbler window.

This finding is outside the lines changed in the latest commit. It still affects the new Last.fm view.

load_scrobbler caches the window at lines 653-658. That insert uses data.milestones = this.log.scrobbled_milestones.clone() from line 631. The account history task usually finishes after the rankings. At insert time the log can still be empty. The history completion at lines 609-615 updates this.data only. It does not update the cached window.

Trigger:

  1. The user opens the Last.fm tab.
  2. The user switches to Local.
  3. The user switches back to Last.fm within FRESH (300 s).

select takes the kept branch. It sets self.data = data.clone(). That clone has empty milestones. No refresh runs. ensure also treats the window as current. The Milestones section stays empty until the window expires or the user refreshes.

Reapply the log milestones in the cached branch.

🐛 Proposed fix

             self.data = data.clone();
+            if matches!(self.source, StatsSource::Scrobbler(_)) {
+                // The window may have been cached before the account history arrived.
+                self.data.milestones = self.log.scrobbled_milestones.clone();
+            }
             self.loaded = Some((self.source, self.period, *at));

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Comment thread crates/state/src/stats.rs Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (3)

Major · Retain recorded plays for local all-time stats · history.rs:174-182

crates/state/src/history.rs:174-182
Major · Functional Correctness · Quick win

Retain recorded plays for local all-time stats

After 500 recorded plays, Store::prune deletes older plays. Local “All time” statistics then omit those plays, even though recorded() has no read limit.

Retain future plays for stats while keeping the history screen capped and preserving clear-history behavior. Plays already deleted cannot be recovered from this store.

Major · Reset scrobbler stats when the linked account changes · stats.rs:205-230

crates/state/src/stats.rs:205-230
Major · Functional Correctness · Quick win

Reset scrobbler stats when the linked account changes

If a user reconnects Last.fm as another account without signing out of the music provider, Stats can show the previous account’s cached rankings, milestones, and density. Track account changes in the settings observer and invalidate the affected scrobbler state, including in-flight requests, even when another source is selected.

Minor · Disclose the partial listening clock · audioscrobbler.rs:509-532

crates/music/src/scrobble/audioscrobbler.rs:509-532
Minor · Functional Correctness · Quick win

Disclose the partial listening clock

When a Last.fm window has more than 800 plays, the clock and peak use only the fetched plays. They can differ from the full-window results, but the screen presents them under the selected window without a sample label. Mark these statistics as partial or hide them when the timestamps are incomplete.

@CodedNil CodedNil reopened this Nov 17, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

icons the icon packs library playlists, albums, artists, history, pins and the browsing screens spotify the Spotify backend, its library, search and sign-in ui rendering, layout, theming, icons, fonts, the window itself

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant