Add Listening Stats plugin, fade in covers, fix low_delay test #119
No reviewers
Labels
No labels
ai-review
ai-tour
bug
enhancement
needs-info
needs-triage
ready-for-agent
ready-for-human
security
wontfix
No milestone
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
SBDeveloper/medley!119
Loading…
Reference in a new issue
No description provided.
Delete branch "fix/fix-rust-build"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary
Test fix:
low_delay.rsnow expects the "not ready" error text instead of "Add a VBAN Receiver" (not re-run here).Unrelated UI polish: covers loaded from a URL (
Cover.svelte) fade in on load, like the smallArtworkcovers.Evidence
After:
cargo test --target x86_64-unknown-linux-gnuinplugins/optional/stats: 6 passed (spans split by day, tops ranked and cut, streak from today / survives a day, empty history, durations). Wasm build succeeds.npm run check: 0 errors;npm run e2e: 3 passed. Not run in the real app.Merge Danger
Door: two-way
The plugin is optional and not bundled; the cover change is CSS and a load handler.
Blast Radius: small
Only
Cover.sveltetouches existing UI (Browse album/artist/Track cards). A cover whoseloadnever fires stays invisible.Forgejo leaves `${{ github.workspace }}` empty in workflow-level env, so CLAUDE_BIN pointed at /.ai-work/... and the review failed with ENOENT. lib.mjs now uses .ai-work/claude when it exists, else `claude` on PATH. Co-Authored-By: Claude Opus 5.5 <[email protected]>🤖 AI review: ⚠️ Has issues worth fixing
This PR adds an optional
statsextension plugin. It records a Track once it has been heard for 30 s (or half its length if shorter), using the same forward-step counting as ListenBrainz, and appends it to/data/history.jsonl. A sidebar page then shows totals, top artists and Tracks, and a UTC daily streak. The pure summary logic is well tested. The event state machine inlib.rshas no tests, and that is where the real risk is: the host only emitsTrackChangedwhen the Track reference changes (player.rs:554), so playing the same Track again (repeat-one, play afterEnded) is either merged into one entry or not recorded at all. TheCover.sveltefade, thelow_delayassertion fix (matcheslib.rs:1543) and the AI-script binary lookup all look correct.3 findings: 1 major, 2 minor; 3 as comments on the diff.
Reviewed
6c4075862ewith Claude Code. An AI review can be wrong: weigh it, don't obey it.@ -0,0 +110,4 @@play.last_position = None;}}),PlaybackEvent::Playback { .. } => finish(),🟠 Playing the same Track again is merged into one entry or not recorded (major)
The player emits
TrackChangedonly when the Track reference differs from the last announced one (crates/core/src/player.rs:554). This plugin starts a newPlayonly onTrackChanged, which causes two failures:Ended: thePlayback { .. } => finish()arm takesplayand leavesNone. If the user presses play again,Player::playonEndedrepositions to 0 withPlaying(player.rs:1246), and picking the same Track again from the library doesn't change the reference either. NoTrackChangedarrives, so everyPlayingevent hitsplay == Noneand the whole listen is never recorded.Playing. The backward step is ignored butlistened_mskeeps growing in the samePlay. Five loops are written as one entry with 5× the time, and the "Most played Tracks" count is 1 instead of 5.The ListenBrainz plugin handles this case (
REPLAY_WITHIN_MS, and it keepsplayon non-Playing statuses). Suggested fix: onEnded, write the entry but keep the Track's metadata. Then treat aPlayingevent at a position near 0, arriving afterEndedor as a backward jump from near the end, as a new play (finish the old one, resetlistened_ms/started_at). Moving the counting into a pure function insummary.rs(or a sibling module) would also let it be tested natively alongside the existing tests. None of the current 6 tests toucheson_event.@ -0,0 +117,4 @@}/// Ends the current Track, writing it to the history if it was listened to.fn finish() {🟡 The Track playing when the app quits is lost (minor)
A listen is written only in
finish(), i.e. on the nextTrackChangedor aStopped/Endedstatus. If the user closes Medley partway through a Track (or the process crashes), the in-memoryPlayis dropped, even after minutes of listening. The last Track of every session is a common case. Suggested fix: write the entry as soon aslistened_mscrossesneededand update it in place afterwards, or keep a small/data/current.jsoncheckpoint that is turned into an entry on the next start.@ -0,0 +158,4 @@})}).collect();if entries.len() > HISTORY_CAP {🟡 History file is never trimmed; "All time" silently stops being all time (minor)
HISTORY_CAPis applied only to the parsedVec.history.jsonlgrows without limit, and everyui_viewreads and parses all of it withread_to_stringbefore dropping the oldest entries. The doc comment says older entries "are dropped when the file is read", but they are only skipped. Once the file passes 50,000 entries, the "All time" totals, top artists and top Tracks quietly cover only the newest 50,000, while the page still says "All time". Suggested fix: rewrite the file with the newestHISTORY_CAPlines when it exceeds the cap (e.g. infinish()every N appends), and either label the span honestly or keep running all-time totals in a separate small file.🎬 Change tour: Listening Stats page and fading covers
The tour opens the new Stats sidebar page with a realistic history: the streak badge, the listening time today, over the last 7 days and overall, the top-artist meters and the most played Tracks. It then clears the history, going through the confirmation to the empty state. Last, it searches and shows album covers loaded from a URL fading in on Browse. The plugin's drawn views are faked with the same shapes its view code returns.
▶ Watch the tour (MP4)
Slideshow: unzip and open
index.html, for step-by-step slides with the voice.Transcript
the Stats page
0:01This pull request adds Listening Stats, an optional plugin that sums up what you have been listening to. It keeps its history on this device and asks for no network.0:11Once installed, it adds a Stats page to the sidebar.0:16At the top is a daily streak: days in a row with at least one Track listened to.0:21Then the listening time for today, the last seven days, and overall.0:27A Track only counts once it has been heard for thirty seconds, or half its length if it is shorter. Seeks and pauses add nothing.0:35Top artists are shown as meters, scaled against the artist you listened to most.0:40And below them, the Tracks played most often, with a play count.clearing the history
0:47At the bottom, the history can be cleared. It asks first.0:54Here is the confirmation, with a way to keep it.0:58Confirm, and the page goes back to its empty state, which explains what will show up.covers fade in on Browse
1:04One smaller change rides along: covers loaded from a link now fade in once they have loaded, instead of popping in one by one.1:14Here are search results with album covers. Each one faded in as it finished loading, so the grid settles calmly.1:21That wraps it up: an optional Stats page that stays on your device, and smoother covers when browsing.Written and narrated by Claude Code · run. The tour runs against a fake backend, not the Rust core.
Thanks, all three held up; I checked the player claims (
player.rs:554,:1246) before changing anything. Fixed in834b16e(committed, being pushed now).Listener(listen.rs).Ended/Stoppednow writes the entry but keeps the Track, and the nextPlayingstarts a new pass. A jump back to within 5 s of the start (from a position more than one step ahead) ends the current pass and starts another, the same idea as ListenBrainz'sREPLAY_WITHIN_MS. A seek back into the middle is not a replay. Tests added: loop gives one entry per pass, replay afterEnded, seek-back is not a replay./data/current.jsonevery 30 s. The next start turns the checkpoint into an entry, so at most about 30 s is lost. Went with the checkpoint file and not in-place rewrite, because the history stays append-only./data/trimmedmarker is set; the page then says "Recent" instead of "All time". Clear history removes the marker too. I did not add running all-time totals: for a stats page of this size, honest labelling seemed enough.Not covered: the recover/checkpoint/trim file handling in
lib.rshas no native test (it needs/data); the decision logic they rely on is tested (15 tests pass, wasm build clean).🤖 AI review: ⚠️ Has issues worth fixing
This PR adds an optional
statsextension plugin. It logs each Track heard for at least 30 s (or half its length, if shorter) from playback events into a JSON-lines history in the plugin's private storage. A Track still playing is saved every 30 s so a quit doesn't lose it, and a sidebar page shows listening time, top artists and Tracks, and a daily streak. Separately, URL covers inCover.sveltenow fade in, the low_delay test now expects the "not ready" message thatCorereally returns, and the AI-review script finds the local Claude install by itself. The cover, test and script changes look correct. The risk is in how the plugin counts listens. Some Tracks are recorded twice: the host sends the end of a Track and the start of the next as separate events. And the Stats page runs in a separate WASM instance from the event handler, so the two instances don't share in-memory state.2 findings: 2 major; 2 as comments on the diff.
Reviewed
834b16e3e6with Claude Code. An AI review can be wrong: weigh it, don't obey it.@ -0,0 +171,4 @@if req.view_id != "page" {return Err(Error::msg(format!("no view {}", req.view_id)).into());}recover();🟠 Opening the page turns the live Track's checkpoint into a history entry, then the Track is counted again (major)
The host runs each lane in its own WASM instance (
plugin_host::Lane).on_eventis called onLane::Events(extensions.rs:246), whileui_viewruns on the main lane. SoSTATE.recoveredis set separately in each instance.Scenario: the app starts and the events instance runs
recover()on its first event. A Track plays past 30 s, so the events instance writes/data/current.json. The user then opens the Stats page for the first time. The main instance'srecoveredis stillfalse, so itsrecover()reads the live checkpoint, appends it to the history and deletes the file. When the Track finishes, the events instance'sListenerappends its full entry as well. That Track now has two entries: one partial, one complete.The same split affects "Clear history" (it also runs on the main lane): it deletes the checkpoint while the events instance still holds the current play, so that Track comes back afterwards. That part is less serious.
Fix: only the events instance should recover, i.e. don't call
recover()fromui_view. If the page must show a checkpoint left by an earlier run before any event arrives, read it there without appending or deleting it. A checkpoint that carries a per-run id would also let a stale one be told apart from a live one.@ -0,0 +113,4 @@/// The Track ended or playback stopped. Keeps the Track, so playing it/// again starts a new pass.pub fn ended(&mut self) -> Option<Entry> {🟠 A Track that ended or was stopped is counted again on the next TrackChanged (major)
ended()returns the entry and setsover = true, but it leaveslistened_msas it was. The nexttrack_changed()then runsself.play.take().and_then(|p| p.entry())on that samePlay, which still meets the threshold, so the listen is returned and appended a second time.The host takes this path in normal use. When the Queue runs out, the player publishes
Ended(player.rs:1372). Stopping playback publishesStopped(Player::stop,clear()). Both reachl.ended()through the catch-allPlaybackEvent::Playback { .. }arm. When the user then picks another Track,TrackChangedarrives and the previous Track is written again. Every stop followed by playing something else double-counts the last Track in plays, time, top Tracks and top artists.Fix: in
track_changed, skip the entry whenp.overis set (.filter(|p| !p.over).and_then(|p| p.entry())), or zerolistened_msinended()once the entry has been handed out. Add a unit test that plays 40 s, callsended(), thentrack_changed(..), and expectsNone.Both confirmed (I checked
extensions.rs:246:on_eventruns onLane::Events, views on the main lane). Fixed in the next commit on this branch.TrackChanged: my bug.track_changednow ignores aPlaythat is alreadyover, since its entry was handed out atended(). Test added: 40 s,ended(), thentrack_changedgivesNone.ui_viewno longer callsrecover(); onlyon_eventdoes, in the instance that owns the checkpoint. A checkpoint left by an earlier run therefore appears once the first playback event arrives, not on opening the page.Known and left: "Clear history" runs on the main lane and deletes the checkpoint, so a Track playing at that moment can come back with its listen at the next 30 s checkpoint. I judged that acceptable (it reflects what was listened to after the clear); say if you want a cleared-at marker instead.
🤖 AI review: ⚠️ Has issues worth fixing
This PR does four things. It adds an optional
statsextension plugin. It makesCover.svelteimages fade in once loaded. It updates thelow_delay.rsassertion to the current "not ready" message, which does matchcrates/core/src/lib.rs:1543. It reworks the AI review/tour workflow so each runs once per PR, again on request via a label, with follow-up rounds that carry state.The plugin's counting logic (
listen.rs) holds up against how the host actually emits events. Position updates come every 250 ms, and the 2 s step and replay rules fit that. Repeat-one gets noTrackChanged, so the replay check covers it. Ended and Stopped are guarded so they count once.The risks are in the file side of the plugin, which only has native unit tests for its pure logic. First, the history is re-read and re-parsed on every redraw, and the open page redraws every second. Second, the trim can rewrite the whole file on every listen. Third, the new follow-up review trusts a state block from any PR comment.
3 new findings: 3 minor; 3 as comments on the diff.
Reviewed
b38d3d6135with Claude Code. An AI review can be wrong: weigh it, don't obey it. Reply to a finding or react 👎 to dispute it; add theai-reviewlabel for a follow-up on the latest commit.@ -0,0 +138,4 @@fn trim() {let text = fs::read_to_string(HISTORY_FILE).unwrap_or_default();let lines: Vec<&str> = text.lines().collect();if lines.len() <= HISTORY_CAP {🟡 F2: Trim keeps 50,000 lines however large they are, so long lines make every append re-read or rewrite the file (minor)
appendcallstrim()whenever the file is overTRIM_BYTES, buttrimcaps lines, not bytes. If the average line is over ~168 bytes, the file passes 8 MiB before it reaches 50,000 lines. That is about 120 characters of artist plus title, which is common with classical metadata such as "Symphony No. 5 in C minor, Op. 67: I. Allegro con brio" by "Berliner Philharmoniker, Herbert von Karajan".In that state:
lines.len() <= HISTORY_CAPand return.The docs' "past about 8 MiB" claim also no longer holds.
Fix: trim by bytes with some headroom, for example keep the newest lines that fit in
TRIM_BYTES / 2. Or keep the line cap but trim down to something likeHISTORY_CAP * 3 / 4, so a trim happens rarely and not on every listen.@ -0,0 +175,4 @@// No `recover()` here: this runs in another instance than `on_event`, and a// checkpoint it finds may belong to the Track playing right now.// The Track playing right now is not in the history yet.let s = summarize(&history(), now(), TOP);🟡 F1: Stats page re-reads and re-parses the whole history every second during playback (minor)
PluginViewPanel.svelteredraws a plugin view whenevertrack_id|status|floor(position_ms/1000)changes, so while the Stats page is open and music plays,ui_viewruns about once a second. Each call doeshistory(): it reads the whole file (up to ~8 MiB / ~80,000 lines, by design) and parses every line into aserde_json::Value, in wasm, and thensummarizebuilds the HashMaps again. With a long history this keeps a core busy the whole time the page is open. The panel also dims the page (stale) while a slow draw is in flight.Nothing in the history changes between those calls. Only
append(on the events instance) andclear_yeschange it.Fix: cache the parsed
Vec<Entry>or theSummaryinSTATEon the UI instance, keyed by the file'slen()(plusnow()/DAY_SECS, so 'Today' rolls over). Re-read only when that key changes.@ -101,0 +203,4 @@...comments.map((c) => ({ body: c.body, at: c.created_at, user: c.user?.login })),].filter((p) => p.body && STATE.test(p.body));if (!posts.length) return null;const latest = posts.sort((a, b) => String(a.at).localeCompare(String(b.at))).at(-1);🟡 F3: Follow-up review accepts a state block from any commenter (minor)
previousRound()buildspostsfrom all reviews and all issue comments whose body matchesSTATE, takes the newest, and setsbot = latest.user. Anyone who can comment on the PR can post a comment with<!-- medley-ai-review-state:<base64> -->. On the nextai-reviewrun:fixed/withdrawn, which the prompt calls "never raise these again", or put arbitrary text into finding bodies that go into Claude's prompt.botbecomes that commenter, so their own replies and reactions are dropped and the real bot's are counted as people's.findings/sha/roundmakeshistory.state.findings.filterthrow, and the review fails.The review is advisory, but this lets a third party silence or steer it.
Fix: only accept state from posts by the identity that posts reviews (
GET /userwithREVIEW_TOKEN, or the known bot login). Validate the shape before use, and fall back to a fresh review if it is wrong.277541a. The page keeps its summary and redoes the sums only when the history file's size or the day changes; "Clear history" drops it. The redraw each second is now cheap.277541a. A trim now keeps the newest lines that fit in half of the 8 MiB limit (and at most 50,000), so it happens rarely and never rewrites on every listen. The docs say so.newest()has a unit test; the file handling around it does not.scripts/ai/review.mjsfroma5ab3ce, the review-workflow commit, not the Stats work, and I can't run that workflow to verify a change. It is advisory only, so I'd take it as a follow-up: accept state only from the bot identity and validate its shape.