From 104f9fd1413db5fbfdcc1a0fa23fad905762a363 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 24 Nov 2026 18:10:08 -0500 Subject: [PATCH] feat: Your genres leads with the genres you play most, not A to Z The genre mix builder already ranks genres by how much you listen to them (taste profile, then plays and likes, then library size), but the rank was lost when the mixes were stored and both apps sorted the shelf by name. Each playlist now has a shelf_rank (migration 0107), which the genre builder fills 1..n in that listening order, even where it picked a narrower genre before a broader one. The list and detail endpoints carry it, and the web and Android Home sort the genre shelf by it, unranked playlists after by name. Android's playlist cache gains the column (Room v14). Co-Authored-By: Claude Opus 5.5 --- .../minstrel/cache/db/AppDatabase.kt | 14 ++++++++- .../minstrel/cache/db/DatabaseModule.kt | 9 +++++- .../cache/db/entities/CachedPlaylistEntity.kt | 3 ++ .../minstrel/home/ui/HomeScreen.kt | 11 +++---- .../fabledsword/minstrel/models/Playlist.kt | 2 ++ .../minstrel/models/wire/PlaylistWire.kt | 6 ++++ .../fabledsword/minstrel/playlists/Shelf.kt | 9 ++++++ .../playlists/data/PlaylistsRepository.kt | 4 +++ .../minstrel/home/ui/BuildPlaylistsRowTest.kt | 17 ++++++++++- .../data/PlaylistsRepositoryCacheMergeTest.kt | 6 ++++ internal/api/playlists.go | 13 ++++++--- internal/db/dbq/models.go | 1 + internal/db/dbq/playlists.sql.go | 17 +++++++---- internal/db/dbq/system_playlists.sql.go | 12 +++++--- .../0107_playlist_shelf_rank.down.sql | 1 + .../0107_playlist_shelf_rank.up.sql | 6 ++++ internal/db/queries/system_playlists.sql | 7 +++-- internal/playlists/genre_mixes.go | 21 ++++++++++++++ internal/playlists/genre_mixes_test.go | 21 ++++++++++++++ internal/playlists/service.go | 13 ++++++--- internal/playlists/system.go | 20 +++++++------ web/src/lib/api/types.ts | 4 +++ web/src/lib/playlists/shelf.test.ts | 29 ++++++++++++++++++- web/src/lib/playlists/shelf.ts | 9 ++++++ web/src/routes/+page.svelte | 6 ++-- 25 files changed, 220 insertions(+), 41 deletions(-) create mode 100644 internal/db/migrations/0107_playlist_shelf_rank.down.sql create mode 100644 internal/db/migrations/0107_playlist_shelf_rank.up.sql diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/AppDatabase.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/AppDatabase.kt index 341e58f2..e6f2f0c9 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/AppDatabase.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/AppDatabase.kt @@ -67,6 +67,8 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity CachedNotificationEntity::class, CachedNotificationSettingsEntity::class, ], + // v14: + cached_playlists.shelfRank, a system mix's place on its Home + // shelf. MIGRATION_13_14 adds it as 0; the next list refresh fills it. // v13: + cached_playlists.coverAlbumIds and createdAt, the albums Home's // shelves draw each playlist tile's picture from and when a mix was // rebuilt. MIGRATION_12_13 adds both empty; the next list refresh fills them. @@ -90,7 +92,7 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity // on auth_session. Versions before v8 rebuild destructively, which is // right for them: the next sync refills every row with the new // columns populated, so there is nothing to migrate by hand. - version = 13, + version = 14, exportSchema = true, ) @TypeConverters(MinstrelTypeConverters::class) @@ -176,3 +178,13 @@ val MIGRATION_12_13: Migration = object : Migration(12, 13) { db.execSQL("ALTER TABLE cached_playlists ADD COLUMN createdAt TEXT NOT NULL DEFAULT ''") } } + +/** + * v13 → v14: a playlist's place on its Home shelf. Starts at 0 (unranked); + * Home refreshes the playlist list on open, which fills it. + */ +val MIGRATION_13_14: Migration = object : Migration(13, 14) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE cached_playlists ADD COLUMN shelfRank INTEGER NOT NULL DEFAULT 0") + } +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/DatabaseModule.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/DatabaseModule.kt index 9f976424..794f5181 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/DatabaseModule.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/DatabaseModule.kt @@ -37,7 +37,14 @@ object DatabaseModule { // and rebuilds. The sync controller refills the cache from the // server on first launch, so a rebuild loses only the unsynced // mutation queue. - .addMigrations(MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13) + .addMigrations( + MIGRATION_8_9, + MIGRATION_9_10, + MIGRATION_10_11, + MIGRATION_11_12, + MIGRATION_12_13, + MIGRATION_13_14, + ) .fallbackToDestructiveMigration(dropAllTables = true) .build() diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/entities/CachedPlaylistEntity.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/entities/CachedPlaylistEntity.kt index d251fe5d..7b51dca7 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/entities/CachedPlaylistEntity.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/entities/CachedPlaylistEntity.kt @@ -35,4 +35,7 @@ data class CachedPlaylistEntity( /** ISO-8601 creation time; for a system mix, when it was last rebuilt. */ @ColumnInfo(defaultValue = "''") val createdAt: String = "", + /** Place on its Home shelf, 1 first; 0 when unranked. */ + @ColumnInfo(defaultValue = "0") + val shelfRank: Int = 0, ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/home/ui/HomeScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/home/ui/HomeScreen.kt index 27f08422..54111f02 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/home/ui/HomeScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/home/ui/HomeScreen.kt @@ -83,6 +83,7 @@ import com.fabledsword.minstrel.nav.ArtistDetail import com.fabledsword.minstrel.nav.Home import com.fabledsword.minstrel.nav.PlaylistDetail import com.fabledsword.minstrel.playlists.assignShelfCovers +import com.fabledsword.minstrel.playlists.byShelfRank import com.fabledsword.minstrel.playlists.data.PlaylistsRepository import com.fabledsword.minstrel.playlists.data.playPlaylistShuffled import com.fabledsword.minstrel.playlists.shelfMeta @@ -1340,10 +1341,10 @@ internal fun buildSongsLikeRow( } /** - * Builds the "Your genres" row: every genre mix, in name order so the - * shelf reads like a stable channel list. No placeholders — a genre mix - * needs listening history or a genre-tagged library, so none built means - * nothing to show. Offline, fully-cached mixes come first and the rest are + * Builds the "Your genres" row: every genre mix, the genres the listener + * plays most first ([byShelfRank], the server's shelf_rank). No + * placeholders — a genre mix needs listening history or a genre-tagged + * library, so none built means nothing to show. Offline, fully-cached mixes come first and the rest are * greyed. Mirrors the web Home's genreMixPlaylists. */ internal fun buildGenreMixRow( @@ -1352,7 +1353,7 @@ internal fun buildGenreMixRow( ): List { val mixes = owned .filter { it.systemVariant == "genre_mix" } - .sortedBy { it.name.lowercase() } + .sortedWith(byShelfRank) if (!offline) return mixes.map { PlaylistRowItem.Real(it) } val (available, greyed) = mixes.partition { !it.unavailableOffline } return (available + greyed).map { PlaylistRowItem.Real(it) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/Playlist.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/Playlist.kt index cd895fac..ab12f7b6 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/Playlist.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/models/Playlist.kt @@ -28,6 +28,8 @@ data class PlaylistRef( val coverAlbumIds: List = emptyList(), /** ISO-8601. A system mix is rebuilt in place, so this is when it was last refreshed. */ val createdAt: String = "", + /** Place on its Home shelf, 1 first; 0 when the app orders it itself. See playlists/Shelf.kt byShelfRank. */ + val shelfRank: Int = 0, ) { val isSystem: Boolean get() = systemVariant != null diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/wire/PlaylistWire.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/wire/PlaylistWire.kt index 586cf0c5..865a6f8e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/wire/PlaylistWire.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/models/wire/PlaylistWire.kt @@ -28,6 +28,11 @@ data class PlaylistWire( * the playlist. Home's shelves pick each tile's picture from these. */ @SerialName("cover_album_ids") val coverAlbumIds: List = emptyList(), + /** + * A system mix's place on its Home shelf, 1 first: genre mixes are + * numbered by how much the listener plays each genre. 0 when unranked. + */ + @SerialName("shelf_rank") val shelfRank: Int = 0, ) /** @@ -86,5 +91,6 @@ data class PlaylistDetailWire( @SerialName("owner_username") val ownerUsername: String = "", @SerialName("created_at") val createdAt: String = "", @SerialName("cover_album_ids") val coverAlbumIds: List = emptyList(), + @SerialName("shelf_rank") val shelfRank: Int = 0, val tracks: List = emptyList(), ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/Shelf.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/Shelf.kt index c2e5c872..1495010a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/Shelf.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/Shelf.kt @@ -88,6 +88,15 @@ fun shelfMeta( return parts.joinToString(" · ").replaceFirstChar { it.uppercase() } } +/** + * Orders a shelf by the rank the server gave each mix (1 first; genre mixes + * lead with the genres the listener plays most). Unranked playlists follow in + * name order, as do ranked ones should two share a rank. + */ +val byShelfRank: Comparator = + compareBy { if (it.shelfRank > 0) it.shelfRank else Int.MAX_VALUE } + .thenBy { it.name.lowercase(Locale.getDefault()) } + /** * "Songs like Low Tide Choir" → "Low Tide Choir": a Songs like tile labels * the artist under its circle, so the prefix would only repeat the shelf. diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepository.kt index 2849a99b..c7a259c0 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepository.kt @@ -265,6 +265,7 @@ private fun CachedPlaylistEntity.toDomain(): PlaylistRef = trackCount = trackCount, coverAlbumIds = coverAlbumIds.split(',').filter { it.isNotEmpty() }, createdAt = createdAt, + shelfRank = shelfRank, // Server returns a relative cover path like "/api/playlists//cover"; // wrap through the placeholder host so BaseUrlInterceptor + the shared // Coil/OkHttpClient resolve it against the live server. Without this @@ -284,6 +285,7 @@ private fun PlaylistWire.toEntity(): CachedPlaylistEntity = systemVariant = systemVariant, coverAlbumIds = coverAlbumIds.joinToString(","), createdAt = createdAt, + shelfRank = shelfRank, ) private fun PlaylistDetailWire.toPlaylistEntity(): CachedPlaylistEntity = @@ -298,6 +300,7 @@ private fun PlaylistDetailWire.toPlaylistEntity(): CachedPlaylistEntity = systemVariant = systemVariant, coverAlbumIds = coverAlbumIds.joinToString(","), createdAt = createdAt, + shelfRank = shelfRank, ) private fun PlaylistDetailWire.toPlaylistRef(): PlaylistRef = @@ -316,6 +319,7 @@ private fun PlaylistDetailWire.toPlaylistRef(): PlaylistRef = ownerUsername = ownerUsername, coverAlbumIds = coverAlbumIds, createdAt = createdAt, + shelfRank = shelfRank, ) private fun PlaylistTrackWire.toDomain(): PlaylistTrackRef = diff --git a/android/app/src/test/java/com/fabledsword/minstrel/home/ui/BuildPlaylistsRowTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/home/ui/BuildPlaylistsRowTest.kt index a686bb99..aacbda94 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/home/ui/BuildPlaylistsRowTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/home/ui/BuildPlaylistsRowTest.kt @@ -105,13 +105,14 @@ class BuildPlaylistsRowTest { assertTrue(buildSongsLikeRow(emptyList(), SystemPlaylistsStatus(), offline = true).isEmpty()) } - private fun genreMix(name: String, cached: Boolean) = PlaylistRef( + private fun genreMix(name: String, cached: Boolean, rank: Int = 0) = PlaylistRef( id = name, userId = "u", name = name, systemVariant = "genre_mix", trackCount = 50, fullyCached = cached, + shelfRank = rank, ) @Test @@ -131,6 +132,20 @@ class BuildPlaylistsRowTest { assertEquals(listOf("u1"), carousel) } + @Test + fun `ranked genre mixes lead with the genre played most, the unranked follow by name`() { + val owned = listOf( + genreMix("Ambient mix", cached = true, rank = 3), + genreMix("Zydeco mix", cached = true), + genreMix("Pop mix", cached = true, rank = 1), + genreMix("Blues mix", cached = true), + genreMix("Jazz mix", cached = true, rank = 2), + ) + val names = buildGenreMixRow(owned, offline = false) + .filterIsInstance().map { it.playlist.name } + assertEquals(listOf("Pop mix", "Jazz mix", "Ambient mix", "Blues mix", "Zydeco mix"), names) + } + @Test fun `genre mixes are not refreshable, so a cached one plays offline`() { assertFalse(genreMix("Jazz mix", cached = true).refreshable) diff --git a/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryCacheMergeTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryCacheMergeTest.kt index 1a495f6c..e39bc5d5 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryCacheMergeTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryCacheMergeTest.kt @@ -70,6 +70,12 @@ class PlaylistsRepositoryCacheMergeTest { assertEquals("2026-11-23T08:00:00Z", out.createdAt) } + @Test + fun `a genre mix keeps its shelf rank through the cache`() { + val row = playlist("p", trackCount = 3).copy(shelfRank = 2) + assertEquals(2, mergePlaylistsWithCache(rows = listOf(row), counts = emptyList()).single().shelfRank) + } + @Test fun `a row cached before cover albums existed has none`() { val out = mergePlaylistsWithCache(rows = listOf(playlist("p", trackCount = 3)), counts = emptyList()) diff --git a/internal/api/playlists.go b/internal/api/playlists.go index 6e797c3a..97efecf6 100644 --- a/internal/api/playlists.go +++ b/internal/api/playlists.go @@ -45,10 +45,14 @@ type playlistRowView struct { // before it already shows, so no cover repeats along the shelf. // Omitted when the playlist has none. CoverAlbumIDs []string `json:"cover_album_ids,omitempty"` - TrackCount int32 `json:"track_count"` - DurationSec int32 `json:"duration_sec"` - CreatedAt string `json:"created_at"` - UpdatedAt string `json:"updated_at"` + // ShelfRank is a system mix's place on its Home shelf, 1 first: genre + // mixes are numbered by how much the user listens to each genre. + // Omitted (0) for playlists the client orders itself. + ShelfRank int32 `json:"shelf_rank,omitempty"` + TrackCount int32 `json:"track_count"` + DurationSec int32 `json:"duration_sec"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` } // playlistTrackView is one row of a playlist's track list on the wire. @@ -453,6 +457,7 @@ func playlistRowToView(r *playlists.PlaylistRow) playlistRowView { Kind: r.Kind, SystemVariant: r.SystemVariant, Refreshable: r.SystemVariant != nil && playlists.RefreshableSystemKind(*r.SystemVariant), + ShelfRank: r.ShelfRank, TrackCount: r.TrackCount, DurationSec: r.DurationSec, CreatedAt: formatTimestamp(r.CreatedAt), diff --git a/internal/db/dbq/models.go b/internal/db/dbq/models.go index 050af6b6..25027583 100644 --- a/internal/db/dbq/models.go +++ b/internal/db/dbq/models.go @@ -448,6 +448,7 @@ type Playlist struct { Kind string SystemVariant *string SeedArtistID pgtype.UUID + ShelfRank int32 } type PlaylistTrack struct { diff --git a/internal/db/dbq/playlists.sql.go b/internal/db/dbq/playlists.sql.go index 6c19e2df..f9b136ea 100644 --- a/internal/db/dbq/playlists.sql.go +++ b/internal/db/dbq/playlists.sql.go @@ -59,7 +59,7 @@ func (q *Queries) AppendPlaylistTrack(ctx context.Context, arg AppendPlaylistTra const createPlaylist = `-- name: CreatePlaylist :one INSERT INTO playlists (user_id, name, description, is_public) VALUES ($1, $2, $3, $4) -RETURNING id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id +RETURNING id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id, shelf_rank ` type CreatePlaylistParams struct { @@ -91,6 +91,7 @@ func (q *Queries) CreatePlaylist(ctx context.Context, arg CreatePlaylistParams) &i.Kind, &i.SystemVariant, &i.SeedArtistID, + &i.ShelfRank, ) return i, err } @@ -132,7 +133,7 @@ func (q *Queries) DeletePlaylistTrack(ctx context.Context, arg DeletePlaylistTra } const getPlaylist = `-- name: GetPlaylist :one -SELECT p.id, p.user_id, p.name, p.description, p.is_public, p.cover_path, p.track_count, p.duration_sec, p.created_at, p.updated_at, p.kind, p.system_variant, p.seed_artist_id, u.username AS owner_username +SELECT p.id, p.user_id, p.name, p.description, p.is_public, p.cover_path, p.track_count, p.duration_sec, p.created_at, p.updated_at, p.kind, p.system_variant, p.seed_artist_id, p.shelf_rank, u.username AS owner_username FROM playlists p JOIN users u ON u.id = p.user_id WHERE p.id = $1 @@ -152,6 +153,7 @@ type GetPlaylistRow struct { Kind string SystemVariant *string SeedArtistID pgtype.UUID + ShelfRank int32 OwnerUsername string } @@ -172,13 +174,14 @@ func (q *Queries) GetPlaylist(ctx context.Context, id pgtype.UUID) (GetPlaylistR &i.Kind, &i.SystemVariant, &i.SeedArtistID, + &i.ShelfRank, &i.OwnerUsername, ) return i, err } const getPlaylistsByIDs = `-- name: GetPlaylistsByIDs :many -SELECT id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id FROM playlists WHERE id = ANY($1::uuid[]) +SELECT id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id, shelf_rank FROM playlists WHERE id = ANY($1::uuid[]) ` // Batched lookup used by /api/library/sync to hydrate upsert payloads @@ -206,6 +209,7 @@ func (q *Queries) GetPlaylistsByIDs(ctx context.Context, dollar_1 []pgtype.UUID) &i.Kind, &i.SystemVariant, &i.SeedArtistID, + &i.ShelfRank, ); err != nil { return nil, err } @@ -380,7 +384,7 @@ func (q *Queries) ListPlaylistTracks(ctx context.Context, playlistID pgtype.UUID } const listPlaylistsForUser = `-- name: ListPlaylistsForUser :many -SELECT p.id, p.user_id, p.name, p.description, p.is_public, p.cover_path, p.track_count, p.duration_sec, p.created_at, p.updated_at, p.kind, p.system_variant, p.seed_artist_id, u.username AS owner_username +SELECT p.id, p.user_id, p.name, p.description, p.is_public, p.cover_path, p.track_count, p.duration_sec, p.created_at, p.updated_at, p.kind, p.system_variant, p.seed_artist_id, p.shelf_rank, u.username AS owner_username FROM playlists p JOIN users u ON u.id = p.user_id WHERE p.user_id = $1 OR p.is_public = true @@ -401,6 +405,7 @@ type ListPlaylistsForUserRow struct { Kind string SystemVariant *string SeedArtistID pgtype.UUID + ShelfRank int32 OwnerUsername string } @@ -429,6 +434,7 @@ func (q *Queries) ListPlaylistsForUser(ctx context.Context, userID pgtype.UUID) &i.Kind, &i.SystemVariant, &i.SeedArtistID, + &i.ShelfRank, &i.OwnerUsername, ); err != nil { return nil, err @@ -480,7 +486,7 @@ SET is_public = CASE WHEN $5::boolean THEN $6::boolean ELSE is_public END, updated_at = now() WHERE id = $7 -RETURNING id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id +RETURNING id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id, shelf_rank ` type UpdatePlaylistParams struct { @@ -521,6 +527,7 @@ func (q *Queries) UpdatePlaylist(ctx context.Context, arg UpdatePlaylistParams) &i.Kind, &i.SystemVariant, &i.SeedArtistID, + &i.ShelfRank, ) return i, err } diff --git a/internal/db/dbq/system_playlists.sql.go b/internal/db/dbq/system_playlists.sql.go index 0f7e96d2..439177ab 100644 --- a/internal/db/dbq/system_playlists.sql.go +++ b/internal/db/dbq/system_playlists.sql.go @@ -26,9 +26,9 @@ func (q *Queries) ClearStaleSystemPlaylistInFlight(ctx context.Context) error { const createSystemPlaylist = `-- name: CreateSystemPlaylist :one INSERT INTO playlists ( user_id, name, description, is_public, - kind, system_variant, seed_artist_id, cover_path -) VALUES ($1, $2, $6, false, 'system', $3, $4, $5) -RETURNING id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id + kind, system_variant, seed_artist_id, cover_path, shelf_rank +) VALUES ($1, $2, $6, false, 'system', $3, $4, $5, $7) +RETURNING id, user_id, name, description, is_public, cover_path, track_count, duration_sec, created_at, updated_at, kind, system_variant, seed_artist_id, shelf_rank ` type CreateSystemPlaylistParams struct { @@ -38,11 +38,13 @@ type CreateSystemPlaylistParams struct { SeedArtistID pgtype.UUID CoverPath *string Description string + ShelfRank int32 } // Inserts a system-generated playlist. Used by BuildSystemPlaylists. // For 'for_you' variant, pass seed_artist_id as NULL (zero-value pgtype.UUID -// with Valid=false). +// with Valid=false). shelf_rank is the mix's place on its Home shelf, 1 +// first, or 0 for kinds the clients order themselves. func (q *Queries) CreateSystemPlaylist(ctx context.Context, arg CreateSystemPlaylistParams) (Playlist, error) { row := q.db.QueryRow(ctx, createSystemPlaylist, arg.UserID, @@ -51,6 +53,7 @@ func (q *Queries) CreateSystemPlaylist(ctx context.Context, arg CreateSystemPlay arg.SeedArtistID, arg.CoverPath, arg.Description, + arg.ShelfRank, ) var i Playlist err := row.Scan( @@ -67,6 +70,7 @@ func (q *Queries) CreateSystemPlaylist(ctx context.Context, arg CreateSystemPlay &i.Kind, &i.SystemVariant, &i.SeedArtistID, + &i.ShelfRank, ) return i, err } diff --git a/internal/db/migrations/0107_playlist_shelf_rank.down.sql b/internal/db/migrations/0107_playlist_shelf_rank.down.sql new file mode 100644 index 00000000..8c599531 --- /dev/null +++ b/internal/db/migrations/0107_playlist_shelf_rank.down.sql @@ -0,0 +1 @@ +ALTER TABLE playlists DROP COLUMN shelf_rank; diff --git a/internal/db/migrations/0107_playlist_shelf_rank.up.sql b/internal/db/migrations/0107_playlist_shelf_rank.up.sql new file mode 100644 index 00000000..6b4d5d00 --- /dev/null +++ b/internal/db/migrations/0107_playlist_shelf_rank.up.sql @@ -0,0 +1,6 @@ +-- Where a system mix sits on its Home shelf, 1 first. The genre mix builder +-- numbers its mixes by how much the user listens to each genre, so the +-- "Your genres" shelf leads with their main genres rather than reading +-- A to Z. 0 means unranked: every other playlist, which clients order their +-- own way. +ALTER TABLE playlists ADD COLUMN shelf_rank integer NOT NULL DEFAULT 0; diff --git a/internal/db/queries/system_playlists.sql b/internal/db/queries/system_playlists.sql index 23260ba3..3a7ec7db 100644 --- a/internal/db/queries/system_playlists.sql +++ b/internal/db/queries/system_playlists.sql @@ -253,11 +253,12 @@ SELECT id, user_id, name, description, is_public, kind, system_variant, -- name: CreateSystemPlaylist :one -- Inserts a system-generated playlist. Used by BuildSystemPlaylists. -- For 'for_you' variant, pass seed_artist_id as NULL (zero-value pgtype.UUID --- with Valid=false). +-- with Valid=false). shelf_rank is the mix's place on its Home shelf, 1 +-- first, or 0 for kinds the clients order themselves. INSERT INTO playlists ( user_id, name, description, is_public, - kind, system_variant, seed_artist_id, cover_path -) VALUES ($1, $2, sqlc.arg(description), false, 'system', $3, $4, $5) + kind, system_variant, seed_artist_id, cover_path, shelf_rank +) VALUES ($1, $2, sqlc.arg(description), false, 'system', $3, $4, $5, sqlc.arg(shelf_rank)) RETURNING *; -- name: GetSystemPlaylistByVariantForUser :one diff --git a/internal/playlists/genre_mixes.go b/internal/playlists/genre_mixes.go index 2bbc41ca..4ae93f8b 100644 --- a/internal/playlists/genre_mixes.go +++ b/internal/playlists/genre_mixes.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "log/slog" + "sort" "time" "github.com/jackc/pgx/v5/pgtype" @@ -123,6 +124,10 @@ func produceGenreMixes( // shelf does not have yet. It takes tier-3 genres only while the shelf is // below genreMixMinShelf. build is handed the genres kept so far, whose songs // the new mix leaves out. +// +// The mixes it keeps are ranked for the shelf in the candidates' own order +// (tier, then score: the genres the user listens to most first), not in the +// order they were picked, which puts specific genres ahead of broad ones. func selectGenreMixes( cands []genreCandidate, build func(genreCandidate, []string) []rankedCandidate, ) []builtPlaylist { @@ -136,6 +141,7 @@ func selectGenreMixes( owned := map[pgtype.UUID]struct{}{} kept := []string{} var out []builtPlaylist + var picked []int // the candidate index of each mix in out for _, i := range specificFirst(cands, sets) { c := cands[i] if len(out) >= genreMixCount { @@ -160,10 +166,25 @@ func selectGenreMixes( Variant: "genre_mix", Tracks: tracks, }) + picked = append(picked, i) } + rankByCandidate(out, picked) return out } +// rankByCandidate numbers each mix's ShelfRank from 1 by its candidate +// index: the lower the index, the more the user listens to the genre. +func rankByCandidate(out []builtPlaylist, picked []int) { + order := make([]int, len(out)) + for k := range order { + order[k] = k + } + sort.Slice(order, func(a, b int) bool { return picked[order[a]] < picked[order[b]] }) + for rank, k := range order { + out[k].ShelfRank = int32(rank + 1) + } +} + // specificFirst returns the candidates' indexes in rank order, except that // within each tier the broad genres come after the specific ones. func specificFirst(cands []genreCandidate, sets []map[pgtype.UUID]struct{}) []int { diff --git a/internal/playlists/genre_mixes_test.go b/internal/playlists/genre_mixes_test.go index b09f683a..a09e0e2e 100644 --- a/internal/playlists/genre_mixes_test.go +++ b/internal/playlists/genre_mixes_test.go @@ -243,3 +243,24 @@ func TestSelectGenreMixes_LibraryGenresOnlyFillAShortShelf(t *testing.T) { } } } + +// The shelf leads with the genre the user listens to most, even when it was +// picked after narrower ones: Rock ranks first though Pop Punk was built +// before it. +func TestSelectGenreMixes_ShelfRankFollowsListeningNotPickOrder(t *testing.T) { + cands := []genreCandidate{ + genreOf("Rock", 1, songs(1, 1000)), // broad: half its songs are Pop Punk + genreOf("Pop Punk", 1, songs(1, 500)), // specific, so picked first + genreOf("Jazz", 1, songs(3000, 3100)), + } + got := selectGenreMixes(cands, buildN(30)) + if names := labels(got); len(names) != 3 || names[0] != "Pop Punk mix" || names[2] != "Rock mix" { + t.Fatalf("pick order = %v, want Pop Punk first and Rock last", names) + } + want := map[string]int32{"Rock mix": 1, "Pop Punk mix": 2, "Jazz mix": 3} + for _, b := range got { + if b.ShelfRank != want[b.Name] { + t.Errorf("%s shelf rank = %d, want %d", b.Name, b.ShelfRank, want[b.Name]) + } + } +} diff --git a/internal/playlists/service.go b/internal/playlists/service.go index ade73431..89f7a59d 100644 --- a/internal/playlists/service.go +++ b/internal/playlists/service.go @@ -80,10 +80,13 @@ type PlaylistRow struct { // empty for a playlist with no covers, and on the rows Create and // Update return. CoverAlbumIDs []pgtype.UUID - TrackCount int32 - DurationSec int32 - CreatedAt pgtype.Timestamptz - UpdatedAt pgtype.Timestamptz + // ShelfRank is a system mix's place on its Home shelf, 1 first; 0 for + // playlists the clients order themselves. Only genre mixes are ranked. + ShelfRank int32 + TrackCount int32 + DurationSec int32 + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz } // PlaylistDetail extends PlaylistRow with the ordered track list. @@ -605,6 +608,7 @@ func playlistFromGetRow(r dbq.GetPlaylistRow) *PlaylistRow { SystemVariant: r.SystemVariant, SeedArtistID: r.SeedArtistID, CoverPath: r.CoverPath, + ShelfRank: r.ShelfRank, TrackCount: r.TrackCount, DurationSec: r.DurationSec, CreatedAt: r.CreatedAt, @@ -624,6 +628,7 @@ func playlistFromListRow(r dbq.ListPlaylistsForUserRow) *PlaylistRow { SystemVariant: r.SystemVariant, SeedArtistID: r.SeedArtistID, CoverPath: r.CoverPath, + ShelfRank: r.ShelfRank, TrackCount: r.TrackCount, DurationSec: r.DurationSec, CreatedAt: r.CreatedAt, diff --git a/internal/playlists/system.go b/internal/playlists/system.go index d91eb1a5..1d2d5fb9 100644 --- a/internal/playlists/system.go +++ b/internal/playlists/system.go @@ -515,6 +515,9 @@ type builtPlaylist struct { Variant string SeedArtistID pgtype.UUID // zero value for non-seeded kinds Tracks []rankedCandidate + // ShelfRank is the mix's place on its Home shelf, 1 first; 0 leaves + // the order to the clients. + ShelfRank int32 } // systemPlaylistProducer computes the playlists for one kind for a @@ -871,8 +874,7 @@ func BuildSystemPlaylists(ctx context.Context, pool *pgxpool.Pool, logger *slog. if len(bp.Tracks) == 0 { continue } - id, err := insertSystemPlaylist(ctx, qtx, userID, bp.Name, bp.Variant, - bp.SeedArtistID, bp.Tracks) + id, err := insertSystemPlaylist(ctx, qtx, userID, bp) if err != nil { buildErr = fmt.Errorf("insert %s (%s): %w", bp.Variant, bp.Name, err) return buildErr @@ -1066,22 +1068,22 @@ func systemMixDescription(variant string) string { // in BuildSystemPlaylists overrides it with a 4-cell composite of the // contributing tracks' album art. func insertSystemPlaylist(ctx context.Context, qtx *dbq.Queries, userID pgtype.UUID, - name, variant string, seedArtistID pgtype.UUID, - tracks []rankedCandidate) (pgtype.UUID, error) { - variantStr := variant + bp builtPlaylist) (pgtype.UUID, error) { + variantStr := bp.Variant p, err := qtx.CreateSystemPlaylist(ctx, dbq.CreateSystemPlaylistParams{ UserID: userID, - Name: name, - Description: systemMixDescription(variant), + Name: bp.Name, + Description: systemMixDescription(bp.Variant), SystemVariant: &variantStr, - SeedArtistID: seedArtistID, + SeedArtistID: bp.SeedArtistID, CoverPath: nil, + ShelfRank: bp.ShelfRank, }) if err != nil { return pgtype.UUID{}, fmt.Errorf("insert playlist row: %w", err) } - tracks, err = oneCopyPerSong(ctx, qtx, tracks) + tracks, err := oneCopyPerSong(ctx, qtx, bp.Tracks) if err != nil { return pgtype.UUID{}, err } diff --git a/web/src/lib/api/types.ts b/web/src/lib/api/types.ts index 8d73adac..482aa007 100644 --- a/web/src/lib/api/types.ts +++ b/web/src/lib/api/types.ts @@ -80,6 +80,10 @@ export type Playlist = { // /api/albums/{id}/cover. Absent when the playlist has none. A home shelf // gives each tile an album no earlier tile shows (lib/playlists/shelf.ts). cover_album_ids?: string[]; + // A system mix's place on its home shelf, 1 first: genre mixes are + // numbered by how much the user listens to each genre. Absent for + // playlists the client orders itself (lib/playlists/shelf.ts byShelfRank). + shelf_rank?: number; track_count: number; duration_sec: number; created_at: string; diff --git a/web/src/lib/playlists/shelf.test.ts b/web/src/lib/playlists/shelf.test.ts index e86eaf8e..4e668a81 100644 --- a/web/src/lib/playlists/shelf.test.ts +++ b/web/src/lib/playlists/shelf.test.ts @@ -1,6 +1,14 @@ import { describe, expect, test } from 'vitest'; import type { Playlist } from '#lib/api/types.js'; -import { assignShelfCovers, refreshedLabel, shelfMeta, shelfTileWidth, songsLikeArtist, washTone } from './shelf.js'; +import { + assignShelfCovers, + byShelfRank, + refreshedLabel, + shelfMeta, + shelfTileWidth, + songsLikeArtist, + washTone +} from './shelf.js'; function pl(over: Partial): Playlist { return { @@ -149,3 +157,22 @@ describe('shelfTileWidth', () => { expect(shelfTileWidth(100, 5, 150, 16)).toBe(150); }); }); + +describe('byShelfRank', () => { + test('ranked mixes lead in rank order, the unranked follow by name', () => { + const shelf = [ + pl({ name: 'Ambient mix', shelf_rank: 3 }), + pl({ name: 'Zydeco mix' }), + pl({ name: 'Pop mix', shelf_rank: 1 }), + pl({ name: 'Blues mix' }), + pl({ name: 'Jazz mix', shelf_rank: 2 }) + ]; + expect([...shelf].sort(byShelfRank).map((p) => p.name)).toEqual([ + 'Pop mix', + 'Jazz mix', + 'Ambient mix', + 'Blues mix', + 'Zydeco mix' + ]); + }); +}); diff --git a/web/src/lib/playlists/shelf.ts b/web/src/lib/playlists/shelf.ts index 1249378f..915aa551 100644 --- a/web/src/lib/playlists/shelf.ts +++ b/web/src/lib/playlists/shelf.ts @@ -66,6 +66,15 @@ export function shelfMeta(playlists: Playlist[], now: Date = new Date()): string return line.charAt(0).toUpperCase() + line.slice(1); } +// Orders a shelf by the rank the server gave each mix (1 first; genre mixes +// lead with the genres the user listens to most). Unranked playlists follow +// in name order, as do ranked ones should two share a rank. +export function byShelfRank(a: Playlist, b: Playlist): number { + const ra = a.shelf_rank || Number.MAX_SAFE_INTEGER; + const rb = b.shelf_rank || Number.MAX_SAFE_INTEGER; + return ra - rb || a.name.localeCompare(b.name); +} + // "Songs like Low Tide Choir" → "Low Tide Choir": a Songs like tile labels // the artist under its circle, so the prefix would only repeat the shelf. export function songsLikeArtist(p: Playlist): string { diff --git a/web/src/routes/+page.svelte b/web/src/routes/+page.svelte index d83bd10a..5271bb06 100644 --- a/web/src/routes/+page.svelte +++ b/web/src/routes/+page.svelte @@ -12,7 +12,7 @@ import { createPlaylistsQuery } from '#lib/api/playlists.js'; import { createSystemPlaylistsStatusQuery } from '#lib/api/me.js'; import type { Playlist } from '#lib/api/types.js'; - import { assignShelfCovers, shelfMeta } from '#lib/playlists/shelf.js'; + import { assignShelfCovers, byShelfRank, shelfMeta } from '#lib/playlists/shelf.js'; const queryStore = createHomeQuery(); const query = $derived($queryStore); @@ -52,12 +52,12 @@ ); // Genre mixes: one "{Genre} mix" per genre the user listens to, on their - // own row in name order so the shelf reads like a stable channel list. + // own row, the genres listened to most first (the server's shelf_rank). // Mirrors Android's buildGenreMixRow (HomeScreen.kt). const genreMixPlaylists = $derived( (systemPlaylistsQ.data?.owned ?? []) .filter((p) => p.system_variant === 'genre_mix') - .sort((a, b) => a.name.localeCompare(b.name)) + .sort(byShelfRank) ); // Secondary system kinds the server generates that don't get pinned