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 media peer selection (#4348)

Adam Eivy354ee1bb20e3
diff --git a/.changelog/next/added-issue-4348.md b/.changelog/next/added-issue-4348.md
index 1d00b5de7d..aef35f7798 100644
--- a/.changelog/next/added-issue-4348.md
+++ b/.changelog/next/added-issue-4348.md
@@ -1 +1,2 @@
- Add an authenticated federated audio provider API with conservative capacity admission and integrity-checked results (#4348).
+- Instances can now opt into a peer's remote audio capacity and allowlist exact models, with stale or busy providers blocked before assignment (#4348).
diff --git a/client/src/components/instances/PeerMediaProviderPanel.jsx b/client/src/components/instances/PeerMediaProviderPanel.jsx
new file mode 100644
index 0000000000..624a21cc76
--- /dev/null
+++ b/client/src/components/instances/PeerMediaProviderPanel.jsx
@@ -0,0 +1,205 @@
+import { useMemo, useState } from 'react';
+import { Check, ChevronDown, ChevronRight, Gauge, Music2 } from 'lucide-react';
+import { probePeer, updatePeer } from '../../services/api';
+import Pill from '../ui/Pill';
+
+const STATE_META = {
+ ready: { label: 'ready', tone: 'success' },
+ busy: { label: 'busy', tone: 'warning' },
+ stale: { label: 'stale', tone: 'warning' },
+ unauthorized: { label: 'auth required', tone: 'warning' },
+ unsupported: { label: 'older peer', tone: 'note' },
+ disabled: { label: 'provider off', tone: 'note' },
+ unavailable: { label: 'unavailable', tone: 'warning' },
+ unreachable: { label: 'unreachable', tone: 'warning' },
+ invalid: { label: 'invalid status', tone: 'warning' },
+};
+
+const STATE_HELP = {
+ busy: 'The peer is reachable, but its shared media lane is currently at capacity.',
+ stale: 'The last capacity snapshot expired. New remote work is blocked until a fresh probe succeeds.',
+ unauthorized: 'Store this peer’s instance-password credential above and make sure this instance is registered there.',
+ unsupported: 'This peer does not expose the federated-media wire-v1 status endpoint yet.',
+ disabled: 'Enable federated media sharing on the peer under Settings → Sharing.',
+ unavailable: 'The peer has no currently ready allowlisted media runtime/model.',
+ unreachable: 'The media status request failed. New remote work remains blocked.',
+ invalid: 'The peer returned a response that did not match the versioned media-provider contract.',
+};
+
+const isRecord = (value) => value && typeof value === 'object' && !Array.isArray(value);
+const keyOf = ({ engine, modelId }) => `${engine}\u0000${modelId}`;
+
+function configOf(peer) {
+ const raw = isRecord(peer?.mediaProvider) ? peer.mediaProvider : {};
+ return {
+ raw,
+ enabled: raw.enabled === true,
+ audioModels: Array.isArray(raw.audioModels) ? raw.audioModels : [],
+ };
+}
+
+function modelRows(config, status) {
+ const rows = new Map();
+ for (const capability of status?.snapshot?.capabilities || []) {
+ if (capability?.kind !== 'audio' || !capability.engine || !capability.modelId) continue;
+ rows.set(keyOf(capability), capability);
+ }
+ for (const selected of config.audioModels) {
+ if (!selected?.engine || !selected.modelId) continue;
+ const key = keyOf(selected);
+ if (!rows.has(key)) {
+ rows.set(key, {
+ kind: 'audio',
+ engine: selected.engine,
+ engineName: selected.engine,
+ modelId: selected.modelId,
+ modelName: selected.modelId,
+ ready: false,
+ unavailableReason: 'not-advertised',
+ });
+ }
+ }
+ return [...rows.values()];
+}
+
+export default function PeerMediaProviderPanel({ peer, onRefresh }) {
+ const [expanded, setExpanded] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const config = configOf(peer);
+ const status = peer.mediaProviderStatus || null;
+ const rows = useMemo(() => modelRows(config, status), [config.raw, status]);
+ const selectedKeys = new Set(config.audioModels
+ .filter((model) => model?.engine && model.modelId)
+ .map(keyOf));
+ const stateMeta = !config.enabled
+ ? { label: 'off', tone: 'note' }
+ : peer.status !== 'online'
+ ? { label: 'peer offline', tone: 'warning' }
+ : STATE_META[status?.state] || { label: 'checking', tone: 'muted' };
+ const queue = status?.snapshot?.queue;
+
+ const saveConfig = async (next, { probe = false } = {}) => {
+ setSaving(true);
+ const updated = await updatePeer(peer.id, { mediaProvider: next }).catch(() => null);
+ if (updated && probe) await probePeer(peer.id).catch(() => null);
+ if (updated) onRefresh();
+ setSaving(false);
+ };
+
+ const toggleEnabled = () => saveConfig(
+ { ...config.raw, enabled: !config.enabled, audioModels: config.audioModels },
+ { probe: !config.enabled },
+ );
+
+ const toggleModel = (model) => {
+ const key = keyOf(model);
+ const selected = selectedKeys.has(key);
+ const audioModels = selected
+ ? config.audioModels.filter((candidate) => keyOf(candidate) !== key)
+ : [...config.audioModels, { engine: model.engine, modelId: model.modelId }];
+ return saveConfig({ ...config.raw, enabled: config.enabled, audioModels });
+ };
+
+ const safePeerId = String(peer.id || 'peer').replace(/[^A-Za-z0-9_-]/g, '-');
+ const enabledId = `${safePeerId}-remote-media-enabled`;
+
+ return (
+ <div className="mt-2 pt-2 border-t border-port-border/50">
+ <button
+ type="button"
+ onClick={() => setExpanded((value) => !value)}
+ className="flex items-center gap-1.5 w-full text-left group"
+ aria-expanded={expanded}
+ >
+ {expanded ? <ChevronDown size={12} className="text-gray-500" /> : <ChevronRight size={12} className="text-gray-500" />}
+ <Gauge size={12} className={config.enabled ? 'text-port-accent' : 'text-gray-500'} />
+ <span className="text-[10px] text-gray-500 uppercase tracking-wider font-medium group-hover:text-gray-400 transition-colors">
+ Remote media provider
+ </span>
+ <Pill tone={stateMeta.tone} size="xs" bordered={false} className="ml-auto">
+ {stateMeta.label}
+ </Pill>
+ </button>
+
+ {expanded && (
+ <div className="mt-2 space-y-2 text-xs">
+ <div className="flex items-start gap-2 rounded border border-port-border px-2 py-2">
+ <input
+ id={enabledId}
+ type="checkbox"
+ checked={config.enabled}
+ disabled={saving || peer.enabled === false}
+ onChange={toggleEnabled}
+ className="mt-0.5 accent-port-accent"
+ />
+ <label htmlFor={enabledId} className="flex-1 text-gray-300 cursor-pointer">
+ Use this peer for remote audio
+ <span className="block text-[10px] text-gray-600 mt-0.5">
+ Opt-in only. The server also requires an allowlisted model and fresh available capacity before routing.
+ </span>
+ </label>
+ </div>
+
+ {config.enabled && (
+ <>
+ {queue && (
+ <div className="flex items-center gap-1.5 text-[10px] text-gray-500">
+ <Gauge size={11} />
+ <span>
+ {queue.running} running · {queue.queued} queued · {queue.totalActive}/{queue.maxQueuedJobs} shared slots active
+ </span>
+ </div>
+ )}
+
+ {status?.state && status.state !== 'ready' && STATE_HELP[status.state] && (
+ <p className="text-[10px] text-port-warning leading-snug">{STATE_HELP[status.state]}</p>
+ )}
+
+ <div className="space-y-1">
+ <div className="text-[10px] text-gray-500 uppercase tracking-wider">Allowed audio models</div>
+ {rows.length === 0 ? (
+ <p className="text-[10px] text-gray-600">
+ No capabilities discovered yet. Verify peer authentication and probe again.
+ </p>
+ ) : rows.map((model, index) => {
+ const key = keyOf(model);
+ const selected = selectedKeys.has(key);
+ const inputId = `${safePeerId}-remote-media-model-${index}`;
+ return (
+ <label
+ key={key}
+ htmlFor={inputId}
+ className="flex items-start gap-2 rounded border border-port-border/70 px-2 py-1.5 cursor-pointer"
+ >
+ <input
+ id={inputId}
+ type="checkbox"
+ checked={selected}
+ disabled={saving}
+ onChange={() => toggleModel(model)}
+ className="sr-only"
+ aria-label={`Allow ${model.modelName}`}
+ />
+ <span className={`w-3 h-3 mt-0.5 rounded-sm border flex items-center justify-center shrink-0 ${
+ selected ? 'bg-port-accent border-port-accent' : 'border-gray-600'
+ }`}>
+ {selected && <Check size={8} className="text-white" />}
+ </span>
+ <Music2 size={12} className={model.ready ? 'text-port-success mt-0.5' : 'text-gray-500 mt-0.5'} />
+ <span className="min-w-0 flex-1">
+ <span className="block text-gray-300 truncate">{model.modelName}</span>
+ <span className="block text-[10px] text-gray-600 truncate">
+ {model.engineName} · {model.ready ? 'ready' : model.unavailableReason || 'unavailable'}
+ </span>
+ </span>
+ </label>
+ );
+ })}
+ </div>
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/instances/PeerMediaProviderPanel.test.jsx b/client/src/components/instances/PeerMediaProviderPanel.test.jsx
new file mode 100644
index 0000000000..16e1708b12
--- /dev/null
+++ b/client/src/components/instances/PeerMediaProviderPanel.test.jsx
@@ -0,0 +1,92 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+
+vi.mock('../../services/api', () => ({
+ probePeer: vi.fn(),
+ updatePeer: vi.fn(),
+}));
+
+import { probePeer, updatePeer } from '../../services/api';
+import PeerMediaProviderPanel from './PeerMediaProviderPanel';
+
+const basePeer = {
+ id: 'peer-example',
+ name: 'Example Provider',
+ enabled: true,
+ status: 'online',
+};
+
+const readyStatus = {
+ state: 'ready',
+ reason: null,
+ checkedAt: '2026-08-17T12:00:00.000Z',
+ freshUntil: '2026-08-17T12:01:00.000Z',
+ snapshot: {
+ queue: { running: 1, queued: 2, totalActive: 3, maxQueuedJobs: 4, accepting: true },
+ capabilities: [{
+ kind: 'audio',
+ engine: 'minimax-music3',
+ engineName: 'MiniMax Music 3',
+ modelId: 'minimax-music3',
+ modelName: 'MiniMax Music 3',
+ ready: true,
+ unavailableReason: null,
+ }],
+ },
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ updatePeer.mockResolvedValue({ id: basePeer.id });
+ probePeer.mockResolvedValue({ id: basePeer.id });
+});
+
+describe('PeerMediaProviderPanel', () => {
+ it('opts in explicitly and probes before refreshing the card', async () => {
+ const onRefresh = vi.fn();
+ render(<PeerMediaProviderPanel peer={basePeer} onRefresh={onRefresh} />);
+
+ fireEvent.click(screen.getByRole('button', { name: /Remote media provider/i }));
+ fireEvent.click(screen.getByLabelText(/Use this peer for remote audio/i));
+
+ await waitFor(() => expect(updatePeer).toHaveBeenCalledWith('peer-example', {
+ mediaProvider: { enabled: true, audioModels: [] },
+ }));
+ await waitFor(() => expect(probePeer).toHaveBeenCalledWith('peer-example'));
+ expect(onRefresh).toHaveBeenCalled();
+ });
+
+ it('shows queue capacity and persists an allowlisted model without dropping future config fields', async () => {
+ const onRefresh = vi.fn();
+ const peer = {
+ ...basePeer,
+ mediaProvider: { enabled: true, audioModels: [], futureField: 'keep' },
+ mediaProviderStatus: readyStatus,
+ };
+ render(<PeerMediaProviderPanel peer={peer} onRefresh={onRefresh} />);
+
+ fireEvent.click(screen.getByRole('button', { name: /Remote media provider/i }));
+ expect(screen.getByText(/1 running · 2 queued · 3\/4 shared slots active/i)).toBeInTheDocument();
+ fireEvent.click(screen.getByLabelText('Allow MiniMax Music 3'));
+
+ await waitFor(() => expect(updatePeer).toHaveBeenCalledWith('peer-example', {
+ mediaProvider: {
+ enabled: true,
+ futureField: 'keep',
+ audioModels: [{ engine: 'minimax-music3', modelId: 'minimax-music3' }],
+ },
+ }));
+ expect(probePeer).not.toHaveBeenCalled();
+ });
+
+ it('explains that stale capacity blocks new work', () => {
+ render(<PeerMediaProviderPanel peer={{
+ ...basePeer,
+ mediaProvider: { enabled: true, audioModels: [] },
+ mediaProviderStatus: { ...readyStatus, state: 'stale', reason: 'stale' },
+ }} onRefresh={vi.fn()} />);
+
+ fireEvent.click(screen.getByRole('button', { name: /Remote media provider/i }));
+ expect(screen.getByText(/capacity snapshot expired/i)).toBeInTheDocument();
+ });
+});
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 363bc171f2..806ae984f9 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -22,6 +22,7 @@ import {
import PeerAppsList from '../components/instances/PeerAppsList';
import PeerAgentsSection from '../components/instances/PeerAgentsSection';
import { SchemaGapBadge } from '../components/instances/SchemaGapBadge';
+import PeerMediaProviderPanel from '../components/instances/PeerMediaProviderPanel';
import { timeAgo, timeUntil } from '../utils/formatters';
import { useLocalStorageBool } from '../hooks/useLocalStorageBool';
import { directionalCounts, describeDirectional } from '../lib/syncCounts';
@@ -1358,6 +1359,8 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {
<SchemaGapBadge peer={peer} peerSubs={peerSubs} />
+ <PeerMediaProviderPanel peer={peer} onRefresh={onRefresh} />
+
<SyncCategoriesPanel peer={peer} onRefresh={onRefresh} />
<SyncStatusSection peer={peer} syncStatus={syncStatus} peerSubs={peerSubs} peerSubsLoaded={peerSubsLoaded} syncing={syncing} />
diff --git a/docs/FEDERATED_MEDIA_PROVIDERS.md b/docs/FEDERATED_MEDIA_PROVIDERS.md
index fcefe493ef..91455a2ab7 100644
--- a/docs/FEDERATED_MEDIA_PROVIDERS.md
+++ b/docs/FEDERATED_MEDIA_PROVIDERS.md
@@ -2,7 +2,7 @@
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.
+Provider-side queued audio and consumer-side capacity discovery/selection are available. Remote proxy-job execution, failover, and consumer-side commission reconciliation remain later slices of issue #4348.
## Enable a provider
@@ -27,6 +27,28 @@ The default is disabled:
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.
+## Configure a consumer
+
+1. Register the provider under **Instances** and make the relationship mutual so the provider recognizes this consumer's instance id.
+2. Store the provider's instance-password credential on its peer card. The normal peer health probe may work without it when provider auth is off, but the federated-media API intentionally does not.
+3. Expand **Remote media provider** on the peer card and enable **Use this peer for remote audio**. PortOS immediately probes the versioned status endpoint through `peerFetch`.
+4. Select the exact advertised engine/model pairs this instance may use. This local allowlist is independent from the provider's sharing allowlist; both sides must permit a model.
+
+The consumer default is also disabled:
+
+```json
+{
+ "mediaProvider": {
+ "enabled": false,
+ "audioModels": []
+ }
+}
+```
+
+This configuration and the last sanitized capacity snapshot live only on the local peer record. They are stripped from announce responses and do not become federation records. Older peers without the wire-v1 endpoint show as **older peer** rather than making the normal instance probe fail.
+
+The Instances card reports the provider's ready/busy/unavailable state, shared active-job count, queue depth, and advertised model readiness. A consumer preflight accepts a model only when the peer is explicitly enabled, the exact model is locally allowlisted, the wire response validates, the capacity timestamp is fresh, the queue is accepting, and runtime/model/CUDA readiness is positive. Unknown, malformed, clock-skewed, or stale status blocks assignment. The provider remains authoritative and repeats admission checks when a later executor submits the job.
+
## Authentication and identity
Every request requires both:
@@ -52,7 +74,7 @@ All successful JSON responses include `wireVersion: 1`. The version is also fixe
### 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.
+`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. A provider timestamp more than 30 seconds in the future is also rejected as unknown clock state rather than extending capacity indefinitely.
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.
@@ -89,4 +111,4 @@ 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.
+Wire v1 currently provides audio only. Consumers can discover and explicitly allowlist a peer/model, but PortOS does not yet submit a local proxy job through that selection. Still remaining from #4348 are consumer-side job proxying and restart reconciliation, converting the Music studio's synchronous generation route to the durable queue, multi-provider fairness/failover, remote image/video jobs and input-asset transfer, and aggregate provider health on System Health.
diff --git a/server/lib/README.md b/server/lib/README.md
index e00f9a29c7..f172d1d1f4 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -222,6 +222,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `httpClient.js` | Fetch-based HTTP client factory (axios.create replacement). |
| `abortTimeout.js` | `withAbortTimeout(timeoutMs, fn)` — runs `fn(signal)` under an `AbortController` that aborts after `timeoutMs` and always clears the timer on settle. Generic lifecycle helper for callers that need the insecure-agent `peerFetch` (so can't use `fetchWithTimeout`) or one signal across parallel fetches. |
| `fetchWithTimeout.js` | `fetch` wrapper with AbortController timeout. |
+| `federatedMediaWire.js` | Versioned federated-media status schema/constants plus fail-closed consumer freshness checks (stale and clock-skewed snapshots are never assignable). |
| `connectivity.js` | `isMachineOnline({timeoutMs?, hosts?})` — internet-reachability probe: bare TCP `connect` to public anycast resolvers on :443 (no DNS, no HTTP), resolves `true` on the first connect and `false` only after all fail; never rejects. Reuse when a caller needs a best-effort local reachability signal. |
| `safeUrlFetch.js` | SSRF-guarded public-URL fetch: `isPublicHttpUrlSafe`/`assertPublicHttpUrl` (scheme + blocked-host-literal via `catalogValidation.isBlockedIngestHost` + DNS-resolve), exported strict `isPrivateAddress`, plus `fetchPublicText`/`fetchPublicBinary` (timeout, redirect revalidation, size cap) and `buildPinnedLookup`/`buildPinnedDispatcher` (the connect-time IP pin that closes the DNS-rebinding TOCTOU). Reuse instead of copying the SSRF guard for any "fetch this remote thing the user pointed us at" flow. |
| `pinterestFeed.js` | Pure Pinterest board RSS helpers: `normalizePinterestFeedUrl(input)` (board URL or `.rss` → `{ feedUrl, boardUrl }`, host-gated) + `parsePinterestRss(xml)` (per-pin `pinUrl`/`imageUrl`/title/description, 736x size upgrade). Feeds the mood-board Pinterest importer. |
diff --git a/server/lib/federatedMediaWire.js b/server/lib/federatedMediaWire.js
new file mode 100644
index 0000000000..2074f2aad0
--- /dev/null
+++ b/server/lib/federatedMediaWire.js
@@ -0,0 +1,76 @@
+import { z } from 'zod';
+
+export const FEDERATED_MEDIA_WIRE_VERSION = 1;
+export const FEDERATED_MEDIA_STALE_AFTER_MS = 60_000;
+export const FEDERATED_MEDIA_MAX_CLOCK_SKEW_MS = 30_000;
+
+// Wire v1 intentionally exposes audio only. Later media kinds get their own
+// versioned capability shape instead of being accepted against audio-specific
+// readiness fields by an older consumer.
+const mediaKindSchema = z.literal('audio');
+
+const federatedMediaCapabilitySchema = z.object({
+ kind: mediaKindSchema,
+ engine: z.string().trim().min(1).max(80),
+ engineName: z.string().trim().min(1).max(256),
+ modelId: z.string().trim().min(1).max(256),
+ modelName: z.string().trim().min(1).max(256),
+ ready: z.boolean(),
+ unavailableReason: z.string().max(120).nullable(),
+ runtimeReady: z.boolean(),
+ platformSupported: z.boolean(),
+ cudaRequired: z.boolean(),
+ cudaState: z.enum(['available', 'absent', 'unknown']),
+ minDurationSec: z.number().finite().positive().nullable(),
+ maxDurationSec: z.number().finite().positive().nullable(),
+ defaultDurationSec: z.number().finite().positive().nullable(),
+ lyrics: z.boolean(),
+ autoDuration: z.boolean(),
+});
+
+const federatedMediaQueueStatusSchema = z.object({
+ totalActive: z.number().int().nonnegative(),
+ providerActive: z.number().int().nonnegative(),
+ queued: z.number().int().nonnegative(),
+ running: z.number().int().nonnegative(),
+ maxQueuedJobs: z.number().int().positive(),
+ accepting: z.boolean(),
+});
+
+// Strip unknown fields from peer responses before persisting or exposing them
+// locally. Mixed-version compatibility lives in the versioned route and the
+// known-field schema; an older consumer must not relay an unreviewed future
+// status field (especially creative metadata) into its own client payload.
+export const federatedMediaProviderStatusSchema = z.object({
+ wireVersion: z.literal(FEDERATED_MEDIA_WIRE_VERSION),
+ generatedAt: z.string().datetime(),
+ staleAfterMs: z.number().int().positive().max(300_000),
+ status: z.enum(['ready', 'busy', 'unavailable']),
+ kinds: z.array(mediaKindSchema).max(1),
+ queue: federatedMediaQueueStatusSchema,
+ capabilities: z.array(federatedMediaCapabilitySchema).max(300),
+});
+
+/**
+ * Check a validated provider snapshot against the consumer's clock.
+ * A timestamp too far in the future is unknown rather than fresh: accepting it
+ * would extend capacity indefinitely on a peer with a broken clock.
+ */
+export function inspectFederatedMediaStatusFreshness(status, now = Date.now()) {
+ const nowMs = typeof now === 'number' ? now : new Date(now).getTime();
+ const generatedAtMs = Date.parse(status?.generatedAt);
+ const staleAfterMs = status?.staleAfterMs;
+ if (!Number.isFinite(nowMs) || !Number.isFinite(generatedAtMs)
+ || !Number.isInteger(staleAfterMs) || staleAfterMs <= 0) {
+ return { fresh: false, reason: 'invalid-timestamp', freshUntil: null };
+ }
+ if (generatedAtMs - nowMs > FEDERATED_MEDIA_MAX_CLOCK_SKEW_MS) {
+ return { fresh: false, reason: 'clock-skew', freshUntil: null };
+ }
+ const freshUntilMs = generatedAtMs + staleAfterMs;
+ return {
+ fresh: nowMs <= freshUntilMs,
+ reason: nowMs <= freshUntilMs ? null : 'stale',
+ freshUntil: new Date(freshUntilMs).toISOString(),
+ };
+}
diff --git a/server/lib/index.js b/server/lib/index.js
index e9d6a57f41..930f4d5a92 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -214,6 +214,7 @@ export * from './ytdlp.js';
export * from './abortTimeout.js';
export * from './connectivity.js';
export * from './fetchWithTimeout.js';
+export * from './federatedMediaWire.js';
export * from './requestAbort.js';
export * from './httpClient.js';
export * from './httpsState.js';
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 24e3c06b2a..b57888aee1 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -704,13 +704,23 @@ export const federatedMediaModelSchema = z.object({
modelId: z.string().trim().min(1).max(256),
}).passthrough();
+const federatedMediaModelListSchema = 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' },
+);
+
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(),
+ audioModels: federatedMediaModelListSchema.optional(),
+}).passthrough();
+
+// Consumer-side peer selection is independent from the provider's local queue
+// limit. Unknown fields stay round-trip-safe across mixed-version Instances
+// clients while known model pairs remain unique and bounded.
+export const federatedMediaPeerSettingsSchema = z.object({
+ enabled: z.boolean().optional(),
+ audioModels: federatedMediaModelListSchema.optional(),
}).passthrough();
export const federationSettingsSchema = z.object({
diff --git a/server/routes/instances.js b/server/routes/instances.js
index 7a51501194..afaea1f75d 100644
--- a/server/routes/instances.js
+++ b/server/routes/instances.js
@@ -16,6 +16,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { DEFAULT_PEER_PORT } from '../lib/ports.js';
import { findTailscale } from '../lib/tailscale.js';
import { safeJSONParse } from '../lib/fileUtils.js';
+import { federatedMediaPeerSettingsSchema, validateRequest } from '../lib/validation.js';
const execFileAsync = promisify(execFile);
@@ -86,7 +87,10 @@ const updatePeerSchema = z.object({
syncCategories: syncCategoriesSchema,
// Accept empty string to clear; any other string is validated/normalized in the service
host: z.string().optional().nullable(),
- auth: peerAuthSchema
+ auth: peerAuthSchema,
+ // Explicit consumer opt-in + model allowlist for using this peer as a media
+ // provider. Provider-side sharing remains independently configured there.
+ mediaProvider: federatedMediaPeerSettingsSchema.optional(),
});
const announceSchema = z.object({
@@ -263,7 +267,7 @@ router.post('/peers', asyncHandler(async (req, res) => {
// PUT /api/instances/peers/:id — update peer
router.put('/peers/:id', asyncHandler(async (req, res) => {
- const data = updatePeerSchema.parse(req.body);
+ const data = validateRequest(updatePeerSchema, req.body);
// Reject invalid DNS names up front so the UI gets a clear error instead of a silent no-op.
if (data.host !== undefined && data.host !== null && data.host !== '') {
if (instances.validHost(data.host) === undefined) {
diff --git a/server/routes/instances.test.js b/server/routes/instances.test.js
index f315d9cc97..84c085bb75 100644
--- a/server/routes/instances.test.js
+++ b/server/routes/instances.test.js
@@ -3,14 +3,16 @@ import express from 'express';
import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
-// Only GET /api/instances/sync-status is exercised here — it's the forPeer
-// validation that regressed (a non-GUID peer probe threw a 500 every sync
-// cycle). Heavy service deps are mocked so importing the router is cheap.
+// Heavy service deps are mocked so route validation stays cheap and does not
+// reach the live instance store.
vi.mock('../services/syncOrchestrator.js', () => ({
getSyncStatus: vi.fn(),
syncWithPeer: vi.fn(),
}));
-vi.mock('../services/instances.js', () => ({}));
+vi.mock('../services/instances.js', () => ({
+ updatePeer: vi.fn(),
+ sanitizePeerForClient: vi.fn((peer) => peer),
+}));
vi.mock('../services/sharing/peerSync.js', () => ({
getFullSyncCoverageForPeer: vi.fn(),
}));
@@ -22,6 +24,7 @@ vi.mock('../lib/tailscale.js', () => ({
}));
import { getSyncStatus } from '../services/syncOrchestrator.js';
+import * as instances from '../services/instances.js';
import instancesRoutes from './instances.js';
const buildApp = () => {
@@ -95,3 +98,40 @@ describe('GET /api/instances/sync-status — forPeer scoping', () => {
expect(res.body).toMatchObject({ brainSeq: 3, memorySeq: 5, cursorForYou: 42 });
});
});
+
+describe('PUT /api/instances/peers/:id — media provider selection', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ instances.updatePeer.mockImplementation(async (id, updates) => ({ id, ...updates }));
+ });
+
+ it('validates and preserves mixed-version fields in the consumer allowlist', async () => {
+ const mediaProvider = {
+ enabled: true,
+ futureField: 'keep',
+ audioModels: [{
+ engine: 'minimax-music3',
+ modelId: 'minimax-music3',
+ futureModelField: 'keep-too',
+ }],
+ };
+
+ const res = await request(buildApp())
+ .put('/api/instances/peers/peer-example')
+ .send({ mediaProvider });
+
+ expect(res.status).toBe(200);
+ expect(instances.updatePeer).toHaveBeenCalledWith('peer-example', { mediaProvider });
+ expect(res.body.mediaProvider).toEqual(mediaProvider);
+ });
+
+ it('rejects duplicate engine/model pairs before mutating the peer record', async () => {
+ const model = { engine: 'minimax-music3', modelId: 'minimax-music3' };
+ const res = await request(buildApp())
+ .put('/api/instances/peers/peer-example')
+ .send({ mediaProvider: { enabled: true, audioModels: [model, model] } });
+
+ expect(res.status).toBe(400);
+ expect(instances.updatePeer).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/federatedMediaConsumer.js b/server/services/federatedMediaConsumer.js
new file mode 100644
index 0000000000..c35ca5693d
--- /dev/null
+++ b/server/services/federatedMediaConsumer.js
@@ -0,0 +1,208 @@
+/**
+ * Consumer-side discovery and selection for federated media providers.
+ *
+ * This module deliberately stops before job proxying: it establishes the
+ * explicit per-peer allowlist and fail-closed capacity preflight that every
+ * remote executor must pass before it can submit work.
+ */
+
+import { ServerError } from '../lib/errorHandler.js';
+import {
+ federatedMediaProviderStatusSchema,
+ inspectFederatedMediaStatusFreshness,
+} from '../lib/federatedMediaWire.js';
+import { peerFetch } from '../lib/peerHttpClient.js';
+import { peerBaseUrl } from '../lib/peerUrl.js';
+import { readResponseJson } from '../lib/readResponseJson.js';
+
+export const DEFAULT_FEDERATED_MEDIA_PEER_CONFIG = Object.freeze({
+ enabled: false,
+ audioModels: Object.freeze([]),
+});
+
+const isRecord = (value) => value && typeof value === 'object' && !Array.isArray(value);
+const modelKey = ({ engine, modelId }) => `${engine}\u0000${modelId}`;
+
+function sanitizeModels(models, { preserveUnknown = false } = {}) {
+ if (!Array.isArray(models)) return [];
+ const seen = new Set();
+ const sanitized = [];
+ for (const model of models) {
+ if (!isRecord(model)) continue;
+ const engine = typeof model.engine === 'string' ? model.engine.trim() : '';
+ const modelId = typeof model.modelId === 'string' ? model.modelId.trim() : '';
+ if (!engine || !modelId) continue;
+ const key = modelKey({ engine, modelId });
+ if (seen.has(key)) continue;
+ seen.add(key);
+ sanitized.push(preserveUnknown ? { ...model, engine, modelId } : { engine, modelId });
+ if (sanitized.length === 100) break;
+ }
+ return sanitized;
+}
+
+export function normalizePeerMediaProviderConfig(peer) {
+ const raw = peer?.mediaProvider;
+ if (!isRecord(raw)) {
+ return { ...DEFAULT_FEDERATED_MEDIA_PEER_CONFIG, audioModels: [] };
+ }
+ return {
+ enabled: raw.enabled === true,
+ audioModels: sanitizeModels(raw.audioModels),
+ };
+}
+
+/**
+ * Merge a validated client patch without dropping fields written by a newer
+ * PortOS version. Known values are normalized; unknown object/model fields are
+ * carried forward for rollback compatibility.
+ */
+export function mergePeerMediaProviderConfig(current, patch) {
+ const base = isRecord(current) ? current : {};
+ const incoming = isRecord(patch) ? patch : {};
+ const merged = { ...base, ...incoming };
+ return {
+ ...merged,
+ enabled: merged.enabled === true,
+ audioModels: sanitizeModels(merged.audioModels, { preserveUnknown: true }),
+ };
+}
+
+const checkedAt = (now) => new Date(now).toISOString();
+const probeResult = (now, state, reason, snapshot = null, freshUntil = null) => ({
+ checkedAt: checkedAt(now),
+ state,
+ reason,
+ freshUntil,
+ snapshot,
+});
+
+function responseState(response, body) {
+ if (response.status === 404) return ['unsupported', 'wire-v1-not-supported'];
+ if (response.status === 401 || response.status === 403) return ['unauthorized', body?.code || `http-${response.status}`];
+ if (body?.code === 'MEDIA_PROVIDER_DISABLED') return ['disabled', body.code];
+ return ['unavailable', body?.code || `http-${response.status || 'error'}`];
+}
+
+/**
+ * Fetch and sanitize one opted-in peer's live status. All failures become a
+ * typed local projection instead of escaping into the background probe loop.
+ */
+export async function probeFederatedMediaProvider(peer, { signal, now = Date.now() } = {}) {
+ const config = normalizePeerMediaProviderConfig(peer);
+ if (!config.enabled) return probeResult(now, 'disabled', 'not-configured');
+
+ const outcome = await peerFetch(
+ `${peerBaseUrl(peer)}/api/federation/media/v1/status`,
+ { signal },
+ peer,
+ ).then((response) => ({ response }), (error) => ({ error }));
+ if (outcome.error) {
+ return probeResult(now, 'unreachable', outcome.error?.name === 'AbortError' ? 'timeout' : 'request-failed');
+ }
+
+ const body = await readResponseJson(outcome.response, { fallback: null, emptyValue: null }).catch(() => null);
+ if (!outcome.response.ok) {
+ const [state, reason] = responseState(outcome.response, body);
+ return probeResult(now, state, reason);
+ }
+
+ const parsed = federatedMediaProviderStatusSchema.safeParse(body);
+ if (!parsed.success) return probeResult(now, 'invalid', 'invalid-wire-response');
+
+ const freshness = inspectFederatedMediaStatusFreshness(parsed.data, now);
+ if (!freshness.fresh) {
+ return probeResult(now, 'stale', freshness.reason, parsed.data, freshness.freshUntil);
+ }
+
+ const providerState = parsed.data.status === 'ready' && !parsed.data.queue.accepting
+ ? 'busy'
+ : parsed.data.status;
+ return probeResult(
+ now,
+ providerState,
+ providerState === 'ready' ? null : `provider-${providerState}`,
+ parsed.data,
+ freshness.freshUntil,
+ );
+}
+
+const rejectSelection = (message, code, status = 503, reason) => {
+ throw new ServerError(message, {
+ status,
+ code,
+ ...(reason ? { context: { reason } } : {}),
+ });
+};
+
+/**
+ * Enforce the local user's explicit peer/model choice against a fresh status.
+ * The provider still rechecks admission on submit; this advisory preflight
+ * prevents arbitrary peer routing and known-bad work from leaving this node.
+ */
+export function assertFederatedMediaProviderSelection(peer, selection, probe, { now = Date.now() } = {}) {
+ if (!peer || peer.enabled === false) {
+ rejectSelection('Selected media provider peer is disabled', 'MEDIA_PROVIDER_PEER_DISABLED', 409);
+ }
+ const config = normalizePeerMediaProviderConfig(peer);
+ if (!config.enabled) {
+ rejectSelection('Peer is not enabled as a media provider', 'MEDIA_PROVIDER_NOT_CONFIGURED', 409);
+ }
+ if (selection?.kind !== 'audio' || typeof selection.engine !== 'string' || typeof selection.modelId !== 'string') {
+ rejectSelection('Only an explicit audio engine and model can be selected', 'MEDIA_PROVIDER_SELECTION_INVALID', 400);
+ }
+ const requested = { engine: selection.engine.trim(), modelId: selection.modelId.trim() };
+ if (!requested.engine || !requested.modelId
+ || !config.audioModels.some((model) => modelKey(model) === modelKey(requested))) {
+ rejectSelection('Requested model is not allowlisted for this peer', 'MEDIA_PROVIDER_MODEL_NOT_ALLOWED', 403);
+ }
+
+ if (probe?.state === 'stale') {
+ rejectSelection('Media provider capacity is stale', 'MEDIA_PROVIDER_STATUS_STALE', 503, probe.reason);
+ }
+ if (probe?.state === 'busy') {
+ rejectSelection('Media provider is at capacity', 'MEDIA_PROVIDER_BUSY', 429, probe.reason);
+ }
+ if (probe?.state !== 'ready' || !probe.snapshot) {
+ rejectSelection('Media provider is unavailable', 'MEDIA_PROVIDER_UNAVAILABLE', 503, probe?.reason || 'status-unknown');
+ }
+ const parsedSnapshot = federatedMediaProviderStatusSchema.safeParse(probe.snapshot);
+ if (!parsedSnapshot.success) {
+ rejectSelection('Media provider status is invalid', 'MEDIA_PROVIDER_UNAVAILABLE', 503, 'invalid-wire-response');
+ }
+ const snapshot = parsedSnapshot.data;
+ if (snapshot.status === 'busy') {
+ rejectSelection('Media provider is at capacity', 'MEDIA_PROVIDER_BUSY', 429, 'provider-busy');
+ }
+ if (snapshot.status !== 'ready') {
+ rejectSelection('Media provider is unavailable', 'MEDIA_PROVIDER_UNAVAILABLE', 503, 'provider-unavailable');
+ }
+ const freshness = inspectFederatedMediaStatusFreshness(snapshot, now);
+ if (!freshness.fresh) {
+ rejectSelection('Media provider capacity is stale', 'MEDIA_PROVIDER_STATUS_STALE', 503, freshness.reason);
+ }
+ if (!snapshot.queue.accepting) {
+ rejectSelection('Media provider is at capacity', 'MEDIA_PROVIDER_BUSY', 429, 'queue-full');
+ }
+
+ const capability = snapshot.capabilities.find((candidate) =>
+ candidate.kind === 'audio'
+ && candidate.engine === requested.engine
+ && candidate.modelId === requested.modelId,
+ );
+ if (!capability || !capability.ready
+ || (capability.cudaRequired && capability.cudaState !== 'available')) {
+ rejectSelection(
+ 'Selected media provider model is unavailable',
+ 'MEDIA_PROVIDER_MODEL_UNAVAILABLE',
+ 503,
+ capability?.unavailableReason || 'capability-unavailable',
+ );
+ }
+ return { peer, capability, status: snapshot };
+}
+
+export async function resolveFederatedMediaProvider(peer, selection, options = {}) {
+ const probe = await probeFederatedMediaProvider(peer, options);
+ return assertFederatedMediaProviderSelection(peer, selection, probe, options);
+}
diff --git a/server/services/federatedMediaConsumer.test.js b/server/services/federatedMediaConsumer.test.js
new file mode 100644
index 0000000000..1786deb91e
--- /dev/null
+++ b/server/services/federatedMediaConsumer.test.js
@@ -0,0 +1,227 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('../lib/peerHttpClient.js', () => ({
+ peerFetch: vi.fn(),
+}));
+
+import { peerFetch } from '../lib/peerHttpClient.js';
+import {
+ assertFederatedMediaProviderSelection,
+ mergePeerMediaProviderConfig,
+ normalizePeerMediaProviderConfig,
+ probeFederatedMediaProvider,
+ resolveFederatedMediaProvider,
+} from './federatedMediaConsumer.js';
+
+const NOW = Date.parse('2026-08-17T12:00:00.000Z');
+const selection = { kind: 'audio', engine: 'minimax-music3', modelId: 'minimax-music3' };
+
+const peer = (overrides = {}) => ({
+ id: 'peer-example',
+ address: '192.0.2.10',
+ port: 5555,
+ enabled: true,
+ mediaProvider: {
+ enabled: true,
+ audioModels: [{ engine: selection.engine, modelId: selection.modelId }],
+ },
+ ...overrides,
+});
+
+function readyStatus(overrides = {}) {
+ return {
+ wireVersion: 1,
+ generatedAt: new Date(NOW).toISOString(),
+ staleAfterMs: 60_000,
+ status: 'ready',
+ kinds: ['audio'],
+ queue: {
+ totalActive: 0,
+ providerActive: 0,
+ queued: 0,
+ running: 0,
+ maxQueuedJobs: 2,
+ accepting: true,
+ },
+ capabilities: [{
+ kind: 'audio',
+ engine: selection.engine,
+ engineName: 'MiniMax Music 3',
+ modelId: selection.modelId,
+ modelName: 'MiniMax Music 3',
+ ready: true,
+ unavailableReason: null,
+ runtimeReady: true,
+ platformSupported: true,
+ cudaRequired: true,
+ cudaState: 'available',
+ minDurationSec: 10,
+ maxDurationSec: 300,
+ defaultDurationSec: 60,
+ lyrics: true,
+ autoDuration: false,
+ privateFutureField: 'must-not-cross',
+ }],
+ privateFutureField: 'must-not-cross',
+ ...overrides,
+ };
+}
+
+const response = (body, status = 200) => ({
+ ok: status >= 200 && status < 300,
+ status,
+ text: vi.fn(async () => body === null ? '' : JSON.stringify(body)),
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('federated media consumer configuration', () => {
+ it('defaults old peer records to disabled with no allowlisted models', () => {
+ expect(normalizePeerMediaProviderConfig({})).toEqual({ enabled: false, audioModels: [] });
+ });
+
+ it('preserves future config/model fields while normalizing and de-duplicating known pairs', () => {
+ const merged = mergePeerMediaProviderConfig(
+ { enabled: false, future: 'keep', audioModels: [] },
+ {
+ enabled: true,
+ audioModels: [
+ { engine: ' minimax-music3 ', modelId: 'minimax-music3', futureModel: 'keep-too' },
+ { engine: 'minimax-music3', modelId: 'minimax-music3' },
+ ],
+ },
+ );
+
+ expect(merged).toEqual({
+ enabled: true,
+ future: 'keep',
+ audioModels: [{ engine: 'minimax-music3', modelId: 'minimax-music3', futureModel: 'keep-too' }],
+ });
+ });
+
+ it('bounds legacy direct-service allowlists to the route schema limit', () => {
+ const audioModels = Array.from({ length: 101 }, (_, index) => ({
+ engine: 'example-engine',
+ modelId: `model-${index}`,
+ }));
+
+ expect(mergePeerMediaProviderConfig({}, { enabled: true, audioModels }).audioModels)
+ .toHaveLength(100);
+ });
+});
+
+describe('federated media provider discovery', () => {
+ it('does not contact a peer until the user opts it in', async () => {
+ const result = await probeFederatedMediaProvider(peer({ mediaProvider: undefined }), { now: NOW });
+ expect(result).toMatchObject({ state: 'disabled', reason: 'not-configured', snapshot: null });
+ expect(peerFetch).not.toHaveBeenCalled();
+ });
+
+ it('uses authenticated peerFetch and stores only the allowlisted wire projection', async () => {
+ peerFetch.mockResolvedValue(response(readyStatus()));
+
+ const target = peer();
+ const result = await probeFederatedMediaProvider(target, { now: NOW });
+
+ expect(peerFetch).toHaveBeenCalledWith(
+ 'http://192.0.2.10:5555/api/federation/media/v1/status',
+ { signal: undefined },
+ target,
+ );
+ expect(result).toMatchObject({ state: 'ready', reason: null, freshUntil: '2026-08-17T12:01:00.000Z' });
+ expect(result.snapshot.privateFutureField).toBeUndefined();
+ expect(result.snapshot.capabilities[0].privateFutureField).toBeUndefined();
+ });
+
+ it('marks expired capacity stale instead of treating a reachable peer as available', async () => {
+ peerFetch.mockResolvedValue(response(readyStatus({ generatedAt: '2026-08-17T11:58:00.000Z' })));
+
+ await expect(probeFederatedMediaProvider(peer(), { now: NOW })).resolves.toMatchObject({
+ state: 'stale',
+ reason: 'stale',
+ });
+ });
+
+ it('distinguishes an older peer with no wire-v1 route', async () => {
+ peerFetch.mockResolvedValue(response({ error: 'Not found' }, 404));
+
+ await expect(probeFederatedMediaProvider(peer(), { now: NOW })).resolves.toMatchObject({
+ state: 'unsupported',
+ reason: 'wire-v1-not-supported',
+ snapshot: null,
+ });
+ });
+
+ it('rejects future media kinds against the audio-only wire-v1 shape', async () => {
+ const futureStatus = readyStatus({
+ kinds: ['image'],
+ capabilities: [{ ...readyStatus().capabilities[0], kind: 'image' }],
+ });
+ peerFetch.mockResolvedValue(response(futureStatus));
+
+ await expect(probeFederatedMediaProvider(peer(), { now: NOW })).resolves.toMatchObject({
+ state: 'invalid',
+ reason: 'invalid-wire-response',
+ snapshot: null,
+ });
+ });
+});
+
+describe('federated media provider selection', () => {
+ it('resolves an explicit allowlisted model only after a fresh ready preflight', async () => {
+ peerFetch.mockResolvedValue(response(readyStatus()));
+
+ const resolved = await resolveFederatedMediaProvider(peer(), selection, { now: NOW });
+
+ expect(resolved.capability).toMatchObject(selection);
+ expect(resolved.status.queue.accepting).toBe(true);
+ });
+
+ it('rejects a model the local user did not allowlist before checking capacity', () => {
+ const configured = peer({ mediaProvider: { enabled: true, audioModels: [] } });
+ const probe = {
+ state: 'ready',
+ reason: null,
+ snapshot: readyStatus(),
+ };
+
+ expect(() => assertFederatedMediaProviderSelection(configured, selection, probe, { now: NOW }))
+ .toThrow(expect.objectContaining({ code: 'MEDIA_PROVIDER_MODEL_NOT_ALLOWED', status: 403 }));
+ });
+
+ it('rejects busy capacity and CUDA unknown even when the peer is reachable', () => {
+ const busy = {
+ state: 'busy',
+ reason: 'provider-busy',
+ snapshot: readyStatus({ status: 'busy', queue: { ...readyStatus().queue, accepting: false } }),
+ };
+ expect(() => assertFederatedMediaProviderSelection(peer(), selection, busy, { now: NOW }))
+ .toThrow(expect.objectContaining({ code: 'MEDIA_PROVIDER_BUSY', status: 429 }));
+
+ const cudaUnknownStatus = readyStatus();
+ cudaUnknownStatus.capabilities[0] = {
+ ...cudaUnknownStatus.capabilities[0],
+ ready: false,
+ unavailableReason: 'cuda-unknown',
+ cudaState: 'unknown',
+ };
+ expect(() => assertFederatedMediaProviderSelection(peer(), selection, {
+ state: 'ready',
+ reason: null,
+ snapshot: cudaUnknownStatus,
+ }, { now: NOW })).toThrow(expect.objectContaining({ code: 'MEDIA_PROVIDER_MODEL_UNAVAILABLE' }));
+ });
+
+ it('revalidates cached snapshots before assignment', () => {
+ expect(() => assertFederatedMediaProviderSelection(peer(), selection, {
+ state: 'ready',
+ reason: null,
+ snapshot: { ...readyStatus(), queue: null },
+ }, { now: NOW })).toThrow(expect.objectContaining({
+ code: 'MEDIA_PROVIDER_UNAVAILABLE',
+ context: { reason: 'invalid-wire-response' },
+ }));
+ });
+});
diff --git a/server/services/federatedMediaProvider.js b/server/services/federatedMediaProvider.js
index 648b9efb00..3c911b3ae4 100644
--- a/server/services/federatedMediaProvider.js
+++ b/server/services/federatedMediaProvider.js
@@ -12,14 +12,17 @@ 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 {
+ FEDERATED_MEDIA_STALE_AFTER_MS,
+ FEDERATED_MEDIA_WIRE_VERSION,
+} from '../lib/federatedMediaWire.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 { FEDERATED_MEDIA_STALE_AFTER_MS, FEDERATED_MEDIA_WIRE_VERSION };
export const DEFAULT_FEDERATED_MEDIA_PROVIDER = Object.freeze({
enabled: false,
maxQueuedJobs: 2,
diff --git a/server/services/instances.js b/server/services/instances.js
index ba4565a8fc..34c954fb6f 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -11,6 +11,7 @@ import crypto from 'crypto';
import { dataPath, readJSONFile, ensureDir, PATHS, atomicWrite } from '../lib/fileUtils.js';
import { createMutex } from '../lib/asyncMutex.js';
import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';
+import { canonicalStringify } from '../lib/objects.js';
import { instanceEvents } from './instanceEvents.js';
import { connectToPeer, disconnectFromPeer } from './peerSocketRelay.js';
import { DEFAULT_PEER_PORT } from '../lib/ports.js';
@@ -20,6 +21,11 @@ import { withAbortTimeout } from '../lib/abortTimeout.js';
import { getSelfHost } from '../lib/peerSelfHost.js';
import { getTailscaleStatus } from '../lib/tailscale.js';
import { autoSubscribePeerToAllRecords } from './sharing/recordEvents.js';
+import {
+ mergePeerMediaProviderConfig,
+ normalizePeerMediaProviderConfig,
+ probeFederatedMediaProvider,
+} from './federatedMediaConsumer.js';
const INSTANCES_FILE = dataPath('instances.json');
const PROBE_TIMEOUT_MS = 5000;
@@ -112,10 +118,17 @@ function sameAuth(a, b) {
// Strip the locally-stored proxy credential before a peer record crosses the
// wire (e.g. the announce response echoes the matched local peer back to the
// announcing instance). The password is OUR secret for reaching THEM and must
-// never leak to the peer itself.
+// never leak to the peer itself. Consumer routing policy and cached capacity
+// are local-only too, so peers cannot discover or influence our assignments.
export function redactPeerForWire(peer) {
- if (!peer || typeof peer !== 'object' || !('auth' in peer)) return peer;
- const { auth: _auth, ...rest } = peer;
+ if (!peer || typeof peer !== 'object') return peer;
+ if (!('auth' in peer) && !('mediaProvider' in peer) && !('mediaProviderStatus' in peer)) return peer;
+ const {
+ auth: _auth,
+ mediaProvider: _mediaProvider,
+ mediaProviderStatus: _mediaProviderStatus,
+ ...rest
+ } = peer;
return rest;
}
@@ -362,6 +375,9 @@ export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, a
fullSync: data.self?.defaultPeerFullSync === true,
syncEnabled: data.self?.defaultPeerFullSync === true,
syncCategories: { ...DEFAULT_SYNC_CATEGORIES },
+ // Consumer-side routing is explicit and machine-local. Enabling a peer
+ // here never changes that peer's provider settings.
+ mediaProvider: { enabled: false, audioModels: [] },
consecutiveFailures: 0,
nextProbeAt: null,
directions: ['outbound']
@@ -470,6 +486,17 @@ export async function updatePeer(id, updates) {
}
}
}
+ if (updates.mediaProvider !== undefined
+ && updates.mediaProvider && typeof updates.mediaProvider === 'object'
+ && !Array.isArray(updates.mediaProvider)) {
+ const previous = peer.mediaProvider;
+ const next = mergePeerMediaProviderConfig(previous, updates.mediaProvider);
+ if (canonicalStringify(previous ?? null) !== canonicalStringify(next)) {
+ peer.mediaProvider = next;
+ if (!next.enabled) delete peer.mediaProviderStatus;
+ console.log(`🌐 Remote media provider ${next.enabled ? 'enabled' : 'disabled'}: ${peer.name}`);
+ }
+ }
if (updates.host !== undefined) {
const normalized = validHost(updates.host);
if (normalized !== undefined && normalized !== peer.host) {
@@ -580,6 +607,7 @@ export async function probePeer(peer) {
const previousStatus = peer.status;
let status, lastHealth, lastSeen, remoteInstanceId, remoteVersion, remoteApps, remoteSyncSeqs;
+ let remoteMediaProviderStatus = null;
// Latches when the peer answers 401/403 — a reachable-but-auth-gated peer, as
// opposed to an unreachable one. The Instances UI reads this to prompt for a
// credential instead of showing a generic offline state.
@@ -596,12 +624,18 @@ export async function probePeer(peer) {
const forPeerQs = typeof ourInstanceId === 'string' && ourInstanceId && ourInstanceId !== UNKNOWN_INSTANCE_ID
? `?forPeer=${encodeURIComponent(ourInstanceId)}`
: '';
- // Fetch health details, apps, and sync status in parallel
- const [healthRes, appsRes, syncRes] = await Promise.all([
+ // Fetch health details, apps, sync status, and opted-in media capacity in
+ // parallel under the same bounded probe budget. Older/unconfigured peers
+ // incur no fourth request.
+ const [healthRes, appsRes, syncRes, mediaProviderStatus] = await Promise.all([
peerFetch(`${baseUrl}/api/system/health/details`, { signal }, peer),
peerFetch(`${baseUrl}/api/apps`, { signal }, peer).catch(() => null),
- peerFetch(`${baseUrl}/api/instances/sync-status${forPeerQs}`, { signal }, peer).catch(() => null)
+ peerFetch(`${baseUrl}/api/instances/sync-status${forPeerQs}`, { signal }, peer).catch(() => null),
+ normalizePeerMediaProviderConfig(peer).enabled
+ ? probeFederatedMediaProvider(peer, { signal })
+ : Promise.resolve(null),
]);
+ remoteMediaProviderStatus = mediaProviderStatus;
if (!healthRes.ok) {
const err = new Error(`HTTP ${healthRes.status}`);
err.httpStatus = healthRes.status;
@@ -631,6 +665,15 @@ export async function probePeer(peer) {
authRequired = err?.httpStatus === 401 || err?.httpStatus === 403;
lastHealth = peer.lastHealth; // preserve last known
lastSeen = peer.lastSeen;
+ if (normalizePeerMediaProviderConfig(peer).enabled && !remoteMediaProviderStatus) {
+ remoteMediaProviderStatus = {
+ checkedAt: new Date().toISOString(),
+ state: 'unreachable',
+ reason: 'peer-offline',
+ freshUntil: null,
+ snapshot: null,
+ };
+ }
});
const stored = await withData(async (data) => {
@@ -644,6 +687,11 @@ export async function probePeer(peer) {
entry.authRequired = authRequired;
entry.lastApps = remoteApps ?? entry.lastApps ?? null;
entry.remoteSyncSeqs = remoteSyncSeqs ?? entry.remoteSyncSeqs ?? null;
+ if (normalizePeerMediaProviderConfig(entry).enabled) {
+ if (remoteMediaProviderStatus) entry.mediaProviderStatus = remoteMediaProviderStatus;
+ } else {
+ delete entry.mediaProviderStatus;
+ }
if (remoteInstanceId) entry.instanceId = remoteInstanceId;
if (status === 'online') entry.version = remoteVersion;
// Auto-update name from hostname if current name is just an IP address
diff --git a/server/services/instances.test.js b/server/services/instances.test.js
index 71d93e7a17..f826b6a598 100644
--- a/server/services/instances.test.js
+++ b/server/services/instances.test.js
@@ -20,8 +20,9 @@ vi.mock('fs/promises', () => ({
rename: vi.fn().mockResolvedValue(undefined)
}));
-vi.mock('../lib/fileUtils.js', () => ({
-tryReadFile: vi.fn().mockResolvedValue(null),
+vi.mock('../lib/fileUtils.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ tryReadFile: vi.fn().mockResolvedValue(null),
dataPath: (name) => `/mock/data/${name}`,
readJSONFile: vi.fn(),
ensureDir: vi.fn().mockResolvedValue(undefined),
@@ -240,6 +241,7 @@ describe('instances.js', () => {
instanceId: null,
status: 'unknown',
enabled: true,
+ mediaProvider: { enabled: false, audioModels: [] },
directions: ['outbound']
});
expect(peer.addedAt).toBeDefined();
@@ -368,11 +370,20 @@ describe('instances.js', () => {
});
describe('redactPeerForWire', () => {
- it('strips the auth credential before a peer crosses the wire', () => {
- const peer = { id: 'peer-1', name: 'host', auth: { username: 'a', password: 'b' }, status: 'online' };
+ it('strips credentials and local media-routing state before a peer crosses the wire', () => {
+ const peer = {
+ id: 'peer-1',
+ name: 'host',
+ auth: { username: 'a', password: 'b' },
+ mediaProvider: { enabled: true, audioModels: [{ engine: 'example', modelId: 'example' }] },
+ mediaProviderStatus: { state: 'ready' },
+ status: 'online',
+ };
const redacted = redactPeerForWire(peer);
expect(redacted).not.toHaveProperty('auth');
+ expect(redacted).not.toHaveProperty('mediaProvider');
+ expect(redacted).not.toHaveProperty('mediaProviderStatus');
expect(redacted).toMatchObject({ id: 'peer-1', name: 'host', status: 'online' });
// Does not mutate the original
expect(peer.auth).toEqual({ username: 'a', password: 'b' });
@@ -517,6 +528,26 @@ describe('instances.js', () => {
expect(disconnectFromPeer).not.toHaveBeenCalled();
});
+ it('stores a disabled remote-media allowlist while preserving future config fields', async () => {
+ const peers = [{ id: 'peer-1', name: 'host', enabled: true }];
+ readJSONFile.mockResolvedValue({ self: null, peers });
+
+ const result = await updatePeer('peer-1', {
+ mediaProvider: {
+ enabled: false,
+ futureField: 'keep',
+ audioModels: [{ engine: ' minimax-music3 ', modelId: 'minimax-music3', futureModel: 'keep-too' }],
+ },
+ });
+
+ expect(result.mediaProvider).toEqual({
+ enabled: false,
+ futureField: 'keep',
+ audioModels: [{ engine: 'minimax-music3', modelId: 'minimax-music3', futureModel: 'keep-too' }],
+ });
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
it('should set a valid DNS host and disconnect the relay so it reconnects via HTTPS', async () => {
const peers = [{ id: 'peer-1', name: 'host', enabled: true, host: null }];
readJSONFile.mockResolvedValue({ self: null, peers });
@@ -1043,6 +1074,51 @@ describe('instances.js', () => {
expect(result.version).toBe('1.0.0');
expect(result.lastSeen).toBeDefined();
expect(connectToPeer).toHaveBeenCalledWith(peer);
+ expect(fetch).toHaveBeenCalledTimes(3);
+ });
+
+ it('discovers and persists capacity only for an opted-in media provider peer', async () => {
+ const target = makePeer({
+ mediaProvider: {
+ enabled: true,
+ audioModels: [{ engine: 'minimax-music3', modelId: 'minimax-music3' }],
+ },
+ });
+ readJSONFile.mockResolvedValue({ self: null, peers: [target] });
+ const providerStatus = {
+ wireVersion: 1,
+ generatedAt: new Date().toISOString(),
+ staleAfterMs: 60_000,
+ status: 'ready',
+ kinds: ['audio'],
+ queue: { totalActive: 0, providerActive: 0, queued: 0, running: 0, maxQueuedJobs: 2, accepting: true },
+ capabilities: [{
+ kind: 'audio', engine: 'minimax-music3', engineName: 'MiniMax Music 3',
+ modelId: 'minimax-music3', modelName: 'MiniMax Music 3', ready: true,
+ unavailableReason: null, runtimeReady: true, platformSupported: true,
+ cudaRequired: true, cudaState: 'available', minDurationSec: 10,
+ maxDurationSec: 300, defaultDurationSec: 60, lyrics: true, autoDuration: false,
+ }],
+ };
+ fetch.mockImplementation(async (url) => {
+ if (String(url).endsWith('/api/system/health/details')) {
+ return { ok: true, json: async () => ({ instanceId: 'remote-id', version: '1.0.0' }) };
+ }
+ if (String(url).endsWith('/api/apps')) return { ok: true, json: async () => [] };
+ if (String(url).includes('/api/instances/sync-status')) return { ok: true, json: async () => ({}) };
+ if (String(url).endsWith('/api/federation/media/v1/status')) {
+ return { ok: true, status: 200, text: async () => JSON.stringify(providerStatus) };
+ }
+ return { ok: false, status: 404, text: async () => '' };
+ });
+
+ const result = await probePeer(target);
+
+ expect(result.mediaProviderStatus).toMatchObject({ state: 'ready', reason: null });
+ expect(fetch).toHaveBeenCalledWith(
+ 'http://10.0.0.1:5555/api/federation/media/v1/status',
+ expect.objectContaining({ signal: expect.any(AbortSignal) }),
+ );
});
it('should mark peer offline on fetch failure', async () => {