Commit Graph

144 Commits

Author SHA1 Message Date
bvandeusen 3d23f4930c feat(scrobble): add pure ListenBrainz HTTP client with typed errors
Implements the HTTP client for ListenBrainz submit-listens with typed
sentinel errors (ErrAuth, ErrPermanent, ErrTransient, *RetryAfterError)
so the scrobble worker can branch on response semantics. All 9 httptest-
driven tests pass.
2026-04-28 08:45:13 -04:00
bvandeusen a0e21f21b6 feat(db): add ListenBrainz user-config and scrobble_queue queries 2026-04-28 08:42:38 -04:00
bvandeusen efc2308348 feat(db): add migration 0008 for scrobble (users LB columns + scrobble_queue table) 2026-04-28 08:40:39 -04:00
bvandeusen 95d68e3d3d feat: M3.5 polish — genre splitting + radio button surface
Two carry-overs from M3 verification, bundled with the search-input
fix already on dev (b7a59a9).

1. Genre splitting in BuildSessionVector
   The library has many tracks whose genre tag is a denormalized
   multi-genre string ("Indie Pop; Pop; Alternative Pop"). Reading them
   as one opaque tag means a single-genre "Pop" track and a multi-genre
   track listing Pop both fail to share the Pop key, so the tags axis
   in similarity scoring (weight 0.7!) returned 0 in nearly all cases
   on real libraries. Result: contextual scoring couldn't differentiate.

   Add splitGenres() that splits on ; and , and trims whitespace;
   strings without a delimiter come back as a single-element slice
   (so the existing single-genre cases keep working unchanged).
   Concatenated-without-separator output ("ElectronicComplextroGlitch
   Hop") stays opaque — that needs a genre dictionary, out of scope.

2. Play-radio button on TrackRow
   playRadio() was only wired to the click handler on /search and
   /search/tracks, leaving /library/liked, album pages, and search
   results' inner clicks with no way to start a radio. Adds a small
   radio button to TrackRow (between LikeButton and the +queue button).
   Click → playRadio(track.id), with stopPropagation so the row's own
   activate handler doesn't also fire.

Tests:
- 3 new sessionvector tests: TestSplitGenres, multi-genre semicolon
  split, no-separator stays opaque. Existing single-genre tests pass
  unchanged.
- 1 new TrackRow test: radio button calls playRadio with track id and
  does NOT trigger row play.

Verified locally: go -short -race ./... clean, golangci-lint clean,
svelte-check 0/0, 175 vitest tests (was 174), web build succeeds.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-27 23:50:00 -04:00
bvandeusen ad56eb279f style(recommendation): drop trailing comments that gofmt-1.23 wants aligned
CI's golangci-lint (`gofmt -s`) on Go 1.23 flagged inline comments after
the SessionVector literals in TestContextualMatchScore_TakesMax because
the variable-length values produced misaligned trailing columns. Local
gofmt on Go 1.26 was lenient. Replace with a leading comment that covers
all three rows; same intent, no alignment dance.
2026-04-27 22:41:24 -04:00
bvandeusen 22622f3065 test(api): end-to-end contextual ranking test for /api/radio
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 21:20:01 -04:00
bvandeusen 284271c190 feat(api): radio handler reads current session vector + threads ContextWeight
Wire contextual scoring end-to-end: add ContextWeight to RecommendationConfig
(struct + Default()), fetch the user's current session vector in handleRadio
via loadCurrentSessionVector (cold-start returns Seed sentinel), and pass it
as the 6th arg to LoadCandidates so ContextualMatchScore flows into Shuffle.
2026-04-27 20:55:25 -04:00
bvandeusen 541698a8b1 test(recommendation): check LoadCandidates errors in new contextual tests
Code review caught four tests using `got, _` to discard load errors. A DB
failure would have surfaced as a misleading "wrong score" assertion rather
than a clear "load failed" message. Match the t.Fatalf pattern used by the
other LoadCandidates tests in this file.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-27 20:51:55 -04:00
bvandeusen 5b79aa1047 feat(recommendation): LoadCandidates computes per-candidate ContextualMatchScore
Adds a 6th argument (currentVector SessionVector) to LoadCandidates,
bulk-fetches the user's active contextual_likes in one query, and sets
ContextualMatchScore on each candidate's ScoringInputs via max-similarity
over that candidate's like vectors. Adds helper + 6 integration tests
covering no-likes, single match, multi-like max, soft-delete filtering,
seed-like filtering, and seed-current short-circuit. Adds contextual_likes
to the TRUNCATE list in testPool to prevent cross-test leakage.

internal/api/radio.go is intentionally left broken (Task 6 fixes it).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 20:41:55 -04:00
bvandeusen cb46b3830f feat(db): add similarity lookup queries (ListActiveContextualLikesForUser, GetCurrentSessionVectorForUser) 2026-04-27 20:36:42 -04:00
bvandeusen 49871ba06d feat(recommendation): extend Score with ContextualMatchScore + ContextWeight 2026-04-27 20:31:54 -04:00
bvandeusen 347884bc2b feat(recommendation): add ContextualMatchScore (max over non-seed likes) 2026-04-27 20:20:53 -04:00
bvandeusen a7211aacff feat(recommendation): add pure Similarity function with weighted Jaccard 2026-04-27 20:04:35 -04:00
bvandeusen bf7c5ad47d feat(subsonic): wire contextual_likes capture/soft-delete into star/unstar
handleStar's track branch calls playevents.CaptureContextualLikeIfPlaying
when the underlying LikeTrack actually inserted a row. handleUnstar
calls SoftDeleteContextualLikes after every track-id unstar. Same
helpers as the api surface — single source of truth.

mediaHandlers struct gains a logger field threaded through Mount.
2026-04-27 11:25:10 -04:00
bvandeusen fe1cc46752 feat(api): capture contextual_likes on like during open play_event
Two new helpers in internal/playevents (CaptureContextualLikeIfPlaying,
SoftDeleteContextualLikes) called by both api and subsonic surfaces.
Like inserts a new contextual_likes row when LikeTrack actually
inserted (rows=1) AND there's an open play_event with a vector.
Unlike soft-deletes via deleted_at. Idempotent in both directions.

Subsonic wiring lands in the next commit.
2026-04-27 11:22:35 -04:00
bvandeusen d6acb3b63c feat(playevents): persist session_vector_at_play on every record path
RecordPlayStarted and RecordSyntheticCompletedPlay both capture the
session vector inside their existing transactions. Single private
helper queries the prior 5 tracks, builds the vector, UPDATEs the
just-inserted play_event. Tests verify the seed flag boundary and
session-scope isolation.
2026-04-27 11:19:16 -04:00
bvandeusen 627b7d1be5 feat(recommendation): add BuildSessionVector pure function
Pure aggregation per spec §6: Seed flag (true when prior < 3),
deduplicated Artists ordered by first appearance, Tags bag-of-counts
from tracks.genre (empty genres skipped), RecentTrackIDs preserving
input order. JSON round-trip verified.
2026-04-27 11:17:11 -04:00
bvandeusen d43d8df6d5 feat(db): add session-vector capture queries; LikeTrack returns row count
ListRecentSessionTracks + UpdatePlayEventVector for the vector capture
path inside RecordPlayStarted. LikeTrack switches to :execrows so the
contextual-likes capture can detect insert vs already-exists. Existing
callers updated to ignore the count for now; later tasks consume it.
2026-04-27 11:16:05 -04:00
bvandeusen 92ef53c04d feat(db): add contextual_likes table (M3 session-context capture)
Table was referenced in migration 0005's comment but never created —
this slice fills the gap. Soft-delete via deleted_at column; hot-path
partial index on active rows; GIN index on session_vector for
M3 sub-plan #3's similarity queries.
2026-04-27 11:13:31 -04:00
bvandeusen 08591debee feat(api): rewrite /api/radio with weighted shuffle v1
Validates seed_track + optional limit (default cfg.Recommendation.RadioSize,
clamped to RadioSizeMax). Calls recommendation.LoadCandidates +
recommendation.Shuffle. Prepends seed to result. Server seeds a
math/rand source at startup; handlers package threads that as a
func() float64 so tests inject deterministic RNGs.

Mount + server.New gain a RecommendationConfig parameter.
2026-04-27 08:08:10 -04:00
bvandeusen 9426dc2eeb feat(config): add recommendation section (weighted shuffle weights)
BaseWeight, LikeBoost, RecencyWeight, SkipPenalty, JitterMagnitude,
RecentlyPlayedHours, RadioSize, RadioSizeMax. Defaults match spec §6.
2026-04-27 08:04:23 -04:00
bvandeusen b513c91520 feat(recommendation): add LoadCandidates DB-backed loader
Wraps the LoadRadioCandidates sqlc query, projects rows to
[]Candidate. Live-DB tests verify seed exclusion, recently-played
exclusion, stat-join correctness (likes + plays + skips +
last_played_at), and cross-user isolation.
2026-04-27 08:03:20 -04:00
bvandeusen 3ef560e414 feat(db): add LoadRadioCandidates query
Single SELECT that joins tracks with general_likes (for is_liked) and
an aggregated LATERAL subquery on play_events (for last_played_at,
play_count, skip_count). Excludes seed + tracks played in the last
N hours. Drives the M3 weighted shuffle scoring.
2026-04-27 08:01:50 -04:00
bvandeusen 8c3d06c0a1 feat(recommendation): add Shuffle orchestrator
Composes Score over a candidate slice, sorts descending, truncates.
Pure — no IO. Liked-rank-higher and high-skip-ranks-last behaviors
are stable across RNG seeds (jitter band is smaller than LikeBoost
and SkipPenalty).
2026-04-27 07:39:16 -04:00
bvandeusen 546234187f feat(recommendation): add pure Score function with recency + skip + jitter
Implements spec §6 weighted-shuffle scoring without the
contextual_match_score term (sub-plan #3 adds it). Pure Go, no DB
dependency; injectable RNG for deterministic tests. Coverage 100%
on score.go via the boundary tests.
2026-04-27 07:38:07 -04:00
bvandeusen c7f4adbcc3 feat(subsonic): add getStarred and getStarred2 handlers
Both return user's starred artists/albums/songs sorted liked_at DESC.
Cap at 500 entries per category for v1 (Subsonic spec doesn't define
pagination on these endpoints; M3+ can revisit if needed).
2026-04-26 16:45:04 -04:00
bvandeusen 32fb3fec20 feat(subsonic): add /rest/star and /rest/unstar handlers
Validate-all-first atomicity on star: a missing entity refuses the whole
call with Subsonic error 70. Unstar is a best-effort delete (missing
entities are no-ops, matching client expectations after library moves).
2026-04-26 16:43:20 -04:00
bvandeusen 61d96bb288 feat(api): add /api/likes/{tracks,albums,artists} endpoints
Like/unlike are POST/DELETE on /api/likes/{type}/{id}; idempotent (204
on repeats). List endpoints return Page<TrackRef|AlbumRef|ArtistRef>
sorted liked_at DESC. /api/likes/ids returns flat id arrays for the
client-side heart-button cache.
2026-04-26 16:23:04 -04:00
bvandeusen 780beaa248 feat(db): add M2 likes schema (general_likes, _albums, _artists)
Three tables keyed on (user_id, entity_id) with liked_at. Per-table
indexes on (user_id, liked_at DESC) for the recently-liked feed.
sqlc queries cover like/unlike/list-rows/count/list-ids per entity.
2026-04-26 16:20:08 -04:00
bvandeusen 599a19f780 feat(subsonic): wire /rest/scrobble into playevents.Writer
submission=false → play_started (replaces in-memory nowPlayingMap).
submission=true (default) → synthetic completed play. The nowPlayingMap
struct + factory + the nowPlaying field on mediaHandlers are deleted;
play_events WHERE ended_at IS NULL is now the source of truth for
'currently playing,' reachable from M3+ work.

api.Mount now takes the shared *playevents.Writer instead of cfg so
the same writer instance feeds both surfaces.
2026-04-26 00:23:20 -04:00
bvandeusen f4e73b81b4 feat(api): add POST /api/events handler
Discriminated-union JSON over three event types: play_started,
play_ended, play_skipped. Auth via existing RequireUser. play_started
returns play_event_id + session_id; the other two return { ok: true }.
Validates ownership: play_ended/play_skipped on another user's row
returns 403. Mount signature now takes EventsConfig and constructs
the playevents.Writer; server.New propagates it through.
2026-04-26 00:12:06 -04:00
bvandeusen 0c7e1b0408 feat(playevents): add Writer with start/end/skipped/synthetic paths
Owns the auto-close-prior step (caps each user at one open row),
spec §6 skip classification rule on play_ended (AND of completion <
0.5 and duration_played < 30s), and skip_events row writes. Synthetic
completed play wires the Subsonic /rest/scrobble?submission=true path
into the same store as native events.
2026-04-26 00:10:02 -04:00
bvandeusen 73d3962fff feat(playsessions): add FindOrCreate session service (30-min rolling window)
Per spec §6: returns existing session id when last_event_at is within
timeout; inserts a new session otherwise. Touch updates last_event_at
and increments track_count so callers can assume FindOrCreate == one
play started.
2026-04-25 22:30:12 -04:00
bvandeusen 722a6784a7 feat(config): add events section (session timeout + skip rule thresholds) 2026-04-25 20:46:23 -04:00
bvandeusen 4fcf2c9616 feat(db): add M2 schema — play_sessions, play_events, skip_events
Tables and indexes per spec §5. session_vector_at_play ships nullable
so M3 doesn't need a follow-up migration. Table is named play_sessions
to avoid collision with the existing sessions (HTTP auth) table from
migration 0004.
2026-04-25 20:45:44 -04:00
bvandeusen 1e66910823 feat(api): add /api/radio stub returning the seed track only
M6 stub. Validates seed_track param (400 on missing/blank/bad UUID),
looks up the track (404 on miss), returns RadioResponse with a single
TrackRef. M4 will replace the body with similarity-driven candidate
pool + scoring; the request/response shape is final.
2026-04-25 15:01:39 -04:00
bvandeusen 75ce65c80e feat(server): serve embedded SPA at root with /api,/rest carve-out
- NotFound wrapper routes unknown /api/* and /rest/* to a JSON 404
- Everything else falls through to the embedded web handler, which
  resolves static assets or returns index.html for SPA deep links
2026-04-22 10:31:30 -04:00
bvandeusen 8fe4a5f578 refactor(web): move embed package to web/ so go:embed reaches build/
go:embed paths are relative to the source file and cannot reach parent
directories, so internal/web/embed.go could not see web/build/ without
duplicating the placeholder. Relocating to web/embed.go lets the
directive resolve to the real SvelteKit build output with no copy step.
2026-04-22 10:29:31 -04:00
bvandeusen d5692a73ca feat(web): embed SvelteKit build output with SPA fallback handler
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 10:26:36 -04:00
bvandeusen 8600b253fd style: gofmt fixes across api package
CI's golangci-lint run flagged three files; two pre-existed this
branch but the Plan 3 seedTrackWithFile struct-literal alignment
is new. Applying gofmt across all three keeps the lint baseline clean.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-21 23:02:20 -04:00
bvandeusen 63d3e234d9 feat(api): register cover + stream routes under RequireUser 2026-04-21 22:48:45 -04:00
bvandeusen 3656461b20 feat(api): GET /api/tracks/{id}/stream with Range support
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-21 22:44:48 -04:00
bvandeusen 945b773cbd feat(api): GET /api/albums/{id}/cover with sidecar fallback 2026-04-21 22:37:53 -04:00
bvandeusen 5af6d7fac6 docs(api): document intentional audioContentType divergence from subsonic 2026-04-21 22:35:29 -04:00
bvandeusen c799e5c1c9 feat(api): scaffold media helpers for cover + stream endpoints 2026-04-21 22:30:25 -04:00
bvandeusen b94b7514f9 fix(api): clamp negative offset instead of erroring + clarify duration_sec=0
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-21 19:27:21 -04:00
bvandeusen db2ee3b21f feat(api): register library + search routes under RequireUser 2026-04-21 08:34:12 -04:00
bvandeusen 683c11661b feat(api): GET /api/search with three paged facets
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 08:29:28 -04:00
bvandeusen 8fb2f4e184 feat(api): GET /api/artists with alpha/newest sort and paging
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 08:06:03 -04:00
bvandeusen f37fd782af feat(api): GET /api/artists/{id} with nested albums 2026-04-21 08:01:25 -04:00