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-2153]): YouTube watch history — CDP scrape + Takeout backfill
Adam Eivyfb657002f9e1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ebd81e97df..c36efc3ba1 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -68,6 +68,7 @@- **[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`)+- **[issue-2153] YouTube watch history** — YouTube killed its watch-history API, so PortOS ingests your viewing two complementary ways, both landing as `media.watch` events on the activity timeline (taste signal for the digital twin). A new **Settings → YouTube** tab scrapes your signed-in `youtube.com/feed/history` page through the managed browser — off by default and opt-in: log into YouTube in the managed browser, run "Check setup" to confirm you're signed in, set a conservative scrape interval (the history page only shows day-bucketed entries, so a few times a day is plenty), and use "Scrape now" to run immediately. Selector failures degrade to a surfaced sync-status error instead of crashing, and all the page selectors live in one place for easy repair. For reliable historical data (and a fallback whenever the scrape breaks), the **Timeline** page gains a **Google Takeout backfill** importer: upload your "YouTube and YouTube Music → history" export (the ZIP or a single `watch-history.json`) and every watch is imported with its exact timestamp. Both paths share a per-video-per-local-day dedupe key, so a Takeout backfill and the live scrape reconcile without double-counting, and re-imports/re-scrapes are always safe. Like the rest of the timeline, watches are machine-local and never federate to your peers. (`server/services/youtubeSync.js`, `server/services/youtubeImport.js`, `server/services/youtubeScheduler.js`, `server/routes/youtube.js`, `client/src/components/settings/YoutubeTab.jsx`, `client/src/components/timeline/YoutubeImportPanel.jsx`)## Privacy Centerdiff --git a/client/src/components/settings/SettingsTabsHeader.jsx b/client/src/components/settings/SettingsTabsHeader.jsxindex 76fa4c7f34..314700fbbd 100644--- a/client/src/components/settings/SettingsTabsHeader.jsx+++ b/client/src/components/settings/SettingsTabsHeader.jsx@@ -27,7 +27,8 @@ export const TABS = [{ 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' }+ { id: 'voice', label: 'Voice', to: '/settings/voice' },+ { id: 'youtube', label: 'YouTube', to: '/settings/youtube' }];export default function SettingsTabsHeader({ activeTab }) {diff --git a/client/src/components/settings/YoutubeTab.jsx b/client/src/components/settings/YoutubeTab.jsxnew file mode 100644index 0000000000..3dde22a8ee--- /dev/null+++ b/client/src/components/settings/YoutubeTab.jsx@@ -0,0 +1,203 @@+import { useEffect, useState } from 'react';+import { Save, Loader2, MonitorPlay, RefreshCw, CheckCircle2, AlertCircle, ShieldQuestion } from 'lucide-react';+import toast from '../ui/Toast';+import BrailleSpinner from '../BrailleSpinner';+import {+ getSettings,+ updateSettings,+ getYoutubeStatus,+ getYoutubeSetupCheck,+ syncYoutube,+} from '../../services/api';++// Settings → YouTube (#2153). Opt-in, machine-local ingestion of YouTube watch+// history into the activity timeline. OFF by default — the YouTube watch-history+// API is gone, so this scrapes the signed-in history page in the managed browser.+// Requires being logged into YouTube there; the Takeout backfill on the Timeline+// page is the reliable historical path.+export function YoutubeTab() {+ const [loading, setLoading] = useState(true);+ const [enabled, setEnabled] = useState(false);+ const [intervalMinutes, setIntervalMinutes] = useState(480);+ const [savedEnabled, setSavedEnabled] = useState(false);+ const [savedInterval, setSavedInterval] = useState(480);+ const [saving, setSaving] = useState(false);++ const [status, setStatus] = useState(null);+ const [syncing, setSyncing] = useState(false);+ const [checking, setChecking] = useState(false);+ const [setup, setSetup] = useState(null);++ useEffect(() => {+ Promise.all([+ getSettings({ silent: true }).catch(() => ({})),+ getYoutubeStatus({ silent: true }).catch(() => null),+ ])+ .then(([settings, st]) => {+ const c = settings?.youtube || {};+ const en = typeof c.enabled === 'boolean' ? c.enabled : false;+ const iv = Number.isFinite(c.intervalMinutes) ? c.intervalMinutes : 480;+ setEnabled(en);+ setIntervalMinutes(iv);+ setSavedEnabled(en);+ setSavedInterval(iv);+ setStatus(st);+ })+ .finally(() => setLoading(false));+ }, []);++ const dirty = enabled !== savedEnabled || Number(intervalMinutes) !== Number(savedInterval);++ const handleSave = async () => {+ const iv = Math.max(1, Math.min(1440, Math.floor(Number(intervalMinutes) || 480)));+ setSaving(true);+ const merged = await updateSettings({ youtube: { 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 handleCheckSetup = async () => {+ setChecking(true);+ const result = await getYoutubeSetupCheck({ silent: true }).catch(() => null);+ setChecking(false);+ setSetup(result);+ if (result?.ok) toast.success('Signed into YouTube in the managed browser');+ else if (result) toast.error(result.error || 'YouTube not ready');+ else toast.error('Setup check failed');+ };++ const handleSyncNow = async () => {+ setSyncing(true);+ const result = await syncYoutube({ silent: true }).catch(() => ({ ok: false, error: 'Sync failed' }));+ setSyncing(false);+ if (result?.ok) {+ toast.success(`Scraped ${result.scanned} entr${result.scanned === 1 ? 'y' : 'ies'} — ${result.recorded} new watch(es)`);+ setStatus((prev) => ({ ...(prev || {}), state: { ...(prev?.state || {}), lastResult: result, lastRunAt: new Date().toISOString() } }));+ } else {+ toast.error(result?.needsAuth ? 'Log into YouTube in the managed browser 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">+ <MonitorPlay size={16} className="text-port-accent" />+ <h3 className="text-lg font-semibold text-white">YouTube watch history</h3>+ </div>+ <p className="text-sm text-gray-400 mb-4">+ Scrapes your{' '}+ <a href="https://www.youtube.com/feed/history" target="_blank" rel="noreferrer" className="text-port-accent hover:underline">+ YouTube history+ </a>{' '}+ in the managed browser and feeds the activity timeline (taste signal for the digital twin). There is no+ watch-history API, so this reads the signed-in page — log into YouTube in the managed browser first.+ Machine-local — nothing federates to peers. For full historical data, use the Google Takeout backfill on+ the Timeline page.+ </p>++ {/* Step 1 — sign in / setup check */}+ <div className="space-y-3 border-b border-port-border pb-5 mb-5">+ <h4 className="text-sm font-semibold text-gray-200">1. Sign into YouTube in the managed browser</h4>+ <div className="flex flex-wrap items-center gap-2">+ <button+ type="button"+ onClick={handleCheckSetup}+ disabled={checking}+ 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"+ >+ {checking ? <Loader2 size={14} className="animate-spin" /> : <ShieldQuestion size={14} />}+ Check setup+ </button>+ {setup && (+ setup.ok ? (+ <span className="inline-flex items-center gap-1.5 text-port-success text-sm"><CheckCircle2 size={14} /> Signed in & ready</span>+ ) : (+ <span className="inline-flex items-center gap-1.5 text-port-warning text-sm"><AlertCircle size={14} /> {setup.error || 'Not ready'}</span>+ )+ )}+ </div>+ {setup && !setup.ok && setup.remediation && (+ <p className="text-xs text-gray-500">{setup.remediation}</p>+ )}+ </div>++ {/* Step 2 — schedule */}+ <div className="space-y-3">+ <h4 className="text-sm font-semibold text-gray-200">2. Scheduled scrape</h4>+ <label htmlFor="youtube-enabled" className="flex items-center gap-2 text-sm text-gray-200 cursor-pointer">+ <input+ id="youtube-enabled"+ type="checkbox"+ checked={enabled}+ onChange={(e) => setEnabled(e.target.checked)}+ className="w-4 h-4 accent-port-accent"+ />+ Enable scheduled YouTube scrape+ </label>++ <div>+ <label htmlFor="youtube-interval" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">+ Scrape interval (minutes)+ </label>+ <input+ id="youtube-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">+ The history page only shows day-bucketed entries — a few times a day (e.g. 480 min) is plenty. Be a polite scraper.+ </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}+ 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} />}+ Scrape now+ </button>+ </div>+ </div>+ </div>++ {lastResult && (+ <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 scrape</h3>+ <dl className="grid grid-cols-2 sm:grid-cols-3 gap-3 text-sm">+ <div><dt className="text-gray-500 text-xs uppercase">Watches recorded</dt><dd className="text-gray-200">{lastResult?.recorded ?? '—'}</dd></div>+ <div><dt className="text-gray-500 text-xs uppercase">Entries scanned</dt><dd className="text-gray-200">{lastResult?.scanned ?? '—'}</dd></div>+ <div><dt className="text-gray-500 text-xs uppercase">Status</dt><dd className="text-gray-200">{lastResult?.ok ? 'ok' : (lastResult?.error || lastResult?.status || 'error')}</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 YoutubeTab;diff --git a/client/src/components/timeline/YoutubeImportPanel.jsx b/client/src/components/timeline/YoutubeImportPanel.jsxnew file mode 100644index 0000000000..05a7ec24d7--- /dev/null+++ b/client/src/components/timeline/YoutubeImportPanel.jsx@@ -0,0 +1,39 @@+import { MonitorPlay } from 'lucide-react';+import * as api from '../../services/api';+import ActivityImportPanel, { dateRangeLabel } from './ActivityImportPanel';++// Bulk-backfill importer for Google Takeout YouTube watch history (#2153), built+// on the shared ActivityImportPanel seam. This is the reliable historical path+// (and a fallback whenever the live scrape breaks).+export default function YoutubeImportPanel({ onImported }) {+ return (+ <ActivityImportPanel+ icon={MonitorPlay}+ title="Import YouTube watch history"+ noun="watch"+ importFn={api.importYoutubeHistory}+ onImported={onImported}+ help={(+ <>+ Request your <span className="text-gray-300">YouTube and YouTube Music → history</span> from+ <a href="https://takeout.google.com" target="_blank" rel="noreferrer" className="text-port-accent hover:underline"> Google Takeout</a>,+ then upload the ZIP (or a single <span className="font-mono">watch-history.json</span>) here. Re-imports are+ safe — already-recorded watches are skipped.+ </>+ )}+ renderPreview={(summary) => (+ <>+ <div>{summary.watches} watch(es) across {summary.uniqueVideos} unique video(s)</div>+ {dateRangeLabel(summary.from, summary.to) && (+ <div>Range: {dateRangeLabel(summary.from, summary.to)}</div>+ )}+ {summary.topChannels?.length > 0 && (+ <div className="mt-1 truncate">+ Top: {summary.topChannels.slice(0, 5).map((c) => c.name).join(', ')}+ </div>+ )}+ </>+ )}+ />+ );+}diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsxindex 424d08f234..97ff3046c6 100644--- a/client/src/pages/Settings.jsx+++ b/client/src/pages/Settings.jsx@@ -16,6 +16,7 @@ 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 { YoutubeTab } from '../components/settings/YoutubeTab';import { VoiceTab } from '../components/settings/VoiceTab';import SettingsTabsHeader from '../components/settings/SettingsTabsHeader';@@ -49,6 +50,7 @@ export default function Settings() {case 'security': return <SecurityTab />;case 'sharing': return <SharingTab />;case 'spotify': return <SpotifyTab />;+ case 'youtube': return <YoutubeTab />;case 'voice': return <VoiceTab />;case 'telegram': return <TelegramTab />;case 'mortalloom': return <MortalLoomTab />;diff --git a/client/src/pages/Timeline.jsx b/client/src/pages/Timeline.jsxindex e56670dba5..4d61bd93ec 100644--- a/client/src/pages/Timeline.jsx+++ b/client/src/pages/Timeline.jsx@@ -10,6 +10,7 @@ import TakeoutLocationImportPanel from '../components/timeline/TakeoutLocationImimport DiscordImportPanel from '../components/timeline/DiscordImportPanel';import WhatsappImportPanel from '../components/timeline/WhatsappImportPanel';import BrowserHistoryImportPanel from '../components/timeline/BrowserHistoryImportPanel';+import YoutubeImportPanel from '../components/timeline/YoutubeImportPanel';import * as api from '../services/api';import toast from '../components/ui/Toast';import { formatClockTime, formatDurationSec } from '../utils/formatters';@@ -217,6 +218,7 @@ export default function Timeline() {<DiscordImportPanel onImported={() => setReloadKey((k) => k + 1)} /><WhatsappImportPanel onImported={() => setReloadKey((k) => k + 1)} /><BrowserHistoryImportPanel onImported={() => setReloadKey((k) => k + 1)} />+ <YoutubeImportPanel onImported={() => setReloadKey((k) => k + 1)} /><Histogram histogram={histogram} />diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 019d5324ea..a706464afe 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -78,6 +78,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiCalendar.js` | Calendar events. || `apiMessages.js` | Messages / notifications. || `apiSpotify.js` | Spotify OAuth + listening-history sync. |+| `apiYoutube.js` | YouTube watch-history scrape sync + setup check. || `apiPersonalities.js` | Agent personality profiles. |## Media / creativediff --git a/client/src/services/api.js b/client/src/services/api.jsindex 90c64bc251..87ed68f51b 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -24,6 +24,7 @@ export * from './apiAccounts.js';export * from './apiSchedules.js';export * from './apiMessages.js';export * from './apiSpotify.js';+export * from './apiYoutube.js';export * from './apiCalendar.js';export * from './apiGoals.js';export * from './apiReview.js';diff --git a/client/src/services/apiTimeline.js b/client/src/services/apiTimeline.jsindex 3cf846cb5b..099783e291 100644--- a/client/src/services/apiTimeline.js+++ b/client/src/services/apiTimeline.js@@ -64,3 +64,9 @@ export const importWhatsappHistory = (file, { yourName, chatLabel, ...options }// visit-instant + URL). Subframe (iframe) loads are dropped server-side.export const importBrowserHistory = (file, options = {}) =>importFile('/timeline/import/browser', file, options);++// Google Takeout YouTube `watch-history.json` (standalone or zipped) — each watch+// becomes a `media.watch` event (dedupe on video id + local day, shared with the+// live scrape so the backfill and scrape reconcile).+export const importYoutubeHistory = (file, options = {}) =>+ importFile('/timeline/import/youtube', file, options);diff --git a/client/src/services/apiYoutube.js b/client/src/services/apiYoutube.jsnew file mode 100644index 0000000000..c3e884d80a--- /dev/null+++ b/client/src/services/apiYoutube.js@@ -0,0 +1,9 @@+import { request } from './apiCore.js';++// YouTube watch-history ingestion (#2153) — CDP scrape of the signed-in history+// page in the managed browser + Takeout backfill, into the machine-local activity+// timeline. Config lives in settings.youtube; last-run state under data/youtube/.+// These wrappers drive the settings tab.+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 });diff --git a/server/index.js b/server/index.jsindex 0dda65f595..a040acf300 100644--- a/server/index.js+++ b/server/index.js@@ -50,6 +50,7 @@ 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 youtubeRoutes from './routes/youtube.js';import notificationsRoutes from './routes/notifications.js';import standardizeRoutes from './routes/standardize.js';import brainRoutes from './routes/brain.js';@@ -172,6 +173,7 @@ 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 { startYoutubeScheduler } from './services/youtubeScheduler.js';import * as telegram from './services/telegram.js';import * as telegramBridge from './services/telegramBridge.js';import { getSettings as getInitSettings } from './services/settings.js';@@ -480,6 +482,7 @@ app.use('/api/tribe', tribeRoutes);app.use('/api/timeline', timelineRoutes);app.use('/api/imessage', imessageRoutes);app.use('/api/spotify', spotifyRoutes);+app.use('/api/youtube', youtubeRoutes);app.use('/api/notifications', notificationsRoutes);app.use('/api/standardize', standardizeRoutes);app.use('/api/brain/import', brainImportRoutes);@@ -611,6 +614,10 @@ startImessageScheduler().catch(err => console.error(`❌ iMessage sync scheduler// 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}`));+// Initialize YouTube watch-history sync scheduler — OFF by default; only scrapes+// the signed-in history page in the managed browser when the user opts in via+// Settings → YouTube (#2153).+startYoutubeScheduler().catch(err => console.error(`❌ YouTube 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 d7a94d3bf1..61ae903147 100644--- a/server/lib/mediaValidation.js+++ b/server/lib/mediaValidation.js@@ -39,6 +39,16 @@ export const spotifyConfigSchema = z.object({intervalMinutes: z.number().int().min(1).max(1440).optional()});+// YouTube watch-history ingestion config (#2153) — the `settings.youtube` slice.+// The scrape is OFF by default and only reads the signed-in history page in the+// managed browser when enabled. Validated as a settings slice on PUT /api/settings;+// service-side DEFAULT_CONFIG fills any absent field (default cadence ~8h, since+// the history page is day-bucketed) so an install with no `youtube` key resolves.+export const youtubeConfigSchema = 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 d80f54c631..a3ad2e3b0d 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -101,7 +101,7 @@ export const NAV_COMMANDS = [{ id: 'nav.messages.config', path: '/messages/config', label: 'Config', section: 'Comms', aliases: ['messages-config', 'comms-config'], keywords: ['comms'] },{ id: 'nav.messages.sync', path: '/messages/sync', label: 'Sync', section: 'Comms', aliases: ['messages-sync', 'comms-sync'], keywords: ['comms'] },{ id: 'nav.openclaw', path: '/openclaw', label: 'OpenClaw', section: 'Brain', aliases: ['openclaw'] },- { id: 'nav.timeline', path: '/timeline', label: 'Timeline', section: 'Brain', aliases: ['activity-timeline', 'activity', 'my-day', 'life-log', 'life-timeline'], keywords: ['human activity', 'life log', 'timeline', 'messages', 'calendar', 'history', 'what did i do', 'daily', 'import', 'backfill', 'whatsapp', 'spotify', 'discord'] },+ { id: 'nav.timeline', path: '/timeline', label: 'Timeline', section: 'Brain', aliases: ['activity-timeline', 'activity', 'my-day', 'life-log', 'life-timeline'], keywords: ['human activity', 'life log', 'timeline', 'messages', 'calendar', 'history', 'what did i do', 'daily', 'import', 'backfill', 'whatsapp', 'spotify', 'discord', 'youtube'] },{ id: 'nav.tribe', path: '/tribe', label: 'Tribe', section: 'Brain', aliases: ['tribe', 'relationships', 'relationship-manager', 'people'], keywords: ['dunbar', 'friends', 'family', 'network', 'social graph', 'care cadence'] },{ id: 'nav.devtools.runs', path: '/devtools/runs', label: 'AI Runs', section: 'Dev Tools', aliases: ['ai-runs', 'devtools'] },@@ -189,6 +189,7 @@ export const NAV_COMMANDS = [{ 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'] },+ { id: 'nav.settings.youtube', path: '/settings/youtube', label: 'YouTube', section: 'Settings', aliases: ['settings-youtube', 'youtube', 'youtube-settings'], keywords: ['youtube', 'watch history', 'video', 'scrape', 'takeout', 'timeline', 'taste', 'media'] },{ id: 'nav.ambient', path: '/ambient', label: 'Ambient', section: 'Dev Tools', aliases: ['ambient', 'ambient-mode', 'ambient mode'], keywords: ['idle', 'background', 'display', 'screensaver', 'fullscreen'] },{ id: 'nav.capabilities', path: '/capabilities', label: 'Capabilities', section: 'Dev Tools', aliases: ['capabilities', 'capability-map', 'integrations'], keywords: ['status', 'setup', 'checklist', 'connected systems', 'integrations', 'providers', 'health overview'] },diff --git a/server/routes/settings.js b/server/routes/settings.jsindex 11aa0ab630..a45e5c407e 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, spotifyConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, validateRequest } from '../lib/validation.js';+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, validateRequest } from '../lib/validation.js';const router = Router();@@ -163,6 +163,11 @@ router.put('/', asyncHandler(async (req, res) => {if (req.body?.spotify !== undefined) {validateRequest(spotifyConfigSchema.partial(), req.body.spotify);}+ // YouTube watch-history scrape config (#2153) — validate the slice when present+ // so a malformed enabled/interval can't reach disk and break the sync scheduler.+ if (req.body?.youtube !== undefined) {+ validateRequest(youtubeConfigSchema.partial(), req.body.youtube);+ }// 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/timeline.js b/server/routes/timeline.jsindex a1244d8a81..c92efd1935 100644--- a/server/routes/timeline.js+++ b/server/routes/timeline.js@@ -11,6 +11,7 @@ import { importTakeoutLocationHistory } from '../services/takeoutLocationImport.import { importDiscordHistory } from '../services/discordImport.js';import { importWhatsappHistory } from '../services/whatsappImport.js';import { importBrowserHistory } from '../services/browserHistoryImport.js';+import { importYoutubeHistory } from '../services/youtubeImport.js';const router = Router();@@ -28,6 +29,9 @@ const zipOrJsonUpload = (label) => uploadSingle('file', {});const uploadSpotify = zipOrJsonUpload('Spotify');+// YouTube watch history ships as a Takeout `watch-history.json` (or the whole+// ZIP) — same ZIP-or-JSON shape as the other Takeout importers.+const uploadYoutube = zipOrJsonUpload('Google Takeout YouTube watch history');const uploadTakeoutLocation = zipOrJsonUpload('Google Takeout location');// Browser history ships as a Takeout Chrome `History.json` (or the whole ZIP) —// same ZIP-or-JSON shape as the other Takeout importers.@@ -166,4 +170,9 @@ router.post('/import/whatsapp', uploadWhatsapp, importHandler(importWhatsappHist// carries no visit id). Subframe (iframe) loads are dropped as noise.router.post('/import/browser', uploadBrowserHistory, importHandler(importBrowserHistory));+// POST /api/timeline/import/youtube — bulk-backfill a Google Takeout YouTube+// `watch-history.json` (standalone or the whole ZIP) → media.watch events under+// source `youtube` (dedupe on video id + local day, shared with the live scrape).+router.post('/import/youtube', uploadYoutube, importHandler(importYoutubeHistory));+export default router;diff --git a/server/routes/youtube.js b/server/routes/youtube.jsnew file mode 100644index 0000000000..a789a7d9e5--- /dev/null+++ b/server/routes/youtube.js@@ -0,0 +1,30 @@+import { Router } from 'express';++import { asyncHandler } from '../lib/errorHandler.js';+import * as youtubeSync from '../services/youtubeSync.js';++const router = Router();++// Setup check — is the managed browser running and signed into YouTube? Never+// throws (checkSetup returns a report), so a signed-out profile surfaces as a+// clean JSON status the settings UI can render with a "log into YouTube" action.+router.get('/setup-check', asyncHandler(async (req, res) => {+ const report = await youtubeSync.checkSetup();+ res.json(report);+}));++// Status — current config (enabled/interval) + machine-local last-run state. No+// scrape, so this is cheap and safe to poll from the settings tab.+router.get('/status', asyncHandler(async (req, res) => {+ const status = await youtubeSync.getStatus();+ res.json(status);+}));++// 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) => {+ const result = await youtubeSync.runSync();+ res.json(result);+}));++export default router;diff --git a/server/services/browserService.js b/server/services/browserService.jsindex a582521822..3ebed05627 100644--- a/server/services/browserService.js+++ b/server/services/browserService.js@@ -23,8 +23,8 @@ const LOGS_TIMEOUT_MS = 5000;const CDP_DEFAULT_TIMEOUT_MS = 10000;const CDP_EVALUATE_TIMEOUT_MS = 60000;-// Auth/login redirect detection across providers (Microsoft, Okta, generic)-const AUTH_PATTERNS = ['login.microsoftonline.com', 'okta.com', 'login.live.com', 'Sign in'];+// Auth/login redirect detection across providers (Microsoft, Okta, Google, generic)+const AUTH_PATTERNS = ['login.microsoftonline.com', 'okta.com', 'login.live.com', 'accounts.google.com', 'Sign in'];const CONFIG_FILE = join(PATHS.data, 'browser-config.json');const ECOSYSTEM_FILE = join(PATHS.root, 'ecosystem.config.cjs');diff --git a/server/services/youtubeImport.js b/server/services/youtubeImport.jsnew file mode 100644index 0000000000..7df11f6e8a--- /dev/null+++ b/server/services/youtubeImport.js@@ -0,0 +1,242 @@+/**+ * YouTube watch-history Takeout importer (#2153) — bulk historical backfill into+ * the machine-local human-activity timeline (#2150).+ *+ * YouTube killed the watch-history API years ago, so the reliable path for+ * historical data is Google Takeout: request "YouTube and YouTube Music →+ * history" and Google ships `watch-history.json` (a flat array, newest first)+ * covering the account lifetime. This importer takes that export (the raw ZIP or+ * the individual JSON) and maps every watch into a `media.watch` activity event+ * with the EXACT timestamp Takeout records.+ *+ * Takeout `watch-history.json` record shape:+ * {+ * header: "YouTube" | "YouTube Music",+ * title: "Watched <video title>", // "Watched a video that has been removed" when gone+ * titleUrl: "https://www.youtube.com/watch?v=VIDEOID", // absent for removed videos / some ads+ * subtitles: [{ name: "<channel>", url: "https://www.youtube.com/channel/UC..." }],+ * time: "2024-01-05T04:32:10.123Z",+ * products: ["YouTube"],+ * activityControls: ["YouTube watch history"],+ * }+ *+ * Dedupe reconciles the scrape and the backfill: BOTH sources key on+ * `yt:<videoId>:<localDay>` (the history page only shows a video once per day, so+ * day-bucketing is the coarsest-common-denominator that keeps a Takeout import and+ * a live scrape of the same watch from double-counting). The `happenedAt` we store+ * from Takeout is the exact timestamp; the scrape can only offer local midnight.+ * `recordEvents`'s `ON CONFLICT DO NOTHING` makes re-imports (and overlap with the+ * scrape) no-ops. No AI-provider calls; parsing is deterministic and LLM-free.+ */+import { createReadStream } from 'fs';+import { readFile } from 'fs/promises';+import { parseZip, collectZipEntry } from '../lib/zipStream.js';+import { shortSummary, recordEvents, localDayKey } from './humanActivity.js';+import { getUserTimezone } from '../lib/timezone.js';++// ---------------------------------------------------------------------------+// Pure helpers (exported for unit tests — no DB, no filesystem, no side effects).+// Shared with youtubeSync.js so the scrape and the backfill agree on video-id+// extraction and dedupe-key construction.+// ---------------------------------------------------------------------------++// Extract the 11-char YouTube video id from any of the URL shapes YouTube emits:+// watch?v=ID · youtu.be/ID · /shorts/ID · /embed/ID · /v/ID · music.youtube.com+// Returns the id or null. The trailing charset is bounded so a garbage query+// string can't smuggle a giant "id" into the dedupe key.+export function youtubeVideoIdFromUrl(url) {+ if (!url) return null;+ const s = String(url).trim();+ const vParam = /[?&]v=([A-Za-z0-9_-]{6,20})/.exec(s);+ if (vParam) return vParam[1];+ const pathId = /(?:youtu\.be\/|\/shorts\/|\/embed\/|\/v\/)([A-Za-z0-9_-]{6,20})/.exec(s);+ if (pathId) return pathId[1];+ return null;+}++// Resolve a Takeout watch timestamp to a UTC ISO string, or null if unparseable.+// Takeout's `time` is ISO-8601 with a `Z` (or an explicit offset), so a plain+// Date parse is correct — no OS-timezone ambiguity to correct for.+export function resolveYoutubeInstant(value) {+ if (!value) return null;+ const d = new Date(String(value).trim());+ return Number.isNaN(d.getTime()) ? null : d.toISOString();+}++// Strip Takeout's localized action prefix from a title. English exports prefix+// "Watched " (videos) / "Viewed " (some ads); other locales differ. We only strip+// the known English prefixes and otherwise keep the title verbatim — the video id+// (not the title) is what identifies the watch, so a non-English title still maps.+export function stripWatchedPrefix(title) {+ if (!title) return '';+ const s = String(title).trim();+ const m = /^(?:Watched|Viewed)\s+(.*)$/s.exec(s);+ return (m ? m[1] : s).trim();+}++// Map ONE raw Takeout watch record to a `media.watch` candidate, or null when it+// lacks a resolvable video id (removed videos / bare ad impressions carry no+// autobiographical signal) or a usable timestamp. `timezone` anchors the+// local-day dedupe bucket so a watch near local midnight keys to the right day.+export function takeoutWatchRecordToCandidate(record, timezone) {+ if (!record || typeof record !== 'object') return null;+ const happenedAt = resolveYoutubeInstant(record.time);+ if (!happenedAt) return null;+ const videoId = youtubeVideoIdFromUrl(record.titleUrl);+ if (!videoId) return null;++ const dayKey = localDayKey(happenedAt, timezone);+ if (!dayKey) return null;++ const title = stripWatchedPrefix(record.title) || '(untitled video)';+ const sub = Array.isArray(record.subtitles) ? record.subtitles[0] : null;+ const channel = sub?.name ? String(sub.name).trim() : null;+ const channelUrl = sub?.url ? String(sub.url).trim() : null;+ const product = typeof record.header === 'string' ? record.header : 'YouTube';++ return {+ source: 'youtube',+ kind: 'media.watch',+ happenedAt,+ title,+ summary: channel ? shortSummary(channel) : null,+ url: `https://www.youtube.com/watch?v=${videoId}`,+ // Shared with the scrape — one watch per video per local day (see file header).+ dedupeKey: `yt:${videoId}:${dayKey}`,+ metadata: {+ videoId,+ channel,+ channelUrl,+ product,+ dayBucket: dayKey,+ },+ };+}++// Map a batch of raw records to candidates, dropping the unmappable ones.+export function youtubeWatchActivityCandidates(records = [], timezone) {+ if (!Array.isArray(records)) return [];+ return records.map((r) => takeoutWatchRecordToCandidate(r, timezone)).filter(Boolean);+}++// Summarize a candidate batch for the import preview: date range, watch count,+// unique videos, and the top channels by watch count. Pure over candidates.+export function summarizeYoutubeCandidates(candidates = []) {+ const list = Array.isArray(candidates) ? candidates : [];+ let earliest = null;+ let latest = null;+ const videos = new Set();+ const channelCounts = new Map();+ for (const c of list) {+ if (c.happenedAt) {+ if (!earliest || c.happenedAt < earliest) earliest = c.happenedAt;+ if (!latest || c.happenedAt > latest) latest = c.happenedAt;+ }+ videos.add(c.metadata?.videoId || c.title);+ const channel = c.metadata?.channel;+ if (channel) channelCounts.set(channel, (channelCounts.get(channel) || 0) + 1);+ }+ const topChannels = [...channelCounts.entries()]+ .sort((a, b) => b[1] - a[1])+ .slice(0, 10)+ .map(([name, count]) => ({ name, count }));+ return {+ watches: list.length,+ uniqueVideos: videos.size,+ from: earliest,+ to: latest,+ topChannels,+ };+}++// Parse the text of a single Takeout watch-history JSON file into a record array.+// Tolerates a top-level array (the normal shape) and an `{ items: [...] }`+// wrapper; anything else yields []. Throws only on malformed JSON.+export function parseYoutubeJsonText(text) {+ const parsed = JSON.parse(text);+ if (Array.isArray(parsed)) return parsed;+ if (Array.isArray(parsed?.items)) return parsed.items;+ return [];+}++// ---------------------------------------------------------------------------+// File ingestion (ZIP or single JSON) → records.+// ---------------------------------------------------------------------------++const isZip = (file) =>+ file?.mimetype === 'application/zip' ||+ file?.mimetype === 'application/x-zip-compressed' ||+ /\.zip$/i.test(file?.originalname || '');++// The watch-history JSON member inside a Takeout ZIP. Google nests it at+// `Takeout/YouTube and YouTube Music/history/watch-history.json`; match the+// filename anywhere so folder-naming/vintage differences don't miss it. The HTML+// variant (`watch-history.html`) is intentionally NOT matched — the JSON export+// is the supported, cheap-to-parse path.+const isWatchHistoryJsonEntry = (entryPath) =>+ /(?:^|\/)watch-history[^/]*\.json$/i.test(String(entryPath || ''));++// Extract and concatenate the watch records from every watch-history JSON member+// of the Takeout ZIP. Non-matching entries are drained and ignored.+async function readRecordsFromZip(filePath) {+ const records = [];+ const reads = [];+ await new Promise((resolve, reject) => {+ let settled = false;+ const src = createReadStream(filePath);+ const parser = parseZip();+ const settle = (fn) => (...args) => {+ if (settled) return;+ settled = true;+ // On failure, tear down the read + parse pipeline so a large upload with an+ // early error (bad JSON member, corrupt ZIP) doesn't keep reading to EOF.+ if (fn === reject) { src.destroy(); parser.destroy?.(); }+ fn(...args);+ };+ src.on('error', settle(reject));+ src+ .pipe(parser)+ .on('entry', (entry) => {+ if (isWatchHistoryJsonEntry(entry.path)) {+ reads.push(+ collectZipEntry(entry)+ .then((buf) => {+ for (const r of parseYoutubeJsonText(buf.toString('utf-8'))) records.push(r);+ })+ .catch(settle(reject)),+ );+ } else {+ entry.autodrain();+ }+ })+ .on('close', () => Promise.all(reads).then(settle(resolve)).catch(settle(reject)))+ .on('error', settle(reject));+ });+ return records;+}++// Read raw watch records from an uploaded file (ZIP export or single JSON array).+export async function readYoutubeRecords(file) {+ if (!file?.path) return [];+ if (isZip(file)) return readRecordsFromZip(file.path);+ const text = await readFile(file.path, 'utf-8');+ return parseYoutubeJsonText(text);+}++// End-to-end import seam: read the file → map → (preview | record). Returns+// counts + a preview summary. `dryRun` parses and summarizes WITHOUT writing so+// the UI can show the user what will be imported before they commit. Because+// `recordEvents` is idempotent, committing (or re-committing) is always safe.+export async function importYoutubeHistory(file, { dryRun = false } = {}) {+ const timezone = await getUserTimezone();+ const records = await readYoutubeRecords(file);+ const candidates = youtubeWatchActivityCandidates(records, timezone);+ const summary = summarizeYoutubeCandidates(candidates);+ if (dryRun) {+ console.log(`📺 YouTube import preview: ${candidates.length} watch(es) from ${records.length} record(s)`);+ return { dryRun: true, parsed: records.length, mapped: candidates.length, recorded: 0, skipped: 0, summary };+ }+ const { recorded, skipped } = await recordEvents(candidates);+ console.log(`📺 YouTube import: ${recorded} new watch(es) recorded, ${skipped} duplicate/invalid (from ${records.length} record(s))`);+ return { dryRun: false, parsed: records.length, mapped: candidates.length, recorded, skipped, summary };+}diff --git a/server/services/youtubeImport.test.js b/server/services/youtubeImport.test.jsnew file mode 100644index 0000000000..face761f09--- /dev/null+++ b/server/services/youtubeImport.test.js@@ -0,0 +1,169 @@+import { describe, it, expect } from 'vitest';+import {+ youtubeVideoIdFromUrl,+ resolveYoutubeInstant,+ stripWatchedPrefix,+ takeoutWatchRecordToCandidate,+ youtubeWatchActivityCandidates,+ summarizeYoutubeCandidates,+ parseYoutubeJsonText,+} from './youtubeImport.js';++const TZ = 'America/New_York';++// A representative Takeout watch-history.json record.+const watchRecord = {+ header: 'YouTube',+ title: 'Watched Rick Astley - Never Gonna Give You Up',+ titleUrl: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',+ subtitles: [{ name: 'Rick Astley', url: 'https://www.youtube.com/channel/UCuAXFkgsw1L7xaCfnd5JJOw' }],+ time: '2024-01-05T18:30:00.000Z',+ products: ['YouTube'],+ activityControls: ['YouTube watch history'],+};++describe('youtubeVideoIdFromUrl', () => {+ it('extracts the id from a watch?v= URL', () => {+ expect(youtubeVideoIdFromUrl('https://www.youtube.com/watch?v=dQw4w9WgXcQ')).toBe('dQw4w9WgXcQ');+ });+ it('extracts from youtu.be, shorts, and embed shapes', () => {+ expect(youtubeVideoIdFromUrl('https://youtu.be/dQw4w9WgXcQ')).toBe('dQw4w9WgXcQ');+ expect(youtubeVideoIdFromUrl('https://www.youtube.com/shorts/abc123XYZ_-')).toBe('abc123XYZ_-');+ expect(youtubeVideoIdFromUrl('https://www.youtube.com/embed/dQw4w9WgXcQ?rel=0')).toBe('dQw4w9WgXcQ');+ });+ it('handles extra query params after v=', () => {+ expect(youtubeVideoIdFromUrl('https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=42s')).toBe('dQw4w9WgXcQ');+ });+ it('returns null for non-video URLs / junk', () => {+ expect(youtubeVideoIdFromUrl('https://www.youtube.com/feed/history')).toBeNull();+ expect(youtubeVideoIdFromUrl('')).toBeNull();+ expect(youtubeVideoIdFromUrl(null)).toBeNull();+ });+});++describe('resolveYoutubeInstant', () => {+ it('passes ISO-8601 timestamps through', () => {+ expect(resolveYoutubeInstant('2024-01-05T18:30:00Z')).toBe('2024-01-05T18:30:00.000Z');+ });+ it('returns null for empty/unparseable values', () => {+ expect(resolveYoutubeInstant('')).toBeNull();+ expect(resolveYoutubeInstant(null)).toBeNull();+ expect(resolveYoutubeInstant('not a date')).toBeNull();+ });+});++describe('stripWatchedPrefix', () => {+ it('strips the "Watched " prefix', () => {+ expect(stripWatchedPrefix('Watched Some Video Title')).toBe('Some Video Title');+ });+ it('strips the "Viewed " prefix', () => {+ expect(stripWatchedPrefix('Viewed an ad')).toBe('an ad');+ });+ it('keeps a title with no known prefix verbatim', () => {+ expect(stripWatchedPrefix('Никогда не сдавайся')).toBe('Никогда не сдавайся');+ });+ it('handles empty input', () => {+ expect(stripWatchedPrefix('')).toBe('');+ expect(stripWatchedPrefix(null)).toBe('');+ });+});++describe('takeoutWatchRecordToCandidate', () => {+ it('maps a watch record to a media.watch candidate with the exact timestamp', () => {+ const c = takeoutWatchRecordToCandidate(watchRecord, TZ);+ expect(c).toMatchObject({+ source: 'youtube',+ kind: 'media.watch',+ happenedAt: '2024-01-05T18:30:00.000Z',+ title: 'Rick Astley - Never Gonna Give You Up',+ url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',+ summary: 'Rick Astley',+ });+ expect(c.metadata).toMatchObject({+ videoId: 'dQw4w9WgXcQ',+ channel: 'Rick Astley',+ channelUrl: 'https://www.youtube.com/channel/UCuAXFkgsw1L7xaCfnd5JJOw',+ product: 'YouTube',+ });+ });++ it('day-buckets the dedupe key in the user timezone', () => {+ // 18:30Z on Jan 5 is 13:30 in America/New_York → still Jan 5 local.+ const c = takeoutWatchRecordToCandidate(watchRecord, TZ);+ expect(c.dedupeKey).toBe('yt:dQw4w9WgXcQ:2024-01-05');+ // The dedupe day follows local time: 02:00Z Jan 6 is 21:00 Jan 5 in NY.+ const late = takeoutWatchRecordToCandidate({ ...watchRecord, time: '2024-01-06T02:00:00Z' }, TZ);+ expect(late.dedupeKey).toBe('yt:dQw4w9WgXcQ:2024-01-05');+ });++ it('drops removed videos (no titleUrl) and missing timestamps', () => {+ expect(takeoutWatchRecordToCandidate({ title: 'Watched a video that has been removed', time: '2024-01-05T18:30:00Z' }, TZ)).toBeNull();+ expect(takeoutWatchRecordToCandidate({ ...watchRecord, time: undefined }, TZ)).toBeNull();+ expect(takeoutWatchRecordToCandidate(null, TZ)).toBeNull();+ });++ it('tolerates a record with no channel subtitle', () => {+ const c = takeoutWatchRecordToCandidate({ ...watchRecord, subtitles: undefined }, TZ);+ expect(c.summary).toBeNull();+ expect(c.metadata.channel).toBeNull();+ });+});++describe('youtubeWatchActivityCandidates', () => {+ it('maps a batch and filters unmappable rows', () => {+ const out = youtubeWatchActivityCandidates([+ watchRecord,+ { title: 'Watched a video that has been removed', time: '2024-01-05T18:30:00Z' },+ { ...watchRecord, titleUrl: 'https://www.youtube.com/watch?v=abcDEF12345', time: '2024-02-01T10:00:00Z' },+ ], TZ);+ expect(out).toHaveLength(2);+ expect(out.every((c) => c.source === 'youtube')).toBe(true);+ });+ it('returns [] for non-arrays', () => {+ expect(youtubeWatchActivityCandidates(null, TZ)).toEqual([]);+ expect(youtubeWatchActivityCandidates({}, TZ)).toEqual([]);+ });+});++describe('summarizeYoutubeCandidates', () => {+ it('computes range, unique videos, and top channels', () => {+ const candidates = youtubeWatchActivityCandidates([+ watchRecord,+ { ...watchRecord, time: '2024-02-10T12:00:00Z' }, // same video, later day+ {+ ...watchRecord,+ titleUrl: 'https://www.youtube.com/watch?v=abcDEF12345',+ subtitles: [{ name: 'Other Channel' }],+ time: '2023-12-01T08:00:00Z',+ },+ ], TZ);+ const s = summarizeYoutubeCandidates(candidates);+ expect(s.watches).toBe(3);+ expect(s.uniqueVideos).toBe(2);+ expect(s.from).toBe('2023-12-01T08:00:00.000Z');+ expect(s.to).toBe('2024-02-10T12:00:00.000Z');+ expect(s.topChannels[0]).toEqual({ name: 'Rick Astley', count: 2 });+ });++ it('handles an empty batch', () => {+ const s = summarizeYoutubeCandidates([]);+ expect(s).toMatchObject({ watches: 0, uniqueVideos: 0, from: null, to: null });+ expect(s.topChannels).toEqual([]);+ });+});++describe('parseYoutubeJsonText', () => {+ it('parses a top-level array', () => {+ expect(parseYoutubeJsonText(JSON.stringify([watchRecord]))).toHaveLength(1);+ });+ it('unwraps an { items: [...] } shape', () => {+ expect(parseYoutubeJsonText(JSON.stringify({ items: [watchRecord] }))).toHaveLength(1);+ });+ it('returns [] for a non-array/object shape', () => {+ expect(parseYoutubeJsonText('42')).toEqual([]);+ expect(parseYoutubeJsonText('{"foo":1}')).toEqual([]);+ });+ it('throws on malformed JSON', () => {+ expect(() => parseYoutubeJsonText('{not json')).toThrow();+ });+});diff --git a/server/services/youtubeScheduler.js b/server/services/youtubeScheduler.jsnew file mode 100644index 0000000000..a7f3be1fde--- /dev/null+++ b/server/services/youtubeScheduler.js@@ -0,0 +1,56 @@+/**+ * YouTube Watch-History Sync Scheduler (#2153)+ *+ * Registers an interval job that periodically runs the CDP scrape of the+ * signed-in YouTube history page (see youtubeSync.js). Mirrors spotifyScheduler /+ * imessageScheduler.+ *+ * OFF by default: only registered when the user has opted in via Settings →+ * YouTube (`settings.youtube.enabled`) AND is logged into YouTube in the managed+ * browser. The history page is DAY-bucketed, so the ~8h default cadence is+ * deliberately conservative (a polite scraper — polling more buys nothing). The+ * interval is locked at registration (changing it needs a restart), but the+ * `enabled` toggle is re-read every tick so disabling stops runs without a restart.+ *+ * No LLM calls happen on this path — extraction is deterministic DOM reading — so+ * the no-cold-bootstrap AI policy does not gate it; the opt-in is purely about+ * user intent + a signed-in browser profile.+ */++import { schedule } from './eventScheduler.js';+import { getYoutubeConfig, runSync } from './youtubeSync.js';++const EVENT_ID = 'youtube-sync';++/**+ * Start the YouTube sync scheduler. No-ops when disabled in settings.+ */+export async function startYoutubeScheduler() {+ const { enabled, intervalMinutes } = await getYoutubeConfig();++ if (!enabled) {+ console.log('📺 YouTube 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 getYoutubeConfig();+ if (!current.enabled) {+ console.log('📺 YouTube sync scheduler: disabled since registration — skipping run');+ return;+ }+ await runSync();+ },+ metadata: { source: 'youtubeScheduler' },+ });++ console.log(`📺 YouTube sync scheduler: registered every ${intervalMinutes}min`);+}diff --git a/server/services/youtubeSync.js b/server/services/youtubeSync.jsnew file mode 100644index 0000000000..0703fdd978--- /dev/null+++ b/server/services/youtubeSync.js@@ -0,0 +1,386 @@+/**+ * YouTube watch-history ingestion (#2153) — CDP scrape of the signed-in+ * `youtube.com/feed/history` page via the managed portos-browser profile, feeding+ * the machine-local human-activity timeline (#2150) with `media.watch` events.+ *+ * Why a scrape: YouTube retired the watch-history API years ago. The reliable+ * historical path is the Takeout backfill (youtubeImport.js); this scrape keeps+ * the timeline fresh between backfills by reading the same page a human sees.+ *+ * Design constraints (docs/plans/2026-07-04-human-activity-tracking.md + #2153):+ *+ * - **Conservative cadence.** The history page only shows DAY-bucketed entries+ * (no per-watch clock time), so polling more than a few times a day buys+ * nothing. The scheduler (youtubeScheduler.js) defaults to every 8h. Be a polite+ * scraper.+ * - **Day-bucket dedupe, shared with Takeout.** `dedupeKey = yt:<videoId>:<localDay>`+ * so a scrape and a Takeout import of the same watch reconcile via+ * `recordEvents`'s `ON CONFLICT DO NOTHING`. `happenedAt` is the day's local+ * midnight (the finest the page offers); Takeout supplies the exact instant.+ * - **Machine-local.** The scrape runs against the local browser profile; the+ * cursor/last-status lives in `data/youtube/` (per-machine, unsynced). Events+ * land in the machine-local `human_activity_events` table.+ * - **Fragility → surfaced status, never a crash.** Selector failures / signed-out+ * redirects degrade to a `lastResult` status the settings UI renders, exactly+ * like message-account `lastSyncStatus`. All selectors live in one place+ * (`YOUTUBE_SELECTORS`) for easy repair.+ * - **LLM-free.** Extraction is deterministic DOM reading; no AI-provider calls.+ *+ * The pure mappers (video-id parse, day-label resolution, candidate mapping) are+ * exported and unit-tested against saved DOM-shaped fixtures — no browser or DB.+ */+import { dataPath, ensureDir, atomicWrite, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';+import { getUserTimezone, todayInTimezone } from '../lib/timezone.js';+import { getSettings } from './settings.js';+import { findOrOpenPage, listCdpPages, isAuthPage, evaluateOnPage } from './browserService.js';+import { localDayRangeUtc, shortSummary } from './humanActivity.js';+import { youtubeVideoIdFromUrl } from './youtubeImport.js';++// ---------------------------------------------------------------------------+// Constants+// ---------------------------------------------------------------------------++const HISTORY_URL = 'https://www.youtube.com/feed/history';++const STATE_FILE = 'sync-state.json';++// OFF by default — the user logs into YouTube in the managed browser and opts in+// from Settings. 480 min = every 8h ≈ 3 scrapes/day (the page is day-bucketed).+const DEFAULT_CONFIG = { enabled: false, intervalMinutes: 480 };++// Post-navigation settle + bounded lazy-load scroll — the history feed hydrates+// client-side and appends more rows as you scroll.+const NAV_SETTLE_MS = 3500;+const MAX_ENTRIES = 200;++// Every CSS selector the scrape depends on, in ONE place so a YouTube DOM change+// is a single-file repair. Consumed by the in-page extraction script below.+export const YOUTUBE_SELECTORS = {+ section: 'ytd-item-section-renderer',+ sectionHeader: '#header #title, ytd-item-section-header-renderer #title, #title.ytd-item-section-header-renderer',+ videoRenderer: 'ytd-video-renderer, ytd-grid-video-renderer',+ videoTitle: 'a#video-title, #video-title-link, a#video-title-link',+ channelLink: 'ytd-channel-name a, #channel-name a, #text-container.ytd-channel-name a',+ signedOut: 'a[href*="accounts.google.com/ServiceLogin"], a[href*="/ServiceLogin"], ytd-button-renderer a[href*="ServiceLogin"]',+ signedIn: '#avatar-btn, button#avatar-btn, #masthead #avatar, ytd-topbar-menu-button-renderer #avatar',+};++const MONTHS = {+ jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6,+ jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12,+};++// ---------------------------------------------------------------------------+// Pure helpers (exported for unit tests — no network, no filesystem, no DB).+// ---------------------------------------------------------------------------++// Shift a YYYY-MM-DD string by whole days using UTC calendar math (independent of+// any timezone — we're only manipulating the date label, not an instant).+function shiftDayStr(dayStr, days) {+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(dayStr || ''));+ if (!m) return null;+ const [, y, mo, d] = m.map(Number);+ const t = new Date(Date.UTC(y, mo - 1, d + days));+ return `${t.getUTCFullYear()}-${String(t.getUTCMonth() + 1).padStart(2, '0')}-${String(t.getUTCDate()).padStart(2, '0')}`;+}++/**+ * Resolve a YouTube history section-header label to a YYYY-MM-DD local-day+ * string, or null if it can't be parsed. Handles the relative labels YouTube+ * shows ("Today", "Yesterday") against the user's `today` (in their timezone),+ * plus absolute dates ("Jan 5, 2024", "Nov 12"). A yearless date is assigned the+ * current year, rolling back a year if that would land in the future.+ */+export function resolveHistoryDay(label, today) {+ const raw = String(label || '').trim();+ if (!raw || !/^\d{4}-\d{2}-\d{2}$/.test(String(today || ''))) return null;+ const lower = raw.toLowerCase();+ if (lower === 'today') return today;+ if (lower === 'yesterday') return shiftDayStr(today, -1);++ const m = /([A-Za-z]{3,})\.?\s+(\d{1,2})(?:,?\s+(\d{4}))?/.exec(raw);+ if (!m) return null;+ const month = MONTHS[m[1].slice(0, 3).toLowerCase()];+ const day = Number(m[2]);+ if (!month || !(day >= 1 && day <= 31)) return null;+ let year = m[3] ? Number(m[3]) : Number(today.slice(0, 4));+ let dayStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;+ // Yearless label that resolves after today → it's from last year.+ if (!m[3] && dayStr > today) {+ year -= 1;+ dayStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;+ }+ return dayStr;+}++/**+ * Map ONE scraped history entry to a `media.watch` candidate, or null when it+ * lacks a resolvable video id or day bucket. `entry` = { title, url, channel,+ * channelUrl, dayLabel }. `today` (the user's local today, YYYY-MM-DD) anchors+ * relative day labels; `timezone` anchors the local-midnight `happenedAt`.+ *+ * The history page carries no clock time, so `happenedAt` is the local midnight+ * of the bucketed day and the dedupe key is day-scoped — identical to what a+ * Takeout import produces for the same watch, so the two paths reconcile.+ */+export function youtubeWatchCandidate(entry, { today, timezone } = {}) {+ const videoId = youtubeVideoIdFromUrl(entry?.url);+ if (!videoId) return null;+ const dayStr = resolveHistoryDay(entry?.dayLabel, today);+ if (!dayStr) return null;+ const range = localDayRangeUtc(dayStr, timezone);+ if (!range) return null;++ const title = String(entry?.title || '').trim() || '(untitled video)';+ const channel = entry?.channel ? String(entry.channel).trim() : null;+ const channelUrl = entry?.channelUrl ? String(entry.channelUrl).trim() : null;++ return {+ source: 'youtube',+ kind: 'media.watch',+ happenedAt: range.start.toISOString(),+ title,+ summary: channel ? shortSummary(channel) : null,+ url: `https://www.youtube.com/watch?v=${videoId}`,+ dedupeKey: `yt:${videoId}:${dayStr}`,+ metadata: {+ videoId,+ channel,+ channelUrl,+ dayBucket: dayStr,+ scraped: true,+ },+ };+}++export function youtubeWatchCandidates(entries = [], ctx = {}) {+ return (entries || []).map((e) => youtubeWatchCandidate(e, ctx)).filter(Boolean);+}++// ---------------------------------------------------------------------------+// In-page extraction script (runs in the browser via CDP Runtime.evaluate).+// Built from YOUTUBE_SELECTORS so selector repair stays single-source.+// ---------------------------------------------------------------------------++function buildExtractionScript() {+ const S = YOUTUBE_SELECTORS;+ return `+ (async function () {+ const S = ${JSON.stringify(S)};+ const MAX = ${MAX_ENTRIES};+ const abs = (href) => { try { return new URL(href, location.origin).href; } catch { return href || null; } };++ // Signed-out gate: the feed shows a ServiceLogin CTA and no avatar.+ const signedOut = !!document.querySelector(S.signedOut) && !document.querySelector(S.signedIn);+ if (signedOut) return { signedOut: true, entries: [] };++ const collect = () => {+ const out = [];+ for (const section of document.querySelectorAll(S.section)) {+ const header = section.querySelector(S.sectionHeader);+ const dayLabel = (header?.textContent || '').trim();+ for (const v of section.querySelectorAll(S.videoRenderer)) {+ const titleEl = v.querySelector(S.videoTitle);+ if (!titleEl) continue;+ const url = abs(titleEl.getAttribute('href'));+ const title = (titleEl.getAttribute('title') || titleEl.textContent || '').trim();+ const chEl = v.querySelector(S.channelLink);+ out.push({+ title,+ url,+ channel: (chEl?.textContent || '').trim() || null,+ channelUrl: chEl ? abs(chEl.getAttribute('href')) : null,+ dayLabel,+ });+ }+ }+ return out;+ };++ // Bounded lazy-load scroll — the feed appends rows as you scroll.+ let entries = collect();+ let stagnant = 0;+ for (let i = 0; i < 12 && entries.length < MAX && stagnant < 3; i++) {+ window.scrollTo(0, document.documentElement.scrollHeight);+ await new Promise((r) => setTimeout(r, 700));+ const next = collect();+ if (next.length <= entries.length) stagnant++; else stagnant = 0;+ entries = next;+ }+ window.scrollTo(0, 0);+ return { signedOut: false, entries: entries.slice(0, MAX) };+ })()+ `;+}++// ---------------------------------------------------------------------------+// Config + machine-local sync state+// ---------------------------------------------------------------------------++export async function getYoutubeConfig() {+ const settings = await getSettings().catch(() => ({}));+ const c = settings?.youtube || {};+ 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('youtube', STATE_FILE);+}++// Machine-local last-run status. NOT federated — it references the local browser+// profile and machine-local activity rows.+export async function readSyncState() {+ const raw = await tryReadFile(stateFilePath());+ const parsed = raw ? safeJSONParse(raw, null, { allowArray: false }) : null;+ return {+ lastRunAt: parsed?.lastRunAt || null,+ lastResult: parsed?.lastResult || null,+ };+}++async function writeSyncState(state) {+ await ensureDir(dataPath('youtube'));+ await atomicWrite(stateFilePath(), JSON.stringify(state, null, 2));+}++// ---------------------------------------------------------------------------+// Browser helpers (side-effecting — CDP). Never throw to the caller: a scrape+// failure returns a status report the UI renders (mirrors message lastSyncStatus).+// ---------------------------------------------------------------------------++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++// Ensure the managed browser has the history page loaded and return the CDP page+// object, or a { status } report when it can't. If a YouTube tab is open on a+// different path, navigate it to the history feed in place (CDP re-attaches to+// the same target after navigation) rather than piling up tabs.+async function ensureHistoryPage() {+ let page = await findOrOpenPage(HISTORY_URL).catch(() => null);+ if (!page) return { page: null, status: 'no-browser' };+ if (isAuthPage(page)) return { page: null, status: 'auth-required' };++ if (!/\/feed\/history/.test(page.url || '')) {+ await evaluateOnPage(page, `location.assign(${JSON.stringify(HISTORY_URL)}); true`);+ await sleep(NAV_SETTLE_MS);+ const refreshed = (await listCdpPages().catch(() => [])).find((p) => p.id === page.id);+ if (refreshed) page = refreshed;+ } else {+ await sleep(NAV_SETTLE_MS);+ }+ if (isAuthPage(page)) return { page: null, status: 'auth-required' };+ return { page, status: 'ok' };+}++// ---------------------------------------------------------------------------+// Setup check (settings UI) — is the managed browser up and signed into YouTube?+// ---------------------------------------------------------------------------++const SIGNED_OUT_REMEDIATION = 'Open the managed browser (Browser page) and log into YouTube, then re-run the setup check.';+const NO_BROWSER_REMEDIATION = 'Start the managed browser (Browser page → Launch) so PortOS can read your YouTube history, then re-run the setup check.';++export async function checkSetup() {+ const page = await findOrOpenPage(HISTORY_URL).catch(() => null);+ if (!page) {+ return { ok: false, browserRunning: false, signedIn: false, error: 'Managed browser is not running', remediation: NO_BROWSER_REMEDIATION };+ }+ if (isAuthPage(page)) {+ return { ok: false, browserRunning: true, signedIn: false, error: 'Signed out of YouTube', remediation: SIGNED_OUT_REMEDIATION };+ }+ const S = YOUTUBE_SELECTORS;+ const probe = await evaluateOnPage(page, `+ (function () {+ const S = ${JSON.stringify(S)};+ return {+ signedIn: !!document.querySelector(S.signedIn),+ signedOut: !!document.querySelector(S.signedOut),+ url: location.href,+ };+ })()+ `);+ if (!probe) {+ return { ok: false, browserRunning: true, signedIn: false, error: 'Could not read the YouTube page', remediation: SIGNED_OUT_REMEDIATION };+ }+ const signedIn = Boolean(probe.signedIn) && !probe.signedOut;+ return signedIn+ ? { ok: true, browserRunning: true, signedIn: true }+ : { ok: false, browserRunning: true, signedIn: false, error: 'Signed out of YouTube', remediation: SIGNED_OUT_REMEDIATION };+}++// ---------------------------------------------------------------------------+// Sync (side-effecting — CDP + DB). Runs outside the request lifecycle+// (scheduler / explicit endpoint), so failures return a status report, not throw.+// ---------------------------------------------------------------------------++// Re-entrancy guard: a manual "Sync now" overlapping a scheduler tick would+// scrape the same page twice (deduped, but wasteful). 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 started = Date.now();+ const { page, status } = await ensureHistoryPage();+ if (!page) {+ const result = status === 'no-browser'+ ? { ok: false, status, error: 'Managed browser is not running', remediation: NO_BROWSER_REMEDIATION }+ : { ok: false, status: 'auth-required', needsAuth: true, error: 'Signed out of YouTube', remediation: SIGNED_OUT_REMEDIATION };+ await writeSyncState({ lastRunAt: new Date().toISOString(), lastResult: result });+ console.log(`📺 YouTube sync: ${result.error}`);+ return result;+ }++ const extracted = await evaluateOnPage(page, buildExtractionScript()).catch(() => null);+ if (!extracted || !Array.isArray(extracted.entries)) {+ const result = { ok: false, status: 'extraction-failed', error: 'Could not extract history entries — the page layout may have changed (selectors need repair)' };+ await writeSyncState({ lastRunAt: new Date().toISOString(), lastResult: result });+ console.error(`📺 YouTube sync: extraction failed — selectors may need repair`);+ return result;+ }+ if (extracted.signedOut) {+ const result = { ok: false, status: 'auth-required', needsAuth: true, error: 'Signed out of YouTube', remediation: SIGNED_OUT_REMEDIATION };+ await writeSyncState({ lastRunAt: new Date().toISOString(), lastResult: result });+ console.log(`📺 YouTube sync: signed out of YouTube`);+ return result;+ }++ const timezone = await getUserTimezone();+ const today = todayInTimezone(timezone);+ const candidates = youtubeWatchCandidates(extracted.entries, { today, timezone });++ let persistFailed = false;+ const { recordEvents } = await import('./humanActivity.js');+ const recordResult = await recordEvents(candidates).catch((err) => {+ console.error(`❌ YouTube activity record failed: ${err?.message || err}`);+ persistFailed = true;+ return { recorded: 0, skipped: candidates.length };+ });++ const result = {+ ok: !persistFailed,+ status: persistFailed ? 'persist-failed' : 'ok',+ ...(persistFailed ? { error: 'Persistence failed — re-run to retry (dedupe makes it safe)' } : {}),+ scanned: extracted.entries.length,+ mapped: candidates.length,+ recorded: recordResult.recorded,+ skipped: recordResult.skipped,+ durationMs: Date.now() - started,+ };+ await writeSyncState({ lastRunAt: new Date().toISOString(), lastResult: result });+ console.log(`📺 YouTube sync: scanned ${result.scanned}, recorded ${result.recorded} watch(es)${persistFailed ? ' — PERSIST FAILED' : ''} in ${result.durationMs}ms`);+ return result;+}++// Status for the settings UI: config + last-run state (no scrape).+export async function getStatus() {+ const [config, state] = await Promise.all([getYoutubeConfig(), readSyncState()]);+ return { config, state };+}diff --git a/server/services/youtubeSync.test.js b/server/services/youtubeSync.test.jsnew file mode 100644index 0000000000..d2bfa6327d--- /dev/null+++ b/server/services/youtubeSync.test.js@@ -0,0 +1,106 @@+import { describe, it, expect } from 'vitest';+import {+ resolveHistoryDay,+ youtubeWatchCandidate,+ youtubeWatchCandidates,+ YOUTUBE_SELECTORS,+} from './youtubeSync.js';++const TZ = 'America/New_York';+const TODAY = '2024-01-15';++describe('resolveHistoryDay', () => {+ it('resolves "Today" / "Yesterday" against the user today', () => {+ expect(resolveHistoryDay('Today', TODAY)).toBe('2024-01-15');+ expect(resolveHistoryDay('Yesterday', TODAY)).toBe('2024-01-14');+ });+ it('is case-insensitive for relative labels', () => {+ expect(resolveHistoryDay('today', TODAY)).toBe('2024-01-15');+ expect(resolveHistoryDay('YESTERDAY', TODAY)).toBe('2024-01-14');+ });+ it('parses an absolute date with a year', () => {+ expect(resolveHistoryDay('Jan 5, 2023', TODAY)).toBe('2023-01-05');+ expect(resolveHistoryDay('November 12, 2022', TODAY)).toBe('2022-11-12');+ });+ it('assigns the current year to a yearless date in the past', () => {+ expect(resolveHistoryDay('Jan 3', TODAY)).toBe('2024-01-03');+ });+ it('rolls a yearless future date back a year', () => {+ // "Dec 25" with today = Jan 15 2024 → the watch was last December.+ expect(resolveHistoryDay('Dec 25', TODAY)).toBe('2023-12-25');+ });+ it('handles month boundaries in yesterday math', () => {+ expect(resolveHistoryDay('Yesterday', '2024-03-01')).toBe('2024-02-29'); // leap year+ expect(resolveHistoryDay('Yesterday', '2024-01-01')).toBe('2023-12-31');+ });+ it('returns null for junk labels or a bad today', () => {+ expect(resolveHistoryDay('', TODAY)).toBeNull();+ expect(resolveHistoryDay('Sometime', TODAY)).toBeNull();+ expect(resolveHistoryDay('Today', 'not-a-date')).toBeNull();+ });+});++describe('youtubeWatchCandidate', () => {+ const entry = {+ title: 'Never Gonna Give You Up',+ url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',+ channel: 'Rick Astley',+ channelUrl: 'https://www.youtube.com/channel/UCuAXFkgsw1L7xaCfnd5JJOw',+ dayLabel: 'Today',+ };++ it('maps a scraped entry to a media.watch candidate at local midnight', () => {+ const c = youtubeWatchCandidate(entry, { today: TODAY, timezone: TZ });+ expect(c).toMatchObject({+ source: 'youtube',+ kind: 'media.watch',+ title: 'Never Gonna Give You Up',+ summary: 'Rick Astley',+ url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',+ dedupeKey: 'yt:dQw4w9WgXcQ:2024-01-15',+ });+ // Jan 15 2024 local midnight in America/New_York (EST, UTC-5) = 05:00Z.+ expect(c.happenedAt).toBe('2024-01-15T05:00:00.000Z');+ expect(c.metadata).toMatchObject({ videoId: 'dQw4w9WgXcQ', channel: 'Rick Astley', scraped: true, dayBucket: '2024-01-15' });+ });++ it('shares the dedupe-key scheme with the Takeout importer (yt:<id>:<day>)', () => {+ const c = youtubeWatchCandidate({ ...entry, dayLabel: 'Jan 5, 2023' }, { today: TODAY, timezone: TZ });+ expect(c.dedupeKey).toBe('yt:dQw4w9WgXcQ:2023-01-05');+ });++ it('drops entries with no video id or an unresolvable day', () => {+ expect(youtubeWatchCandidate({ ...entry, url: 'https://www.youtube.com/feed/history' }, { today: TODAY, timezone: TZ })).toBeNull();+ expect(youtubeWatchCandidate({ ...entry, dayLabel: 'whenever' }, { today: TODAY, timezone: TZ })).toBeNull();+ });++ it('tolerates a missing channel', () => {+ const c = youtubeWatchCandidate({ ...entry, channel: null, channelUrl: null }, { today: TODAY, timezone: TZ });+ expect(c.summary).toBeNull();+ expect(c.metadata.channel).toBeNull();+ });+});++describe('youtubeWatchCandidates', () => {+ it('maps a batch and filters unmappable entries', () => {+ const out = youtubeWatchCandidates([+ { title: 'A', url: 'https://youtu.be/aaaaaaaaaaa', dayLabel: 'Today' },+ { title: 'gone', url: 'https://www.youtube.com/feed/history', dayLabel: 'Today' },+ { title: 'B', url: 'https://www.youtube.com/watch?v=bbbbbbbbbbb', dayLabel: 'Yesterday' },+ ], { today: TODAY, timezone: TZ });+ expect(out).toHaveLength(2);+ expect(out.every((c) => c.kind === 'media.watch')).toBe(true);+ });+ it('returns [] for a non-array', () => {+ expect(youtubeWatchCandidates(null, { today: TODAY, timezone: TZ })).toEqual([]);+ });+});++describe('YOUTUBE_SELECTORS', () => {+ it('exports the selector map in one place for easy repair', () => {+ expect(YOUTUBE_SELECTORS).toHaveProperty('videoRenderer');+ expect(YOUTUBE_SELECTORS).toHaveProperty('videoTitle');+ expect(YOUTUBE_SELECTORS).toHaveProperty('signedOut');+ expect(YOUTUBE_SELECTORS).toHaveProperty('signedIn');+ });+});