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-1946]): Dev Tools video downloader (YouTube/x.com URL → download + manage)
[._.]/ Adam Eivy105017558fe0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 8af667c9a4..fe2cda54df 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -22,6 +22,10 @@- **[issue-1867] Auto-cast first-pass scene reference frames.** Extends the opt-in first-pass gen step from #1818 (catalog portraits) one stage later: once a treatment exists (via auto-compose, or a later `/:id/start`), the director seeds a first reference frame per scene the same way it already seeds cast portraits — one image-gen job per scene, rendered at the project's locked-in aspect ratio, enqueued onto the durable media-job queue and filed onto `scene.sourceImageFile` (the same field a manual reference image or i2v-continuation source already populates) by a new `creativeDirectorSceneImageHook`, so the render lands even with no client mounted. The user's opt-in is persisted on the project independent of the compose toggle (the OverviewTab checkboxes are independent, and a project can be started later without re-composing in the same request). Idempotent (a scene that already has a reference frame is left alone), skips `useContinuationFromPrior` scenes (their actual source is the prior scene's extracted last frame at render time, so a seeded frame there would just be discarded), and only fires for queue-backed image-gen modes (local/Codex), mirroring the portrait path's graceful skip for external mode. The two remaining downstream modalities #1818 named — first-pass scene clips (image-to-video) and a first-pass music bed — are genuinely separate pipelines and are tracked as their own follow-up issues (#1927, #1928) rather than folded into this slice. (`server/services/creativeDirector/firstPassGen.js`, `server/services/creativeDirectorSceneImageHook.js`)+## Dev Tools++- **[issue-1946] Download full videos from a YouTube or x.com URL.** A new **Dev Tools → Video Downloader** page lets you paste a YouTube (video/shorts/youtu.be) or x.com/Twitter status URL and download the *full video* (not just the audio, which is #1945's job) via `yt-dlp` — the same host dependency the music-video track import already uses. The clip lands in your video storage as a distinguishable `downloaded-<id>.mp4`, gets an auto-generated thumbnail, and — because it's written as a `source: 'download'` entry into the shared video-history store — also shows up in your media gallery alongside AI-generated renders (no new "library" concept; the existing media asset index picks it up through the same completed-video path it already uses, and prunes it on delete). Download progress streams live (download % → merging → finalizing) with a Cancel button, and the page lists everything you've downloaded (thumbnail, title, source link, age) with delete. x.com/Twitter pulls are best-effort — login-walled or rate-limited posts surface a clear error rather than a generic failure. Long/huge downloads are bounded (≤1h, ≤2GB) so a livestream or archive URL can't eat disk unbounded. `POST /api/devtools/video-download` (`server/services/videoDownload.js`, `server/routes/videoDownload.js`) mirrors #1945's async-job/SSE pattern. (Closes #1946)+## Architecture- **[issue-1878] CoS runner now wires the process-level `unhandledRejection`/`uncaughtException` net (defense-in-depth).** The main server (`server/index.js`) already registered a process-level net via the shared `setupProcessErrorHandlers()` helper (`server/lib/errorHandler.js`) — but the standalone CoS runner (`server/cos-runner/index.js`), a separate long-lived PM2 process that spawns and supervises child agents, had none, so a stray async handler that rejected/threw outside the request lifecycle would crash it with Node's default unhandled output. The runner now calls the same shared helper, giving it the identical, already-tested convention: log via the emoji-prefixed `console.error` style, log-and-stay-alive on an unhandled rejection, and log-then-exit-cleanly on an uncaught exception (after flushing, so PM2 restarts a process that would otherwise be left in an undefined state and reaps any orphaned agents on boot). Reusing the shared helper (rather than rolling inline handlers) keeps the two long-lived processes consistent and routes arbitrary non-Error throw values through `normalizeError`, so the net can't itself throw on a `reason` with no `.stack`. This is the backstop for the per-handler try/catch wrapping done in #1825 — not a replacement for it. While wiring this up, hardened the shared helper's `uncaughtException` branch, which dereferenced `error.stack` on the raw thrown value — a non-Error throw (`throw null`) made the net itself throw, masking the original exception and skipping the clean exit/flush; it now guards `error instanceof Error` (mirroring the existing `unhandledRejection` branch). A regression test (`server/process-safety-net.test.js`) asserts the shared helper registers both handlers, that both entry processes wire it up, and that the `uncaughtException` listener tolerates a non-Error throw value. (Closes #1878)diff --git a/client/src/App.jsx b/client/src/App.jsxindex 4994304c7b..8c812363ce 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -34,6 +34,7 @@ const Goals = lazyWithReload(() => import('./pages/Goals'));const OpenClawPage = lazyWithReload(() => import('./pages/OpenClaw'));const Submodules = lazyWithReload(() => import('./pages/Submodules'));const ImageClean = lazyWithReload(() => import('./pages/ImageClean'));+const VideoDownloaderPage = lazyWithReload(() => import('./pages/VideoDownloaderPage'));const ChiefOfStaff = lazyWithReload(() => import('./pages/ChiefOfStaff'));const Ask = lazyWithReload(() => import('./pages/Ask'));const MediaGen = lazyWithReload(() => import('./pages/MediaGen'));@@ -206,6 +207,7 @@ export default function App() {<Route path="devtools/runner" element={<RunnerPage />} /><Route path="devtools/submodules" element={<Submodules />} /><Route path="devtools/usage" element={<UsagePage />} />+ <Route path="devtools/video-download" element={<VideoDownloaderPage />} /><Route path="devtools/processes" element={<ProcessesPage />} /><Route path="devtools/agents" element={<AgentsPage />} /><Route path="ai" element={<AIProviders />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex cae3bc99af..0e6e814e99 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -26,6 +26,7 @@ import {CheckCircle,Dna,Download,+ Film,MessageSquare,Palette,PenLine,@@ -251,6 +252,7 @@ const navItems = [{ to: '/system-health', label: 'System Health', icon: Activity },{ to: '/uploads', label: 'Uploads', icon: Upload },{ to: '/devtools/usage', label: 'Usage', icon: BarChart3 },+ { to: '/devtools/video-download', label: 'Video Downloader', icon: Film },{ to: '/workspace-contexts', label: 'Workspaces', icon: Layers },],},diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 67b9ca69ad..dd78521e62 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -147,3 +147,4 @@ grep -i "what you want to do" client/src/hooks/README.md| `useVoiceUiSync` | Keeps voice server's UI index in sync with current page. | Wire once at root for voice agent support. || `useMoltworldWs` | Moltworld WebSocket feed. | Moltworld surfaces only. || `useYoutubeTrackImport` | One YouTube-audio-import job slot (#1945): start/cancel + SSE progress + terminal-frame handling via `POST /api/tracks/import/youtube`. Returns `{ active, percent, start(url, context), cancel }`; `onComplete(track, context)` fires with the finished Track. Call once per UI surface that can independently kick off an import — a shared slot would let one surface's kickoff orphan another's in-flight job. | Any picker that lets a user paste a YouTube URL to create a Track (Music Video's create form and track-change row). |+| `useVideoDownload` | One full-video-download job slot (#1946): start/cancel + SSE progress + terminal-frame handling via `POST /api/devtools/video-download`. Returns `{ active, percent, stage, start(url), cancel }`; `onComplete(video)` fires with the finished video-history entry. | The Dev Tools Video Downloader page. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 7461fccd0d..d005538d94 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -44,6 +44,7 @@ export { default as useRowDraft } from './useRowDraft.js';export { default as useTheme } from './useTheme.js';export { default as useUniverse } from './useUniverse.js';export { default as useUniverseAction } from './useUniverseAction.js';+export { default as useVideoDownload } from './useVideoDownload.js';export { default as useYoutubeTrackImport } from './useYoutubeTrackImport.js';// === Mixed (both default and named) — surface both ===diff --git a/client/src/hooks/useVideoDownload.js b/client/src/hooks/useVideoDownload.jsnew file mode 100644index 0000000000..160b8550df--- /dev/null+++ b/client/src/hooks/useVideoDownload.js@@ -0,0 +1,65 @@+import { useEffect, useState } from 'react';+import toast from '../components/ui/Toast';+import { startVideoDownload, cancelVideoDownload, videoDownloadEventsUrl } from '../services/apiVideoDownload.js';+import { useSseProgress, isTerminalSseFrame } from './useSseProgress.js';++/**+ * One full-video-download job slot (#1946) — start/cancel + SSE progress ++ * terminal-frame handling via `POST /api/devtools/video-download`. Mirrors+ * useYoutubeTrackImport (#1945): kick off returns a jobId, progress streams over+ * SSE, and terminal frames drive completion. `onComplete(video)` fires once the+ * download lands a video-history entry so the caller can prepend it to its list+ * without a full refetch.+ */+export default function useVideoDownload({ onComplete } = {}) {+ const [job, setJob] = useState(null); // { jobId }+ // `pending` covers the gap between clicking Download and the kickoff request+ // resolving, when `job` is still null — without it a fast double-click could+ // fire a second request whose response silently orphans the first job.+ const [pending, setPending] = useState(false);+ const sse = useSseProgress(job ? videoDownloadEventsUrl(job.jobId) : null);+ const percent = Math.round(sse.latest?.percent ?? 0);+ const stage = sse.latest?.stage || null;++ useEffect(() => {+ const frame = sse.latest;+ if (!job || !frame) return;+ if (frame.type === 'complete') {+ onComplete?.(frame.video);+ toast.success(`Downloaded "${frame.video?.title || 'video'}"`);+ setJob(null);+ } else if (frame.type === 'error') {+ toast.error(frame.error || 'Video download failed');+ setJob(null);+ } else if (frame.type === 'canceled' || frame.type === 'cancelled') {+ toast.info('Video download cancelled');+ setJob(null);+ }+ }, [sse.latest]);++ // Stream closed without a terminal frame (server restart mid-download, or the+ // job was pruned before/after attach) — recover so the progress UI can't hang.+ useEffect(() => {+ if (job && sse.closed && !isTerminalSseFrame(sse.latest)) {+ setJob(null);+ toast.info('Lost connection to the download — check the list below');+ }+ }, [sse.closed]);++ const start = (url) => {+ const trimmed = (url || '').trim();+ if (!trimmed || job || pending) return;+ setPending(true);+ startVideoDownload(trimmed, { silent: true })+ .then(({ jobId }) => setJob({ jobId }))+ .catch((err) => toast.error(err?.message || 'Failed to start download'))+ .finally(() => setPending(false));+ };++ const cancel = () => {+ if (!job) return;+ cancelVideoDownload(job.jobId, { silent: true }).catch(() => {});+ };++ return { active: pending || !!job, percent, stage, start, cancel };+}diff --git a/client/src/pages/VideoDownloaderPage.jsx b/client/src/pages/VideoDownloaderPage.jsxnew file mode 100644index 0000000000..cf64f4e5b1--- /dev/null+++ b/client/src/pages/VideoDownloaderPage.jsx@@ -0,0 +1,187 @@+import { useEffect, useState } from 'react';+import { Download, Film, Loader2, Trash2, ExternalLink, Video } from 'lucide-react';+import toast from '../components/ui/Toast';+import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';+import { useVideoDownload, useConfirmDelete } from '../hooks';+import { listVideoDownloads, deleteVideoDownload } from '../services/apiVideoDownload.js';+import { timeAgo, formatTimecode } from '../utils/formatters';++// Dev Tools video downloader (#1946) — paste a YouTube or x.com/Twitter URL,+// download the full video via yt-dlp into data/videos (where it also shows up in+// the media gallery), and browse/delete what's been downloaded.+export default function VideoDownloaderPage() {+ const [url, setUrl] = useState('');+ const [downloads, setDownloads] = useState([]);+ const [loading, setLoading] = useState(true);+ const [deletingId, setDeletingId] = useState(null);+ const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();++ useEffect(() => {+ listVideoDownloads()+ .then((list) => setDownloads(Array.isArray(list) ? list : []))+ .catch(() => setDownloads([]))+ .finally(() => setLoading(false));+ }, []);++ // Prepend the finished clip to the list rather than refetching (reactive UI).+ const { active, percent, stage, start, cancel } = useVideoDownload({+ onComplete: (video) => {+ if (video) setDownloads((prev) => [video, ...prev.filter((d) => d.id !== video.id)]);+ setUrl('');+ },+ });++ const onSubmit = (e) => {+ e.preventDefault();+ const trimmed = url.trim();+ if (!trimmed || active) return;+ start(trimmed);+ };++ const onDelete = (id) => confirmDelete(async () => {+ setDeletingId(id);+ await deleteVideoDownload(id, { silent: true })+ .then(() => setDownloads((prev) => prev.filter((d) => d.id !== id)))+ .catch((err) => toast.error(err?.message || 'Failed to delete video'))+ .finally(() => setDeletingId(null));+ });++ return (+ <div className="max-w-4xl mx-auto space-y-6">+ <header>+ <h1 className="text-xl font-semibold flex items-center gap-2">+ <Film size={20} className="text-port-accent" /> Video Downloader+ </h1>+ <p className="text-sm text-gray-400 mt-1">+ Download a full video from a YouTube or x.com/Twitter URL. Downloaded clips also appear in your media gallery.+ </p>+ </header>++ <form onSubmit={onSubmit} className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">+ <label htmlFor="video-download-url" className="block text-sm text-gray-300">+ Video URL+ </label>+ <div className="flex flex-col sm:flex-row gap-2">+ <input+ id="video-download-url"+ type="url"+ value={url}+ onChange={(e) => setUrl(e.target.value)}+ placeholder="https://www.youtube.com/watch?v=… or https://x.com/…/status/…"+ disabled={active}+ className="flex-1 bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-port-accent disabled:opacity-50"+ />+ <button+ type="submit"+ disabled={active || !url.trim()}+ className="inline-flex items-center justify-center gap-2 px-4 py-2 text-sm rounded bg-port-accent hover:bg-blue-600 text-white transition-colors disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {active ? <Loader2 size={16} className="animate-spin" /> : <Download size={16} />}+ {active ? 'Downloading…' : 'Download'}+ </button>+ </div>++ {active && (+ <div className="flex items-center gap-3 text-[12px] text-port-accent">+ <Loader2 size={14} className="animate-spin shrink-0" />+ <div className="flex-1 min-w-0">+ <div className="flex items-center justify-between gap-2">+ <span className="truncate">+ {stage ? `${stage}…` : 'Downloading…'} {percent > 0 ? `${percent}%` : ''}+ </span>+ <button type="button" onClick={cancel} className="text-gray-400 hover:text-white shrink-0">+ Cancel+ </button>+ </div>+ <div className="mt-1 h-1 bg-port-border rounded overflow-hidden">+ <div className="h-full bg-port-accent transition-all" style={{ width: `${percent}%` }} />+ </div>+ </div>+ </div>+ )}+ <p className="text-[11px] text-gray-500">+ x.com/Twitter downloads are best-effort — login-walled or rate-limited posts may fail.+ </p>+ </form>++ <section>+ <h2 className="text-sm font-semibold text-gray-300 mb-2">Downloaded ({downloads.length})</h2>+ {loading ? (+ <p className="text-sm text-gray-500 flex items-center gap-2">+ <Loader2 size={14} className="animate-spin" /> Loading…+ </p>+ ) : downloads.length === 0 ? (+ <p className="text-sm text-gray-500">No videos downloaded yet.</p>+ ) : (+ <ul className="space-y-2">+ {downloads.map((d) => (+ <li+ key={d.id}+ className="flex items-center gap-3 bg-port-card border border-port-border rounded-lg p-3"+ >+ <a+ href={`/data/videos/${d.filename}`}+ target="_blank"+ rel="noreferrer"+ className="shrink-0 block w-28 aspect-video rounded overflow-hidden bg-port-bg border border-port-border"+ >+ {d.thumbnail ? (+ <img+ src={`/data/video-thumbnails/${d.thumbnail}`}+ alt=""+ className="w-full h-full object-cover"+ />+ ) : (+ <span className="w-full h-full flex items-center justify-center text-gray-600">+ <Video size={20} />+ </span>+ )}+ </a>+ <div className="flex-1 min-w-0">+ <p className="text-sm text-white truncate" title={d.title}>{d.title || 'Downloaded video'}</p>+ <div className="text-[11px] text-gray-500 flex items-center gap-2 mt-0.5">+ <span>{timeAgo(d.createdAt)}</span>+ {d.durationSec != null && <span>· {formatTimecode(d.durationSec)}</span>}+ </div>+ {d.sourceUrl && (+ <a+ href={d.sourceUrl}+ target="_blank"+ rel="noreferrer"+ className="text-[11px] text-port-accent hover:underline inline-flex items-center gap-1 mt-0.5 max-w-full truncate"+ title={d.sourceUrl}+ >+ <ExternalLink size={11} className="shrink-0" />+ <span className="truncate">{d.sourceUrl}</span>+ </a>+ )}+ </div>+ <div className="shrink-0">+ {isConfirming(d.id) ? (+ <ConfirmButtonPair+ prompt="Delete?"+ busy={deletingId === d.id}+ busyText="Deleting"+ onConfirm={() => onDelete(d.id)}+ onCancel={cancelDelete}+ ariaLabel={`Delete ${d.title || 'video'}`}+ />+ ) : (+ <button+ type="button"+ onClick={() => requestDelete(d.id)}+ className="p-2 text-gray-400 hover:text-port-error transition-colors"+ aria-label={`Delete ${d.title || 'video'}`}+ >+ <Trash2 size={16} />+ </button>+ )}+ </div>+ </li>+ ))}+ </ul>+ )}+ </section>+ </div>+ );+}diff --git a/client/src/services/README.md b/client/src/services/README.mdindex bab6c62d3a..407b4c1dab 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -94,6 +94,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiArtists.js` | Music artist personas (name, genre, bio, musical style, portrait description/style). || `apiAlbums.js` | Music albums (title, artist FK + name, description, genre, release year, cover art, ordered track ids). || `apiTracks.js` | Music tracks (title, album/artist FKs, lyrics, prompt, gen metadata, audio-library pointer) + shared music-library list + audio upload/attach/clear. |+| `apiVideoDownload.js` | Dev Tools video downloader (#1946): start/cancel a YouTube/x.com full-video download via yt-dlp (SSE progress), list + delete downloaded clips. || `apiMusic.js` | On-device music generation (MusicGen / AudioLDM2 / ACE-Step): list engines (+ readiness) and generate a track from a prompt/lyrics. || `apiWritersRoom.js` | Writers Room (folders + works + drafts, live continuation + render-preview reservation, scene-image attach). || `apiSharing.js` | Share buckets + federation sync. |diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 4e90d1ad18..ecf99b1b3c 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -51,6 +51,7 @@ export * from './apiAuthors.js';export * from './apiArtists.js';export * from './apiAlbums.js';export * from './apiTracks.js';+export * from './apiVideoDownload.js';export * from './apiMusic.js';export * from './apiPipeline.js';export * from './apiSharing.js';diff --git a/client/src/services/apiVideoDownload.js b/client/src/services/apiVideoDownload.jsnew file mode 100644index 0000000000..8918897eea--- /dev/null+++ b/client/src/services/apiVideoDownload.js@@ -0,0 +1,29 @@+import { request } from './apiCore.js';++// Video downloader (#1946) — Dev Tools utility that downloads a full video from+// a YouTube or x.com/Twitter URL via yt-dlp. Kickoff returns `{ jobId }`;+// progress streams over SSE (subscribe with useSseProgress). `options` lets a+// caller suppress request()'s auto-toast with `{ silent: true }`.+export const startVideoDownload = (url, options = {}) => request('/devtools/video-download', {+ method: 'POST',+ body: JSON.stringify({ url }),+ ...options,+});++export const videoDownloadEventsUrl = (jobId) =>+ `/api/devtools/video-download/${encodeURIComponent(jobId)}/events`;++export const cancelVideoDownload = (jobId, options = {}) =>+ request(`/devtools/video-download/${encodeURIComponent(jobId)}/cancel`, {+ method: 'POST',+ ...options,+ });++// The `source: 'download'` slice of video-history, newest first.+export const listVideoDownloads = (options = {}) => request('/devtools/video-download/downloads', options);++export const deleteVideoDownload = (id, options = {}) =>+ request(`/devtools/video-download/downloads/${encodeURIComponent(id)}`, {+ method: 'DELETE',+ ...options,+ });diff --git a/server/index.js b/server/index.jsindex 36f1e470c1..c7a39b7b6b 100644--- a/server/index.js+++ b/server/index.js@@ -103,6 +103,7 @@ import characterRoutes from './routes/character.js';import toolsRoutes from './routes/tools.js';import imageGenRoutes from './routes/imageGen.js';import videoGenRoutes from './routes/videoGen.js';+import videoDownloadRoutes from './routes/videoDownload.js';import videoTimelineRoutes from './routes/videoTimeline.js';import mediaJobsRoutes from './routes/mediaJobs.js';import creativeDirectorRoutes from './routes/creativeDirector.js';@@ -505,6 +506,7 @@ app.use('/api/character', characterRoutes);app.use('/api/tools', toolsRoutes);app.use('/api/image-gen', imageGenRoutes);app.use('/api/video-gen', videoGenRoutes);+app.use('/api/devtools/video-download', videoDownloadRoutes);app.use('/api/video-timeline', videoTimelineRoutes);app.use('/api/media-jobs', mediaJobsRoutes);app.use('/api/creative-director', creativeDirectorRoutes);diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 53dfc4225b..523c97deee 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -112,6 +112,7 @@ export const NAV_COMMANDS = [{ id: 'nav.shell', path: '/shell', label: 'Shell', section: 'Dev Tools', aliases: ['shell', 'terminal'] },{ id: 'nav.devtools.submodules', path: '/devtools/submodules', label: 'Submodules', section: 'Dev Tools', aliases: ['devtools-submodules'] },{ id: 'nav.devtools.usage', path: '/devtools/usage', label: 'Usage', section: 'Dev Tools', aliases: ['devtools-usage'] },+ { id: 'nav.devtools.video-download', path: '/devtools/video-download', label: 'Video Downloader', section: 'Dev Tools', aliases: ['video-download', 'video-downloader', 'download-video'], keywords: ['youtube', 'x.com', 'twitter', 'yt-dlp', 'download', 'clip'] },{ id: 'nav.workspace-contexts', path: '/workspace-contexts', label: 'Workspaces', section: 'Dev Tools', aliases: ['workspaces', 'workspace-contexts', 'project-contexts', 'project-switcher'], keywords: ['project', 'context', 'switch project', 'branch', 'shell', 'tasks', 'restore', 'working context'] },{ id: 'nav.twin.overview', path: '/digital-twin/overview', label: 'Overview', section: 'Identity', aliases: ['digital-twin', 'twin'] },diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 8dc1a1e825..4742fb6624 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -558,6 +558,13 @@ export const legacyExportSchema = z.object({includePdf: z.boolean().optional()});+// Video downloader (#1946) — paste a YouTube/x.com URL, download the full+// video. The host allowlist is enforced in the service (assertSupportedVideoUrl)+// so the error names the supported hosts; the schema just guards the shape.+export const videoDownloadSchema = z.object({+ url: z.string().url().max(2048)+});+// =============================================================================// TRANSITIONAL RE-EXPORTS (issue #1151 split)// =============================================================================diff --git a/server/routes/videoDownload.js b/server/routes/videoDownload.jsnew file mode 100644index 0000000000..4eee730b94--- /dev/null+++ b/server/routes/videoDownload.js@@ -0,0 +1,51 @@+/**+ * Video downloader routes (#1946) — Dev Tools utility that downloads a full+ * video from a YouTube or x.com/Twitter URL via yt-dlp into PATHS.videos, then+ * surfaces it in the existing media library.+ *+ * POST /api/devtools/video-download → { jobId } (kick off a download)+ * GET /api/devtools/video-download/downloads → Entry[] (downloaded videos, newest first)+ * DELETE /api/devtools/video-download/downloads/:id → { ok } (delete a downloaded video)+ * GET /api/devtools/video-download/:jobId/events → SSE progress+ * POST /api/devtools/video-download/:jobId/cancel → { ok }+ */++import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest, videoDownloadSchema } from '../lib/validation.js';+import {+ startVideoDownload,+ attachDownloadSseClient,+ cancelVideoDownload,+ listDownloads,+ deleteDownload,+} from '../services/videoDownload.js';++const router = Router();++router.post('/', asyncHandler(async (req, res) => {+ const { url } = validateRequest(videoDownloadSchema, req.body ?? {});+ res.status(202).json(await startVideoDownload(url));+}));++// `downloads` is a distinct first segment from a job's `:jobId` (whose routes+// are always two-segment — `:jobId/events`, `:jobId/cancel`), so no collision.+router.get('/downloads', asyncHandler(async (_req, res) => {+ res.json(await listDownloads());+}));++router.delete('/downloads/:id', asyncHandler(async (req, res) => {+ res.json(await deleteDownload(req.params.id));+}));++router.get('/:jobId/events', (req, res) => {+ if (!attachDownloadSseClient(req.params.jobId, res)) {+ throw new ServerError('Download job not found or expired', { status: 404, code: 'NOT_FOUND' });+ }+});++router.post('/:jobId/cancel', (req, res) => {+ res.json({ ok: cancelVideoDownload(req.params.jobId) });+});++export default router;diff --git a/server/routes/videoDownload.test.js b/server/routes/videoDownload.test.jsnew file mode 100644index 0000000000..e78c31a4a0--- /dev/null+++ b/server/routes/videoDownload.test.js@@ -0,0 +1,69 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';++vi.mock('../services/videoDownload.js', () => ({+ startVideoDownload: vi.fn(async () => ({ jobId: 'job-1' })),+ attachDownloadSseClient: vi.fn(() => true),+ cancelVideoDownload: vi.fn(() => true),+ listDownloads: vi.fn(async () => [{ id: 'dl-1', filename: 'downloaded-dl-1.mp4', source: 'download' }]),+ deleteDownload: vi.fn(async () => ({ ok: true })),+}));++import * as svc from '../services/videoDownload.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import videoDownloadRoutes from './videoDownload.js';++function makeApp() {+ const app = express();+ app.use(express.json());+ app.use('/api/devtools/video-download', videoDownloadRoutes);+ app.use(errorMiddleware);+ return app;+}++describe('video download routes (#1946)', () => {+ let app;+ beforeEach(() => { app = makeApp(); vi.clearAllMocks(); });++ it('POST / starts a job for a valid URL', async () => {+ const url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ';+ const r = await request(app).post('/api/devtools/video-download').send({ url });+ expect(r.status).toBe(202);+ expect(r.body).toEqual({ jobId: 'job-1' });+ expect(svc.startVideoDownload).toHaveBeenCalledWith(url);+ });++ it('POST / rejects a non-URL body before reaching the service', async () => {+ const r = await request(app).post('/api/devtools/video-download').send({ url: 'not a url' });+ expect(r.status).toBe(400);+ expect(svc.startVideoDownload).not.toHaveBeenCalled();+ });++ it('GET /downloads lists downloaded videos (not read as a jobId)', async () => {+ const r = await request(app).get('/api/devtools/video-download/downloads');+ expect(r.status).toBe(200);+ expect(r.body[0].id).toBe('dl-1');+ expect(svc.attachDownloadSseClient).not.toHaveBeenCalled();+ });++ it('DELETE /downloads/:id deletes a download', async () => {+ const r = await request(app).delete('/api/devtools/video-download/downloads/dl-1');+ expect(r.status).toBe(200);+ expect(r.body).toEqual({ ok: true });+ expect(svc.deleteDownload).toHaveBeenCalledWith('dl-1');+ });++ it('GET /:jobId/events 404s when the job is unknown', async () => {+ svc.attachDownloadSseClient.mockReturnValueOnce(false);+ const r = await request(app).get('/api/devtools/video-download/missing/events');+ expect(r.status).toBe(404);+ });++ it('POST /:jobId/cancel proxies to the service', async () => {+ const r = await request(app).post('/api/devtools/video-download/job-1/cancel');+ expect(r.status).toBe(200);+ expect(r.body).toEqual({ ok: true });+ expect(svc.cancelVideoDownload).toHaveBeenCalledWith('job-1');+ });+});diff --git a/server/services/videoDownload.js b/server/services/videoDownload.jsnew file mode 100644index 0000000000..95d5f82865--- /dev/null+++ b/server/services/videoDownload.js@@ -0,0 +1,261 @@+/**+ * Video downloader (#1946) — follow-up to #1945. Where trackYoutubeImport.js+ * extracts just the AUDIO track, this downloads the FULL video from a YouTube+ * or x.com/Twitter URL via yt-dlp, lands it under PATHS.videos as a+ * distinguishable `downloaded-<uuid>.mp4`, generates a thumbnail, and writes a+ * `source: 'download'` entry into the shared video-history store so it shows up+ * in the existing media library/gallery and gets picked up by the mediaAssetIndex+ * `videoGenEvents 'completed'` hook UNMODIFIED (issue design option (b) —+ * "write a lightweight video-history-like entry"; the `source` marker + filename+ * prefix keep the "derived, not a generation" framing honest without a new row+ * shape or a new index event).+ *+ * Mirrors trackYoutubeImport's job pattern exactly: kickoff returns a jobId+ * immediately, the download runs detached, progress streams over the shared SSE+ * helpers, and the client attaches with useSseProgress. A single yt-dlp+ * invocation does the whole job (best mp4 video+audio merged via ffmpeg).+ */++import { spawn } from 'child_process';+import { existsSync } from 'fs';+import { readdir, unlink } from 'fs/promises';+import { join, dirname } from 'path';+import { randomUUID } from 'crypto';+import { ServerError } from '../lib/errorHandler.js';+import { shortId, PATHS } from '../lib/fileUtils.js';+import { findFfmpeg, generateThumbnail, probeVideoDuration } from '../lib/ffmpeg.js';+import { findYtDlp } from '../lib/ytdlp.js';+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../lib/sseUtils.js';+import { safeChildProcessEnv } from '../lib/processEnv.js';+import { loadHistory, saveHistory } from './videoGen/history.js';+import { deleteHistoryItem } from './videoGen/local.js';+import { videoGenEvents } from './videoGen/events.js';++// Host allowlist: YouTube (watch/shorts/youtu.be) + x.com/Twitter status URLs.+// Same reasoning as #1945's YOUTUBE_URL_RE — constrains what a shelled-out+// yt-dlp will touch even though args are passed as an array (no shell+// interpolation), and gives the user a clear "unsupported host" error up front+// instead of a cryptic yt-dlp failure.+export const SUPPORTED_VIDEO_URL_RE =+ /^https?:\/\/(www\.|m\.|mobile\.)?(youtube\.com\/(watch\?[^\s#]*\bv=[\w-]{6,}|shorts\/[\w-]{6,})|youtu\.be\/[\w-]{6,}|(x|twitter)\.com\/[^\s/]+\/status\/\d+)/i;++export function assertSupportedVideoUrl(url) {+ if (typeof url !== 'string' || !SUPPORTED_VIDEO_URL_RE.test(url)) {+ throw new ServerError(+ 'Unsupported video URL (expected a YouTube video/shorts, youtu.be, or x.com/twitter.com status URL)',+ { status: 400, code: 'VIDEO_URL_INVALID' },+ );+ }+}++// Bound resource use the same way #1945 does for audio: without these, a long+// video, livestream, or archive URL downloads unbounded, eating disk in+// data/videos and CPU with no cap. Generous but finite for full-video pulls.+export const VIDEO_DOWNLOAD_MAX_BYTES = 2 * 1024 * 1024 * 1024; // 2 GB+export const VIDEO_DOWNLOAD_MAX_DURATION_SEC = 60 * 60; // 1 hour++const FILENAME_PREFIX = 'downloaded-';++// jobId -> { id, status, clients, lastPayload, process }+const downloadJobs = new Map();++export const attachDownloadSseClient = (jobId, res) => attachSse(downloadJobs, jobId, res);++/** Cancel an in-flight download. Returns false if the job is unknown or already finished. */+export function cancelVideoDownload(jobId) {+ const job = downloadJobs.get(jobId);+ if (!job || !job.process) return false;+ const proc = job.process;+ proc.kill('SIGTERM');+ setTimeout(() => {+ if (job.process === proc && proc.exitCode === null && proc.signalCode === null) {+ console.log(`⚠️ yt-dlp download didn't exit on SIGTERM — escalating to SIGKILL`);+ proc.kill('SIGKILL');+ }+ }, 8000);+ return true;+}++/** List downloaded videos — the `source: 'download'` slice of video-history, newest first. */+export async function listDownloads() {+ const history = await loadHistory().catch(() => []);+ return (Array.isArray(history) ? history : []).filter((h) => h?.source === 'download');+}++/**+ * Delete a downloaded video. Verifies the id is actually a download (not a+ * generated render) before delegating to the shared deleteHistoryItem, which+ * removes the file, thumbnail, and history entry. The next mediaAssetIndex+ * reconcile prunes its row (identical lifecycle to a deleted generation).+ */+export async function deleteDownload(id) {+ const history = await loadHistory().catch(() => []);+ const item = (Array.isArray(history) ? history : []).find((h) => h?.id === id);+ if (!item || item.source !== 'download') {+ throw new ServerError('Downloaded video not found', { status: 404, code: 'NOT_FOUND' });+ }+ return deleteHistoryItem(id);+}++const TITLE_PREFIX = 'PORTOS_TITLE:';+// Machine-readable progress markers via yt-dlp's --progress-template rather than+// scraping human-readable console lines — mirrors trackYoutubeImport.+const PROGRESS_PREFIX = 'PORTOS_PROGRESS:';+const STAGE_PREFIX = 'PORTOS_STAGE:';++// A cancelled/failed run can leave yt-dlp's pre-merge fragment files behind+// (`downloaded-<uuid>.f137.mp4`, `.part`, etc.), so cleanup globs every file+// this job's prefix touched in PATHS.videos rather than unlinking one path.+async function cleanupDownloadFiles(jobId) {+ const prefix = `${FILENAME_PREFIX}${jobId}`;+ const entries = await readdir(PATHS.videos).catch(() => []);+ await Promise.all(+ entries.filter((name) => name.startsWith(prefix)).map((name) => unlink(join(PATHS.videos, name)).catch(() => {})),+ );+}++/**+ * Kick off a full-video download. Returns `{ jobId }` immediately; the download+ * runs detached and streams progress over SSE. Terminal frames:+ * `{ type: 'complete', id, video }`, `{ type: 'error', error }`, or+ * `{ type: 'canceled' }`.+ */+export async function startVideoDownload(url) {+ assertSupportedVideoUrl(url);++ const [ytDlp, ffmpeg] = await Promise.all([findYtDlp(), findFfmpeg()]);+ if (!ytDlp) throw new ServerError('yt-dlp not found on PATH', { status: 500, code: 'YTDLP_MISSING' });+ if (!ffmpeg) throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });++ const jobId = randomUUID();+ const filename = `${FILENAME_PREFIX}${jobId}.mp4`;+ const outPath = join(PATHS.videos, filename);+ // yt-dlp writes intermediate streams as `downloaded-<uuid>.<ext>` then merges+ // to .mp4; --merge-output-format mp4 makes the final container known up front.+ const outTemplate = join(PATHS.videos, `${FILENAME_PREFIX}${jobId}.%(ext)s`);++ const job = { id: jobId, status: 'running', clients: [], process: null };+ downloadJobs.set(jobId, job);+ console.log(`📥 Video download ${shortId(jobId)} — ${url}`);++ (async () => {+ let title = '';+ try {+ const args = [+ // Prefer an mp4 (h264/aac) video+audio pair that merges cleanly for+ // broad browser playback; fall back to best single-file mp4, then best.+ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',+ '--merge-output-format', 'mp4',+ '--no-playlist',+ '--ffmpeg-location', dirname(ffmpeg),+ '--newline',+ '--print', `${TITLE_PREFIX}%(title)s`,+ '--progress-template', `download:${PROGRESS_PREFIX}%(progress._percent_str)s`,+ '--progress-template', `postprocess:${STAGE_PREFIX}merging`,+ // --print implies --simulate AND suppresses normal progress reporting;+ // --no-simulate + --progress restore the real run + machine markers+ // (same yt-dlp quirk documented in trackYoutubeImport).+ '--no-simulate',+ '--progress',+ '--max-filesize', String(VIDEO_DOWNLOAD_MAX_BYTES),+ '--match-filters', `duration <= ${VIDEO_DOWNLOAD_MAX_DURATION_SEC}`,+ '-o', outTemplate,+ url,+ ];+ const proc = spawn(ytDlp, args, { env: safeChildProcessEnv(), stdio: ['ignore', 'pipe', 'pipe'] });+ job.process = proc;++ const onLine = (line) => {+ if (line.startsWith(TITLE_PREFIX)) {+ title = line.slice(TITLE_PREFIX.length).trim();+ return;+ }+ if (line.startsWith(PROGRESS_PREFIX)) {+ const percent = parseFloat(line.slice(PROGRESS_PREFIX.length));+ if (Number.isFinite(percent)) broadcastSse(job, { type: 'progress', percent });+ return;+ }+ if (line.startsWith(STAGE_PREFIX)) {+ broadcastSse(job, { type: 'progress', percent: 100, stage: line.slice(STAGE_PREFIX.length) });+ }+ };+ // Separate buffers per stream — a shared buffer can complete a partial+ // line from one stream with a chunk from the other, corrupting a marker.+ const makeLineReader = () => {+ let buf = '';+ return (chunk) => {+ buf += chunk.toString();+ const lines = buf.split(/\r?\n/);+ buf = lines.pop();+ lines.forEach(onLine);+ };+ };+ proc.stdout.on('data', makeLineReader());+ proc.stderr.on('data', makeLineReader()); // yt-dlp writes some progress/info lines to stderr too++ const exit = await new Promise((resolve) => {+ proc.on('error', (err) => resolve({ code: null, reason: `spawn failed: ${err.message}` }));+ proc.on('close', (code, signal) => resolve({ code, signal }));+ });+ job.process = null;++ if (exit.signal === 'SIGTERM' || exit.signal === 'SIGKILL') {+ console.log(`🛑 Video download ${shortId(jobId)} cancelled`);+ broadcastSse(job, { type: 'canceled' });+ await cleanupDownloadFiles(jobId);+ return;+ }+ if (exit.code !== 0 || !existsSync(outPath)) {+ // A --match-filters/--max-filesize rejection exits 0 with no output+ // file (yt-dlp treats a filtered-out video as "nothing to do") — and+ // --print suppresses the specific reason, so name the two known bounds.+ // x.com/Twitter downloads also fail here on login-walled/rate-limited+ // content; surface a clear message rather than a bare exit code.+ const reason = exit.code === 0+ ? `no video was produced — it may be longer than ${VIDEO_DOWNLOAD_MAX_DURATION_SEC / 60} minutes or larger than ${Math.round(VIDEO_DOWNLOAD_MAX_BYTES / 1024 / 1024 / 1024)}GB, or (for x.com) login-walled or rate-limited`+ : (exit.reason || `yt-dlp exited ${exit.code}`);+ throw new Error(reason);+ }++ broadcastSse(job, { type: 'progress', percent: 100, stage: 'finalizing' });+ const [thumbnail, durationSec] = await Promise.all([+ generateThumbnail(outPath, jobId),+ probeVideoDuration(outPath).catch(() => null),+ ]);++ // Derived, not a generation: a `source: 'download'` video-history entry so+ // the existing videoToRow / onVideoCompleted media-index path and the+ // gallery pick it up unmodified. `id === jobId` so the shared+ // deleteHistoryItem cleans the file + `${jobId}.jpg` thumbnail.+ const entry = {+ id: jobId,+ filename,+ thumbnail,+ createdAt: new Date().toISOString(),+ mode: 'download',+ source: 'download',+ sourceUrl: url,+ title: title || 'Downloaded video',+ ...(durationSec != null ? { durationSec } : {}),+ };+ const history = await loadHistory().catch(() => []);+ history.unshift(entry);+ await saveHistory(history);++ // Let the live media-asset index hook index this immediately (it loads+ // history by generationId and upserts one row). Reconcile is the backstop.+ videoGenEvents.emit('completed', { generationId: jobId, filename, path: `/data/videos/${filename}`, thumbnail });++ console.log(`📥 Video download ${shortId(jobId)} complete — "${entry.title}" (${filename})`);+ broadcastSse(job, { type: 'complete', id: jobId, video: entry });+ } catch (err) {+ console.error(`❌ Video download ${shortId(jobId)} failed: ${err?.message || err}`);+ broadcastSse(job, { type: 'error', error: err?.message || String(err) });+ await cleanupDownloadFiles(jobId);+ } finally {+ closeJobAfterDelay(downloadJobs, jobId);+ }+ })();++ return { jobId };+}diff --git a/server/services/videoDownload.test.js b/server/services/videoDownload.test.jsnew file mode 100644index 0000000000..c8194b5209--- /dev/null+++ b/server/services/videoDownload.test.js@@ -0,0 +1,85 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mock the history store so listDownloads/deleteDownload can be exercised+// without touching disk, and mock deleteHistoryItem so deleteDownload's+// delegation is observable.+const { historyStore, deleteHistoryItem } = vi.hoisted(() => ({+ historyStore: { items: [] },+ deleteHistoryItem: vi.fn(async () => ({ ok: true })),+}));+vi.mock('./videoGen/history.js', () => ({+ loadHistory: vi.fn(async () => historyStore.items),+ saveHistory: vi.fn(async (h) => { historyStore.items = h; }),+}));+vi.mock('./videoGen/local.js', () => ({ deleteHistoryItem }));+vi.mock('./videoGen/events.js', () => ({ videoGenEvents: { emit: vi.fn() } }));++import {+ SUPPORTED_VIDEO_URL_RE,+ assertSupportedVideoUrl,+ listDownloads,+ deleteDownload,+} from './videoDownload.js';++describe('videoDownload URL allowlist', () => {+ it('accepts YouTube watch, shorts, and youtu.be', () => {+ for (const url of [+ 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',+ 'https://m.youtube.com/watch?v=dQw4w9WgXcQ',+ 'https://youtube.com/shorts/abc123XYZ',+ 'https://youtu.be/dQw4w9WgXcQ',+ ]) {+ expect(SUPPORTED_VIDEO_URL_RE.test(url)).toBe(true);+ expect(() => assertSupportedVideoUrl(url)).not.toThrow();+ }+ });++ it('accepts x.com and twitter.com status URLs', () => {+ expect(() => assertSupportedVideoUrl('https://x.com/someone/status/1234567890')).not.toThrow();+ expect(() => assertSupportedVideoUrl('https://twitter.com/someone/status/1234567890')).not.toThrow();+ });++ it('rejects other hosts and malformed URLs with a 400', () => {+ for (const url of ['https://vimeo.com/12345', 'https://example.com/x', 'not-a-url', '', null]) {+ expect(() => assertSupportedVideoUrl(url)).toThrow(/Unsupported video URL/);+ }+ // The thrown error carries the 400 status/code contract.+ try {+ assertSupportedVideoUrl('https://vimeo.com/12345');+ } catch (err) {+ expect(err.status).toBe(400);+ expect(err.code).toBe('VIDEO_URL_INVALID');+ }+ });+});++describe('listDownloads / deleteDownload', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ historyStore.items = [+ { id: 'gen-1', filename: 'abc.mp4' }, // a real generation — must be excluded+ { id: 'dl-1', filename: 'downloaded-dl-1.mp4', source: 'download', title: 'Clip' },+ ];+ });++ it('lists only the source:download slice of history', async () => {+ const list = await listDownloads();+ expect(list).toHaveLength(1);+ expect(list[0].id).toBe('dl-1');+ });++ it('deletes a download by delegating to deleteHistoryItem', async () => {+ const res = await deleteDownload('dl-1');+ expect(res).toEqual({ ok: true });+ expect(deleteHistoryItem).toHaveBeenCalledWith('dl-1');+ });++ it('refuses to delete a non-download history id (404)', async () => {+ await expect(deleteDownload('gen-1')).rejects.toMatchObject({ status: 404 });+ expect(deleteHistoryItem).not.toHaveBeenCalled();+ });++ it('404s for an unknown id', async () => {+ await expect(deleteDownload('nope')).rejects.toMatchObject({ status: 404 });+ });+});