Skip to content

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

feat: update yt-dlp from the Video Downloader page

[._.]/ Adam Eivy6cb73ac2ce46
diff --git a/client/src/components/video/YtDlpUpdateCard.jsx b/client/src/components/video/YtDlpUpdateCard.jsx
new file mode 100644
index 0000000000..6a984650e4
--- /dev/null
+++ b/client/src/components/video/YtDlpUpdateCard.jsx
@@ -0,0 +1,113 @@
+import { useCallback, useEffect, useState } from 'react';
+import { AlertTriangle, CheckCircle2, Loader2, RefreshCw } from 'lucide-react';
+import toast from '../ui/Toast';
+import { useSocket } from '../../hooks';
+import { getYtDlpStatus, updateYtDlp } from '../../services/apiVideoDownload.js';
+
+/**
+ * yt-dlp version + one-click update, on the Video Downloader page.
+ *
+ * YouTube gates media URLs behind a player handshake that yt-dlp tracks
+ * release-to-release, so a binary only weeks old fails downloads the browser
+ * plays fine. The failure message already names the remedy (#7255); this is the
+ * remedy itself, next to the field that hit it — the same affordance the Local
+ * LLMs page gives llama.cpp and Ollama.
+ */
+export default function YtDlpUpdateCard() {
+ const socket = useSocket();
+ const [status, setStatus] = useState(null);
+ const [updating, setUpdating] = useState(false);
+ const [progress, setProgress] = useState('');
+
+ const refresh = useCallback(
+ () => getYtDlpStatus({ silent: true }).then(setStatus).catch(() => setStatus(null)),
+ [],
+ );
+
+ useEffect(() => { refresh(); }, [refresh]);
+
+ // `brew upgrade` relays its own output while it runs, so the button can show
+ // what it's doing rather than spinning silently for a minute.
+ useEffect(() => {
+ const onFrame = (frame) => {
+ if (frame?.event === 'progress' && frame.message) setProgress(String(frame.message).trim());
+ };
+ socket.on('ytdlp:update', onFrame);
+ return () => socket.off('ytdlp:update', onFrame);
+ }, [socket]);
+
+ const onUpdate = async () => {
+ setUpdating(true);
+ setProgress('');
+ await updateYtDlp({ silent: true })
+ .then((result) => {
+ toast.success(result?.note ? `yt-dlp ${result.note}` : `yt-dlp updated to ${result?.version || 'the latest release'}`);
+ return refresh();
+ })
+ .catch((err) => toast.error(err?.message || 'yt-dlp update failed'))
+ .finally(() => {
+ setUpdating(false);
+ setProgress('');
+ });
+ };
+
+ // Nothing known yet — stay silent rather than flashing a "not installed" claim
+ // the first response may contradict.
+ if (!status) return null;
+
+ const outdated = status.installed && status.updateAvailable;
+
+ return (
+ <div className="bg-port-card border border-port-border rounded-lg p-3 flex flex-col sm:flex-row sm:items-center gap-3">
+ <div className="flex-1 min-w-0">
+ <p className="text-sm text-gray-300 flex items-center gap-2">
+ {status.installed ? (
+ outdated
+ ? <AlertTriangle size={14} className="text-port-warning shrink-0" />
+ : <CheckCircle2 size={14} className="text-port-success shrink-0" />
+ ) : (
+ <AlertTriangle size={14} className="text-port-error shrink-0" />
+ )}
+ <span className="truncate">
+ {status.installed
+ ? `yt-dlp ${status.version || 'installed'}`
+ : 'yt-dlp is not installed'}
+ {outdated && status.latestVersion ? ` — ${status.latestVersion} is available` : ''}
+ </span>
+ </p>
+ <p className="text-[11px] text-gray-500 mt-0.5 truncate">
+ {progress
+ || status.blockedReason
+ || (outdated
+ ? 'A stale yt-dlp is the usual cause of a failed YouTube download.'
+ : status.installed
+ ? `Up to date via ${status.methodLabel}.`
+ : null)}
+ </p>
+ </div>
+ {status.installed && status.canUpdate && (
+ <button
+ type="button"
+ onClick={onUpdate}
+ disabled={updating}
+ className={`shrink-0 inline-flex items-center justify-center gap-2 px-3 py-1.5 text-sm rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${
+ outdated ? 'bg-port-accent hover:bg-blue-600 text-white' : 'border border-port-border text-gray-300 hover:text-white'
+ }`}
+ >
+ {updating ? <Loader2 size={14} className="animate-spin" /> : <RefreshCw size={14} />}
+ {updating ? 'Updating…' : 'Update yt-dlp'}
+ </button>
+ )}
+ {!status.installed && status.downloadUrl && (
+ <a
+ href={status.downloadUrl}
+ target="_blank"
+ rel="noreferrer"
+ className="shrink-0 px-3 py-1.5 text-sm rounded border border-port-border text-gray-300 hover:text-white transition-colors"
+ >
+ Install instructions
+ </a>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/video/YtDlpUpdateCard.test.jsx b/client/src/components/video/YtDlpUpdateCard.test.jsx
new file mode 100644
index 0000000000..4923d713f2
--- /dev/null
+++ b/client/src/components/video/YtDlpUpdateCard.test.jsx
@@ -0,0 +1,88 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import YtDlpUpdateCard from './YtDlpUpdateCard';
+
+vi.mock('../../services/apiVideoDownload.js', () => ({
+ getYtDlpStatus: vi.fn(),
+ updateYtDlp: vi.fn(),
+}));
+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
+
+const handlers = new Map();
+vi.mock('../../hooks', () => ({
+ useSocket: () => ({
+ on: (event, fn) => handlers.set(event, fn),
+ off: (event) => handlers.delete(event),
+ }),
+}));
+
+import { getYtDlpStatus, updateYtDlp } from '../../services/apiVideoDownload.js';
+import toast from '../ui/Toast';
+
+const STALE = {
+ installed: true, version: '2026.07.04', latestVersion: '2026.08.19',
+ updateAvailable: true, canUpdate: true, method: 'brew', methodLabel: 'Homebrew',
+ blockedReason: null, downloadUrl: 'https://example.com/install',
+};
+
+describe('YtDlpUpdateCard', () => {
+ beforeEach(() => { vi.clearAllMocks(); handlers.clear(); });
+
+ it('names the installed and available versions when yt-dlp is stale', async () => {
+ getYtDlpStatus.mockResolvedValue(STALE);
+ render(<YtDlpUpdateCard />);
+ expect(await screen.findByText(/yt-dlp 2026\.07\.04 — 2026\.08\.19 is available/)).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /update yt-dlp/i })).toBeInTheDocument();
+ });
+
+ it('updates on click and re-reads the status so the card shows what landed', async () => {
+ getYtDlpStatus
+ .mockResolvedValueOnce(STALE)
+ .mockResolvedValue({ ...STALE, version: '2026.08.19', updateAvailable: false });
+ updateYtDlp.mockResolvedValue({ success: true, version: '2026.08.19' });
+
+ render(<YtDlpUpdateCard />);
+ await userEvent.click(await screen.findByRole('button', { name: /update yt-dlp/i }));
+
+ await waitFor(() => expect(toast.success).toHaveBeenCalled());
+ expect(await screen.findByText(/Up to date via Homebrew/)).toBeInTheDocument();
+ });
+
+ it('reports a failed update instead of leaving the card claiming success', async () => {
+ getYtDlpStatus.mockResolvedValue(STALE);
+ updateYtDlp.mockRejectedValue(new Error('yt-dlp is pinned in Homebrew.'));
+
+ render(<YtDlpUpdateCard />);
+ await userEvent.click(await screen.findByRole('button', { name: /update yt-dlp/i }));
+
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('yt-dlp is pinned in Homebrew.'));
+ expect(screen.getByRole('button', { name: /update yt-dlp/i })).toBeEnabled();
+ });
+
+ // A blocked install (pinned formula, unlinked keg) must not offer a button
+ // that cannot work — the reason replaces it.
+ it('shows the blocking reason and no update button when PortOS may not update', async () => {
+ getYtDlpStatus.mockResolvedValue({ ...STALE, canUpdate: false, blockedReason: 'yt-dlp is pinned in Homebrew.' });
+ render(<YtDlpUpdateCard />);
+ expect(await screen.findByText('yt-dlp is pinned in Homebrew.')).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /update yt-dlp/i })).not.toBeInTheDocument();
+ });
+
+ it('points at install instructions when yt-dlp is missing entirely', async () => {
+ getYtDlpStatus.mockResolvedValue({
+ installed: false, version: null, canUpdate: false,
+ blockedReason: 'yt-dlp is not on PATH.', downloadUrl: 'https://example.com/install',
+ });
+ render(<YtDlpUpdateCard />);
+ expect(await screen.findByText(/yt-dlp is not installed/)).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: /install instructions/i })).toHaveAttribute('href', 'https://example.com/install');
+ });
+
+ it('renders nothing while the status is unknown rather than claiming yt-dlp is missing', async () => {
+ getYtDlpStatus.mockRejectedValue(new Error('offline'));
+ const { container } = render(<YtDlpUpdateCard />);
+ await waitFor(() => expect(getYtDlpStatus).toHaveBeenCalled());
+ expect(container).toBeEmptyDOMElement();
+ });
+});
diff --git a/client/src/pages/VideoDownloaderPage.jsx b/client/src/pages/VideoDownloaderPage.jsx
index 4a196a38d2..33fe4580c7 100644
--- a/client/src/pages/VideoDownloaderPage.jsx
+++ b/client/src/pages/VideoDownloaderPage.jsx
@@ -3,6 +3,7 @@ import { Download, Film, Loader2, Trash2, ExternalLink, Video } from 'lucide-rea
import BrailleSpinner from '../components/BrailleSpinner';
import toast from '../components/ui/Toast';
import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
+import YtDlpUpdateCard from '../components/video/YtDlpUpdateCard';
import { useVideoDownload, useConfirmDelete } from '../hooks';
import { listVideoDownloads, deleteVideoDownload } from '../services/apiVideoDownload.js';
import { timeAgo, formatTimecode } from '../utils/formatters';
@@ -58,6 +59,8 @@ export default function VideoDownloaderPage() {
</p>
</header>
+ <YtDlpUpdateCard />
+
<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
diff --git a/client/src/services/README.md b/client/src/services/README.md
index e66f0efe6a..27dc659352 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -120,7 +120,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. |
-| `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. |
+| `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, plus `getYtDlpStatus`/`updateYtDlp` for the in-place yt-dlp update the page offers when a download fails on a stale binary. |
| `apiMusic.js` | On-device music generation (MusicGen / AudioLDM2 / ACE-Step): list engines (+ readiness), the stepped designer's AI describe/lyrics steps, 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/apiVideoDownload.js b/client/src/services/apiVideoDownload.js
index 8918897eea..481b8df087 100644
--- a/client/src/services/apiVideoDownload.js
+++ b/client/src/services/apiVideoDownload.js
@@ -27,3 +27,11 @@ export const deleteVideoDownload = (id, options = {}) =>
method: 'DELETE',
...options,
});
+
+// yt-dlp's own version and whether PortOS can update it in place. A stale
+// yt-dlp is the usual cause of a failed YouTube download, so the page surfaces
+// the state and the one-click remedy next to the URL field.
+export const getYtDlpStatus = (options = {}) => request('/devtools/video-download/yt-dlp', options);
+
+export const updateYtDlp = (options = {}) =>
+ request('/devtools/video-download/yt-dlp/update', { method: 'POST', ...options });
diff --git a/server/lib/README.md b/server/lib/README.md
index d23158f54b..7baad345d2 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -369,7 +369,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `youtubeIngestFormat.js` | Pure data transformations for the brain's YouTube ingest (#6015): `parseVideoMetadata(json)` (yt-dlp `--dump-single-json` → the stored metadata shape, incl. the `subtitles`-vs-`automatic_captions` manual-caption signal), `buildIngestNote({meta,url,transcript,tags,agentPrompt,capturedAt})` (the Obsidian note, whose YAML frontmatter the user's own vault queries key on — every interpolated scalar goes through `yamlString`), `buildAgentTaskContext(...)` (the CoS follow-up prompt, including the untrusted-transcript boundary notice), `resolveObsidianPointer({written,vaultId,notePath,prior})` (keeps the prior note pointer when an ATTEMPTED mirror failed, so an evicted note can't be orphaned — #3706), plus `sanitizeFilename`, `formatDuration` (seconds → `h:mm:ss`) and `yamlString`. No fs/db/childProcess/SSE imports; orchestration and storage stay in `services/youtubeIngest.js`. Surfaced through the barrel as a NAMESPACE export (`youtubeIngestFormat.*`) because `formatDuration` collides with `fileCore.js` and `sanitizeFilename` with `mimeTypes.js`. |
| `youtubeUrl.js` | Canonical YouTube single-video URL rule (#6014). `YOUTUBE_VIDEO_URL_RE` (accepts `watch`/`shorts`/`live`/`embed` plus the `www.`/`m.`/`music.` hosts, rejects playlists, channels, and `/@handle` feeds), `youtubeVideoIdFromUrl(url)` (alias `youtubeVideoId`), `isYoutubeVideoUrl(url)`, and the shared `YOUTUBE_URL_INVALID_MESSAGE`. Single source for the brain ingest, the Takeout importer, the history scrape, the Music Video track import, and (by re-export) `client/src/lib/youtubeUrl.js`. A pure leaf — the throwing form lives in `youtubeUrlAssert.js`, so importing this can never drag `errorHandler.js` into the browser bundle. |
| `youtubeUrlAssert.js` | `assertYoutubeVideoUrl(url)` — the throwing form of the `youtubeUrl.js` rule: returns the video id, else throws 400 `YOUTUBE_URL_INVALID`. Separate because it needs `ServerError` (and so Node's `events`), which must stay out of the pure leaf the client re-exports. |
-| `ytdlp.js` | `findYtDlp()` — cached discovery of the `yt-dlp` binary on PATH, mirrors `findFfmpeg()` in `ffmpeg.js`. Used by the track YouTube-import job. |
+| `ytdlp.js` | `findYtDlp()` — cached discovery of the `yt-dlp` binary on PATH, mirrors `findFfmpeg()` in `ffmpeg.js`. Used by the track YouTube-import job. `resetYtDlpCache()` drops that cache after an in-place update or a fresh install, so neither needs a server restart to take effect. |
## Networking
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index 3431b0f67a..3a49bb59b8 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -444,7 +444,14 @@ describe('deferred imports stay deferred (#6156)', () => {
// closure (32). There is nothing to narrow — the leaf IS the narrow form — so
// raise by exactly that delta and keep the existing headroom. The measured total
// is 103,356 after rebasing onto a main that grew by 36 on its own.
-const MAX_STATIC_INSTANTIATIONS = 103368;
+// The yt-dlp update path adds services/ytdlpUpdate.js (closure 22 — 17 of them
+// lib/bufferedSpawn.js, which the Video Downloader route already reached) and
+// its own test file. The measured whole-tree delta is +16: nearly everything
+// ytdlpUpdate.js reaches was already in some suite's closure, so the cost is
+// the new modules themselves rather than a new heavy subtree. There is nothing
+// to narrow — bufferedSpawn IS how this tree captures a subprocess's output —
+// so raise by exactly that delta and keep the existing headroom.
+const MAX_STATIC_INSTANTIATIONS = 103384;
const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
diff --git a/server/lib/ytdlp.js b/server/lib/ytdlp.js
index a5365c6207..e9a444354f 100644
--- a/server/lib/ytdlp.js
+++ b/server/lib/ytdlp.js
@@ -22,3 +22,13 @@ export const findYtDlp = async () => {
cachedYtDlpPath = await whichFirst('yt-dlp');
return cachedYtDlpPath;
};
+
+/**
+ * Forget the resolved path so the next `findYtDlp()` probes disk again.
+ *
+ * An in-place update can relink the keg under a different prefix, and an
+ * install performed while the server is running has to become visible without a
+ * restart — both would otherwise keep serving the cached answer (including the
+ * cached `null` from before the install).
+ */
+export const resetYtDlpCache = () => { cachedYtDlpPath = undefined; };
diff --git a/server/routes/videoDownload.js b/server/routes/videoDownload.js
index 81420ce9fc..f832a26e41 100644
--- a/server/routes/videoDownload.js
+++ b/server/routes/videoDownload.js
@@ -6,6 +6,8 @@
* 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/yt-dlp → yt-dlp version + update availability
+ * POST /api/devtools/video-download/yt-dlp/update → update yt-dlp in place
* GET /api/devtools/video-download/:jobId/events → SSE progress
* POST /api/devtools/video-download/:jobId/cancel → { ok }
*/
@@ -22,6 +24,7 @@ import {
listDownloads,
deleteDownload,
} from '../services/videoDownload.js';
+import { getYtDlpUpdateStatus, updateYtDlp } from '../services/ytdlpUpdate.js';
const router = Router();
@@ -42,6 +45,33 @@ router.delete('/downloads/:id', asyncHandler(async (req, res) => {
res.json(await deleteDownload(req.params.id));
}));
+// yt-dlp's own version and update state. A stale yt-dlp is the most common cause
+// of a failed download here — YouTube's player handshake moves release to
+// release — so the page offers the update rather than sending the user to a
+// terminal. Kept off the download request: it spends a `brew info` and possibly
+// a GitHub round-trip, neither of which a download should wait on.
+//
+// `yt-dlp` is a distinct first segment from `downloads` and from a job's
+// `:jobId` (whose routes are always two-segment), so no collision.
+router.get('/yt-dlp', asyncHandler(async (_req, res) => {
+ res.json(await getYtDlpUpdateStatus());
+}));
+
+// A `brew upgrade` can take a minute, so the package manager's own output is
+// relayed over `ytdlp:update` while it runs — the page renders it as a status
+// line on the button that started it.
+router.post('/yt-dlp/update', asyncHandler(async (req, res) => {
+ const io = req.app.get('io');
+ const emit = (frame) => io?.emit('ytdlp:update', frame);
+ const result = await updateYtDlp({ onProgress: emit });
+ if (!result.success) {
+ emit({ event: 'error', message: result.error });
+ throw new ServerError(result.error || 'yt-dlp update failed', { status: 502 });
+ }
+ emit({ event: 'complete', message: `yt-dlp ${result.note || `updated to ${result.version}`}` });
+ res.json(result);
+}));
+
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' });
diff --git a/server/routes/videoDownload.test.js b/server/routes/videoDownload.test.js
index 8b7230c86a..2635e26578 100644
--- a/server/routes/videoDownload.test.js
+++ b/server/routes/videoDownload.test.js
@@ -10,7 +10,13 @@ vi.mock('../services/videoDownload.js', () => ({
deleteDownload: vi.fn(async () => ({ ok: true })),
}));
+vi.mock('../services/ytdlpUpdate.js', () => ({
+ getYtDlpUpdateStatus: vi.fn(async () => ({ installed: true, version: '2026.08.19', canUpdate: true })),
+ updateYtDlp: vi.fn(async () => ({ success: true, version: '2026.08.19' })),
+}));
+
import * as svc from '../services/videoDownload.js';
+import * as ytdlpUpdate from '../services/ytdlpUpdate.js';
import { errorMiddleware } from '../lib/errorHandler.js';
import videoDownloadRoutes from './videoDownload.js';
@@ -83,4 +89,30 @@ describe('video download routes (#1946)', () => {
expect(r.body).toEqual({ ok: true });
expect(svc.cancelVideoDownload).toHaveBeenCalledWith('job-1');
});
+
+ // `yt-dlp` has to stay a literal first segment rather than falling into
+ // `/:jobId/events`, the same collision `downloads` is guarded against above.
+ it('GET /yt-dlp reports update status instead of being read as a jobId', async () => {
+ const r = await request(app).get('/api/devtools/video-download/yt-dlp');
+ expect(r.status).toBe(200);
+ expect(r.body.version).toBe('2026.08.19');
+ expect(svc.attachDownloadSseClient).not.toHaveBeenCalled();
+ });
+
+ it('POST /yt-dlp/update returns the update result', async () => {
+ const r = await request(app).post('/api/devtools/video-download/yt-dlp/update');
+ expect(r.status).toBe(200);
+ expect(r.body).toEqual({ success: true, version: '2026.08.19' });
+ expect(svc.cancelVideoDownload).not.toHaveBeenCalled();
+ });
+
+ // A refusal (Homebrew pin, missing binary, failed upgrade) is returned rather
+ // than thrown by the service, so the route is the only place it can become an
+ // error the page renders — a 200 here would report a failed update as done.
+ it('POST /yt-dlp/update surfaces a refusal as an error, not a success', async () => {
+ ytdlpUpdate.updateYtDlp.mockResolvedValueOnce({ success: false, error: 'yt-dlp is pinned in Homebrew.' });
+ const r = await request(app).post('/api/devtools/video-download/yt-dlp/update');
+ expect(r.status).toBe(502);
+ expect(r.body.error ?? r.body.message).toContain('pinned');
+ });
});
diff --git a/server/services/ytdlpUpdate.js b/server/services/ytdlpUpdate.js
new file mode 100644
index 0000000000..ef029db149
--- /dev/null
+++ b/server/services/ytdlpUpdate.js
@@ -0,0 +1,251 @@
+/**
+ * yt-dlp version reporting and in-place update (#7255 follow-up).
+ *
+ * YouTube gates its media URLs behind a player handshake that yt-dlp tracks
+ * release-to-release, so a binary only weeks old starts returning a flat
+ * `HTTP Error 403: Forbidden` for videos the browser plays fine. That is the
+ * single most common cause of a failed download here, and the remedy is always
+ * the same one command — so the Video Downloader page offers the button rather
+ * than sending the user to a terminal, mirroring the llama.cpp / Ollama update
+ * affordances on the Local LLMs page.
+ *
+ * Deliberately NOT modelled on `llamaServerManager`'s package plan: yt-dlp has
+ * no daemon to stop and restart, and its own `-U` self-update covers every
+ * install shape Homebrew doesn't (standalone binary, pip, pipx) — refusing with
+ * its own accurate message when it can't. So there are exactly two paths here,
+ * and the non-Homebrew one delegates the decision to yt-dlp itself.
+ */
+
+import { realpath } from 'fs/promises';
+import { bufferedSpawn } from '../lib/bufferedSpawn.js';
+import { runStreamingCommand } from '../lib/streamingSpawn.js';
+import { findYtDlp, resetYtDlpCache } from '../lib/ytdlp.js';
+
+const BREW_FORMULA = 'yt-dlp';
+const VERSION_PROBE_TIMEOUT_MS = 10_000;
+const BREW_INFO_TIMEOUT_MS = 20_000;
+const UPGRADE_TIMEOUT_MS = 10 * 60 * 1000;
+const GITHUB_TIMEOUT_MS = 8_000;
+
+export const YTDLP_DOWNLOAD_URL = 'https://github.com/yt-dlp/yt-dlp#installation';
+
+/**
+ * Run a small local command and retain its output without throwing. Version and
+ * Homebrew metadata are optional decorations on a status response, so a
+ * missing or broken command must not take the endpoint down with it.
+ */
+async function readCommandOutput(command, args, timeoutMs) {
+ const result = await bufferedSpawn(command, args, { timeoutMs, shell: false });
+ return { ok: result.success === true, stdout: result.stdout || '', stderr: result.stderr || '' };
+}
+
+/** `yt-dlp --version` prints the bare version token (`2026.08.19`) and nothing else. */
+async function readYtDlpVersion(binaryPath) {
+ const result = await readCommandOutput(binaryPath, ['--version'], VERSION_PROBE_TIMEOUT_MS);
+ if (!result.ok) return null;
+ return result.stdout.trim().split(/\r?\n/)[0]?.trim() || null;
+}
+
+/**
+ * Homebrew's view of the formula, or null when Homebrew doesn't have it (which
+ * includes "Homebrew isn't installed" — the same answer for this caller).
+ */
+async function readBrewInfo() {
+ const result = await readCommandOutput(
+ 'brew',
+ ['info', '--json=v2', '--formula', BREW_FORMULA],
+ BREW_INFO_TIMEOUT_MS,
+ );
+ if (!result.ok) return null;
+ return Promise.resolve()
+ .then(() => JSON.parse(result.stdout))
+ .then((payload) => {
+ const formula = payload?.formulae?.find((entry) => entry?.name === BREW_FORMULA);
+ if (!formula?.installed?.[0]) return null;
+ return {
+ installedVersion: String(formula.installed[0].version || '') || null,
+ latestVersion: formula.versions?.stable ? String(formula.versions.stable) : null,
+ outdated: formula.outdated === true,
+ pinned: formula.pinned === true,
+ linked: Boolean(formula.linked_keg),
+ };
+ })
+ .catch(() => null);
+}
+
+/**
+ * Confirm the yt-dlp on PATH really is Homebrew's linked keg.
+ *
+ * `brew info` reports that the formula is linked, not which executable PATH
+ * resolves — a pip or standalone install earlier on PATH coexists happily with
+ * a linked formula, and `brew upgrade` would then leave the *running* binary
+ * untouched. Canonicalize both sides so Homebrew's `bin` → `opt` → `Cellar`
+ * symlink chain compares equal.
+ */
+async function isHomebrewYtDlp(binaryPath) {
+ const prefix = await readCommandOutput('brew', ['--prefix', BREW_FORMULA], BREW_INFO_TIMEOUT_MS);
+ const prefixPath = prefix.ok ? prefix.stdout.trim().split(/\r?\n/)[0] : '';
+ if (!binaryPath || !prefixPath) return false;
+ const [active, brewed] = await Promise.all([
+ realpath(binaryPath).catch(() => null),
+ realpath(`${prefixPath}/bin/yt-dlp`).catch(() => null),
+ ]);
+ return Boolean(active && brewed && active === brewed);
+}
+
+// Latest published yt-dlp release, cached. GitHub's release API is
+// unauthenticated-rate-limited and this endpoint is hit on every Video
+// Downloader page load, so a steady-state UI must not ask it each time.
+// `version: null` is the not-fetched sentinel (distinct from a cached value); a
+// success holds for the long TTL, a failure backs off for the short one rather
+// than poisoning the cache forever or hammering.
+let latestReleaseCache = { version: null, fetchedAt: 0 };
+const LATEST_TTL_MS = 6 * 60 * 60 * 1000;
+const LATEST_ERROR_TTL_MS = 10 * 60 * 1000;
+
+/** Exported for tests — a module-level cache would otherwise leak across cases. */
+export function resetYtDlpLatestCache() {
+ latestReleaseCache = { version: null, fetchedAt: 0 };
+}
+
+async function getLatestYtDlpVersion() {
+ const age = Date.now() - latestReleaseCache.fetchedAt;
+ if (latestReleaseCache.version && age < LATEST_TTL_MS) return latestReleaseCache.version;
+ if (!latestReleaseCache.version && latestReleaseCache.fetchedAt && age < LATEST_ERROR_TTL_MS) return null;
+
+ const release = await fetch('https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest', {
+ headers: { 'User-Agent': 'PortOS', Accept: 'application/vnd.github+json' },
+ signal: AbortSignal.timeout(GITHUB_TIMEOUT_MS),
+ }).then((r) => (r.ok ? r.json() : null)).catch(() => null);
+ const version = release?.tag_name ? String(release.tag_name).trim() : null;
+ latestReleaseCache = { version, fetchedAt: Date.now() };
+ return version;
+}
+
+/**
+ * yt-dlp versions are zero-padded dates (`2026.08.19`, nightlies
+ * `2026.08.19.232702`), so a plain string comparison orders them correctly —
+ * and a nightly ahead of the latest stable tag is correctly reported as current
+ * rather than as an available "update" that would move the user backwards.
+ */
+const isNewer = (latest, installed) => Boolean(latest && installed && latest > installed);
+
+/**
+ * What the Video Downloader page needs to render the update row: which yt-dlp
+ * is on PATH, how old it is, and whether PortOS may update it for the user.
+ *
+ * Kept off the download path — it spends a `brew info` and (for non-Homebrew
+ * installs) a GitHub round-trip, neither of which a download should wait on.
+ */
+export async function getYtDlpUpdateStatus() {
+ const binaryPath = await findYtDlp();
+ if (!binaryPath) {
+ return {
+ installed: false,
+ path: null,
+ version: null,
+ latestVersion: null,
+ updateAvailable: false,
+ canUpdate: false,
+ method: null,
+ methodLabel: null,
+ updateCommand: null,
+ blockedReason: 'yt-dlp is not on PATH. Install it first — PortOS does not vendor it.',
+ downloadUrl: YTDLP_DOWNLOAD_URL,
+ };
+ }
+
+ const [version, brew] = await Promise.all([readYtDlpVersion(binaryPath), readBrewInfo()]);
+ const brewOwnsIt = Boolean(brew) && await isHomebrewYtDlp(binaryPath);
+
+ if (brewOwnsIt) {
+ // Homebrew's own `outdated` flag is authoritative — it compares against the
+ // formula the upgrade would actually install, which is what the button runs.
+ const blockedReason = brew.pinned
+ ? 'yt-dlp is pinned in Homebrew. Unpin it before asking PortOS to update it.'
+ : !brew.linked
+ ? 'Homebrew has yt-dlp installed but its keg is not linked. Link the formula before asking PortOS to update it.'
+ : null;
+ return {
+ installed: true,
+ path: binaryPath,
+ version: version || brew.installedVersion,
+ latestVersion: brew.latestVersion,
+ updateAvailable: brew.outdated,
+ canUpdate: blockedReason === null,
+ method: 'brew',
+ methodLabel: 'Homebrew',
+ updateCommand: 'brew upgrade yt-dlp',
+ blockedReason,
+ downloadUrl: YTDLP_DOWNLOAD_URL,
+ };
+ }
+
+ // Everything else — a standalone binary, pip, pipx — goes through yt-dlp's own
+ // `-U`, which updates a standalone binary in place and refuses a managed
+ // install with an accurate message naming the manager that owns it. PortOS
+ // can't tell those two apart reliably, and yt-dlp can, so it decides.
+ const latestVersion = await getLatestYtDlpVersion();
+ return {
+ installed: true,
+ path: binaryPath,
+ version,
+ latestVersion,
+ updateAvailable: isNewer(latestVersion, version),
+ canUpdate: true,
+ method: 'self',
+ methodLabel: 'yt-dlp self-update',
+ updateCommand: 'yt-dlp -U',
+ blockedReason: null,
+ downloadUrl: YTDLP_DOWNLOAD_URL,
+ };
+}
+
+/**
+ * Update yt-dlp in place, streaming the package manager's own output so the
+ * page can show progress on a `brew upgrade` that takes a minute.
+ *
+ * Never throws for an update failure — the caller turns the returned shape into
+ * a response. `version` is re-read afterwards so the UI reports what is on disk
+ * now rather than what the command claimed.
+ */
+export async function updateYtDlp({ onProgress = () => {} } = {}) {
+ const status = await getYtDlpUpdateStatus();
+ if (!status.installed) return { success: false, error: status.blockedReason };
+ if (!status.canUpdate) return { success: false, error: status.blockedReason };
+
+ const [command, args] = status.method === 'brew'
+ ? ['brew', ['upgrade', BREW_FORMULA]]
+ : [status.path, ['-U']];
+
+ onProgress({ event: 'progress', message: `Updating yt-dlp via ${status.methodLabel}…` });
+ const run = await runStreamingCommand(
+ command,
+ args,
+ (message) => onProgress({ event: 'progress', message }),
+ { timeoutMs: UPGRADE_TIMEOUT_MS },
+ );
+
+ if (!run.success) {
+ return {
+ success: false,
+ error: `yt-dlp update failed: ${run.error || `${status.methodLabel} reported an unknown error`}`,
+ };
+ }
+
+ // A Homebrew upgrade relinks the keg, which can move the binary PATH resolves
+ // — drop the discovery cache so the next download spawns the new one.
+ resetYtDlpCache();
+ resetYtDlpLatestCache();
+ const after = await getYtDlpUpdateStatus();
+ return {
+ success: true,
+ version: after.version,
+ previousVersion: status.version,
+ // A `brew upgrade` on an already-current formula and a `yt-dlp -U` with
+ // nothing to do both exit 0, so say so rather than implying a new build.
+ note: after.version && status.version && after.version === status.version
+ ? `already on ${after.version}`
+ : null,
+ };
+}
diff --git a/server/services/ytdlpUpdate.test.js b/server/services/ytdlpUpdate.test.js
new file mode 100644
index 0000000000..cd1f1a1014
--- /dev/null
+++ b/server/services/ytdlpUpdate.test.js
@@ -0,0 +1,143 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+// `fs/promises#realpath` decides whether the yt-dlp on PATH really is
+// Homebrew's keg, and the tests below need to answer for paths that don't exist
+// on the machine running them.
+vi.mock('fs/promises', () => ({ realpath: vi.fn(async (p) => p) }));
+vi.mock('../lib/bufferedSpawn.js', () => ({ bufferedSpawn: vi.fn() }));
+vi.mock('../lib/streamingSpawn.js', () => ({ runStreamingCommand: vi.fn(async () => ({ success: true })) }));
+vi.mock('../lib/ytdlp.js', () => ({ findYtDlp: vi.fn(), resetYtDlpCache: vi.fn() }));
+
+import { bufferedSpawn } from '../lib/bufferedSpawn.js';
+import { runStreamingCommand } from '../lib/streamingSpawn.js';
+import { findYtDlp } from '../lib/ytdlp.js';
+import { getYtDlpUpdateStatus, updateYtDlp, resetYtDlpLatestCache } from './ytdlpUpdate.js';
+
+const BREW_PREFIX = '/opt/homebrew/opt/yt-dlp';
+const BREW_BINARY = `${BREW_PREFIX}/bin/yt-dlp`;
+
+const brewPayload = (formula) => JSON.stringify({ formulae: [{ name: 'yt-dlp', ...formula }] });
+
+const ok = (stdout) => ({ success: true, stdout, stderr: '' });
+const fail = () => ({ success: false, stdout: '', stderr: '', code: 1 });
+
+/**
+ * Route each probe by the command it runs. `getYtDlpUpdateStatus` fires
+ * `yt-dlp --version`, `brew info` and `brew --prefix` — asserting on call order
+ * would pin an implementation detail (two of them run in parallel), so the
+ * double answers by question instead.
+ */
+function stubProbes({ version = '2026.07.04', brew = null, prefix = BREW_PREFIX } = {}) {
+ bufferedSpawn.mockImplementation(async (cmd, args) => {
+ if (args?.[0] === '--version') return ok(`${version}\n`);
+ if (cmd === 'brew' && args?.[0] === 'info') return brew ? ok(brewPayload(brew)) : fail();
+ if (cmd === 'brew' && args?.[0] === '--prefix') return prefix ? ok(`${prefix}\n`) : fail();
+ return fail();
+ });
+}
+
+const LINKED_CURRENT_BREW = { installed: [{ version: '2026.08.19' }], versions: { stable: '2026.08.19' }, linked_keg: '2026.08.19', outdated: false };
+
+describe('ytdlpUpdate', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetYtDlpLatestCache();
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({ tag_name: '2026.08.19' }) })));
+ });
+ afterEach(() => vi.unstubAllGlobals());
+
+ it('reports a missing binary as not installed and not updatable', async () => {
+ findYtDlp.mockResolvedValue(null);
+ const status = await getYtDlpUpdateStatus();
+ expect(status).toMatchObject({ installed: false, canUpdate: false, version: null });
+ expect(status.blockedReason).toMatch(/not on PATH/);
+ });
+
+ it('takes Homebrew\'s own outdated flag rather than comparing version strings', async () => {
+ // Homebrew writes the stable version unpadded (`2026.8.19`) while the binary
+ // prints `2026.07.04`, so a lexicographic comparison of the two reports the
+ // stale install as CURRENT. That is the exact live case this shipped for.
+ findYtDlp.mockResolvedValue(BREW_BINARY);
+ stubProbes({
+ version: '2026.07.04',
+ brew: { installed: [{ version: '2026.07.04' }], versions: { stable: '2026.8.19' }, linked_keg: '2026.07.04', outdated: true },
+ });
+ const status = await getYtDlpUpdateStatus();
+ expect(status).toMatchObject({ method: 'brew', updateAvailable: true, canUpdate: true, version: '2026.07.04' });
+ });
+
+ it('refuses a pinned Homebrew formula and names why', async () => {
+ findYtDlp.mockResolvedValue(BREW_BINARY);
+ stubProbes({ brew: { ...LINKED_CURRENT_BREW, pinned: true, outdated: true } });
+ const status = await getYtDlpUpdateStatus();
+ expect(status.canUpdate).toBe(false);
+ expect(status.blockedReason).toMatch(/pinned/);
+ });
+
+ it('falls back to yt-dlp -U when the binary on PATH is not the Homebrew keg', async () => {
+ // A pip or standalone install earlier on PATH coexists with a linked
+ // formula; `brew upgrade` would leave the binary that actually runs alone.
+ findYtDlp.mockResolvedValue('/usr/local/bin/yt-dlp');
+ stubProbes({ brew: LINKED_CURRENT_BREW });
+ const status = await getYtDlpUpdateStatus();
+ expect(status).toMatchObject({ method: 'self', updateCommand: 'yt-dlp -U', canUpdate: true });
+ });
+
+ it('compares the GitHub release tag against the installed version on the self-update path', async () => {
+ findYtDlp.mockResolvedValue('/usr/local/bin/yt-dlp');
+ stubProbes({ version: '2026.07.04', brew: null });
+ expect(await getYtDlpUpdateStatus()).toMatchObject({ latestVersion: '2026.08.19', updateAvailable: true });
+ });
+
+ it('does not offer a downgrade to a nightly ahead of the latest stable tag', async () => {
+ findYtDlp.mockResolvedValue('/usr/local/bin/yt-dlp');
+ stubProbes({ version: '2026.08.19.232702', brew: null });
+ expect(await getYtDlpUpdateStatus()).toMatchObject({ updateAvailable: false });
+ });
+
+ it('runs brew upgrade for a Homebrew install and reports the new version', async () => {
+ findYtDlp.mockResolvedValue(BREW_BINARY);
+ const stale = { installed: [{ version: '2026.07.04' }], versions: { stable: '2026.8.19' }, linked_keg: '2026.07.04', outdated: true };
+ stubProbes({ version: '2026.07.04', brew: stale });
+ // The post-upgrade status re-reads the binary, which is how the caller
+ // learns what actually landed rather than what the command claimed.
+ runStreamingCommand.mockImplementationOnce(async () => {
+ stubProbes({ version: '2026.08.19', brew: { ...stale, installed: [{ version: '2026.08.19' }], linked_keg: '2026.08.19', outdated: false } });
+ return { success: true };
+ });
+
+ const result = await updateYtDlp();
+ expect(runStreamingCommand).toHaveBeenCalledWith('brew', ['upgrade', 'yt-dlp'], expect.any(Function), expect.any(Object));
+ expect(result).toMatchObject({ success: true, version: '2026.08.19', previousVersion: '2026.07.04', note: null });
+ });
+
+ it('runs yt-dlp -U for a non-Homebrew install', async () => {
+ findYtDlp.mockResolvedValue('/usr/local/bin/yt-dlp');
+ stubProbes({ brew: null });
+ await updateYtDlp();
+ expect(runStreamingCommand).toHaveBeenCalledWith('/usr/local/bin/yt-dlp', ['-U'], expect.any(Function), expect.any(Object));
+ });
+
+ // Both `brew upgrade` on a current formula and `yt-dlp -U` with nothing to do
+ // exit 0, so a success that moved nothing must not imply a new build landed.
+ it('says "already on" when the version did not move', async () => {
+ findYtDlp.mockResolvedValue('/usr/local/bin/yt-dlp');
+ stubProbes({ version: '2026.08.19', brew: null });
+ expect(await updateYtDlp()).toMatchObject({ success: true, note: 'already on 2026.08.19' });
+ });
+
+ it('returns a failed upgrade rather than throwing out of the child-process boundary', async () => {
+ findYtDlp.mockResolvedValue('/usr/local/bin/yt-dlp');
+ stubProbes({ brew: null });
+ runStreamingCommand.mockResolvedValueOnce({ success: false, error: 'exit 1: network unreachable' });
+ const result = await updateYtDlp();
+ expect(result.success).toBe(false);
+ expect(result.error).toMatch(/network unreachable/);
+ });
+
+ it('refuses to update a binary that is not installed', async () => {
+ findYtDlp.mockResolvedValue(null);
+ expect(await updateYtDlp()).toMatchObject({ success: false });
+ expect(runStreamingCommand).not.toHaveBeenCalled();
+ });
+});