Commit graph

3527 commits

Author SHA1 Message Date
BoulderBadgeDad
cc433fad37 Album picker #730: add word-boundary full-phrase bonus (from PR #731 review)
Compared my #730 fix against contributor PR #731 (same independent design).
Grafted their good idea — a confidence bonus when the album's full core phrase
appears intact in the release title (rescues long multi-word names whose token
coverage gets diluted) — and kept my accent-folding, which #731 lacks (their
normalize drops accented chars: Bjork -> 'bj rk').

IMPORTANT: implemented the phrase bonus WORD-BOUNDARY anchored, not as a raw
substring. My first cut used 'phrase in norm_title' (matching #731) and it
immediately reintroduced the substring bug #730 exists to fix — 'heroes'
matched 'superheroes' and the wrong album scored 0.9/passed. PR #731 has this
latent flaw. The regex anchors the phrase to word boundaries so the bonus
fires for real matches only.

Verified: substring trap (Superheroes/Scary Monsters) rejected; edition
suffixes + intact-phrase albums kept. +1 phrase-bonus test (incl. the
word-boundary guard). 126 plugin tests pass; ruff clean.

Co-authored-by: Tyler Richardson-LaPlume <170156756+IamGroot60@users.noreply.github.com>
2026-05-30 20:10:22 -07:00
BoulderBadgeDad
1c2efbb15c Album picker #730: drop the unused artist_name param (review cleanup)
Review caught that artist_name was added to pick_best_album_release's signature
and threaded through both call sites but never actually used — dead, misleading
code. Removed it from the helper + both callers. Artist-aware gating would be a
deliberate future feature (titles carry the artist inconsistently, so a hard
artist gate would risk the same false-negative class I just fixed); the album
relevance gate already resolves the reported wrong-release bug. No behavior
change. 127 plugin tests pass; compile + ruff clean.
2026-05-30 19:10:51 -07:00
BoulderBadgeDad
78c6f09e13 Album picker #730: don't reject the right album over an edition suffix
Self-review found a false-negative in the title-relevance gate I just added:
it scored 'fraction of the ALBUM-NAME's words present in the title', so a
stored album name with an edition/remaster suffix the torrent lacks
('Currents (Deluxe)', 'Heroes (2017 Remaster)') scored BELOW the 0.6 floor and
the correct release was wrongly refused -> fell back to per-track. The very
first issue example ('Heroes 2017 Remaster') would have regressed.

Fix: strip edition/format/year NOISE words (deluxe, remaster, edition, flac,
years, bitrates, ...) before scoring, via _significant_words(), with a fallback
to the raw words so an album literally named '1989' or 'Deluxe' isn't emptied
to match-everything. Verified both directions: edition suffixes now KEPT, while
the wrong-album rejection (Scary Monsters for a Heroes request, Superheroes)
still scores 0.

Tests: +2 regression tests (edition-suffix kept; noise/number-only album name).
125 album-bundle/dispatch/plugin tests pass; compile + ruff clean.
2026-05-30 19:08:03 -07:00
BoulderBadgeDad
95f4f41c50 Album bundle: gate Prowlarr release picker by album-title relevance (#730)
Reporter (IamGroot60): requesting an album via a Prowlarr-backed source
(Usenet/Torrent) could download a DIFFERENT album — e.g. asking for Bowie's
'Heroes' downloaded 'Scary Monsters' because the picker ranked purely by
seeders/grabs -> quality -> size with NO title check, and the wrong album had
~16x the grabs. (Confirmed the old picker chose the wrong release on exactly
this scenario.)

Fix (the reporter's proposal):
- album_title_relevance(candidate_title, album_name): word-coverage match,
  accent-folded (Bjork != bj rk) and WORD-BOUNDARY (Heroes != Superheroes), so
  a wrong album that shares no title words scores 0.
- pick_best_album_release gains album_name/artist_name params and a relevance
  gate (floor 0.6) applied BEFORE the seeders/quality/size ranking. When
  album_name is given and NOTHING clears the floor, returns None.
- torrent.py + usenet.py call sites pass album_name/artist_name and set
  result['fallback'] = True on None, so the dispatcher (source-agnostic
  fallback routing) hands off to the per-track flow instead of grabbing a
  wrong album. Matches what Soulseek already did via its preflight scorer.

No album_name -> no gating (old behavior preserved for callers without a
title). Tests: 9 new in test_album_bundle.py (relevance math incl. the
substring trap + accent fold, the exact Bowie refuse-and-fallback scenario,
None-when-no-match, and no-gate-without-name). 125 album-bundle/dispatch/plugin
tests pass; compile + ruff clean.
2026-05-30 18:56:07 -07:00
BoulderBadgeDad
c3f7cf795a Image cache: reject truncated downloads instead of caching broken covers (#750)
Reporter: album covers render as a top strip then solid grey ('break' on
import) — and it happens regardless of the album-art toggles. That ruled out
the import embed/cover.jpg paths (all toggle-gated) and pointed at the DISPLAY
cache, which every cover view goes through.

Root cause: ImageCache._fetch_and_store streamed the body to a tmp file and
committed it as status='ok' with only a 'total <= 0' (empty) guard. A
dropped/short connection makes requests' iter_content END EARLY WITHOUT
raising, so a PARTIAL image was cached permanently and served forever as a
half-decoded cover. The high-res art change in 2.6.4 (bigger images) makes a
mid-stream cutoff more likely, especially on the reporter's LXC.

Fix: capture the declared Content-Length and, after streaming, reject when
fewer bytes arrived (unlink the tmp file, raise ImageCacheError) so nothing
broken is cached and the next request retries fresh. When the server omits
Content-Length (chunked), we can't detect truncation, so we don't reject —
behavior unchanged there.

Tests (tests/test_image_cache.py): truncated download raises + caches nothing +
a later good fetch still works (differential-verified it's silently cached
without the guard); positive control (declared==actual) caches normally;
no-Content-Length still caches. 6 image-cache tests pass.

Strong-candidate fix: it's a real defect that produces exactly this symptom,
but I can't reproduce the reporter's LXC network to prove it's THE cause.
2026-05-30 17:45:01 -07:00
BoulderBadgeDad
fa750b6e89 Search: bump live-search debounce 300ms -> 600ms (#751)
Reporter (Vicky-2418) saw the artist search fire a separate external-API
search for nearly every letter typed. There WAS a 300ms debounce, but that's
short enough that a deliberately-typed name lands a keystroke per debounce
window, so each letter kicked off (and aborted) a fresh search — noisy in the
logs and wasteful.

Bumped both live-search surfaces that drive the shared SearchController
(external metadata APIs) to 600ms: the /search enhanced input (search.js) and
the global-search widget (downloads.js). 600ms coalesces a name being typed
into one search after the user pauses, while still feeling live. Enter still
triggers an immediate search on both (existing keypress/keydown handlers),
and the per-change abort already cancels stale in-flight fetches.

Frontend-only; both files syntax-clean.
2026-05-30 15:34:34 -07:00
BoulderBadgeDad
401b3ed327 revamp_plan: reconcile checkboxes with what actually shipped 2026-05-30 15:16:21 -07:00
BoulderBadgeDad
112ecbb24f Player: seek hover tooltip on the Now Playing progress bar
The mockup had a seek tooltip (timestamp tracks the cursor over the progress
bar) but it was never ported to the real player. Added it: mousemove computes
the hovered fraction -> formatTime(duration*frac), positions the tip, shows on
hover / hides on leave. Guarded when no duration. Frontend-only; JS + CSS clean.
2026-05-30 15:15:58 -07:00
BoulderBadgeDad
bf2a2ca928 Player: log SoulSync web-player plays (recently-played + smart-radio recency)
listening_history was populated ONLY from the media server; the web player
recorded nothing. Now a play heard ~10s logs to listening_history AND bumps
tracks.play_count/last_played — so the existing 'recently played' query reflects
actual SoulSync listening, and the Phase-2 smart-radio recency signal gets real
data.

- core/playback/play_log.build_play_event(): pure, DB-agnostic normalizer from
  player payload -> listening_history event shape. Caller supplies the
  timestamp (stays pure). Composite/streamed ids never become the int
  db_track_id; bool ids rejected; missing title -> skip. 9 unit tests.
- MusicDatabase.record_web_player_play(): inserts the history row + increments
  play_count/last_played for the library track in one call.
- /api/library/log-play: thin endpoint, server-side timestamp, best-effort
  (logging failure never 500s / never affects playback).
- Frontend: npMaybeLogPlay on timeupdate fires once per track at the 10s
  threshold (flag reset in setTrackInfo, set-before-fetch so it can't
  double-fire), fully fire-and-forget.

Pure builder is unit-tested; the DB write can't run in-sandbox (real DB throws)
so it's a thin straightforward insert+update. JS + web_server parse clean.
2026-05-30 15:11:46 -07:00
BoulderBadgeDad
f9bc96bd90 Player: 'Playing from' context header (Radio / <Artist> Radio)
Spotify-style context line above the track title. npSetPlayContext(text) shows/
hides it; set to 'Radio' when radio mode turns on, '<Artist> Radio' from
playArtistRadio (specific label wins over generic), cleared on stop/clearTrack
and when radio mode is turned off. Accent-colored name, uppercase label.

Frontend-only; JS + CSS clean.
2026-05-30 15:07:31 -07:00
BoulderBadgeDad
ab2b5c64f4 Player: shuffle + repeat on the mini-player (parity with modal)
The sidebar mini-player had prev/play/next/stop/expand but not the two
set-and-forget controls you reach for without opening the full view. Added
shuffle + repeat (3-mode, with a repeat-one badge) to the mini-controls.

State stays in sync both ways: handleNpShuffle/handleNpRepeat now call a shared
syncShuffleRepeatUI() that reflects state onto BOTH the modal and mini buttons,
so toggling in either place updates the other. Mini buttons reuse the same
handlers. Accent-active styling via --accent-light-rgb.

JS clean; CSS balance consistent with HEAD.
2026-05-30 14:57:04 -07:00
BoulderBadgeDad
1e514693f1 Player: 'Play next' action + accent-correct queue buttons
- Added playNext(track): inserts a track right after the current one (Spotify
  'Play next'), vs addToQueue which appends to the end. Falls back to
  addToQueue when nothing is playing.
- Artist-detail track rows now show BOTH a Play-next (⇥) and Add-to-queue (+)
  button; the delegated handler builds one shared library-track payload and
  routes to playNext / addToQueue. (Add-to-queue was already wired; play-next
  + the second button are new.)
- Fixed the queue button's hardcoded 29,185,84 to var(--accent-rgb) so it
  follows the settings accent (kettui UI-consistency), and styled the new
  play-next button to match.

Note: deliberately NOT adding queue buttons to SEARCH results — those are
stream/download (non-library) tracks the queue's auto-advance can't reliably
play. JS syntax clean on both files.
2026-05-30 14:54:14 -07:00
BoulderBadgeDad
65f49ccecd Player: N/P next-prev keys + global mute + persist volume across reloads
- Keyboard: added N (next) / P (previous) track shortcuts; 'm' mute now works
  whether or not the modal is open (was modal-only). Space/seek/volume/escape
  unchanged.
- Volume persistence: volume now saved to localStorage on every change (slider
  + arrow keys, via npPersistVolume) and restored on load instead of always
  resetting to 70%. npLoadSavedVolume validates the stored 0..100 value.
  initializeMediaPlayer applies it + syncs both slider UIs.

Frontend-only; init runs from init.js after full parse so the module consts
are defined. JS syntax clean.
2026-05-30 14:52:16 -07:00
BoulderBadgeDad
3c123958ca Fix: Artist Radio never populated the queue
playArtistRadio() flipped npRadioMode=true directly but never fetched similar
tracks, so the queue stayed empty until the current song ENDED (onAudioEnded is
what triggered the radio fetch). The modal's Radio button does it right via
npSetRadioMode(true, {fetchIfNeeded:true}).

Fix: await playLibraryTrack(...) (it's async and sets currentTrack only after
resolving the canonical DB row), THEN call npSetRadioMode(true, {fetchIfNeeded})
— which seeds the current track into the queue and immediately fetches the
radio queue. Replaces the old fixed-setTimeout guess that raced the async track
load (and could fire before currentTrack.id existed -> silent no-op).
2026-05-30 14:45:39 -07:00
BoulderBadgeDad
592b68c16c Player revamp: harden crossfade race conditions + global decl (audit fixes)
Self-audit of the revamp surface found real bugs, now fixed:

- DOUBLE-ADVANCE race: crossfade starts ~6s before track end, but when the
  track actually 'ended' fired, onAudioEnded ALSO advanced — two skips.
  onAudioEnded now bails when npXfadeActive (crossfade owns the advance).
- STRAY CROSSFADE on manual skip/stop: skipping or stopping mid-fade left the
  interval running, firing npFinishCrossfade on top of the manual change, and
  left the second <audio> playing. Added npCancelCrossfade() (clears the timer,
  tears down the 2nd audio, restores main volume) called at the top of
  playQueueItem and in handleStop. The fade interval also self-checks
  npXfadeActive each tick. npFinishCrossfade clears all flags cleanly so the
  legitimate handoff isn't treated as an abort.
- stream_start: moved 'global stream_background_task' to function top (it was
  declared inside an if-block — parsed, but brittle/bad form).

web_server parses; 76 streaming+radio tests pass; JS syntax clean; CSS balance
unchanged from HEAD.
2026-05-30 14:38:28 -07:00
BoulderBadgeDad
a2fe3da839 revamp_plan: mark Phase 3b (per-listener sessions) done 2026-05-30 14:29:40 -07:00
BoulderBadgeDad
f617458962 Phase 3b: per-listener stream sessions (no more shared-playback collision)
Wires the StreamStateStore (Phase 3a) into the live routes so each browser/
device gets its OWN playback instead of every client sharing one global
stream_state. Fixes the long-standing limit where a second tab/device/listener
would hijack the one playback.

- _stream_session_id(): stable per-browser id stored in the Flask session
  cookie (falls back to DEFAULT when no request context — e.g. the socket
  broadcast thread — so single-user behavior is identical).
- _current_stream_state(): the StreamSession for the calling browser.
- Routes rewired to the caller's session + its own lock: /api/library/play,
  /api/stream/start, /api/stream/status, /stream/audio, /api/stream/stop.
- Background tasks tracked per session (stream_tasks[sid]) instead of one
  global Future, so stopping/replacing one listener's stream doesn't cancel
  another's. Executor bumped 1 -> 4 workers so concurrent listeners don't
  queue behind each other.
- Per-session staging: named sessions stage under Stream/<sid>/Stream so
  listeners never clear each other's files; default session keeps flat Stream/.
- /stream/status now returns THIS listener's state, which is what the frontend
  polls — so per-listener works without touching the socket broadcast (left
  serving the default session, now vestigial for status).

Isolation invariant covered by tests/streaming/test_stream_state_store.py
(distinct sessions independent, default stable). The route-level cookie wiring
+ actual two-client no-collision behavior need live multi-client verification
(can't be tested without booting Flask + separate cookies) — EXPERIMENTAL,
needs Boulder to test with 2 browsers/devices. 33 streaming tests still pass;
web_server parses.
2026-05-30 14:29:19 -07:00
BoulderBadgeDad
866f2e4a23 Now Playing: complete Media Session lock-screen controls
The Media Session API was partial — play/pause/stop/seek±10/prev/next handlers
+ metadata/artwork existed, but the OS lock-screen/Bluetooth/notification
control had a DEAD scrubber (no position, no drag-to-seek). Completed it:

- setPositionState (duration/position/rate) so the lock screen shows a live
  progress bar, pushed throttled (~1/s) from timeupdate, reset on
  loadedmetadata of a new track, and on manual seek.
- 'seekto' action handler so dragging the lock-screen/notification scrubber
  actually seeks (with fastSeek when available).

Now hardware/Bluetooth keys + the lock-screen scrubber fully drive playback
with art, metadata, and live position. Feature-detected throughout.
2026-05-30 14:23:29 -07:00
BoulderBadgeDad
843f4081cf Now Playing: click-to-seek synced lyrics
Click any synced lyric line to jump playback to that line's timestamp (and
resume if paused). Reuses the existing _npLyricsState.lines {time,text} data.
Hover affordance: accent-tinted line + pointer cursor. Synced lyrics only
(plain lyrics have no timestamps).
2026-05-30 14:17:51 -07:00
BoulderBadgeDad
a8985b317f Now Playing: fix squashed stop button + queue persistence + crafted entrance
- Stop button fix: my round .np-btn { width/height 46px; border-radius:50% }
  override was also hitting .np-btn-stop (it carries both classes), squashing
  the 'Stop' text pill into a tiny circle. Exempted .np-btn.np-btn-stop back to
  an auto-width pill.
- Queue persistence: npPersistQueue() (called from renderNpQueue, the single
  mutation hook) saves the queue to localStorage; npRestoreQueue() on init
  repopulates the panel on reload WITHOUT auto-playing (index reset to -1).
  Queue no longer vanishes on refresh.
- Crafted entrance: controls stagger-fade/rise in when the modal opens
  (npRiseIn keyframe, delays cascading util->progress->controls->volume->
  upnext). Art container excluded so its transform stays free for the
  play-scale.

Frontend-only; Boulder verifying live.
2026-05-30 14:17:07 -07:00
BoulderBadgeDad
ccfb3fb042 Now Playing: real crossfade for library tracks (experimental)
Crossfade was a no-op toggle. Real crossfade needs two tracks audible at once,
but /stream/audio only serves the ONE current track (single global
stream_state). So:

- web_server: extracted the range-serving body of /stream/audio into
  _serve_audio_file_with_range, and added /stream/library-audio?path= which
  serves an arbitrary LIBRARY file through it. Security: the path is resolved
  via _resolve_library_file_path (same validator /api/library/play uses) so it
  only serves files inside the configured transfer/download/media-library
  dirs — not arbitrary disk.
- frontend: a second hidden <audio> (#audio-player-xfade) preloads the NEXT
  library track when the current one is within 6s of ending (crossfade on,
  not repeat-one), ramps the two volumes in opposite directions, then hands
  off to playQueueItem so all normal now-playing state is set.

Honest limits (documented in code): library→library only (streamed tracks
hard-cut as before); there's a brief silent reload at hand-off because
playQueueItem re-points the single stream_state — the perceived crossfade has
already happened by then. EXPERIMENTAL — needs Boulder's live audio
verification; I can't test audio in-sandbox.

33 streaming tests still pass (stream_audio refactor is behavior-preserving).
2026-05-30 11:48:56 -07:00
BoulderBadgeDad
ffbe669c67 Now Playing: vibrant album-art color extraction + drag-to-reorder queue
Two next-level player features (frontend-only):

1. Album-art ambient color — replaced the flat pixel AVERAGE (which muddied
   every cover to grey-brown) with dominant-VIBRANT extraction: coarse
   histogram binning weighted by saturation² × population, then a punch-up
   pass (boost saturation ~1.3x, floor brightness) so the modal glow reads as
   the cover's real standout color, Apple-Music style. Feeds the existing
   --np-ambient-r/g/b hooks.

2. Drag-to-reorder queue — queue rows are now draggable; npReorderQueue moves
   the item AND recomputes npQueueIndex so the currently-playing track stays
   correctly tracked after a reorder. Accent drop-line indicator, grab cursor,
   dragging opacity.

Verified live in-browser by Boulder.
2026-05-30 11:46:31 -07:00
BoulderBadgeDad
3461d9235b Now Playing modal: full visual redesign + click-art visualizer, sleep timer, up-next
Player-revamp frontend (Phase 1). Brings the Now Playing modal to the approved
mockup look + features:

- Full restyle (override block in style.css): 28px modal radius, stronger
  art-driven ambient glow, 340px rounded art that scales while playing, bold
  28px title, accent artist name, accent FLAC pill, dominant 70px gradient
  play button, accent-gradient progress/volume/visualizer. All driven by the
  existing --accent-rgb / --accent-light-rgb so it follows the settings accent.
- Click album art -> Plexamp-style visualizer takeover, fed by the REAL
  music-synced Web Audio analyser (npStartVisualizerLoop), click again -> art.
- Rich queue rows: album thumbnail + title/artist + duration, equalizer
  animation on the now-playing row, hover-reveal remove.
- Up-next peek below the controls (shows the next queued track).
- Sleep timer (cycles 15/30/60m, real setTimeout -> handleStop).
- Crossfade toggle present (visual state + persisted pref; the dual-audio
  crossfade engine is the next step, not yet wired).

Frontend-only; verified live in-browser by Boulder. No backend/test surface.
2026-05-30 11:43:45 -07:00
BoulderBadgeDad
ca90c6ae6f Player revamp Phase 3a: extract stream state into testable per-session store
Foundation for multi-listener playback. Today web_server.py keeps ONE global
stream_state dict + one lock (web_server.py:747), so the whole server shares a
single 'currently playing' — every tab/device is a remote for the same
playback and two listeners collide. That global is woven through ~22 sites and
isn't unit-testable where it lives.

Lifted into core/streaming/state.py WITHOUT changing behavior:
  - StreamSession: one playback's state, dict-compatible (s['k'], s.get,
    s.update, 'k' in s) so existing call sites work unchanged, each with its
    OWN RLock so distinct sessions never block/clobber each other.
  - StreamStateStore: registry of named sessions; lazy + race-safe create;
    DEFAULT session reproduces today's exact single-global behavior. Also
    drop()/active_ids()/session_ids() for the eventual per-listener wiring.

web_server.py now binds  (DEFAULT) and
. Drop-in: every .update()/[k]/.get()/ site behaves identically. _set_stream_state routes a reassign
through session.replace() so the store's session stays the live object (it's
effectively dead — prepare.py only mutates in place — but safe now).

Honest scope: this is the PROVABLE half of Phase 3. The remaining half (3b:
derive a per-browser session id, per-session Stream/ staging, executor
concurrency, disconnect cleanup) is browser-coupled and can't be verified
without driving 2+ live clients — deferred to a live session. The store API is
already shaped for it.

Tests (tests/streaming/, 33 total):
  - test_stream_state_store.py (19): session dict-compat, isolation, lazy
    create, drop rules, active_ids, concurrent-create race safety.
  - test_stream_state_callsite_compat.py (7): every real web_server access
    pattern (library/play, stream/start, status, audio guard, stop, prepare
    in-place mutation, set->replace) against the exact object web_server binds.
  - test_prepare.py +1: real prepare worker drives an actual StreamSession.
76 streaming+radio tests green; ruff clean; web_server.py parses.
2026-05-30 08:59:15 -07:00
BoulderBadgeDad
c3aea58b03 Player revamp Phase 2: smart radio ranking (play-count + popularity)
Replaces radio's pure ORDER BY RANDOM() with weighted ranking. Each tier now
fetches a generous random POOL (4x the needed count, floored) and
core/radio/selection ranks it before the collector keeps the best:

  score_candidate = play_count(log-damped, w=1.0)
                  + lastfm_playcount(log-damped, w=0.5)
                  - recently_played penalty(w=2.0)
                  + stable per-id jitter(w=1.0, hash-derived so runs vary but
                    tests stay reproducible)

Modest weights so popularity guides without burying lesser-played tracks, and
jitter keeps radio from being identical every run. All intelligence is in pure
functions (rank_candidates / score_candidate) so it's tunable + unit-testable
without SQL.

Defensive: the DB method probes PRAGMA table_info(tracks) and omits
play_count/lastfm_playcount from the SELECT when absent (older DBs predating
the listening-history migration) — the scorer treats missing signals as 0, so
radio degrades to jitter-only instead of crashing on 'no such column'.

Tests (tests/radio/, 43 total):
  - score_candidate / rank_candidates: deterministic unit coverage (popularity
    ordering, lastfm contribution, recency penalty, garbage→0, stable jitter).
    These CANNOT pass against pre-Phase-2 code.
  - DB end-to-end: ranking surfaces the heavily-played track first out of a
    decoy pool (wiring proof — probabilistic vs old random, documented honestly);
    plus a no-rank-columns DB proving the defensive degrade path.
  - All Phase-0a behavioral/refactor-equivalence tests still green.
60 radio + adjacent-DB tests pass; ruff clean.
2026-05-30 08:47:18 -07:00
BoulderBadgeDad
cbc001e283 Player revamp Phase 0a: extract radio selection into testable core/radio/
First step of the stream/player/radio revamp (see revamp_plan.md). The radio
algorithm lived inline inside database.music_database.get_radio_tracks as raw
SQL tangled with selection logic — untestable without a live DB (which also
throws in the dev sandbox). Lifted the pure DECISIONS into core/radio/selection.py:

  - parse_tags / merge_tags  — JSON-or-CSV tag fields → ordered deduped list
  - same_artist_cap          — tier-1 30%-floored-at-5 cap
  - build_like_conditions    — OR-of-LIKEs SQL fragment + params per tier
  - RadioCollector           — dedup + cap + exclude-set + NOT-IN placeholder/value tracking

The DB method keeps the cursor work and now delegates every decision to these
helpers. Faithful extraction, not a rewrite — behavior unchanged.

This is the kettui foundation move: radio is now unit-testable, so Phase 2
(smart ranking — play-count / recency / feature seeding) becomes 'evolve a
tested function' instead of 'rewrite SQL and pray'.

Tests (tests/radio/):
  - test_selection.py (22): unit coverage of every extracted helper
  - test_get_radio_tracks_db.py (7): drive the REAL get_radio_tracks against
    in-memory sqlite — tier fallback, dedup, exclude, file_path filter.
    Behavior-pinned: these 7 pass against BOTH old inline and new extracted
    code (refactor-equivalence proof). 52 adjacent DB+radio tests green.
2026-05-30 08:34:27 -07:00
BoulderBadgeDad
472ec7ea01 Bump version to 2.6.5 (dev — prep for next cycle) 2026-05-30 00:48:58 -07:00
BoulderBadgeDad
443257915c Path builder: validate $year, never blind-slice release_date (#745)
The $year template variable was a blind release_date[:4] slice. When
something upstream poisoned release_date with a non-date value — the album
NAME — that slice emitted garbage: 'Mantras (Deluxe)'[:4] -> 'Mant', so
every download landed in 'Mantras (Deluxe) (Mant) [Album]/' instead of
'(2026)' (Tacobell444's screenshot).

Add _extract_year_from_release_date(): returns the leading 4 chars only
when they're a plausible year (isdigit, 1900 < y <= 2100), else ''. Matches
the guard the codebase already uses in soulid_worker._extract_year. A
non-year resolves to '' and the template's existing empty-() cleanup drops
it, so a poisoned release_date can never write rubbish into the path again.

This is the shared post-process path builder
(core/imports/paths.build_final_path_for_track) that DOWNLOADS, reorganize,
and imports all route through, so the guard covers every surface at once.

Defensive fix only — it stops the SYMPTOM regardless of which upstream
writes the album name into release_date. Pinning that upstream needs the
reporter's metadata source + the release_date value from app.log (the
Soulseek + AcoustID + future-dated-album combo is the discriminator);
tracked separately.

Tests (tests/imports/test_import_paths.py): unit coverage for the helper
(real dates kept, names/sentinels/short values rejected) + an integration
test reproducing #745 — a poisoned release_date yields 'Mantras (Deluxe)
[Album]' not '(Mant)' — differential-verified it produces the exact
'(Mant)' folder without the fix. Positive control keeps real (2026). 395
import + reorganize tests green.
2026-05-30 00:31:14 -07:00
BoulderBadgeDad
56c58c3afc
Merge pull request #748 from Nezreka/fix/reorganize-skip-deleted-quarantine-746
Reorganize: skip files in the duplicate-cleaner /deleted quarantine (…
2026-05-30 00:19:53 -07:00
BoulderBadgeDad
20cd12e66b Reorganize: skip files in the duplicate-cleaner /deleted quarantine (#746)
The Duplicate Cleaner moves de-duplicated files into <transfer>/deleted/.
If a user's media server scans the transfer folder (e.g. a /music root
holding both the library and the transfer dir), those quarantined files
get real track rows in SoulSync's DB. Reorganize is purely DB-driven —
it acts on each track's stored file_path — so it would dutifully move a
quarantined file back OUT of /deleted to the template location, exactly
what Tacobell444 reported.

We can't stop the rows from existing (they come from the media server,
which the app doesn't control), so the fix is bounded to Reorganize, as
the reporter asked: skip any track whose resolved path is under
<transfer>/deleted. Surfaced as a non-matched 'In deleted/quarantine
folder — skipped' in the preview; apply mirrors it (post-process never
runs, file left in place, counted as skipped).

Detection is anchored to the <transfer>/deleted PREFIX (not a bare
substring) so a real album like 'Deleted Scenes' is kept; falls back to
an exact 'deleted' path-segment match when transfer_dir is unavailable
(mirrors the cleaner's own 'if deleted in dirs' skip). The one
unavoidable ambiguity — an artist folder named exactly 'deleted' at the
transfer root — is pinned in a test as intentional.

Guard added once where both consumers see it: preview_album_reorganize
and the apply worker (_RunContext gains transfer_dir).

Tests: tests/test_reorganize_deleted_quarantine.py (8 unit) +
test_library_reorganize_orchestrator.py (preview + apply integration,
differential-verified they fail without the fix). 128 adjacent
reorganize tests still green.
2026-05-30 00:15:06 -07:00
BoulderBadgeDad
0e1f07433a
Merge pull request #747 from Nezreka/fix/soulseek-album-poll-stall
Fix/soulseek album poll stall
2026-05-29 22:52:58 -07:00
BoulderBadgeDad
e94523f3e9 Album bundle: fall back to per-track when the chosen folder yields nothing
When the preflight-selected Soulseek folder produces zero usable files —
every transfer failed/aborted/stalled (the Slipknot dead-peer case: all
tracks 'Completed, Aborted' at 0 bytes) — _poll_album_bundle_downloads
returns []. download_album_to_staging used to return that with
fallback=False, so try_dispatch marked the whole batch failed and nothing
was retried elsewhere until the next wishlist run.

Flip that branch to fallback=True so the existing, proven per-track flow
takes over and re-searches every missing track across ALL sources/peers.
This reuses the per-track multi-source robustness instead of reimplementing
candidate-folder retry inside the bundle.

Tests: tests/test_soulseek_album_fallback.py drives the preflight-reuse path
with a stubbed poll — empty poll -> fallback=True (differential-verified it
fails without the fix), healthy poll -> fallback stays False. Downstream
routing (fallback=True -> per-track) already covered by
test_album_bundle_dispatch.py.
2026-05-29 19:46:52 -07:00
BoulderBadgeDad
a60eae9315 Soulseek album poll: treat 'Aborted'/'Cancelled' transfers as failed
Live testing surfaced that slskd reports a peer-side abort as 'Completed,
Aborted' at 0 bytes (peer accepts then drops every transfer). That string
contains 'Completed', so the poll's completed-branch ran first and misread it as
'completed but file missing' — routing it into the #715 unresolved/download_path
grace (gives up after 45s with a misleading 'download_path mismatch' log)
instead of recognizing it as a failure.

Add 'Aborted' and 'Cancelled' to the failure-token check (which runs before the
completed branch), so these resolve immediately and correctly as failed. Test
added for the all-aborted folder.
2026-05-29 19:29:55 -07:00
BoulderBadgeDad
aa2806180e Fix: Soulseek album poll hangs on a stalled peer; failed batches never cleared
Two related bugs from the Slipknot album never finishing.

1) _poll_album_bundle_downloads hung when the peer stalled. The finish check
   needs every transfer terminal (completed/failed); the #715 grace only covers
   'slskd says Completed but file not on disk'. A transfer stuck InProgress /
   Queued, or dropped by slskd, is none of those — so it blocked both the finish
   AND the grace exit, and the poll spun to the full ~6h timeout.

   Add a bundle-level stall guard: track a progress marker (#terminal transfers,
   total bytes across pending). If NOTHING advances for _stall_grace (180s) —
   no terminal transition AND no pending byte movement — the peer has stalled;
   mark the stuck transfers failed so the existing finish/all-failed checks
   resolve the bundle with whatever completed (missing tracks then fall back to
   the per-track matcher). Conservative: only trips when EVERYTHING is frozen,
   so a slow-but-progressing or still-queued transfer is unaffected.

2) Failed batches lingered in the UI forever ('No tracks loaded'). The
   auto-cleanup gate removed only complete/error/cancelled phases — 'failed'
   (e.g. an album-bundle hard failure) was missing, so it never aged out. Add
   'failed' to the terminal set so it's removed after 5 minutes like the others.

Tests (tests/test_soulseek_album_poll_stall.py): stalled peer → gives up with the
completed subset (not the deadline); progressing bundle not falsely stalled;
all-stalled → empty; dropped transfers stall out; clean finish unaffected.
124 download/soulseek tests pass; ruff clean.
2026-05-29 19:19:28 -07:00
BoulderBadgeDad
8ec6d2ae83
Merge pull request #744 from Nezreka/refactor/wishlist-orchestration-unify
Refactor/wishlist orchestration unify
2026-05-29 18:41:24 -07:00
BoulderBadgeDad
cea897cbd1 Wishlist: import Optional (fix ruff F821 in processing.py)
make_wishlist_batch_row / _run_wishlist_cycle annotate params with Optional,
but the typing import only had Any/Callable/Dict. Slipped past py_compile +
tests because 'from __future__ import annotations' makes annotations strings
(never evaluated at runtime), but ruff flags it statically (F821).
2026-05-29 18:31:45 -07:00
BoulderBadgeDad
d3c897fb9d Wishlist: route the manual flow through the shared engine (manual == auto)
Stage 2: the manual 'Download Wishlist' flow now calls the same
_run_wishlist_cycle engine the auto timer uses, so a manual scan runs the exact
same code path as an auto scan. The old bespoke manual orchestration (build
payloads + SERIAL inline dispatch) is deleted — its grouping/dispatch was a
near-duplicate of auto's that had already drifted.

Behavior changes (all intended, discussed):
- Manual now dispatches album bundles in PARALLEL (album pool) like auto, instead
  of serially on one thread. A single cycle='albums' engine call covers the whole
  selection (albums bundled, singles/ungroupable -> per-track residual), so no
  'both cycles' pass is needed.
- The manual placeholder batch_id is reused as the engine's first sub-batch
  (first_batch_id), so the modal's existing poll target stays valid.
- WishlistManualDownloadRuntime gains album_bundle_executor (wired in web_server,
  falls back to the shared pool when unset).
- 'Don't start manual while auto is running' is unchanged — the existing route
  guard (is_wishlist_actually_processing -> 409) already covers it; no queue added.

NOT touched: process_wishlist_automatically's behavior (proven by test_automation
staying green in Stage 1) and the per-track download mechanics.

test_manual_download.py rewritten to characterize the new behavior (engine
dispatch via the executor, parallel, placeholder reuse, album-context). Full
wishlist suite green (131); wishlist + automation = 392 passed.
2026-05-29 17:43:40 -07:00
BoulderBadgeDad
db1e51109c Wishlist: extract shared _run_wishlist_cycle engine; auto delegates to it
Stage 1 of unifying the auto + manual wishlist flows. Extract the
group -> per-album+residual batches -> register -> dispatch logic that lived
inline in process_wishlist_automatically into a standalone _run_wishlist_cycle()
engine (built on make_wishlist_batch_row). The auto path now just calls it.

Per-flow differences are arguments (auto_initiated stamps the auto-only fields +
selects auto vs manual naming/logging; first_batch_id lets a caller reuse a
pre-created placeholder). Album batches dispatch to the dedicated album pool,
residual to the shared pool (unchanged from #740).

Auto behavior is PROVABLY unchanged: its full characterization suite
(test_automation.py) stays green (10/10), and the whole wishlist suite passes
(131). This commit does NOT touch the manual flow yet (Stage 2) and does not
change what auto does — it only moves auto's logic behind a shared entrypoint
the manual flow will call next.
2026-05-29 17:22:00 -07:00
BoulderBadgeDad
e4b5cbbe60 Wishlist: unify batch-row construction into make_wishlist_batch_row
The auto and manual wishlist flows each built the same ~20-field
download_batches row in separate places (auto album, auto residual, manual
placeholder, manual sub-batches) — four near-identical literals that could (and
did) drift apart, producing subtly different batch shapes between the flows.

Extract make_wishlist_batch_row() as the single source of truth: it emits the
consistent core field set, with the genuinely per-flow differences as explicit
arguments — initial phase ('queued' for auto / 'analysis' for manual), the
auto-only auto_initiated/auto_processing_timestamp/current_cycle via
extra_fields, and album-vs-residual contexts. All four sites now go through it,
so every wishlist batch has an IDENTICAL shape (this also removes the field
drift that confused the modal-hydration code).

Deliberately NOT unified — and left explicit in each caller, per the
'don't cargo-cult genuinely-different code' principle: the grouping decision
(auto groups only on the albums cycle), batch-id allocation (manual reuses the
caller's placeholder id for the first sub-batch), and dispatch (auto
parallel-submits album batches to the dedicated pool + residual to the shared
pool; manual runs them serially on one thread). Those are real behavioral
differences, not duplication.

Behavior-preserving: verified safe to normalize the row shape (grep confirmed
every reader uses .get() with defaults, no key-presence checks). The existing
auto (test_automation.py) and manual (test_manual_download.py) characterization
suites stay green = differential proof of identical behavior. Adds
test_batch_factory.py (core fields, album/residual, extra_fields, no shared
mutable state, consistent key shape). 131 wishlist tests pass.
2026-05-29 16:55:31 -07:00
BoulderBadgeDad
1801bfc8f8
Merge pull request #742 from Nezreka/fix/wishlist-batch-jam-740
Fix #740: run wishlist album-bundle downloads on a dedicated pool
2026-05-29 15:32:17 -07:00
BoulderBadgeDad
0898014364 Fix #740: run wishlist album-bundle downloads on a dedicated pool
A 2.6.3 change (c3b88e69) split the wishlist albums cycle into one batch per
album. Each album batch runs an INLINE-BLOCKING soulseek/torrent/usenet
album-bundle download (album_bundle_dispatch.try_dispatch ->
download_album_to_staging) that holds its worker thread for the whole
search+download. All of these were submitted to the shared 3-worker
missing_download_executor -- the same pool used for per-track downloads AND the
manual 'Download Wishlist' analysis.

So a large Album-Completeness 'Fix all' (-> ~819 wishlist tracks -> ~82 per-album
batches) saturated all 3 workers with blocking album downloads; the manual
wishlist analysis could never get a thread ('Library Analysis' stuck on
Pending), the other ~79 batches sat in phase='queued' forever, and auto-cleanup
(which only evicts terminal-phase batches) never cleared them -> jam until
restart. Fixing batch STATUS would not help: the threads are blocked inside the
download, not waiting on a phase flip.

Fix: add a dedicated bounded album_bundle_executor (max_workers=3) and route the
AUTO per-album bundle batches to it, keeping the shared pool free for analysis /
per-track / the manual wishlist (which always starts now). Hung/slow album
downloads can only delay other album downloads, never the user-facing path.
Additive and decoupled; the submit site falls back to the shared pool when the
album pool isn't wired (older callers / tests) so behavior is unchanged there.
The manual path is untouched (it already runs album bundles serially on a single
thread, by design).

Tests (tests/wishlist/test_automation.py): album sub-batches route to the
dedicated pool while the residual per-track batch stays on the shared pool;
fallback-to-shared-pool when no album pool is wired. Existing auto-processing
tests still green (fallback preserves prior behavior). 707 passed across
wishlist + downloads suites.
2026-05-29 14:31:10 -07:00
BoulderBadgeDad
2d68843343
Merge pull request #741 from Nezreka/refactor/db-schema-hardening
Refactor/db schema hardening
2026-05-29 13:57:24 -07:00
BoulderBadgeDad
4fcc461616 Source IDs: add canonical registry, adopt at the highest-value sites
The same provider ID is stored under inconsistent column names across tables
(deezer_id vs deezer_artist_id vs album_deezer_id vs similar_artist_deezer_id;
spotify/itunes keep an entity qualifier, others don't; musicbrainz uses three
nouns), so code checks 2-5 name variants everywhere.

Add core/source_ids.py as the single source of truth for (provider, entity) ->
column, with accessors that read an ID from a dict/sqlite3.Row robustly
(canonical column first, then known aliases). NO database columns are renamed —
these are the real names today; the registry just centralizes the knowledge.

Targeted adoption (behavior-identical, verified):
- core/artist_source_lookup.SOURCE_ID_FIELD now derives from the registry
  instead of duplicating the mapping (values unchanged).
- web_server.py artist-detail builds artist_source_ids via source_id_map(...)
  instead of a hand-rolled per-source .get() dict.

Broader call-site adoption deferred as clearly-scoped follow-up.

Tests: tests/test_source_ids_registry.py (canonical columns, alias fallback,
canonical-preferred, sqlite3.Row, source_id_map, SOURCE_ID_FIELD unchanged).
Existing artist_source_lookup + artist_full_detail suites still green.
2026-05-29 12:19:59 -07:00
BoulderBadgeDad
b55faff54b DB: add schema_migrations ledger + PRAGMA user_version backstop
Migration state was scattered across PRAGMA-table_info guards, sentinel marker
tables (_genius_search_fix_applied, ...) and metadata-flag rows
(id_columns_migrated, ...), with no single source of truth and no schema
version — so a half-migrated DB was undetectable.

Add a non-gating backstop: a schema_migrations(name, applied_at) ledger plus a
_sync_migration_ledger pass (runs last in init) that back-fills the ledger from
the existing signals and stamps PRAGMA user_version. ADDITIVE only — existing
migrations keep their own idempotency gates; nothing decides whether a
migration runs based on the ledger or the version. New one-time migrations call
_record_migration (the genres migration already does).

Tests: tests/test_db_migration_ledger.py — table exists, user_version stamped,
record idempotent, genres recorded on fresh init, backfill from flag + marker,
absent signals not recorded.
2026-05-29 12:14:20 -07:00
BoulderBadgeDad
c5b02c0026 DB: normalize legacy comma-separated genres to canonical JSON
artists.genres / albums.genres stored EITHER a JSON array (new writes) OR a
legacy comma-separated string (old writes), forcing every reader to
try-JSON-then-split. Add a marker-gated one-time migration
(_normalize_genres_to_json) that rewrites legacy rows to JSON in place,
mirroring the readers' exact parse (JSON list, else comma-split/strip/
drop-empties) so genre VALUES are unchanged — only the storage format.
Per-row diffed (already-canonical rows untouched, no churn) and non-fatal on
error, consistent with the other migrations. Readers still tolerate both
formats, so this breaks nothing; it just removes the dual-format debt.

Tests: tests/test_db_genres_json_normalization.py — CSV->JSON, JSON-unchanged,
whitespace/empties dropped, albums table, legacy-reader-equivalence,
idempotent re-run, marker set on fresh init.
2026-05-29 12:11:09 -07:00
BoulderBadgeDad
2bb935b9d7 DB: stop watchlist_artists rebuilds from dropping amazon_artist_id
amazon_artist_id is added to watchlist_artists via ALTER (music_database.py
~1732), but both table-rebuild migrations — the spotify_id-nullable fix
(_fix_watchlist_spotify_id_nullable, two CREATE variants) and the
profile-scoped UNIQUE rebuild — recreated the table from a hardcoded column
list that omitted amazon_artist_id. Because shared_cols filters new_cols
against the old table, the column and any stored Amazon artist IDs were
silently dropped on every init (fresh OR upgraded), so Amazon watchlist IDs
never persisted at all.

Fix: add amazon_artist_id to all three rebuild CREATE schemas, both rebuild
new_cols lists, and the base CREATE TABLE (so fresh installs are consistent
and don't rely on the ALTER). Purely additive, column-named inserts + Row
factory mean column position is irrelevant.

Tests (tests/test_db_watchlist_amazon_id_migration.py): drive the real
migrations via MusicDatabase() against a seeded pre-migration temp DB and
assert the column + data survive; differential-proven to FAIL pre-fix.
2026-05-29 12:04:11 -07:00
BoulderBadgeDad
9b34d06b6d UI: migrate remaining compact button families to the .btn--sm tier
Continue the design-system unification (kettui UI-consistency item):
migrate the five remaining compact button families onto the shared
.btn .btn--sm primitive + color modifiers, and drop their bespoke base
CSS (net -125 lines of CSS).

- ya-header-btn (Your Albums/Artists, discover.js-injected) -> .btn .btn--sm
  .btn--secondary; ya-refresh/ya-settings/ya-viewall co-modifiers kept.
- explorer-action-btn (Playlist Explorer) -> .btn--secondary / .btn--primary.
- repair-bulk-btn -> .btn--secondary / .btn--primary / .btn--warning (fix-all).
- enhanced-bulk-btn (Library bulk bar, library.js-injected) -> .btn--primary/
  --secondary/--danger; class kept as a hook for the mobile.css size
  override + the .tag-write / .rg-analyze special colors.
- profile-create-btn (init.js-injected) -> .btn .btn--block .btn--primary;
  class kept for the scoped .profile-edit-buttons flex:1 rule.

mini-nav-btn deliberately left as a distinct icon-button archetype.
2026-05-29 11:40:31 -07:00
BoulderBadgeDad
169c30fd5b UI: add .btn--sm/.btn--block/.btn--warning tier; migrate sync-history buttons
Formalize the compact 'toolbar' button tier as design-system modifiers
(.btn--sm), plus a full-width (.btn--block) and amber caution
(.btn--warning) modifier, so the many smaller per-page buttons can share
the .btn primitive without being forced to the large default size.

First adopter: the Sync page header buttons (.sync-history-btn) now use
.btn .btn--sm .btn--secondary. The class is kept as a JS/onboarding
selector hook; .auto-sync-manager-btn still tints Auto-Sync accent.
2026-05-29 11:30:13 -07:00
BoulderBadgeDad
ae0968e1b0 UI: migrate watchlist/wishlist action buttons to the shared .btn primitive
The watchlist + wishlist header/overview buttons used a bespoke
.watchlist-action-btn family (different padding/radius/font and white
primary text) instead of the shared .btn design-system primitive.
Migrate all 11 of them to .btn / .btn--primary / .btn--secondary /
.btn--danger so they match the rest of the app, and drop the now-dead
CSS.

The .watchlist-batch-remove-btn / .wishlist-batch-remove-btn hook
classes are kept on the remove buttons (their !important red overrides
compose correctly over .btn--secondary). Static HTML only; no JS-injected
usages, and mobile.css overrides target .playlist-modal-btn, not these.
2026-05-29 11:18:19 -07:00
BoulderBadgeDad
a42f8ecc10 UI: move Downloads above Automations in the sidebar
Reorder the sidebar nav so Downloads sits between Wishlist and
Automations. Mobile nav reuses the same .nav-button elements and the
helper/onboarding references are selector-keyed, so no other changes
are needed.
2026-05-29 11:07:09 -07:00