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
fix([pipeline-audio-phase-4c-2-4c-3-4d-2-local-oss]): address codex+claude review
[._.]/ Adam Eivy4fccaa8f15f6
diff --git a/client/src/components/pipeline/stages/AudioStage.jsx b/client/src/components/pipeline/stages/AudioStage.jsxindex b79acb8ff4..858bf3bbe8 100644--- a/client/src/components/pipeline/stages/AudioStage.jsx+++ b/client/src/components/pipeline/stages/AudioStage.jsx@@ -91,7 +91,8 @@ export default function AudioStage({ issue, onStageUpdate }) {const openGenPanel = async () => {setGenPanelOpen(true);if (generators === null) {- const result = await listPipelineMusicGenerators().catch((err) => {+ // Owns its own error toast → silent so the helper doesn't double-toast.+ const result = await listPipelineMusicGenerators({ silent: true }).catch((err) => {toast.error(err.message || 'Failed to load generators');return null;});@@ -552,7 +553,14 @@ export default function AudioStage({ issue, onStageUpdate }) {max={generators.maxDurationSec ?? 30}step="1"value={genDuration}- onChange={(e) => setGenDuration(Number(e.target.value))}+ onChange={(e) => {+ // Clamp to the server's accepted range so a blank/typed+ // out-of-range value can't 400 on Generate. NaN → default.+ const min = generators.minDurationSec ?? 1;+ const max = generators.maxDurationSec ?? 30;+ const n = Number(e.target.value);+ setGenDuration(Number.isFinite(n) ? Math.max(min, Math.min(max, n)) : (generators.defaultDurationSec ?? 12));+ }}className="w-24 px-2 py-1.5 bg-port-card border border-port-border rounded text-white text-sm"/></div>diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex 2848de40a4..de38997a56 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -620,8 +620,8 @@ export const deletePipelineMusicTrack = (filename) =>// Returns { models, defaultModelId, defaultDurationSec, minDurationSec,// maxDurationSec, ready }. `ready=false` → show the install hint instead of// the prompt box.-export const listPipelineMusicGenerators = () =>- request('/pipeline/audio/music/generators');+export const listPipelineMusicGenerators = (options = {}) =>+ request('/pipeline/audio/music/generators', options);// Generate a background-music track with MusicGen (MLX) and attach it to the// issue (source: 'gen'). Long-running (~tens of seconds); callers own a busydiff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.shindex aa8fe6c43c..1d3bdfe77a 100755--- a/scripts/setup-image-video.sh+++ b/scripts/setup-image-video.sh@@ -313,19 +313,25 @@ if [[ "$INSTALL_MUSICGEN" == "1" ]]; then"$MUSICGEN_PY" -m pip install --upgrade pip wheel setuptools >/dev/null# mlx + numpy run the model; transformers (<5 for MLX compat) + sentencepiece# provide the T5 text conditioner's tokenizer; scipy is imported by the- # mlx-examples musicgen utils. We write WAV via the stdlib `wave` module in- # the sidecar, so no soundfile dependency.+ # mlx-examples musicgen utils. torch is required because MusicGen.from_pretrained+ # loads the upstream PyTorch checkpoints (torch.load) before converting to MLX —+ # without it generation fails at model-load even though the class imports fine.+ # We write WAV via the stdlib `wave` module in the sidecar, so no soundfile dep."$MUSICGEN_PY" -m pip install --upgrade \mlx \numpy \+ torch \"transformers<5" \sentencepiece \"huggingface_hub[hf_xet]" \scipy+ # Verify BOTH that the class imports AND that torch loaded — the import alone+ # passed even when torch was missing, so install used to report ready and+ # then fail on the first generation.if ! PORTOS_MUSICGEN_RUNTIME_DIR="${MLX_EXAMPLES_DIR}/musicgen" \- "$MUSICGEN_PY" -c "import sys, os; sys.path.insert(0, os.environ['PORTOS_MUSICGEN_RUNTIME_DIR']); from musicgen import MusicGen" 2>/dev/null; then- echo "❌ MusicGen venv built but 'from musicgen import MusicGen' failed." >&2- echo " Check that ${MLX_EXAMPLES_DIR}/musicgen exists and the clone is intact." >&2+ "$MUSICGEN_PY" -c "import sys, os, torch; sys.path.insert(0, os.environ['PORTOS_MUSICGEN_RUNTIME_DIR']); from musicgen import MusicGen" 2>/dev/null; then+ echo "❌ MusicGen venv built but 'import torch; from musicgen import MusicGen' failed." >&2+ echo " Check that ${MLX_EXAMPLES_DIR}/musicgen exists and torch installed cleanly." >&2exit 1fiecho "✅ MusicGen venv ready: $MUSICGEN_PY (runtime: ${MLX_EXAMPLES_DIR}/musicgen @ ${MLX_EXAMPLES_PIN:0:12})"diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex 150d78d394..5aece2f154 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -912,7 +912,6 @@ const musicGenerateSchema = z.object({prompt: z.string().trim().min(1).max(800),durationSec: z.number().min(MIN_DURATION_SEC).max(MAX_DURATION_SEC).optional(),modelId: z.enum(MUSICGEN_MODELS.map((m) => m.id)).optional(),- label: z.string().trim().max(200).nullable().optional(),});router.post('/issues/:id/stages/audio/music/generate', asyncHandler(async (req, res) => {const body = validateRequest(musicGenerateSchema, req.body ?? {});@@ -926,13 +925,12 @@ router.post('/issues/:id/stages/audio/music/generate', asyncHandler(async (req,durationSec: body.durationSec ?? DEFAULT_DURATION_SEC,modelId: body.modelId ?? DEFAULT_MUSICGEN_MODEL_ID,}).catch((err) => { throw mapServiceError(err); });- const label = body.label?.trim() || gen.model;const { issue: updatedIssue, stage } = await issuesSvc.updateStageWithLatest(req.params.id,'audio',(current) => ({status: audioStatusAfterMusicChange(current),- music: { source: MUSIC_SOURCE.GEN, trackFilename: gen.filename, label },+ music: { source: MUSIC_SOURCE.GEN, trackFilename: gen.filename, label: gen.model },errorMessage: '',}),).catch((err) => { throw mapServiceError(err); });diff --git a/server/services/pipeline/audioMux.js b/server/services/pipeline/audioMux.jsindex d887d5eac6..78af20ef54 100644--- a/server/services/pipeline/audioMux.js+++ b/server/services/pipeline/audioMux.js@@ -22,6 +22,11 @@* video's audio track rather than mixing under it. AI-gen clips are silent* today, but LTX-2 audio-to-video can carry a clip soundtrack — preserving +* ducking that under VO is tracked as a follow-up in PLAN.md.+ *+ * ffmpeg floor: the VO graph uses `amix ... normalize=0` + `sidechaincompress`+ * (ffmpeg 4.4+, 2021). On an older ffmpeg `muxVoLines` returns ok:false and the+ * CD stitch falls back to `muxMusicBed`, which uses only `aresample`/`aformat`+ * and works on every ffmpeg — so the fallback is never broken on the same host.*/import { join } from 'path';@@ -164,10 +169,19 @@ export function buildVoMuxArgs({ inputVideoPath, voLines, musicPath, musicGain =if (musicPath) {const musicIdx = voLines.length + 1;const gain = Number(musicGain).toFixed(3);- chains.push(`${voMixLabel}asplit=2[vosc][vomain]`);+ chains.push(`${voMixLabel}asplit=2[voscraw][vomain]`);+ // Pad the sidechain *key* to infinity (silence after the last VO line).+ // sidechaincompress ends with its shortest input, so a finite VO key would+ // cut the ducked bed off at the last line — the music would vanish for the+ // rest of the episode. With an infinite (silence-padded) key, the bed runs+ // the full video length: ducked under dialogue, full-level in the gaps.+ chains.push(`[voscraw]apad[vosc]`);chains.push(`[${musicIdx}:a]volume=${gain},${AFMT}[bed]`);chains.push(`[bed][vosc]sidechaincompress=threshold=${duck.threshold}:ratio=${duck.ratio}:attack=${duck.attack}:release=${duck.release}[ducked]`);- chains.push(`[ducked][vomain]amix=inputs=2:normalize=0,apad[aout]`);+ // `[vomain]` is the finite VO; `[ducked]` is bed-length (infinite via the+ // looped music). amix=longest keeps the bed past the VO; -shortest then+ // pins the whole output to the video length.+ chains.push(`[ducked][vomain]amix=inputs=2:normalize=0[aout]`);} else {chains.push(`${voMixLabel}apad[aout]`);}diff --git a/server/services/pipeline/audioMux.test.js b/server/services/pipeline/audioMux.test.jsindex 21676feb53..004e0e99ce 100644--- a/server/services/pipeline/audioMux.test.js+++ b/server/services/pipeline/audioMux.test.js@@ -236,11 +236,14 @@ describe('buildVoMuxArgs', () => {// music is the looped last input (index 2 here: video=0, vo=1, music=2)expect(args).toContain('-stream_loop');const filter = args[args.indexOf('-filter_complex') + 1];- expect(filter).toContain('asplit=2[vosc][vomain]');+ expect(filter).toContain('asplit=2[voscraw][vomain]');expect(filter).toContain('[2:a]volume=0.400');expect(filter).toContain('sidechaincompress=threshold=');expect(filter).toContain('[bed][vosc]sidechaincompress');- expect(filter).toContain('[ducked][vomain]amix=inputs=2:normalize=0,apad[aout]');+ expect(filter).toContain('[ducked][vomain]amix=inputs=2:normalize=0[aout]');+ // The sidechain KEY must be padded to infinity so the music bed survives+ // past the last VO line (sidechaincompress ends with its shortest input).+ expect(filter).toContain('[voscraw]apad[vosc]');});it('uses a single VO label without amix for one line', () => {diff --git a/server/services/pipeline/musicGen.js b/server/services/pipeline/musicGen.jsindex b34b972522..b8c2bbeeb7 100644--- a/server/services/pipeline/musicGen.js+++ b/server/services/pipeline/musicGen.js@@ -20,6 +20,8 @@*/import { spawn } from 'child_process';+import { existsSync, statSync } from 'fs';+import { unlink } from 'fs/promises';import { join, dirname } from 'path';import { fileURLToPath } from 'url';import { randomUUID } from 'crypto';@@ -140,15 +142,23 @@ export async function generateMusic({ prompt, durationSec = DEFAULT_DURATION_SEC// anonymous HF rate limits.const env = safeChildProcessEnv(await hfTokenEnv());const result = await runMusicGenProcess({ bin, args, env, signal });- if (!result.ok) {- throw new ServerError(`Music generation failed: ${result.reason}`, {+ // A clean exit isn't enough — the sidecar could exit 0 yet write nothing (or+ // a truncated file) if the runtime changes shape. Require both a parsed+ // RESULT line AND a non-empty file on disk before we persist the library+ // pointer; otherwise unlink the partial and fail, so the audio stage never+ // attaches a dangling/empty track.+ const parsed = result.ok ? parseResultLine(result.stdout) : null;+ const wroteFile = existsSync(outputPath) && statSync(outputPath).size > 0;+ if (!result.ok || !parsed || !wroteFile) {+ await unlink(outputPath).catch(() => {});+ const reason = !result.ok ? result.reason : (!wroteFile ? 'sidecar wrote no audio' : 'sidecar returned no result');+ throw new ServerError(`Music generation failed: ${reason}`, {status: 500, code: 'PIPELINE_MUSIC_GEN_FAILED',});}- const parsed = parseResultLine(result.stdout);return {filename,- durationSec: Number.isFinite(parsed?.durationSec) ? parsed.durationSec : clampDuration(durationSec),+ durationSec: Number.isFinite(parsed.durationSec) ? parsed.durationSec : clampDuration(durationSec),modelId: model.id,model: model.name,};