Files
archy/packages/app/src/composables/usePlayer.ts
T
DorianandClaude Opus 4.6 493657549e fix(app): harden persistence, player performance, content extraction
- Fix chat persistence: unwrap Vue Proxy objects before IDB storage,
  flush pending saves on page unload/visibility change, use immediate
  saves for conversation creation and seed migration
- Fix player performance: parallel music search across providers,
  server-side LRU cache, client-side result cache, audio element reuse,
  instant UI feedback, abort stale searches, next-song prefetch
- Fix content extraction: strip recipe/event tags in stripContentTags,
  extend cleanMagazineContent regex for all _ext patterns
- Fix PlayerBar: move to App.vue root to avoid stacking context clipping,
  remove unused isDark conditionals (dark-only app)
- Add /seed command: loads 15 seed conversations from fixture index,
  opens history panel, switches to first seed conversation
- Add seed prompt index: 15 realistic AI prompt/response pairs covering
  films, songs, books, TV, places, podcasts, code, images, recipes, events
- Add seedExtraction.test.ts: 60 tests validating extraction counts,
  tag stripping completeness, and data integrity

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 17:34:21 +00:00

334 lines
9.4 KiB
TypeScript

import { ref, shallowRef, computed, watch } from 'vue'
import type { Song } from '@aiui/core/types/content'
import Plyr from 'plyr'
import 'plyr/dist/plyr.css'
interface MusicSearchResult {
source: string
type: 'stream' | 'embed'
url: string
title?: string
artist?: string
}
// ─── Global singleton state ───────────────────────────────────
const currentSong = ref<Song | null>(null)
const playableSource = ref<MusicSearchResult | null>(null)
const isPlaying = ref(false)
const isLoading = ref(false)
const error = ref<string | null>(null)
const currentTime = ref(0)
const duration = ref(0)
// Queue management
const queue = shallowRef<Song[]>([])
const currentIndex = ref(-1)
let plyrInstance: Plyr | null = null
let containerEl: HTMLDivElement | null = null
let audioEl: HTMLAudioElement | null = null
// Client-side search result cache — avoids re-searching songs
const resultCache = new Map<string, MusicSearchResult | null>()
// Active search abort controller — cancel stale searches on rapid switching
let activeSearchController: AbortController | null = null
export function usePlayer() {
const hasTrack = computed(() => !!currentSong.value)
const progress = computed(() => {
if (duration.value <= 0) return 0
return (currentTime.value / duration.value) * 100
})
// ─── Search with abort + cache ────────────────────────────
async function searchMusic(query: string, title?: string, artist?: string): Promise<MusicSearchResult | null> {
const cacheKey = `${query}|${title ?? ''}|${artist ?? ''}`
const cached = resultCache.get(cacheKey)
if (cached !== undefined) return cached
// Cancel any in-flight search
activeSearchController?.abort()
const controller = new AbortController()
activeSearchController = controller
try {
const params = new URLSearchParams({ q: query })
if (title) params.set('title', title)
if (artist) params.set('artist', artist)
const res = await fetch(`/api/music/search?${params}`, {
signal: controller.signal,
})
const data = (await res.json()) as MusicSearchResult & { error?: string }
if (data.error || !data.url) {
error.value = data.error ?? 'No playable source found'
resultCache.set(cacheKey, null)
return null
}
const result = data as MusicSearchResult
resultCache.set(cacheKey, result)
return result
} catch (e) {
if ((e as Error).name === 'AbortError') return null
error.value = 'Network error. Is the dev server running?'
return null
}
}
// ─── Container management ─────────────────────────────────
function setContainer(el: HTMLDivElement | null) {
containerEl = el
if (el && playableSource.value) {
initPlayer(playableSource.value)
}
}
// ─── Audio player init — reuses audio element when possible ─
function initPlayer(result: MusicSearchResult) {
if (!containerEl) return
if (result.type === 'stream') {
// Reuse existing audio element if we have one — just change src
if (audioEl && plyrInstance) {
audioEl.src = result.url
audioEl.load()
Promise.resolve(plyrInstance.play()).catch(() => { /* autoplay blocked */ })
return
}
// First time — create audio element and Plyr
destroyPlayer()
audioEl = document.createElement('audio')
audioEl.src = result.url
audioEl.crossOrigin = 'anonymous'
audioEl.preload = 'auto'
containerEl.innerHTML = ''
containerEl.appendChild(audioEl)
plyrInstance = new Plyr(audioEl, {
controls: [],
autoplay: true,
muted: false,
})
plyrInstance.on('ready', () => {
Promise.resolve(plyrInstance!.play()).catch(() => { /* autoplay blocked */ })
})
plyrInstance.on('timeupdate', () => {
currentTime.value = plyrInstance!.currentTime ?? 0
})
plyrInstance.on('loadedmetadata', () => {
duration.value = plyrInstance!.duration ?? 0
})
plyrInstance.on('ended', () => {
isPlaying.value = false
if (currentIndex.value >= 0 && currentIndex.value < queue.value.length - 1) {
playNext()
}
})
plyrInstance.on('playing', () => {
isPlaying.value = true
isLoading.value = false
})
plyrInstance.on('pause', () => {
isPlaying.value = false
})
} else {
// Embed (Odysee etc.) — must recreate iframe
destroyPlayer()
const iframe = document.createElement('iframe')
iframe.src = result.url
iframe.style.width = '100%'
iframe.style.height = '100%'
iframe.style.border = 'none'
containerEl.innerHTML = ''
containerEl.appendChild(iframe)
plyrInstance = null
audioEl = null
duration.value = 0
currentTime.value = 0
}
}
function destroyPlayer() {
if (plyrInstance) {
plyrInstance.destroy()
plyrInstance = null
}
audioEl = null
if (containerEl) {
containerEl.innerHTML = ''
}
}
// ─── Play — instant feedback, then load ───────────────────
async function play(song: Song) {
error.value = null
// Resume if same song
if (currentSong.value?.id === song.id && playableSource.value) {
if (plyrInstance) {
Promise.resolve(plyrInstance.play()).catch(() => {})
isPlaying.value = true
}
return
}
// Set song immediately for instant UI feedback
currentSong.value = song
isLoading.value = true
currentTime.value = 0
duration.value = 0
const query = `${song.title} ${song.artist}`.trim()
const result = await searchMusic(query, song.title, song.artist)
// Guard: user may have switched to a different song while we were searching
if (currentSong.value?.id !== song.id) return
isLoading.value = false
if (!result) {
if (!error.value) error.value = 'No playable source. Tried: Internet Archive, Jamendo, Odysee.'
return
}
error.value = null
playableSource.value = result
if (containerEl) {
initPlayer(result)
}
}
function pause() {
plyrInstance?.pause()
isPlaying.value = false
}
function toggle() {
if (isLoading.value) return
if (plyrInstance) {
if (isPlaying.value) pause()
else Promise.resolve(plyrInstance.play()).catch(() => {})
}
}
function seek(percent: number) {
if (!plyrInstance || !duration.value) return
const time = (percent / 100) * duration.value
plyrInstance.currentTime = time
currentTime.value = time
}
// ─── Queue management ─────────────────────────────────────
function addToQueue(song: Song) {
const existing = queue.value.find(s => s.id === song.id)
if (!existing) {
queue.value = [...queue.value, song]
}
}
function playNext() {
if (queue.value.length === 0) return
const nextIdx = currentIndex.value + 1
if (nextIdx < queue.value.length) {
currentIndex.value = nextIdx
play(queue.value[nextIdx])
}
}
function playPrevious() {
if (queue.value.length === 0) return
const prevIdx = currentIndex.value - 1
if (prevIdx >= 0) {
currentIndex.value = prevIdx
play(queue.value[prevIdx])
}
}
function removeFromQueue(index: number) {
const newQueue = [...queue.value]
newQueue.splice(index, 1)
queue.value = newQueue
if (index < currentIndex.value) {
currentIndex.value--
} else if (index === currentIndex.value) {
currentIndex.value = Math.min(currentIndex.value, newQueue.length - 1)
}
}
async function playWithQueue(song: Song) {
const idx = queue.value.findIndex(s => s.id === song.id)
if (idx === -1) {
addToQueue(song)
currentIndex.value = queue.value.length - 1
} else {
currentIndex.value = idx
}
await play(song)
}
// ─── Prefetch next song in queue ──────────────────────────
watch(currentIndex, (idx) => {
const nextIdx = idx + 1
if (nextIdx < queue.value.length) {
const next = queue.value[nextIdx]
const query = `${next.title} ${next.artist}`.trim()
// Fire-and-forget — populates the cache
searchMusic(query, next.title, next.artist)
}
})
// ─── Cleanup ──────────────────────────────────────────────
function clear() {
pause()
destroyPlayer()
currentSong.value = null
playableSource.value = null
currentTime.value = 0
duration.value = 0
error.value = null
}
function clearQueue() {
clear()
queue.value = []
currentIndex.value = -1
}
const hasNext = computed(() => currentIndex.value < queue.value.length - 1)
const hasPrevious = computed(() => currentIndex.value > 0)
return {
currentSong,
playableSource,
isPlaying,
isLoading,
error,
currentTime,
duration,
hasTrack,
progress,
queue,
currentIndex,
hasNext,
hasPrevious,
play: playWithQueue,
pause,
toggle,
seek,
clear,
clearQueue,
addToQueue,
playNext,
playPrevious,
removeFromQueue,
setContainer,
}
}