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: queue Music Studio renders and add processing widget (#4353)

[._.]/ Adam Eivyf00790163724
diff --git a/.changelog/next/fixed-issue-4353.md b/.changelog/next/fixed-issue-4353.md
new file mode 100644
index 0000000000..609ddb25a0
--- /dev/null
+++ b/.changelog/next/fixed-issue-4353.md
@@ -0,0 +1 @@
+- Music Studio renders now persist through the media queue and remain visible in dashboard processing status.
diff --git a/client/src/components/dashboard/ActiveProcessingWidget.jsx b/client/src/components/dashboard/ActiveProcessingWidget.jsx
new file mode 100644
index 0000000000..afc1d5f53d
--- /dev/null
+++ b/client/src/components/dashboard/ActiveProcessingWidget.jsx
@@ -0,0 +1,53 @@
+import { memo } from 'react';
+import { Link } from 'react-router';
+import { Cpu, ExternalLink, X } from 'lucide-react';
+import * as api from '../../services/api';
+import { useAutoRefetch } from '../../hooks/useAutoRefetch';
+
+const elapsed = (startedAt, now = Date.now()) => {
+ if (!startedAt) return 'queued';
+ const seconds = Math.max(0, Math.floor((now - Date.parse(startedAt)) / 1000));
+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;
+};
+const eta = (etaMs) => (Number.isFinite(etaMs) && etaMs >= 0 ? `~${Math.ceil(etaMs / 60000)}m` : null);
+
+function JobRow({ job, onCancel }) {
+ const tag = job.params?.musicStudio;
+ const label = tag?.title || job.params?.characterName || `${job.kind} render`;
+ const target = tag?.trackId ? `/music/tracks/${encodeURIComponent(tag.trackId)}` : null;
+ return (
+ <div className="flex items-center gap-2 rounded-lg border border-port-border bg-port-bg/60 px-2 py-1.5 text-xs">
+ <span className={`h-2 w-2 rounded-full ${job.status === 'running' ? 'bg-port-accent animate-pulse' : 'bg-port-warning'}`} aria-hidden="true" />
+ <span className="min-w-0 flex-1 truncate text-gray-200">{label}</span>
+ <span className="shrink-0 font-mono text-gray-500">{job.status === 'queued' ? `#${job.position || '—'}` : elapsed(job.startedAt)}{eta(job.etaMs) ? ` · ${eta(job.etaMs)}` : ''}</span>
+ {target ? <Link to={target} title="Open track" className="text-gray-500 hover:text-port-accent"><ExternalLink size={13} /></Link> : null}
+ <button type="button" onClick={() => onCancel(job.id)} title="Cancel render" className="text-gray-500 hover:text-port-warning"><X size={13} /></button>
+ </div>
+ );
+}
+
+function ActiveProcessingWidget() {
+ const { data, loading } = useAutoRefetch(() => api.getActiveProcessing({ silent: true }), 3000, {
+ compare: (a, b) => a?.updatedAt === b?.updatedAt,
+ });
+ const cancel = (id) => api.cancelMediaJob(id, { silent: true }).catch(() => undefined);
+ const jobs = data?.jobs || [];
+ const gpu = data?.gpu;
+ const idle = !jobs.length && !(data?.extras?.imageTo3d || []).length && !(data?.agents?.active || 0);
+ return (
+ <div className="h-full rounded-xl border border-port-border bg-port-card p-4">
+ <div className="mb-3 flex items-center justify-between">
+ <h3 className="flex items-center gap-2 text-sm font-semibold text-white"><Cpu size={15} className="text-port-accent" /> Active Processing</h3>
+ <span className="text-[10px] uppercase tracking-wider text-gray-500">live</span>
+ </div>
+ {loading && !data ? <p className="text-xs text-gray-500">Checking render lanes…</p> : null}
+ {idle ? <div className="rounded-lg border border-port-border bg-port-bg px-3 py-3 text-xs text-gray-400">Idle · GPU {gpu?.status === 'available' ? 'ready' : gpu?.status || 'unknown'}</div> : null}
+ <div className="space-y-1.5">{jobs.map((job) => <JobRow key={job.id} job={job} onCancel={cancel} />)}</div>
+ {(data?.extras?.imageTo3d || []).map((item) => <div key={`3d-${item.id}`} className="mt-1.5 text-xs text-gray-400">Image-to-3D · {item.name}</div>)}
+ {data?.agents?.active ? <div className="mt-2 text-xs text-gray-400">CoS agents · {data.agents.active} active{data.agents.queued ? ` · ${data.agents.queued} queued` : ''}</div> : null}
+ {gpu?.status === 'available' && gpu.gpus?.length ? <div className="mt-3 text-[11px] text-gray-500">GPU {gpu.gpus[0].utilizationPercent == null ? 'utilization unknown' : `${Math.round(gpu.gpus[0].utilizationPercent)}% utilized`}</div> : null}
+ </div>
+ );
+}
+
+export default memo(ActiveProcessingWidget);
diff --git a/client/src/components/dashboard/widgetRegistry.jsx b/client/src/components/dashboard/widgetRegistry.jsx
index a6b09579f6..ae598a94a3 100644
--- a/client/src/components/dashboard/widgetRegistry.jsx
+++ b/client/src/components/dashboard/widgetRegistry.jsx
@@ -28,6 +28,7 @@ const FeedsWidget = lazyWithReload(() => import('./builtins/FeedsWidge
const MeatSpaceStreakWidget = lazyWithReload(() => import('./builtins/MeatSpaceStreakWidget'));
const AutoFixMetricsWidget = lazyWithReload(() => import('./builtins/AutoFixMetricsWidget'));
const DailyDriverWidget = lazyWithReload(() => import('./builtins/DailyDriverWidget'));
+const ActiveProcessingWidget = lazyWithReload(() => import('./ActiveProcessingWidget'));
// Each entry: { id, label, Component, width, defaultH?, gate? }.
// `gate(state) => bool` skips the widget when it has nothing useful to show.
@@ -66,6 +67,7 @@ export const WIDGETS = [
{ id: 'feeds', label: 'Feeds Digest', Component: FeedsWidget, width: 'quarter', defaultH: 4, gate: (s) => (s.feeds?.totalFeeds ?? 0) > 0 },
{ id: 'meatspace-streak', label: 'Health Logging Streak', Component: MeatSpaceStreakWidget, width: 'third', defaultH: 4, gate: (s) => (s.meatspaceLogging?.totalLogged ?? 0) > 0 },
{ id: 'autofix-metrics', label: 'Auto-Fix Telemetry', Component: AutoFixMetricsWidget, width: 'quarter', defaultH: 5 },
+ { id: 'active-processing', label: 'Active Processing', Component: ActiveProcessingWidget, width: 'half', defaultH: 5 },
];
export const WIDGETS_BY_ID = Object.fromEntries(WIDGETS.map((w) => [w.id, w]));
diff --git a/client/src/components/music/MusicGenPanel.jsx b/client/src/components/music/MusicGenPanel.jsx
index 6c9ef98849..518c374fdd 100644
--- a/client/src/components/music/MusicGenPanel.jsx
+++ b/client/src/components/music/MusicGenPanel.jsx
@@ -22,12 +22,14 @@
import { useEffect, useMemo, useState } from 'react';
import useMounted from '../../hooks/useMounted';
+import useMediaJobProgress from '../../hooks/useMediaJobProgress';
+import { useAutoRefetch } from '../../hooks/useAutoRefetch';
import { Loader2, Wand2, Download, X } from 'lucide-react';
import toast from '../ui/Toast';
import { analyzeMusicLyrics } from '../../lib/musicDuration.js';
import { formatDurationSec } from '../../utils/formatters.js';
import {
- listMusicEngines, generateMusic, installAudioModel, removeAudioModel,
+ listMusicEngines, generateMusic, installAudioModel, removeAudioModel, getActiveProcessing, getMediaJob, getTrack, cancelMediaJob,
} from '../../services/api';
import { formatDownloadGb } from '../../utils/formatters';
import RuntimeInstallModal from '../install/RuntimeInstallModal';
@@ -84,6 +86,8 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
const [durationSec, setDurationSec] = useState(null);
const [durationMode, setDurationMode] = useState('auto');
const [generating, setGenerating] = useState(false);
+ const [activeJob, setActiveJob] = useState(null);
+ const [activeJobId, setActiveJobId] = useState(null);
const [generationElapsedSec, setGenerationElapsedSec] = useState(0);
// Inline HF model install.
const [installRepo, setInstallRepo] = useState('');
@@ -97,6 +101,51 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
const [userSelectedEngine, setUserSelectedEngine] = useState(false);
const mountedRef = useMounted();
+ const refreshActiveJob = async () => {
+ const snapshot = await getActiveProcessing({ silent: true });
+ if (!mountedRef.current) return;
+ const jobs = snapshot?.jobs || [];
+ const found = jobs.find((job) => {
+ const tag = job.params?.musicStudio;
+ return job.kind === 'audio' && (track?.id ? tag?.trackId === track.id : tag && !tag.trackId);
+ });
+ if (found) {
+ setActiveJob(found);
+ setActiveJobId(found.id);
+ setGenerating(true);
+ } else if (progress.status !== 'completed') {
+ setActiveJob(null);
+ setActiveJobId(null);
+ }
+ };
+
+ useAutoRefetch(refreshActiveJob, 3000, { pollOnly: true });
+ const progress = useMediaJobProgress(activeJobId, { kind: 'audio' });
+ const isGenerating = generating || ['queued', 'running'].includes(activeJob?.status) || ['queued', 'running'].includes(progress.status);
+
+ useEffect(() => {
+ if (!activeJobId || progress.status !== 'completed') return undefined;
+ let canceled = false;
+ const finish = async () => {
+ const job = await getMediaJob(activeJobId).catch(() => null);
+ const targetId = track?.id || job?.result?.trackId || progress.trackId;
+ if (!targetId || canceled) return;
+ let updated = null;
+ for (let attempt = 0; attempt < 4 && !updated && !canceled; attempt += 1) {
+ updated = await getTrack(targetId, { silent: true }).catch(() => null);
+ if (!updated && attempt < 3) await new Promise((resolve) => setTimeout(resolve, 250));
+ }
+ if (canceled || !mountedRef.current) return;
+ setGenerating(false);
+ setActiveJob(null);
+ setActiveJobId(null);
+ if (updated) onGenerated?.(updated);
+ toast.success('Track generated');
+ };
+ finish();
+ return () => { canceled = true; };
+ }, [activeJobId, progress.status, progress.trackId, track?.id]);
+
// Returns the freshly-fetched list as well as storing it: the post-runtime
// chain below needs the NEW engine record, and reading `engine` off state
// right after setEngines() would still see the pre-install one.
@@ -118,14 +167,14 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
useEffect(() => { loadEngines(); }, []);
useEffect(() => {
- if (!generating) return undefined;
- const startedAt = Date.now();
- setGenerationElapsedSec(0);
+ if (!isGenerating) return undefined;
+ const startedAt = activeJob?.startedAt ? Date.parse(activeJob.startedAt) : Date.now();
+ setGenerationElapsedSec(Math.max(0, Math.floor((Date.now() - startedAt) / 1000)));
const timer = setInterval(() => {
if (mountedRef.current) setGenerationElapsedSec(Math.floor((Date.now() - startedAt) / 1000));
}, 1000);
return () => clearInterval(timer);
- }, [generating]);
+ }, [isGenerating, activeJob?.startedAt]);
const engine = useMemo(() => engines.find((e) => e.id === engineId) || null, [engines, engineId]);
const selectedModel = engine?.models?.find((item) => item.id === modelId)
@@ -180,7 +229,7 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
setDurationSec((d) => (d == null ? engine.defaultDurationSec : d));
}, [engine?.id, engine?.models]);
- const canGenerate = !!engine?.ready && selectedModelReady && !!prompt?.trim() && !generating;
+ const canGenerate = !!engine?.ready && selectedModelReady && !!prompt?.trim() && !isGenerating;
const selectedModelSizeGb = engine?.modelSizeGbById?.[selectedModelId] ?? null;
const setup = engineSetupState(engine, selectedModelReady, selectedModelSizeGb);
@@ -256,10 +305,28 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
else if (Number.isFinite(durationSec)) body.durationSec = durationSec;
const res = await generateMusic(body, { silent: true }).catch((err) => { toast.error(err.message || 'Generation failed'); return null; });
if (!mountedRef.current) return;
- setGenerating(false);
if (res?.track) {
+ // Compatibility with an older server during a rolling upgrade. New
+ // servers always return the queued job acknowledgement below.
+ setGenerating(false);
onGenerated?.(res.track);
toast.success('Track generated');
+ } else if (res?.jobId) {
+ setActiveJob({ id: res.jobId, status: res.status, queuedAt: new Date().toISOString(), params: { musicStudio: { trackId: track?.id || null } } });
+ setActiveJobId(res.jobId);
+ } else {
+ setGenerating(false);
+ toast.error('Music generation did not return a job');
+ }
+ };
+
+ const handleCancel = async () => {
+ if (!activeJobId) return;
+ await cancelMediaJob(activeJobId, { silent: true }).catch((err) => toast.error(err.message || 'Cancel failed'));
+ if (mountedRef.current) {
+ setGenerating(false);
+ setActiveJob(null);
+ setActiveJobId(null);
}
};
@@ -432,8 +499,8 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
title={!prompt?.trim() ? 'Add a generation prompt' : !engine?.ready ? 'Complete engine setup first' : !selectedModelReady ? 'Install the selected model first' : track?.id ? 'Generate audio' : 'Generate and create a standalone track'}
className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"
>
- {generating ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />}
- {generating ? 'Generating…' : track?.id ? 'Generate' : 'Generate track'}
+ {isGenerating ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />}
+ {isGenerating ? 'Generating…' : track?.id ? 'Generate' : 'Generate track'}
</button>
{selectedUserModel ? (
<button
@@ -446,11 +513,11 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
</button>
) : null}
</div>
- {generating ? (
+ {isGenerating ? (
<div role="status" className="rounded-lg border border-port-accent/30 bg-port-accent/10 px-3 py-2">
<div className="flex items-center justify-between gap-3 text-xs">
<span className="text-gray-300">
- {engine?.cudaRequired ? 'Processing on the GPU' : 'Rendering audio'}
+ {activeJob?.status === 'queued' ? `Queued${activeJob.position ? ` · position ${activeJob.position}` : ''}` : engine?.cudaRequired ? 'Processing on the GPU' : 'Rendering audio'}
</span>
<span className="font-mono tabular-nums text-port-accent">
{Math.floor(generationElapsedSec / 60)}:{String(generationElapsedSec % 60).padStart(2, '0')} elapsed
@@ -466,6 +533,7 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
? 'MiniMax Music 3 MLX does not report an exact percentage yet; the first render includes model loading.'
: 'Generation is still active. Longer requested durations take more time.'}
</p>
+ {activeJobId ? <button type="button" onClick={handleCancel} className="mt-2 text-[11px] text-port-warning hover:text-white">Cancel render</button> : null}
</div>
) : null}
diff --git a/client/src/components/music/MusicGenPanel.test.jsx b/client/src/components/music/MusicGenPanel.test.jsx
index 597b1210e2..68215954fc 100644
--- a/client/src/components/music/MusicGenPanel.test.jsx
+++ b/client/src/components/music/MusicGenPanel.test.jsx
@@ -7,6 +7,10 @@ import * as api from '../../services/api';
vi.mock('../../services/api', () => ({
listMusicEngines: vi.fn(),
generateMusic: vi.fn(),
+ getActiveProcessing: vi.fn(),
+ getMediaJob: vi.fn(),
+ getTrack: vi.fn(),
+ cancelMediaJob: vi.fn(),
installAudioModel: vi.fn(),
removeAudioModel: vi.fn(),
}));
@@ -57,6 +61,7 @@ const minimax = (overrides) => engine({
describe('MusicGenPanel', () => {
beforeEach(() => {
vi.clearAllMocks();
+ api.getActiveProcessing.mockResolvedValue({ jobs: [] });
});
it('does not show a missing-runtime warning immediately for an empty saved track', async () => {
@@ -179,6 +184,18 @@ describe('MusicGenPanel', () => {
expect(onGenerated).toHaveBeenCalledWith(expect.objectContaining({ id: 'generated-track' }));
});
+ it('rehydrates a running Music Studio job when the panel remounts', async () => {
+ api.listMusicEngines.mockResolvedValue({ defaultEngine: 'musicgen', engines: [engine({ ready: true })] });
+ api.getActiveProcessing.mockResolvedValue({ jobs: [{
+ id: 'job-remounted', kind: 'audio', status: 'running', startedAt: new Date(Date.now() - 5000).toISOString(),
+ params: { musicStudio: { trackId: 'track-1' } },
+ }] });
+ api.getMediaJob.mockResolvedValue({ status: 'running', startedAt: new Date(Date.now() - 5000).toISOString() });
+ render(<MusicGenPanel track={{ id: 'track-1' }} prompt="warm folk" lyrics="" />);
+ expect(await screen.findByText(/processing on the gpu|rendering audio/i)).toBeInTheDocument();
+ expect(screen.getByRole('status')).toHaveTextContent(/elapsed/);
+ });
+
it('suggests a lyric-aware MiniMax ceiling and sends Auto mode', async () => {
api.listMusicEngines.mockResolvedValue({
defaultEngine: 'minimax-music3',
diff --git a/client/src/hooks/useMediaJobProgress.js b/client/src/hooks/useMediaJobProgress.js
index 033a7931d6..a2903aca74 100644
--- a/client/src/hooks/useMediaJobProgress.js
+++ b/client/src/hooks/useMediaJobProgress.js
@@ -38,6 +38,8 @@ const INITIAL_STATE = Object.freeze({
filename: null,
path: null,
error: null,
+ startedAt: null,
+ trackId: null,
});
export default function useMediaJobProgress(jobId, { kind = 'image' } = {}) {
@@ -78,6 +80,8 @@ export default function useMediaJobProgress(jobId, { kind = 'image' } = {}) {
filename: job.result?.filename || prev.filename,
path: job.result?.path || prev.path,
error: job.error || prev.error,
+ startedAt: job.startedAt || prev.startedAt,
+ trackId: job.result?.trackId || prev.trackId,
}));
}).catch(() => {
// 404 (job past 24h archive TTL) and any other failure stay silent;
@@ -136,6 +140,7 @@ export default function useMediaJobProgress(jobId, { kind = 'image' } = {}) {
statusMsg: 'Completed',
filename: data.filename ?? prev.filename,
path: data.path ?? prev.path,
+ trackId: data.trackId ?? prev.trackId,
}));
};
const onFailed = (data) => {
diff --git a/client/src/services/README.md b/client/src/services/README.md
index ce5fb956f9..b0c7a78cf4 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -62,7 +62,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiScaffold.js` | App scaffolding templates. |
| `apiSchedules.js` | Automation schedules. |
| `apiQuotaBurn.js` | Quota Burn plan + live status, the job-type catalog its config form renders, and manual runs (`getQuotaBurn`/`getQuotaBurnCatalog`/`saveQuotaBurn`/`runQuotaBurn`), plus `rearmQuotaBurn` to put spent `run once` steps back into the rotation. |
-| `apiSystem.js` | System info (CPU/memory/ports/alerts) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getUsage`/`getUsageRaw`/`resetUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison). |
+| `apiSystem.js` | System info (CPU/memory/ports/alerts/active processing) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getUsage`/`getUsageRaw`/`resetUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison). |
| `apiAuth.js` | Optional login password — status, login/logout, set/clear password. |
| `apiLoops.js` | Scheduled loops. |
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 8b45d6db4c..daab6ad076 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -33,6 +33,7 @@ export const triageSystemResources = (payload, options = {}) => request('/system
body: JSON.stringify(payload),
...options,
});
+export const getActiveProcessing = (options) => request('/system/processing', options);
export const getNetworkExposure = (options) => request('/network-exposure/status', options);
export const getCapabilities = (options) => request('/capabilities', options);
export const updateHealthThresholds = (thresholds, options = {}) => request('/system/health/thresholds', {
diff --git a/scripts/migrations/273-seed-active-processing-widget.js b/scripts/migrations/273-seed-active-processing-widget.js
new file mode 100644
index 0000000000..3cf67ba398
--- /dev/null
+++ b/scripts/migrations/273-seed-active-processing-widget.js
@@ -0,0 +1,26 @@
+import { readLayoutsDoc, writeLayoutsDoc } from './_lib.js';
+
+const WIDGET_ID = 'active-processing';
+
+const appendToLayout = (layout) => {
+ if (!layout || typeof layout !== 'object') return false;
+ if (!['default', 'ops'].includes(layout.id)) return false;
+ const widgets = Array.isArray(layout.widgets) ? layout.widgets : [];
+ const grid = Array.isArray(layout.grid) ? layout.grid : [];
+ if (widgets.includes(WIDGET_ID)) return false;
+ layout.widgets = [...widgets, WIDGET_ID];
+ const maxOrder = grid.reduce((max, item) => Math.max(max, Number.isFinite(item?.order) ? item.order : -1), -1);
+ layout.grid = [...grid, { id: WIDGET_ID, x: 0, w: 6, order: maxOrder + 1, h: 5 }];
+ return true;
+};
+
+export default {
+ async up({ rootDir }) {
+ const result = await readLayoutsDoc({ rootDir, label: 'migration 273' });
+ if (!result.ok) return { updated: 0, reason: result.reason };
+ let updated = 0;
+ for (const layout of result.doc.layouts) if (appendToLayout(layout)) updated += 1;
+ if (updated) await writeLayoutsDoc(result.path, result.doc);
+ return { updated };
+ },
+};
diff --git a/server/lib/cudaCapability.js b/server/lib/cudaCapability.js
index e349e93631..c518fa82f4 100644
--- a/server/lib/cudaCapability.js
+++ b/server/lib/cudaCapability.js
@@ -36,6 +36,40 @@ export const NVIDIA_SMI_QUERY_ARGS = Object.freeze([
'--format=csv,noheader,nounits',
]);
+export const NVIDIA_SMI_UTILIZATION_QUERY_ARGS = Object.freeze([
+ '--query-gpu=name,utilization.gpu,memory.used,memory.total',
+ '--format=csv,noheader,nounits',
+]);
+
+export function parseNvidiaSmiUtilization(stdout) {
+ return String(stdout ?? '').split(/\r?\n/).flatMap((raw) => {
+ const [name, utilization, memoryUsed, memoryTotal] = raw.trim().split(',').map((cell) => cell.trim());
+ if (!name) return [];
+ const numeric = (value) => {
+ const parsed = Number(value);
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
+ };
+ return [{
+ name,
+ utilizationPercent: numeric(utilization),
+ memoryUsedMib: numeric(memoryUsed),
+ memoryTotalMib: numeric(memoryTotal),
+ }];
+ });
+}
+
+export async function detectCudaUtilization({ execFileImpl = execFile, timeoutMs = 2000 } = {}) {
+ const result = await new Promise((resolve) => {
+ execFileImpl('nvidia-smi', [...NVIDIA_SMI_UTILIZATION_QUERY_ARGS], { timeout: timeoutMs },
+ (err, stdout) => resolve({ err, stdout: String(stdout ?? '') }));
+ }).catch((err) => ({ err, stdout: '' }));
+ if (result.err) {
+ return { status: result.err.code === 'ENOENT' ? 'absent' : 'unknown', gpus: [], error: result.err.message || null };
+ }
+ const gpus = parseNvidiaSmiUtilization(result.stdout);
+ return { status: gpus.length ? 'available' : 'absent', gpus, error: null };
+}
+
/**
* Parse `nvidia-smi --query-gpu=name,memory.total` CSV output into GPU descriptors.
* Pure, so the format is covered deterministically instead of depending on whatever
@@ -173,3 +207,20 @@ export function resetCudaCapabilityCache() {
cachedProbe = null;
cacheExpiresAt = Infinity;
}
+
+let cachedUtilization = null;
+let utilizationExpiresAt = 0;
+export const CUDA_UTILIZATION_TTL_MS = 4000;
+
+export async function getCudaUtilization({ refresh = false, now = Date.now, ...probeOpts } = {}) {
+ if (!refresh && cachedUtilization && now() < utilizationExpiresAt) return cachedUtilization;
+ const pending = detectCudaUtilization(probeOpts);
+ cachedUtilization = pending;
+ utilizationExpiresAt = now() + CUDA_UTILIZATION_TTL_MS;
+ return pending;
+}
+
+export function resetCudaUtilizationCache() {
+ cachedUtilization = null;
+ utilizationExpiresAt = 0;
+}
diff --git a/server/routes/mediaJobs.js b/server/routes/mediaJobs.js
index 657fc02e18..3eacb051af 100644
--- a/server/routes/mediaJobs.js
+++ b/server/routes/mediaJobs.js
@@ -13,6 +13,7 @@ import { listJobs, getJob, cancelJob, cancelQueuedJobs, enqueueJob, removeArchiv
import { refineMediaPrompt } from '../services/mediaPromptRefiner.js';
import { promptFromMedia } from '../services/mediaPromptFromMedia.js';
import { CODEX_EFFORT_LEVELS } from '../lib/providerModels.js';
+import { sanitizeJob } from '../services/mediaJobQueue/sanitizeJob.js';
const router = Router();
@@ -95,64 +96,6 @@ const promptFromMediaSchema = z.object({
}
});
-// Sanitize a job before serialization. The internal job record carries
-// worker-only data (the python interpreter path, absolute filesystem paths
-// to multipart uploads / source images) that the UI doesn't need and that
-// shouldn't ride out over the API. Only surface the user-visible params
-// the Render Queue UI actually renders (prompt, owner-supplied settings).
-const PARAM_ALLOWLIST = new Set([
- 'prompt', 'negativePrompt', 'modelId',
- // `model` is the codex-side counterpart to `modelId` (different field name
- // because Codex passes a model string straight to the CLI, while local /
- // video providers carry a registry-id). Without it the UI can't tell which
- // codex model a failed job tried to use — the row would just say "codex".
- 'model',
- // `effort` is the Codex per-render reasoning-effort level (`low` by default).
- // Surfacing it lets the Render Queue row show which effort a failed job used
- // and lets the retry editor pre-fill the current level (see the retry-editor
- // Reasoning-effort control). Codex-only; local/external/video jobs never set it.
- 'effort',
- 'width', 'height', 'numFrames', 'fps', 'steps', 'guidanceScale',
- 'seed', 'tiling', 'disableAudio', 'mode', 'imageStrength',
- 'cfgScale', 'guidance', 'quantize',
- // Training-kind label fields so the Render Queue UI can title training
- // rows ("Training: Kessa · mflux · 1000 steps") without exposing paths.
- 'runId', 'runtime', 'datasetId', 'characterId', 'characterName',
- 'triggerWord', 'rank', 'baseModelId',
- // Sprite reference destination tag (#2896) — pure identifiers (record id,
- // target/direction, key hex, mode/model), no filesystem paths. The Sprites
- // UI correlates queued/running renders by it to rehydrate its in-flight
- // guard after a reload.
- 'spriteRef',
- // Sprite walk-video destination tag (#2897) — record id, direction, run id,
- // key hex; same rehydration contract as spriteRef, for kind:'video' jobs.
- 'spriteWalk',
-]);
-function sanitizeJob(job) {
- if (!job) return job;
- const safeParams = job.params
- ? Object.fromEntries(Object.entries(job.params).filter(([k]) => PARAM_ALLOWLIST.has(k)))
- : undefined;
- return {
- id: job.id,
- kind: job.kind,
- owner: job.owner,
- status: job.status,
- queuedAt: job.queuedAt,
- startedAt: job.startedAt,
- completedAt: job.completedAt,
- position: job.position,
- progress: job.progress,
- statusMsg: job.statusMsg,
- // History-calibrated render ETA (#3801); undefined when the gen produced
- // no estimate, which the client renders as "unknown".
- etaMs: job.etaMs,
- error: job.error,
- result: job.result,
- params: safeParams,
- };
-}
-
router.get('/', asyncHandler(async (req, res) => {
const filters = validateRequest(listQuerySchema, req.query);
// Live jobs preserve `listJobs` order — [running, codexRunning, ...queue] —
diff --git a/server/routes/music.js b/server/routes/music.js
index 74b8c0bb32..33db66fcf3 100644
--- a/server/routes/music.js
+++ b/server/routes/music.js
@@ -4,7 +4,7 @@
* GET /api/music/engines → { engines, defaultEngine }
* POST /api/music/describe → { description, llm }
* POST /api/music/lyrics → { lyrics, llm }
- * POST /api/music/generate → { track, filename, durationSec, engine, modelId }
+ * POST /api/music/generate → { jobId, position, status }
*
* `describe`/`lyrics` are the Generate tab's stepped designer (#4305): an LLM
* expands a short reference/vibe into a rich conditioning prompt, then writes
@@ -12,15 +12,13 @@
* fires them on its own (AI Provider Usage Policy).
*
* Generation runs the engine-agnostic `generateMusic` (server/services/pipeline/
- * musicGen.js) — MusicGen / AudioLDM2 / ACE-Step / MiniMax-Music3 behind one contract — lands the
- * WAV in the shared music library (data/music/), then creates a new Track (or
- * updates an existing one via `trackId`) with the audio pointer + the prompt /
- * lyrics / engine / model / duration metadata. The pipeline audio stage has its
- * own generator routes; this is the studio's standalone path.
+ * musicGen.js) through the unified audio media-job lane. The completion hook
+ * lands the WAV in the shared music library and creates or updates the Track,
+ * independently of whether the requesting browser remains mounted. The pipeline
+ * audio stage has its own generator routes; this is the studio's standalone path.
*
- * Generation is synchronous here (one render at a time, like the pipeline audio
- * stage's generate route) — a long ACE-Step render holds the request open. An
- * async mediaJobQueue lane can be added later behind the same response shape.
+ * Generation is acknowledged immediately and drained by the audio media-job
+ * lane, so a long render never holds the HTTP request open.
*/
import { Router } from 'express';
@@ -32,7 +30,7 @@ import { createLineReader } from '../lib/streamLines.js';
import { SETUP_IMAGE_VIDEO_SCRIPT, spawnSetupScript, stopSetupScript } from '../lib/setupScriptRunner.js';
import {
ENGINES, getEngine, isEngineHealthy, isEnginePlatformSupported,
- enginePlatformLabel, generateMusic,
+ enginePlatformLabel,
} from '../services/pipeline/musicGen.js';
import { listEngineModels, addAudioModel, removeAudioModel, isValidRepoId } from '../services/audioModels.js';
import { listMusicEngineCapabilities } from '../services/musicEngineCapabilities.js';
@@ -41,8 +39,8 @@ import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';
import { createInstallLogger } from '../lib/installLogger.js';
import { inspectModelCache } from '../lib/hfCache.js';
import { getCudaCapability } from '../lib/cudaCapability.js';
+import { enqueueJob, listJobs } from '../services/mediaJobQueue/index.js';
import * as tracks from '../services/tracks/index.js';
-import * as albums from '../services/albums/index.js';
const router = Router();
@@ -388,78 +386,41 @@ router.post('/generate', asyncHandler(async (req, res) => {
// track's old words").
const usedLyrics = engine.lyrics ? (body.lyrics ?? '') : '';
- // generateMusic throws a typed ServerError (503 venv-missing / 500 sidecar
- // failure) that asyncHandler maps verbatim — no need to re-wrap here.
- const result = await generateMusic({
- prompt: body.prompt,
- lyrics: usedLyrics,
- engine: engine.id,
- modelId: body.modelId,
- repo,
- durationSec: body.durationSec,
- durationMode: body.durationMode,
+ const liveJobs = listJobs({ kind: 'audio' }).filter((job) => job.status === 'queued' || job.status === 'running');
+ const duplicate = liveJobs.find((job) => {
+ const tag = job.params?.musicStudio;
+ return body.trackId ? tag?.trackId === body.trackId : tag && !tag.trackId;
});
-
- // Persist the audio + gen metadata. Lyrics follow the audio that was actually
- // rendered: for a lyric-aware engine we persist what the caller SENT —
- // including an intentional '' clear (the audio was generated without lyrics) —
- // but an ABSENT lyrics field leaves the track's lyrics untouched. A non-lyric
- // engine never writes lyrics (it can't erase a song's words by adding a bed).
- const durationSec = Math.round(result.durationSec);
- // Re-read the track AFTER the (minutes-long) render so the append lands on the
- // FRESHEST persisted history — a render uploaded/generated to this same track
- // while this generation was running isn't dropped by writing back a stale
- // pre-render array. (The sub-millisecond getTrack→updateTrack window is a
- // single-user request race we intentionally don't lock against — trust model.)
- const current = existing ? ((await tracks.getTrack(body.trackId)) ?? existing) : null;
- const { renders } = tracks.buildRenderAppend(current, {
- audioFilename: result.filename,
- prompt: body.prompt,
- lyrics: usedLyrics,
- engine: result.engine,
- modelId: result.modelId,
- durationSec,
- });
-
- const meta = {
- audioFilename: result.filename,
- engine: result.engine,
- modelId: result.modelId,
- durationSec,
- prompt: body.prompt,
- renders,
- };
- if (engine.lyrics && body.lyrics !== undefined) meta.lyrics = body.lyrics;
-
- let track;
- if (existing) {
- track = await tracks.updateTrack(body.trackId, meta);
- } else {
- track = await tracks.createTrack({
- title: body.title?.trim() || body.prompt.slice(0, 60),
- artistId: body.artistId,
- artist: body.artist,
- albumId: body.albumId,
- ...(engine.lyrics && body.lyrics !== undefined ? { lyrics: body.lyrics } : {}),
- ...meta,
+ if (duplicate) {
+ throw new ServerError('Music generation is already in progress', {
+ status: 409,
+ code: 'PIPELINE_MUSIC_BUSY',
+ context: { jobId: duplicate.id },
});
- // Mirror the /api/tracks create path: a new track with an albumId must be
- // appended to that album's ordered trackIds so album views show it.
- if (track.albumId) {
- const album = await albums.getAlbum(track.albumId).catch(() => null);
- if (album && !(album.trackIds || []).includes(track.id)) {
- await albums.updateAlbum(track.albumId, { trackIds: [...(album.trackIds || []), track.id] }).catch(() => {});
- }
- }
}
- res.status(body.trackId ? 200 : 201).json({
- track,
- filename: result.filename,
- durationSec: result.durationSec,
- engine: result.engine,
- modelId: result.modelId,
+ const result = enqueueJob({
+ kind: 'audio',
+ params: {
+ prompt: body.prompt,
+ lyrics: usedLyrics,
+ engine: engine.id,
+ modelId: body.modelId,
+ repo,
+ durationSec: body.durationSec,
+ durationMode: body.durationMode,
+ musicStudio: {
+ trackId: body.trackId || null,
+ title: body.title || body.prompt.slice(0, 60),
+ artistId: body.artistId,
+ artist: body.artist,
+ albumId: body.albumId,
+ lyricsEnabled: engine.lyrics === true,
+ lyricsProvided: body.lyrics !== undefined,
+ },
+ },
});
+ res.status(202).json(result);
}));
export default router;
diff --git a/server/routes/music.test.js b/server/routes/music.test.js
index f4af5fa291..d5d826f298 100644
--- a/server/routes/music.test.js
+++ b/server/routes/music.test.js
@@ -14,6 +14,7 @@ const gen = vi.hoisted(() => ({
healthyByEngine: null,
unsupportedPlatform: null,
}));
+const mediaQueue = vi.hoisted(() => ({ jobs: [], enqueue: vi.fn() }));
const cuda = vi.hoisted(() => ({ status: 'available' }));
vi.mock('../lib/cudaCapability.js', () => ({
getCudaCapability: vi.fn(async () => ({ status: cuda.status, gpus: [], maxVramGb: null, error: null })),
@@ -49,6 +50,12 @@ vi.mock('../services/pipeline/musicGen.js', () => {
generateMusic: gen.generateMusic,
};
});
+vi.mock('../services/mediaJobQueue/index.js', () => ({
+ enqueueJob: (...args) => mediaQueue.enqueue(...args),
+ listJobs: () => mediaQueue.jobs,
+ JOB_KINDS: ['video', 'image', 'training', 'audio'],
+ JOB_STATUSES: ['queued', 'running', 'completed', 'failed', 'canceled'],
+}));
// The install route shells out to scripts/setup-image-video.sh. Stand in a child
// that closes immediately so the SSE stream terminates instead of running a real
@@ -147,6 +154,8 @@ describe('music routes', () => {
// clears call history) — otherwise an unconsumed mockResolvedValueOnce on
// generateMusic leaks into the next test.
gen.generateMusic.mockReset();
+ mediaQueue.enqueue.mockReset().mockImplementation(() => ({ jobId: 'job-1', position: 1, status: 'queued' }));
+ mediaQueue.jobs = [];
models.list.mockReset();
// add/remove return promises by default so the route's `.catch()` chains
// don't throw on an undefined return (mockReset clears the impl).
@@ -503,22 +512,17 @@ describe('music routes', () => {
expect(models.remove).toHaveBeenCalledWith({ engine: 'musicgen', id: 'facebook/musicgen-large' });
});
- it('POST /generate creates a new track from the result', async () => {
- gen.generateMusic.mockResolvedValueOnce({ filename: 'music-gen-x.wav', durationSec: 61.4, engine: 'acestep', modelId: 'a' });
+ it('POST /generate queues a new track render', async () => {
const r = await request(app).post('/api/music/generate').send({
prompt: 'warm folk', lyrics: '[verse] hi', engine: 'acestep', title: 'My Song',
});
- expect(r.status).toBe(201);
- expect(gen.generateMusic).toHaveBeenCalledWith(expect.objectContaining({ prompt: 'warm folk', lyrics: '[verse] hi', engine: 'acestep' }));
- expect(tracks.createTrack).toHaveBeenCalledWith(expect.objectContaining({
- title: 'My Song', audioFilename: 'music-gen-x.wav', engine: 'acestep', modelId: 'a', durationSec: 61, lyrics: '[verse] hi',
+ expect(r.status).toBe(202);
+ expect(mediaQueue.enqueue).toHaveBeenCalledWith(expect.objectContaining({
+ kind: 'audio', params: expect.objectContaining({ prompt: 'warm folk', lyrics: '[verse] hi', engine: 'acestep' }),
}));
- expect(r.body.track.id).toBe('track-new');
- expect(r.body.filename).toBe('music-gen-x.wav');
});
- it('POST /generate forwards MiniMax auto duration mode to the generator', async () => {
- gen.generateMusic.mockResolvedValueOnce({ filename: 'music-gen-auto.wav', durationSec: 148, engine: 'minimax-music3', modelId: 'minimax-music3' });
+ it('POST /generate forwards MiniMax auto duration mode to the queue', async () => {
const r = await request(app).post('/api/music/generate').send({
prompt: 'warm folk',
lyrics: `[verse]\n${'word '.repeat(180)}\n[outro]`,
@@ -526,65 +530,49 @@ describe('music routes', () => {
durationMode: 'auto',
});
- expect(r.status).toBe(201);
- expect(gen.generateMusic).toHaveBeenCalledWith(expect.objectContaining({
+ expect(r.status).toBe(202);
+ expect(mediaQueue.enqueue).toHaveBeenCalledWith(expect.objectContaining({
+ params: expect.objectContaining({
engine: 'minimax-music3',
lyrics: expect.stringContaining('[verse]'),
durationMode: 'auto',
+ }),
}));
});
- it('POST /generate with trackId updates the existing track (200)', async () => {
+ it('POST /generate queues an existing-track render', async () => {
tracks.getTrack.mockResolvedValueOnce({ id: 'track-1', title: 'Existing' });
- gen.generateMusic.mockResolvedValueOnce({ filename: 'music-gen-y.wav', durationSec: 30, engine: 'musicgen', modelId: 'm' });
const r = await request(app).post('/api/music/generate').send({ prompt: 'beat', trackId: 'track-1' });
- expect(r.status).toBe(200);
- expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', expect.objectContaining({ audioFilename: 'music-gen-y.wav' }));
- expect(tracks.createTrack).not.toHaveBeenCalled();
+ expect(r.status).toBe(202);
+ expect(mediaQueue.enqueue).toHaveBeenCalledWith(expect.objectContaining({ params: expect.objectContaining({ musicStudio: expect.objectContaining({ trackId: 'track-1' }) }) }));
});
- it('POST /generate on a non-lyric engine does NOT write lyrics (no erasure)', async () => {
+ it('POST /generate marks non-lyric jobs as not lyric-enabled', async () => {
tracks.getTrack.mockResolvedValueOnce({ id: 'track-1', title: 'Has Lyrics', lyrics: 'keep me' });
gen.generateMusic.mockResolvedValueOnce({ filename: 'm.wav', durationSec: 12, engine: 'musicgen', modelId: 'm' });
// MusicGen is not lyric-aware; even if the client sends lyrics:'' the update must omit lyrics.
await request(app).post('/api/music/generate').send({ prompt: 'bed', lyrics: '', engine: 'musicgen', trackId: 'track-1' });
- const patch = tracks.updateTrack.mock.calls[0][1];
- expect(patch).not.toHaveProperty('lyrics');
+ expect(mediaQueue.enqueue).toHaveBeenCalledWith(expect.objectContaining({ params: expect.objectContaining({ musicStudio: expect.objectContaining({ lyricsEnabled: false }) }) }));
});
- it('POST /generate on a lyric engine with ABSENT lyrics leaves the track lyrics untouched', async () => {
+ it('POST /generate records the empty conditioning snapshot when lyrics are absent', async () => {
tracks.getTrack.mockResolvedValueOnce({ id: 'track-1', title: 'Song', lyrics: 'old words' });
gen.generateMusic.mockResolvedValueOnce({ filename: 'm.wav', durationSec: 60, engine: 'acestep', modelId: 'a' });
await request(app).post('/api/music/generate').send({ prompt: 'folk', engine: 'acestep', trackId: 'track-1' }); // no lyrics field
- const patch = tracks.updateTrack.mock.calls[0][1];
- expect(patch).not.toHaveProperty('lyrics');
- // The sidecar still renders (with empty lyrics) — engine.lyrics coalesces to ''.
- expect(gen.generateMusic).toHaveBeenCalledWith(expect.objectContaining({ lyrics: '' }));
- // The render SNAPSHOT records the lyrics that actually conditioned it ('' —
- // generated without lyrics), NOT the track's stale saved lyrics. Otherwise
- // the card would falsely advertise conditioning text the audio wasn't built from.
- expect(tracks.buildRenderAppend).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ lyrics: '' }));
- });
-
- it('POST /generate appends the render onto the FRESHEST track state (re-reads after the render)', async () => {
- // A render added to the same track WHILE this multi-minute generation ran
- // must not be dropped: the append must use the post-render track, not the
- // pre-render snapshot.
- const stale = { id: 'track-1', title: 'S', renders: [{ id: 'r-old', audioFilename: 'old.wav' }] };
- const fresh = { id: 'track-1', title: 'S', renders: [{ id: 'r-old', audioFilename: 'old.wav' }, { id: 'r-concurrent', audioFilename: 'concurrent.wav' }] };
- tracks.getTrack.mockResolvedValueOnce(stale).mockResolvedValueOnce(fresh);
- gen.generateMusic.mockResolvedValueOnce({ filename: 'm.wav', durationSec: 12, engine: 'musicgen', modelId: 'm' });
+ expect(mediaQueue.enqueue).toHaveBeenCalledWith(expect.objectContaining({ params: expect.objectContaining({ lyrics: '', musicStudio: expect.objectContaining({ lyricsEnabled: true }) }) }));
+ });
+
+ it('POST /generate keeps the track destination in the job snapshot', async () => {
+ tracks.getTrack.mockResolvedValueOnce({ id: 'track-1' });
await request(app).post('/api/music/generate').send({ prompt: 'beat', engine: 'musicgen', trackId: 'track-1' });
- expect(tracks.getTrack).toHaveBeenCalledTimes(2); // validate, then re-read after the render
- expect(tracks.buildRenderAppend).toHaveBeenCalledWith(fresh, expect.objectContaining({ audioFilename: 'm.wav' }));
+ expect(mediaQueue.enqueue).toHaveBeenCalledWith(expect.objectContaining({ params: expect.objectContaining({ musicStudio: expect.objectContaining({ trackId: 'track-1' }) }) }));
});
- it('POST /generate on a lyric engine with an EXPLICIT empty lyrics persists the clear', async () => {
+ it('POST /generate preserves an explicit lyric clear in the job snapshot', async () => {
tracks.getTrack.mockResolvedValueOnce({ id: 'track-1', title: 'Song', lyrics: 'old words' });
gen.generateMusic.mockResolvedValueOnce({ filename: 'm.wav', durationSec: 60, engine: 'acestep', modelId: 'a' });
await request(app).post('/api/music/generate').send({ prompt: 'instrumental', lyrics: '', engine: 'acestep', trackId: 'track-1' });
- const patch = tracks.updateTrack.mock.calls[0][1];
- expect(patch.lyrics).toBe(''); // audio was rendered WITHOUT lyrics → persist the clear
+ expect(mediaQueue.enqueue).toHaveBeenCalledWith(expect.objectContaining({ params: expect.objectContaining({ lyrics: '', musicStudio: expect.objectContaining({ lyricsEnabled: true }) }) }));
});
it('POST /generate validates trackId BEFORE rendering (no wasted render)', async () => {
@@ -594,14 +582,13 @@ describe('music routes', () => {
expect(gen.generateMusic).not.toHaveBeenCalled(); // render never started
});
- it('POST /generate resolves a USER-INSTALLED model id to its repo for the sidecar', async () => {
+ it('POST /generate resolves a USER-INSTALLED model id to the queued job', async () => {
models.list.mockResolvedValueOnce([
{ id: 'm', name: 'M', userAdded: false },
{ id: 'someorg/big-musicgen', name: 'Big', repo: 'someorg/big-musicgen', userAdded: true },
]);
- gen.generateMusic.mockResolvedValueOnce({ filename: 'm.wav', durationSec: 12, engine: 'musicgen', modelId: 'someorg/big-musicgen' });
await request(app).post('/api/music/generate').send({ prompt: 'x', engine: 'musicgen', modelId: 'someorg/big-musicgen' });
- expect(gen.generateMusic).toHaveBeenCalledWith(expect.objectContaining({ repo: 'someorg/big-musicgen', modelId: 'someorg/big-musicgen' }));
+ expect(mediaQueue.enqueue).toHaveBeenCalledWith(expect.objectContaining({ params: expect.objectContaining({ repo: 'someorg/big-musicgen', modelId: 'someorg/big-musicgen' }) }));
});
it('POST /generate rejects an unknown modelId BEFORE rendering', async () => {
@@ -612,41 +599,60 @@ describe('music routes', () => {
expect(gen.generateMusic).not.toHaveBeenCalled();
});
- it('POST /generate creating a track with albumId appends it to the album tracklist', async () => {
- albums.getAlbum.mockResolvedValueOnce({ id: 'album-1', trackIds: ['track-0'] });
- tracks.createTrack.mockResolvedValueOnce({ id: 'track-gen', title: 'x', albumId: 'album-1' });
- gen.generateMusic.mockResolvedValueOnce({ filename: 'm.wav', durationSec: 12, engine: 'musicgen', modelId: 'm' });
+ it('POST /generate carries album metadata to the queued job', async () => {
await request(app).post('/api/music/generate').send({ prompt: 'x', engine: 'musicgen', albumId: 'album-1' });
- expect(albums.updateAlbum).toHaveBeenCalledWith('album-1', { trackIds: ['track-0', 'track-gen'] });
+ expect(mediaQueue.enqueue).toHaveBeenCalledWith(expect.objectContaining({ params: expect.objectContaining({ musicStudio: expect.objectContaining({ albumId: 'album-1' }) }) }));
});
- it('POST /generate with an unknown trackId 404s and does not create', async () => {
+ it('POST /generate with an unknown trackId 404s and does not queue', async () => {
tracks.getTrack.mockResolvedValueOnce(null);
- gen.generateMusic.mockResolvedValueOnce({ filename: 'm.wav', durationSec: 10, engine: 'musicgen', modelId: 'm' });
const r = await request(app).post('/api/music/generate').send({ prompt: 'x', trackId: 'track-missing' });
expect(r.status).toBe(404);
expect(tracks.updateTrack).not.toHaveBeenCalled();
- expect(tracks.createTrack).not.toHaveBeenCalled();
+ expect(mediaQueue.enqueue).not.toHaveBeenCalled();
});
- it('POST /generate rejects an unknown engine before rendering (no wrong-backend output)', async () => {
+ it('POST /generate rejects an unknown engine before queueing (no wrong-backend output)', async () => {
const r = await request(app).post('/api/music/generate').send({ prompt: 'x', engine: 'acestep-v2' });
expect(r.status).toBe(400);
expect(r.body.code).toBe('PIPELINE_MUSIC_UNKNOWN_ENGINE');
- expect(gen.generateMusic).not.toHaveBeenCalled();
+ expect(mediaQueue.enqueue).not.toHaveBeenCalled();
});
it('POST /generate rejects a missing prompt', async () => {
const r = await request(app).post('/api/music/generate').send({ engine: 'acestep' });
expect(r.status).toBe(400);
- expect(gen.generateMusic).not.toHaveBeenCalled();
+ expect(mediaQueue.enqueue).not.toHaveBeenCalled();
});
- it('POST /generate surfaces a 503 when the engine venv is missing', async () => {
- gen.generateMusic.mockRejectedValueOnce(new ServerError('ACE-Step runtime not found. Run `INSTALL_ACESTEP=1 …`', { status: 503, code: 'PIPELINE_MUSIC_RUNTIME_MISSING' }));
+ it('POST /generate acknowledges even when rendering will later report a runtime failure', async () => {
const r = await request(app).post('/api/music/generate').send({ prompt: 'x', engine: 'acestep' });
- expect(r.status).toBe(503);
- expect(r.body.code).toBe('PIPELINE_MUSIC_RUNTIME_MISSING');
- expect(tracks.createTrack).not.toHaveBeenCalled();
+ expect(r.status).toBe(202);
+ expect(mediaQueue.enqueue).toHaveBeenCalled();
+ });
+
+ it('POST /generate returns a queued audio job with the Music Studio destination tag', async () => {
+ const r = await request(app).post('/api/music/generate').send({
+ prompt: 'warm folk', lyrics: '[verse] hi', engine: 'acestep', title: 'My Song', albumId: 'album-1',
+ });
+ expect(r.status).toBe(202);
+ expect(r.body).toEqual({ jobId: 'job-1', position: 1, status: 'queued' });
+ expect(mediaQueue.enqueue).toHaveBeenCalledWith(expect.objectContaining({
+ kind: 'audio',
+ params: expect.objectContaining({
+ prompt: 'warm folk', lyrics: '[verse] hi', engine: 'acestep',
+ musicStudio: expect.objectContaining({ trackId: null, title: 'My Song', albumId: 'album-1', lyricsEnabled: true }),
+ }),
+ }));
+ });
+
+ it('POST /generate rejects a duplicate live render for the same track', async () => {
+ mediaQueue.jobs = [{ id: 'existing-job', kind: 'audio', status: 'running', params: { musicStudio: { trackId: 'track-1' } } }];
+ tracks.getTrack.mockResolvedValueOnce({ id: 'track-1' });
+ const r = await request(app).post('/api/music/generate').send({ prompt: 'beat', trackId: 'track-1' });
+ expect(r.status).toBe(409);
+ expect(r.body.code).toBe('PIPELINE_MUSIC_BUSY');
+ expect(r.body.context.jobId).toBe('existing-job');
+ expect(mediaQueue.enqueue).not.toHaveBeenCalled();
});
});
diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.js
index 558d04884b..a33a2d66cd 100644
--- a/server/routes/systemHealth.js
+++ b/server/routes/systemHealth.js
@@ -14,6 +14,7 @@ import { getSettings, updateSettingsWith } from '../services/settings.js';
import { checkGhHealth } from '../services/github.js';
import { isAuthEnabled } from '../services/auth.js';
import { getHttpsEnabledAtBoot } from '../lib/httpsState.js';
+import { getActiveProcessing } from '../services/activeProcessing.js';
// Defaults are tuned for a real dev machine: memory routinely sits in the
// 75-85% band on a host with a couple of LLMs loaded, and big SSDs commonly
@@ -40,6 +41,10 @@ async function loadThresholds() {
const router = Router();
+router.get('/processing', asyncHandler(async (req, res) => {
+ res.json(await getActiveProcessing());
+}));
+
router.get('/health', asyncHandler(async (req, res) => {
const [self, version, authRequired] = await Promise.all([
getSelf().catch(() => null),
diff --git a/server/services/activeProcessing.js b/server/services/activeProcessing.js
new file mode 100644
index 0000000000..188d560c13
--- /dev/null
+++ b/server/services/activeProcessing.js
@@ -0,0 +1,46 @@
+import { getCudaCapability, getCudaUtilization } from '../lib/cudaCapability.js';
+import { listJobs, getRunningJob } from './mediaJobQueue/index.js';
+import { sanitizeJob } from './mediaJobQueue/sanitizeJob.js';
+import { listModels } from './imageTo3d/models.js';
+import { getLoadedModels } from './ollamaManager.js';
+import * as cos from './cos.js';
+
+const LIVE_STATUSES = new Set(['queued', 'running']);
+
+export async function getActiveProcessing() {
+ const [capability, jobs, models, loadedModels, cosStatus, taskData] = await Promise.all([
+ getCudaCapability(),
+ Promise.resolve(listJobs()).then((items) => items.filter((job) => LIVE_STATUSES.has(job.status))),
+ listModels().catch(() => []),
+ getLoadedModels().catch(() => []),
+ cos.getStatus().catch(() => null),
+ cos.getAllTasks().catch(() => ({ user: {}, cos: {} })),
+ ]);
+ const utilization = capability.status === 'available' ? await getCudaUtilization() : { status: capability.status, gpus: [] };
+ const pendingTasks = [...(taskData.user?.tasks || []), ...(taskData.cos?.tasks || [])]
+ .filter((task) => task.status === 'pending').length;
+ const gpuBusy = Boolean(getRunningJob());
+ return {
+ updatedAt: new Date().toISOString(),
+ gpu: {
+ status: capability.status,
+ laneBusy: gpuBusy,
+ laneKind: getRunningJob()?.kind || null,
+ gpus: (utilization.gpus.length ? utilization.gpus : capability.gpus).map((gpu) => ({
+ name: gpu.name,
+ utilizationPercent: gpu.utilizationPercent ?? null,
+ memoryUsedMib: gpu.memoryUsedMib ?? null,
+ memoryTotalMib: gpu.memoryTotalMib ?? gpu.vramMib ?? null,
+ })),
+ },
+ jobs: jobs.map(sanitizeJob),
+ extras: {
+ imageTo3d: models.filter((model) => model.status === 'generating').map((model) => ({ id: model.id, name: model.name || model.id })),
+ ollama: loadedModels,
+ },
+ agents: {
+ active: cosStatus?.activeAgents || 0,
+ queued: pendingTasks,
+ },
+ };
+}
diff --git a/server/services/activeProcessing.test.js b/server/services/activeProcessing.test.js
new file mode 100644
index 0000000000..9fdc2d0e69
--- /dev/null
+++ b/server/services/activeProcessing.test.js
@@ -0,0 +1,50 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const deps = vi.hoisted(() => ({
+ capability: vi.fn(), utilization: vi.fn(), jobs: vi.fn(), running: vi.fn(), models: vi.fn(), loaded: vi.fn(), status: vi.fn(), tasks: vi.fn(),
+}));
+vi.mock('../lib/cudaCapability.js', () => ({ getCudaCapability: deps.capability, getCudaUtilization: deps.utilization }));
+vi.mock('./mediaJobQueue/index.js', () => ({ listJobs: deps.jobs, getRunningJob: deps.running }));
+vi.mock('./mediaJobQueue/sanitizeJob.js', () => ({ sanitizeJob: (job) => ({ id: job.id, kind: job.kind, status: job.status, params: { musicStudio: job.params.musicStudio } }) }));
+vi.mock('./imageTo3d/models.js', () => ({ listModels: deps.models }));
+vi.mock('./ollamaManager.js', () => ({ getLoadedModels: deps.loaded }));
+vi.mock('./cos.js', () => ({ getStatus: deps.status, getAllTasks: deps.tasks }));
+
+const { getActiveProcessing } = await import('./activeProcessing.js');
+
+describe('active processing snapshot', () => {
+ beforeEach(() => {
+ Object.values(deps).forEach((mock) => mock.mockReset());
+ });
+
+ it('reports sanitized audio work, GPU utilization, and non-media extras', async () => {
+ deps.capability.mockResolvedValue({ status: 'available', gpus: [{ name: 'Example GPU', vramMib: 24000 }] });
+ deps.utilization.mockResolvedValue({ status: 'available', gpus: [{ name: 'Example GPU', utilizationPercent: 44, memoryUsedMib: 1000, memoryTotalMib: 24000 }] });
+ deps.jobs.mockReturnValue([{ id: 'audio-1', kind: 'audio', status: 'running', params: { prompt: 'fake', musicStudio: { trackId: 'track-1' }, secretPath: '/private' } }]);
+ deps.running.mockReturnValue({ kind: 'audio' });
+ deps.models.mockResolvedValue([{ id: 'mesh-1', name: 'Fake mesh', status: 'generating' }]);
+ deps.loaded.mockResolvedValue([{ id: 'model-1', name: 'Fake model' }]);
+ deps.status.mockResolvedValue({ activeAgents: 2 });
+ deps.tasks.mockResolvedValue({ user: { tasks: [{ status: 'pending' }] }, cos: { tasks: [{ status: 'completed' }] } });
+ const snapshot = await getActiveProcessing();
+ expect(snapshot.jobs).toHaveLength(1);
+ expect(snapshot.gpu).toMatchObject({ status: 'available', laneBusy: true, laneKind: 'audio' });
+ expect(snapshot.gpu.gpus[0]).toMatchObject({ utilizationPercent: 44, memoryUsedMib: 1000 });
+ expect(snapshot.extras.imageTo3d).toEqual([{ id: 'mesh-1', name: 'Fake mesh' }]);
+ expect(snapshot.extras.ollama).toEqual([{ id: 'model-1', name: 'Fake model' }]);
+ expect(snapshot.agents).toEqual({ active: 2, queued: 1 });
+ });
+
+ it('preserves an absent GPU as a real negative state without probing utilization', async () => {
+ deps.capability.mockResolvedValue({ status: 'absent', gpus: [] });
+ deps.jobs.mockReturnValue([]);
+ deps.running.mockReturnValue(null);
+ deps.models.mockResolvedValue([]);
+ deps.loaded.mockResolvedValue([]);
+ deps.status.mockResolvedValue({ activeAgents: 0 });
+ deps.tasks.mockResolvedValue({ user: {}, cos: {} });
+ const snapshot = await getActiveProcessing();
+ expect(snapshot.gpu).toMatchObject({ status: 'absent', laneBusy: false, laneKind: null, gpus: [] });
+ expect(deps.utilization).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index ae05da0c86..31af654fc3 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -119,6 +119,7 @@ import { initWritersRoomSceneImageHook } from './writersRoomSceneImageHook.js';
import { initMusicVideoSceneImageHook } from './musicVideoSceneImageHook.js';
import { initMusicVideoSceneVideoHook } from './musicVideoSceneVideoHook.js';
import { initCreativeDirectorMusicBedHook } from './creativeDirectorMusicBedHook.js';
+import { initMusicStudioHook } from './musicStudioHook.js';
import { initImageGenQuotaHook } from './imageGenQuota.js';
import { initSpriteReferenceImageHook } from './spriteReferenceImageHook.js';
import { initCreativeDirectorSceneImageHook } from './creativeDirectorSceneImageHook.js';
@@ -476,6 +477,9 @@ const initMediaJobDependentHooks = () => {
// audio render onto its project's `musicBed` field on completion, even if
// the requesting client unmounted mid-render (#1928).
initCreativeDirectorMusicBedHook();
+ // Music Studio audio jobs attach to their track after completion so the
+ // library remains correct across a client remount or navigation.
+ initMusicStudioHook();
// Image-gen quota observation — the cloud image backends expose no quota API,
// so the Usage page's Image Gen card is built from renders we watched succeed
// or get refused. One bus subscriber, never per-provider edits.
diff --git a/server/services/dashboardLayouts.js b/server/services/dashboardLayouts.js
index 5b19b5e66d..0d7a3d6f6d 100644
--- a/server/services/dashboardLayouts.js
+++ b/server/services/dashboardLayouts.js
@@ -90,7 +90,7 @@ const DEFAULT_LAYOUTS = [
'quick-brain', 'quick-idea', 'quick-image', 'quick-task',
'apps',
'cos', 'goal-progress', 'upcoming-tasks',
- 'proactive-alerts', 'review-hub', 'while-away', 'system-health', 'network-exposure', 'backup', 'death-clock', 'quick-stats', 'decision-log',
+ 'proactive-alerts', 'review-hub', 'while-away', 'system-health', 'active-processing', 'network-exposure', 'backup', 'death-clock', 'quick-stats', 'decision-log',
'activity-streak', 'hourly-activity', 'tribe-care', 'feeds',
],
// Above-the-fold capture row stretches to h=5 so the Quick Task card
@@ -105,30 +105,31 @@ const DEFAULT_LAYOUTS = [
{ id: 'quick-image', x: 0, w: 3, order: 3, h: 3 },
// Primary monitoring + alerts
{ id: 'system-health', x: 0, w: 5, order: 4, h: 5 },
- { id: 'proactive-alerts', x: 5, w: 3, order: 5, h: 3 },
- { id: 'death-clock', x: 8, w: 4, order: 6, h: 2 },
- { id: 'activity-streak', x: 8, w: 4, order: 7, h: 3 },
- { id: 'review-hub', x: 5, w: 3, order: 8, h: 2 },
+ { id: 'active-processing',x: 5, w: 3, order: 5, h: 5 },
+ { id: 'proactive-alerts', x: 8, w: 3, order: 6, h: 3 },
+ { id: 'death-clock', x: 8, w: 4, order: 7, h: 2 },
+ { id: 'activity-streak', x: 8, w: 4, order: 8, h: 3 },
+ { id: 'review-hub', x: 5, w: 3, order: 9, h: 2 },
// Secondary widgets
- { id: 'backup', x: 0, w: 3, order: 9, h: 4 },
- { id: 'quick-stats', x: 3, w: 3, order: 10, h: 3 },
- { id: 'goal-progress', x: 6, w: 3, order: 11, h: 4 },
- { id: 'network-exposure', x: 9, w: 3, order: 12, h: 5 },
+ { id: 'backup', x: 0, w: 3, order: 10, h: 4 },
+ { id: 'quick-stats', x: 3, w: 3, order: 11, h: 3 },
+ { id: 'goal-progress', x: 6, w: 3, order: 12, h: 4 },
+ { id: 'network-exposure', x: 9, w: 3, order: 13, h: 5 },
// Lower-priority + cos
- { id: 'decision-log', x: 0, w: 4, order: 13, h: 2 },
- { id: 'cos', x: 4, w: 5, order: 14, h: 4 },
- { id: 'while-away', x: 9, w: 3, order: 15, h: 3 },
+ { id: 'decision-log', x: 0, w: 4, order: 14, h: 2 },
+ { id: 'cos', x: 4, w: 5, order: 15, h: 4 },
+ { id: 'while-away', x: 9, w: 3, order: 16, h: 3 },
// Full-width visualizations + apps
- { id: 'hourly-activity', x: 0, w: 12, order: 16, h: 3 },
- { id: 'apps', x: 0, w: 12, order: 17, h: 8 },
+ { id: 'hourly-activity', x: 0, w: 12, order: 17, h: 3 },
+ { id: 'apps', x: 0, w: 12, order: 18, h: 8 },
// Quick-idea (catalog) is sequenced below apps so the seeded layout
// doesn't crowd the tightly-packed above-the-fold band.
// Reorderable via the Arrange button on the dashboard.
- { id: 'quick-idea', x: 0, w: 4, order: 18, h: 4 },
+ { id: 'quick-idea', x: 0, w: 4, order: 19, h: 4 },
// Gated on the Tribe having people — hidden on installs that don't use it.
- { id: 'tribe-care', x: 4, w: 4, order: 19, h: 4 },
+ { id: 'tribe-care', x: 4, w: 4, order: 20, h: 4 },
// Gated on having subscribed feeds — hidden on installs with none.
- { id: 'feeds', x: 8, w: 3, order: 20, h: 4 },
+ { id: 'feeds', x: 8, w: 3, order: 21, h: 4 },
],
},
{
@@ -173,18 +174,19 @@ const DEFAULT_LAYOUTS = [
id: 'ops',
name: 'Ops',
builtIn: true,
- widgets: ['system-health', 'network-exposure', 'cos', 'backup', 'apps', 'quick-stats'],
+ widgets: ['system-health', 'active-processing', 'network-exposure', 'cos', 'backup', 'apps', 'quick-stats'],
// System monitoring focus — system-health takes the tall left column
// (the primary alarm surface), cos in the center for ChiefOfStaff
- // status, backup + quick-stats stacked on the right, apps grid fills
- // the empty cell below cos so all 5 widgets fit above the fold.
+ // status, active-processing + quick-stats stacked on the right, apps grid
+ // fills the empty cell below cos so the monitoring widgets stay above fold.
grid: [
{ id: 'system-health', x: 0, w: 6, order: 0, h: 5 },
- { id: 'quick-stats', x: 6, w: 6, order: 1, h: 3 },
- { id: 'cos', x: 6, w: 6, order: 2, h: 4 },
- { id: 'backup', x: 0, w: 3, order: 3, h: 3 },
- { id: 'network-exposure', x: 3, w: 3, order: 4, h: 5 },
- { id: 'apps', x: 0, w: 12, order: 5, h: 11 },
+ { id: 'active-processing',x: 6, w: 6, order: 1, h: 5 },
+ { id: 'quick-stats', x: 6, w: 6, order: 2, h: 3 },
+ { id: 'cos', x: 6, w: 6, order: 3, h: 4 },
+ { id: 'backup', x: 0, w: 3, order: 4, h: 3 },
+ { id: 'network-exposure', x: 3, w: 3, order: 5, h: 5 },
+ { id: 'apps', x: 0, w: 12, order: 6, h: 11 },
],
},
...INTENT_LAYOUTS.map((l) => ({ ...l, builtIn: true })),
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 637287438a..476bc637c0 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -247,6 +247,21 @@ export function getJob(jobId) {
return findJob(jobId);
}
+// Completion hooks may attach a generated artifact to a domain record after
+// the audio worker has emitted its result. Persist that attachment on the job
+// too so a remounted client can discover the created track without guessing.
+export async function updateJobResult(jobId, patch) {
+ const job = findJob(jobId);
+ if (!job || !patch || typeof patch !== 'object') return false;
+ job.result = { ...(job.result || {}), ...patch };
+ await persist();
+ return true;
+}
+
+export function getRunningJob() {
+ return running;
+}
+
export function listJobs({ status, kind, owner } = {}) {
const all = [
...(running ? [running] : []),
diff --git a/server/services/mediaJobQueue/sanitizeJob.js b/server/services/mediaJobQueue/sanitizeJob.js
new file mode 100644
index 0000000000..4a495a3442
--- /dev/null
+++ b/server/services/mediaJobQueue/sanitizeJob.js
@@ -0,0 +1,44 @@
+// Public projection of a media job. Keep worker-only paths and subprocess
+// details out of both the queue API and the processing dashboard.
+const PARAM_ALLOWLIST = new Set([
+ 'prompt', 'negativePrompt', 'modelId', 'model', 'effort',
+ 'width', 'height', 'numFrames', 'fps', 'steps', 'guidanceScale',
+ 'seed', 'tiling', 'disableAudio', 'mode', 'imageStrength',
+ 'cfgScale', 'guidance', 'quantize',
+ 'runId', 'runtime', 'datasetId', 'characterId', 'characterName',
+ 'triggerWord', 'rank', 'baseModelId', 'spriteRef', 'spriteWalk',
+]);
+
+const MUSIC_STUDIO_KEYS = new Set([
+ 'trackId', 'title', 'artistId', 'artist', 'albumId', 'lyricsEnabled', 'lyricsProvided',
+]);
+
+export function sanitizeJob(job) {
+ if (!job) return job;
+ const safeParams = job.params
+ ? Object.fromEntries(Object.entries(job.params)
+ .filter(([key]) => PARAM_ALLOWLIST.has(key) || key === 'musicStudio')
+ .map(([key, value]) => [
+ key,
+ key === 'musicStudio' && value && typeof value === 'object'
+ ? Object.fromEntries(Object.entries(value).filter(([nestedKey]) => MUSIC_STUDIO_KEYS.has(nestedKey)))
+ : value,
+ ]))
+ : undefined;
+ return {
+ id: job.id,
+ kind: job.kind,
+ owner: job.owner,
+ status: job.status,
+ queuedAt: job.queuedAt,
+ startedAt: job.startedAt,
+ completedAt: job.completedAt,
+ position: job.position,
+ progress: job.progress,
+ statusMsg: job.statusMsg,
+ etaMs: job.etaMs,
+ error: job.error,
+ result: job.result,
+ params: safeParams,
+ };
+}
diff --git a/server/services/musicStudioHook.js b/server/services/musicStudioHook.js
new file mode 100644
index 0000000000..92405b0cb0
--- /dev/null
+++ b/server/services/musicStudioHook.js
@@ -0,0 +1,87 @@
+/**
+ * Files completed Music Studio audio jobs onto their track, even when the
+ * browser that started the render has unmounted (#4353).
+ */
+import { createMediaJobImageHook } from './mediaJobImageHook.js';
+import { updateJobResult } from './mediaJobQueue/index.js';
+import * as tracks from './tracks/index.js';
+import * as albums from './albums/index.js';
+
+const hook = createMediaJobImageHook({
+ label: 'Music Studio',
+ initLog: '🎵 Music Studio completion hook initialized',
+ kind: 'audio',
+ tagKey: 'musicStudio',
+ identify: (tag) => (tag && (tag.trackId === null || typeof tag.trackId === 'string')
+ ? { trackId: tag.trackId || null } : null),
+ serializeKey: ({ trackId }) => trackId || 'standalone',
+ describe: ({ trackId }) => trackId || 'standalone',
+ extractResult: (job) => {
+ const filename = job.result?.filename;
+ if (typeof filename !== 'string' || !filename) return null;
+ const tag = job.params.musicStudio;
+ return {
+ filename,
+ durationSec: Number.isFinite(job.result?.durationSec) ? Math.round(job.result.durationSec) : null,
+ engine: typeof job.result?.engine === 'string' ? job.result.engine : null,
+ modelId: typeof job.result?.modelId === 'string' ? job.result.modelId : null,
+ prompt: job.params.prompt,
+ lyrics: job.params.lyrics,
+ lyricsEnabled: tag.lyricsEnabled === true,
+ lyricsProvided: tag.lyricsProvided === true,
+ title: tag.title,
+ artistId: tag.artistId,
+ artist: tag.artist,
+ albumId: tag.albumId,
+ };
+ },
+ attach: async ({ job, trackId, filename, durationSec, engine, modelId, prompt, lyrics, lyricsEnabled, lyricsProvided, title, artistId, artist, albumId }) => {
+ const current = trackId ? await tracks.getTrack(trackId) : null;
+ // A deleted target is a successful render but no longer an attach target.
+ if (trackId && !current) return null;
+ const { renders } = tracks.buildRenderAppend(current, {
+ audioFilename: filename,
+ prompt,
+ lyrics: lyricsEnabled ? lyrics : '',
+ engine,
+ modelId,
+ durationSec,
+ });
+ const meta = {
+ audioFilename: filename,
+ engine,
+ modelId,
+ durationSec,
+ prompt,
+ renders,
+ };
+ if (lyricsEnabled && lyricsProvided) meta.lyrics = lyrics;
+ const track = trackId
+ ? await tracks.updateTrack(trackId, meta)
+ : await tracks.createTrack({
+ title: title || prompt.slice(0, 60),
+ artistId,
+ artist,
+ albumId,
+ ...(lyricsEnabled && lyricsProvided ? { lyrics } : {}),
+ ...meta,
+ });
+ if (!trackId && track?.albumId) {
+ const album = await albums.getAlbum(track.albumId).catch(() => null);
+ if (album && !(album.trackIds || []).includes(track.id)) {
+ await albums.updateAlbum(track.albumId, { trackIds: [...(album.trackIds || []), track.id] }).catch(() => {});
+ }
+ }
+ await updateJobResult(job.id, { trackId: track.id });
+ return track;
+ },
+ onAttached: ({ trackId, filename }, track) => {
+ console.log(`🎵 Music Studio ${trackId || track?.id || 'new'} ← ${filename}`);
+ },
+});
+
+export function initMusicStudioHook() {
+ hook.init();
+}
+
+export const __testing = hook.__testing;
diff --git a/server/services/musicStudioHook.test.js b/server/services/musicStudioHook.test.js
new file mode 100644
index 0000000000..829b360c1f
--- /dev/null
+++ b/server/services/musicStudioHook.test.js
@@ -0,0 +1,67 @@
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+const queue = vi.hoisted(() => {
+ const listeners = new Set();
+ return {
+ events: {
+ on: (_event, handler) => listeners.add(handler),
+ off: (_event, handler) => listeners.delete(handler),
+ emit: (_event, job) => listeners.forEach((handler) => handler(job)),
+ },
+ updateJobResult: vi.fn(),
+ };
+});
+const trackStore = vi.hoisted(() => ({ getTrack: vi.fn(), buildRenderAppend: vi.fn(), updateTrack: vi.fn(), createTrack: vi.fn() }));
+const albumStore = vi.hoisted(() => ({ getAlbum: vi.fn(), updateAlbum: vi.fn() }));
+
+vi.mock('./mediaJobQueue/index.js', () => ({ mediaJobEvents: queue.events, updateJobResult: queue.updateJobResult }));
+vi.mock('./tracks/index.js', () => trackStore);
+vi.mock('./albums/index.js', () => albumStore);
+
+const { initMusicStudioHook, __testing } = await import('./musicStudioHook.js');
+
+describe('music studio completion hook', () => {
+ beforeEach(() => {
+ __testing.reset();
+ queue.updateJobResult.mockReset();
+ trackStore.getTrack.mockReset();
+ trackStore.buildRenderAppend.mockReset().mockReturnValue({ renders: [{ id: 'render-1' }] });
+ trackStore.updateTrack.mockReset().mockResolvedValue({ id: 'track-1' });
+ trackStore.createTrack.mockReset().mockResolvedValue({ id: 'track-new', albumId: 'album-1' });
+ albumStore.getAlbum.mockReset().mockResolvedValue({ trackIds: [] });
+ albumStore.updateAlbum.mockReset().mockResolvedValue({});
+ initMusicStudioHook();
+ });
+
+ it('attaches a completed render to an existing track and records its id', async () => {
+ trackStore.getTrack.mockResolvedValue({ id: 'track-1', renders: [] });
+ queue.events.emit('completed', {
+ id: 'job-1', kind: 'audio', queuedAt: new Date().toISOString(),
+ params: { prompt: 'fake prompt', lyrics: '[verse] fake', musicStudio: { trackId: 'track-1', lyricsEnabled: true, lyricsProvided: true } },
+ result: { filename: 'fake.wav', durationSec: 12, engine: 'acestep', modelId: 'a' },
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(trackStore.updateTrack).toHaveBeenCalledWith('track-1', expect.objectContaining({ audioFilename: 'fake.wav', lyrics: '[verse] fake' }));
+ expect(queue.updateJobResult).toHaveBeenCalledWith('job-1', { trackId: 'track-1' });
+ });
+
+ it('creates a standalone track, appends its album, and does not crash when target is deleted', async () => {
+ trackStore.createTrack.mockResolvedValue({ id: 'track-new', albumId: 'album-1' });
+ queue.events.emit('completed', {
+ id: 'job-2', kind: 'audio', queuedAt: new Date().toISOString(),
+ params: { prompt: 'fake prompt', musicStudio: { trackId: null, title: 'Fake song', albumId: 'album-1' } },
+ result: { filename: 'fake.wav', durationSec: 8, engine: 'musicgen', modelId: 'm' },
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(trackStore.createTrack).toHaveBeenCalledWith(expect.objectContaining({ title: 'Fake song', albumId: 'album-1' }));
+ expect(albumStore.updateAlbum).toHaveBeenCalledWith('album-1', { trackIds: ['track-new'] });
+
+ trackStore.getTrack.mockResolvedValue(null);
+ queue.events.emit('completed', {
+ id: 'job-3', kind: 'audio', queuedAt: new Date().toISOString(),
+ params: { prompt: 'fake prompt', musicStudio: { trackId: 'deleted-track' } },
+ result: { filename: 'orphan.wav' },
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(trackStore.updateTrack).not.toHaveBeenCalledWith('deleted-track', expect.anything());
+ });
+});