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

surface yt-dlp's real error instead of a bare "yt-dlp exited 1"

[._.]/ Adam Eivy9abdf2de8274
diff --git a/server/services/ytdlpAudioImport.js b/server/services/ytdlpAudioImport.js
index 7acb21f45c..eb39b958f7 100644
--- a/server/services/ytdlpAudioImport.js
+++ b/server/services/ytdlpAudioImport.js
@@ -29,7 +29,7 @@ import { join, dirname } from 'path';
import { ServerError } from '../lib/errorHandler.js';
import { findFfmpeg } from '../lib/ffmpeg.js';
import { findYtDlp } from '../lib/ytdlp.js';
-import { runYtDlp, ytdlpMarkerArgs } from './ytdlpRun.js';
+import { runYtDlp, ytdlpMarkerArgs, describeYtDlpFailure } from './ytdlpRun.js';
/**
* Locate yt-dlp + ffmpeg, throwing an actionable ServerError if either is
@@ -109,11 +109,14 @@ export async function downloadAudioToTempMp3({
// A --match-filters/--max-filesize rejection exits 0 with no output file
// (yt-dlp treats a filtered-out video as "nothing to do", not an error) —
// `--print`'s suppression of normal reporting (see ytdlpRun) means the
- // specific reason never reaches our stdout/stderr parsing, so name the two
- // known bounds explicitly rather than a bare exit code.
+ // specific reason often never reaches our stdout/stderr parsing, so name the
+ // two known bounds. Only those bounds are ours: describeYtDlpFailure owns
+ // the prose and appends whatever yt-dlp did print, which outranks the guess.
const reason = exit.code === 0
- ? `no audio was produced — the source may be longer than ${Math.round(maxDurationSec / 60)} minutes or its audio larger than ${Math.round(maxBytes / 1024 / 1024)}MB, or it may be otherwise unavailable`
- : (exit.reason || `yt-dlp exited ${exit.code}`);
+ ? describeYtDlpFailure(exit.code, exit.output, {
+ fallback: `no audio was produced — the source may be longer than ${Math.round(maxDurationSec / 60)} minutes or its audio larger than ${Math.round(maxBytes / 1024 / 1024)}MB, or it may be otherwise unavailable`,
+ })
+ : exit.reason; // always populated for a non-zero exit (see runYtDlp)
await cleanupYtDlpTemp(tempPrefix);
return { outcome: 'failed', reason };
}
diff --git a/server/services/ytdlpRun.js b/server/services/ytdlpRun.js
index 64c9386035..99db1c9fea 100644
--- a/server/services/ytdlpRun.js
+++ b/server/services/ytdlpRun.js
@@ -21,7 +21,7 @@
import { spawn } from '../lib/childProcess.js';
import { safeChildProcessOptions } from '../lib/processEnv.js';
-import { createLineReader } from '../lib/streamLines.js';
+import { createLineReader, createOutputTail } from '../lib/streamLines.js';
/**
* The wire protocol between our `--progress-template`/`--print` flags and the
@@ -61,6 +61,45 @@ export const ytdlpMarkerArgs = (postprocessStage) => [
'--progress',
];
+/**
+ * YouTube gates its media URLs behind a player-client / PO-token handshake that
+ * yt-dlp tracks release-to-release, so a binary only weeks out of date reports a
+ * video the browser plays fine as a flat `HTTP Error 403: Forbidden`. That is
+ * the most common cause of a failed download here and it is invisible from the
+ * message alone, so name the remedy rather than leaving the user to re-try.
+ *
+ * Every alternative below must be diagnostic of THAT class, or the hint sends
+ * the user to the one action that cannot help. Deliberately excluded: a bare
+ * `Forbidden` (any site's 403 — the x.com login-wall/rate-limit path returns
+ * one, and `HTTP Error 403` already covers the YouTube case) and `Sign in to
+ * confirm` (YouTube's bot check, whose remedy is cookies, not an upgrade).
+ */
+const STALE_YTDLP_SIGNATURE = /HTTP Error 403|PO Token|nsig|Failed to extract any player response/i;
+
+const STALE_YTDLP_HINT = 'the installed yt-dlp is likely out of date for YouTube\'s current player — update it (`yt-dlp -U`, or `brew upgrade yt-dlp`) and retry';
+
+/**
+ * Compose the user-facing reason for a failed yt-dlp run.
+ *
+ * Exported because both importers need it for the case the runner cannot
+ * describe — a clean exit that produced no file — and because the prose is
+ * worth pinning by a unit test rather than only through a spawn.
+ *
+ * @param {number|null} code Exit code (null when the binary never started).
+ * @param {string} output Recent yt-dlp output (the tail).
+ * @param {string} [o.fallback] The caller's own account of the failure, for
+ * a run that exited 0 and still produced nothing: only the caller knows which
+ * of its bounds was tripped. yt-dlp's own words outrank a guess, so they are
+ * appended to it whenever there are any.
+ */
+export function describeYtDlpFailure(code, output, { fallback } = {}) {
+ const said = (output || '').trim();
+ const base = fallback
+ ? [fallback, said].filter(Boolean).join(' — yt-dlp said: ')
+ : (said ? `yt-dlp failed: ${said}` : `yt-dlp exited ${code}`);
+ return STALE_YTDLP_SIGNATURE.test(said) ? `${base} — ${STALE_YTDLP_HINT}` : base;
+}
+
/**
* Spawn yt-dlp, stream its markers to `onProgress`, and classify the exit.
*
@@ -69,15 +108,23 @@ export const ytdlpMarkerArgs = (postprocessStage) => [
* @param {string[]} opts.args Fully-built argv (marker args included).
* @param {function} opts.onProgress ({ percent, stage }) => void — SSE-agnostic.
* @param {function} opts.registerProcess (proc|null) => void — lets the caller wire cancel.
- * @returns {Promise<{ canceled:boolean, code:number|null, signal:string|null, reason:string|null, title:string }>}
- * `canceled` is true when the child died on SIGTERM/SIGKILL. `reason` carries
- * the spawn-failure message when the binary never started, else null.
+ * @returns {Promise<{ canceled:boolean, code:number|null, signal:string|null, reason:string|null, title:string, output:string }>}
+ * `canceled` is true when the child died on SIGTERM/SIGKILL. `reason` is the
+ * user-facing failure prose for any non-zero exit — the spawn-failure message
+ * when the binary never started, else what yt-dlp printed (see
+ * `describeYtDlpFailure`) — and null on a clean exit. `output` is the raw tail
+ * of non-marker output, for callers that compose their own reason.
*/
export async function runYtDlp({ ytDlp, args, onProgress, registerProcess }) {
const proc = spawn(ytDlp, args, safeChildProcessOptions({ stdio: ['ignore', 'pipe', 'pipe'] }));
registerProcess(proc);
let title = '';
+ // Recent non-marker output, kept so a non-zero exit reports what yt-dlp said
+ // instead of just its exit code. Marker lines are our own protocol and each
+ // branch below returns, so progress spam never evicts the `ERROR:` line from
+ // the tail's budget.
+ const tail = createOutputTail();
const onLine = (line) => {
if (line.startsWith(YTDLP_MARKERS.TITLE)) {
title = line.slice(YTDLP_MARKERS.TITLE.length).trim();
@@ -90,7 +137,9 @@ export async function runYtDlp({ ytDlp, args, onProgress, registerProcess }) {
}
if (line.startsWith(YTDLP_MARKERS.STAGE)) {
onProgress({ percent: 100, stage: line.slice(YTDLP_MARKERS.STAGE.length) });
+ return;
}
+ tail.remember(line);
};
// Separate readers per stream — stdout and stderr chunks arrive
// independently, so a shared buffer can complete a partial line from one
@@ -113,14 +162,17 @@ export async function runYtDlp({ ytDlp, args, onProgress, registerProcess }) {
return { canceled: true, code: exit.code ?? null, signal: exit.signal, reason: null, title };
}
// Flush any final line the child wrote without a trailing newline before exit.
+ // yt-dlp's `ERROR:` line is often exactly that last line, so flushing has to
+ // happen BEFORE the tail is read or the failure reason loses its cause.
stdoutReader.flush();
stderrReader.flush();
- return {
- canceled: false,
- code: exit.code ?? null,
- signal: exit.signal ?? null,
- reason: exit.reason ?? null,
- title,
- };
+ const code = exit.code ?? null;
+ const output = tail.text();
+ // Exit 0 keeps `reason: null` — the caller owns the "exited 0 but produced
+ // nothing" case, where the bound that was tripped is knowable only to it. A
+ // spawn failure has no output to explain it, so its own message stands.
+ const reason = code === 0 ? null : (exit.reason ?? describeYtDlpFailure(code, output));
+
+ return { canceled: false, code, signal: exit.signal ?? null, reason, title, output };
}
diff --git a/server/services/ytdlpRun.test.js b/server/services/ytdlpRun.test.js
index 6a4985b30e..16c7b1093c 100644
--- a/server/services/ytdlpRun.test.js
+++ b/server/services/ytdlpRun.test.js
@@ -12,7 +12,7 @@ import { EventEmitter } from 'events';
vi.mock('../lib/childProcess.js', async (importOriginal) => ({ ...(await importOriginal()), spawn: vi.fn() }));
const { spawn } = await import('../lib/childProcess.js');
-const { runYtDlp, ytdlpMarkerArgs, YTDLP_MARKERS } = await import('./ytdlpRun.js');
+const { runYtDlp, ytdlpMarkerArgs, YTDLP_MARKERS, describeYtDlpFailure } = await import('./ytdlpRun.js');
/**
* A fake yt-dlp child. `script` is a list of `[stream, chunk]` pairs written in
@@ -49,6 +49,56 @@ describe('ytdlpMarkerArgs', () => {
});
});
+describe('describeYtDlpFailure', () => {
+ it('names the stale-binary remedy for the YouTube gating class', () => {
+ // A 403 on media URLs is what a yt-dlp that has fallen behind YouTube's
+ // player handshake reports for a video the browser plays fine; without the
+ // hint the user has a real message and still no next step.
+ const reason = describeYtDlpFailure(1, 'ERROR: unable to download video data: HTTP Error 403: Forbidden');
+ expect(reason).toContain('HTTP Error 403: Forbidden');
+ expect(reason).toMatch(/yt-dlp -U/);
+ });
+
+ it('leaves an unrelated failure without the upgrade hint', () => {
+ const reason = describeYtDlpFailure(1, 'ERROR: Video unavailable');
+ expect(reason).toBe('yt-dlp failed: ERROR: Video unavailable');
+ expect(reason).not.toMatch(/yt-dlp -U/);
+ });
+
+ // Two failures that LOOK like the stale-player class and are not. Advising an
+ // upgrade for either sends the user to the one action that cannot help, so the
+ // exclusions are pinned rather than left to the regex's shape.
+ it('does not advise an upgrade for YouTube\'s bot check, whose remedy is cookies', () => {
+ const reason = describeYtDlpFailure(1, 'ERROR: Sign in to confirm you are not a bot');
+ expect(reason).not.toMatch(/yt-dlp -U/);
+ });
+
+ it('does not advise an upgrade for a non-YouTube 403', () => {
+ const reason = describeYtDlpFailure(1, 'ERROR: unable to download: Forbidden (rate-limited)');
+ expect(reason).not.toMatch(/yt-dlp -U/);
+ });
+
+ it('falls back to the exit code when there is no output', () => {
+ expect(describeYtDlpFailure(2, ' ')).toBe('yt-dlp exited 2');
+ });
+
+ describe('with a caller fallback (a clean exit that produced nothing)', () => {
+ it('appends what yt-dlp printed to the caller\'s guess', () => {
+ const reason = describeYtDlpFailure(0, 'ERROR: boom', { fallback: 'no video was produced' });
+ expect(reason).toBe('no video was produced — yt-dlp said: ERROR: boom');
+ });
+
+ it('uses the guess alone when yt-dlp printed nothing', () => {
+ expect(describeYtDlpFailure(0, '', { fallback: 'no video was produced' })).toBe('no video was produced');
+ });
+
+ it('still names the upgrade remedy when the printed cause is the gating class', () => {
+ const reason = describeYtDlpFailure(0, 'ERROR: HTTP Error 403: Forbidden', { fallback: 'no video was produced' });
+ expect(reason).toMatch(/yt-dlp -U/);
+ });
+ });
+});
+
describe('runYtDlp — marker parsing', () => {
it('emits one progress frame for a marker split across two stdout chunks', async () => {
const seen = [];
@@ -106,11 +156,52 @@ describe('runYtDlp — exit classification', () => {
await expect(runYtDlp(baseArgs)).resolves.toMatchObject({ canceled: true, signal: 'SIGTERM' });
});
- it('passes a non-zero exit code through without a reason', async () => {
+ it('falls back to the exit code when yt-dlp printed nothing', async () => {
spawn.mockReturnValue(fakeChild({ code: 1 }));
- await expect(runYtDlp(baseArgs)).resolves.toMatchObject({ canceled: false, code: 1, reason: null });
+ await expect(runYtDlp(baseArgs)).resolves.toMatchObject({
+ canceled: false, code: 1, reason: 'yt-dlp exited 1',
+ });
+ });
+
+ // The reported bug: a real 403 reached the user as a bare "yt-dlp exited 1"
+ // because stderr was read for markers and then dropped.
+ it('reports what yt-dlp printed to stderr rather than just the exit code', async () => {
+ spawn.mockReturnValue(fakeChild({
+ code: 1,
+ script: [['stderr', 'ERROR: unable to download video data: HTTP Error 403: Forbidden\n']],
+ }));
+ const result = await runYtDlp(baseArgs);
+ expect(result.reason).toContain('HTTP Error 403: Forbidden');
+ expect(result.reason).not.toBe('yt-dlp exited 1');
+ });
+
+ it('flushes an unterminated final stderr line into the failure reason', async () => {
+ // yt-dlp's ERROR line is frequently the last thing written, with no newline.
+ spawn.mockReturnValue(fakeChild({ code: 1, script: [['stderr', 'ERROR: Video unavailable']] }));
+ const result = await runYtDlp(baseArgs);
+ expect(result.reason).toContain('Video unavailable'); // prose itself is pinned above
+
+ });
+
+ it('keeps our own marker lines out of the failure reason', async () => {
+ spawn.mockReturnValue(fakeChild({
+ code: 1,
+ script: [['stdout', 'PORTOS_TITLE:Example Clip\nPORTOS_PROGRESS: 12.0%\n'], ['stderr', 'ERROR: boom\n']],
+ }));
+ const result = await runYtDlp(baseArgs);
+ expect(result.reason).toBe('yt-dlp failed: ERROR: boom');
+ expect(result.output).not.toContain('PORTOS_');
+ });
+
+ it('leaves reason null on a clean exit so the caller owns the "produced nothing" case', async () => {
+ spawn.mockReturnValue(fakeChild({ code: 0, script: [['stderr', 'WARNING: something benign\n']] }));
+ const result = await runYtDlp(baseArgs);
+ expect(result.reason).toBeNull();
+ expect(result.output).toContain('WARNING: something benign');
});
+ // Also pins that a spawn failure keeps its own message rather than falling
+ // through to the empty-output `yt-dlp exited null`.
it('reports a spawn failure as a reason rather than throwing', async () => {
const proc = new EventEmitter();
proc.stdout = new EventEmitter();
diff --git a/server/services/ytdlpVideoImport.js b/server/services/ytdlpVideoImport.js
index f2a4a392f6..747404ee2d 100644
--- a/server/services/ytdlpVideoImport.js
+++ b/server/services/ytdlpVideoImport.js
@@ -20,7 +20,7 @@
import { readdir, unlink } from 'fs/promises';
import { join, dirname } from 'path';
import { ensureDir } from '../lib/fileUtils.js';
-import { runYtDlp, ytdlpMarkerArgs } from './ytdlpRun.js';
+import { runYtDlp, ytdlpMarkerArgs, describeYtDlpFailure } from './ytdlpRun.js';
/**
* Locate the final produced file for a download prefix. yt-dlp writes
@@ -121,10 +121,14 @@ export async function downloadVideoToDir({
// 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 known bounds. x.com/Twitter
- // downloads also fail here on login-walled/rate-limited content.
+ // downloads also fail here on login-walled/rate-limited content. Only the
+ // bounds are ours; describeYtDlpFailure owns the prose and appends whatever
+ // yt-dlp actually printed, which outranks the guess.
const reason = exit.code === 0
- ? `no video was produced — it may be longer than ${Math.round(maxDurationSec / 60)} minutes or larger than ${Math.round(maxBytes / 1024 / 1024 / 1024)}GB, or (for x.com) login-walled, rate-limited, or otherwise unavailable`
- : (exit.reason || `yt-dlp exited ${exit.code}`);
+ ? describeYtDlpFailure(exit.code, exit.output, {
+ fallback: `no video was produced — it may be longer than ${Math.round(maxDurationSec / 60)} minutes or larger than ${Math.round(maxBytes / 1024 / 1024 / 1024)}GB, or (for x.com) login-walled, rate-limited, or otherwise unavailable`,
+ })
+ : exit.reason; // always populated for a non-zero exit (see runYtDlp)
await cleanupProducedFiles(filePrefix, outDir);
return { outcome: 'failed', reason };
}