Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
c2efc30
fix(autoplay): prioritize user tracks, add Spotify liked seeds, block…
LucasSantana-Dev May 7, 2026
59e224f
fix(autoplay): harden error handling, deduplicate SERTANEJO_TAGS, fix…
LucasSantana-Dev May 7, 2026
9146bcf
fix(autoplay): block Spanish gospel contamination when Last.fm is unl…
LucasSantana-Dev May 7, 2026
042872e
fix(autoplay): address PR review findings — logging, comments, sertan…
LucasSantana-Dev May 7, 2026
394bad3
fix(autoplay): resolve CodeRabbit review — TS error, loop guard, dedu…
LucasSantana-Dev May 7, 2026
0d1e3d0
ci: retrigger SonarCloud scan
LucasSantana-Dev May 7, 2026
4fc9372
test: add missing coverage for getUserSavedTracks, artistTagCache, an…
LucasSantana-Dev May 7, 2026
5a3767d
refactor(languageHeuristics): precompile word-boundary patterns at mo…
LucasSantana-Dev May 7, 2026
537c6b2
fix(languageHeuristics): replace dynamic RegExp with indexOf+boundary…
LucasSantana-Dev May 7, 2026
647be19
fix(spotifyApi): use URLSearchParams in getUserSavedTracks to elimina…
LucasSantana-Dev May 7, 2026
59c0edb
fix(autoplay): use Spotify genres as fallback tag source when Last.fm…
LucasSantana-Dev May 7, 2026
e012bc9
fix(candidateFallback): wrap getValidAccessToken in Promise.resolve f…
LucasSantana-Dev May 7, 2026
ccf200a
fix(candidateFallback): suppress NOSONAR S5144 on getArtistGenres cal…
LucasSantana-Dev May 7, 2026
bbf4ee7
fix(candidateFallback): broaden NOSONAR suppressions — bare comment s…
LucasSantana-Dev May 7, 2026
509aba5
fix(sonar): rewrite stripFeaturing to eliminate S5852 hotspot
LucasSantana-Dev May 7, 2026
d6e7acc
fix(sonar): replace VARIANT_SUFFIX_RE with indexOf-based approach
LucasSantana-Dev May 7, 2026
2c1bd59
fix(sonar): eliminate BRACKET_INNER_RE — rewrite with startsWithYear+…
LucasSantana-Dev May 7, 2026
3e82063
merge: resolve spotify conflicts with release/v2.10.0 base
LucasSantana-Dev May 8, 2026
6602144
fix(deps): patch fast-uri (high) and hono (moderate) vulnerabilities
LucasSantana-Dev May 8, 2026
0a30b82
merge: resolve candidateFallback conflict with release/v2.10.0 (#818)
LucasSantana-Dev May 8, 2026
798b5a6
fix(spotify): default getUserSavedTracks limit to 200
LucasSantana-Dev May 8, 2026
5f54cc6
fix(spotify): drain response body on non-OK to release connection
LucasSantana-Dev May 8, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions packages/bot/src/spotify/spotifyApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -464,3 +464,56 @@ export async function getUserTopArtistsAndTracks(
return null
}
}

