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: add federated audio provider contract (#4348)

[._.]/ Adam Eivyb3f5407dea34
diff --git a/.changelog/next/added-issue-4348.md b/.changelog/next/added-issue-4348.md
new file mode 100644
index 0000000000..1d00b5de7d
--- /dev/null
+++ b/.changelog/next/added-issue-4348.md
@@ -0,0 +1 @@
+- Add an authenticated federated audio provider API with conservative capacity admission and integrity-checked results (#4348).
diff --git a/client/src/components/settings/SharingTab.jsx b/client/src/components/settings/SharingTab.jsx
index a6b8639605..b5aecdf78f 100644
--- a/client/src/components/settings/SharingTab.jsx
+++ b/client/src/components/settings/SharingTab.jsx
@@ -1,8 +1,22 @@
import { useEffect, useState } from 'react';
-import { Save, Loader2, Users, ShieldCheck } from 'lucide-react';
+import { Save, Loader2, Users, ShieldCheck, Network } from 'lucide-react';
import toast from '../ui/Toast';
import BrailleSpinner from '../BrailleSpinner';
-import { getSettings, updateSettings } from '../../services/api';
+import { getAuthStatus, getSettings, listMusicEngines, updateSettings } from '../../services/api';
+
+const modelKey = ({ engine, modelId }) => `${engine}\u0000${modelId}`;
+const normalizeSelectedModels = (models) => Array.isArray(models)
+ ? models.filter((model) => model && typeof model.engine === 'string' && typeof model.modelId === 'string')
+ .map((model) => ({ ...model, engine: model.engine, modelId: model.modelId }))
+ : [];
+const stableModels = (models) => normalizeSelectedModels(models).map(modelKey).sort().join('\n');
+
+function modelReady(engine, model) {
+ if (!engine.runtimeReady || !engine.platformSupported) return false;
+ if (engine.cudaRequired && engine.cudaState !== 'available') return false;
+ if (engine.fixedModelInstall && engine.modelReadyById?.[model.id] !== true) return false;
+ return true;
+}
export function SharingTab() {
const [loading, setLoading] = useState(true);
@@ -16,10 +30,29 @@ export function SharingTab() {
// The settings PATCH shallow-merges top-level keys, so `federation` is
// replaced wholesale — carry the rest of the slice forward on every write.
const [federationSettings, setFederationSettings] = useState({});
+ const [authEnabled, setAuthEnabled] = useState(false);
+ const [musicEngines, setMusicEngines] = useState([]);
+ const [providerSettings, setProviderSettings] = useState({});
+ const [providerEnabled, setProviderEnabled] = useState(false);
+ const [providerMaxQueuedJobs, setProviderMaxQueuedJobs] = useState(2);
+ const [providerModels, setProviderModels] = useState([]);
+ const [savedProviderEnabled, setSavedProviderEnabled] = useState(false);
+ const [savedProviderMaxQueuedJobs, setSavedProviderMaxQueuedJobs] = useState(2);
+ const [savedProviderModels, setSavedProviderModels] = useState([]);
+ const [providerSaving, setProviderSaving] = useState(false);
useEffect(() => {
- getSettings({ silent: true })
- .then((settings) => {
+ // Engine health probes may spawn local Python checks on a cold cache. Load
+ // them independently so the existing sharing controls do not wait on that
+ // optional provider catalog.
+ listMusicEngines({ silent: true })
+ .then((music) => setMusicEngines(Array.isArray(music?.engines) ? music.engines : []))
+ .catch(() => setMusicEngines([]));
+ Promise.all([
+ getSettings({ silent: true }),
+ getAuthStatus({ silent: true }).catch(() => ({ enabled: false })),
+ ])
+ .then(([settings, auth]) => {
const display = settings?.sharingDisplayName || '';
const b = settings?.sharingBio || '';
setDisplayName(display);
@@ -29,12 +62,29 @@ export function SharingTab() {
const federation = settings?.federation && typeof settings.federation === 'object' ? settings.federation : {};
setFederationSettings(federation);
setStrictPull(federation.strictPullAuthorization === true);
+ setAuthEnabled(auth?.enabled === true);
+ const provider = federation.mediaProvider && typeof federation.mediaProvider === 'object'
+ ? federation.mediaProvider
+ : {};
+ const enabled = provider.enabled === true;
+ const maxQueuedJobs = Number.isInteger(provider.maxQueuedJobs) ? provider.maxQueuedJobs : 2;
+ const models = normalizeSelectedModels(provider.audioModels);
+ setProviderSettings(provider);
+ setProviderEnabled(enabled);
+ setProviderMaxQueuedJobs(maxQueuedJobs);
+ setProviderModels(models);
+ setSavedProviderEnabled(enabled);
+ setSavedProviderMaxQueuedJobs(maxQueuedJobs);
+ setSavedProviderModels(models);
})
.catch(() => toast.error('Failed to load settings'))
.finally(() => setLoading(false));
}, []);
const dirty = displayName !== savedDisplayName || bio !== savedBio;
+ const providerDirty = providerEnabled !== savedProviderEnabled
+ || providerMaxQueuedJobs !== savedProviderMaxQueuedJobs
+ || stableModels(providerModels) !== stableModels(savedProviderModels);
const handleSave = async () => {
setSaving(true);
@@ -63,6 +113,47 @@ export function SharingTab() {
toast.success(next ? 'Strict pull authorization on' : 'Strict pull authorization off');
};
+ const toggleProviderModel = (engine, modelId, checked) => {
+ const selected = { engine, modelId };
+ const key = modelKey(selected);
+ setProviderModels((current) => checked
+ ? (current.some((model) => modelKey(model) === key) ? current : [...current, selected])
+ : current.filter((model) => modelKey(model) !== key));
+ };
+
+ const handleProviderSave = async () => {
+ if (providerEnabled && !authEnabled) {
+ toast.error('Enable an instance password before sharing media capacity');
+ return;
+ }
+ if (providerEnabled && providerModels.length === 0) {
+ toast.error('Select at least one audio model');
+ return;
+ }
+ const maxQueuedJobs = Math.max(1, Math.min(20, Number(providerMaxQueuedJobs) || 1));
+ const mediaProvider = {
+ ...providerSettings,
+ enabled: providerEnabled,
+ maxQueuedJobs,
+ audioModels: normalizeSelectedModels(providerModels),
+ };
+ const federation = { ...federationSettings, mediaProvider };
+ setProviderSaving(true);
+ const merged = await updateSettings({ federation }, { silent: true }).catch(() => null);
+ setProviderSaving(false);
+ if (!merged) {
+ toast.error('Failed to save media provider settings');
+ return;
+ }
+ setFederationSettings(federation);
+ setProviderSettings(mediaProvider);
+ setProviderMaxQueuedJobs(maxQueuedJobs);
+ setSavedProviderEnabled(providerEnabled);
+ setSavedProviderMaxQueuedJobs(maxQueuedJobs);
+ setSavedProviderModels(normalizeSelectedModels(providerModels));
+ toast.success(providerEnabled ? 'Media provider enabled' : 'Media provider disabled');
+ };
+
if (loading) return <BrailleSpinner />;
return (
@@ -131,7 +222,7 @@ export function SharingTab() {
id="federation-strict-pull"
type="checkbox"
checked={strictPull}
- disabled={strictPullSaving}
+ disabled={strictPullSaving || providerSaving}
onChange={(e) => handleStrictPullToggle(e.target.checked)}
className="mt-1 h-4 w-4 accent-port-accent disabled:opacity-40"
/>
@@ -141,6 +232,105 @@ export function SharingTab() {
</span>
</label>
</div>
+
+ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6">
+ <div className="flex items-center gap-2 mb-2">
+ <Network size={16} className="text-port-accent" />
+ <h3 className="text-lg font-semibold text-white">Federated media provider</h3>
+ </div>
+ <p className="text-sm text-gray-400 mb-4">
+ Let registered PortOS peers submit allowlisted audio renders to this machine&apos;s durable media queue.
+ Prompts and job details stay out of capability status, and completed downloads include a SHA-256 integrity hash.
+ </p>
+
+ {!authEnabled && (
+ <div className="mb-4 rounded border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm text-amber-200">
+ An instance password is required for peer jobs. Configure one in the Security tab before enabling this provider.
+ </div>
+ )}
+
+ <div className="space-y-4">
+ <label htmlFor="federated-media-enabled" className="flex items-start gap-3 cursor-pointer">
+ <input
+ id="federated-media-enabled"
+ type="checkbox"
+ checked={providerEnabled}
+ disabled={providerSaving || strictPullSaving || (!authEnabled && !providerEnabled)}
+ onChange={(event) => setProviderEnabled(event.target.checked)}
+ className="mt-1 h-4 w-4 accent-port-accent disabled:opacity-40"
+ />
+ <span className="text-sm text-white">Accept audio generation jobs from authenticated registered peers</span>
+ </label>
+
+ <div>
+ <label htmlFor="federated-media-max-queued" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">
+ Shared active-job limit
+ </label>
+ <input
+ id="federated-media-max-queued"
+ type="number"
+ min="1"
+ max="20"
+ value={providerMaxQueuedJobs}
+ disabled={providerSaving || strictPullSaving}
+ onChange={(event) => setProviderMaxQueuedJobs(Number(event.target.value))}
+ className="w-28 px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm disabled:opacity-40"
+ />
+ <p className="mt-1 text-xs text-gray-500">
+ Remote admission stops when this many local and remote media jobs are already active.
+ </p>
+ </div>
+
+ <fieldset>
+ <legend className="block text-xs uppercase tracking-wider text-gray-500 mb-2">Allowed audio models</legend>
+ {musicEngines.length === 0 ? (
+ <p className="text-sm text-gray-500">The local music engine catalog is not available to configure.</p>
+ ) : (
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
+ {musicEngines.map((engine, engineIndex) => (
+ <div key={engine.id} className="rounded border border-port-border bg-port-bg/40 p-3">
+ <div className="text-sm font-medium text-white mb-2">{engine.name}</div>
+ <div className="space-y-2">
+ {(engine.models || []).map((model, modelIndex) => {
+ const selection = { engine: engine.id, modelId: model.id };
+ const checked = providerModels.some((candidate) => modelKey(candidate) === modelKey(selection));
+ const ready = modelReady(engine, model);
+ const inputId = `federated-media-model-${engineIndex}-${modelIndex}`;
+ return (
+ <label key={model.id} htmlFor={inputId} className="flex items-start gap-2 text-sm cursor-pointer">
+ <input
+ id={inputId}
+ type="checkbox"
+ checked={checked}
+ disabled={providerSaving || strictPullSaving || (!ready && !checked)}
+ onChange={(event) => toggleProviderModel(engine.id, model.id, event.target.checked)}
+ className="mt-0.5 h-4 w-4 accent-port-accent disabled:opacity-40"
+ />
+ <span className={ready ? 'text-gray-200' : 'text-gray-500'}>
+ {model.name}{!ready && ' (not ready)'}
+ </span>
+ </label>
+ );
+ })}
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </fieldset>
+
+ <button
+ type="button"
+ onClick={handleProviderSave}
+ disabled={!providerDirty || providerSaving || strictPullSaving
+ || (providerEnabled && (!authEnabled || providerModels.length === 0))}
+ className="inline-flex items-center justify-center gap-2 min-h-[40px] px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
+ >
+ {providerSaving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
+ {providerSaving ? 'Saving...' : 'Save provider'}
+ </button>
+ </div>
+ </div>
</div>
);
}
diff --git a/client/src/components/settings/SharingTab.test.jsx b/client/src/components/settings/SharingTab.test.jsx
index 6ee7152620..127cc609c8 100644
--- a/client/src/components/settings/SharingTab.test.jsx
+++ b/client/src/components/settings/SharingTab.test.jsx
@@ -2,7 +2,9 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
vi.mock('../../services/api', () => ({
+ getAuthStatus: vi.fn(),
getSettings: vi.fn(),
+ listMusicEngines: vi.fn(),
updateSettings: vi.fn(),
}));
vi.mock('../ui/Toast', () => ({
@@ -14,17 +16,101 @@ vi.mock('../ui/Toast', () => ({
}),
}));
-import { getSettings, updateSettings } from '../../services/api';
+import { getAuthStatus, getSettings, listMusicEngines, updateSettings } from '../../services/api';
import { SharingTab } from './SharingTab';
const strictToggle = () => screen.getByLabelText(/Enforce per-peer sharing settings/i);
beforeEach(() => {
vi.clearAllMocks();
+ getAuthStatus.mockResolvedValue({ enabled: false });
getSettings.mockResolvedValue({ sharingDisplayName: '', sharingBio: '' });
+ listMusicEngines.mockResolvedValue({ engines: [] });
updateSettings.mockResolvedValue({});
});
+describe('SharingTab — federated media provider (#4348)', () => {
+ const providerToggle = () => screen.getByLabelText(/Accept audio generation jobs/i);
+
+ it('keeps provider opt-in disabled until an instance password exists', async () => {
+ render(<SharingTab />);
+ await waitFor(() => expect(providerToggle()).toBeInTheDocument());
+ expect(providerToggle()).toBeDisabled();
+ expect(screen.getByText(/instance password is required/i)).toBeInTheDocument();
+ });
+
+ it('persists an allowlisted model while preserving the rest of the federation slice', async () => {
+ getAuthStatus.mockResolvedValue({ enabled: true });
+ getSettings.mockResolvedValue({
+ federation: {
+ strictPullAuthorization: false,
+ somethingElse: 'keep-me',
+ mediaProvider: {
+ enabled: false,
+ maxQueuedJobs: 2,
+ audioModels: [{ engine: 'minimax-music3', modelId: 'minimax-music3', futureModelField: 'keep-model-too' }],
+ futureField: 'keep-too',
+ },
+ },
+ });
+ listMusicEngines.mockResolvedValue({
+ engines: [{
+ id: 'minimax-music3',
+ name: 'MiniMax Music 3',
+ runtimeReady: true,
+ platformSupported: true,
+ cudaRequired: true,
+ cudaState: 'available',
+ fixedModelInstall: true,
+ modelReadyById: { 'minimax-music3': true },
+ models: [{ id: 'minimax-music3', name: 'MiniMax model' }],
+ }],
+ });
+
+ render(<SharingTab />);
+ await waitFor(() => expect(providerToggle()).toBeEnabled());
+ await waitFor(() => expect(screen.getByLabelText('MiniMax model')).toBeInTheDocument());
+ fireEvent.click(providerToggle());
+ fireEvent.click(screen.getByRole('button', { name: 'Save provider' }));
+
+ await waitFor(() => expect(updateSettings).toHaveBeenCalledWith({
+ federation: {
+ strictPullAuthorization: false,
+ somethingElse: 'keep-me',
+ mediaProvider: {
+ enabled: true,
+ maxQueuedJobs: 2,
+ audioModels: [{
+ engine: 'minimax-music3',
+ modelId: 'minimax-music3',
+ futureModelField: 'keep-model-too',
+ }],
+ futureField: 'keep-too',
+ },
+ },
+ }, { silent: true }));
+ });
+
+ it('lets an auth-off install disable a provider that was previously enabled', async () => {
+ getSettings.mockResolvedValue({
+ federation: {
+ mediaProvider: {
+ enabled: true,
+ maxQueuedJobs: 2,
+ audioModels: [{ engine: 'minimax-music3', modelId: 'minimax-music3' }],
+ },
+ },
+ });
+ render(<SharingTab />);
+ await waitFor(() => expect(providerToggle()).toBeEnabled());
+ fireEvent.click(providerToggle());
+ fireEvent.click(screen.getByRole('button', { name: 'Save provider' }));
+ await waitFor(() => expect(updateSettings).toHaveBeenCalledWith(expect.objectContaining({
+ federation: expect.objectContaining({ mediaProvider: expect.objectContaining({ enabled: false }) }),
+ }), { silent: true }));
+ });
+});
+
describe('SharingTab — federation pull authorization (#3659)', () => {
it('defaults the strict-pull toggle off when the setting is absent', async () => {
render(<SharingTab />);
diff --git a/data.reference/settings.json b/data.reference/settings.json
index 3fd040e6c7..9db31b01f0 100644
--- a/data.reference/settings.json
+++ b/data.reference/settings.json
@@ -54,5 +54,12 @@
"apiAccess": {
"voice": { "exposed": false, "requireAuth": false },
"sdapi": { "exposed": false, "requireAuth": false }
+ },
+ "federation": {
+ "mediaProvider": {
+ "enabled": false,
+ "maxQueuedJobs": 2,
+ "audioModels": []
+ }
}
-}
\ No newline at end of file
+}
diff --git a/docs/API.md b/docs/API.md
index c67d2170c0..ce739e4bcf 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -513,6 +513,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom
| `/api/health` | Health check |
| `/api/insights` | Cross-domain insights |
| `/api/instances`, `/api/sync`, `/api/peer-sync`, `/api/sharing` | Federation / peer sync (see [COMPANION_APP_API.md](./COMPANION_APP_API.md)) |
+| `/api/federation/media/v1` | Authenticated queued peer audio provider (see [FEDERATED_MEDIA_PROVIDERS.md](./FEDERATED_MEDIA_PROVIDERS.md)) |
| `/api/mortalloom` | MortalLoom (iCloud-JSON sync precedent) |
| `/api/review` | Review queue |
| `/api/settings` | App settings |
diff --git a/docs/FEDERATED_MEDIA_PROVIDERS.md b/docs/FEDERATED_MEDIA_PROVIDERS.md
new file mode 100644
index 0000000000..fcefe493ef
--- /dev/null
+++ b/docs/FEDERATED_MEDIA_PROVIDERS.md
@@ -0,0 +1,92 @@
+# Federated Media Providers
+
+PortOS can opt in to serving local media-generation capacity to another registered PortOS peer. The first wire contract, `/api/federation/media/v1`, supports queued audio generation through the existing durable `mediaJobQueue` and local music engines.
+
+This is provider-side infrastructure. A peer can call the contract directly, but automatic provider discovery, selection, failover, and consumer-side commission reconciliation are later slices of issue #4348.
+
+## Enable a provider
+
+1. In **Settings → Security**, configure an instance password. The provider API remains closed when authentication is off, even though ordinary PortOS APIs normally trust the private network in that posture.
+2. Register the consumer under **Instances**. The consumer must store this provider's Basic credential on its peer record and send its own registered instance id on every request.
+3. Install and verify the desired music runtime and model under **Music**. A model must be locally ready before it can be advertised or accept work.
+4. In **Settings → Sharing → Federated media provider**, select the allowed audio models, choose the shared active-job limit, and enable the provider.
+
+The default is disabled:
+
+```json
+{
+ "federation": {
+ "mediaProvider": {
+ "enabled": false,
+ "maxQueuedJobs": 2,
+ "audioModels": []
+ }
+ }
+}
+```
+
+An older install without this settings slice behaves exactly like the default above. Known fields are validated while unknown future fields are preserved, so rolling an install back does not erase newer provider settings.
+
+## Authentication and identity
+
+Every request requires both:
+
+- `Authorization: Basic …`, verified against the provider instance password by the global auth gate; browser session and Bearer authentication are deliberately rejected for this peer-only surface.
+- `X-PortOS-Instance-Id: <consumer-instance-id>`, resolving to an enabled peer registered on the provider.
+
+Use `peerFetch` for PortOS-to-PortOS calls; it already attaches the configured Basic credential and local instance id. The instance-id header identifies the registered peer, while the Basic credential authenticates access to this PortOS install.
+
+As with existing peer sync, the instance-id header is self-asserted. Basic authentication proves access to the provider install; it does not cryptographically bind that credential to one peer row. Owner-scoped job lookup is therefore a least-disclosure boundary for cooperating peers on the trusted network, not protection from another holder of the same instance password spoofing a registered id.
+
+## Wire v1
+
+All successful JSON responses include `wireVersion: 1`. The version is also fixed in the route path so an incompatible future contract can coexist rather than silently changing v1.
+
+| Method | Endpoint | Purpose |
+|--------|----------|---------|
+| `GET` | `/api/federation/media/v1/status` | Fresh allowlisted capabilities, CUDA/runtime/model readiness, queue depth, and staleness window |
+| `POST` | `/api/federation/media/v1/jobs` | Submit an idempotent audio job; returns `202` for new work and `200` for a replay |
+| `GET` | `/api/federation/media/v1/jobs/:id` | Read an owner-scoped sanitized job projection |
+| `POST` | `/api/federation/media/v1/jobs/:id/cancel` | Cancel the caller's queued or running job |
+| `GET` | `/api/federation/media/v1/jobs/:id/result` | Download completed WAV bytes with integrity metadata |
+
+### Capacity status
+
+`GET /status` is computed live and carries `generatedAt` plus `staleAfterMs`. Consumers must stop assigning new work after that window instead of treating stale capacity as available.
+
+CUDA has three states: `available`, `absent`, and `unknown`. A CUDA model is ready only when the state is positively `available`; a failed or ambiguous probe blocks admission. Runtime, host-platform, exact fixed-checkpoint readiness, and queue capacity are similarly fail-closed.
+
+The configured `maxQueuedJobs` is conservative: all currently queued/running local and remote media work counts against it. This prevents a reachable route from advertising spare capacity while the machine's shared media lane is already occupied.
+
+Status never includes prompts, lyrics, credentials, local paths, commission records, or private creative metadata.
+
+### Submit a job
+
+Send a unique, stable `Idempotency-Key` header with the text-only request:
+
+```json
+{
+ "engine": "minimax-music3",
+ "modelId": "minimax-music3",
+ "prompt": "A fictional cinematic synth theme",
+ "lyrics": "[instrumental]",
+ "durationSec": 60,
+ "durationMode": "manual"
+}
+```
+
+Unknown fields are rejected. The contract accepts no source URL, filesystem path, shell argument, provider credential, or arbitrary proxy target.
+
+Within the queue's retained job window, repeating the same caller/key/body returns the original job without enqueuing again. Reusing that key with a different body returns `409 MEDIA_PROVIDER_IDEMPOTENCY_CONFLICT`. Job lookup and cancellation return the same not-found response for an unknown id and another peer's id.
+
+The provider persists accepted work in the existing machine-local `data/media-jobs.json` queue. No commission, CoS, schedule, taste, or Digital Twin record is copied to the provider. The submitted prompt/lyrics exist only in the provider's local queue record needed to execute that explicit job.
+
+### Download and verify a result
+
+A completed job projection includes `result.sha256`, `result.sizeBytes`, `result.mimeType`, and an owner-scoped `result.downloadUrl`. The download repeats the digest in `X-Content-SHA256`. Consumers should stream to a temporary file, verify both byte count and SHA-256, then atomically promote it into their local library. A missing or changed provider-side file returns a typed unavailable result instead of a dangling path.
+
+Provider filesystem paths and original filenames never cross the API boundary.
+
+## Current boundary
+
+Wire v1 currently provides audio only. Still remaining from #4348 are consumer-side `peerFetch` proxying and restart reconciliation, converting the Music studio's synchronous generation route to the durable queue, capacity-aware peer selection/failover, remote image/video jobs and input-asset transfer, and aggregate provider health in Instances/System Health.
diff --git a/docs/README.md b/docs/README.md
index ffe8e4670a..bc0ee6793d 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -9,6 +9,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo
| [ARCHITECTURE.md](./ARCHITECTURE.md) | System design: React client, Express server, PM2 satellites, PostgreSQL + `data/` files |
| [API.md](./API.md) | REST endpoints, complete route-domain index, Socket.IO events |
| [COMPANION_APP_API.md](./COMPANION_APP_API.md) | PortDeck native iOS companion client discovery and HTTP API contract |
+| [FEDERATED_MEDIA_PROVIDERS.md](./FEDERATED_MEDIA_PROVIDERS.md) | Authenticated, capacity-aware peer audio provider wire contract and setup |
| [STORAGE.md](./STORAGE.md) | Storage classification contract — PostgreSQL vs filesystem, new-data-store checklist |
| [BACKUP.md](./BACKUP.md) | Filesystem snapshots + PostgreSQL dumps, restore semantics |
| [PORTS.md](./PORTS.md) | Port allocation (5553–5561) and how 5555/5553/5554 relate |
diff --git a/server/index.js b/server/index.js
index bb5b24074d..4778eea877 100644
--- a/server/index.js
+++ b/server/index.js
@@ -112,6 +112,7 @@ import videoGenRoutes from './routes/videoGen.js';
import videoDownloadRoutes from './routes/videoDownload.js';
import videoTimelineRoutes from './routes/videoTimeline.js';
import mediaJobsRoutes from './routes/mediaJobs.js';
+import federatedMediaRoutes from './routes/federatedMedia.js';
import creativeDirectorRoutes from './routes/creativeDirector.js';
import creativeCommissionRoutes from './routes/creativeCommissions.js';
import gamesRoutes from './routes/games.js';
@@ -344,6 +345,7 @@ app.use('/api/video-gen', videoGenRoutes);
app.use('/api/devtools/video-download', videoDownloadRoutes);
app.use('/api/video-timeline', videoTimelineRoutes);
app.use('/api/media-jobs', mediaJobsRoutes);
+app.use('/api/federation/media/v1', federatedMediaRoutes);
app.use('/api/creative-director', creativeDirectorRoutes);
app.use('/api/creative-commission', creativeCommissionRoutes);
app.use('/api/games', gamesRoutes);
diff --git a/server/lib/authGate.js b/server/lib/authGate.js
index 311c4ce6a7..f9d6127b93 100644
--- a/server/lib/authGate.js
+++ b/server/lib/authGate.js
@@ -65,6 +65,11 @@ const isPublicPath = (path) => {
// the cookie or Authorization: Bearer header.
export const authGate = async (req, res, next) => {
const enabled = await isAuthEnabled();
+ // Downstream peer-provider routes need to distinguish a verified peer Basic
+ // credential from an interactive browser session. The global gate is the
+ // one authoritative verifier, so leave a request-local, non-secret marker
+ // instead of re-running password verification in each provider route.
+ req.portosAuthContext = { enabled, authenticated: false, method: null };
if (!enabled) return next();
// CSRF guard runs FIRST, before isPublicPath — public endpoints like
// /api/auth/logout still mutate state (clear the cookie + revoke the
@@ -89,14 +94,20 @@ export const authGate = async (req, res, next) => {
const settings = await getSettings();
if (isRegistryPublic(settings, path)) return next();
const token = extractToken(req);
- if (await verifySession(token)) return next();
+ if (await verifySession(token)) {
+ req.portosAuthContext = { enabled: true, authenticated: true, method: 'session' };
+ return next();
+ }
// Also accept HTTP Basic auth — used by peer-to-peer federation probes.
// The peer sends `Authorization: Basic <base64(:password)>` (the Instances
// UI stores username + password; only the password is validated here since
// PortOS is single-user). scrypt verification is intentionally slow but runs
// in libuv's thread pool so it doesn't block the event loop.
const basicPassword = extractBasicPassword(req);
- if (basicPassword && await verifyBasicPassword(basicPassword)) return next();
+ if (basicPassword && await verifyBasicPassword(basicPassword)) {
+ req.portosAuthContext = { enabled: true, authenticated: true, method: 'basic' };
+ return next();
+ }
// /data/* is hit directly by <img>/<audio>/<video> tags which don't show a
// structured-JSON error — return a plain 401 there. API callers expect the
// PortOS error envelope.
diff --git a/server/lib/authGate.test.js b/server/lib/authGate.test.js
index 33cf0a229c..a6eb27a7ae 100644
--- a/server/lib/authGate.test.js
+++ b/server/lib/authGate.test.js
@@ -66,8 +66,10 @@ const runGate = async (gate, req) => new Promise((resolve) => {
describe('authGate middleware', () => {
it('is a no-op when auth is disabled', async () => {
const { authGate } = await import('./authGate.js');
- const result = await runGate(authGate, { path: '/api/cos', headers: {} });
+ const req = { path: '/api/cos', headers: {} };
+ const result = await runGate(authGate, req);
expect(result.called).toBe(true);
+ expect(req.portosAuthContext).toEqual({ enabled: false, authenticated: false, method: null });
});
it('passes /api/auth/login through even when auth is enabled', async () => {
@@ -392,11 +394,13 @@ describe('authGate HTTP Basic auth (peer federation)', () => {
const auth = await import('../services/auth.js');
await auth.setPassword({ newPassword: 'peer-secret' });
const { authGate } = await import('./authGate.js');
- const result = await runGate(authGate, {
+ const req = {
path: '/api/cos',
headers: { authorization: basicHeader('peer-secret') },
- });
+ };
+ const result = await runGate(authGate, req);
expect(result.called).toBe(true);
+ expect(req.portosAuthContext).toEqual({ enabled: true, authenticated: true, method: 'basic' });
});
it('also works with a non-empty username (username is ignored)', async () => {
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 064c250c8a..5cd06c97a4 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -695,6 +695,47 @@ export const musicSettingsSchema = z.object({
}).partial().optional(),
});
+// Federated media is an opt-in provider surface. The outer objects remain
+// passthrough for mixed-version peers/settings UIs: a rolled-back install must
+// preserve fields introduced by a newer build while still validating every
+// field this build understands.
+export const federatedMediaModelSchema = z.object({
+ engine: z.string().trim().min(1).max(80),
+ modelId: z.string().trim().min(1).max(256),
+}).passthrough();
+
+export const federatedMediaProviderSettingsSchema = z.object({
+ enabled: z.boolean().optional(),
+ maxQueuedJobs: z.number().int().min(1).max(20).optional(),
+ audioModels: z.array(federatedMediaModelSchema).max(100).refine(
+ (models) => new Set(models.map((model) => `${model.engine}\u0000${model.modelId}`)).size === models.length,
+ { message: 'audioModels must not contain duplicate engine/model pairs' },
+ ).optional(),
+}).passthrough();
+
+export const federationSettingsSchema = z.object({
+ strictPullAuthorization: z.boolean().optional(),
+ mediaProvider: federatedMediaProviderSettingsSchema.optional(),
+}).passthrough();
+
+// Provider submissions intentionally accept text + model selection only. No
+// URL, local path, command, or provider credential can ride this contract.
+export const federatedMediaJobSubmissionSchema = z.object({
+ engine: z.string().trim().min(1).max(80),
+ modelId: z.string().trim().min(1).max(256),
+ prompt: z.string().trim().min(1).max(8000),
+ lyrics: z.string().max(50_000).optional(),
+ durationSec: z.number().finite().min(1).max(3600).optional(),
+ durationMode: z.enum(['auto', 'manual']).optional(),
+}).strict();
+
+export const federatedMediaIdempotencyKeySchema = z.string().trim().min(1).max(200)
+ .regex(/^[A-Za-z0-9._:-]+$/, 'Idempotency-Key contains unsupported characters');
+
+export const federatedMediaJobParamsSchema = z.object({
+ id: z.string().uuid(),
+}).strict();
+
// Creative Director settings slice. Each LLM-backed stage can pin its own
// provider/model instead of inheriting the system default. `evaluation` is a
// direct vision API call (blank = auto-pick a local vision model, else fall
diff --git a/server/routes/federatedMedia.js b/server/routes/federatedMedia.js
new file mode 100644
index 0000000000..337c6ee147
--- /dev/null
+++ b/server/routes/federatedMedia.js
@@ -0,0 +1,76 @@
+/**
+ * Versioned, allowlisted peer-provider API. All routes sit behind authGate and
+ * additionally require its verified-Basic marker plus a registered peer id.
+ */
+
+import { Router } from 'express';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import {
+ federatedMediaIdempotencyKeySchema,
+ federatedMediaJobParamsSchema,
+ federatedMediaJobSubmissionSchema,
+ validateRequest,
+} from '../lib/validation.js';
+import {
+ authorizeFederatedMediaPeer,
+ cancelFederatedMediaJob,
+ describeFederatedMediaJob,
+ getFederatedMediaProviderStatus,
+ getFederatedMediaResult,
+ submitFederatedMediaJob,
+} from '../services/federatedMediaProvider.js';
+
+const router = Router();
+
+router.get('/status', asyncHandler(async (req, res) => {
+ const { config } = await authorizeFederatedMediaPeer(req);
+ res.json(await getFederatedMediaProviderStatus(config));
+}));
+
+router.post('/jobs', asyncHandler(async (req, res) => {
+ const { callerId, config } = await authorizeFederatedMediaPeer(req);
+ const input = validateRequest(federatedMediaJobSubmissionSchema, req.body);
+ const idempotencyKey = validateRequest(
+ federatedMediaIdempotencyKeySchema,
+ req.get('Idempotency-Key'),
+ );
+ const result = await submitFederatedMediaJob({ callerId, config, input, idempotencyKey });
+ res.status(result.replayed ? 200 : 202).json(result.job);
+}));
+
+router.get('/jobs/:id', asyncHandler(async (req, res) => {
+ const { callerId } = await authorizeFederatedMediaPeer(req);
+ const { id } = validateRequest(federatedMediaJobParamsSchema, req.params);
+ res.json(await describeFederatedMediaJob(callerId, id));
+}));
+
+router.post('/jobs/:id/cancel', asyncHandler(async (req, res) => {
+ const { callerId } = await authorizeFederatedMediaPeer(req);
+ const { id } = validateRequest(federatedMediaJobParamsSchema, req.params);
+ res.json(await cancelFederatedMediaJob(callerId, id));
+}));
+
+router.get('/jobs/:id/result', asyncHandler(async (req, res, next) => {
+ const { callerId } = await authorizeFederatedMediaPeer(req);
+ const { id } = validateRequest(federatedMediaJobParamsSchema, req.params);
+ const result = await getFederatedMediaResult(callerId, id);
+ res.set({
+ 'Cache-Control': 'private, no-store',
+ 'Content-Disposition': `attachment; filename="${id}.wav"`,
+ 'Content-Length': String(result.metadata.sizeBytes),
+ 'Content-Type': result.metadata.mimeType,
+ 'X-Content-SHA256': result.metadata.sha256,
+ });
+ // sendFile opens after the integrity projection was built, so a user could
+ // delete the local result in that narrow window. Replace its filesystem-rich
+ // error with the typed provider envelope before it reaches the client.
+ res.sendFile(result.path, (err) => {
+ if (!err) return;
+ next(new ServerError('Provider result became unavailable', {
+ status: 410,
+ code: 'MEDIA_PROVIDER_RESULT_UNAVAILABLE',
+ }));
+ });
+}));
+
+export default router;
diff --git a/server/routes/federatedMedia.test.js b/server/routes/federatedMedia.test.js
new file mode 100644
index 0000000000..87fa81acd0
--- /dev/null
+++ b/server/routes/federatedMedia.test.js
@@ -0,0 +1,107 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+const provider = vi.hoisted(() => ({
+ replayed: false,
+ resultPath: '',
+ authorize: vi.fn(async () => ({
+ callerId: 'peer-example',
+ config: { enabled: true, maxQueuedJobs: 2, audioModels: [] },
+ })),
+ status: vi.fn(async () => ({ wireVersion: 1, status: 'ready' })),
+ submit: vi.fn(async () => ({
+ replayed: provider.replayed,
+ job: { wireVersion: 1, id: '00000000-0000-4000-8000-000000000001', status: 'queued' },
+ })),
+ describe: vi.fn(async (_caller, id) => ({ wireVersion: 1, id, status: 'queued' })),
+ cancel: vi.fn(async (_caller, id) => ({ wireVersion: 1, id, status: 'canceled' })),
+ result: vi.fn(async () => ({
+ path: provider.resultPath,
+ metadata: { mimeType: 'audio/wav', sizeBytes: 4, sha256: 'a'.repeat(64) },
+ })),
+}));
+
+vi.mock('../services/federatedMediaProvider.js', () => ({
+ authorizeFederatedMediaPeer: (...args) => provider.authorize(...args),
+ getFederatedMediaProviderStatus: (...args) => provider.status(...args),
+ submitFederatedMediaJob: (...args) => provider.submit(...args),
+ describeFederatedMediaJob: (...args) => provider.describe(...args),
+ cancelFederatedMediaJob: (...args) => provider.cancel(...args),
+ getFederatedMediaResult: (...args) => provider.result(...args),
+}));
+
+import federatedMediaRoutes from './federatedMedia.js';
+
+let tempRoot;
+
+beforeAll(() => {
+ tempRoot = mkdtempSync(join(tmpdir(), 'portos-federated-media-route-'));
+ provider.resultPath = join(tempRoot, 'result.wav');
+ writeFileSync(provider.resultPath, 'RIFF');
+});
+
+afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ provider.replayed = false;
+});
+
+function buildApp() {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/federation/media/v1', federatedMediaRoutes);
+ app.use(errorMiddleware);
+ return app;
+}
+
+const jobId = '00000000-0000-4000-8000-000000000001';
+
+describe('federated media routes', () => {
+ it('requires an Idempotency-Key before submitting work', async () => {
+ const response = await request(buildApp()).post('/api/federation/media/v1/jobs').send({
+ engine: 'minimax-music3', modelId: 'minimax-music3', prompt: 'test prompt',
+ });
+ expect(response.status).toBe(400);
+ expect(response.body.code).toBe('VALIDATION_ERROR');
+ expect(provider.submit).not.toHaveBeenCalled();
+ });
+
+ it('returns 202 for a new job and 200 for an idempotent replay', async () => {
+ const body = { engine: 'minimax-music3', modelId: 'minimax-music3', prompt: 'test prompt' };
+ const created = await request(buildApp()).post('/api/federation/media/v1/jobs')
+ .set('Idempotency-Key', 'commission-1').send(body);
+ expect(created.status).toBe(202);
+ expect(provider.submit).toHaveBeenCalledWith(expect.objectContaining({
+ callerId: 'peer-example', idempotencyKey: 'commission-1', input: body,
+ }));
+
+ provider.replayed = true;
+ const replay = await request(buildApp()).post('/api/federation/media/v1/jobs')
+ .set('Idempotency-Key', 'commission-1').send(body);
+ expect(replay.status).toBe(200);
+ });
+
+ it('rejects unknown request fields so paths and URLs cannot become an implicit proxy', async () => {
+ const response = await request(buildApp()).post('/api/federation/media/v1/jobs')
+ .set('Idempotency-Key', 'commission-1').send({
+ engine: 'minimax-music3', modelId: 'minimax-music3', prompt: 'test',
+ sourcePath: '/tmp/private.wav',
+ });
+ expect(response.status).toBe(400);
+ expect(provider.submit).not.toHaveBeenCalled();
+ });
+
+ it('serves completed bytes with an integrity header and no source path', async () => {
+ const response = await request(buildApp()).get(`/api/federation/media/v1/jobs/${jobId}/result`);
+ expect(response.status).toBe(200);
+ expect(response.headers['content-type']).toContain('audio/wav');
+ expect(response.headers['x-content-sha256']).toBe('a'.repeat(64));
+ expect(response.headers['content-disposition']).toContain(`${jobId}.wav`);
+ });
+});
diff --git a/server/routes/music.js b/server/routes/music.js
index f2d35eee8f..74b8c0bb32 100644
--- a/server/routes/music.js
+++ b/server/routes/music.js
@@ -31,10 +31,11 @@ import { validateRequest } from '../lib/validation.js';
import { createLineReader } from '../lib/streamLines.js';
import { SETUP_IMAGE_VIDEO_SCRIPT, spawnSetupScript, stopSetupScript } from '../lib/setupScriptRunner.js';
import {
- ENGINES, DEFAULT_ENGINE_ID, getEngine, getEngineModel, isEngineHealthy, isEnginePlatformSupported,
+ ENGINES, getEngine, isEngineHealthy, isEnginePlatformSupported,
enginePlatformLabel, generateMusic,
} from '../services/pipeline/musicGen.js';
import { listEngineModels, addAudioModel, removeAudioModel, isValidRepoId } from '../services/audioModels.js';
+import { listMusicEngineCapabilities } from '../services/musicEngineCapabilities.js';
import { describeMusic, writeLyrics } from '../services/musicDesigner.js';
import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';
import { createInstallLogger } from '../lib/installLogger.js';
@@ -50,65 +51,7 @@ const router = Router();
// support, and a `ready` flag (the opt-in venv is provisioned). The UI gates its
// Generate affordance + shows the install hint from this.
router.get('/engines', asyncHandler(async (_req, res) => {
- const cuda = await getCudaCapability();
- const engines = await Promise.all(Object.values(ENGINES).map(async (engine) => {
- const fixedModels = engine.fixedModelInstall ? engine.models : [];
- const modelReadyById = engine.fixedModelInstall
- ? Object.fromEntries(await Promise.all(fixedModels.map(async (model) => [
- model.id,
- (await inspectModelCache(model.repo, { revision: model.revision }).catch(() => ({ cached: false }))).cached === true,
- ])))
- : null;
- // `modelReady` remains an aggregate for older clients. Newer clients gate
- // generation against the selected model in `modelReadyById`, so having the
- // smaller MLX checkpoint cached does not falsely green-light its BF16 peer.
- const modelReady = modelReadyById ? Object.values(modelReadyById).some(Boolean) : true;
- // The one checkpoint a fixed-model engine installs. Resolved by
- // defaultModelId, not position, so readiness + size stay attached to the
- // model the client actually downloads and renders with.
- const fixedModel = engine.fixedModelInstall ? getEngineModel(engine.id, engine.defaultModelId) : null;
- const modelSizeGbById = engine.fixedModelInstall
- ? Object.fromEntries(fixedModels.map((model) => [model.id, model.downloadSizeGb ?? null]))
- : null;
- // isEngineHealthy, not isEngineReady: a half-built venv (install died
- // mid-pip) still has its interpreter, and reporting that as runtimeReady
- // hides the install affordance on a backend that cannot generate.
- const runtimeReady = await isEngineHealthy(engine.id);
- return ({
- id: engine.id,
- name: engine.name,
- models: await listEngineModels(engine.id),
- defaultModelId: engine.defaultModelId,
- minDurationSec: engine.minDurationSec,
- maxDurationSec: engine.maxDurationSec,
- defaultDurationSec: engine.defaultDurationSec,
- lyrics: engine.lyrics === true,
- autoDuration: engine.autoDuration === true,
- // Whether this engine can render an arbitrary HuggingFace checkpoint (gates
- // the "install/select model" UI). ACE-Step resolves a single foundation
- // checkpoint via checkpoint_dir, so custom repos don't apply to it.
- customModels: engine.customModels === true,
- fixedModelInstall: engine.fixedModelInstall === true,
- modelReady,
- ...(modelReadyById ? { modelReadyById } : {}),
- // Rough download footprint for the fixed weights, so the install button can
- // say how big the pull is before the user commits to it.
- modelSizeGb: fixedModel?.downloadSizeGb ?? null,
- ...(modelSizeGbById ? { modelSizeGbById } : {}),
- runtimeReady,
- cudaRequired: engine.cudaRequired === true,
- // false when this host can never run the backend (e.g. MLX MusicGen off
- // Apple Silicon) — the UI shows "unavailable" instead of an Install button
- // whose installer would skip and exit 0.
- platformSupported: isEnginePlatformSupported(engine.id),
- platformLabel: enginePlatformLabel(engine.id),
- cudaState: engine.cudaRequired ? cuda.status : 'available',
- ready: runtimeReady && (!engine.cudaRequired || cuda.status === 'available') && modelReady,
- installEnv: engine.installEnv,
- venvDefault: engine.venvDefault,
- });
- }));
- res.json({ engines, defaultEngine: DEFAULT_ENGINE_ID });
+ res.json(await listMusicEngineCapabilities());
}));
// --- Install music runtime venvs -------------------------------------------
diff --git a/server/routes/settings.js b/server/routes/settings.js
index aa268d7868..7ce36496fc 100644
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@ -11,7 +11,7 @@ import {
} from '../services/mediaJobQueue/index.js';
import { asyncHandler } from '../lib/errorHandler.js';
import { isPlainObject } from '../lib/objects.js';
-import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, validateRequest } from '../lib/validation.js';
+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, federationSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, validateRequest } from '../lib/validation.js';
const router = Router();
@@ -159,6 +159,9 @@ router.put('/', asyncHandler(async (req, res) => {
if (req.body?.music !== undefined) {
validateRequest(musicSettingsSchema.partial(), req.body.music);
}
+ if (req.body?.federation !== undefined) {
+ validateRequest(federationSettingsSchema, req.body.federation);
+ }
// Home location ({ lat, lon }) read by the weather_now voice tool. The schema
// already makes both fields optional + nullable (clearing falls back to the
// tool default), and the refine enforces both-or-neither — so validate the
diff --git a/server/routes/settings.test.js b/server/routes/settings.test.js
index dcc3dc66bb..e91e9e9c5a 100644
--- a/server/routes/settings.test.js
+++ b/server/routes/settings.test.js
@@ -83,6 +83,50 @@ describe('Settings routes — apiAccess slice', () => {
});
});
+describe('Settings routes — federated media provider slice (#4348)', () => {
+ beforeEach(() => {
+ store = {};
+ vi.clearAllMocks();
+ });
+
+ it('accepts a disabled-by-default provider config and preserves future federation keys', async () => {
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ federation: {
+ strictPullAuthorization: true,
+ futureFederationField: 'preserve',
+ mediaProvider: {
+ enabled: false,
+ maxQueuedJobs: 2,
+ audioModels: [{ engine: 'minimax-music3', modelId: 'minimax-music3', futureModelField: true }],
+ futureProviderField: 'preserve',
+ },
+ } });
+ expect(res.status).toBe(200);
+ expect(res.body.federation.mediaProvider).toMatchObject({
+ enabled: false,
+ maxQueuedJobs: 2,
+ futureProviderField: 'preserve',
+ });
+ expect(res.body.federation.futureFederationField).toBe('preserve');
+ });
+
+ it('rejects invalid limits and duplicate engine/model pairs', async () => {
+ const invalidLimit = await request(buildApp())
+ .put('/api/settings')
+ .send({ federation: { mediaProvider: { maxQueuedJobs: 0 } } });
+ expect(invalidLimit.status).toBe(400);
+
+ const duplicate = await request(buildApp())
+ .put('/api/settings')
+ .send({ federation: { mediaProvider: { audioModels: [
+ { engine: 'musicgen', modelId: 'm' },
+ { engine: 'musicgen', modelId: 'm' },
+ ] } } });
+ expect(duplicate.status).toBe(400);
+ });
+});
+
describe('Settings routes — imageGen.grok slice (#2859)', () => {
beforeEach(() => {
store = {};
diff --git a/server/services/audioGen/local.js b/server/services/audioGen/local.js
index 2023ef02da..3bb6dd65a2 100644
--- a/server/services/audioGen/local.js
+++ b/server/services/audioGen/local.js
@@ -24,7 +24,7 @@ import { audioGenEvents } from './events.js';
// jobId → AbortController, so cancelJob() can interrupt an in-flight render.
const controllers = new Map();
-export async function generateAudio({ jobId, prompt, lyrics, engine, durationSec, modelId, repo }) {
+export async function generateAudio({ jobId, prompt, lyrics, engine, durationSec, durationMode, modelId, repo }) {
const controller = new AbortController();
controllers.set(jobId, controller);
try {
@@ -33,6 +33,7 @@ export async function generateAudio({ jobId, prompt, lyrics, engine, durationSec
lyrics,
engine,
durationSec,
+ durationMode,
modelId,
repo,
signal: controller.signal,
diff --git a/server/services/audioGen/local.test.js b/server/services/audioGen/local.test.js
index 6b961a8733..f89ce5d2c9 100644
--- a/server/services/audioGen/local.test.js
+++ b/server/services/audioGen/local.test.js
@@ -18,10 +18,10 @@ describe('generateAudio', () => {
const onCompleted = vi.fn();
audioGenEvents.once('completed', onCompleted);
- await generateAudio({ jobId: 'job-1', prompt: 'a moody synth bed', engine: 'musicgen', durationSec: 12 });
+ await generateAudio({ jobId: 'job-1', prompt: 'a moody synth bed', engine: 'musicgen', durationSec: 12, durationMode: 'manual' });
expect(generateMusic).toHaveBeenCalledWith(expect.objectContaining({
- prompt: 'a moody synth bed', engine: 'musicgen', durationSec: 12,
+ prompt: 'a moody synth bed', engine: 'musicgen', durationSec: 12, durationMode: 'manual',
signal: expect.any(AbortSignal),
onActivity: expect.any(Function),
}));
diff --git a/server/services/federatedMediaProvider.js b/server/services/federatedMediaProvider.js
new file mode 100644
index 0000000000..648b9efb00
--- /dev/null
+++ b/server/services/federatedMediaProvider.js
@@ -0,0 +1,333 @@
+/**
+ * Provider-side federated media contract (wire v1).
+ *
+ * This first slice exposes queued audio generation without introducing a
+ * second runner or persistence layer: accepted work is tagged and submitted to
+ * mediaJobQueue. Provider settings and queue records stay machine-local. Only
+ * allowlisted capability/job/result projections cross the peer boundary.
+ */
+
+import { stat } from 'node:fs/promises';
+import { ServerError } from '../lib/errorHandler.js';
+import { createMutex } from '../lib/asyncMutex.js';
+import { canonicalStringify } from '../lib/objects.js';
+import { PATHS, makePathResolver, sha256File, sha256Text } from '../lib/fileUtils.js';
+import { getSettings } from './settings.js';
+import { enqueueJob, getJob, listJobs, cancelJob } from './mediaJobQueue/index.js';
+import { listMusicEngineCapabilities } from './musicEngineCapabilities.js';
+import { readCallerInstanceId } from './sharing/peerPullAuthorization.js';
+import { findPeerById } from './sharing/peerSyncShared.js';
+
+export const FEDERATED_MEDIA_WIRE_VERSION = 1;
+export const FEDERATED_MEDIA_STALE_AFTER_MS = 60_000;
+export const DEFAULT_FEDERATED_MEDIA_PROVIDER = Object.freeze({
+ enabled: false,
+ maxQueuedJobs: 2,
+ audioModels: Object.freeze([]),
+});
+
+const ACTIVE_STATUSES = new Set(['queued', 'running']);
+const OWNER_PREFIX = 'federated-media:';
+const MUSIC_RESULT_RE = /^music-gen-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.wav$/i;
+const RESULT_HASH_CACHE_MAX = 100;
+const resolveMusicResult = makePathResolver(() => PATHS.music, { extensions: ['wav'] });
+const resultHashCache = new Map();
+const withAdmissionLock = createMutex();
+
+const unavailable = (message, code, status = 503, context) => {
+ throw new ServerError(message, { status, code, ...(context ? { context } : {}) });
+};
+
+export function normalizeFederatedMediaProviderConfig(settings) {
+ const raw = settings?.federation?.mediaProvider;
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
+ return { ...DEFAULT_FEDERATED_MEDIA_PROVIDER, audioModels: [] };
+ }
+ return {
+ ...raw,
+ enabled: raw.enabled === true,
+ maxQueuedJobs: Number.isInteger(raw.maxQueuedJobs)
+ ? Math.max(1, Math.min(20, raw.maxQueuedJobs))
+ : DEFAULT_FEDERATED_MEDIA_PROVIDER.maxQueuedJobs,
+ audioModels: Array.isArray(raw.audioModels)
+ ? raw.audioModels
+ .filter((model) => model && typeof model === 'object' && !Array.isArray(model))
+ .map(({ engine, modelId }) => ({ engine, modelId }))
+ .filter(({ engine, modelId }) => typeof engine === 'string' && typeof modelId === 'string')
+ : [],
+ };
+}
+
+/**
+ * The provider is stricter than ordinary federation reads: it never inherits
+ * authGate's auth-off bypass and never accepts a browser session. A verified
+ * Basic credential plus a registered, enabled caller is required every time.
+ */
+export async function authorizeFederatedMediaPeer(req) {
+ const config = normalizeFederatedMediaProviderConfig(await getSettings());
+ if (!config.enabled) {
+ unavailable('Federated media provider is disabled', 'MEDIA_PROVIDER_DISABLED');
+ }
+ if (req.portosAuthContext?.method !== 'basic' || req.portosAuthContext?.authenticated !== true) {
+ unavailable('Verified peer Basic authentication is required', 'MEDIA_PROVIDER_PEER_AUTH_REQUIRED', 403);
+ }
+ const callerId = readCallerInstanceId(req);
+ if (!callerId) {
+ unavailable('A peer instance id is required', 'MEDIA_PROVIDER_PEER_ID_REQUIRED', 403);
+ }
+ const peer = await findPeerById(callerId);
+ if (!peer || peer.enabled === false) {
+ unavailable('The caller is not an enabled registered peer', 'MEDIA_PROVIDER_PEER_FORBIDDEN', 403);
+ }
+ return { callerId, config };
+}
+
+function readinessReason(engine, modelReady) {
+ if (!engine) return 'unknown-engine';
+ if (!engine.platformSupported) return 'platform-unsupported';
+ if (!engine.runtimeReady) return 'runtime-unavailable';
+ if (engine.cudaRequired && engine.cudaState !== 'available') {
+ return engine.cudaState === 'unknown' ? 'cuda-unknown' : 'cuda-absent';
+ }
+ if (!modelReady) return 'model-unavailable';
+ return null;
+}
+
+async function configuredAudioCapabilities(config) {
+ const { engines } = await listMusicEngineCapabilities();
+ const enginesById = new Map(engines.map((engine) => [engine.id, engine]));
+ return config.audioModels.map((selected) => {
+ const engine = enginesById.get(selected.engine);
+ const model = engine?.models.find((candidate) => candidate.id === selected.modelId);
+ const modelReady = !!model && (!engine.fixedModelInstall || engine.modelReadyById?.[model.id] === true);
+ const reason = model ? readinessReason(engine, modelReady) : (engine ? 'unknown-model' : 'unknown-engine');
+ return {
+ kind: 'audio',
+ engine: selected.engine,
+ engineName: engine?.name ?? selected.engine,
+ modelId: selected.modelId,
+ modelName: model?.name ?? selected.modelId,
+ ready: reason === null,
+ unavailableReason: reason,
+ runtimeReady: engine?.runtimeReady === true,
+ platformSupported: engine?.platformSupported === true,
+ cudaRequired: engine?.cudaRequired === true,
+ cudaState: engine?.cudaRequired ? engine.cudaState : 'available',
+ minDurationSec: engine?.minDurationSec ?? null,
+ maxDurationSec: engine?.maxDurationSec ?? null,
+ defaultDurationSec: engine?.defaultDurationSec ?? null,
+ lyrics: engine?.lyrics === true,
+ autoDuration: engine?.autoDuration === true,
+ _engine: engine,
+ _model: model,
+ };
+ });
+}
+
+function activeQueueSnapshot(config) {
+ const active = listJobs().filter((job) => ACTIVE_STATUSES.has(job.status));
+ const providerActive = active.filter((job) => job.owner?.startsWith(OWNER_PREFIX));
+ return {
+ totalActive: active.length,
+ providerActive: providerActive.length,
+ queued: providerActive.filter((job) => job.status === 'queued').length,
+ running: providerActive.filter((job) => job.status === 'running').length,
+ maxQueuedJobs: config.maxQueuedJobs,
+ accepting: active.length < config.maxQueuedJobs,
+ };
+}
+
+const publicCapability = ({ _engine, _model, ...capability }) => capability;
+
+export async function getFederatedMediaProviderStatus(config) {
+ const capabilities = await configuredAudioCapabilities(config);
+ const queue = activeQueueSnapshot(config);
+ const anyReady = capabilities.some((capability) => capability.ready);
+ return {
+ wireVersion: FEDERATED_MEDIA_WIRE_VERSION,
+ generatedAt: new Date().toISOString(),
+ staleAfterMs: FEDERATED_MEDIA_STALE_AFTER_MS,
+ status: !anyReady ? 'unavailable' : (queue.accepting ? 'ready' : 'busy'),
+ kinds: ['audio'],
+ queue,
+ capabilities: capabilities.map(publicCapability),
+ };
+}
+
+const jobOwner = (callerId) => `${OWNER_PREFIX}${callerId}`;
+const jobBelongsToCaller = (job, callerId) =>
+ job?.owner === jobOwner(callerId)
+ && job.params?.federatedMedia?.callerInstanceId === callerId;
+
+function lookupCallerJob(callerId, jobId) {
+ const job = getJob(jobId);
+ if (!jobBelongsToCaller(job, callerId)) {
+ unavailable('Provider job not found', 'MEDIA_PROVIDER_JOB_NOT_FOUND', 404);
+ }
+ return job;
+}
+
+function findIdempotentJob(callerId, idempotencyKey) {
+ return listJobs().find((job) =>
+ jobBelongsToCaller(job, callerId)
+ && job.params?.federatedMedia?.idempotencyKey === idempotencyKey,
+ ) || null;
+}
+
+async function describeResult(job) {
+ if (job.status !== 'completed') return null;
+ const filename = job.result?.filename;
+ // The queue record is persisted and therefore could be hand-edited. Bind a
+ // provider job only to the filename shape generateMusic itself creates;
+ // makePathResolver confines the root, while this prevents cross-job file
+ // substitution inside that root.
+ if (typeof filename !== 'string' || !MUSIC_RESULT_RE.test(filename)) {
+ unavailable('Provider result is unavailable', 'MEDIA_PROVIDER_RESULT_UNAVAILABLE', 410);
+ }
+ const path = resolveMusicResult(filename);
+ if (!path) {
+ unavailable('Provider result is unavailable', 'MEDIA_PROVIDER_RESULT_UNAVAILABLE', 410);
+ }
+ const info = await stat(path).catch(() => null);
+ if (!info?.isFile() || info.size <= 0) {
+ unavailable('Provider result is unavailable', 'MEDIA_PROVIDER_RESULT_UNAVAILABLE', 410);
+ }
+ const cacheKey = `${filename}:${info.size}:${info.mtimeMs}`;
+ let sha256 = resultHashCache.get(cacheKey);
+ if (!sha256) {
+ sha256 = await sha256File(path).catch(() => null);
+ if (!sha256) {
+ unavailable('Provider result is unavailable', 'MEDIA_PROVIDER_RESULT_UNAVAILABLE', 410);
+ }
+ if (resultHashCache.size >= RESULT_HASH_CACHE_MAX) {
+ resultHashCache.delete(resultHashCache.keys().next().value);
+ }
+ resultHashCache.set(cacheKey, sha256);
+ }
+ return {
+ metadata: {
+ available: true,
+ mimeType: 'audio/wav',
+ sizeBytes: info.size,
+ sha256,
+ downloadUrl: `/api/federation/media/v1/jobs/${job.id}/result`,
+ engine: job.result?.engine ?? job.params?.engine ?? null,
+ modelId: job.result?.modelId ?? job.params?.modelId ?? null,
+ durationSec: Number.isFinite(job.result?.durationSec) ? job.result.durationSec : null,
+ },
+ path,
+ };
+}
+
+export async function describeFederatedMediaJob(callerId, jobOrId) {
+ const job = typeof jobOrId === 'string' ? lookupCallerJob(callerId, jobOrId) : jobOrId;
+ if (!jobBelongsToCaller(job, callerId)) {
+ unavailable('Provider job not found', 'MEDIA_PROVIDER_JOB_NOT_FOUND', 404);
+ }
+ const result = await describeResult(job);
+ return {
+ wireVersion: FEDERATED_MEDIA_WIRE_VERSION,
+ id: job.id,
+ kind: 'audio',
+ status: job.status,
+ queuedAt: job.queuedAt,
+ startedAt: job.startedAt ?? null,
+ completedAt: job.completedAt ?? null,
+ position: Number.isFinite(job.position) ? job.position : null,
+ progress: Number.isFinite(job.progress) ? job.progress : null,
+ etaMs: Number.isFinite(job.etaMs) ? job.etaMs : null,
+ ...(job.status === 'failed' ? { failure: { code: 'MEDIA_PROVIDER_JOB_FAILED', message: 'Provider job failed' } } : {}),
+ ...(result ? { result: result.metadata } : {}),
+ };
+}
+
+export async function submitFederatedMediaJob({ callerId, config, input, idempotencyKey }) {
+ return withAdmissionLock(async () => {
+ const requestHash = sha256Text(canonicalStringify(input));
+ const existing = findIdempotentJob(callerId, idempotencyKey);
+ if (existing) {
+ if (existing.params?.federatedMedia?.requestHash !== requestHash) {
+ unavailable('Idempotency-Key was already used with a different request', 'MEDIA_PROVIDER_IDEMPOTENCY_CONFLICT', 409);
+ }
+ return { replayed: true, job: await describeFederatedMediaJob(callerId, existing) };
+ }
+
+ const queue = activeQueueSnapshot(config);
+ if (!queue.accepting) {
+ unavailable('Provider queue is at capacity', 'MEDIA_PROVIDER_BUSY', 429, {
+ retryable: true,
+ maxQueuedJobs: queue.maxQueuedJobs,
+ });
+ }
+
+ const capabilities = await configuredAudioCapabilities(config);
+ const capability = capabilities.find((candidate) =>
+ candidate.engine === input.engine && candidate.modelId === input.modelId,
+ );
+ if (!capability) {
+ unavailable('Requested model is not enabled for federation', 'MEDIA_PROVIDER_MODEL_NOT_ALLOWED', 400);
+ }
+ if (!capability.ready) {
+ unavailable('Requested model is not currently available', 'MEDIA_PROVIDER_MODEL_UNAVAILABLE', 503, {
+ reason: capability.unavailableReason,
+ });
+ }
+ if (input.durationMode === 'auto' && !capability.autoDuration) {
+ unavailable('Requested engine does not support automatic duration', 'MEDIA_PROVIDER_AUTO_DURATION_UNSUPPORTED', 400);
+ }
+ if (input.durationSec !== undefined
+ && (input.durationSec < capability.minDurationSec || input.durationSec > capability.maxDurationSec)) {
+ unavailable('Requested duration is outside the engine limits', 'MEDIA_PROVIDER_DURATION_UNSUPPORTED', 400, {
+ minDurationSec: capability.minDurationSec,
+ maxDurationSec: capability.maxDurationSec,
+ });
+ }
+
+ const queued = enqueueJob({
+ kind: 'audio',
+ owner: jobOwner(callerId),
+ params: {
+ prompt: input.prompt,
+ lyrics: input.lyrics,
+ engine: input.engine,
+ modelId: input.modelId,
+ ...(capability._model?.userAdded ? { repo: capability._model.repo } : {}),
+ ...(input.durationSec !== undefined ? { durationSec: input.durationSec } : {}),
+ ...(input.durationMode ? { durationMode: input.durationMode } : {}),
+ federatedMedia: {
+ wireVersion: FEDERATED_MEDIA_WIRE_VERSION,
+ callerInstanceId: callerId,
+ idempotencyKey,
+ requestHash,
+ },
+ },
+ });
+ return {
+ replayed: false,
+ job: await describeFederatedMediaJob(callerId, queued.jobId),
+ };
+ });
+}
+
+export async function cancelFederatedMediaJob(callerId, jobId) {
+ lookupCallerJob(callerId, jobId);
+ const outcome = await cancelJob(jobId);
+ if (!outcome.ok) {
+ unavailable(outcome.error || 'Provider job cannot be canceled', outcome.code === 'ALREADY_TERMINAL'
+ ? 'MEDIA_PROVIDER_JOB_TERMINAL'
+ : 'MEDIA_PROVIDER_JOB_NOT_FOUND', outcome.code === 'ALREADY_TERMINAL' ? 409 : 404);
+ }
+ return describeFederatedMediaJob(callerId, jobId);
+}
+
+export async function getFederatedMediaResult(callerId, jobId) {
+ const job = lookupCallerJob(callerId, jobId);
+ if (job.status !== 'completed') {
+ unavailable('Provider result is not ready', 'MEDIA_PROVIDER_RESULT_NOT_READY', 409);
+ }
+ return describeResult(job);
+}
+
+export function __resetFederatedMediaProviderForTests() {
+ resultHashCache.clear();
+}
diff --git a/server/services/federatedMediaProvider.test.js b/server/services/federatedMediaProvider.test.js
new file mode 100644
index 0000000000..83c29de251
--- /dev/null
+++ b/server/services/federatedMediaProvider.test.js
@@ -0,0 +1,257 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+
+const state = vi.hoisted(() => ({
+ settings: {},
+ peer: null,
+ jobs: [],
+ nextId: 1,
+ capabilities: { engines: [], defaultEngine: 'musicgen' },
+ cancelResult: { ok: true, status: 'canceled' },
+}));
+
+vi.mock('./settings.js', () => ({
+ getSettings: vi.fn(async () => state.settings),
+}));
+
+vi.mock('./sharing/peerPullAuthorization.js', () => ({
+ readCallerInstanceId: (req) => req.headers?.['x-portos-instance-id'] || null,
+}));
+
+vi.mock('./sharing/peerSyncShared.js', () => ({
+ findPeerById: vi.fn(async (id) => state.peer?.instanceId === id ? state.peer : null),
+}));
+
+vi.mock('./musicEngineCapabilities.js', () => ({
+ listMusicEngineCapabilities: vi.fn(async () => state.capabilities),
+}));
+
+vi.mock('./mediaJobQueue/index.js', () => ({
+ listJobs: vi.fn(() => state.jobs),
+ getJob: vi.fn((id) => state.jobs.find((job) => job.id === id) || null),
+ enqueueJob: vi.fn(({ kind, owner, params }) => {
+ const suffix = String(state.nextId++).padStart(12, '0');
+ const id = `00000000-0000-4000-8000-${suffix}`;
+ const job = {
+ id, kind, owner, params, status: 'queued', position: state.jobs.length + 1,
+ queuedAt: '2026-08-16T00:00:00.000Z',
+ };
+ state.jobs.push(job);
+ return { jobId: id, position: job.position, status: job.status };
+ }),
+ cancelJob: vi.fn(async (id) => {
+ const job = state.jobs.find((candidate) => candidate.id === id);
+ if (state.cancelResult.ok && job) {
+ job.status = 'canceled';
+ job.completedAt = '2026-08-16T00:01:00.000Z';
+ }
+ return state.cancelResult;
+ }),
+}));
+
+import {
+ authorizeFederatedMediaPeer,
+ describeFederatedMediaJob,
+ getFederatedMediaProviderStatus,
+ normalizeFederatedMediaProviderConfig,
+ submitFederatedMediaJob,
+ __resetFederatedMediaProviderForTests,
+} from './federatedMediaProvider.js';
+import { enqueueJob } from './mediaJobQueue/index.js';
+import { PATHS, sha256Text } from '../lib/fileUtils.js';
+
+const originalMusicPath = PATHS.music;
+let tempMusicPath;
+
+beforeAll(() => {
+ tempMusicPath = mkdtempSync(join(tmpdir(), 'portos-federated-media-service-'));
+ PATHS.music = tempMusicPath;
+});
+
+afterAll(() => {
+ PATHS.music = originalMusicPath;
+ rmSync(tempMusicPath, { recursive: true, force: true });
+});
+
+const selection = { engine: 'minimax-music3', modelId: 'minimax-music3' };
+const config = () => ({ enabled: true, maxQueuedJobs: 2, audioModels: [selection] });
+const input = () => ({ ...selection, prompt: 'slow synthwave', durationSec: 60, durationMode: 'manual' });
+
+function readyEngine(overrides = {}) {
+ return {
+ id: 'minimax-music3',
+ name: 'MiniMax Music 3',
+ models: [{ id: 'minimax-music3', name: 'MiniMax Music 3', userAdded: false }],
+ fixedModelInstall: true,
+ modelReadyById: { 'minimax-music3': true },
+ runtimeReady: true,
+ platformSupported: true,
+ cudaRequired: true,
+ cudaState: 'available',
+ minDurationSec: 1,
+ maxDurationSec: 300,
+ defaultDurationSec: 60,
+ lyrics: true,
+ autoDuration: true,
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ state.settings = { federation: { mediaProvider: config() } };
+ state.peer = { instanceId: 'peer-example', enabled: true };
+ state.jobs = [];
+ state.nextId = 1;
+ state.capabilities = { engines: [readyEngine()], defaultEngine: 'musicgen' };
+ state.cancelResult = { ok: true, status: 'canceled' };
+ __resetFederatedMediaProviderForTests();
+});
+
+describe('federated media provider authorization', () => {
+ it('defaults absent settings to disabled with conservative limits', () => {
+ expect(normalizeFederatedMediaProviderConfig({})).toEqual({
+ enabled: false, maxQueuedJobs: 2, audioModels: [],
+ });
+ });
+
+ it('requires verified Basic auth and an enabled registered peer', async () => {
+ const baseReq = { headers: { 'x-portos-instance-id': 'peer-example' } };
+ await expect(authorizeFederatedMediaPeer(baseReq)).rejects.toMatchObject({
+ status: 403, code: 'MEDIA_PROVIDER_PEER_AUTH_REQUIRED',
+ });
+ await expect(authorizeFederatedMediaPeer({
+ ...baseReq,
+ portosAuthContext: { enabled: true, authenticated: true, method: 'session' },
+ })).rejects.toMatchObject({
+ status: 403, code: 'MEDIA_PROVIDER_PEER_AUTH_REQUIRED',
+ });
+
+ const req = {
+ ...baseReq,
+ portosAuthContext: { enabled: true, authenticated: true, method: 'basic' },
+ };
+ await expect(authorizeFederatedMediaPeer(req)).resolves.toEqual({
+ callerId: 'peer-example', config: config(),
+ });
+
+ state.peer.enabled = false;
+ await expect(authorizeFederatedMediaPeer(req)).rejects.toMatchObject({
+ status: 403, code: 'MEDIA_PROVIDER_PEER_FORBIDDEN',
+ });
+ });
+});
+
+describe('federated media provider capacity and idempotency', () => {
+ it('reports CUDA unknown as unavailable instead of optimistic capacity', async () => {
+ state.capabilities.engines = [readyEngine({ cudaState: 'unknown' })];
+ const status = await getFederatedMediaProviderStatus(config());
+ expect(status).toMatchObject({ status: 'unavailable', wireVersion: 1, kinds: ['audio'] });
+ expect(status.capabilities[0]).toMatchObject({
+ ready: false, cudaState: 'unknown', unavailableReason: 'cuda-unknown',
+ });
+ expect(status.capabilities[0]).not.toHaveProperty('_engine');
+ });
+
+ it('queues allowlisted audio without exposing the prompt in its response', async () => {
+ const result = await submitFederatedMediaJob({
+ callerId: 'peer-example', config: config(), input: input(), idempotencyKey: 'commission-1',
+ });
+ expect(result).toMatchObject({ replayed: false, job: { status: 'queued', kind: 'audio', wireVersion: 1 } });
+ expect(result.job).not.toHaveProperty('params');
+ expect(enqueueJob).toHaveBeenCalledWith(expect.objectContaining({
+ kind: 'audio', owner: 'federated-media:peer-example',
+ params: expect.objectContaining({
+ prompt: 'slow synthwave', engine: 'minimax-music3', modelId: 'minimax-music3',
+ durationMode: 'manual',
+ federatedMedia: expect.objectContaining({
+ callerInstanceId: 'peer-example', idempotencyKey: 'commission-1',
+ }),
+ }),
+ }));
+ });
+
+ it('replays a matching key and rejects a key reused with different input', async () => {
+ const first = await submitFederatedMediaJob({
+ callerId: 'peer-example', config: config(), input: input(), idempotencyKey: 'commission-1',
+ });
+ const replay = await submitFederatedMediaJob({
+ callerId: 'peer-example', config: config(), input: input(), idempotencyKey: 'commission-1',
+ });
+ expect(replay.replayed).toBe(true);
+ expect(replay.job.id).toBe(first.job.id);
+ expect(enqueueJob).toHaveBeenCalledTimes(1);
+
+ await expect(submitFederatedMediaJob({
+ callerId: 'peer-example', config: config(),
+ input: { ...input(), prompt: 'different' }, idempotencyKey: 'commission-1',
+ })).rejects.toMatchObject({ status: 409, code: 'MEDIA_PROVIDER_IDEMPOTENCY_CONFLICT' });
+ });
+
+ it('counts all active local media work against the conservative provider cap', async () => {
+ state.jobs = [
+ { id: 'local-1', owner: null, status: 'running' },
+ { id: 'local-2', owner: null, status: 'queued' },
+ ];
+ await expect(submitFederatedMediaJob({
+ callerId: 'peer-example', config: config(), input: input(), idempotencyKey: 'commission-2',
+ })).rejects.toMatchObject({ status: 429, code: 'MEDIA_PROVIDER_BUSY' });
+ expect(enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('fails closed when CUDA readiness is unknown', async () => {
+ state.capabilities.engines = [readyEngine({ cudaState: 'unknown' })];
+ await expect(submitFederatedMediaJob({
+ callerId: 'peer-example', config: config(), input: input(), idempotencyKey: 'commission-3',
+ })).rejects.toMatchObject({
+ status: 503,
+ code: 'MEDIA_PROVIDER_MODEL_UNAVAILABLE',
+ context: { reason: 'cuda-unknown' },
+ });
+ });
+
+ it('hides jobs owned by another caller', async () => {
+ const created = await submitFederatedMediaJob({
+ callerId: 'peer-example', config: config(), input: input(), idempotencyKey: 'commission-4',
+ });
+ await expect(describeFederatedMediaJob('other-peer', created.job.id)).rejects.toMatchObject({
+ status: 404, code: 'MEDIA_PROVIDER_JOB_NOT_FOUND',
+ });
+ });
+
+ it('describes only generator-shaped result files with verified byte integrity', async () => {
+ const created = await submitFederatedMediaJob({
+ callerId: 'peer-example', config: config(), input: input(), idempotencyKey: 'commission-5',
+ });
+ const job = state.jobs.find((candidate) => candidate.id === created.job.id);
+ const filename = 'music-gen-11111111-1111-4111-8111-111111111111.wav';
+ const bytes = Buffer.from('RIFF-fake-audio');
+ writeFileSync(join(tempMusicPath, filename), bytes);
+ Object.assign(job, {
+ status: 'completed',
+ completedAt: '2026-08-16T00:02:00.000Z',
+ result: { filename, durationSec: 60, engine: selection.engine, modelId: selection.modelId },
+ });
+
+ const described = await describeFederatedMediaJob('peer-example', job.id);
+ expect(described.result).toEqual({
+ available: true,
+ mimeType: 'audio/wav',
+ sizeBytes: bytes.length,
+ sha256: sha256Text(bytes),
+ downloadUrl: `/api/federation/media/v1/jobs/${job.id}/result`,
+ engine: selection.engine,
+ modelId: selection.modelId,
+ durationSec: 60,
+ });
+ expect(described.result).not.toHaveProperty('path');
+ expect(described.result).not.toHaveProperty('filename');
+
+ job.result.filename = `../${filename}`;
+ await expect(describeFederatedMediaJob('peer-example', job.id)).rejects.toMatchObject({
+ status: 410, code: 'MEDIA_PROVIDER_RESULT_UNAVAILABLE',
+ });
+ });
+});
diff --git a/server/services/musicEngineCapabilities.js b/server/services/musicEngineCapabilities.js
new file mode 100644
index 0000000000..b0f9b8e4b3
--- /dev/null
+++ b/server/services/musicEngineCapabilities.js
@@ -0,0 +1,72 @@
+/**
+ * One authoritative view of the music engines this install can actually run.
+ *
+ * The Music UI and the federated-media provider both consume this projection.
+ * Keeping runtime, platform, fixed-model, and CUDA readiness in one place is
+ * important: a provider must never advertise work that the local UI would
+ * correctly reject, especially when CUDA probing returned `unknown`.
+ */
+
+import { inspectModelCache } from '../lib/hfCache.js';
+import { getCudaCapability } from '../lib/cudaCapability.js';
+import {
+ ENGINES,
+ DEFAULT_ENGINE_ID,
+ getEngineModel,
+ isEngineHealthy,
+ isEnginePlatformSupported,
+ enginePlatformLabel,
+} from './pipeline/musicGen.js';
+import { listEngineModels } from './audioModels.js';
+
+export async function listMusicEngineCapabilities() {
+ const cuda = await getCudaCapability();
+ const engines = await Promise.all(Object.values(ENGINES).map(async (engine) => {
+ const fixedModels = engine.fixedModelInstall ? engine.models : [];
+ const modelReadyById = engine.fixedModelInstall
+ ? Object.fromEntries(await Promise.all(fixedModels.map(async (model) => [
+ model.id,
+ (await inspectModelCache(model.repo, { revision: model.revision }).catch(() => ({ cached: false }))).cached === true,
+ ])))
+ : null;
+ // Preserve the aggregate for older clients, while newer consumers gate
+ // the exact selected checkpoint through modelReadyById.
+ const modelReady = modelReadyById ? Object.values(modelReadyById).some(Boolean) : true;
+ const fixedModel = engine.fixedModelInstall
+ ? getEngineModel(engine.id, engine.defaultModelId)
+ : null;
+ const modelSizeGbById = engine.fixedModelInstall
+ ? Object.fromEntries(fixedModels.map((model) => [model.id, model.downloadSizeGb ?? null]))
+ : null;
+ const runtimeReady = await isEngineHealthy(engine.id);
+ const cudaState = engine.cudaRequired ? cuda.status : 'available';
+
+ return {
+ id: engine.id,
+ name: engine.name,
+ models: await listEngineModels(engine.id),
+ defaultModelId: engine.defaultModelId,
+ minDurationSec: engine.minDurationSec,
+ maxDurationSec: engine.maxDurationSec,
+ defaultDurationSec: engine.defaultDurationSec,
+ lyrics: engine.lyrics === true,
+ autoDuration: engine.autoDuration === true,
+ customModels: engine.customModels === true,
+ fixedModelInstall: engine.fixedModelInstall === true,
+ modelReady,
+ ...(modelReadyById ? { modelReadyById } : {}),
+ modelSizeGb: fixedModel?.downloadSizeGb ?? null,
+ ...(modelSizeGbById ? { modelSizeGbById } : {}),
+ runtimeReady,
+ cudaRequired: engine.cudaRequired === true,
+ platformSupported: isEnginePlatformSupported(engine.id),
+ platformLabel: enginePlatformLabel(engine.id),
+ cudaState,
+ ready: runtimeReady && (!engine.cudaRequired || cudaState === 'available') && modelReady,
+ installEnv: engine.installEnv,
+ venvDefault: engine.venvDefault,
+ };
+ }));
+
+ return { engines, defaultEngine: DEFAULT_ENGINE_ID };
+}