Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: add Spotify and YouTube Brain libraries

[._.]/ Adam Eivy6a0d1033f0a7
diff --git a/client/src/components/brain/tabs/SpotifyTab.jsx b/client/src/components/brain/tabs/SpotifyTab.jsx
index ccc550eacf..83757ef363 100644
--- a/client/src/components/brain/tabs/SpotifyTab.jsx
+++ b/client/src/components/brain/tabs/SpotifyTab.jsx
@@ -1,6 +1,6 @@
-import { useEffect, useState } from 'react';
+import { useEffect, useMemo, useState } from 'react';
import { useSearchParams } from 'react-router';
-import { Save, Loader2, Music, Link2, LogOut, RefreshCw, CheckCircle2, AlertCircle } from 'lucide-react';
+import { Save, Loader2, Music, Link2, LogOut, RefreshCw, CheckCircle2, AlertCircle, ExternalLink, Search } from 'lucide-react';
import toast from '../../ui/Toast';
import BrailleSpinner from '../../BrailleSpinner';
import { formatDateTime } from '../../../utils/formatters';
@@ -11,6 +11,8 @@ import {
saveSpotifyCredentials,
clearSpotifyAuth,
syncSpotify,
+ getSpotifyPlaylists,
+ syncSpotifyPlaylists,
} from '../../../services/api';
// Brain → Spotify (#2152). Opt-in, machine-local ingestion of Spotify
@@ -29,9 +31,26 @@ export function SpotifyTab() {
const [connecting, setConnecting] = useState(false);
const [syncing, setSyncing] = useState(false);
+ const [playlists, setPlaylists] = useState(null);
+ const [playlistsLoading, setPlaylistsLoading] = useState(false);
+ const [playlistsSyncing, setPlaylistsSyncing] = useState(false);
+ const [playlistQuery, setPlaylistQuery] = useState('');
+ const auth = status?.auth;
const loadStatus = () => getSpotifyStatus({ silent: true }).catch(() => null).then((st) => { if (st) setStatus(st); return st; });
+ const loadPlaylists = () => {
+ setPlaylistsLoading(true);
+ return getSpotifyPlaylists({ silent: true })
+ .then((result) => setPlaylists(result?.snapshot || null))
+ .catch(() => null)
+ .finally(() => setPlaylistsLoading(false));
+ };
+
+ useEffect(() => {
+ if (!loading && auth?.hasTokens) loadPlaylists();
+ }, [loading, auth?.hasTokens]);
+
// Surface the OAuth callback outcome (the browser redirect lands back here).
useEffect(() => {
if (searchParams.get('oauthConnected')) {
@@ -46,8 +65,6 @@ export function SpotifyTab() {
}
}, [searchParams, setSearchParams]);
- const auth = status?.auth;
-
const handleSave = async () => {
if (!await save()) return;
toast.success('Saved — scheduler applies on next server restart');
@@ -103,9 +120,32 @@ export function SpotifyTab() {
}
};
- if (loading) return <BrailleSpinner />;
+ const handleSyncPlaylists = async () => {
+ setPlaylistsSyncing(true);
+ const result = await syncSpotifyPlaylists({ silent: true }).catch(() => ({ ok: false, error: 'Playlist sync failed' }));
+ setPlaylistsSyncing(false);
+ if (result?.playlistCount !== undefined) {
+ await loadPlaylists();
+ if (result.ok) toast.success(`Synced ${result.playlistCount} playlist(s) and ${result.trackCount} track(s)`);
+ else toast.error(`Playlist sync completed with ${result.failed || 0} warning(s)`);
+ } else {
+ toast.error(result?.needsAuth ? 'Connect Spotify first' : (result?.error || 'Playlist sync failed'));
+ }
+ };
const lastResult = status?.state?.lastResult;
+ const hasPlaylistScope = String(auth?.scope || '').split(/\s+/).includes('playlist-read-private');
+ const storedPlaylists = Array.isArray(playlists?.playlists) ? playlists.playlists : [];
+ const filteredPlaylists = useMemo(() => {
+ const query = playlistQuery.trim().toLowerCase();
+ if (!query) return storedPlaylists;
+ return storedPlaylists.filter((playlist) => String(playlist.name || '').toLowerCase().includes(query)
+ || playlist.tracks?.some((track) => String(track.name || '').toLowerCase().includes(query)
+ || track.artists?.some((artist) => String(artist.name || '').toLowerCase().includes(query))));
+ }, [playlistQuery, storedPlaylists]);
+ const playlistTrackCount = storedPlaylists.reduce((total, playlist) => total + (playlist.tracks?.length || 0), 0);
+
+ if (loading) return <BrailleSpinner />;
return (
<div className="space-y-6">
@@ -270,8 +310,122 @@ export function SpotifyTab() {
</dl>
</div>
)}
+
+ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6">
+ <div className="flex flex-wrap items-start justify-between gap-3 mb-2">
+ <div className="flex items-center gap-2">
+ <Music size={16} className="text-port-accent" />
+ <h3 className="text-lg font-semibold text-white">Playlist taste library</h3>
+ </div>
+ <button
+ type="button"
+ onClick={handleSyncPlaylists}
+ disabled={playlistsSyncing || !auth?.hasTokens || !hasPlaylistScope}
+ title={!auth?.hasTokens ? 'Connect Spotify first' : (!hasPlaylistScope ? 'Reconnect Spotify to grant playlist access' : undefined)}
+ className="inline-flex items-center justify-center gap-2 min-h-[40px] px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
+ >
+ {playlistsSyncing ? <Loader2 size={14} className="animate-spin" /> : <RefreshCw size={14} />}
+ Sync playlists
+ </button>
+ </div>
+ <p className="text-sm text-gray-400 mb-4">
+ A local reference shelf for the music you keep and revisit. PortOS stores playlist and track metadata here
+ so your musical context stays alongside your Brain consumption history. It never sends this library to peers.
+ </p>
+
+ {auth?.hasTokens && !hasPlaylistScope && (
+ <div className="mb-4 flex items-start gap-2 rounded border border-port-warning/30 bg-port-warning/10 p-3 text-sm text-port-warning">
+ <AlertCircle size={16} className="mt-0.5 shrink-0" />
+ <span>Reconnect Spotify above to grant playlist access. Your existing listening-history connection remains usable.</span>
+ </div>
+ )}
+
+ {playlistsLoading ? <BrailleSpinner /> : storedPlaylists.length > 0 ? (
+ <>
+ <div className="mb-4 flex flex-wrap items-center gap-x-4 gap-y-2 text-xs text-gray-500">
+ <span>{storedPlaylists.length} playlist(s)</span>
+ <span>{playlistTrackCount} track reference(s)</span>
+ {playlists.syncedAt && <span>Last synced {formatDateTime(playlists.syncedAt)}</span>}
+ {playlists.warnings?.length > 0 && <span className="text-port-warning">{playlists.warnings.length} incomplete</span>}
+ </div>
+ <label htmlFor="spotify-playlist-search" className="sr-only">Search playlists and tracks</label>
+ <div className="relative mb-4 max-w-md">
+ <Search size={15} className="pointer-events-none absolute left-3 top-2.5 text-gray-500" />
+ <input
+ id="spotify-playlist-search"
+ type="search"
+ value={playlistQuery}
+ onChange={(event) => setPlaylistQuery(event.target.value)}
+ placeholder="Search playlists or tracks"
+ className="w-full rounded border border-port-border bg-port-bg py-2 pl-9 pr-3 text-sm text-white placeholder:text-gray-500"
+ />
+ </div>
+ {filteredPlaylists.length > 0 ? (
+ <div className="grid gap-3 xl:grid-cols-2">
+ {filteredPlaylists.map((playlist) => (
+ <PlaylistCard key={playlist.id} playlist={playlist} query={playlistQuery} />
+ ))}
+ </div>
+ ) : (
+ <p className="rounded border border-dashed border-port-border p-6 text-center text-sm text-gray-500">No playlists or tracks match that search.</p>
+ )}
+ {playlists.warnings?.length > 0 && (
+ <p className="mt-4 text-xs text-port-warning">Some playlists could not be refreshed; retained references are marked by the last successful sync.</p>
+ )}
+ </>
+ ) : (
+ <div className="rounded border border-dashed border-port-border p-6 text-center text-sm text-gray-500">
+ {auth?.hasTokens && hasPlaylistScope
+ ? 'Sync playlists to build your local music reference shelf.'
+ : 'Connect Spotify and grant playlist access to build your local music reference shelf.'}
+ </div>
+ )}
+ </div>
</div>
);
}
+function PlaylistCard({ playlist, query }) {
+ const matchingTracks = playlist.tracks || [];
+ const visibleTracks = query.trim() ? matchingTracks : matchingTracks.slice(0, 8);
+ const remaining = Math.max(0, matchingTracks.length - visibleTracks.length);
+ const image = playlist.images?.[0];
+ return (
+ <section className="min-w-0 rounded border border-port-border bg-port-bg/40 p-3">
+ <div className="flex gap-3">
+ {image && <img src={image.url} alt="" className="h-16 w-16 shrink-0 rounded object-contain" />}
+ <div className="min-w-0 flex-1">
+ <div className="flex items-start justify-between gap-2">
+ <h4 className="truncate font-semibold text-gray-100">{playlist.name}</h4>
+ <a href={playlist.spotifyUrl} target="_blank" rel="noreferrer" className="shrink-0 text-gray-500 hover:text-port-accent" aria-label={`Open ${playlist.name} in Spotify`}>
+ <ExternalLink size={15} />
+ </a>
+ </div>
+ <div className="mt-1 flex flex-wrap gap-x-2 text-xs text-gray-500">
+ <span>{playlist.trackCount} track(s)</span>
+ {playlist.public === false && <span>Private</span>}
+ {playlist.collaborative && <span>Collaborative</span>}
+ </div>
+ {playlist.description && <p className="mt-1 line-clamp-2 text-xs text-gray-400">{playlist.description}</p>}
+ </div>
+ </div>
+ {visibleTracks.length > 0 && (
+ <div className="mt-3 divide-y divide-port-border/60 border-t border-port-border/60">
+ {visibleTracks.map((track, index) => (
+ <div key={`${track.id}-${track.addedAt || index}`} className="flex min-w-0 items-center gap-2 py-2 text-xs">
+ <span className="w-5 shrink-0 text-right text-gray-600">{index + 1}</span>
+ <div className="min-w-0 flex-1">
+ <a href={track.spotifyUrl} target="_blank" rel="noreferrer" className="block truncate text-gray-200 hover:text-port-accent hover:underline">{track.name}</a>
+ <div className="truncate text-gray-500">{track.artists?.map((artist) => artist.name).join(', ') || 'Unknown artist'}{track.album ? ` · ${track.album}` : ''}</div>
+ </div>
+ </div>
+ ))}
+ {remaining > 0 && <div className="pt-2 text-center text-xs text-gray-500">+ {remaining} more track(s)</div>}
+ </div>
+ )}
+ <div className="mt-3 text-[10px] uppercase tracking-wide text-gray-600">Spotify reference</div>
+ </section>
+ );
+}
+
export default SpotifyTab;
diff --git a/client/src/components/brain/tabs/YoutubeTab.jsx b/client/src/components/brain/tabs/YoutubeTab.jsx
index 2ee4055c26..4a12c28ff0 100644
--- a/client/src/components/brain/tabs/YoutubeTab.jsx
+++ b/client/src/components/brain/tabs/YoutubeTab.jsx
@@ -1,14 +1,17 @@
-import { useState } from 'react';
-import { Save, Loader2, MonitorPlay, RefreshCw, CheckCircle2, AlertCircle, ShieldQuestion } from 'lucide-react';
+import { useEffect, useMemo, useState } from 'react';
+import { Save, Loader2, MonitorPlay, RefreshCw, CheckCircle2, AlertCircle, ShieldQuestion, Search, ExternalLink, Download, X } from 'lucide-react';
import toast from '../../ui/Toast';
import FormField from '../../ui/FormField';
import BrailleSpinner from '../../BrailleSpinner';
import { formatDateTime } from '../../../utils/formatters';
import { useSyncSourceSettings } from '../../../hooks/useSyncSourceSettings';
+import { useVideoDownload } from '../../../hooks';
import {
getYoutubeStatus,
getYoutubeSetupCheck,
syncYoutube,
+ getYoutubePlaylists,
+ syncYoutubePlaylists,
} from '../../../services/api';
// Brain → YouTube (#2153). Opt-in, machine-local ingestion of YouTube watch
@@ -24,6 +27,25 @@ export function YoutubeTab() {
const [syncing, setSyncing] = useState(false);
const [checking, setChecking] = useState(false);
const [setup, setSetup] = useState(null);
+ const [playlists, setPlaylists] = useState(null);
+ const [playlistsLoading, setPlaylistsLoading] = useState(true);
+ const [playlistsSyncing, setPlaylistsSyncing] = useState(false);
+ const [playlistQuery, setPlaylistQuery] = useState('');
+ const [requestedVideoId, setRequestedVideoId] = useState(null);
+ const { active: downloading, percent, stage, context: downloadingVideoId, start: startDownload, cancel: cancelDownload } = useVideoDownload();
+
+ const loadPlaylists = () => {
+ setPlaylistsLoading(true);
+ return getYoutubePlaylists({ silent: true })
+ .then((result) => setPlaylists(result?.snapshot || null))
+ .catch(() => null)
+ .finally(() => setPlaylistsLoading(false));
+ };
+
+ useEffect(() => { loadPlaylists(); }, []);
+ useEffect(() => {
+ if (!downloading) setRequestedVideoId(null);
+ }, [downloading]);
const handleSave = async () => {
if (!await save()) return;
@@ -52,9 +74,37 @@ export function YoutubeTab() {
}
};
- if (loading) return <BrailleSpinner />;
+ const handleSyncPlaylists = async () => {
+ setPlaylistsSyncing(true);
+ const result = await syncYoutubePlaylists({ silent: true }).catch(() => ({ ok: false, error: 'Playlist sync failed' }));
+ setPlaylistsSyncing(false);
+ if (result?.playlistCount !== undefined) {
+ await loadPlaylists();
+ if (result.ok) toast.success(`Synced ${result.playlistCount} playlist(s) and ${result.videoCount} video(s)`);
+ else toast.error(`Playlist sync completed with ${result.failed || 0} warning(s)`);
+ } else {
+ toast.error(result?.needsAuth ? 'Log into YouTube in the managed browser first' : (result?.error || 'Playlist sync failed'));
+ }
+ };
+
+ const handleDownload = (video) => {
+ if (downloading) return;
+ setRequestedVideoId(video.id);
+ startDownload(video.url, video.id);
+ };
const lastResult = status?.state?.lastResult;
+ const storedPlaylists = Array.isArray(playlists?.playlists) ? playlists.playlists : [];
+ const filteredPlaylists = useMemo(() => {
+ const query = playlistQuery.trim().toLowerCase();
+ if (!query) return storedPlaylists;
+ return storedPlaylists.filter((playlist) => String(playlist.name || '').toLowerCase().includes(query)
+ || playlist.videos?.some((video) => String(video.title || '').toLowerCase().includes(query)
+ || String(video.channel || '').toLowerCase().includes(query)));
+ }, [playlistQuery, storedPlaylists]);
+ const playlistVideoCount = storedPlaylists.reduce((total, playlist) => total + (playlist.videos?.length || 0), 0);
+
+ if (loading) return <BrailleSpinner />;
return (
<div className="space-y-6">
@@ -166,8 +216,125 @@ export function YoutubeTab() {
</dl>
</div>
)}
+
+ <section className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6">
+ <div className="flex flex-wrap items-start justify-between gap-3 mb-2">
+ <div className="flex items-center gap-2">
+ <MonitorPlay size={16} className="text-port-accent" />
+ <h3 className="text-lg font-semibold text-white">Playlist video library</h3>
+ </div>
+ <button
+ type="button"
+ onClick={handleSyncPlaylists}
+ disabled={playlistsSyncing}
+ className="inline-flex items-center justify-center gap-2 min-h-[40px] px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
+ >
+ {playlistsSyncing ? <Loader2 size={14} className="animate-spin" /> : <RefreshCw size={14} />}
+ Sync playlists
+ </button>
+ </div>
+ <p className="text-sm text-gray-400 mb-4">
+ Browse the videos you have organized in YouTube playlists. Download is always an explicit action and uses
+ the shared Video Downloader, so completed videos also land in the PortOS media library.
+ </p>
+
+ {downloading && (
+ <div className="mb-4 rounded border border-port-accent/30 bg-port-accent/10 p-3 text-sm text-port-accent">
+ <div className="flex items-center gap-2">
+ <Loader2 size={15} className="animate-spin shrink-0" />
+ <span className="truncate">{stage ? `${stage}…` : 'Downloading video…'} {percent > 0 ? `${percent}%` : ''}</span>
+ <button type="button" onClick={cancelDownload} className="ml-auto inline-flex shrink-0 items-center gap-1 text-xs text-gray-300 hover:text-white"><X size={13} /> Cancel</button>
+ </div>
+ <div className="mt-2 h-1 overflow-hidden rounded bg-port-border"><div className="h-full bg-port-accent transition-all" style={{ width: `${percent}%` }} /></div>
+ </div>
+ )}
+
+ {playlistsLoading ? <BrailleSpinner /> : storedPlaylists.length > 0 ? (
+ <>
+ <div className="mb-4 flex flex-wrap items-center gap-x-4 gap-y-2 text-xs text-gray-500">
+ <span>{storedPlaylists.length} playlist(s)</span>
+ <span>{playlistVideoCount} video reference(s)</span>
+ {playlists.syncedAt && <span>Last synced {formatDateTime(playlists.syncedAt)}</span>}
+ {playlists.warnings?.length > 0 && <span className="text-port-warning">{playlists.warnings.length} incomplete</span>}
+ </div>
+ <label htmlFor="youtube-playlist-search" className="sr-only">Search playlists and videos</label>
+ <div className="relative mb-4 max-w-md">
+ <Search size={15} className="pointer-events-none absolute left-3 top-2.5 text-gray-500" />
+ <input
+ id="youtube-playlist-search"
+ type="search"
+ value={playlistQuery}
+ onChange={(event) => setPlaylistQuery(event.target.value)}
+ placeholder="Search playlists, videos, or channels"
+ className="w-full rounded border border-port-border bg-port-bg py-2 pl-9 pr-3 text-sm text-white placeholder:text-gray-500"
+ />
+ </div>
+ {filteredPlaylists.length > 0 ? (
+ <div className="grid gap-3 xl:grid-cols-2">
+ {filteredPlaylists.map((playlist) => (
+ <YoutubePlaylistCard
+ key={playlist.id}
+ playlist={playlist}
+ downloading={downloading}
+ downloadingVideoId={downloadingVideoId || requestedVideoId}
+ onDownload={handleDownload}
+ />
+ ))}
+ </div>
+ ) : (
+ <p className="rounded border border-dashed border-port-border p-6 text-center text-sm text-gray-500">No playlists or videos match that search.</p>
+ )}
+ {playlists.warnings?.length > 0 && <p className="mt-4 text-xs text-port-warning">Some playlist pages could not be refreshed; existing references were retained where available.</p>}
+ </>
+ ) : (
+ <div className="rounded border border-dashed border-port-border p-6 text-center text-sm text-gray-500">
+ Sync playlists to build your local YouTube video reference library.
+ </div>
+ )}
+ </section>
</div>
);
}
+function YoutubePlaylistCard({ playlist, downloading, downloadingVideoId, onDownload }) {
+ const videos = playlist.videos || [];
+ return (
+ <section className="min-w-0 rounded border border-port-border bg-port-bg/40 p-3">
+ <div className="flex items-start justify-between gap-2">
+ <div className="min-w-0">
+ <h4 className="truncate font-semibold text-gray-100">{playlist.name}</h4>
+ <span className="text-xs text-gray-500">{playlist.videoCount} video(s)</span>
+ </div>
+ <a href={playlist.url} target="_blank" rel="noreferrer" className="shrink-0 text-gray-500 hover:text-port-accent" aria-label={`Open ${playlist.name} on YouTube`}>
+ <ExternalLink size={15} />
+ </a>
+ </div>
+ {videos.length > 0 && (
+ <div className="mt-3 divide-y divide-port-border/60 border-t border-port-border/60">
+ {videos.map((video) => (
+ <div key={video.id} className="flex min-w-0 items-center gap-2 py-2">
+ {video.thumbnail && <img src={video.thumbnail} alt="" className="h-12 w-20 shrink-0 rounded object-cover" />}
+ <div className="min-w-0 flex-1">
+ <a href={video.url} target="_blank" rel="noreferrer" className="block truncate text-xs text-gray-200 hover:text-port-accent hover:underline">{video.title}</a>
+ <div className="truncate text-[11px] text-gray-500">{video.channel || 'Unknown channel'}{video.duration ? ` · ${video.duration}` : ''}</div>
+ </div>
+ <button
+ type="button"
+ onClick={() => onDownload(video)}
+ disabled={downloading}
+ className="inline-flex shrink-0 items-center gap-1 rounded border border-port-border px-2 py-1.5 text-[11px] text-gray-300 hover:border-port-accent hover:text-port-accent disabled:cursor-not-allowed disabled:opacity-40"
+ title={downloadingVideoId === video.id ? 'Downloading this video' : 'Download this video'}
+ >
+ {downloadingVideoId === video.id ? <Loader2 size={12} className="animate-spin" /> : <Download size={12} />}
+ <span className="hidden sm:inline">{downloadingVideoId === video.id ? 'Downloading' : 'Download'}</span>
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+ <div className="mt-3 text-[10px] uppercase tracking-wide text-gray-600">YouTube reference</div>
+ </section>
+ );
+}
+
export default YoutubeTab;
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 5ea8011f81..416653fcb9 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -211,7 +211,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useVideoGenQueue` | `useVideoGenQueue({ generating, runGeneration })` → `{ queue, runningQueueId, enqueue, removeFromQueue, clearFinishedQueue, cancelRunning }`. Client-side serial batch queue for VideoGen: owns the queue array + running marker + the worker effect that pumps the head whenever nothing is generating (with BUSY-backoff retry + unmount/staleness guards). | The VideoGen "Add to queue" batch flow. |
| `useVideoGenSubmitFlow` | Builds the current VideoGen wire payload and enveloped prompt from a form-state snapshot. | Internal submission slice composed by `useVideoGenForm`; all local, Grok, and federated request shaping remains in `videoGenSubmission`. |
| `useVideoGenValidation` | Derives keyframe errors and all VideoGen submit-blocking predicates from the current fields and model capabilities. | Internal validation slice composed by `useVideoGenForm`; also exports `validateVideoKeyframes` for focused tests. |
-| `useVideoDownload` | One full-video-download job slot (#1946): start/cancel + SSE progress + terminal-frame handling via `POST /api/devtools/video-download`. Returns `{ active, percent, stage, start(url), cancel }`; `onComplete(video)` fires with the finished video-history entry. | The Dev Tools Video Downloader page. |
+| `useVideoDownload` | One full-video-download job slot (#1946): start/cancel + SSE progress + terminal-frame handling via `POST /api/devtools/video-download`. Returns `{ active, percent, stage, context, start(url, context), cancel }`; `onComplete(video)` fires with the finished video-history entry. | The Dev Tools Video Downloader page. |
| `useReferenceAudioImport` | One round reference-audio-import job slot (#2120): start/cancel + SSE progress + terminal-frame handling via `POST /api/rounds/reference-audio/import`. Returns `{ active, percent, stage, start(url, context), cancel }`; `onComplete(filename, context)` fires with the uploads-dir filename to persist on the reference. Call once per surface that can independently kick off a download. | The reference-audio attach controls (`ReferenceAudioAttach`) — the "Download from URL" convenience. |
| `useMidiTranscription` | One audio → MIDI transcription job slot (MuScriptor): start/cancel + SSE stage progress + terminal-frame handling, generic over the Rounds and Music Video API surfaces (pass `startRequest`/`eventsUrl`/`cancelRequest`). Returns `{ active, stage, stageLabel, context, start(context), cancel }` (`stageLabel` is the ready-to-render human label for the current STAGE — including a distinct "Downloading model…" for the first-use weight download, which also fires a one-time toast; `context` is the in-flight job's captured target, for per-target UI gates); `onComplete(frame, context)` fires with the terminal frame (`filename`, `model`, any server-merged extras). | The Rounds reference "Transcribe MIDI" control and the Music Video MIDI button. |
| `useMusicVideoYoutubeImport` | The Music Video page's two independent `useYoutubeTrackImport` slots (create form + detail-view track row) plus their URL drafts, the detail slot's captured target project, and the URL-nav backstop that bounces a deep link / Back / ⌘K jump away from an in-flight import back to its project. Returns `{ createUrl, setCreateUrl, editUrl, setEditUrl, createJob, editJob, startCreate, startEdit, switchBlockedMessage }`. | The Music Video page. Reuse `switchBlockedMessage` for any additional guard (delete, list picker) so every surface says the same thing. |
diff --git a/client/src/hooks/useVideoDownload.js b/client/src/hooks/useVideoDownload.js
index dd51c82945..d1e69ce584 100644
--- a/client/src/hooks/useVideoDownload.js
+++ b/client/src/hooks/useVideoDownload.js
@@ -10,7 +10,7 @@ import useSseJobSlot from './useSseJobSlot.js';
* caller can prepend it to its list without a full refetch.
*/
export default function useVideoDownload({ onComplete } = {}) {
- const { active, percent, stage, start, cancel } = useSseJobSlot({
+ const { active, percent, stage, context, start, cancel } = useSseJobSlot({
startRequest: (url) => startVideoDownload(url, { silent: true }),
eventsUrl: videoDownloadEventsUrl,
cancelRequest: cancelVideoDownload,
@@ -22,5 +22,5 @@ export default function useVideoDownload({ onComplete } = {}) {
lostConnectionMessage: 'Lost connection to the download — check the list below',
startErrorFallback: 'Failed to start download',
});
- return { active, percent, stage, start, cancel };
+ return { active, percent, stage, context, start, cancel };
}
diff --git a/client/src/services/README.md b/client/src/services/README.md
index bdbade9a3d..97c7caeb85 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -89,8 +89,8 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiX.js` | X account diagnostics, public post metrics, review-gated drafts, and manual browser handoffs. |
| `apiContacts.js` | macOS Contacts sync + identity resolve + Tribe enrich (#2415). |
| `apiSignal.js` | Signal Desktop ingestion status / setup-check / sync. |
-| `apiSpotify.js` | Spotify OAuth + listening-history sync. |
-| `apiYoutube.js` | YouTube watch-history scrape sync + setup check. |
+| `apiSpotify.js` | Spotify OAuth + listening-history and playlist-library sync. |
+| `apiYoutube.js` | YouTube watch-history scrape, playlist/video library sync, and setup check. |
| `apiPersonalities.js` | Agent personality profiles. |
## Media / creative
diff --git a/client/src/services/apiSpotify.js b/client/src/services/apiSpotify.js
index 102aad33ee..9c66c12941 100644
--- a/client/src/services/apiSpotify.js
+++ b/client/src/services/apiSpotify.js
@@ -10,3 +10,5 @@ export const saveSpotifyCredentials = (data, options = {}) =>
export const clearSpotifyAuth = (options = {}) =>
request('/spotify/auth/clear', { method: 'POST', ...options });
export const syncSpotify = (options = {}) => request('/spotify/sync', { method: 'POST', ...options });
+export const getSpotifyPlaylists = (options = {}) => request('/spotify/playlists', options);
+export const syncSpotifyPlaylists = (options = {}) => request('/spotify/playlists/sync', { method: 'POST', ...options });
diff --git a/client/src/services/apiYoutube.js b/client/src/services/apiYoutube.js
index c3e884d80a..af5cdd7840 100644
--- a/client/src/services/apiYoutube.js
+++ b/client/src/services/apiYoutube.js
@@ -7,3 +7,5 @@ import { request } from './apiCore.js';
export const getYoutubeStatus = (options = {}) => request('/youtube/status', options);
export const getYoutubeSetupCheck = (options = {}) => request('/youtube/setup-check', options);
export const syncYoutube = (options = {}) => request('/youtube/sync', { method: 'POST', ...options });
+export const getYoutubePlaylists = (options = {}) => request('/youtube/playlists', options);
+export const syncYoutubePlaylists = (options = {}) => request('/youtube/playlists/sync', { method: 'POST', ...options });
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index a4a961614e..964460af1f 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -61,7 +61,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- App scaffolds / cloned repos / browser profiles — `data/repos`, `data/browser-profile` — inherently filesystem-oriented.
- Sprite animation-track definitions — `data/sprites/animation-tracks.json` (#3152). A small hand-editable authoring config: which animation types exist beyond the compiled-in `walk` (label, directionality, frame/fps bounds, prompt template, and the on-disk `setKind` strings). `file-primary` rather than `db-primary` because it is **machine-local and inseparable from the on-disk sprite tree it describes** — a row names the `setKind` an approved set under `data/sprites/{id}/` already carries, so the two travel together or neither means anything — and because it has no cross-record queries, no relationships beyond `kinds` strings, and no sync cursor. Read synchronously and cached per process (`server/services/sprites/animationTrackStore.js`): `server/lib/validation.js` builds sprite Zod ranges from it at module load, so it must resolve without `await`. Seeded from `data.reference/sprites/animation-tracks.json` (migration 211), which is also the fallback read when no user copy exists yet. Backed up in full by the rsync snapshot.
- Quota-burn plan — `data/cos/quota-burn.json` (#3390). The install's burn plan: master switch, poll interval, and per-provider-family windows + ordered job list. `file-primary` and **intentionally machine-local — never federated**: quota belongs to a particular machine and provider account, so a synced plan would have each peer spending against the other's window budget, and the plan's `agent-prompt` jobs name managed apps that only exist on this machine. No sync cursor, no tombstone. Its four companions are `ephemeral-file` — regenerable telemetry, all safe to delete: `data/cos/quota-burn-dispatches.json` (per-window dispatch counts, self-pruning at 30 days), `data/cos/quota-burn-runs.json` (capped run log), `data/cos/quota-burn-inflight.json` (entries a burn job has enqueued but whose renders have not completed, self-pruning at 6 hours — deleting it only risks re-queueing a render already in flight), and `data/cos/quota-burn-denials.json` (per-family blocks from an observed provider refusal, cleared by the next successful burn or a 5-hour TTL — deleting it only risks one dispatch into a still-exhausted window). Backed up with the rest of `data/cos/`; a restored plan simply re-applies on this machine. See [Quota Burn](./QUOTA-BURN.md).
-- YouTube brain ingests — `data/brain/youtube/{videoId}.md` (transcript), `{videoId}.mp3` (optional audio), plus `data/brain/youtube/index.json` (the ingest index) and `data/brain/youtube-ingest-settings.json`. The transcript IS an external file: it is mirrored into the user's Obsidian vault, edited there, and syncs through iCloud — the same boundary that keeps the Daily Log file-backed. The index is **intentionally machine-local — never federated**: every field in it is a local filesystem path, an Obsidian vault id, or a local video-history id, so a peer's copy would be meaningless and would poison brain reconcile exactly the way the daily log's `journal-obsidian-locations.json` sidecar would. The durable, federated record of "I consumed and kept this" is the brain `links` entry (`db-primary` via the brain store) plus a `media.watch` row in `human_activity_events`. No sync cursor, no tombstone. Adapter: `server/services/youtubeIngest.js`.
+- YouTube brain ingests — `data/brain/youtube/{videoId}.md` (transcript), `{videoId}.mp3` (optional audio), plus `data/brain/youtube/index.json` (the ingest index) and `data/brain/youtube-ingest-settings.json`. The transcript IS an external file: it is mirrored into the user's Obsidian vault, edited there, and syncs through iCloud — the same boundary that keeps the Daily Log file-backed. The index is **intentionally machine-local — never federated**: every field in it is a local filesystem path, an Obsidian vault id, or a local video-history id, so a peer's copy would be meaningless and would poison brain reconcile exactly the way the daily log's `journal-obsidian-locations.json` sidecar would. The playlist/video reference shelf at `data/youtube/playlists.json` follows the same local-only rule: it is a bounded cache of browser-scraped YouTube metadata and links, not a federated Brain record. The durable, federated record of "I consumed and kept this" is the brain `links` entry (`db-primary` via the brain store) plus a `media.watch` row in `human_activity_events`. No sync cursor, no tombstone. Adapters: `server/services/youtubeIngest.js` and `server/services/youtubePlaylists.js`.
- IdeaLoom lists — `data/brain/idealoom-lists/{uuid}/index.json` with a schema-stamped collection index holding the disabled-by-default local integration settings. Lists retain their ordered idea strings, prompt/title/category/status/help, timestamps, and importer-owned local sync metadata. Explicit exchange reads/writes only the configured vault's `Idea Loom/` folder through the specialized `server/services/idealoomObsidian.js` parser/renderer; new notes use a date/title filename and imported note paths remain stable. **Intentionally machine-local — never federated, reconciled, or memory-bridged**: a vault id, note path, and content hash are meaningful only on the install that configured them. Native Brain `ideas` remain a separate federated collection. Exchange is base-hash reconciled: a note and a list that both changed since the stored hash report `conflicted` and neither is written, and a note deleted in the vault reports `missing` rather than being recreated (an iCloud note that is merely un-downloaded is `unavailable`, a separate outcome). Opt-in automatic export (`autoSync`, off by default, debounced by `server/services/idealoomAutoSync.js`) can only update an existing note — it never deletes, recreates, or resolves a conflict. Backed up in full with the rest of `data/brain/`; the vault notes themselves are the user's Obsidian data and are outside PortOS's snapshot. Adapters: `server/services/idealoomLists.js` (records), `server/services/idealoomObsidian.js` (exchange).
- Local-model assessments — `data/local-llm/assessments.json` (#4539). Measured evidence for one installed local model per (backend, model): the fit verdict (`fits`/`does-not-fit`/`incompatible`/`unknown`), per-context throughput/TTFT samples, resident footprint, and the coarse hardware environment the measurement was taken in. `file-primary` — a flat, capped, single-JSON projection with no cross-record queries and no relationships; the newest measurement replaces the old one per model rather than accumulating history. **Intentionally machine-local — never federated**: an assessment is a claim about THIS box, so a peer inheriting a 128 GB machine's its verdict for its 8 GB laptop would be actively wrong. No sync cursor, no tombstone, no `PORTOS_SCHEMA_VERSIONS` entry. Backed up (a run costs the user minutes of local compute), and the environment record deliberately carries no hostname/username/path. Adapter: `server/services/localModelAssessmentStore.js` (durable store + environment capture; no path to a provider, so read-only consumers like the catalog fit badge can import it); the run lives in `server/services/localModelAssessments.js` and the scoring in `server/lib/localModelAssessment.js`. Each record's environment is re-compared against the live machine on read, so a reading taken before a RAM upgrade or backend update is flagged stale rather than silently trusted.
- LoRA training datasets — `data/lora-datasets/{id}/index.json` + `images/*.png` (collectionStore). The record is inseparable from the image bytes it organizes, has no cross-record queries beyond a small characterId scan, and is **machine-local** like `data/loras/` itself (training artifacts tied to this machine's GPU output — never federates, no sync cursor/tombstone). Backed up in full: uploads and hand-edited captions are not re-creatable. Training RUN records are `db-primary` (`lora_training_runs`); run artifacts (checkpoints/samples) live under `data/training-runs/{runId}/` with checkpoints/cache excluded from backup.
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index fd756d585a..633b721162 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -19389,7 +19389,7 @@
"sources": [
{
"source": "server/routes/spotify.js",
- "line": 71
+ "line": 87
}
]
},
@@ -19400,7 +19400,7 @@
"sources": [
{
"source": "server/routes/spotify.js",
- "line": 34
+ "line": 46
}
]
},
@@ -19411,7 +19411,7 @@
"sources": [
{
"source": "server/routes/spotify.js",
- "line": 45
+ "line": 57
}
]
},
@@ -19422,7 +19422,29 @@
"sources": [
{
"source": "server/routes/spotify.js",
- "line": 53
+ "line": 65
+ }
+ ]
+ },
+ {
+ "method": "GET",
+ "path": "/api/spotify/playlists",
+ "mountPath": "/api/spotify",
+ "sources": [
+ {
+ "source": "server/routes/spotify.js",
+ "line": 35
+ }
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/spotify/playlists/sync",
+ "mountPath": "/api/spotify",
+ "sources": [
+ {
+ "source": "server/routes/spotify.js",
+ "line": 41
}
]
},
@@ -19433,7 +19455,7 @@
"sources": [
{
"source": "server/routes/spotify.js",
- "line": 28
+ "line": 29
}
]
},
@@ -19444,7 +19466,7 @@
"sources": [
{
"source": "server/routes/spotify.js",
- "line": 78
+ "line": 94
}
]
},
@@ -23254,6 +23276,28 @@
}
]
},
+ {
+ "method": "GET",
+ "path": "/api/youtube/playlists",
+ "mountPath": "/api/youtube",
+ "sources": [
+ {
+ "source": "server/routes/youtube.js",
+ "line": 26
+ }
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/youtube/playlists/sync",
+ "mountPath": "/api/youtube",
+ "sources": [
+ {
+ "source": "server/routes/youtube.js",
+ "line": 33
+ }
+ ]
+ },
{
"method": "GET",
"path": "/api/youtube/setup-check",
@@ -23261,7 +23305,7 @@
"sources": [
{
"source": "server/routes/youtube.js",
- "line": 11
+ "line": 12
}
]
},
@@ -23272,7 +23316,7 @@
"sources": [
{
"source": "server/routes/youtube.js",
- "line": 18
+ "line": 19
}
]
},
@@ -23283,7 +23327,7 @@
"sources": [
{
"source": "server/routes/youtube.js",
- "line": 25
+ "line": 39
}
]
},
diff --git a/server/routes/spotify.js b/server/routes/spotify.js
index 819eafd01f..e7cc3849b9 100644
--- a/server/routes/spotify.js
+++ b/server/routes/spotify.js
@@ -5,6 +5,7 @@ import { asyncHandler } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import * as spotifyAuth from '../services/spotifyAuth.js';
import * as spotifySync from '../services/spotifySync.js';
+import * as spotifyPlaylists from '../services/spotifyPlaylists.js';
const router = Router();
@@ -30,6 +31,17 @@ router.get('/status', asyncHandler(async (req, res) => {
res.json(status);
}));
+// Read the last machine-local playlist snapshot without contacting Spotify.
+router.get('/playlists', asyncHandler(async (_req, res) => {
+ const snapshot = await spotifyPlaylists.getStoredPlaylists();
+ res.json({ snapshot, summary: spotifyPlaylists.playlistSnapshotSummary(snapshot) });
+}));
+
+// Explicit user action — fetch current playlists and their track metadata.
+router.post('/playlists/sync', asyncHandler(async (_req, res) => {
+ res.json(await spotifyPlaylists.syncSpotifyPlaylists());
+}));
+
// Save the user-created Spotify developer app credentials (client id/secret).
router.post('/auth/credentials', asyncHandler(async (req, res) => {
const schema = z.object({
@@ -57,14 +69,18 @@ router.get('/oauth/callback', asyncHandler(async (req, res) => {
const { code, error: authError } = req.query;
if (authError) return res.redirect(settingsUrl(String(authError)));
if (!code) return res.redirect(settingsUrl('Missing authorization code'));
- const error = await spotifyAuth.handleCallback(String(code), requestRedirectOptions(req)).then(() => null)
+ const callback = await spotifyAuth.handleCallback(String(code), requestRedirectOptions(req)).then((result) => ({ result }))
.catch((err) => {
// This catch replaces asyncHandler's logging (the redirect swallows the
// throw), so keep the failure visible in server logs.
console.error(`❌ Spotify OAuth callback failed: ${err.message}`);
- return err.message || 'Spotify OAuth callback failed';
+ return { error: err.message || 'Spotify OAuth callback failed' };
});
- res.redirect(settingsUrl(error));
+ if (callback.error) return res.redirect(settingsUrl(callback.error));
+ console.log(callback.result?.duplicate
+ ? '🎧 Spotify OAuth callback replay ignored; tokens already stored'
+ : '🎧 Spotify OAuth callback processed, tokens stored');
+ res.redirect(settingsUrl());
}));
// Disconnect — clear stored tokens (leaves the client id/secret in place).
diff --git a/server/routes/spotify.test.js b/server/routes/spotify.test.js
index 836c3ddf10..1fc4fb53d1 100644
--- a/server/routes/spotify.test.js
+++ b/server/routes/spotify.test.js
@@ -10,6 +10,9 @@ const mocks = vi.hoisted(() => ({
saveCredentials: vi.fn(async (_data, options) => ({ redirectUri: mocks.getRedirectUri(options) })),
handleCallback: vi.fn(async () => ({ success: true })),
clearAuth: vi.fn(async () => ({ cleared: true })),
+ getStoredPlaylists: vi.fn(async () => ({ playlists: [] })),
+ playlistSnapshotSummary: vi.fn(() => ({ playlistCount: 0, trackCount: 0 })),
+ syncSpotifyPlaylists: vi.fn(async () => ({ ok: true, playlistCount: 1, trackCount: 2 })),
}));
vi.mock('../services/spotifyAuth.js', () => ({
@@ -25,6 +28,12 @@ vi.mock('../services/spotifySync.js', () => ({
runSync: vi.fn(),
}));
+vi.mock('../services/spotifyPlaylists.js', () => ({
+ getStoredPlaylists: (...args) => mocks.getStoredPlaylists(...args),
+ playlistSnapshotSummary: (...args) => mocks.playlistSnapshotSummary(...args),
+ syncSpotifyPlaylists: (...args) => mocks.syncSpotifyPlaylists(...args),
+}));
+
import spotifyRoutes from './spotify.js';
function makeApp() {
@@ -58,4 +67,16 @@ describe('Spotify routes', () => {
expect(mocks.getAuthUrl).toHaveBeenCalledWith({ origin: 'https://host-example.ts.net:5555' });
});
+
+ it('serves the stored playlist snapshot and starts an explicit playlist sync', async () => {
+ const app = makeApp();
+ const snapshot = await request(app).get('/api/spotify/playlists');
+ expect(snapshot.status).toBe(200);
+ expect(snapshot.body).toMatchObject({ snapshot: { playlists: [] }, summary: { playlistCount: 0 } });
+
+ const sync = await request(app).post('/api/spotify/playlists/sync');
+ expect(sync.status).toBe(200);
+ expect(sync.body).toMatchObject({ ok: true, playlistCount: 1, trackCount: 2 });
+ expect(mocks.syncSpotifyPlaylists).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/server/routes/youtube.js b/server/routes/youtube.js
index a789a7d9e5..715d68653a 100644
--- a/server/routes/youtube.js
+++ b/server/routes/youtube.js
@@ -2,6 +2,7 @@ import { Router } from 'express';
import { asyncHandler } from '../lib/errorHandler.js';
import * as youtubeSync from '../services/youtubeSync.js';
+import * as youtubePlaylists from '../services/youtubePlaylists.js';
const router = Router();
@@ -20,6 +21,19 @@ router.get('/status', asyncHandler(async (req, res) => {
res.json(status);
}));
+// Read the last machine-local playlist/video snapshot without opening the
+// managed browser.
+router.get('/playlists', asyncHandler(async (_req, res) => {
+ const snapshot = await youtubePlaylists.getStoredYoutubePlaylists();
+ res.json({ snapshot, summary: youtubePlaylists.youtubePlaylistSnapshotSummary(snapshot) });
+}));
+
+// Explicit user action — scrape playlists and their video rows in the managed
+// browser. Downloading a video remains a separate, explicit downloader action.
+router.post('/playlists/sync', asyncHandler(async (_req, res) => {
+ res.json(await youtubePlaylists.syncYoutubePlaylists());
+}));
+
// Run one scrape pass now (explicit user action). Returns the pass summary, or a
// status report when the browser isn't running / is signed out.
router.post('/sync', asyncHandler(async (req, res) => {
diff --git a/server/routes/youtube.test.js b/server/routes/youtube.test.js
new file mode 100644
index 0000000000..4f17da88d3
--- /dev/null
+++ b/server/routes/youtube.test.js
@@ -0,0 +1,36 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+const mocks = vi.hoisted(() => ({
+ getStatus: vi.fn(async () => ({ state: {} })), checkSetup: vi.fn(async () => ({ ok: true })),
+ runSync: vi.fn(async () => ({ ok: true, recorded: 1 })), getStoredYoutubePlaylists: vi.fn(async () => ({ playlists: [] })),
+ youtubePlaylistSnapshotSummary: vi.fn(() => ({ playlistCount: 0, videoCount: 0 })),
+ syncYoutubePlaylists: vi.fn(async () => ({ ok: true, playlistCount: 1, videoCount: 2 })),
+}));
+vi.mock('../services/youtubeSync.js', () => ({
+ getStatus: (...args) => mocks.getStatus(...args), checkSetup: (...args) => mocks.checkSetup(...args), runSync: (...args) => mocks.runSync(...args),
+}));
+vi.mock('../services/youtubePlaylists.js', () => ({
+ getStoredYoutubePlaylists: (...args) => mocks.getStoredYoutubePlaylists(...args), youtubePlaylistSnapshotSummary: (...args) => mocks.youtubePlaylistSnapshotSummary(...args),
+ syncYoutubePlaylists: (...args) => mocks.syncYoutubePlaylists(...args),
+}));
+import youtubeRoutes from './youtube.js';
+
+function makeApp() {
+ const app = express(); app.use('/api/youtube', youtubeRoutes); app.use(errorMiddleware); return app;
+}
+describe('YouTube playlist routes', () => {
+ beforeEach(() => vi.clearAllMocks());
+ it('serves the stored library and starts an explicit playlist sync', async () => {
+ const app = makeApp();
+ const snapshot = await request(app).get('/api/youtube/playlists');
+ expect(snapshot.status).toBe(200);
+ expect(snapshot.body).toMatchObject({ snapshot: { playlists: [] }, summary: { playlistCount: 0 } });
+ const sync = await request(app).post('/api/youtube/playlists/sync');
+ expect(sync.status).toBe(200);
+ expect(sync.body).toMatchObject({ ok: true, playlistCount: 1, videoCount: 2 });
+ expect(mocks.syncYoutubePlaylists).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/server/services/spotifyAuth.js b/server/services/spotifyAuth.js
index 39ef9ff89c..f6b964df3f 100644
--- a/server/services/spotifyAuth.js
+++ b/server/services/spotifyAuth.js
@@ -35,10 +35,14 @@ const AUTH_DIR = dataPath('spotify');
const CREDENTIALS_FILE = dataPath('spotify', 'credentials.json');
const TOKENS_FILE = dataPath('spotify', 'tokens.json');
-// Only the read-recently-played scope is required for history ingestion.
-// (`user-read-playback-state` would enable a future live "now playing" — out of
-// scope here, so we keep the grant minimal.)
-export const SPOTIFY_SCOPES = ['user-read-recently-played'];
+// These are the minimal read-only scopes for history ingestion plus the
+// playlist reference library. (`user-read-playback-state` would enable a
+// future live "now playing" feature, so it remains out of scope.)
+export const SPOTIFY_SCOPES = [
+ 'user-read-recently-played',
+ 'playlist-read-private',
+ 'playlist-read-collaborative',
+];
const ACCOUNTS_BASE = 'https://accounts.spotify.com';
@@ -178,7 +182,7 @@ export async function getAuthUrl(options = {}) {
return { url: `${ACCOUNTS_BASE}/authorize?${params.toString()}` };
}
-export async function handleCallback(code, options = {}) {
+async function processCallback(code, options = {}) {
const tokens = await requestToken({
grant_type: 'authorization_code',
code,
@@ -189,6 +193,34 @@ export async function handleCallback(code, options = {}) {
return { success: true };
}
+// Spotify authorization codes are single-use. Browsers and reverse proxies can
+// replay a redirect while the first callback is still settling, and Spotify
+// then reports the second request as "Invalid authorization code" even though
+// the first request successfully stored the tokens. Remember successful codes
+// briefly so an immediate replay is a harmless success.
+const completedCallbacks = new Map();
+const callbackInFlight = new Map();
+const CALLBACK_REPLAY_WINDOW_MS = 120000;
+
+export async function handleCallback(code, options = {}) {
+ const key = `${code}\u0000${getRedirectUri(options)}`;
+ const prior = completedCallbacks.get(key);
+ if (prior && Date.now() - prior.completedAt < CALLBACK_REPLAY_WINDOW_MS) {
+ return { ...prior.result, duplicate: true };
+ }
+ const active = callbackInFlight.get(key);
+ if (active) return active;
+ const promise = processCallback(code, options).then((result) => {
+ completedCallbacks.set(key, { completedAt: Date.now(), result });
+ for (const [cachedKey, cached] of completedCallbacks) {
+ if (Date.now() - cached.completedAt >= CALLBACK_REPLAY_WINDOW_MS) completedCallbacks.delete(cachedKey);
+ }
+ return result;
+ }).finally(() => callbackInFlight.delete(key));
+ callbackInFlight.set(key, promise);
+ return promise;
+}
+
// Single-flight guard: while one refresh is in flight, concurrent callers await
// the same promise instead of each POSTing their own refresh (Spotify rotates
// the grant, so a double-refresh means the loser writes a stale token — classic
diff --git a/server/services/spotifyAuth.test.js b/server/services/spotifyAuth.test.js
index 279dcf5f02..7167395cde 100644
--- a/server/services/spotifyAuth.test.js
+++ b/server/services/spotifyAuth.test.js
@@ -28,7 +28,7 @@ vi.mock('../lib/httpsState.js', () => ({
getHttpsEnabledAtBoot: (...args) => mocks.getHttpsEnabledAtBoot(...args),
}));
-import { isTokenExpired, withExpiry, getRedirectUri, getAuthStatus, getAccessToken } from './spotifyAuth.js';
+import { isTokenExpired, withExpiry, getRedirectUri, getAuthStatus, getAccessToken, handleCallback, SPOTIFY_SCOPES } from './spotifyAuth.js';
describe('spotifyAuth pure helpers', () => {
describe('withExpiry', () => {
@@ -214,3 +214,32 @@ describe('getAccessToken', () => {
expect(mocks.fetchWithTimeout).toHaveBeenCalledTimes(2);
});
});
+
+describe('handleCallback', () => {
+ it('requests playlist scopes for the expanded Brain integration', () => {
+ expect(SPOTIFY_SCOPES).toEqual([
+ 'user-read-recently-played',
+ 'playlist-read-private',
+ 'playlist-read-collaborative',
+ ]);
+ });
+
+ it('single-flights and replays a successful callback without reusing the code', async () => {
+ mocks.tryReadFile.mockImplementation(async (path) => (
+ String(path).endsWith('credentials.json')
+ ? JSON.stringify({ clientId: 'cid', clientSecret: 'secret' })
+ : null
+ ));
+ let resolveFetch;
+ mocks.fetchWithTimeout.mockReturnValue(new Promise((resolve) => { resolveFetch = resolve; }));
+
+ const first = handleCallback('one-time-code');
+ const second = handleCallback('one-time-code');
+ while (mocks.fetchWithTimeout.mock.calls.length === 0) await new Promise((resolve) => setTimeout(resolve, 0));
+ resolveFetch({ ok: true, json: async () => ({ access_token: 'fresh', refresh_token: 'refresh', expires_in: 3600 }) });
+
+ await expect(Promise.all([first, second])).resolves.toEqual([{ success: true }, { success: true }]);
+ await expect(handleCallback('one-time-code')).resolves.toMatchObject({ success: true, duplicate: true });
+ expect(mocks.fetchWithTimeout).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/server/services/spotifyPlaylists.js b/server/services/spotifyPlaylists.js
new file mode 100644
index 0000000000..4efbf17f81
--- /dev/null
+++ b/server/services/spotifyPlaylists.js
@@ -0,0 +1,178 @@
+/**
+ * Spotify playlist ingestion for the Brain taste library.
+ *
+ * Playlists are machine-local reference material. We persist bounded Spotify
+ * metadata (playlist names, descriptions, track/artist/album names, artwork
+ * URLs, and service links) under data/spotify/; raw API responses never leave
+ * the request and this snapshot is not part of federation.
+ */
+import { dataPath, ensureDir, atomicWrite, readJSONFile } from '../lib/fileUtils.js';
+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
+import { getAccessToken } from './spotifyAuth.js';
+
+const API_BASE = 'https://api.spotify.com/v1';
+const REQUEST_TIMEOUT_MS = 15000;
+const PAGE_LIMIT = 50;
+const PLAYLISTS_FILE = dataPath('spotify', 'playlists.json');
+const SNAPSHOT_VERSION = 1;
+
+const playlistUrl = (id) => `https://open.spotify.com/playlist/${encodeURIComponent(id)}`;
+
+const imageShape = (image) => {
+ if (!image?.url || !/^https:\/\//i.test(image.url)) return null;
+ return {
+ url: image.url,
+ ...(Number.isFinite(image.height) ? { height: image.height } : {}),
+ ...(Number.isFinite(image.width) ? { width: image.width } : {}),
+ };
+};
+
+const trackShape = (raw) => {
+ const track = raw?.item || raw?.track;
+ if (!track?.id || !track?.name) return null;
+ const artists = Array.isArray(track.artists)
+ ? track.artists.map((artist) => ({ id: artist?.id || null, name: String(artist?.name || '').trim() }))
+ .filter((artist) => artist.name)
+ : [];
+ return {
+ id: track.id,
+ name: track.name,
+ artists,
+ album: track.album?.name || null,
+ albumId: track.album?.id || null,
+ durationMs: Number.isFinite(track.duration_ms) ? track.duration_ms : null,
+ explicit: typeof track.explicit === 'boolean' ? track.explicit : null,
+ isLocal: track.is_local === true,
+ spotifyUrl: track.external_urls?.spotify || `https://open.spotify.com/track/${encodeURIComponent(track.id)}`,
+ addedAt: raw.added_at || null,
+ };
+};
+
+export function normalizeSpotifyTrack(raw) {
+ return trackShape(raw);
+}
+
+export function normalizeSpotifyPlaylist(raw, tracks = []) {
+ if (!raw?.id || !raw?.name) return null;
+ return {
+ id: raw.id,
+ name: raw.name,
+ description: raw.description || '',
+ public: typeof raw.public === 'boolean' ? raw.public : null,
+ collaborative: raw.collaborative === true,
+ trackCount: Number.isFinite(raw.tracks?.total) ? raw.tracks.total : tracks.length,
+ spotifyUrl: raw.external_urls?.spotify || playlistUrl(raw.id),
+ images: Array.isArray(raw.images) ? raw.images.map(imageShape).filter(Boolean) : [],
+ tracks,
+ };
+}
+
+export function playlistSnapshotSummary(snapshot) {
+ const playlists = Array.isArray(snapshot?.playlists) ? snapshot.playlists : [];
+ return {
+ playlistCount: playlists.length,
+ trackCount: playlists.reduce((total, playlist) => total + (playlist.tracks?.length || 0), 0),
+ syncedAt: snapshot?.syncedAt || null,
+ warningCount: Array.isArray(snapshot?.warnings) ? snapshot.warnings.length : 0,
+ };
+}
+
+async function fetchJson(url, accessToken) {
+ const response = await fetchWithTimeout(url, {
+ headers: { Authorization: `Bearer ${accessToken}` },
+ }, REQUEST_TIMEOUT_MS);
+ const payload = await response.json().catch(() => ({}));
+ if (!response.ok) {
+ throw new Error(`Spotify API returned ${response.status}${payload?.error?.message ? `: ${payload.error.message}` : ''}`);
+ }
+ return payload;
+}
+
+async function fetchPages(path, accessToken) {
+ const items = [];
+ let offset = 0;
+ let total = null;
+ do {
+ const page = await fetchJson(`${API_BASE}${path}?limit=${PAGE_LIMIT}&offset=${offset}`, accessToken);
+ const pageItems = Array.isArray(page?.items) ? page.items : [];
+ items.push(...pageItems);
+ total = Number.isFinite(page?.total) ? page.total : null;
+ offset += pageItems.length;
+ } while (items.length && (total === null ? items.length >= PAGE_LIMIT : offset < total));
+ return items;
+}
+
+async function fetchPlaylist(playlist, accessToken) {
+ const items = await fetchPages(`/playlists/${encodeURIComponent(playlist.id)}/items`, accessToken);
+ const tracks = items.map(normalizeSpotifyTrack).filter(Boolean);
+ return normalizeSpotifyPlaylist(playlist, tracks);
+}
+
+export async function getStoredPlaylists() {
+ return readJSONFile(PLAYLISTS_FILE, null);
+}
+
+let syncInFlight = null;
+
+export async function syncSpotifyPlaylists() {
+ if (syncInFlight) return syncInFlight;
+ syncInFlight = doSyncSpotifyPlaylists().finally(() => { syncInFlight = null; });
+ return syncInFlight;
+}
+
+async function doSyncSpotifyPlaylists() {
+ const accessToken = await getAccessToken().catch((error) => {
+ console.error(`❌ Spotify playlist sync auth failed: ${error?.message || error}`);
+ return null;
+ });
+ if (!accessToken) {
+ return { ok: false, needsAuth: true, error: 'Spotify not connected — authorize in Brain → Spotify.' };
+ }
+
+ const previous = await getStoredPlaylists();
+ const playlistResult = await fetchPages('/me/playlists', accessToken)
+ .then((value) => ({ value }))
+ .catch((error) => ({ error }));
+ if (playlistResult.error) {
+ const error = playlistResult.error;
+ console.error(`❌ Spotify playlist list failed: ${error.message}`);
+ return { ok: false, error: error.message };
+ }
+ const playlistSummaries = playlistResult.value;
+
+ const results = await Promise.allSettled(playlistSummaries.map((playlist) => fetchPlaylist(playlist, accessToken)));
+ const previousById = new Map((previous?.playlists || []).map((playlist) => [playlist.id, playlist]));
+ const warnings = [];
+ const playlists = [];
+ results.forEach((result, index) => {
+ const summary = playlistSummaries[index];
+ if (result.status === 'fulfilled' && result.value) {
+ playlists.push(result.value);
+ return;
+ }
+ const message = result.reason?.message || 'Could not read playlist items';
+ warnings.push(`${summary?.name || 'Playlist'}: ${message}`);
+ const stale = previousById.get(summary?.id);
+ if (stale) playlists.push(stale);
+ });
+
+ const snapshot = {
+ schemaVersion: SNAPSHOT_VERSION,
+ syncedAt: new Date().toISOString(),
+ playlists,
+ warnings,
+ };
+ await ensureDir(dataPath('spotify'));
+ await atomicWrite(PLAYLISTS_FILE, snapshot);
+
+ const summary = playlistSnapshotSummary(snapshot);
+ const result = {
+ ok: warnings.length === 0,
+ ...summary,
+ scanned: playlistSummaries.length,
+ failed: warnings.length,
+ ...(warnings.length ? { warnings } : {}),
+ };
+ console.log(`🎧 Spotify playlists: synced ${summary.playlistCount} playlist(s), ${summary.trackCount} track(s)${warnings.length ? `, ${warnings.length} warning(s)` : ''}`);
+ return result;
+}
diff --git a/server/services/spotifyPlaylists.test.js b/server/services/spotifyPlaylists.test.js
new file mode 100644
index 0000000000..d7286aa365
--- /dev/null
+++ b/server/services/spotifyPlaylists.test.js
@@ -0,0 +1,58 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ getAccessToken: vi.fn(), fetchWithTimeout: vi.fn(), readJSONFile: vi.fn(), ensureDir: vi.fn(), atomicWrite: vi.fn(),
+}));
+
+vi.mock('./spotifyAuth.js', () => ({ getAccessToken: (...args) => mocks.getAccessToken(...args) }));
+vi.mock('../lib/fetchWithTimeout.js', () => ({ fetchWithTimeout: (...args) => mocks.fetchWithTimeout(...args) }));
+vi.mock('../lib/fileUtils.js', () => ({
+ dataPath: (...parts) => `/tmp/${parts.join('/')}`, readJSONFile: (...args) => mocks.readJSONFile(...args),
+ ensureDir: (...args) => mocks.ensureDir(...args), atomicWrite: (...args) => mocks.atomicWrite(...args),
+}));
+
+import { normalizeSpotifyPlaylist, normalizeSpotifyTrack, playlistSnapshotSummary, syncSpotifyPlaylists } from './spotifyPlaylists.js';
+
+const playlist = {
+ id: 'playlist-1', name: 'Example playlist', description: 'A reference shelf', public: false, collaborative: false,
+ tracks: { total: 1 }, external_urls: { spotify: 'https://open.spotify.com/playlist/playlist-1' },
+ images: [{ url: 'https://i.scdn.co/image/example', height: 300, width: 300 }],
+};
+const trackItem = {
+ added_at: '2026-08-29T09:00:00Z', item: {
+ id: 'track-1', name: 'Example track', artists: [{ id: 'artist-1', name: 'Example artist' }],
+ album: { id: 'album-1', name: 'Example album' }, duration_ms: 180000,
+ external_urls: { spotify: 'https://open.spotify.com/track/track-1' },
+ },
+};
+
+describe('Spotify playlist normalization', () => {
+ it('keeps bounded playlist and track metadata with Spotify links', () => {
+ expect(normalizeSpotifyTrack(trackItem)).toMatchObject({ id: 'track-1', name: 'Example track', album: 'Example album' });
+ expect(normalizeSpotifyPlaylist(playlist, [normalizeSpotifyTrack(trackItem)])).toMatchObject({
+ id: 'playlist-1', name: 'Example playlist', trackCount: 1, tracks: [{ id: 'track-1' }],
+ });
+ });
+ it('summarizes a missing snapshot as unsynced', () => {
+ expect(playlistSnapshotSummary(null)).toEqual({ playlistCount: 0, trackCount: 0, syncedAt: null, warningCount: 0 });
+ });
+});
+
+describe('syncSpotifyPlaylists', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getAccessToken.mockResolvedValue('access-token');
+ mocks.readJSONFile.mockResolvedValue(null);
+ mocks.fetchWithTimeout
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ total: 1, items: [playlist] }) })
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ total: 1, items: [trackItem] }) });
+ });
+ it('fetches playlists and items, then writes one local snapshot', async () => {
+ const result = await syncSpotifyPlaylists();
+ expect(result).toMatchObject({ ok: true, playlistCount: 1, trackCount: 1, scanned: 1, failed: 0 });
+ expect(mocks.fetchWithTimeout).toHaveBeenCalledTimes(2);
+ expect(mocks.fetchWithTimeout.mock.calls[0][0].toString()).toContain('/me/playlists?limit=50&offset=0');
+ expect(mocks.fetchWithTimeout.mock.calls[1][0].toString()).toContain('/playlists/playlist-1/items?limit=50&offset=0');
+ expect(mocks.atomicWrite).toHaveBeenCalledWith('/tmp/spotify/playlists.json', expect.objectContaining({ schemaVersion: 1 }));
+ });
+});
diff --git a/server/services/youtubePlaylists.js b/server/services/youtubePlaylists.js
new file mode 100644
index 0000000000..0fe7c2ca82
--- /dev/null
+++ b/server/services/youtubePlaylists.js
@@ -0,0 +1,213 @@
+/**
+ * YouTube playlist and saved-video reference ingestion for Brain.
+ *
+ * YouTube has no usable watch-history API for this feature, so this follows the
+ * existing managed-browser boundary used by youtubeSync. The snapshot is local
+ * to this install and contains only bounded display metadata plus source URLs;
+ * video bytes are fetched only after the user explicitly starts a download.
+ */
+import { dataPath, ensureDir, atomicWrite, readJSONFile, sleep } from '../lib/fileUtils.js';
+import { findOrOpenPage, isAuthPage, evaluateOnPage } from './browserService.js';
+
+const PLAYLISTS_URL = 'https://www.youtube.com/feed/playlists';
+const PLAYLIST_URL = 'https://www.youtube.com/playlist?list=';
+const PLAYLISTS_FILE = dataPath('youtube', 'playlists.json');
+const SNAPSHOT_VERSION = 1;
+const MAX_PLAYLISTS = 100;
+const MAX_VIDEOS_PER_PLAYLIST = 200;
+const NAV_SETTLE_MS = 2500;
+
+export function youtubePlaylistIdFromUrl(value) {
+ const match = /^(?:https?:\/\/)(?:www\.)?youtube\.com\/playlist\?[^#]*\blist=([^&#]+)/i.exec(String(value || ''));
+ return match ? match[1] : null;
+}
+
+export function normalizeYoutubeVideo(raw) {
+ if (!raw?.id || !raw?.title) return null;
+ return {
+ id: raw.id,
+ title: raw.title,
+ channel: raw.channel || null,
+ thumbnail: raw.thumbnail && /^https:\/\//i.test(raw.thumbnail) ? raw.thumbnail : null,
+ url: `https://www.youtube.com/watch?v=${encodeURIComponent(raw.id)}`,
+ duration: raw.duration || null,
+ };
+}
+
+export function normalizeYoutubePlaylist(raw, videos = []) {
+ if (!raw?.id || !raw?.name) return null;
+ return {
+ id: raw.id,
+ name: raw.name,
+ videoCount: Number.isFinite(raw.videoCount) ? raw.videoCount : videos.length,
+ url: `https://www.youtube.com/playlist?list=${encodeURIComponent(raw.id)}`,
+ thumbnail: raw.thumbnail && /^https:\/\//i.test(raw.thumbnail) ? raw.thumbnail : null,
+ videos,
+ };
+}
+
+export function youtubePlaylistSnapshotSummary(snapshot) {
+ const playlists = Array.isArray(snapshot?.playlists) ? snapshot.playlists : [];
+ return {
+ playlistCount: playlists.length,
+ videoCount: playlists.reduce((total, playlist) => total + (playlist.videos?.length || 0), 0),
+ syncedAt: snapshot?.syncedAt || null,
+ warningCount: Array.isArray(snapshot?.warnings) ? snapshot.warnings.length : 0,
+ };
+}
+
+function buildPlaylistsExtractionScript() {
+ return `
+ (async () => {
+ const signedOut = /accounts\.google\.com|\/ServiceLogin/i.test(location.href)
+ || (!!document.querySelector('a[href*="ServiceLogin"]') && !document.querySelector('#avatar-btn, button#avatar-btn, #masthead #avatar'));
+ if (signedOut) return { signedOut: true, playlists: [] };
+ const abs = (href) => { try { return new URL(href, location.origin).href; } catch { return href || null; } };
+ const seen = new Set();
+ const playlists = [];
+ const collect = () => Array.from(document.querySelectorAll('ytd-playlist-renderer, ytd-grid-playlist-renderer, ytd-playlist-card-renderer')).map((card) => {
+ const link = Array.from(card.querySelectorAll('a[href*="list="]'))[0];
+ const url = link ? abs(link.getAttribute('href')) : null;
+ let id = null;
+ try { id = url ? new URL(url).searchParams.get('list') : null; } catch {}
+ const titleEl = card.querySelector('a#video-title, #video-title, #video-title-link');
+ const image = card.querySelector('img');
+ const text = (card.textContent || '').replace(/\\s+/g, ' ').trim();
+ const count = text.match(/([\\d,]+)\\s+videos?/i);
+ return { id, name: (titleEl?.textContent || link?.textContent || '').trim(), videoCount: count ? Number(count[1].replace(/,/g, '')) : null, thumbnail: image?.src || image?.getAttribute('data-thumb') || null };
+ });
+ const append = (items) => items.forEach((item) => {
+ if (item.id && !seen.has(item.id)) { seen.add(item.id); playlists.push(item); }
+ });
+ append(collect());
+ // Playlist pages hydrate additional cards as the feed scrolls. Keep the
+ // scrape bounded while giving the page a chance to reveal them.
+ let previousHeight = 0;
+ for (let i = 0; i < 8 && playlists.length < ${MAX_PLAYLISTS}; i++) {
+ window.scrollTo(0, document.documentElement.scrollHeight);
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ const height = document.documentElement.scrollHeight;
+ if (height === previousHeight) break;
+ previousHeight = height;
+ append(collect());
+ }
+ if (playlists.length === 0) return { signedOut: false, playlists: [] };
+ return { signedOut: false, playlists: playlists.slice(0, ${MAX_PLAYLISTS}) };
+ })()
+ `;
+}
+
+function buildPlaylistVideosExtractionScript() {
+ return `
+ (async () => {
+ const signedOut = /accounts\.google\.com|\/ServiceLogin/i.test(location.href)
+ || (!!document.querySelector('a[href*="ServiceLogin"]') && !document.querySelector('#avatar-btn, button#avatar-btn, #masthead #avatar'));
+ if (signedOut) return { signedOut: true, videos: [] };
+ const abs = (href) => { try { return new URL(href, location.origin).href; } catch { return href || null; } };
+ const seen = new Set();
+ const videos = [];
+ const collect = () => Array.from(document.querySelectorAll('ytd-playlist-video-renderer, ytd-playlist-panel-video-renderer, ytd-grid-video-renderer')).map((row) => {
+ const titleEl = row.querySelector('a#video-title, a#video-title-link');
+ const url = titleEl ? abs(titleEl.getAttribute('href')) : null;
+ let id = null;
+ try { id = url ? new URL(url).searchParams.get('v') : null; } catch {}
+ const channelEl = row.querySelector('#byline a, ytd-channel-name a, #channel-name a');
+ const image = row.querySelector('img');
+ const durationEl = row.querySelector('ytd-thumbnail-overlay-time-status-renderer span, #text.ytd-thumbnail-overlay-time-status-renderer');
+ return { id, title: (titleEl?.textContent || '').trim(), channel: (channelEl?.textContent || '').trim() || null, thumbnail: image?.src || image?.getAttribute('data-thumb') || null, duration: (durationEl?.textContent || '').trim() || null };
+ });
+ const append = (items) => items.forEach((item) => {
+ if (item.id && !seen.has(item.id)) { seen.add(item.id); videos.push(item); }
+ });
+ append(collect());
+ let previousHeight = 0;
+ for (let i = 0; i < 12 && videos.length < ${MAX_VIDEOS_PER_PLAYLIST}; i++) {
+ window.scrollTo(0, document.documentElement.scrollHeight);
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ const height = document.documentElement.scrollHeight;
+ if (height === previousHeight) break;
+ previousHeight = height;
+ append(collect());
+ }
+ return { signedOut: false, videos: videos.slice(0, ${MAX_VIDEOS_PER_PLAYLIST}) };
+ })()
+ `;
+}
+
+async function loadPage(url) {
+ const page = await findOrOpenPage(url).catch(() => null);
+ if (!page || isAuthPage(page)) return { page: null, status: page ? 'auth-required' : 'no-browser' };
+ return { page, status: 'ok' };
+}
+
+export async function getStoredYoutubePlaylists() {
+ return readJSONFile(PLAYLISTS_FILE, null);
+}
+
+let syncInFlight = null;
+
+export async function syncYoutubePlaylists() {
+ if (syncInFlight) return syncInFlight;
+ syncInFlight = doSyncYoutubePlaylists().finally(() => { syncInFlight = null; });
+ return syncInFlight;
+}
+
+async function doSyncYoutubePlaylists() {
+ const loaded = await loadPage(PLAYLISTS_URL);
+ if (!loaded.page) {
+ return loaded.status === 'auth-required'
+ ? { ok: false, status: loaded.status, needsAuth: true, error: 'Signed out of YouTube', remediation: 'Log into YouTube in the managed browser, then sync playlists again.' }
+ : { ok: false, status: loaded.status, error: 'Managed browser is not running', remediation: 'Start the managed browser, then sync playlists again.' };
+ }
+
+ const extracted = await evaluateOnPage(loaded.page, buildPlaylistsExtractionScript()).catch(() => null);
+ if (!extracted || !Array.isArray(extracted.playlists)) {
+ return { ok: false, status: 'extraction-failed', error: 'Could not read YouTube playlists — the page layout may have changed.' };
+ }
+ if (extracted.signedOut) {
+ return { ok: false, status: 'auth-required', needsAuth: true, error: 'Signed out of YouTube', remediation: 'Log into YouTube in the managed browser, then sync playlists again.' };
+ }
+
+ const previous = await getStoredYoutubePlaylists();
+ const playlists = [];
+ const warnings = [];
+ const sourcePlaylists = extracted.playlists.filter((playlist) => playlist?.id && playlist?.name);
+ for (const rawPlaylist of sourcePlaylists) {
+ const navigated = await evaluateOnPage(loaded.page, `location.assign(${JSON.stringify(`${PLAYLIST_URL}${encodeURIComponent(rawPlaylist.id)}`)}); true`).catch(() => false);
+ if (!navigated) {
+ warnings.push(`${rawPlaylist.name || 'Playlist'}: could not open playlist`);
+ continue;
+ }
+ await sleep(NAV_SETTLE_MS);
+ const detail = await evaluateOnPage(loaded.page, buildPlaylistVideosExtractionScript()).catch(() => null);
+ if (!detail || !Array.isArray(detail.videos) || detail.signedOut) {
+ warnings.push(`${rawPlaylist.name || 'Playlist'}: could not read videos`);
+ const stale = previous?.playlists?.find((playlist) => playlist.id === rawPlaylist.id);
+ if (stale) playlists.push(stale);
+ continue;
+ }
+ const normalizedVideos = detail.videos.map(normalizeYoutubeVideo).filter(Boolean);
+ const playlist = normalizeYoutubePlaylist(rawPlaylist, normalizedVideos);
+ if (playlist) playlists.push(playlist);
+ }
+
+ const snapshot = {
+ schemaVersion: SNAPSHOT_VERSION,
+ syncedAt: new Date().toISOString(),
+ playlists,
+ warnings,
+ };
+ await ensureDir(dataPath('youtube'));
+ await atomicWrite(PLAYLISTS_FILE, snapshot);
+
+ const summary = youtubePlaylistSnapshotSummary(snapshot);
+ const result = {
+ ok: warnings.length === 0,
+ ...summary,
+ scanned: sourcePlaylists.length,
+ failed: warnings.length,
+ ...(warnings.length ? { warnings } : {}),
+ };
+ console.log(`📺 YouTube playlists: synced ${summary.playlistCount} playlist(s), ${summary.videoCount} video(s)${warnings.length ? `, ${warnings.length} warning(s)` : ''}`);
+ return result;
+}
diff --git a/server/services/youtubePlaylists.test.js b/server/services/youtubePlaylists.test.js
new file mode 100644
index 0000000000..4dce2dcdcb
--- /dev/null
+++ b/server/services/youtubePlaylists.test.js
@@ -0,0 +1,50 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ findOrOpenPage: vi.fn(), isAuthPage: vi.fn(), evaluateOnPage: vi.fn(), readJSONFile: vi.fn(), ensureDir: vi.fn(), atomicWrite: vi.fn(),
+}));
+vi.mock('./browserService.js', () => ({
+ findOrOpenPage: (...args) => mocks.findOrOpenPage(...args), isAuthPage: (...args) => mocks.isAuthPage(...args),
+ evaluateOnPage: (...args) => mocks.evaluateOnPage(...args),
+}));
+vi.mock('../lib/fileUtils.js', () => ({
+ dataPath: (...parts) => `/tmp/${parts.join('/')}`, readJSONFile: (...args) => mocks.readJSONFile(...args),
+ ensureDir: (...args) => mocks.ensureDir(...args), atomicWrite: (...args) => mocks.atomicWrite(...args), sleep: vi.fn(async () => {}),
+}));
+
+import { normalizeYoutubePlaylist, normalizeYoutubeVideo, youtubePlaylistIdFromUrl, youtubePlaylistSnapshotSummary, syncYoutubePlaylists } from './youtubePlaylists.js';
+
+describe('YouTube playlist normalization', () => {
+ it('extracts playlist ids and produces downloader-ready video URLs', () => {
+ expect(youtubePlaylistIdFromUrl('https://www.youtube.com/playlist?list=PL-example')).toBe('PL-example');
+ expect(youtubePlaylistIdFromUrl('https://www.youtube.com/watch?v=abc')).toBeNull();
+ expect(normalizeYoutubeVideo({ id: 'video-1', title: 'Example video', channel: 'Example channel' })).toMatchObject({
+ id: 'video-1', url: 'https://www.youtube.com/watch?v=video-1',
+ });
+ expect(normalizeYoutubePlaylist({ id: 'PL-example', name: 'Example playlist' }, [{ id: 'video-1' }])).toMatchObject({
+ id: 'PL-example', videoCount: 1, videos: [{ id: 'video-1' }],
+ });
+ });
+ it('summarizes a missing snapshot as unsynced', () => {
+ expect(youtubePlaylistSnapshotSummary(null)).toEqual({ playlistCount: 0, videoCount: 0, syncedAt: null, warningCount: 0 });
+ });
+});
+
+describe('syncYoutubePlaylists', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.findOrOpenPage.mockResolvedValue({ id: 'page-1', url: 'https://www.youtube.com/feed/playlists' });
+ mocks.isAuthPage.mockReturnValue(false);
+ mocks.readJSONFile.mockResolvedValue(null);
+ mocks.evaluateOnPage
+ .mockResolvedValueOnce({ signedOut: false, playlists: [{ id: 'PL-example', name: 'Example playlist', videoCount: 1 }] })
+ .mockResolvedValueOnce(true)
+ .mockResolvedValueOnce({ signedOut: false, videos: [{ id: 'video-1', title: 'Example video', channel: 'Example channel' }] });
+ });
+ it('scrapes playlist pages and writes a local video snapshot', async () => {
+ const result = await syncYoutubePlaylists();
+ expect(result).toMatchObject({ ok: true, playlistCount: 1, videoCount: 1, scanned: 1, failed: 0 });
+ expect(mocks.findOrOpenPage).toHaveBeenCalledWith('https://www.youtube.com/feed/playlists');
+ expect(mocks.atomicWrite).toHaveBeenCalledWith('/tmp/youtube/playlists.json', expect.objectContaining({ schemaVersion: 1 }));
+ });
+});