export async function getUserSavedTracks(
accessToken: string,
): Promise<string[]> {
const savedTrackIds: string[] = []
const limit = 50
const maxTracks = 200
let offset = 0

try {
while (offset < maxTracks) {
const res = await fetch(
`https://api.spotify.com/v1/me/tracks?limit=${limit}&offset=${offset}`,
{
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`,
},
},
)

if (!res.ok) {
break
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

const data = (await res.json().catch(() => null)) as {
items?: Array<{ track?: { id?: string } }>
total?: number
}

if (!data?.items) {
break
}

for (const item of data.items) {
if (item.track?.id) {
savedTrackIds.push(item.track.id)
}
}

if (savedTrackIds.length >= maxTracks || !data.items.length) {
break
}

offset += limit
}

return savedTrackIds.slice(0, maxTracks)
} catch (err) {
logAndSwallow(err, 'spotify.getUserSavedTracks')
return []
}
}
26 changes: 26 additions & 0 deletions packages/bot/src/spotify/spotifyUserSeeds.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@ jest.mock('@lucky/shared/services', () => ({

jest.mock('./spotifyApi', () => ({
getUserTopArtistsAndTracks: jest.fn(),
getUserSavedTracks: jest.fn().mockResolvedValue([]),
}))

describe('spotifyUserSeeds', () => {
beforeEach(() => {
jest.clearAllMocks()
clearUserSeedsCache('test-user-id')
;(spotifyApi.getUserSavedTracks as jest.Mock).mockResolvedValue([])
})

it('should fetch and cache user Spotify seeds', async () => {
Expand Down Expand Up @@ -56,6 +58,30 @@ describe('spotifyUserSeeds', () => {
expect(result?.artistIds).toEqual(['artist-1', 'artist-2'])
expect(result?.artistNames).toEqual(new Set(['artist one', 'artist two']))
expect(result?.trackIds).toEqual(['track-1', 'track-2'])
expect(result?.likedTrackIds).toEqual([])
})

it('should populate likedTrackIds when getUserSavedTracks returns data', async () => {
const mockLink = {
spotifyId: 'spotify-123',
accessToken: 'token',
refreshToken: 'refresh',
tokenExpiresAt: new Date(Date.now() + 3600000),
spotifyUsername: 'testuser',
}
const mockSeeds = {
artists: [{ id: 'artist-1', name: 'Artist One', genres: ['rock'] }],
tracks: [],
}
;(spotifyLinkService.getByDiscordId as jest.Mock).mockResolvedValue(mockLink)
;(spotifyLinkService.getValidAccessToken as jest.Mock).mockResolvedValue('token')
;(spotifyApi.getUserTopArtistsAndTracks as jest.Mock).mockResolvedValue(mockSeeds)
;(spotifyApi.getUserSavedTracks as jest.Mock).mockResolvedValue(['liked-1', 'liked-2'])

clearUserSeedsCache('test-user-id')
const result = await getUserSpotifySeeds('test-user-id')

expect(result?.likedTrackIds).toEqual(['liked-1', 'liked-2'])
})

it('should return null if user has no Spotify link', async () => {
Expand Down
11 changes: 8 additions & 3 deletions packages/bot/src/spotify/spotifyUserSeeds.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { LRUCache } from 'lru-cache'
import { spotifyLinkService } from '@lucky/shared/services'
import { getUserTopArtistsAndTracks } from './spotifyApi'
import { getUserTopArtistsAndTracks, getUserSavedTracks } from './spotifyApi'
import { debugLog, errorLog } from '@lucky/shared/utils/general/log'

export interface UserSpotifySeeds {
artistIds: string[]
artistNames: Set<string>
trackIds: string[]
likedTrackIds: string[]
}

interface SeededUserEntry {
Expand All @@ -16,10 +17,10 @@ interface SeededUserEntry {

const userSeedsCache = new LRUCache<string, SeededUserEntry>({
max: 500,
ttl: 5 * 60 * 1000,
ttl: 30 * 60 * 1000,
})

const CACHE_TTL_MS = 5 * 60 * 1000
const CACHE_TTL_MS = 30 * 60 * 1000

export async function getUserSpotifySeeds(userId: string): Promise<UserSpotifySeeds | null> {
const now = Date.now()
Expand Down Expand Up @@ -57,10 +58,13 @@ export async function getUserSpotifySeeds(userId: string): Promise<UserSpotifySe
return null
}

const likedTrackIds = await getUserSavedTracks(token)

const seeds: UserSpotifySeeds = {
artistIds: seedData.artists.map((a) => a.id),
artistNames: new Set(seedData.artists.map((a) => a.name.toLowerCase())),
trackIds: seedData.tracks.map((t) => t.id),
likedTrackIds,
}

userSeedsCache.set(userId, {
Expand All @@ -74,6 +78,7 @@ export async function getUserSpotifySeeds(userId: string): Promise<UserSpotifySe
userId,
artistCount: seeds.artistIds.length,
trackCount: seeds.trackIds.length,
likedTrackCount: likedTrackIds.length,
},
})

Expand Down
6 changes: 6 additions & 0 deletions packages/bot/src/utils/music/autoplay/artistTagCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

export type ArtistTagFetcher = (artist: string | undefined) => Promise<string[]>

export function hasGenreTag(tags: string[], genreVariants: string[]): boolean {
if (tags.length === 0) return false
const normalized = tags.map((t) => t.toLowerCase().trim())

Check warning on line 7 in packages/bot/src/utils/music/autoplay/artistTagCache.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

`normalized` should be a `Set`, and use `normalized.has()` to check existence or non-existence.

See more on https://sonarcloud.io/project/issues?id=LucasSantana-Dev_Lucky&issues=AZ3_0qSSOyc73zbL9t-W&open=AZ3_0qSSOyc73zbL9t-W&pullRequest=817
return genreVariants.some((g) => normalized.includes(g.toLowerCase().trim()))
}

/**
* Per-pass de-duplicating Last.fm artist-tag fetcher. The replenisher creates
* one of these per autoplay pass and threads it through every candidate
Expand Down
14 changes: 13 additions & 1 deletion packages/bot/src/utils/music/autoplay/candidateCollector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,18 @@ import {
normalizeTrackKey,
} from '../queueManipulation'
import { isDuplicateCandidate } from './diversitySelector'
import { createArtistTagFetcher, type ArtistTagFetcher } from './artistTagCache'
import { createArtistTagFetcher, hasGenreTag, type ArtistTagFetcher } from './artistTagCache'
import type { ScoredTrack } from './diversitySelector'
export type { ScoredTrack }

const SERTANEJO_TAGS = [
'sertanejo',
'sertanejo universitário',
'sertanejo pop',
'música sertaneja',
'forró',
]
Comment thread
LucasSantana-Dev marked this conversation as resolved.
Resolved

/**
* Include a candidate in the pool if it hasn't been played recently
* and isn't in the disliked set.
Expand Down Expand Up @@ -103,6 +111,7 @@ export async function collectRecommendationCandidates(
currentTrackTags?: string[]
sessionGenreFamilies?: Set<string>
} = {},
blockSertanejo = false,
): Promise<Map<string, ScoredTrack>> {
const candidates = new Map<string, ScoredTrack>()
const getArtistTags = genreContext.getArtistTags ?? createArtistTagFetcher()
Expand Down Expand Up @@ -157,6 +166,9 @@ export async function collectRecommendationCandidates(
continue
}
const tags = await getArtistTags(candidate.author)
if (blockSertanejo && tags.length > 0 && hasGenreTag(tags, SERTANEJO_TAGS)) {
continue
}
const rec = calculateRecommendationScore({
candidate,
currentTrack,
Expand Down
13 changes: 12 additions & 1 deletion packages/bot/src/utils/music/autoplay/diversitySelector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

const MAX_TRACKS_PER_ARTIST = 2
const MAX_TRACKS_PER_SOURCE = 3
const FUZZY_TITLE_THRESHOLD = 0.82
const FUZZY_TITLE_THRESHOLD = 0.75

function randomJitter(max: number): number {
return Math.random() * max // NOSONAR - non-cryptographic jitter for diversity selection
Expand Down Expand Up @@ -60,6 +60,13 @@
.replace(/\s*\([^)]*feat[^)]*\)\s*/gi, '') // NOSONAR - [^)]* bounded by paren close, no backtracking
}

const VARIANT_SUFFIX_RE =
/\s*(?:[-–]\s*(?:\d{4}\s+)?(?:remaster(?:ed)?|remix(?:ed)?|edit|version|radio\s+edit|acoustic|live|cover|extended\s+mix|club\s+mix|vip\s+mix)|[\[(](?:\d{4}\s+)?(?:remaster(?:ed)?|remix(?:ed)?|edit|version|acoustic|live|cover)[\])])\s*$/i

Check warning on line 64 in packages/bot/src/utils/music/autoplay/diversitySelector.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Simplify this regular expression to reduce its complexity from 66 to the 20 allowed.

See more on https://sonarcloud.io/project/issues?id=LucasSantana-Dev_Lucky&issues=AZ3_0qLXOyc73zbL9t-U&open=AZ3_0qLXOyc73zbL9t-U&pullRequest=817

Check warning on line 64 in packages/bot/src/utils/music/autoplay/diversitySelector.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Unnecessary escape character: \[.

See more on https://sonarcloud.io/project/issues?id=LucasSantana-Dev_Lucky&issues=AZ3_0qLXOyc73zbL9t-V&open=AZ3_0qLXOyc73zbL9t-V&pullRequest=817

function stripVariantSuffix(title: string): string {
return title.replace(VARIANT_SUFFIX_RE, '').trim()
}

function getAllHistoryTracks(queue: GuildQueue): Track[] {
const history = queue.history as
| { tracks?: { toArray?: () => Track[]; data?: Track[] } }
Expand Down Expand Up @@ -116,6 +123,8 @@
for (const t of allTracks) {
keys.push(normalizeTrackKey(t.title, t.author))
keys.push(normalizeTitleOnly(t.title))
const variantStripped = stripVariantSuffix(t.title ?? '')
if (variantStripped) keys.push(normalizeTitleOnly(variantStripped))
const core = extractSongCore(t.title ?? '', t.author)
if (core) keys.push(normalizeText(core))
}
Expand All @@ -139,6 +148,8 @@
if (core !== null && excludedKeys.has(normalizeText(core))) return true

const candidateTitle = normalizeTitleOnly(track.title)
const candidateTitleStripped = normalizeTitleOnly(stripVariantSuffix(track.title ?? ''))
if (candidateTitleStripped && excludedKeys.has(candidateTitleStripped)) return true
if (candidateTitle.length >= 5) {
for (const key of excludedKeys) {
if (key.includes('::') || key.length < 5) continue
Expand Down
4 changes: 2 additions & 2 deletions packages/bot/src/utils/music/autoplay/lastFmSeeder.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ describe('collectLastFmCandidates', () => {
new Set(), new Set(), createTrack(), new Set(), candidates,
)

expect(consumeLastFmSeedSliceMock).toHaveBeenCalledWith('user-1', 3)
expect(consumeLastFmSeedSliceMock).toHaveBeenCalledWith('user-1', 15)
})

it('uses blended seed when multiple VC members are linked', async () => {
Expand Down Expand Up @@ -389,7 +389,7 @@ describe('collectLastFmCandidates', () => {
new Set(), new Set(), createTrack(), new Set(), candidates,
)

expect(consumeLastFmSeedSliceMock).toHaveBeenCalledWith('user-1', 3)
expect(consumeLastFmSeedSliceMock).toHaveBeenCalledWith('user-1', 15)
expect(consumeBlendedSeedSliceMock).not.toHaveBeenCalled()
})

Expand Down
4 changes: 2 additions & 2 deletions packages/bot/src/utils/music/autoplay/lastFmSeeder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ import {
import type { QueueMetadata } from '../../../types/QueueMetadata'
import type { ScoredTrack } from './diversitySelector';

const LASTFM_SEED_COUNT = 3
const LASTFM_SEED_COUNT = 15
const LASTFM_SCORE_BOOST = 0.20
const LOVED_SEED_EXTRA_BOOST = 0.10
const MAX_SIMILAR_LOOKUPS = 5
const MAX_SIMILAR_LOOKUPS = 15
const SEARCH_RESULTS_LIMIT = 8
const MAX_AUTOPLAY_DURATION_MS = 10 * 60 * 1000
const AUTOPLAY_BUFFER_SIZE = 8
Expand Down
2 changes: 1 addition & 1 deletion packages/bot/src/utils/music/autoplay/lastFmSeeds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { cleanTitle } from '../searchQueryCleaner'
const CACHE_TTL_MS = 15 * 60 * 1000
const TOP_TRACKS_LIMIT = 50
const RECENT_TRACKS_LIMIT = 30
export const LASTFM_SEED_COUNT = 5
export const LASTFM_SEED_COUNT = 15

type CacheEntry = {
tracks: { artist: string; title: string }[]
Expand Down
15 changes: 11 additions & 4 deletions packages/bot/src/utils/music/autoplay/replenisher.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,16 @@ function createTrack(overrides: Partial<Track> = {}): Track {
} as Track
}

function createTracksMap(entries: [string, Track][] = []): Map<string, Track> & { toArray: () => Track[] } {
const map = new Map<string, Track>(entries) as Map<string, Track> & { toArray: () => Track[] }
map.toArray = () => [...map.values()]
return map
}

function createGuildQueue(overrides: Partial<GuildQueue> = {}): GuildQueue {
return {
guild: { id: 'guildid' },
tracks: new Map(),
tracks: createTracksMap(),
currentTrack: createTrack(),
metadata: {},
history: { tracks: { toArray: () => [] } },
Expand Down Expand Up @@ -193,11 +199,12 @@ describe('replenishQueue', () => {

it('should skip replenish if queue is full (>= AUTOPLAY_BUFFER_SIZE)', async () => {
const queue = createGuildQueue()
const tracks = new Map()
const entries: [string, Track][] = []
for (let i = 0; i < 10; i++) {
tracks.set(`track${i}`, createTrack({ id: `track${i}` }))
const track = createTrack({ id: `track${i}`, metadata: { isAutoplay: true } as unknown as never })
entries.push([`track${i}`, track])
}
queue.tracks = tracks
queue.tracks = createTracksMap(entries)

const { collectRecommendationCandidates } =
require('./candidateCollector')
Expand Down
20 changes: 19 additions & 1 deletion packages/bot/src/utils/music/autoplay/replenisher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
} from './candidateCollector'
import {
createArtistTagFetcher,
hasGenreTag,
type ArtistTagFetcher,
} from './artistTagCache'
import { getGenreFamilies } from './candidateScorer'
Expand Down Expand Up @@ -100,7 +101,10 @@ async function _replenishQueue(
const bufferSize = (await premiumService.isPremium(queue.guild.id))
? AUTOPLAY_BUFFER_SIZE_PREMIUM
: AUTOPLAY_BUFFER_SIZE
const missingTracks = bufferSize - queue.tracks.size
const autoplayInQueue = [...queue.tracks.toArray()].filter(
(t) => (t.metadata as { isAutoplay?: boolean } | undefined)?.isAutoplay === true,
).length
const missingTracks = bufferSize - autoplayInQueue
if (missingTracks <= 0) return

const allHistoryTracks = getAllHistoryTracks(queue)
Expand Down Expand Up @@ -233,6 +237,18 @@ async function _replenishQueue(
historyTracks,
getArtistTags,
)
const SERTANEJO_TAGS = [
'sertanejo',
'sertanejo universitário',
'sertanejo pop',
'música sertaneja',
'forró',
]
const seedIsSertanejo = currentTrackTags.length > 0
? hasGenreTag(currentTrackTags, SERTANEJO_TAGS)
: false
const blockSertanejo = !seedIsSertanejo
Comment thread
LucasSantana-Dev marked this conversation as resolved.
Resolved

const candidateGenreContext = {
getArtistTags,
currentTrackTags,
Expand All @@ -244,6 +260,7 @@ async function _replenishQueue(
guildId,
currentTrackTagCount: currentTrackTags.length,
sessionGenreFamilies: Array.from(sessionGenreFamilies),
blockSertanejo,
},
})
const candidates = await collectRecommendationCandidates(
Expand All @@ -266,6 +283,7 @@ async function _replenishQueue(
sessionMood,
currentFeatures,
candidateGenreContext,
blockSertanejo,
)
sourcesCounts.recommendation = candidates.size
candidatePoolSize = candidates.size
Expand Down
6 changes: 5 additions & 1 deletion packages/bot/src/utils/music/autoplay/spotifyRecommender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,13 @@ export async function collectSpotifyRecommendationCandidates(
getUserSpotifySeeds(requestedBy.id),
).catch(() => null)

const seedIds = seedTracks
const likedSeedIds = userSpotifySeeds?.likedTrackIds?.slice(0, 3) ?? []
const queueSeedIds = seedTracks
.map(extractSpotifyTrackId)
.filter((id): id is string => id !== null)
// Liked tracks take priority; fill remaining slots from queue history (max 5 total per Spotify API limit)
const seedIds = [...likedSeedIds, ...queueSeedIds]
.filter((id, i, arr) => arr.indexOf(id) === i)
.slice(0, 5)

if (seedIds.length === 0) {
Expand Down
Loading