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
feat([issue-2152]): Spotify listening-history ingestion (OAuth + recently-played polling)
Adam Eivyc2a7da540ec0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 92f90f1bfb..c3919e0331 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -57,6 +57,7 @@## Human Activity Tracking- **[issue-2150] Activity timeline** — a new `/timeline` page shows a unified, day-by-day view of your activity (emails sent/received and calendar events, with more sources coming), backed by a machine-local `human_activity_events` store that your existing message and calendar syncs populate automatically. Pick any day (deep-linkable via `/timeline/:date`), see an hourly activity histogram and per-source tallies, and browse the day's events. Only metadata and a short summary line are stored — full message bodies stay in their per-source caches — and the timeline is machine-local (never federated to peers), like Tribe.+- **[issue-2152] Spotify listening history** — a new Settings → Spotify tab pulls your recently-played tracks into the activity timeline as listen events (taste signal for the digital twin). Create a free Spotify developer app, paste its client ID/secret, and connect your account with one click (standard OAuth) — PortOS surfaces the exact redirect URI to register. It's off by default and opt-in: enable it, set a sync interval (keep it under ~25 minutes since Spotify only exposes your last 50 plays), and use "Sync now" to run immediately. Each play records the track, artists, album, and duration; re-syncs are incremental and idempotent, so running it repeatedly never double-logs. Like the rest of the timeline, listens are machine-local and never federate to your peers, and your Spotify credentials/tokens stay on this machine.- **[issue-2151] iMessage ingestion (macOS)** — a new Settings → iMessage tab lets you pull your Mac's Messages history into the activity timeline and your Tribe touchpoints. It reads `~/Library/Messages/chat.db` read-only (never writing to Apple's database) using a built-in SQLite reader — no new dependencies — and matches conversations to the people you track by phone number (a new phone field on Tribe people, matched in E.164 form) as well as email. It's off by default and opt-in: enable it, set a sync interval, and use "Check setup" to confirm PortOS has macOS Full Disk Access (with a clear fix if it doesn't) or "Sync now" to run immediately. Only conversation metadata and a short preview line are stored — full message text stays in chat.db — and, like Tribe, nothing federates to your peers. Re-syncs are incremental and idempotent, so running it repeatedly never double-logs.- **[issue-2160] WhatsApp import direction inference** — the WhatsApp chat backfill importer now takes an optional "your name in this chat" field. When set, messages from a sender matching that name land as `message.sent` events and everyone else as `message.received` (the same kinds email uses); left blank, messages stay neutral `message` events as before. The preview shows the sent/received split before you commit. Direction isn't part of the dedupe key, so an earlier neutral import isn't double-counted — clear the source's events and re-import to apply the classification.- **[issue-2160] WhatsApp import optional chat label — hardens the cross-chat dedupe collision** — the WhatsApp chat backfill importer now takes an optional "chat label" field. WhatsApp exports carry no stable chat id (the filename differs between a `WhatsApp Chat - Alice.zip` and the bare `_chat.txt` extracted from it), so the content-hash dedupe key was deliberately un-scoped — which meant two DIFFERENT chats that each contained a same-named sender sending an identical message at the same timestamp granularity could collapse into a single event. Supplying a chat label (e.g. "Family group") now folds that stable, user-supplied scope into the dedupe hash so distinct chats key apart, and the label also becomes the displayed chat title. Left blank, the dedupe key is byte-identical to before, so existing imports and their idempotency are unchanged; use the same label consistently for a given chat across re-imports. (`server/services/whatsappImport.js`, `server/routes/timeline.js`, `client/src/services/apiTimeline.js`, `client/src/components/timeline/WhatsappImportPanel.jsx`)diff --git a/client/src/components/settings/SettingsTabsHeader.jsx b/client/src/components/settings/SettingsTabsHeader.jsxindex b0bd1ce3c8..76fa4c7f34 100644--- a/client/src/components/settings/SettingsTabsHeader.jsx+++ b/client/src/components/settings/SettingsTabsHeader.jsx@@ -25,6 +25,7 @@ export const TABS = [{ id: 'providers', label: 'Providers', to: '/ai' },{ id: 'security', label: 'Security', to: '/settings/security' },{ id: 'sharing', label: 'Sharing', to: '/settings/sharing' },+ { id: 'spotify', label: 'Spotify', to: '/settings/spotify' },{ id: 'telegram', label: 'Telegram', to: '/settings/telegram' },{ id: 'voice', label: 'Voice', to: '/settings/voice' }];diff --git a/client/src/components/settings/SpotifyTab.jsx b/client/src/components/settings/SpotifyTab.jsxnew file mode 100644index 0000000000..9931f63c9c--- /dev/null+++ b/client/src/components/settings/SpotifyTab.jsx@@ -0,0 +1,306 @@+import { useEffect, useState } from 'react';+import { useSearchParams } from 'react-router-dom';+import { Save, Loader2, Music, Link2, LogOut, RefreshCw, CheckCircle2, AlertCircle } from 'lucide-react';+import toast from '../ui/Toast';+import BrailleSpinner from '../BrailleSpinner';+import {+ getSettings,+ updateSettings,+ getSpotifyStatus,+ getSpotifyAuthUrl,+ saveSpotifyCredentials,+ clearSpotifyAuth,+ syncSpotify,+} from '../../services/api';++// Settings → Spotify (#2152). Opt-in, machine-local ingestion of Spotify+// listening history (recently-played) into the activity timeline. OFF by+// default — requires a user-created Spotify developer app + OAuth connection.+export function SpotifyTab() {+ const [searchParams, setSearchParams] = useSearchParams();+ const [loading, setLoading] = useState(true);+ const [enabled, setEnabled] = useState(false);+ const [intervalMinutes, setIntervalMinutes] = useState(25);+ const [savedEnabled, setSavedEnabled] = useState(false);+ const [savedInterval, setSavedInterval] = useState(25);+ const [saving, setSaving] = useState(false);++ const [clientId, setClientId] = useState('');+ const [clientSecret, setClientSecret] = useState('');+ const [savingCreds, setSavingCreds] = useState(false);++ const [status, setStatus] = useState(null);+ const [connecting, setConnecting] = useState(false);+ const [syncing, setSyncing] = useState(false);++ const loadStatus = () => getSpotifyStatus({ silent: true }).catch(() => null).then((st) => { if (st) setStatus(st); return st; });++ useEffect(() => {+ Promise.all([+ getSettings({ silent: true }).catch(() => ({})),+ getSpotifyStatus({ silent: true }).catch(() => null),+ ])+ .then(([settings, st]) => {+ const c = settings?.spotify || {};+ const en = typeof c.enabled === 'boolean' ? c.enabled : false;+ const iv = Number.isFinite(c.intervalMinutes) ? c.intervalMinutes : 25;+ setEnabled(en);+ setIntervalMinutes(iv);+ setSavedEnabled(en);+ setSavedInterval(iv);+ setStatus(st);+ })+ .finally(() => setLoading(false));+ }, []);++ // Surface the OAuth callback outcome (the browser redirect lands back here).+ useEffect(() => {+ if (searchParams.get('oauthConnected')) {+ toast.success('Spotify connected');+ loadStatus();+ searchParams.delete('oauthConnected');+ setSearchParams(searchParams, { replace: true });+ } else if (searchParams.get('oauthError')) {+ toast.error(`Spotify connect failed: ${searchParams.get('oauthError')}`);+ searchParams.delete('oauthError');+ setSearchParams(searchParams, { replace: true });+ }+ }, [searchParams, setSearchParams]);++ const dirty = enabled !== savedEnabled || Number(intervalMinutes) !== Number(savedInterval);+ const auth = status?.auth;++ const handleSave = async () => {+ const iv = Math.max(1, Math.min(1440, Math.floor(Number(intervalMinutes) || 25)));+ setSaving(true);+ const merged = await updateSettings({ spotify: { enabled, intervalMinutes: iv } }).catch(() => null);+ setSaving(false);+ if (!merged) return;+ setIntervalMinutes(iv);+ setSavedEnabled(enabled);+ setSavedInterval(iv);+ toast.success('Saved — scheduler applies on next server restart');+ };++ const handleSaveCreds = async () => {+ if (!clientId.trim() || !clientSecret.trim()) {+ toast.error('Enter both client ID and client secret');+ return;+ }+ setSavingCreds(true);+ const result = await saveSpotifyCredentials(+ { clientId: clientId.trim(), clientSecret: clientSecret.trim() },+ { silent: true },+ ).catch(() => null);+ setSavingCreds(false);+ if (!result) { toast.error('Failed to save credentials'); return; }+ toast.success('Spotify credentials saved');+ setClientSecret('');+ loadStatus();+ };++ const handleConnect = async () => {+ setConnecting(true);+ const result = await getSpotifyAuthUrl({ silent: true }).catch(() => null);+ setConnecting(false);+ if (result?.url) {+ window.location.href = result.url;+ } else {+ toast.error('Save your Spotify credentials first');+ }+ };++ const handleDisconnect = async () => {+ const result = await clearSpotifyAuth({ silent: true }).catch(() => null);+ if (result?.cleared) {+ toast.success('Spotify disconnected');+ loadStatus();+ } else {+ toast.error('Failed to disconnect');+ }+ };++ const handleSyncNow = async () => {+ setSyncing(true);+ const result = await syncSpotify({ silent: true }).catch(() => ({ ok: false, error: 'Sync failed' }));+ setSyncing(false);+ if (result?.ok) {+ toast.success(`Synced: ${result.recorded} listen(s)${result.hasMore ? ' — more history remains, run again' : ''}`);+ setStatus((prev) => ({ ...(prev || {}), state: { ...(prev?.state || {}), cursorAfter: result.cursorAfter, lastResult: result, lastRunAt: new Date().toISOString() } }));+ } else {+ toast.error(result?.needsAuth ? 'Connect Spotify first' : (result?.error || 'Sync failed'));+ }+ };++ if (loading) return <BrailleSpinner />;++ const lastResult = status?.state?.lastResult;++ return (+ <div className="space-y-6">+ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6">+ <div className="flex items-center gap-2 mb-2">+ <Music size={16} className="text-port-accent" />+ <h3 className="text-lg font-semibold text-white">Spotify listening history</h3>+ </div>+ <p className="text-sm text-gray-400 mb-4">+ Polls your Spotify recently-played tracks and feeds the activity timeline (taste signal for the digital+ twin). Machine-local — nothing federates to peers. Requires a free{' '}+ <a href="https://developer.spotify.com/dashboard" target="_blank" rel="noreferrer" className="text-port-accent hover:underline">+ Spotify developer app+ </a>{' '}+ — create one, add the redirect URI below, then paste its client ID and secret.+ </p>++ {/* Step 1 — developer app credentials */}+ <div className="space-y-3 border-b border-port-border pb-5 mb-5">+ <h4 className="text-sm font-semibold text-gray-200">1. Developer app credentials</h4>+ {auth?.redirectUri && (+ <p className="text-xs text-gray-500">+ Add this exact redirect URI in your Spotify app settings:{' '}+ <code className="text-gray-300 break-all">{auth.redirectUri}</code>+ </p>+ )}+ <div>+ <label htmlFor="spotify-client-id" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">+ Client ID+ </label>+ <input+ id="spotify-client-id"+ type="text"+ value={clientId}+ onChange={(e) => setClientId(e.target.value)}+ placeholder={auth?.hasCredentials ? '•••••••• (saved — re-enter to change)' : 'Spotify app client ID'}+ className="w-full max-w-md px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ </div>+ <div>+ <label htmlFor="spotify-client-secret" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">+ Client secret+ </label>+ <input+ id="spotify-client-secret"+ type="password"+ value={clientSecret}+ onChange={(e) => setClientSecret(e.target.value)}+ placeholder={auth?.hasCredentials ? '•••••••• (saved — re-enter to change)' : 'Spotify app client secret'}+ className="w-full max-w-md px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ </div>+ <button+ type="button"+ onClick={handleSaveCreds}+ disabled={savingCreds}+ 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"+ >+ {savingCreds ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}+ Save credentials+ </button>+ </div>++ {/* Step 2 — connect via OAuth */}+ <div className="space-y-3 border-b border-port-border pb-5 mb-5">+ <h4 className="text-sm font-semibold text-gray-200">2. Connect your Spotify account</h4>+ <div className="flex items-center gap-2 text-sm">+ {auth?.hasTokens ? (+ <span className="inline-flex items-center gap-1.5 text-port-success"><CheckCircle2 size={14} /> Connected</span>+ ) : (+ <span className="inline-flex items-center gap-1.5 text-gray-400"><AlertCircle size={14} /> Not connected</span>+ )}+ {auth?.expiresAt && <span className="text-gray-500 text-xs">token expires {new Date(auth.expiresAt).toLocaleString()}</span>}+ </div>+ <div className="flex flex-wrap gap-2">+ <button+ type="button"+ onClick={handleConnect}+ disabled={connecting || !auth?.hasCredentials}+ title={!auth?.hasCredentials ? 'Save credentials first' : undefined}+ className="inline-flex items-center justify-center gap-2 min-h-[40px] px-4 py-2 bg-port-bg border border-port-border hover:border-port-accent text-gray-200 rounded-lg text-sm transition-colors disabled:opacity-40"+ >+ {connecting ? <Loader2 size={14} className="animate-spin" /> : <Link2 size={14} />}+ {auth?.hasTokens ? 'Reconnect' : 'Connect Spotify'}+ </button>+ {auth?.hasTokens && (+ <button+ type="button"+ onClick={handleDisconnect}+ className="inline-flex items-center justify-center gap-2 min-h-[40px] px-4 py-2 bg-port-bg border border-port-border hover:border-port-error text-gray-200 rounded-lg text-sm transition-colors"+ >+ <LogOut size={14} /> Disconnect+ </button>+ )}+ </div>+ </div>++ {/* Step 3 — schedule */}+ <div className="space-y-3">+ <h4 className="text-sm font-semibold text-gray-200">3. Scheduled sync</h4>+ <label htmlFor="spotify-enabled" className="flex items-center gap-2 text-sm text-gray-200 cursor-pointer">+ <input+ id="spotify-enabled"+ type="checkbox"+ checked={enabled}+ onChange={(e) => setEnabled(e.target.checked)}+ className="w-4 h-4 accent-port-accent"+ />+ Enable scheduled Spotify sync+ </label>++ <div>+ <label htmlFor="spotify-interval" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">+ Sync interval (minutes)+ </label>+ <input+ id="spotify-interval"+ type="number"+ min={1}+ max={1440}+ value={intervalMinutes}+ onChange={(e) => setIntervalMinutes(e.target.value)}+ className="w-32 px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ <p className="text-xs text-gray-500 mt-1">+ Spotify only exposes the last 50 plays — keep this under ~25 min so no listens are missed.+ </p>+ </div>++ <div className="flex flex-wrap gap-2 pt-1">+ <button+ type="button"+ onClick={handleSave}+ disabled={!dirty || saving}+ 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"+ >+ {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}+ {saving ? 'Saving...' : 'Save'}+ </button>+ <button+ type="button"+ onClick={handleSyncNow}+ disabled={syncing || !auth?.hasTokens}+ title={!auth?.hasTokens ? 'Connect Spotify first' : undefined}+ className="inline-flex items-center justify-center gap-2 min-h-[40px] px-4 py-2 bg-port-bg border border-port-border hover:border-port-accent text-gray-200 rounded-lg text-sm transition-colors disabled:opacity-40"+ >+ {syncing ? <Loader2 size={14} className="animate-spin" /> : <RefreshCw size={14} />}+ Sync now+ </button>+ </div>+ </div>+ </div>++ {(lastResult || status?.state?.cursorAfter > 0) && (+ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6">+ <h3 className="text-sm font-semibold text-white mb-2">Last sync</h3>+ <dl className="grid grid-cols-2 sm:grid-cols-3 gap-3 text-sm">+ <div><dt className="text-gray-500 text-xs uppercase">Listens recorded</dt><dd className="text-gray-200">{lastResult?.recorded ?? '—'}</dd></div>+ <div><dt className="text-gray-500 text-xs uppercase">Scanned</dt><dd className="text-gray-200">{lastResult?.scanned ?? '—'}</dd></div>+ <div><dt className="text-gray-500 text-xs uppercase">More remaining</dt><dd className="text-gray-200">{lastResult?.hasMore ? 'yes' : 'no'}</dd></div>+ <div><dt className="text-gray-500 text-xs uppercase">Last run</dt><dd className="text-gray-200">{status?.state?.lastRunAt ? new Date(status.state.lastRunAt).toLocaleString() : '—'}</dd></div>+ </dl>+ </div>+ )}+ </div>+ );+}++export default SpotifyTab;diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsxindex 6768a81f67..424d08f234 100644--- a/client/src/pages/Settings.jsx+++ b/client/src/pages/Settings.jsx@@ -15,6 +15,7 @@ import { IMessageTab } from '../components/settings/IMessageTab';import { MortalLoomTab } from '../components/settings/MortalLoomTab';import { SecurityTab } from '../components/settings/SecurityTab';import { SharingTab } from '../components/settings/SharingTab';+import { SpotifyTab } from '../components/settings/SpotifyTab';import { VoiceTab } from '../components/settings/VoiceTab';import SettingsTabsHeader from '../components/settings/SettingsTabsHeader';@@ -47,6 +48,7 @@ export default function Settings() {case 'local-llm': return <LocalLlmTab />;case 'security': return <SecurityTab />;case 'sharing': return <SharingTab />;+ case 'spotify': return <SpotifyTab />;case 'voice': return <VoiceTab />;case 'telegram': return <TelegramTab />;case 'mortalloom': return <MortalLoomTab />;diff --git a/client/src/services/README.md b/client/src/services/README.mdindex b7109aff2a..2796f7b45f 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -77,6 +77,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiTribe.js` | Tribe people (relationship rings + contacts). || `apiCalendar.js` | Calendar events. || `apiMessages.js` | Messages / notifications. |+| `apiSpotify.js` | Spotify OAuth + listening-history sync. || `apiPersonalities.js` | Agent personality profiles. |## Media / creativediff --git a/client/src/services/api.js b/client/src/services/api.jsindex b517b6b6c6..352dfebc88 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -23,6 +23,7 @@ export * from './apiPersonalities.js';export * from './apiAccounts.js';export * from './apiSchedules.js';export * from './apiMessages.js';+export * from './apiSpotify.js';export * from './apiCalendar.js';export * from './apiGoals.js';export * from './apiReview.js';diff --git a/client/src/services/apiSpotify.js b/client/src/services/apiSpotify.jsnew file mode 100644index 0000000000..102aad33ee--- /dev/null+++ b/client/src/services/apiSpotify.js@@ -0,0 +1,12 @@+import { request } from './apiCore.js';++// Spotify listening-history ingestion (#2152) — OAuth + recently-played polling+// into the machine-local activity timeline. Credentials/tokens live server-side+// under data/spotify/; these wrappers drive the settings tab.+export const getSpotifyStatus = (options = {}) => request('/spotify/status', options);+export const getSpotifyAuthUrl = (options = {}) => request('/spotify/auth/url', options);+export const saveSpotifyCredentials = (data, options = {}) =>+ request('/spotify/auth/credentials', { method: 'POST', body: JSON.stringify(data), ...options });+export const clearSpotifyAuth = (options = {}) =>+ request('/spotify/auth/clear', { method: 'POST', ...options });+export const syncSpotify = (options = {}) => request('/spotify/sync', { method: 'POST', ...options });diff --git a/server/index.js b/server/index.jsindex 76bbbc10c7..0dda65f595 100644--- a/server/index.js+++ b/server/index.js@@ -49,6 +49,7 @@ import memoryRoutes from './routes/memory.js';import tribeRoutes from './routes/tribe.js';import timelineRoutes from './routes/timeline.js';import imessageRoutes from './routes/imessage.js';+import spotifyRoutes from './routes/spotify.js';import notificationsRoutes from './routes/notifications.js';import standardizeRoutes from './routes/standardize.js';import brainRoutes from './routes/brain.js';@@ -170,6 +171,7 @@ import * as cos from './services/cos.js';import { startBackupScheduler } from './services/backupScheduler.js';import { startCitySnapshotScheduler } from './services/citySnapshotScheduler.js';import { startImessageScheduler } from './services/imessageScheduler.js';+import { startSpotifyScheduler } from './services/spotifyScheduler.js';import * as telegram from './services/telegram.js';import * as telegramBridge from './services/telegramBridge.js';import { getSettings as getInitSettings } from './services/settings.js';@@ -477,6 +479,7 @@ app.use('/api/memory', memoryRoutes);app.use('/api/tribe', tribeRoutes);app.use('/api/timeline', timelineRoutes);app.use('/api/imessage', imessageRoutes);+app.use('/api/spotify', spotifyRoutes);app.use('/api/notifications', notificationsRoutes);app.use('/api/standardize', standardizeRoutes);app.use('/api/brain/import', brainImportRoutes);@@ -604,6 +607,10 @@ startCitySnapshotScheduler().catch(err => console.error(`❌ City snapshot sched// Initialize iMessage sync scheduler — OFF by default; only polls chat.db when// the user opts in via Settings → iMessage (needs macOS Full Disk Access) (#2151).startImessageScheduler().catch(err => console.error(`❌ iMessage sync scheduler init failed: ${err.message}`));+// Initialize Spotify sync scheduler — OFF by default; only polls the+// recently-played API when the user connects Spotify + opts in via+// Settings → Spotify (#2152).+startSpotifyScheduler().catch(err => console.error(`❌ Spotify sync scheduler init failed: ${err.message}`));// Periodically GC orphan zero-issue/zero-canon importer shells left by an// abandoned analyze (issue #727).startOrphanShellGc();diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.jsindex 0becffa949..d7a94d3bf1 100644--- a/server/lib/mediaValidation.js+++ b/server/lib/mediaValidation.js@@ -29,6 +29,16 @@ export const imessageConfigSchema = z.object({intervalMinutes: z.number().int().min(1).max(1440).optional()});+// Spotify listening-history ingestion config (#2152) — the `settings.spotify`+// slice. Sync is OFF by default and only polls the recently-played API when+// enabled AND the user has completed OAuth (credentials/tokens live under+// data/spotify/, not settings). Validated as a settings slice on+// PUT /api/settings; service-side DEFAULT_CONFIG fills any absent field.+export const spotifyConfigSchema = z.object({+ enabled: z.boolean().optional(),+ intervalMinutes: z.number().int().min(1).max(1440).optional()+});+// Shared LoRA-training parameter bounds — used by both the settings-slice// defaults and the per-run override on POST /api/lora-training/runs.const loraTrainingParamsSchema = z.object({diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex a23c3a6e64..3b66d5f93b 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -183,6 +183,7 @@ export const NAV_COMMANDS = [{ id: 'nav.settings.mortalloom', path: '/settings/mortalloom', label: 'MortalLoom', section: 'Settings', aliases: ['settings-mortalloom', 'mortalloom'] },{ id: 'nav.settings.security', path: '/settings/security', label: 'Security', section: 'Settings', aliases: ['settings-security', 'login-password', 'auth-password', 'password-settings'], keywords: ['password', 'login', 'auth', 'sign-in', 'lock', 'tailnet', 'sidecar'] },{ id: 'nav.settings.sharing', path: '/settings/sharing', label: 'Sharing', section: 'Settings', aliases: ['settings-sharing', 'sharing-settings'], keywords: ['display name', 'bio', 'attribution', 'identity', 'source'] },+ { id: 'nav.settings.spotify', path: '/settings/spotify', label: 'Spotify', section: 'Settings', aliases: ['settings-spotify', 'spotify', 'spotify-settings'], keywords: ['spotify', 'music', 'listening', 'recently played', 'oauth', 'timeline', 'taste', 'media'] },{ id: 'nav.settings.telegram', path: '/settings/telegram', label: 'Telegram', section: 'Settings', aliases: ['settings-telegram', 'telegram'] },{ id: 'nav.settings.voice', path: '/settings/voice', label: 'Voice', section: 'Settings', aliases: ['settings-voice', 'voice', 'voice-settings'], keywords: ['mic', 'microphone', 'speech', 'tts', 'whisper', 'kokoro'] },diff --git a/server/routes/settings.js b/server/routes/settings.jsindex 9dbb008897..11aa0ab630 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -10,7 +10,7 @@ import {} from '../services/mediaJobQueue/index.js';import { asyncHandler } from '../lib/errorHandler.js';import { isPlainObject } from '../lib/objects.js';-import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, validateRequest } from '../lib/validation.js';+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, spotifyConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, validateRequest } from '../lib/validation.js';const router = Router();@@ -158,6 +158,11 @@ router.put('/', asyncHandler(async (req, res) => {if (req.body?.imessage !== undefined) {validateRequest(imessageConfigSchema.partial(), req.body.imessage);}+ // Spotify ingestion config (#2152) — validate the slice when present so a+ // malformed enabled/interval can't reach disk and break the sync scheduler.+ if (req.body?.spotify !== undefined) {+ validateRequest(spotifyConfigSchema.partial(), req.body.spotify);+ }// LoRA training config (caption provider + training defaults) — validate// the slice when present so a malformed save can't write bad bounds the// trainer would then pass to the python child.diff --git a/server/routes/spotify.js b/server/routes/spotify.jsnew file mode 100644index 0000000000..f9580fb7d5--- /dev/null+++ b/server/routes/spotify.js@@ -0,0 +1,68 @@+import { Router } from 'express';+import { z } from 'zod';++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';++const router = Router();++// Status — config (enabled/interval) + machine-local cursor state + OAuth status.+// No API call, so cheap and safe to poll from the settings tab.+router.get('/status', asyncHandler(async (req, res) => {+ const status = await spotifySync.getStatus();+ res.json(status);+}));++// Save the user-created Spotify developer app credentials (client id/secret).+router.post('/auth/credentials', asyncHandler(async (req, res) => {+ const schema = z.object({+ clientId: z.string().min(1),+ clientSecret: z.string().min(1),+ });+ const data = validateRequest(schema, req.body);+ const result = await spotifyAuth.saveCredentials(data);+ res.json(result);+}));++// Build the Spotify authorize URL (the SPA opens it to start the OAuth flow).+router.get('/auth/url', asyncHandler(async (req, res) => {+ const result = await spotifyAuth.getAuthUrl();+ res.json(result);+}));++// OAuth redirect target — hit by a BROWSER redirect from Spotify, not the SPA —+// so render every outcome as a redirect to the settings tab (which toasts the+// oauthError param) instead of the JSON envelope the middleware would send.+router.get('/oauth/callback', asyncHandler(async (req, res) => {+ const settingsUrl = (error) => (error+ ? `/settings/spotify?oauthError=${encodeURIComponent(error)}`+ : '/settings/spotify?oauthConnected=1');+ 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)).then(() => null)+ .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';+ });+ res.redirect(settingsUrl(error));+}));++// Disconnect — clear stored tokens (leaves the client id/secret in place).+router.post('/auth/clear', asyncHandler(async (req, res) => {+ const result = await spotifyAuth.clearAuth();+ res.json(result);+}));++// Run one incremental sync pass now (explicit user action). Returns the pass+// summary, or a needsAuth report when Spotify isn't connected.+router.post('/sync', asyncHandler(async (req, res) => {+ const result = await spotifySync.runSync();+ res.json(result);+}));++export default router;diff --git a/server/services/spotifyAuth.js b/server/services/spotifyAuth.jsnew file mode 100644index 0000000000..f6e5e0497a--- /dev/null+++ b/server/services/spotifyAuth.js@@ -0,0 +1,212 @@+/**+ * Spotify OAuth (#2152) — authorization-code flow with refresh tokens for the+ * machine-local Spotify listening-history ingestion (see spotifySync.js).+ *+ * Design constraints (docs/plans/2026-07-04-human-activity-tracking.md):+ *+ * - **Zero new dependencies.** Spotify has no first-party Node SDK we need — the+ * token exchange is two `fetch` POSTs to `accounts.spotify.com`, so we own the+ * ~40 lines rather than pull a library (per the dependency policy). Node ≥18+ * `fetch` is built in.+ * - **Confidential client.** The user creates their own Spotify developer app and+ * pastes the client id/secret (stored under `data/spotify/`, mirroring+ * `data/calendar/google-auth/`). We authenticate the token endpoint with HTTP+ * Basic (`client_secret_basic`) — no PKCE needed for a server-side secret.+ * - **Machine-local.** Credentials + tokens live in `data/spotify/` JSON files,+ * never federated. Derived `media.listen` events land in the machine-local+ * `human_activity_events` table.+ * - **No cold-bootstrap side effects.** Nothing here runs at module load; the+ * first token exchange only happens when the user completes the OAuth flow.+ *+ * The pure helpers (`isTokenExpired`, `withExpiry`, `getRedirectUri`) are exported+ * and unit-tested without any network or filesystem access.+ */+import { dataPath, ensureDir, atomicWrite, tryReadFile } from '../lib/fileUtils.js';+import { ServerError } from '../lib/errorHandler.js';++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'];++const ACCOUNTS_BASE = 'https://accounts.spotify.com';++// ---------------------------------------------------------------------------+// Pure helpers (exported for unit tests — no network, no filesystem).+// ---------------------------------------------------------------------------++/**+ * The redirect URI registered in the user's Spotify developer app. Mirrors+ * googleAuth's env-driven constant so it stays stable across the auth-url and+ * callback round-trip. Surfaced in the auth status so the user can copy the+ * exact string into the Spotify dashboard (it must match byte-for-byte).+ */+export function getRedirectUri() {+ if (process.env.SPOTIFY_REDIRECT_URI) return process.env.SPOTIFY_REDIRECT_URI;+ const host = process.env.PUBLIC_HOST || 'localhost';+ const port = process.env.PORT || 5555;+ return `http://${host}:${port}/api/spotify/oauth/callback`;+}++/**+ * Stamp an absolute `expires_at` (epoch ms) onto a raw Spotify token response so+ * `isTokenExpired` can decide when to refresh. `expires_in` is seconds-from-now.+ */+export function withExpiry(tokens, now = Date.now()) {+ const expiresIn = Number(tokens?.expires_in);+ return {+ ...tokens,+ expires_at: Number.isFinite(expiresIn) ? now + expiresIn * 1000 : null,+ };+}++/**+ * True when the access token is missing or within `skewMs` of its expiry (so a+ * caller refreshes proactively). An unknown `expires_at` counts as expired — we+ * refresh rather than gamble on a stale token. `null`/absent token ⇒ expired.+ */+export function isTokenExpired(tokens, now = Date.now(), skewMs = 60000) {+ if (!tokens?.access_token) return true;+ if (!Number.isFinite(tokens?.expires_at)) return true;+ return now >= tokens.expires_at - skewMs;+}++// ---------------------------------------------------------------------------+// Credentials + tokens (machine-local files under data/spotify/).+// ---------------------------------------------------------------------------++async function ensureAuthDir() {+ await ensureDir(AUTH_DIR);+}++export async function getCredentials() {+ await ensureAuthDir();+ const raw = await tryReadFile(CREDENTIALS_FILE);+ if (!raw) return null;+ return JSON.parse(raw);+}++export async function saveCredentials({ clientId, clientSecret }) {+ await ensureAuthDir();+ const credentials = { clientId, clientSecret, redirectUri: getRedirectUri() };+ await atomicWrite(CREDENTIALS_FILE, credentials);+ console.log('🎧 Spotify OAuth credentials saved');+ return { hasCredentials: true, redirectUri: credentials.redirectUri };+}++export async function getTokens() {+ await ensureAuthDir();+ const raw = await tryReadFile(TOKENS_FILE);+ if (!raw) return null;+ return JSON.parse(raw);+}++async function saveTokens(tokens) {+ await ensureAuthDir();+ await atomicWrite(TOKENS_FILE, tokens);+}++export async function clearAuth() {+ await ensureAuthDir();+ await atomicWrite(TOKENS_FILE, {});+ console.log('🎧 Spotify OAuth tokens cleared');+ return { cleared: true };+}++// ---------------------------------------------------------------------------+// OAuth flow (side-effecting — network via fetch).+// ---------------------------------------------------------------------------++// Exchange with the Spotify token endpoint. `.json()` failures are caught inline+// (a non-JSON error body must not mask the real HTTP status).+async function requestToken(params) {+ const credentials = await getCredentials();+ if (!credentials?.clientId) {+ throw new ServerError('No Spotify OAuth credentials configured', { status: 400 });+ }+ const basic = Buffer.from(`${credentials.clientId}:${credentials.clientSecret}`).toString('base64');+ const res = await fetch(`${ACCOUNTS_BASE}/api/token`, {+ method: 'POST',+ headers: {+ Authorization: `Basic ${basic}`,+ 'Content-Type': 'application/x-www-form-urlencoded',+ },+ body: new URLSearchParams(params).toString(),+ });+ const json = await res.json().catch(() => ({}));+ if (!res.ok) {+ throw new ServerError(+ `Spotify token request failed: ${json.error_description || json.error || res.status}`,+ { status: 400 },+ );+ }+ return json;+}++export async function getAuthUrl() {+ const credentials = await getCredentials();+ if (!credentials?.clientId) {+ throw new ServerError('No Spotify OAuth credentials configured', { status: 400 });+ }+ const params = new URLSearchParams({+ client_id: credentials.clientId,+ response_type: 'code',+ redirect_uri: getRedirectUri(),+ scope: SPOTIFY_SCOPES.join(' '),+ show_dialog: 'false',+ });+ return { url: `${ACCOUNTS_BASE}/authorize?${params.toString()}` };+}++export async function handleCallback(code) {+ const tokens = await requestToken({+ grant_type: 'authorization_code',+ code,+ redirect_uri: getRedirectUri(),+ });+ await saveTokens(withExpiry(tokens));+ console.log('🎧 Spotify OAuth callback processed, tokens stored');+ return { success: true };+}++/**+ * Return a valid access token, refreshing via the stored refresh token when the+ * current one is expired/near-expiry. Returns `null` when the user hasn't+ * connected (no tokens) or the grant is unrecoverable (no refresh token) — the+ * caller surfaces a "connect in Settings" prompt rather than throwing.+ *+ * Spotify may OMIT `refresh_token` from a refresh response (it stays valid), so+ * the existing refresh token is preserved when the response doesn't carry one.+ */+export async function getAccessToken() {+ const tokens = await getTokens();+ if (!tokens?.access_token && !tokens?.refresh_token) return null;+ if (!isTokenExpired(tokens)) return tokens.access_token;+ if (!tokens?.refresh_token) return null;++ const refreshed = await requestToken({+ grant_type: 'refresh_token',+ refresh_token: tokens.refresh_token,+ });+ const merged = withExpiry({ ...tokens, ...refreshed });+ if (!refreshed.refresh_token) merged.refresh_token = tokens.refresh_token;+ await saveTokens(merged);+ console.log('🎧 Spotify OAuth access token refreshed');+ return merged.access_token;+}++export async function getAuthStatus() {+ const credentials = await getCredentials();+ const tokens = await getTokens();+ return {+ hasCredentials: !!credentials?.clientId,+ hasTokens: !!(tokens?.access_token || tokens?.refresh_token),+ expiresAt: Number.isFinite(tokens?.expires_at) ? new Date(tokens.expires_at).toISOString() : null,+ scope: tokens?.scope || null,+ redirectUri: getRedirectUri(),+ };+}diff --git a/server/services/spotifyAuth.test.js b/server/services/spotifyAuth.test.jsnew file mode 100644index 0000000000..6c074a9de3--- /dev/null+++ b/server/services/spotifyAuth.test.js@@ -0,0 +1,59 @@+import { describe, it, expect, afterEach } from 'vitest';+import { isTokenExpired, withExpiry, getRedirectUri } from './spotifyAuth.js';++describe('spotifyAuth pure helpers', () => {+ describe('withExpiry', () => {+ it('stamps an absolute expires_at from expires_in seconds', () => {+ const now = 1_700_000_000_000;+ const tokens = withExpiry({ access_token: 'a', expires_in: 3600 }, now);+ expect(tokens.expires_at).toBe(now + 3600 * 1000);+ expect(tokens.access_token).toBe('a');+ });++ it('sets expires_at to null when expires_in is absent/non-numeric', () => {+ expect(withExpiry({ access_token: 'a' }).expires_at).toBeNull();+ expect(withExpiry({ access_token: 'a', expires_in: 'nope' }).expires_at).toBeNull();+ });+ });++ describe('isTokenExpired', () => {+ const now = 1_700_000_000_000;++ it('is false for a token comfortably before expiry', () => {+ expect(isTokenExpired({ access_token: 'a', expires_at: now + 600_000 }, now)).toBe(false);+ });++ it('is true within the refresh skew window', () => {+ expect(isTokenExpired({ access_token: 'a', expires_at: now + 30_000 }, now, 60_000)).toBe(true);+ });++ it('is true past expiry', () => {+ expect(isTokenExpired({ access_token: 'a', expires_at: now - 1 }, now)).toBe(true);+ });++ it('treats a missing access_token or expires_at as expired', () => {+ expect(isTokenExpired({ expires_at: now + 600_000 }, now)).toBe(true);+ expect(isTokenExpired({ access_token: 'a' }, now)).toBe(true);+ expect(isTokenExpired(null, now)).toBe(true);+ });+ });++ describe('getRedirectUri', () => {+ const savedEnv = { ...process.env };+ afterEach(() => {+ process.env = { ...savedEnv };+ });++ it('honors an explicit SPOTIFY_REDIRECT_URI override', () => {+ process.env.SPOTIFY_REDIRECT_URI = 'https://example.test/api/spotify/oauth/callback';+ expect(getRedirectUri()).toBe('https://example.test/api/spotify/oauth/callback');+ });++ it('builds the callback path from PUBLIC_HOST/PORT otherwise', () => {+ delete process.env.SPOTIFY_REDIRECT_URI;+ process.env.PUBLIC_HOST = 'myhost';+ process.env.PORT = '5555';+ expect(getRedirectUri()).toBe('http://myhost:5555/api/spotify/oauth/callback');+ });+ });+});diff --git a/server/services/spotifyScheduler.js b/server/services/spotifyScheduler.jsnew file mode 100644index 0000000000..132dd35a75--- /dev/null+++ b/server/services/spotifyScheduler.js@@ -0,0 +1,55 @@+/**+ * Spotify Sync Scheduler (#2152)+ *+ * Registers an interval job that periodically runs the incremental Spotify+ * recently-played ingestion (see spotifySync.js). Mirrors imessageScheduler.+ *+ * OFF by default: the scheduler is only registered when the user has connected+ * Spotify AND opted in via Settings → Spotify (`settings.spotify.enabled`). The+ * ~25-min default cadence beats the API's 50-track recently-played window so no+ * plays are missed. The interval value is locked at registration (changing it+ * needs a restart), but the `enabled` toggle is re-read on every tick so+ * disabling from settings stops runs without a restart.+ *+ * No LLM calls happen on this path — ingestion is deterministic — so the+ * no-cold-bootstrap AI policy does not gate it; the opt-in is purely about user+ * intent + a completed OAuth connection.+ */++import { schedule } from './eventScheduler.js';+import { getSpotifyConfig, runSync } from './spotifySync.js';++const EVENT_ID = 'spotify-sync';++/**+ * Start the Spotify sync scheduler. No-ops when disabled in settings.+ */+export async function startSpotifyScheduler() {+ const { enabled, intervalMinutes } = await getSpotifyConfig();++ if (!enabled) {+ console.log('🎧 Spotify sync scheduler: disabled in settings — skipping');+ return;+ }++ const intervalMs = intervalMinutes * 60 * 1000;++ schedule({+ id: EVENT_ID,+ type: 'interval',+ intervalMs,+ handler: async () => {+ // Re-read settings each run so an `enabled: false` toggle takes effect+ // without a restart (the interval value itself is locked at registration).+ const current = await getSpotifyConfig();+ if (!current.enabled) {+ console.log('🎧 Spotify sync scheduler: disabled since registration — skipping run');+ return;+ }+ await runSync();+ },+ metadata: { source: 'spotifyScheduler' },+ });++ console.log(`🎧 Spotify sync scheduler: registered every ${intervalMinutes}min`);+}diff --git a/server/services/spotifySync.js b/server/services/spotifySync.jsnew file mode 100644index 0000000000..b2fb025974--- /dev/null+++ b/server/services/spotifySync.js@@ -0,0 +1,243 @@+/**+ * Spotify listening-history ingestion (#2152) — poll the Web API's+ * recently-played endpoint and feed the machine-local human-activity timeline+ * (#2150) with `media.listen` events.+ *+ * Design constraints (docs/plans/2026-07-04-human-activity-tracking.md):+ *+ * - **50-track window ⇒ cadence must beat it.** `GET /v1/me/player/recently-played`+ * only exposes the last 50 plays, so the scheduler polls every ~25 min (see+ * spotifyScheduler.js) to avoid gaps. An incremental `after` cursor (the newest+ * `played_at` seen) keeps each poll to just the new plays.+ * - **Machine-local + idempotent.** The cursor lives in a `data/spotify/` JSON+ * file (per-machine, unsynced). Each event carries a stable+ * `spotify:<played_at>:<trackId>` dedupe key, so re-polls are no-ops.+ * - **LLM-free.** Track/artist/genre metadata is stored verbatim for later twin+ * enrichment (Phase 7); no AI-provider calls happen on this path.+ * - **Raw-response cache.** The latest API payload is cached under+ * `data/spotify/cache/` (local, unsynced) for debugging / re-derivation.+ *+ * The pure mappers (candidate mapping, dedupe keys, cursor advance) are exported+ * and unit-tested with fixture payloads — no network or DB required.+ */+import { dataPath, ensureDir, atomicWrite, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';+import { getSettings } from './settings.js';+import { getAccessToken, getAuthStatus } from './spotifyAuth.js';++// ---------------------------------------------------------------------------+// Constants+// ---------------------------------------------------------------------------++const RECENTLY_PLAYED_URL = 'https://api.spotify.com/v1/me/player/recently-played';++// The API caps this at 50; the cursor + fast cadence keep us from missing plays.+const SCAN_LIMIT = 50;++const STATE_FILE = 'sync-state.json';+const CACHE_FILE = 'recently-played.json';++// Sync is OFF by default — the user connects Spotify + opts in from Settings.+const DEFAULT_CONFIG = { enabled: false, intervalMinutes: 25 };++// ---------------------------------------------------------------------------+// Pure helpers (exported for unit tests — no network, no filesystem, no DB).+// ---------------------------------------------------------------------------++/**+ * Map one recently-played item to a human-activity `media.listen` candidate, or+ * `null` when it's missing a track id / valid `played_at`. Dedupe key is+ * `spotify:<played_at ISO>:<trackId>` — the same track replayed later is a+ * distinct listen, but the same play re-fetched is deduped.+ *+ * `metadata` keeps track/artist/album pointers (+ isrc/popularity) verbatim for+ * Phase 7 taste enrichment; the short `summary` is the artist line only (privacy+ * contract — no full payload in the event row).+ */+export function spotifyListenCandidate(item) {+ const track = item?.track;+ const playedAt = item?.played_at;+ if (!track?.id || !playedAt) return null;+ const at = new Date(playedAt);+ if (Number.isNaN(at.getTime())) return null;++ const artists = Array.isArray(track.artists)+ ? track.artists.map((a) => ({ id: a?.id || null, name: String(a?.name || '').trim() })).filter((a) => a.name)+ : [];+ const artistNames = artists.map((a) => a.name).join(', ');+ const durationS = Number.isFinite(track.duration_ms) ? Math.round(track.duration_ms / 1000) : null;++ return {+ source: 'spotify',+ accountId: null,+ kind: 'media.listen',+ happenedAt: at.toISOString(),+ durationS,+ title: track.name || '(unknown track)',+ summary: artistNames,+ url: track.external_urls?.spotify || null,+ dedupeKey: `spotify:${at.toISOString()}:${track.id}`,+ metadata: {+ trackId: track.id,+ trackName: track.name || null,+ artists,+ album: track.album?.name || null,+ albumId: track.album?.id || null,+ isrc: track.external_ids?.isrc || null,+ popularity: Number.isFinite(track.popularity) ? track.popularity : null,+ explicit: typeof track.explicit === 'boolean' ? track.explicit : null,+ context: item.context?.type || null,+ contextUri: item.context?.uri || null,+ },+ };+}++export function spotifyListenCandidates(items = []) {+ return (items || []).map(spotifyListenCandidate).filter(Boolean);+}++/**+ * Advance the `after` cursor to the newest `played_at` (epoch ms) across a batch,+ * never regressing below the current cursor. Spotify's `after` param is a Unix-ms+ * timestamp that returns plays strictly AFTER it, so the max seen is the next+ * cursor. Ignores items with an unparseable `played_at`.+ */+export function maxPlayedAtMs(items = [], current = 0) {+ let max = Number.isFinite(current) ? current : 0;+ for (const item of items || []) {+ const t = new Date(item?.played_at).getTime();+ if (Number.isFinite(t) && t > max) max = t;+ }+ return max;+}++// ---------------------------------------------------------------------------+// Config + machine-local cursor state+// ---------------------------------------------------------------------------++export async function getSpotifyConfig() {+ const settings = await getSettings().catch(() => ({}));+ const c = settings?.spotify || {};+ return {+ enabled: typeof c.enabled === 'boolean' ? c.enabled : DEFAULT_CONFIG.enabled,+ intervalMinutes: Number.isFinite(c.intervalMinutes) && c.intervalMinutes >= 1+ ? Math.floor(c.intervalMinutes)+ : DEFAULT_CONFIG.intervalMinutes,+ };+}++function stateFilePath() {+ return dataPath('spotify', STATE_FILE);+}++// Machine-local incremental cursor. NOT federated — the recently-played window+// and its timestamps are per-account, so this must never sync to a peer.+export async function readSyncState() {+ const raw = await tryReadFile(stateFilePath());+ const parsed = raw ? safeJSONParse(raw, null, { allowArray: false }) : null;+ return {+ cursorAfter: Number.isFinite(parsed?.cursorAfter) ? parsed.cursorAfter : 0,+ lastRunAt: parsed?.lastRunAt || null,+ lastResult: parsed?.lastResult || null,+ };+}++async function writeSyncState(state) {+ await ensureDir(dataPath('spotify'));+ await atomicWrite(stateFilePath(), JSON.stringify(state, null, 2));+}++async function writeRawCache(payload) {+ await ensureDir(dataPath('spotify', 'cache'));+ await atomicWrite(dataPath('spotify', 'cache', CACHE_FILE), JSON.stringify(payload, null, 2));+}++// ---------------------------------------------------------------------------+// Sync (side-effecting — network + DB). Runs outside the request lifecycle+// (scheduler / explicit endpoint), so network/persist failures return an error+// report instead of throwing.+// ---------------------------------------------------------------------------++// Re-entrancy guard: a manual "Sync now" overlapping a scheduler tick would+// double-read the same cursor (deduped, but doubled work, and the slower writer+// could stamp a stale cursor over the fresher one) — so concurrent callers share+// the in-flight pass.+let syncInFlight = null;+export async function runSync() {+ if (syncInFlight) return syncInFlight;+ syncInFlight = doRunSync().finally(() => { syncInFlight = null; });+ return syncInFlight;+}++async function doRunSync() {+ const accessToken = await getAccessToken().catch((err) => {+ console.error(`❌ Spotify sync auth failed: ${err?.message || err}`);+ return null;+ });+ if (!accessToken) {+ return { ok: false, needsAuth: true, error: 'Spotify not connected — authorize in Settings → Spotify.' };+ }++ const started = Date.now();+ const state = await readSyncState();+ const url = new URL(RECENTLY_PLAYED_URL);+ url.searchParams.set('limit', String(SCAN_LIMIT));+ if (state.cursorAfter) url.searchParams.set('after', String(state.cursorAfter));++ const res = await fetch(url, { headers: { Authorization: `Bearer ${accessToken}` } });+ if (!res.ok) {+ const body = await res.text().catch(() => '');+ console.error(`❌ Spotify recently-played fetch failed: ${res.status} ${body.slice(0, 200)}`);+ return { ok: false, status: res.status, error: `Spotify API returned ${res.status}` };+ }+ const payload = await res.json().catch(() => null);+ const items = Array.isArray(payload?.items) ? payload.items : [];+ await writeRawCache(payload).catch((err) => console.error(`⚠️ Spotify raw-cache write failed: ${err?.message || err}`));++ const candidates = spotifyListenCandidates(items);++ // Persistence failures must NOT advance the cursor: the dedupe keys make a+ // re-poll a no-op, but the recently-played window scrolls, so skipping past+ // unpersisted plays loses them permanently. Hold the cursor on failure.+ let persistFailed = false;+ const { recordEvents } = await import('./humanActivity.js');+ const recordResult = await recordEvents(candidates).catch((err) => {+ console.error(`❌ Spotify activity record failed: ${err?.message || err}`);+ persistFailed = true;+ return { recorded: 0, skipped: candidates.length };+ });++ // Prefer the response's own `cursors.after` (Spotify's canonical next cursor),+ // falling back to the computed max — but never regress below the stored cursor.+ const responseCursor = Number(payload?.cursors?.after);+ const computed = maxPlayedAtMs(items, state.cursorAfter);+ const advanced = Number.isFinite(responseCursor) && responseCursor > (state.cursorAfter || 0)+ ? responseCursor+ : computed;+ const nextCursor = persistFailed ? state.cursorAfter : advanced;++ const result = {+ ok: !persistFailed,+ ...(persistFailed ? { error: 'Persistence failed — cursor held so the batch retries next sync' } : {}),+ scanned: items.length,+ recorded: recordResult.recorded,+ skipped: recordResult.skipped,+ cursorAfter: nextCursor,+ // A full 50-item batch means older plays may remain beyond this pass — the+ // caller (UI toast / next scheduler tick) should run again to keep draining.+ hasMore: items.length === SCAN_LIMIT,+ durationMs: Date.now() - started,+ };+ await writeSyncState({ cursorAfter: nextCursor, lastRunAt: new Date().toISOString(), lastResult: result });+ console.log(`🎧 Spotify sync: scanned ${result.scanned}, recorded ${result.recorded} listen(s), cursor→${result.cursorAfter}${result.hasMore ? ' (more remaining)' : ''}${persistFailed ? ' — PERSIST FAILED, cursor held' : ''} in ${result.durationMs}ms`);+ return result;+}++// Status for the settings UI: config + cursor state + auth status (no API call).+export async function getStatus() {+ const [config, state, auth] = await Promise.all([+ getSpotifyConfig(),+ readSyncState(),+ getAuthStatus(),+ ]);+ return { config, state, auth };+}diff --git a/server/services/spotifySync.test.js b/server/services/spotifySync.test.jsnew file mode 100644index 0000000000..fce2bffdff--- /dev/null+++ b/server/services/spotifySync.test.js@@ -0,0 +1,138 @@+import { describe, it, expect } from 'vitest';+import {+ spotifyListenCandidate,+ spotifyListenCandidates,+ maxPlayedAtMs,+} from './spotifySync.js';++// A minimal recently-played item, shaped like the Spotify Web API response.+function makeItem(overrides = {}) {+ return {+ played_at: '2024-03-10T15:30:00.123Z',+ track: {+ id: 'track123',+ name: 'Test Song',+ duration_ms: 210000,+ artists: [+ { id: 'artist1', name: 'Alpha' },+ { id: 'artist2', name: 'Beta' },+ ],+ album: { id: 'album1', name: 'Test Album' },+ external_urls: { spotify: 'https://open.spotify.com/track/track123' },+ external_ids: { isrc: 'USABC1234567' },+ explicit: false,+ popularity: 72,+ },+ context: { type: 'playlist', uri: 'spotify:playlist:xyz' },+ ...overrides,+ };+}++describe('spotifySync pure helpers', () => {+ describe('spotifyListenCandidate', () => {+ it('maps a recently-played item to a media.listen candidate', () => {+ const c = spotifyListenCandidate(makeItem());+ expect(c.source).toBe('spotify');+ expect(c.kind).toBe('media.listen');+ expect(c.title).toBe('Test Song');+ expect(c.summary).toBe('Alpha, Beta');+ expect(c.durationS).toBe(210);+ expect(c.url).toBe('https://open.spotify.com/track/track123');+ expect(c.happenedAt).toBe(new Date('2024-03-10T15:30:00.123Z').toISOString());+ });++ it('uses spotify:<played_at ISO>:<trackId> as the dedupe key', () => {+ const c = spotifyListenCandidate(makeItem());+ expect(c.dedupeKey).toBe('spotify:2024-03-10T15:30:00.123Z:track123');+ });++ it('carries track/artist/album metadata verbatim for later enrichment', () => {+ const c = spotifyListenCandidate(makeItem());+ expect(c.metadata).toMatchObject({+ trackId: 'track123',+ trackName: 'Test Song',+ album: 'Test Album',+ albumId: 'album1',+ isrc: 'USABC1234567',+ popularity: 72,+ explicit: false,+ context: 'playlist',+ contextUri: 'spotify:playlist:xyz',+ });+ expect(c.metadata.artists).toEqual([+ { id: 'artist1', name: 'Alpha' },+ { id: 'artist2', name: 'Beta' },+ ]);+ });++ it('returns null when the track id is missing', () => {+ expect(spotifyListenCandidate(makeItem({ track: { name: 'x' } }))).toBeNull();+ });++ it('returns null when played_at is missing or invalid', () => {+ expect(spotifyListenCandidate(makeItem({ played_at: null }))).toBeNull();+ expect(spotifyListenCandidate(makeItem({ played_at: 'not-a-date' }))).toBeNull();+ expect(spotifyListenCandidate(null)).toBeNull();+ });++ it('tolerates a missing duration / album / artists', () => {+ const c = spotifyListenCandidate({+ played_at: '2024-03-10T15:30:00.000Z',+ track: { id: 't', name: 'Bare' },+ });+ expect(c.durationS).toBeNull();+ expect(c.summary).toBe('');+ expect(c.metadata.artists).toEqual([]);+ expect(c.metadata.album).toBeNull();+ });++ it('distinguishes the same track replayed at a different time', () => {+ const a = spotifyListenCandidate(makeItem({ played_at: '2024-03-10T10:00:00.000Z' }));+ const b = spotifyListenCandidate(makeItem({ played_at: '2024-03-10T12:00:00.000Z' }));+ expect(a.dedupeKey).not.toBe(b.dedupeKey);+ });+ });++ describe('spotifyListenCandidates', () => {+ it('maps a batch and drops invalid items', () => {+ const list = spotifyListenCandidates([+ makeItem(),+ makeItem({ track: { name: 'no-id' } }),+ makeItem({ played_at: null }),+ ]);+ expect(list).toHaveLength(1);+ });++ it('returns an empty array for non-array input', () => {+ expect(spotifyListenCandidates(null)).toEqual([]);+ expect(spotifyListenCandidates(undefined)).toEqual([]);+ });+ });++ describe('maxPlayedAtMs (cursor advance)', () => {+ it('returns the newest played_at across the batch', () => {+ const items = [+ { played_at: '2024-03-10T10:00:00.000Z' },+ { played_at: '2024-03-10T12:00:00.000Z' },+ { played_at: '2024-03-10T11:00:00.000Z' },+ ];+ expect(maxPlayedAtMs(items, 0)).toBe(new Date('2024-03-10T12:00:00.000Z').getTime());+ });++ it('never regresses below the current cursor', () => {+ const cursor = new Date('2024-03-11T00:00:00.000Z').getTime();+ const items = [{ played_at: '2024-03-10T12:00:00.000Z' }];+ expect(maxPlayedAtMs(items, cursor)).toBe(cursor);+ });++ it('ignores items with an unparseable played_at', () => {+ const items = [{ played_at: 'garbage' }, { played_at: '2024-03-10T12:00:00.000Z' }];+ expect(maxPlayedAtMs(items, 0)).toBe(new Date('2024-03-10T12:00:00.000Z').getTime());+ });++ it('returns the current cursor for an empty batch', () => {+ expect(maxPlayedAtMs([], 42)).toBe(42);+ expect(maxPlayedAtMs(null, 42)).toBe(42);+ });+ });+});