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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: address review (claude) playlist sync findings
[._.]/ Adam Eivyc5d3bbae172b
diff --git a/server/services/spotifyPlaylists.js b/server/services/spotifyPlaylists.jsindex 4efbf17f81..3d7f27d849 100644--- a/server/services/spotifyPlaylists.js+++ b/server/services/spotifyPlaylists.js@@ -13,6 +13,7 @@ import { getAccessToken } from './spotifyAuth.js';const API_BASE = 'https://api.spotify.com/v1';const REQUEST_TIMEOUT_MS = 15000;const PAGE_LIMIT = 50;+const PLAYLIST_BATCH_SIZE = 5;const PLAYLISTS_FILE = dataPath('spotify', 'playlists.json');const SNAPSHOT_VERSION = 1;@@ -92,13 +93,15 @@ async function fetchPages(path, accessToken) {const items = [];let offset = 0;let total = null;+ let pageItems = [];do {const page = await fetchJson(`${API_BASE}${path}?limit=${PAGE_LIMIT}&offset=${offset}`, accessToken);- const pageItems = Array.isArray(page?.items) ? page.items : [];+ pageItems = Array.isArray(page?.items) ? page.items : [];items.push(...pageItems);+ if (!pageItems.length) break;total = Number.isFinite(page?.total) ? page.total : null;offset += pageItems.length;- } while (items.length && (total === null ? items.length >= PAGE_LIMIT : offset < total));+ } while (total === null ? pageItems.length >= PAGE_LIMIT : offset < total);return items;}@@ -140,7 +143,11 @@ async function doSyncSpotifyPlaylists() {}const playlistSummaries = playlistResult.value;- const results = await Promise.allSettled(playlistSummaries.map((playlist) => fetchPlaylist(playlist, accessToken)));+ const results = [];+ for (let index = 0; index < playlistSummaries.length; index += PLAYLIST_BATCH_SIZE) {+ const batch = playlistSummaries.slice(index, index + PLAYLIST_BATCH_SIZE);+ results.push(...await Promise.allSettled(batch.map((playlist) => fetchPlaylist(playlist, accessToken))));+ }const previousById = new Map((previous?.playlists || []).map((playlist) => [playlist.id, playlist]));const warnings = [];const playlists = [];diff --git a/server/services/spotifyPlaylists.test.js b/server/services/spotifyPlaylists.test.jsindex d7286aa365..35ee3f377d 100644--- a/server/services/spotifyPlaylists.test.js+++ b/server/services/spotifyPlaylists.test.js@@ -47,7 +47,7 @@ describe('syncSpotifyPlaylists', () => {.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 () => {+ it('fetches playlists and current playlist 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);@@ -55,4 +55,40 @@ describe('syncSpotifyPlaylists', () => {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 }));});++ it('stops pagination when Spotify returns an empty page', async () => {+ const pageItems = Array.from({ length: 50 }, (_, index) => ({+ ...trackItem,+ item: { ...trackItem.item, id: `track-${index}` },+ }));+ mocks.fetchWithTimeout+ .mockReset()+ .mockResolvedValueOnce({ ok: true, json: async () => ({ total: 1, items: [playlist] }) })+ .mockResolvedValueOnce({ ok: true, json: async () => ({ total: 100, items: pageItems }) })+ .mockResolvedValueOnce({ ok: true, json: async () => ({ total: 100, items: [] }) });++ const result = await syncSpotifyPlaylists();++ expect(result).toMatchObject({ ok: true, playlistCount: 1, trackCount: 50 });+ expect(mocks.fetchWithTimeout).toHaveBeenCalledTimes(3);+ expect(mocks.fetchWithTimeout.mock.calls[2][0].toString()).toContain('/playlists/playlist-1/items?limit=50&offset=50');+ });++ it('limits concurrent playlist item requests to bounded batches', async () => {+ const playlists = Array.from({ length: 6 }, (_, index) => ({ ...playlist, id: `playlist-${index}` }));+ let active = 0;+ let maximumActive = 0;+ mocks.fetchWithTimeout.mockReset().mockImplementation(async (url) => {+ if (url.includes('/me/playlists')) return { ok: true, json: async () => ({ total: playlists.length, items: playlists }) };+ active += 1;+ maximumActive = Math.max(maximumActive, active);+ await Promise.resolve();+ active -= 1;+ return { ok: true, json: async () => ({ total: 0, items: [] }) };+ });++ await syncSpotifyPlaylists();++ expect(maximumActive).toBe(5);+ });});diff --git a/server/services/youtubePlaylists.js b/server/services/youtubePlaylists.jsindex 0fe7c2ca82..235c2a4635 100644--- a/server/services/youtubePlaylists.js+++ b/server/services/youtubePlaylists.js@@ -7,7 +7,7 @@* 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';+import { findOrOpenPage, listCdpPages, isAuthPage, evaluateOnPage } from './browserService.js';const PLAYLISTS_URL = 'https://www.youtube.com/feed/playlists';const PLAYLIST_URL = 'https://www.youtube.com/playlist?list=';@@ -17,11 +17,6 @@ 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 {@@ -59,7 +54,7 @@ export function youtubePlaylistSnapshotSummary(snapshot) {function buildPlaylistsExtractionScript() {return `(async () => {- const signedOut = /accounts\.google\.com|\/ServiceLogin/i.test(location.href)+ 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; } };@@ -100,7 +95,7 @@ function buildPlaylistsExtractionScript() {function buildPlaylistVideosExtractionScript() {return `(async () => {- const signedOut = /accounts\.google\.com|\/ServiceLogin/i.test(location.href)+ 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; } };@@ -135,8 +130,16 @@ function buildPlaylistVideosExtractionScript() {}async function loadPage(url) {- const page = await findOrOpenPage(url).catch(() => null);+ let page = await findOrOpenPage(url).catch(() => null);if (!page || isAuthPage(page)) return { page: null, status: page ? 'auth-required' : 'no-browser' };+ if (!/\/feed\/playlists/.test(page.url || '')) {+ const navigated = await evaluateOnPage(page, `location.assign(${JSON.stringify(url)}); true`).catch(() => false);+ if (!navigated) return { page: null, status: 'navigation-failed' };+ await sleep(NAV_SETTLE_MS);+ const refreshed = (await listCdpPages().catch(() => [])).find((candidate) => candidate.id === page.id);+ if (refreshed) page = refreshed;+ }+ if (isAuthPage(page)) return { page: null, status: 'auth-required' };return { page, status: 'ok' };}@@ -172,6 +175,16 @@ async function doSyncYoutubePlaylists() {const playlists = [];const warnings = [];const sourcePlaylists = extracted.playlists.filter((playlist) => playlist?.id && playlist?.name);+ if (!sourcePlaylists.length && previous?.playlists?.length) {+ return {+ ok: false,+ status: 'extraction-empty',+ error: 'No playlists found — keeping the previous snapshot.',+ ...youtubePlaylistSnapshotSummary(previous),+ scanned: extracted.playlists.length,+ failed: 0,+ };+ }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) {diff --git a/server/services/youtubePlaylists.test.js b/server/services/youtubePlaylists.test.jsindex 4dce2dcdcb..c2ac893f2c 100644--- a/server/services/youtubePlaylists.test.js+++ b/server/services/youtubePlaylists.test.js@@ -1,10 +1,10 @@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(),+ findOrOpenPage: vi.fn(), listCdpPages: 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),+ findOrOpenPage: (...args) => mocks.findOrOpenPage(...args), listCdpPages: (...args) => mocks.listCdpPages(...args), isAuthPage: (...args) => mocks.isAuthPage(...args),evaluateOnPage: (...args) => mocks.evaluateOnPage(...args),}));vi.mock('../lib/fileUtils.js', () => ({@@ -12,12 +12,10 @@ vi.mock('../lib/fileUtils.js', () => ({ensureDir: (...args) => mocks.ensureDir(...args), atomicWrite: (...args) => mocks.atomicWrite(...args), sleep: vi.fn(async () => {}),}));-import { normalizeYoutubePlaylist, normalizeYoutubeVideo, youtubePlaylistIdFromUrl, youtubePlaylistSnapshotSummary, syncYoutubePlaylists } from './youtubePlaylists.js';+import { normalizeYoutubePlaylist, normalizeYoutubeVideo, 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();+ it('produces downloader-ready video URLs', () => {expect(normalizeYoutubeVideo({ id: 'video-1', title: 'Example video', channel: 'Example channel' })).toMatchObject({id: 'video-1', url: 'https://www.youtube.com/watch?v=video-1',});@@ -34,6 +32,7 @@ describe('syncYoutubePlaylists', () => {beforeEach(() => {vi.clearAllMocks();mocks.findOrOpenPage.mockResolvedValue({ id: 'page-1', url: 'https://www.youtube.com/feed/playlists' });+ mocks.listCdpPages.mockResolvedValue([]);mocks.isAuthPage.mockReturnValue(false);mocks.readJSONFile.mockResolvedValue(null);mocks.evaluateOnPage@@ -45,6 +44,36 @@ describe('syncYoutubePlaylists', () => {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.evaluateOnPage.mock.calls[0][1]).toContain('/accounts\\.google\\.com|\\/ServiceLogin/i');expect(mocks.atomicWrite).toHaveBeenCalledWith('/tmp/youtube/playlists.json', expect.objectContaining({ schemaVersion: 1 }));});++ it('navigates an existing YouTube tab to the playlists feed', async () => {+ mocks.findOrOpenPage.mockResolvedValue({ id: 'page-1', url: 'https://www.youtube.com/watch?v=video-1' });+ mocks.listCdpPages.mockResolvedValue([{ id: 'page-1', url: 'https://www.youtube.com/feed/playlists' }]);+ mocks.readJSONFile.mockResolvedValue(null);+ mocks.evaluateOnPage+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce({ signedOut: false, playlists: [{ id: 'PL-example', name: 'Example playlist' }] })+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce({ signedOut: false, videos: [] });++ await syncYoutubePlaylists();++ expect(mocks.evaluateOnPage.mock.calls[0][1]).toContain('location.assign("https://www.youtube.com/feed/playlists")');+ expect(mocks.listCdpPages).toHaveBeenCalledTimes(1);+ });++ it('keeps the prior snapshot when playlist extraction is unexpectedly empty', async () => {+ mocks.readJSONFile.mockResolvedValue({+ syncedAt: '2026-08-28T00:00:00.000Z',+ playlists: [{ id: 'PL-example', name: 'Example playlist', videos: [{ id: 'video-1' }] }],+ });+ mocks.evaluateOnPage.mockReset().mockResolvedValueOnce({ signedOut: false, playlists: [] });++ const result = await syncYoutubePlaylists();++ expect(result).toMatchObject({ ok: false, status: 'extraction-empty', playlistCount: 1, videoCount: 1 });+ expect(mocks.atomicWrite).not.toHaveBeenCalled();+ });});