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 durable remote audio execution (#4467)

[._.]/ Adam Eivy3bcce8666794
diff --git a/.changelog/next/added-issue-4348.md b/.changelog/next/added-issue-4348.md
index aef35f7798..bbec2a9bac 100644
--- a/.changelog/next/added-issue-4348.md
+++ b/.changelog/next/added-issue-4348.md
@@ -1,2 +1,3 @@
- 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).
+- Music generation can now run privacy-safe structured instrumental profiles on an explicitly selected peer, survive consumer restarts, relay progress and cancellation, and import only integrity-verified audio (#4348).
diff --git a/client/src/services/apiMusic.js b/client/src/services/apiMusic.js
index 400d553368..85ffe12140 100644
--- a/client/src/services/apiMusic.js
+++ b/client/src/services/apiMusic.js
@@ -9,11 +9,14 @@ import { request, maybeRedirectToLogin } from './apiCore.js';
// and a `ready` flag (the opt-in venv is provisioned) → { engines, defaultEngine }.
export const listMusicEngines = (options = {}) => request('/music/engines', options);
-// Generate a track. body: { prompt, lyrics?, instrumentalOnly?, engine?, modelId?, durationSec?,
-// durationMode?: 'auto'|'manual',
-// trackId? (update) | title?/artistId?/artist?/albumId? (create) }. New servers
-// acknowledge with HTTP 202 + { jobId, position, status }; an older rolling-
-// upgrade peer may still return { track }. Callers own their loading UI.
+// Generate a queued track job. body: { prompt, lyrics?, instrumentalOnly?, engine?, modelId?,
+// durationSec?, durationMode?: 'auto'|'manual', mediaProviderPeerId?,
+// remoteMusicProfile?: { style, mood, tempo?, energy?, instruments? },
+// trackId? (update) | title?/artistId?/artist?/albumId? (create) }. Resolves to
+// { jobId, position, status }; callers watch the shared media-job SSE lifecycle.
+// A remote peer id requires an explicit engine, model, and fixed-vocabulary
+// instrumental profile. The free-form prompt remains local; non-empty remote
+// lyrics are rejected.
export const generateMusic = (body, requestOptions = {}) => request('/music/generate', {
method: 'POST',
body: JSON.stringify(body),
diff --git a/docs/FEDERATED_MEDIA_PROVIDERS.md b/docs/FEDERATED_MEDIA_PROVIDERS.md
index 91455a2ab7..42a1199231 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.
-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.
+Provider-side queued audio, consumer-side capacity discovery, and durable remote audio execution are available. Multi-provider scheduling, image/video transfer, and higher-level commission routing remain later slices of issue #4348.
## Enable a provider
@@ -49,6 +49,26 @@ This configuration and the last sanitized capacity snapshot live only on the loc
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.
+An API caller deliberately selects remote execution on Music generation by sending the local peer-record id together with an explicit advertised engine/model and a fixed-vocabulary instrumental profile:
+
+```json
+{
+ "prompt": "A fictional slow synthetic pulse",
+ "engine": "minimax-music3",
+ "modelId": "minimax-music3",
+ "mediaProviderPeerId": "00000000-0000-4000-8000-000000000001",
+ "remoteMusicProfile": {
+ "style": "cinematic",
+ "mood": "dreamy",
+ "tempo": "slow",
+ "energy": "medium",
+ "instruments": ["strings", "synthesizer"]
+ }
+}
+```
+
+`POST /api/music/generate` performs the fresh capacity preflight before returning the normal queued media-job response. Omitting `mediaProviderPeerId` keeps the existing local-engine behavior. The peer id and free-form `prompt` stay local. The worker renders the provider prompt only from the profile's enum values; non-empty remote lyrics are rejected so arbitrary personal text cannot cross the federation boundary.
+
## Authentication and identity
Every request requires both:
@@ -78,30 +98,29 @@ All successful JSON responses include `wireVersion: 1`. The version is also fixe
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.
+The configured `maxQueuedJobs` is conservative: all queued/running work that consumes this machine's media resources counts against it. Outgoing proxy jobs are excluded because they consume another peer's capacity; counting them could make two idle peers report busy while waiting on each other.
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:
+Send a unique, stable `Idempotency-Key` header with the canonical instrumental request rendered by the consumer:
```json
{
"engine": "minimax-music3",
"modelId": "minimax-music3",
- "prompt": "A fictional cinematic synth theme",
- "lyrics": "[instrumental]",
+ "prompt": "Instrumental cinematic music with a dreamy mood, slow tempo, medium energy, featuring strings and synthesizer. No vocals or spoken words.",
"durationSec": 60,
"durationMode": "manual"
}
```
-Unknown fields are rejected. The contract accepts no source URL, filesystem path, shell argument, provider credential, or arbitrary proxy target.
+Unknown fields, free-form prompts, and non-empty lyrics are rejected. The contract accepts no source URL, filesystem path, shell argument, provider credential, or arbitrary proxy target. Keeping the wire shape as prompt text lets an older wire-v1 provider accept a newer consumer, while the canonical grammar lets a newer provider fail closed on arbitrary text from an older consumer.
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.
+The provider persists accepted work in the existing machine-local `data/media-jobs.json` queue. No commission, CoS, schedule, taste, Digital Twin record, free-form prompt, or lyrics are copied to the provider. Its queue contains only the canonical instrumental prompt derived from fixed musical descriptors.
### Download and verify a result
@@ -109,6 +128,14 @@ A completed job projection includes `result.sha256`, `result.sizeBytes`, `result
Provider filesystem paths and original filenames never cross the API boundary.
+### Consumer reconciliation
+
+Remote audio jobs use a dedicated non-GPU lane in the consumer's durable media queue. The local job UUID is also the stable provider `Idempotency-Key`. If the consumer restarts while the job is running, it requeues that same local record, replays the submission to recover the provider job id, and resumes status/progress polling. Temporary peer and provider outages remain queued rather than creating duplicate work.
+
+Cancellation intent is persisted before the consumer contacts the provider. After a restart it is replayed against the recovered provider job instead of resurrecting the render. A provider restart is handled by its own durable media queue; the consumer continues polling the owner-scoped wire job.
+
+On completion, the consumer ignores the advisory download URL and derives the fixed owner-scoped v1 result endpoint from the validated provider job id. It streams into a local partial file, verifies `Content-Length`, MIME type, both advertised digests, actual byte count, and SHA-256, then atomically promotes the WAV into the local Music library. Only that verified local filename is handed to the normal Music Studio completion hook.
+
## Current boundary
-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.
+Wire v1 currently provides instrumental audio only, and remote selection is exposed through the generation API rather than a Music-page peer picker. Still remaining from #4348 are that Music UI, a privacy-preserving design for remote lyrical conditioning, multi-provider fairness/failover, remote image/video jobs and input-asset transfer, Creative Commission routing/UX, and aggregate provider health on System Health.
diff --git a/server/lib/federatedMediaWire.js b/server/lib/federatedMediaWire.js
index 2074f2aad0..e3523418be 100644
--- a/server/lib/federatedMediaWire.js
+++ b/server/lib/federatedMediaWire.js
@@ -4,6 +4,70 @@ 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;
+const FEDERATED_AUDIO_STYLES = [
+ 'ambient', 'cinematic', 'classical', 'electronic', 'folk', 'hip-hop',
+ 'jazz', 'metal', 'orchestral', 'pop', 'rock', 'synthwave',
+];
+const FEDERATED_AUDIO_MOODS = [
+ 'bright', 'calm', 'dark', 'dreamy', 'energetic', 'hopeful',
+ 'melancholic', 'mysterious', 'playful', 'tense', 'triumphant', 'warm',
+];
+const FEDERATED_AUDIO_INSTRUMENTS = [
+ 'acoustic-guitar', 'bass', 'brass', 'cello', 'drums', 'electric-guitar',
+ 'flute', 'piano', 'strings', 'synthesizer', 'violin', 'woodwinds',
+];
+
+// Free-form text can contain PII and therefore cannot cross the federation
+// boundary. Consumers select only these fixed musical descriptors; the remote
+// adapter renders the provider prompt locally from this validated profile.
+export const federatedMediaAudioProfileSchema = z.object({
+ style: z.enum(FEDERATED_AUDIO_STYLES),
+ mood: z.enum(FEDERATED_AUDIO_MOODS),
+ tempo: z.enum(['slow', 'moderate', 'fast']).default('moderate'),
+ energy: z.enum(['low', 'medium', 'high']).default('medium'),
+ instruments: z.array(z.enum(FEDERATED_AUDIO_INSTRUMENTS)).max(6).default([])
+ .refine((items) => new Set(items).size === items.length, {
+ message: 'instruments must not contain duplicates',
+ }),
+}).strict();
+
+const words = (value) => value.replaceAll('-', ' ');
+const styleByWords = new Map(FEDERATED_AUDIO_STYLES.map((value) => [words(value), value]));
+const instrumentByWords = new Map(FEDERATED_AUDIO_INSTRUMENTS.map((value) => [words(value), value]));
+const AUDIO_PROMPT_RE = /^Instrumental ([a-z ]+) music with a ([a-z]+) mood, (slow|moderate|fast) tempo, (low|medium|high) energy(?:, featuring ([a-z ]+(?: and [a-z ]+){0,5}))?\. No vocals or spoken words\.$/;
+
+export function renderFederatedMediaAudioPrompt(profile) {
+ const parsed = federatedMediaAudioProfileSchema.safeParse(profile);
+ if (!parsed.success) return null;
+ const { style, mood, tempo, energy, instruments } = parsed.data;
+ const instrumentation = instruments.length > 0
+ ? `, featuring ${instruments.map(words).join(' and ')}`
+ : '';
+ return `Instrumental ${words(style)} music with a ${mood} mood, ${tempo} tempo, ${energy} energy${instrumentation}. No vocals or spoken words.`;
+}
+
+// Provider-side validation receives only the rendered text (not the local
+// profile) so older wire-v1 providers can still accept newer consumers. Parse
+// the canonical grammar back into fixed tokens and require an exact round trip;
+// arbitrary prose, names, lyrics, and redaction-sensitive fields fail closed.
+export function isFederatedMediaAudioPrompt(value) {
+ if (typeof value !== 'string') return false;
+ const match = AUDIO_PROMPT_RE.exec(value);
+ if (!match) return false;
+ const style = styleByWords.get(match[1]);
+ const instruments = match[5]
+ ? match[5].split(' and ').map((item) => instrumentByWords.get(item))
+ : [];
+ if (!style || instruments.some((item) => !item)) return false;
+ return renderFederatedMediaAudioPrompt({
+ style,
+ mood: match[2],
+ tempo: match[3],
+ energy: match[4],
+ instruments,
+ }) === value;
+}
+
// 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.
@@ -51,6 +115,39 @@ export const federatedMediaProviderStatusSchema = z.object({
capabilities: z.array(federatedMediaCapabilitySchema).max(300),
});
+const federatedMediaResultSchema = z.object({
+ available: z.literal(true),
+ mimeType: z.literal('audio/wav'),
+ sizeBytes: z.number().int().positive().max(4_294_967_296),
+ sha256: z.string().regex(/^[a-f0-9]{64}$/),
+ downloadUrl: z.string().trim().min(1).max(500),
+ engine: z.string().trim().min(1).max(80).nullable(),
+ modelId: z.string().trim().min(1).max(256).nullable(),
+ durationSec: z.number().finite().positive().max(3600).nullable(),
+});
+
+// Consumer-side job reconciliation validates every provider response against
+// this projection before acting on status, progress, or result metadata. The
+// result URL is still advisory: consumers derive the fixed v1 result endpoint
+// from the validated job id rather than following provider-supplied URLs.
+export const federatedMediaProviderJobSchema = z.object({
+ wireVersion: z.literal(FEDERATED_MEDIA_WIRE_VERSION),
+ id: z.string().uuid(),
+ kind: mediaKindSchema,
+ status: z.enum(['queued', 'running', 'completed', 'failed', 'canceled']),
+ queuedAt: z.string().datetime(),
+ startedAt: z.string().datetime().nullable(),
+ completedAt: z.string().datetime().nullable(),
+ position: z.number().int().positive().nullable(),
+ progress: z.number().finite().min(0).max(1).nullable(),
+ etaMs: z.number().finite().nonnegative().nullable(),
+ failure: z.object({
+ code: z.string().trim().min(1).max(120),
+ message: z.string().trim().min(1).max(500),
+ }).optional(),
+ result: federatedMediaResultSchema.optional(),
+});
+
/**
* Check a validated provider snapshot against the consumer's clock.
* A timestamp too far in the future is unknown rather than fresh: accepting it
diff --git a/server/lib/federatedMediaWire.test.js b/server/lib/federatedMediaWire.test.js
new file mode 100644
index 0000000000..9857f63d9f
--- /dev/null
+++ b/server/lib/federatedMediaWire.test.js
@@ -0,0 +1,68 @@
+import { describe, expect, it } from 'vitest';
+import {
+ federatedMediaAudioProfileSchema,
+ federatedMediaProviderJobSchema,
+ isFederatedMediaAudioPrompt,
+ renderFederatedMediaAudioPrompt,
+} from './federatedMediaWire.js';
+
+const job = (overrides = {}) => ({
+ wireVersion: 1,
+ id: '00000000-0000-4000-8000-000000000001',
+ kind: 'audio',
+ status: 'queued',
+ queuedAt: '2026-08-17T12:00:00.000Z',
+ startedAt: null,
+ completedAt: null,
+ position: 1,
+ progress: null,
+ etaMs: null,
+ ...overrides,
+});
+
+describe('federated media provider job wire projection', () => {
+ it('strips unknown provider fields before consumer reconciliation', () => {
+ const parsed = federatedMediaProviderJobSchema.parse(job({ privateFutureField: 'do-not-relay' }));
+ expect(parsed.privateFutureField).toBeUndefined();
+ });
+
+ it('rejects invalid integrity metadata and future media kinds', () => {
+ expect(federatedMediaProviderJobSchema.safeParse(job({
+ status: 'completed',
+ completedAt: '2026-08-17T12:01:00.000Z',
+ result: {
+ available: true,
+ mimeType: 'audio/wav',
+ sizeBytes: 10,
+ sha256: 'not-a-hash',
+ downloadUrl: '/result',
+ engine: 'example-engine',
+ modelId: 'example/model',
+ durationSec: 30,
+ },
+ })).success).toBe(false);
+ expect(federatedMediaProviderJobSchema.safeParse(job({ kind: 'video' })).success).toBe(false);
+ });
+});
+
+describe('federated media privacy-safe audio profiles', () => {
+ it('renders provider prompts only from fixed musical vocabulary', () => {
+ const profile = {
+ style: 'cinematic',
+ mood: 'dreamy',
+ tempo: 'slow',
+ energy: 'medium',
+ instruments: ['strings', 'synthesizer'],
+ };
+
+ const prompt = renderFederatedMediaAudioPrompt(profile);
+ expect(prompt).toBe('Instrumental cinematic music with a dreamy mood, slow tempo, medium energy, featuring strings and synthesizer. No vocals or spoken words.');
+ expect(isFederatedMediaAudioPrompt(prompt)).toBe(true);
+ expect(isFederatedMediaAudioPrompt('Cinematic music for [email protected]')).toBe(false);
+ expect(federatedMediaAudioProfileSchema.safeParse({
+ ...profile,
+ subject: '[email protected]',
+ }).success).toBe(false);
+ expect(renderFederatedMediaAudioPrompt({ ...profile, mood: 'a named person' })).toBeNull();
+ });
+});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index b57888aee1..d1d1717916 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -13,6 +13,7 @@ import {
import { PR_COMPLETION_VALUES } from './prDisposition.js';
import { EFFORT_LEVELS } from './providerModels.js';
import { MAX_TIMEOUT as AI_RUN_TIMEOUT_MAX_MS, MIN_TIMEOUT as AI_RUN_TIMEOUT_MIN_MS } from './aiToolkit/constants.js';
+import { isFederatedMediaAudioPrompt } from './federatedMediaWire.js';
// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total
// pixels. Mirror the ceiling for every image-gen route. Local mflux can
@@ -728,17 +729,37 @@ export const federationSettingsSchema = z.object({
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({
+export const federatedMediaJobRoutingSchema = 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();
+// Provider submissions intentionally accept model selection plus only the
+// canonical fixed-vocabulary instrumental prompt. Free-form prompt/lyrics can
+// contain PII and must remain on the consumer; URLs, paths, commands, provider
+// credentials, and unknown fields are excluded by the strict object as before.
+export const federatedMediaJobSubmissionSchema = federatedMediaJobRoutingSchema.extend({
+ prompt: z.string().trim().min(1).max(8000),
+ lyrics: z.string().max(50_000).optional(),
+}).strict().superRefine((value, ctx) => {
+ if (!isFederatedMediaAudioPrompt(value.prompt)) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['prompt'],
+ message: 'prompt must be rendered from a privacy-safe federated audio profile',
+ });
+ }
+ if (value.lyrics) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['lyrics'],
+ message: 'federated audio submissions are instrumental only',
+ });
+ }
+});
+
export const federatedMediaIdempotencyKeySchema = z.string().trim().min(1).max(200)
.regex(/^[A-Za-z0-9._:-]+$/, 'Idempotency-Key contains unsupported characters');
diff --git a/server/routes/federatedMedia.test.js b/server/routes/federatedMedia.test.js
index 87fa81acd0..5041a5d75b 100644
--- a/server/routes/federatedMedia.test.js
+++ b/server/routes/federatedMedia.test.js
@@ -61,11 +61,12 @@ function buildApp() {
}
const jobId = '00000000-0000-4000-8000-000000000001';
+const safePrompt = 'Instrumental synthwave music with a dreamy mood, moderate tempo, medium energy. No vocals or spoken words.';
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',
+ engine: 'minimax-music3', modelId: 'minimax-music3', prompt: safePrompt,
});
expect(response.status).toBe(400);
expect(response.body.code).toBe('VALIDATION_ERROR');
@@ -73,7 +74,7 @@ describe('federated media routes', () => {
});
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 body = { engine: 'minimax-music3', modelId: 'minimax-music3', prompt: safePrompt };
const created = await request(buildApp()).post('/api/federation/media/v1/jobs')
.set('Idempotency-Key', 'commission-1').send(body);
expect(created.status).toBe(202);
@@ -90,13 +91,28 @@ describe('federated media routes', () => {
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',
+ engine: 'minimax-music3', modelId: 'minimax-music3', prompt: safePrompt,
sourcePath: '/tmp/private.wav',
});
expect(response.status).toBe(400);
expect(provider.submit).not.toHaveBeenCalled();
});
+ it('rejects free-form prompts and lyrics at the provider boundary', async () => {
+ const freeform = await request(buildApp()).post('/api/federation/media/v1/jobs')
+ .set('Idempotency-Key', 'commission-private').send({
+ engine: 'minimax-music3', modelId: 'minimax-music3', prompt: 'Write about [email protected]',
+ });
+ const lyrics = await request(buildApp()).post('/api/federation/media/v1/jobs')
+ .set('Idempotency-Key', 'commission-private-lyrics').send({
+ engine: 'minimax-music3', modelId: 'minimax-music3', prompt: safePrompt, lyrics: 'Private words',
+ });
+
+ expect(freeform.status).toBe(400);
+ expect(lyrics.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);
diff --git a/server/routes/music.js b/server/routes/music.js
index 8a4a4ac12c..3c6caf0ecd 100644
--- a/server/routes/music.js
+++ b/server/routes/music.js
@@ -40,7 +40,13 @@ import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';
import { createInstallLogger } from '../lib/installLogger.js';
import { inspectModelCache } from '../lib/hfCache.js';
import { getCudaCapability } from '../lib/cudaCapability.js';
+import {
+ FEDERATED_MEDIA_WIRE_VERSION,
+ federatedMediaAudioProfileSchema,
+} from '../lib/federatedMediaWire.js';
import { enqueueJob, listJobs } from '../services/mediaJobQueue/index.js';
+import { resolveFederatedMediaProvider } from '../services/federatedMediaConsumer.js';
+import { getPeers } from '../services/instances.js';
import * as tracks from '../services/tracks/index.js';
const router = Router();
@@ -339,8 +345,13 @@ const generateSchema = z.object({
// A render-level override: ignore even supplied lyrics without clearing the
// track's saved lyric field when the completed audio is attached.
instrumentalOnly: z.boolean().optional().default(false),
- engine: z.string().trim().max(60).optional(),
- modelId: z.string().trim().max(120).optional(),
+ engine: z.string().trim().min(1).max(80).optional(),
+ modelId: z.string().trim().min(1).max(256).optional(),
+ // The peer record id is machine-local routing intent. It never crosses the
+ // provider boundary. Free-form text stays local too: remote execution uses a
+ // fixed-vocabulary instrumental profile rendered by the worker.
+ mediaProviderPeerId: z.string().uuid().optional(),
+ remoteMusicProfile: federatedMediaAudioProfileSchema.optional(),
durationSec: z.number().positive().max(600).optional(),
durationMode: z.enum(['auto', 'manual']).optional(),
// Attach the result to an existing track (else a new one is created). The
@@ -350,45 +361,137 @@ const generateSchema = z.object({
artistId: z.string().trim().max(80).optional().default(''),
artist: z.string().trim().max(120).optional().default(''),
albumId: z.string().trim().max(80).optional().default(''),
+}).superRefine((value, ctx) => {
+ if (!value.mediaProviderPeerId) {
+ if (value.remoteMusicProfile) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['remoteMusicProfile'],
+ message: 'remoteMusicProfile requires a remote media provider',
+ });
+ }
+ return;
+ }
+ if (!value.engine) {
+ ctx.addIssue({ code: 'custom', path: ['engine'], message: 'engine is required for a remote media provider' });
+ }
+ if (!value.modelId) {
+ ctx.addIssue({ code: 'custom', path: ['modelId'], message: 'modelId is required for a remote media provider' });
+ }
+ if (!value.remoteMusicProfile) {
+ ctx.addIssue({ code: 'custom', path: ['remoteMusicProfile'], message: 'remoteMusicProfile is required for a remote media provider' });
+ }
+ if (value.lyrics) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['lyrics'],
+ message: 'Remote media generation is instrumental only so personal lyrics stay machine-local',
+ });
+ }
});
const INSTRUMENTAL_ONLY_GUIDANCE = 'Instrumental only. Do not include sung, spoken, chanted, choir, or background vocals. Carry the lead melody with the described instruments or textures.';
router.post('/generate', asyncHandler(async (req, res) => {
const body = validateRequest(generateSchema, req.body ?? {});
- // Reject an unknown engine explicitly rather than letting getEngine() fall
- // back to the default — a typo/stale client (`acestep-v2`) would otherwise
- // burn a render producing the WRONG backend's output + metadata. An ABSENT
- // engine is allowed (uses the default).
- if (body.engine !== undefined && !ENGINES[body.engine]) {
- throw new ServerError(`Unknown audio engine: ${body.engine}`, { status: 400, code: 'PIPELINE_MUSIC_UNKNOWN_ENGINE' });
- }
- const engine = getEngine(body.engine);
- // Validate the target track BEFORE the (minutes-long) render so a stale/
- // deleted trackId fails fast instead of wasting a render + orphaning a WAV.
- let existing = null;
+ // Validate local destination and duplicate state before any peer probe. A
+ // stale track or duplicate request should not generate needless federation
+ // traffic, even though the probe itself does not start provider work.
if (body.trackId) {
- existing = await tracks.getTrack(body.trackId);
+ const existing = await tracks.getTrack(body.trackId);
if (!existing) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });
}
+ const liveJobs = listJobs({ kind: 'audio' }).filter((job) => job.status === 'queued' || job.status === 'running');
+ const duplicate = liveJobs.find((job) => {
+ const tag = job.params?.musicStudio;
+ return body.trackId ? tag?.trackId === body.trackId : tag && !tag.trackId;
+ });
+ if (duplicate) {
+ throw new ServerError('Music generation is already in progress', {
+ status: 409,
+ code: 'PIPELINE_MUSIC_BUSY',
+ context: { jobId: duplicate.id },
+ });
+ }
- // Resolve the requested model against the engine's merged list. An unknown
- // modelId (stale UI selection, removed model) must FAIL FAST — otherwise
- // `repo` stays undefined and generateMusic silently renders the engine default,
- // spending minutes producing audio from the wrong checkpoint. A user-installed
- // id resolves to its HF repo (passed to the sidecar); a shipped id leaves
- // `repo` undefined (generateMusic uses its own registry for shipped models).
+ let engine;
let repo;
- if (body.modelId) {
- const merged = await listEngineModels(engine.id);
- const picked = merged.find((m) => m.id === body.modelId);
- if (!picked) {
- throw new ServerError(`Unknown model for ${engine.name}: ${body.modelId}`, { status: 400, code: 'PIPELINE_MUSIC_UNKNOWN_MODEL' });
+ let remoteMedia;
+
+ if (body.mediaProviderPeerId) {
+ const peers = await getPeers();
+ const peer = peers.find((candidate) => candidate.id === body.mediaProviderPeerId);
+ if (!peer) {
+ throw new ServerError('Selected media provider peer was not found', {
+ status: 404,
+ code: 'MEDIA_PROVIDER_PEER_NOT_FOUND',
+ });
+ }
+ const resolved = await resolveFederatedMediaProvider(peer, {
+ kind: 'audio',
+ engine: body.engine,
+ modelId: body.modelId,
+ });
+ const capability = resolved.capability;
+ if (body.durationMode === 'auto' && !capability.autoDuration) {
+ throw new ServerError('Selected remote engine does not support automatic duration', {
+ status: 400,
+ code: 'MEDIA_PROVIDER_AUTO_DURATION_UNSUPPORTED',
+ });
+ }
+ if (body.durationSec !== undefined
+ && ((Number.isFinite(capability.minDurationSec) && body.durationSec < capability.minDurationSec)
+ || (Number.isFinite(capability.maxDurationSec) && body.durationSec > capability.maxDurationSec))) {
+ throw new ServerError('Requested duration is outside the remote engine limits', {
+ status: 400,
+ code: 'MEDIA_PROVIDER_DURATION_UNSUPPORTED',
+ context: {
+ minDurationSec: capability.minDurationSec,
+ maxDurationSec: capability.maxDurationSec,
+ },
+ });
+ }
+ engine = {
+ id: capability.engine,
+ name: capability.engineName,
+ lyrics: capability.lyrics,
+ };
+ remoteMedia = {
+ wireVersion: FEDERATED_MEDIA_WIRE_VERSION,
+ peerId: peer.id,
+ reconcile: false,
+ cancelRequested: false,
+ profile: body.remoteMusicProfile,
+ };
+ } else {
+ // Reject an unknown engine explicitly rather than letting getEngine() fall
+ // back to the default — a typo/stale client would otherwise render with the
+ // wrong local backend. An absent engine still selects the local default.
+ if (body.engine !== undefined && !ENGINES[body.engine]) {
+ throw new ServerError(`Unknown audio engine: ${body.engine}`, { status: 400, code: 'PIPELINE_MUSIC_UNKNOWN_ENGINE' });
+ }
+ engine = getEngine(body.engine);
+
+ // Resolve a local user-installed model to its HF repo. Remote models are
+ // validated against the peer's exact allowlist and never interpreted as a
+ // path or local repository on this machine.
+ if (body.modelId) {
+ const merged = await listEngineModels(engine.id);
+ const picked = merged.find((m) => m.id === body.modelId);
+ if (!picked) {
+ throw new ServerError(`Unknown model for ${engine.name}: ${body.modelId}`, { status: 400, code: 'PIPELINE_MUSIC_UNKNOWN_MODEL' });
+ }
+ if (picked.userAdded) repo = picked.repo || picked.id;
}
- if (picked.userAdded) repo = picked.repo || picked.id;
}
+ // The lyrics that actually CONDITION this render: what the caller sent for a
+ // lyric-aware engine ('' = render without lyrics), nothing for a non-lyric
+ // engine. The same value drives the generation call AND the render snapshot,
+ // so a render card can never claim conditioning text the audio wasn't built
+ // from (an absent-lyrics lyric render is genuinely un-conditioned, not "the
+ // track's old words").
// Make the render-level override explicit in BOTH conditioning inputs. Merely
// dropping lyrics is not enough when the authored caption itself mentions a
// vocalist. Keep it idempotent so remixing an instrumental take does not append
@@ -396,38 +499,32 @@ router.post('/generate', asyncHandler(async (req, res) => {
const usedPrompt = body.instrumentalOnly && !body.prompt.includes(INSTRUMENTAL_ONLY_GUIDANCE)
? `${body.prompt}\n\n${INSTRUMENTAL_ONLY_GUIDANCE}`
: body.prompt;
-
- // The lyrics that actually CONDITION this render: what the caller sent for a
- // lyric-aware engine ('' = render without lyrics), nothing for a non-lyric
- // engine. The same value drives the generation call AND the render snapshot,
- // so a render card can never claim conditioning text the audio wasn't built
- // from (an absent-lyrics lyric render is genuinely un-conditioned, not "the
- // track's old words").
const usedLyrics = engine.lyrics && !body.instrumentalOnly ? (body.lyrics ?? '') : '';
-
- const liveJobs = listJobs({ kind: 'audio' }).filter((job) => job.status === 'queued' || job.status === 'running');
- const duplicate = liveJobs.find((job) => {
- const tag = job.params?.musicStudio;
- return body.trackId ? tag?.trackId === body.trackId : tag && !tag.trackId;
- });
- if (duplicate) {
- throw new ServerError('Music generation is already in progress', {
- status: 409,
- code: 'PIPELINE_MUSIC_BUSY',
- context: { jobId: duplicate.id },
- });
+ if (remoteMedia) {
+ remoteMedia.request = {
+ engine: engine.id,
+ modelId: body.modelId,
+ ...(body.durationSec !== undefined ? { durationSec: body.durationSec } : {}),
+ ...(body.durationMode !== undefined ? { durationMode: body.durationMode } : {}),
+ };
}
const result = enqueueJob({
kind: 'audio',
params: {
- prompt: usedPrompt,
- lyrics: usedLyrics,
+ // Keep only the fixed-vocabulary profile and routing request under the
+ // versioned remote marker. An older PortOS that does not understand
+ // remoteMedia will route this audio job to the local adapter; the empty
+ // prompt makes that rollback fail closed before a duplicate local render.
+ // New consumers derive the safe provider prompt from the profile.
+ prompt: remoteMedia ? '' : usedPrompt,
+ lyrics: remoteMedia ? '' : usedLyrics,
engine: engine.id,
modelId: body.modelId,
repo,
durationSec: body.durationSec,
durationMode: body.durationMode,
+ ...(remoteMedia ? { remoteMedia } : {}),
musicStudio: {
trackId: body.trackId || null,
title: body.title || body.prompt.slice(0, 60),
diff --git a/server/routes/music.test.js b/server/routes/music.test.js
index 5fbecea453..4d871468d7 100644
--- a/server/routes/music.test.js
+++ b/server/routes/music.test.js
@@ -13,6 +13,7 @@ const gen = vi.hoisted(() => ({
unsupportedPlatform: null,
}));
const mediaQueue = vi.hoisted(() => ({ jobs: [], enqueue: vi.fn() }));
+const remoteProvider = vi.hoisted(() => ({ peers: [], resolve: vi.fn() }));
const cuda = vi.hoisted(() => ({ status: 'available', maxVramGb: 40 }));
vi.mock('../lib/cudaCapability.js', () => ({
getCudaCapability: vi.fn(async () => ({ status: cuda.status, gpus: [], maxVramGb: cuda.maxVramGb, error: null })),
@@ -77,6 +78,12 @@ vi.mock('../services/mediaJobQueue/index.js', () => ({
JOB_KINDS: ['video', 'image', 'training', 'audio'],
JOB_STATUSES: ['queued', 'running', 'completed', 'failed', 'canceled'],
}));
+vi.mock('../services/instances.js', () => ({
+ getPeers: vi.fn(async () => remoteProvider.peers),
+}));
+vi.mock('../services/federatedMediaConsumer.js', () => ({
+ resolveFederatedMediaProvider: (...args) => remoteProvider.resolve(...args),
+}));
// The install route shells out to scripts/setup-image-video.sh. Stand in a child
// that closes immediately so the SSE stream terminates instead of running a real
@@ -173,6 +180,8 @@ describe('music routes', () => {
app = makeApp();
mediaQueue.enqueue.mockReset().mockImplementation(() => ({ jobId: 'job-1', position: 1, status: 'queued' }));
mediaQueue.jobs = [];
+ remoteProvider.peers = [];
+ remoteProvider.resolve.mockReset();
models.list.mockReset();
// add/remove return promises by default so the route's `.catch()` chains
// don't throw on an undefined return (mockReset clears the impl).
@@ -548,6 +557,118 @@ describe('music routes', () => {
}));
});
+ it('POST /generate queues an explicitly selected remote model without resolving it locally', async () => {
+ const peer = { id: '00000000-0000-4000-8000-000000000001', enabled: true };
+ remoteProvider.peers = [peer];
+ remoteProvider.resolve.mockResolvedValueOnce({
+ peer,
+ capability: {
+ kind: 'audio',
+ engine: 'remote-audio',
+ engineName: 'Remote Audio',
+ modelId: 'example/model',
+ lyrics: true,
+ autoDuration: false,
+ minDurationSec: 10,
+ maxDurationSec: 120,
+ },
+ });
+
+ const r = await request(app).post('/api/music/generate').send({
+ prompt: 'private idea for [email protected]',
+ engine: 'remote-audio',
+ modelId: 'example/model',
+ durationSec: 30,
+ mediaProviderPeerId: peer.id,
+ remoteMusicProfile: {
+ style: 'cinematic',
+ mood: 'dreamy',
+ tempo: 'slow',
+ energy: 'medium',
+ instruments: ['strings', 'synthesizer'],
+ },
+ });
+
+ expect(r.status).toBe(202);
+ expect(remoteProvider.resolve).toHaveBeenCalledWith(peer, {
+ kind: 'audio', engine: 'remote-audio', modelId: 'example/model',
+ });
+ expect(models.list).not.toHaveBeenCalled();
+ expect(mediaQueue.enqueue).toHaveBeenCalledWith(expect.objectContaining({
+ kind: 'audio',
+ params: expect.objectContaining({
+ engine: 'remote-audio',
+ modelId: 'example/model',
+ prompt: '',
+ lyrics: '',
+ remoteMedia: {
+ wireVersion: 1,
+ peerId: peer.id,
+ reconcile: false,
+ cancelRequested: false,
+ profile: {
+ style: 'cinematic',
+ mood: 'dreamy',
+ tempo: 'slow',
+ energy: 'medium',
+ instruments: ['strings', 'synthesizer'],
+ },
+ request: {
+ engine: 'remote-audio',
+ modelId: 'example/model',
+ durationSec: 30,
+ },
+ },
+ musicStudio: expect.objectContaining({ lyricsEnabled: true }),
+ }),
+ }));
+ const remoteMarker = mediaQueue.enqueue.mock.calls[0][0].params.remoteMedia;
+ expect(JSON.stringify(remoteMarker)).not.toContain('[email protected]');
+ });
+
+ it('POST /generate fails before queueing when remote routing is incomplete or unavailable', async () => {
+ const peer = { id: '00000000-0000-4000-8000-000000000001', enabled: true };
+ remoteProvider.peers = [peer];
+
+ const incomplete = await request(app).post('/api/music/generate').send({
+ prompt: 'pulse', engine: 'remote-audio', mediaProviderPeerId: peer.id,
+ });
+ expect(incomplete.status).toBe(400);
+
+ remoteProvider.resolve.mockRejectedValueOnce(new ServerError('Provider busy', {
+ status: 429,
+ code: 'MEDIA_PROVIDER_BUSY',
+ }));
+ const busy = await request(app).post('/api/music/generate').send({
+ prompt: 'pulse',
+ engine: 'remote-audio',
+ modelId: 'example/model',
+ mediaProviderPeerId: peer.id,
+ remoteMusicProfile: { style: 'ambient', mood: 'calm' },
+ });
+ expect(busy.status).toBe(429);
+ expect(busy.body.code).toBe('MEDIA_PROVIDER_BUSY');
+ expect(mediaQueue.enqueue).not.toHaveBeenCalled();
+ });
+
+ it('POST /generate rejects free-form lyrics before probing a remote provider', async () => {
+ const peer = { id: '00000000-0000-4000-8000-000000000001', enabled: true };
+ remoteProvider.peers = [peer];
+
+ const r = await request(app).post('/api/music/generate').send({
+ prompt: 'private concept',
+ lyrics: 'Call [email protected]',
+ engine: 'remote-audio',
+ modelId: 'example/model',
+ mediaProviderPeerId: peer.id,
+ remoteMusicProfile: { style: 'ambient', mood: 'calm' },
+ });
+
+ expect(r.status).toBe(400);
+ expect(remoteProvider.resolve).not.toHaveBeenCalled();
+ expect(mediaQueue.enqueue).not.toHaveBeenCalled();
+ });
+
it('POST /generate forwards MiniMax auto duration mode to the queue', async () => {
const r = await request(app).post('/api/music/generate').send({
prompt: 'warm folk',
diff --git a/server/services/audioGen/events.js b/server/services/audioGen/events.js
index 0c0c28c4c1..601ec206d6 100644
--- a/server/services/audioGen/events.js
+++ b/server/services/audioGen/events.js
@@ -3,7 +3,7 @@ import { EventEmitter } from 'events';
// Mirrors imageGenEvents/videoGenEvents/trainingEvents — the mediaJobQueue
// emitter contract every gen module rides (`progress`/`activity`/`completed`/
// `failed`, keyed by `generationId`). See server/services/imageGenEvents.js for
-// the maxListeners rationale; audio jobs are lower-volume (no Codex-style
-// parallel lane) but the cap is cheap insurance against the same warning.
+// the maxListeners rationale. Federated audio jobs can share a bounded parallel
+// lane, so retain the same generous listener cap as the other media adapters.
export const audioGenEvents = new EventEmitter();
audioGenEvents.setMaxListeners(200);
diff --git a/server/services/audioGen/remote.js b/server/services/audioGen/remote.js
new file mode 100644
index 0000000000..ff91d2f146
--- /dev/null
+++ b/server/services/audioGen/remote.js
@@ -0,0 +1,490 @@
+/**
+ * Durable consumer-side adapter for federated audio jobs.
+ *
+ * The local media-job UUID is the provider Idempotency-Key. A worker restart
+ * therefore replays the same submission, recovers the provider job, and keeps
+ * polling instead of creating duplicate paid/GPU work. Provider URLs are never
+ * accepted from the wire: every request derives the fixed v1 endpoint from the
+ * locally configured peer.
+ */
+
+import { createWriteStream } from 'node:fs';
+import { mkdir, rename, stat, unlink } from 'node:fs/promises';
+import { createHash } from 'node:crypto';
+import { join } from 'node:path';
+import { Readable, Transform } from 'node:stream';
+import { pipeline } from 'node:stream/promises';
+import { z } from 'zod';
+import { PATHS, sha256File } from '../../lib/fileUtils.js';
+import {
+ FEDERATED_MEDIA_WIRE_VERSION,
+ federatedMediaAudioProfileSchema,
+ federatedMediaProviderJobSchema,
+ renderFederatedMediaAudioPrompt,
+} from '../../lib/federatedMediaWire.js';
+import { peerFetch } from '../../lib/peerHttpClient.js';
+import { peerBaseUrl } from '../../lib/peerUrl.js';
+import { readResponseJson } from '../../lib/readResponseJson.js';
+import { federatedMediaJobRoutingSchema } from '../../lib/validation.js';
+import { resolveFederatedMediaProvider } from '../federatedMediaConsumer.js';
+import { getPeers } from '../instances.js';
+import { audioGenEvents } from './events.js';
+
+const remoteMediaMarkerSchema = z.object({
+ wireVersion: z.literal(FEDERATED_MEDIA_WIRE_VERSION),
+ peerId: z.string().uuid(),
+ reconcile: z.boolean().optional(),
+ cancelRequested: z.boolean().optional(),
+ profile: federatedMediaAudioProfileSchema,
+ // Free-form prompt/lyrics are deliberately absent from persisted routing
+ // state. The adapter renders a fixed-vocabulary instrumental prompt from the
+ // profile immediately before submission, so hand-edited queue state cannot
+ // smuggle personal text onto the federation wire.
+ request: federatedMediaJobRoutingSchema,
+}).passthrough();
+
+const RETRYABLE_HTTP_STATUSES = new Set([408, 425, 429]);
+const PERMANENT_SELECTION_CODES = new Set([
+ 'MEDIA_PROVIDER_PEER_DISABLED',
+ 'MEDIA_PROVIDER_NOT_CONFIGURED',
+ 'MEDIA_PROVIDER_SELECTION_INVALID',
+ 'MEDIA_PROVIDER_MODEL_NOT_ALLOWED',
+]);
+const NON_RETRYABLE_FILE_CODES = new Set(['EACCES', 'ENOSPC', 'EPERM', 'EROFS']);
+const RETRYABLE_TRANSPORT_CODES = new Set([
+ 'ECONNREFUSED',
+ 'ECONNRESET',
+ 'EHOSTUNREACH',
+ 'ENETUNREACH',
+ 'ETIMEDOUT',
+ 'UND_ERR_CONNECT_TIMEOUT',
+ 'UND_ERR_SOCKET',
+]);
+
+let pollDelayMs = 1_000;
+let retryDelayMs = 2_000;
+let requestTimeoutMs = 30_000;
+const activeJobs = new Map();
+
+const remoteError = (message, details = {}) => Object.assign(new Error(message), details);
+const canceledError = () => remoteError('Remote audio generation canceled', { canceled: true });
+const isRetryableStatus = (status) => RETRYABLE_HTTP_STATUSES.has(status) || status >= 500;
+const isRetryableTransportError = (error) =>
+ error?.retryable === true
+ || error?.name === 'AbortError'
+ || error?.name === 'TimeoutError'
+ || error?.name === 'TypeError'
+ || RETRYABLE_TRANSPORT_CODES.has(error?.code);
+
+function emitActivity(jobId) {
+ audioGenEvents.emit('activity', { generationId: jobId });
+}
+
+function emitStatus(jobId, message) {
+ emitActivity(jobId);
+ audioGenEvents.emit('status', { generationId: jobId, message });
+}
+
+async function waitForRetry(state, delayMs) {
+ emitActivity(state.jobId);
+ if (delayMs <= 0) return;
+ await new Promise((resolve) => {
+ let settled = false;
+ const finish = () => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ if (state.wake === finish) state.wake = null;
+ resolve();
+ };
+ const timer = setTimeout(finish, delayMs);
+ timer.unref?.();
+ state.wake = finish;
+ });
+}
+
+async function withRequest(state, fn, { respectCancel = true, timeoutMs = requestTimeoutMs } = {}) {
+ const controller = new AbortController();
+ const timer = timeoutMs === null ? null : setTimeout(() => controller.abort(), timeoutMs);
+ timer?.unref?.();
+ state.requestController = controller;
+ if (respectCancel && state.cancelRequested) controller.abort();
+ try {
+ return await fn(controller.signal);
+ } finally {
+ if (timer) clearTimeout(timer);
+ if (state.requestController === controller) state.requestController = null;
+ }
+}
+
+async function findPeer(peerId) {
+ const peers = await getPeers();
+ const peer = peers.find((candidate) => candidate.id === peerId);
+ if (!peer || peer.enabled === false) {
+ throw remoteError('Selected media provider peer is no longer available', {
+ code: 'MEDIA_PROVIDER_PEER_UNAVAILABLE',
+ });
+ }
+ return peer;
+}
+
+async function requestJson(state, path, options = {}, requestOptions = {}) {
+ const peer = await findPeer(state.peerId);
+ const { response, body } = await withRequest(
+ state,
+ async (signal) => {
+ const response = await peerFetch(`${peerBaseUrl(peer)}${path}`, {
+ redirect: 'error',
+ ...options,
+ signal,
+ }, peer);
+ const body = await readResponseJson(response, { fallback: null, emptyValue: null });
+ return { response, body };
+ },
+ requestOptions,
+ );
+ if (!response.ok) {
+ const code = typeof body?.code === 'string' ? body.code : `HTTP_${response.status}`;
+ throw remoteError(`Remote media provider rejected the request (${code})`, {
+ code,
+ status: response.status,
+ retryable: isRetryableStatus(response.status),
+ });
+ }
+ return body;
+}
+
+function parseProviderJob(body, expectedId) {
+ const parsed = federatedMediaProviderJobSchema.safeParse(body);
+ if (!parsed.success || (expectedId && parsed.data.id !== expectedId)) {
+ throw remoteError('Remote media provider returned an invalid wire-v1 job projection', {
+ code: 'MEDIA_PROVIDER_INVALID_JOB_RESPONSE',
+ });
+ }
+ return parsed.data;
+}
+
+async function preflight(state, selection) {
+ while (true) {
+ if (state.cancelRequested) throw canceledError();
+ const peer = await findPeer(state.peerId);
+ try {
+ await withRequest(
+ state,
+ (signal) => resolveFederatedMediaProvider(peer, selection, { signal }),
+ );
+ return;
+ } catch (error) {
+ if (state.cancelRequested) throw canceledError();
+ if (PERMANENT_SELECTION_CODES.has(error?.code)) throw error;
+ emitStatus(state.jobId, 'Waiting for remote provider readiness');
+ await waitForRetry(state, retryDelayMs);
+ }
+ }
+}
+
+async function submitOrRecover(state, request) {
+ const path = '/api/federation/media/v1/jobs';
+ while (true) {
+ // Once an attempt begins, an abort is ambiguous: the provider may have
+ // accepted the body before the connection broke. Keep replaying with the
+ // same key (even after local cancellation) until its job id is recovered.
+ state.submissionMayExist = true;
+ try {
+ const body = await requestJson(state, path, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Idempotency-Key': state.jobId,
+ },
+ body: JSON.stringify(request),
+ }, { respectCancel: !state.cancelRequested });
+ return parseProviderJob(body);
+ } catch (error) {
+ if (!isRetryableTransportError(error)) throw error;
+ emitStatus(state.jobId, state.cancelRequested
+ ? 'Recovering remote job before cancellation'
+ : 'Waiting to submit to the remote provider');
+ // Cancellation must still recover the possibly-accepted submission before
+ // it can target the provider job. Keep the normal backoff while doing so:
+ // a disconnected peer must not turn a durable cancel into a hot loop.
+ await waitForRetry(state, retryDelayMs);
+ }
+ }
+}
+
+async function sendRemoteCancel(state, remoteJobId) {
+ while (true) {
+ try {
+ const body = await requestJson(
+ state,
+ `/api/federation/media/v1/jobs/${remoteJobId}/cancel`,
+ { method: 'POST' },
+ { respectCancel: false },
+ );
+ state.cancelSent = true;
+ return parseProviderJob(body, remoteJobId);
+ } catch (error) {
+ // A terminal provider job returns 409. The local user still asked to
+ // cancel, so do not import a result that won the race.
+ if (error?.status === 409) throw canceledError();
+ if (!isRetryableTransportError(error)) throw error;
+ emitStatus(state.jobId, 'Waiting to cancel the remote job');
+ await waitForRetry(state, retryDelayMs);
+ }
+ }
+}
+
+function emitProviderProgress(state, job) {
+ emitActivity(state.jobId);
+ if (typeof job.progress === 'number') {
+ audioGenEvents.emit('progress', {
+ generationId: state.jobId,
+ progress: job.progress,
+ message: 'Rendering on remote provider',
+ ...(typeof job.etaMs === 'number' ? { etaMs: job.etaMs } : {}),
+ });
+ return;
+ }
+ const position = typeof job.position === 'number' ? ` (position ${job.position})` : '';
+ emitStatus(state.jobId, job.status === 'queued'
+ ? `Queued on remote provider${position}`
+ : 'Rendering on remote provider');
+}
+
+async function pollProviderJob(state, initial) {
+ let current = initial;
+ while (true) {
+ if (state.cancelRequested && !state.cancelSent) {
+ current = await sendRemoteCancel(state, current.id);
+ }
+ if (state.cancelRequested && ['completed', 'failed', 'canceled'].includes(current.status)) {
+ throw canceledError();
+ }
+ if (current.status === 'completed') {
+ if (!current.result) {
+ throw remoteError('Remote provider completed without result metadata', {
+ code: 'MEDIA_PROVIDER_RESULT_MISSING',
+ });
+ }
+ return current;
+ }
+ if (current.status === 'failed') {
+ throw remoteError(`Remote provider job failed (${current.failure?.code || 'MEDIA_PROVIDER_JOB_FAILED'})`, {
+ code: current.failure?.code || 'MEDIA_PROVIDER_JOB_FAILED',
+ });
+ }
+ if (current.status === 'canceled') {
+ throw remoteError('Remote provider canceled the job', { code: 'MEDIA_PROVIDER_JOB_CANCELED' });
+ }
+
+ emitProviderProgress(state, current);
+ await waitForRetry(state, pollDelayMs);
+ try {
+ const body = await requestJson(
+ state,
+ `/api/federation/media/v1/jobs/${current.id}`,
+ {},
+ { respectCancel: true },
+ );
+ current = parseProviderJob(body, current.id);
+ } catch (error) {
+ if (state.cancelRequested && error?.name === 'AbortError') continue;
+ if (!isRetryableTransportError(error)) throw error;
+ emitStatus(state.jobId, 'Remote provider temporarily unavailable');
+ await waitForRetry(state, retryDelayMs);
+ }
+ }
+}
+
+async function existingResultMatches(path, metadata) {
+ const info = await stat(path).catch(() => null);
+ if (!info?.isFile() || info.size !== metadata.sizeBytes) return false;
+ const digest = await sha256File(path).catch(() => null);
+ return digest === metadata.sha256;
+}
+
+function responseStream(body) {
+ if (!body) throw remoteError('Remote provider returned an empty result body');
+ return typeof body.getReader === 'function' ? Readable.fromWeb(body) : Readable.from(body);
+}
+
+async function downloadOnce(state, remoteJob) {
+ const metadata = remoteJob.result;
+ const filename = `music-gen-${state.jobId}.wav`;
+ const finalPath = join(PATHS.music, filename);
+ const partialPath = join(PATHS.music, `.${filename}.partial`);
+ await mkdir(PATHS.music, { recursive: true });
+ if (await existingResultMatches(finalPath, metadata)) return filename;
+ await unlink(partialPath).catch(() => {});
+
+ const peer = await findPeer(state.peerId);
+ // Keep the controller live for the body stream so cancel()/the queue
+ // watchdog can interrupt a stalled transfer. There is intentionally no
+ // fixed wall-clock timeout: large WAVs over a slow Tailnet are valid work,
+ // and chunk activity keeps the queue's idle watchdog fresh.
+ return withRequest(state, async (signal) => {
+ const response = await peerFetch(
+ `${peerBaseUrl(peer)}/api/federation/media/v1/jobs/${remoteJob.id}/result`,
+ { redirect: 'error', signal },
+ peer,
+ );
+ if (!response.ok) {
+ throw remoteError(`Remote result download failed (HTTP_${response.status})`, {
+ status: response.status,
+ retryable: isRetryableStatus(response.status),
+ });
+ }
+
+ const contentLength = Number(response.headers.get('content-length'));
+ const contentType = response.headers.get('content-type')?.split(';', 1)[0]?.trim();
+ const advertisedHash = response.headers.get('x-content-sha256')?.toLowerCase();
+ if (!Number.isInteger(contentLength) || contentLength !== metadata.sizeBytes
+ || contentType !== metadata.mimeType || advertisedHash !== metadata.sha256) {
+ throw remoteError('Remote result headers did not match the validated metadata', {
+ code: 'MEDIA_PROVIDER_RESULT_HEADERS_INVALID',
+ });
+ }
+
+ let sizeBytes = 0;
+ let lastActivityAt = 0;
+ const hasher = createHash('sha256');
+ const meter = new Transform({
+ transform(chunk, _encoding, callback) {
+ sizeBytes += chunk.length;
+ if (sizeBytes > metadata.sizeBytes) {
+ callback(remoteError('Remote result exceeded its advertised size'));
+ return;
+ }
+ hasher.update(chunk);
+ const now = Date.now();
+ if (now - lastActivityAt >= 1_000) {
+ lastActivityAt = now;
+ emitActivity(state.jobId);
+ }
+ callback(null, chunk);
+ },
+ });
+ try {
+ await pipeline(responseStream(response.body), meter, createWriteStream(partialPath, { flags: 'wx' }));
+ const digest = hasher.digest('hex');
+ if (sizeBytes !== metadata.sizeBytes || digest !== metadata.sha256) {
+ throw remoteError('Remote result failed byte-integrity verification', {
+ code: 'MEDIA_PROVIDER_RESULT_INTEGRITY_FAILED',
+ });
+ }
+ // POSIX rename replaces an existing file atomically. Do not unlink the
+ // destination first: consumers should never observe a missing final path
+ // between integrity verification and promotion.
+ await rename(partialPath, finalPath);
+ return filename;
+ } finally {
+ await unlink(partialPath).catch(() => {});
+ }
+ }, { timeoutMs: null });
+}
+
+async function downloadResult(state, remoteJob) {
+ while (true) {
+ if (state.cancelRequested) throw canceledError();
+ emitStatus(state.jobId, 'Downloading verified remote audio');
+ try {
+ return await downloadOnce(state, remoteJob);
+ } catch (error) {
+ if (state.cancelRequested) throw canceledError();
+ const retryable = !NON_RETRYABLE_FILE_CODES.has(error?.code)
+ && !error?.code?.startsWith('MEDIA_PROVIDER_RESULT_')
+ && isRetryableTransportError(error);
+ if (!retryable) throw error;
+ emitStatus(state.jobId, 'Remote audio transfer interrupted; retrying');
+ await waitForRetry(state, retryDelayMs);
+ }
+ }
+}
+
+async function runRemoteAudio(state, routingRequest, profile, marker) {
+ const prompt = renderFederatedMediaAudioPrompt(profile);
+ if (!prompt) {
+ throw remoteError('Remote audio job has an invalid privacy-safe profile', {
+ code: 'MEDIA_PROVIDER_AUDIO_PROFILE_INVALID',
+ });
+ }
+ const request = { ...routingRequest, prompt };
+ const selection = { kind: 'audio', engine: request.engine, modelId: request.modelId };
+ if (!marker.reconcile) await preflight(state, selection);
+ if (state.cancelRequested && !marker.reconcile && !state.submissionMayExist) throw canceledError();
+
+ const submitted = await submitOrRecover(state, request);
+ const completed = await pollProviderJob(state, submitted);
+ const filename = await downloadResult(state, completed);
+ return {
+ filename,
+ durationSec: completed.result.durationSec ?? request.durationSec ?? null,
+ engine: completed.result.engine ?? request.engine,
+ modelId: completed.result.modelId ?? request.modelId,
+ federatedMedia: {
+ wireVersion: FEDERATED_MEDIA_WIRE_VERSION,
+ peerId: state.peerId,
+ remoteJobId: completed.id,
+ },
+ };
+}
+
+export async function generateAudio(params) {
+ const marker = remoteMediaMarkerSchema.safeParse(params?.remoteMedia);
+ if (!marker.success) {
+ audioGenEvents.emit('failed', {
+ generationId: params?.jobId,
+ error: 'Remote audio job has invalid persisted routing metadata',
+ });
+ return;
+ }
+
+ const state = {
+ jobId: params.jobId,
+ peerId: marker.data.peerId,
+ cancelRequested: marker.data.cancelRequested === true,
+ cancelSent: false,
+ submissionMayExist: marker.data.reconcile === true,
+ requestController: null,
+ wake: null,
+ };
+ activeJobs.set(params.jobId, state);
+ try {
+ const result = await runRemoteAudio(state, marker.data.request, marker.data.profile, marker.data);
+ audioGenEvents.emit('completed', { generationId: params.jobId, ...result });
+ } catch (error) {
+ audioGenEvents.emit('failed', {
+ generationId: params.jobId,
+ error: error?.canceled ? 'Remote audio generation canceled' : (error?.message || 'Remote audio generation failed'),
+ });
+ } finally {
+ activeJobs.delete(params.jobId);
+ }
+}
+
+export function cancel(jobId) {
+ const state = activeJobs.get(jobId);
+ if (!state) return;
+ state.cancelRequested = true;
+ state.requestController?.abort();
+ state.wake?.();
+}
+
+export function __configureRemoteAudioForTests(options = {}) {
+ pollDelayMs = options.pollDelayMs ?? 0;
+ retryDelayMs = options.retryDelayMs ?? 0;
+ requestTimeoutMs = options.requestTimeoutMs ?? 1_000;
+}
+
+export function __resetRemoteAudioForTests() {
+ for (const state of activeJobs.values()) {
+ state.cancelRequested = true;
+ state.requestController?.abort();
+ state.wake?.();
+ }
+ activeJobs.clear();
+ pollDelayMs = 1_000;
+ retryDelayMs = 2_000;
+ requestTimeoutMs = 30_000;
+}
diff --git a/server/services/audioGen/remote.test.js b/server/services/audioGen/remote.test.js
new file mode 100644
index 0000000000..1667f42533
--- /dev/null
+++ b/server/services/audioGen/remote.test.js
@@ -0,0 +1,333 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createHash } from 'node:crypto';
+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+let tempMusicDir;
+const transport = vi.hoisted(() => ({ fetch: vi.fn() }));
+const federation = vi.hoisted(() => ({ resolve: vi.fn(), peers: [] }));
+
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ return {
+ ...actual,
+ PATHS: new Proxy(actual.PATHS, {
+ get(target, key) {
+ if (key === 'music') return tempMusicDir;
+ return target[key];
+ },
+ }),
+ };
+});
+
+vi.mock('../../lib/peerHttpClient.js', () => ({
+ peerFetch: (...args) => transport.fetch(...args),
+}));
+
+vi.mock('../federatedMediaConsumer.js', () => ({
+ resolveFederatedMediaProvider: (...args) => federation.resolve(...args),
+}));
+
+vi.mock('../instances.js', () => ({
+ getPeers: vi.fn(async () => federation.peers),
+}));
+
+import { audioGenEvents } from './events.js';
+import {
+ __configureRemoteAudioForTests,
+ __resetRemoteAudioForTests,
+ cancel,
+ generateAudio,
+} from './remote.js';
+
+const LOCAL_JOB_ID = '00000000-0000-4000-8000-000000000010';
+const REMOTE_JOB_ID = '00000000-0000-4000-8000-000000000020';
+const PEER_ID = '00000000-0000-4000-8000-000000000030';
+const SAFE_PROMPT = 'Instrumental cinematic music with a dreamy mood, slow tempo, medium energy, featuring strings and synthesizer. No vocals or spoken words.';
+const peer = {
+ id: PEER_ID,
+ enabled: true,
+ address: '192.0.2.10',
+ port: 5555,
+ mediaProvider: { enabled: true, audioModels: [{ engine: 'remote-audio', modelId: 'example/model' }] },
+};
+
+const sha256 = (value) => createHash('sha256').update(value).digest('hex');
+const jsonResponse = (body, status = 200) => new Response(JSON.stringify(body), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+});
+
+function providerJob(status, overrides = {}) {
+ return {
+ wireVersion: 1,
+ id: REMOTE_JOB_ID,
+ kind: 'audio',
+ status,
+ queuedAt: '2026-08-17T12:00:00.000Z',
+ startedAt: status === 'queued' ? null : '2026-08-17T12:00:01.000Z',
+ completedAt: ['completed', 'failed', 'canceled'].includes(status) ? '2026-08-17T12:00:02.000Z' : null,
+ position: status === 'queued' ? 1 : null,
+ progress: status === 'running' ? 0.5 : null,
+ etaMs: status === 'running' ? 5_000 : null,
+ ...overrides,
+ };
+}
+
+const params = (overrides = {}) => ({
+ jobId: LOCAL_JOB_ID,
+ prompt: '',
+ lyrics: '',
+ engine: 'remote-audio',
+ modelId: 'example/model',
+ durationSec: 30,
+ remoteMedia: {
+ wireVersion: 1,
+ peerId: PEER_ID,
+ profile: {
+ style: 'cinematic',
+ mood: 'dreamy',
+ tempo: 'slow',
+ energy: 'medium',
+ instruments: ['strings', 'synthesizer'],
+ },
+ request: {
+ engine: 'remote-audio',
+ modelId: 'example/model',
+ durationSec: 30,
+ },
+ },
+ ...overrides,
+});
+
+function captureTerminal(jobId) {
+ return new Promise((resolve) => {
+ const onCompleted = (event) => {
+ if (event.generationId !== jobId) return;
+ cleanup();
+ resolve({ type: 'completed', event });
+ };
+ const onFailed = (event) => {
+ if (event.generationId !== jobId) return;
+ cleanup();
+ resolve({ type: 'failed', event });
+ };
+ const cleanup = () => {
+ audioGenEvents.off('completed', onCompleted);
+ audioGenEvents.off('failed', onFailed);
+ };
+ audioGenEvents.on('completed', onCompleted);
+ audioGenEvents.on('failed', onFailed);
+ });
+}
+
+async function waitFor(predicate) {
+ for (let attempt = 0; attempt < 100; attempt += 1) {
+ if (predicate()) return;
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ }
+ throw new Error('Timed out waiting for condition');
+}
+
+beforeEach(() => {
+ tempMusicDir = mkdtempSync(join(tmpdir(), 'remote-audio-test-'));
+ federation.peers = [peer];
+ federation.resolve.mockReset().mockResolvedValue({ peer, capability: { engine: 'remote-audio', modelId: 'example/model' } });
+ transport.fetch.mockReset();
+ __configureRemoteAudioForTests({ pollDelayMs: 0, retryDelayMs: 0, requestTimeoutMs: 1_000 });
+});
+
+afterEach(() => {
+ __resetRemoteAudioForTests();
+ rmSync(tempMusicDir, { recursive: true, force: true });
+});
+
+describe('federated audio consumer adapter', () => {
+ it('reconciles a queued provider job and atomically imports a verified WAV', async () => {
+ const wav = Buffer.from('RIFF-example-wave-bytes');
+ const digest = sha256(wav);
+ const metadata = {
+ available: true,
+ mimeType: 'audio/wav',
+ sizeBytes: wav.length,
+ sha256: digest,
+ downloadUrl: `/api/federation/media/v1/jobs/${REMOTE_JOB_ID}/result`,
+ engine: 'remote-audio',
+ modelId: 'example/model',
+ durationSec: 30,
+ };
+ transport.fetch.mockImplementation(async (url, options) => {
+ if (url.endsWith('/jobs') && options.method === 'POST') return jsonResponse(providerJob('queued'), 202);
+ if (url.endsWith(`/jobs/${REMOTE_JOB_ID}`)) return jsonResponse(providerJob('completed', { result: metadata }));
+ if (url.endsWith(`/jobs/${REMOTE_JOB_ID}/result`)) {
+ return new Response(wav, {
+ headers: {
+ 'Content-Length': String(wav.length),
+ 'Content-Type': 'audio/wav',
+ 'X-Content-SHA256': digest,
+ },
+ });
+ }
+ throw new Error(`Unexpected test URL: ${url}`);
+ });
+
+ const terminal = captureTerminal(LOCAL_JOB_ID);
+ await generateAudio(params());
+ const outcome = await terminal;
+
+ expect(outcome).toMatchObject({
+ type: 'completed',
+ event: {
+ generationId: LOCAL_JOB_ID,
+ filename: `music-gen-${LOCAL_JOB_ID}.wav`,
+ engine: 'remote-audio',
+ modelId: 'example/model',
+ federatedMedia: { wireVersion: 1, peerId: PEER_ID, remoteJobId: REMOTE_JOB_ID },
+ },
+ });
+ expect(readFileSync(join(tempMusicDir, outcome.event.filename))).toEqual(wav);
+ expect(transport.fetch).toHaveBeenCalledWith(
+ 'http://192.0.2.10:5555/api/federation/media/v1/jobs',
+ expect.objectContaining({
+ method: 'POST',
+ headers: expect.objectContaining({ 'Idempotency-Key': LOCAL_JOB_ID }),
+ }),
+ peer,
+ );
+ const submission = transport.fetch.mock.calls.find(([url, options]) =>
+ url.endsWith('/jobs') && options.method === 'POST');
+ expect(JSON.parse(submission[1].body)).toEqual({
+ engine: 'remote-audio',
+ modelId: 'example/model',
+ prompt: SAFE_PROMPT,
+ durationSec: 30,
+ });
+ });
+
+ it('replays an uncertain submission with the same idempotency key', async () => {
+ const wav = Buffer.from('RIFF-replayed');
+ const digest = sha256(wav);
+ const completed = providerJob('completed', {
+ result: {
+ available: true,
+ mimeType: 'audio/wav',
+ sizeBytes: wav.length,
+ sha256: digest,
+ downloadUrl: '/ignored/provider/url',
+ engine: 'remote-audio',
+ modelId: 'example/model',
+ durationSec: 30,
+ },
+ });
+ let submissions = 0;
+ transport.fetch.mockImplementation(async (url, options) => {
+ if (url.endsWith('/jobs') && options.method === 'POST') {
+ submissions += 1;
+ if (submissions === 1) throw new TypeError('temporary connection loss');
+ return jsonResponse(completed, 200);
+ }
+ return new Response(wav, {
+ headers: {
+ 'Content-Length': String(wav.length),
+ 'Content-Type': 'audio/wav',
+ 'X-Content-SHA256': digest,
+ },
+ });
+ });
+
+ const terminal = captureTerminal(LOCAL_JOB_ID);
+ await generateAudio(params({
+ remoteMedia: {
+ wireVersion: 1,
+ peerId: PEER_ID,
+ reconcile: true,
+ profile: {
+ style: 'cinematic',
+ mood: 'dreamy',
+ tempo: 'slow',
+ energy: 'medium',
+ instruments: ['strings', 'synthesizer'],
+ },
+ request: {
+ engine: 'remote-audio',
+ modelId: 'example/model',
+ durationSec: 30,
+ },
+ },
+ }));
+ expect((await terminal).type).toBe('completed');
+
+ const postCalls = transport.fetch.mock.calls.filter(([, options]) => options.method === 'POST');
+ expect(postCalls).toHaveLength(2);
+ expect(postCalls.map(([, options]) => options.headers['Idempotency-Key']))
+ .toEqual([LOCAL_JOB_ID, LOCAL_JOB_ID]);
+ expect(federation.resolve).not.toHaveBeenCalled();
+ });
+
+ it('fails closed and removes the partial file when result integrity is wrong', async () => {
+ const expected = Buffer.from('RIFF-expected');
+ const received = Buffer.from('RIFF-tampered');
+ const digest = sha256(expected);
+ const metadata = {
+ available: true,
+ mimeType: 'audio/wav',
+ sizeBytes: received.length,
+ sha256: digest,
+ downloadUrl: '/ignored/provider/url',
+ engine: 'remote-audio',
+ modelId: 'example/model',
+ durationSec: 30,
+ };
+ transport.fetch.mockImplementation(async (url, options) => {
+ if (url.endsWith('/jobs') && options.method === 'POST') {
+ return jsonResponse(providerJob('completed', { result: metadata }), 202);
+ }
+ return new Response(received, {
+ headers: {
+ 'Content-Length': String(received.length),
+ 'Content-Type': 'audio/wav',
+ 'X-Content-SHA256': digest,
+ },
+ });
+ });
+
+ const terminal = captureTerminal(LOCAL_JOB_ID);
+ await generateAudio(params());
+ const outcome = await terminal;
+
+ expect(outcome.type).toBe('failed');
+ expect(outcome.event.error).toMatch(/integrity/i);
+ expect(existsSync(join(tempMusicDir, `music-gen-${LOCAL_JOB_ID}.wav`))).toBe(false);
+ expect(existsSync(join(tempMusicDir, `.music-gen-${LOCAL_JOB_ID}.wav.partial`))).toBe(false);
+ });
+
+ it('delivers cancellation to the recovered provider job', async () => {
+ let polling = false;
+ transport.fetch.mockImplementation(async (url, options) => {
+ if (url.endsWith('/jobs') && options.method === 'POST') return jsonResponse(providerJob('queued'), 202);
+ if (url.endsWith('/cancel')) return jsonResponse(providerJob('canceled'));
+ if (url.endsWith(`/jobs/${REMOTE_JOB_ID}`)) {
+ polling = true;
+ return new Promise((_resolve, reject) => {
+ options.signal.addEventListener('abort', () => {
+ reject(Object.assign(new Error('aborted'), { name: 'AbortError' }));
+ }, { once: true });
+ });
+ }
+ throw new Error(`Unexpected test URL: ${url}`);
+ });
+
+ const terminal = captureTerminal(LOCAL_JOB_ID);
+ const running = generateAudio(params());
+ await waitFor(() => polling);
+ cancel(LOCAL_JOB_ID);
+ await running;
+ const outcome = await terminal;
+
+ expect(outcome.type).toBe('failed');
+ expect(outcome.event.error).toMatch(/canceled/i);
+ expect(transport.fetch.mock.calls.some(([url, options]) =>
+ url.endsWith(`/jobs/${REMOTE_JOB_ID}/cancel`) && options.method === 'POST')).toBe(true);
+ });
+});
diff --git a/server/services/federatedMediaConsumer.js b/server/services/federatedMediaConsumer.js
index c35ca5693d..580207b4a5 100644
--- a/server/services/federatedMediaConsumer.js
+++ b/server/services/federatedMediaConsumer.js
@@ -1,9 +1,8 @@
/**
* 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.
+ * This module establishes the explicit per-peer allowlist and fail-closed
+ * capacity preflight used by remote executors before they submit work.
*/
import { ServerError } from '../lib/errorHandler.js';
diff --git a/server/services/federatedMediaProvider.js b/server/services/federatedMediaProvider.js
index 9fb8d6fceb..1697d6fbdc 100644
--- a/server/services/federatedMediaProvider.js
+++ b/server/services/federatedMediaProvider.js
@@ -17,7 +17,13 @@ import {
FEDERATED_MEDIA_WIRE_VERSION,
} from '../lib/federatedMediaWire.js';
import { getSettings } from './settings.js';
-import { enqueueJob, getJob, listJobs, cancelJob } from './mediaJobQueue/index.js';
+import {
+ cancelJob,
+ enqueueJob,
+ getJob,
+ isRemoteMediaJob,
+ listJobs,
+} from './mediaJobQueue/index.js';
import { listMusicEngineCapabilities } from './musicEngineCapabilities.js';
import { readCallerInstanceId } from './sharing/peerPullAuthorization.js';
import { findPeerById } from './sharing/peerSyncShared.js';
@@ -134,7 +140,13 @@ async function configuredAudioCapabilities(config) {
}
function activeQueueSnapshot(config) {
- const active = listJobs().filter((job) => ACTIVE_STATUSES.has(job.status));
+ // Outgoing proxy jobs consume a remote peer's capacity, not this provider's
+ // local generation resources. Counting them here can create a federation
+ // deadlock where two otherwise-idle peers both report busy while waiting on
+ // each other.
+ const active = listJobs().filter((job) =>
+ ACTIVE_STATUSES.has(job.status) && !isRemoteMediaJob(job),
+ );
const providerActive = active.filter((job) => job.owner?.startsWith(OWNER_PREFIX));
return {
totalActive: active.length,
diff --git a/server/services/federatedMediaProvider.test.js b/server/services/federatedMediaProvider.test.js
index 5e5379c163..670b3cdfce 100644
--- a/server/services/federatedMediaProvider.test.js
+++ b/server/services/federatedMediaProvider.test.js
@@ -30,6 +30,7 @@ vi.mock('./musicEngineCapabilities.js', () => ({
vi.mock('./mediaJobQueue/index.js', () => ({
listJobs: vi.fn(() => state.jobs),
+ isRemoteMediaJob: (job) => job?.kind === 'audio' && job.params?.remoteMedia !== undefined,
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');
@@ -77,7 +78,9 @@ afterAll(() => {
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' });
+const SAFE_PROMPT = 'Instrumental synthwave music with a dreamy mood, slow tempo, medium energy. No vocals or spoken words.';
+const OTHER_SAFE_PROMPT = 'Instrumental ambient music with a calm mood, slow tempo, low energy. No vocals or spoken words.';
+const input = () => ({ ...selection, prompt: SAFE_PROMPT, durationSec: 60, durationMode: 'manual' });
function readyEngine(overrides = {}) {
return {
@@ -173,7 +176,7 @@ describe('federated media provider capacity and idempotency', () => {
expect(enqueueJob).toHaveBeenCalledWith(expect.objectContaining({
kind: 'audio', owner: 'federated-media:peer-example',
params: expect.objectContaining({
- prompt: 'slow synthwave', engine: 'minimax-music3', modelId: 'minimax-music3',
+ prompt: SAFE_PROMPT, engine: 'minimax-music3', modelId: 'minimax-music3',
durationMode: 'manual',
federatedMedia: expect.objectContaining({
callerInstanceId: 'peer-example', idempotencyKey: 'commission-1',
@@ -195,7 +198,7 @@ describe('federated media provider capacity and idempotency', () => {
await expect(submitFederatedMediaJob({
callerId: 'peer-example', config: config(),
- input: { ...input(), prompt: 'different' }, idempotencyKey: 'commission-1',
+ input: { ...input(), prompt: OTHER_SAFE_PROMPT }, idempotencyKey: 'commission-1',
})).rejects.toMatchObject({ status: 409, code: 'MEDIA_PROVIDER_IDEMPOTENCY_CONFLICT' });
});
@@ -210,6 +213,23 @@ describe('federated media provider capacity and idempotency', () => {
expect(enqueueJob).not.toHaveBeenCalled();
});
+ it('does not count outgoing proxy jobs against this machine provider capacity', async () => {
+ state.jobs = [
+ {
+ id: 'remote-outgoing',
+ kind: 'audio',
+ owner: null,
+ status: 'running',
+ params: { remoteMedia: { wireVersion: 1, peerId: '00000000-0000-4000-8000-000000000001' } },
+ },
+ { id: 'local-1', kind: 'video', owner: null, status: 'running', params: {} },
+ ];
+
+ await expect(submitFederatedMediaJob({
+ callerId: 'peer-example', config: config(), input: input(), idempotencyKey: 'commission-remote-capacity',
+ })).resolves.toMatchObject({ replayed: false, job: { status: 'queued' } });
+ });
+
it('fails closed when CUDA readiness is unknown', async () => {
state.capabilities.engines = [readyEngine({ cudaState: 'unknown' })];
await expect(submitFederatedMediaJob({
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 476bc637c0..2406802884 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -1,5 +1,5 @@
/**
- * Media Job Queue — two-lane FIFO for image + video gen jobs.
+ * Media Job Queue — lane-aware FIFO for media generation jobs.
*
* Why this exists: video gen (mlx_video) and local image gen (mflux/diffusers)
* both spawn heavy GPU/Metal child processes. Running two simultaneously OOMs
@@ -8,10 +8,9 @@
* to retry/backoff. This queue serializes submissions so callers always get
* an immediate `queued` ack and watch progress via SSE.
*
- * Lanes: GPU jobs (video + local image) drain serially through `running` since
- * they share the MLX runtime. Codex image jobs run in a parallel `cloudRunning`
- * lane — they shell out to an external CLI and don't compete for GPU memory,
- * so a long video render never blocks a Codex storyboard generation.
+ * Lanes: GPU jobs drain serially through `running`; cloud CLI jobs use the
+ * bounded `cloudRunning` lane; federated audio uses `remoteRunning` so work on
+ * another machine never occupies this machine's GPU slot.
*
* Scope: gates `videoGen/local#generateVideo` (always),
* `imageGen/local#generateImage` (when imageGen mode === 'local'), and
@@ -22,8 +21,8 @@
* constraint to absorb.
*
* Persistence: data/media-jobs.json holds queued + running + recently-finished
- * jobs. On boot, any 'running' is reclassified as 'failed (interrupted by
- * restart)' since the spawned child died with the previous server process.
+ * jobs. On boot, local child-process jobs fail as interrupted; detached
+ * training and idempotent remote jobs reconcile against their surviving work.
* Completed/failed/canceled entries older than 24h or beyond the 500-most-
* recent are pruned to keep the file small.
*/
@@ -58,6 +57,19 @@ const isCloudImageJob = (j) =>
(j.kind === 'image' && CLOUD_IMAGE_GEN_MODES.includes(j.params?.mode))
|| (j.kind === 'video' && j.params?.mode === IMAGE_GEN_MODE.GROK);
+// Presence, not truthiness of individual nested fields, selects the remote
+// adapter. Persisted queue state is user-editable; a malformed marker must fail
+// closed in audioGen/remote rather than accidentally falling through to a local
+// engine with a remote-only model id.
+export const isRemoteMediaJob = (job) =>
+ job?.kind === 'audio' && job.params?.remoteMedia !== undefined;
+
+const jobLane = (job) => {
+ if (isRemoteMediaJob(job)) return 'remote';
+ if (isCloudImageJob(job)) return 'cloud';
+ return 'gpu';
+};
+
const JOBS_FILE = join(PATHS.data, 'media-jobs.json');
const COMPLETED_TTL_MS = 24 * 60 * 60 * 1000;
const MAX_PERSISTED_ARCHIVE = 500;
@@ -135,6 +147,7 @@ function getGenModuleForJob(job) {
if (job.kind === 'video' && job.params?.mode === IMAGE_GEN_MODE.GROK) return import('../videoGen/grok.js');
if (job.kind === 'video') return import('../videoGen/local.js');
if (job.kind === 'training') return import('../loraTraining/index.js');
+ if (isRemoteMediaJob(job)) return import('../audioGen/remote.js');
if (job.kind === 'audio') return import('../audioGen/local.js');
if (job.kind === 'image' && job.params?.mode === IMAGE_GEN_MODE.CODEX) return import('../imageGen/codex.js');
if (job.kind === 'image' && job.params?.mode === IMAGE_GEN_MODE.GROK) return import('../imageGen/grok.js');
@@ -185,17 +198,21 @@ export const mediaJobEvents = new EventEmitter();
// emitters already set (imageGenEvents 200, videoGenEvents 50).
mediaJobEvents.setMaxListeners(100);
-// GPU lane: serialized — `running` holds at most one job (the MLX runtime can't
-// share VRAM). Codex lane: up to `codexParallelLimit` jobs in `cloudRunning[]`
-// since each call shells out to its own external child process. `queue` is
-// shared submission order. `archive` is recently-finished jobs (~24h TTL),
-// including canceled ones so /api/media-jobs?status=canceled and the recent-
-// reel UI can still find them within the 24h window.
+// GPU lane: serialized — `running` holds at most one job. Cloud CLI and remote
+// provider lanes are parallel because neither consumes the local GPU. `queue`
+// preserves submission order across lanes; positions are lane-scoped.
const queue = [];
let running = null;
const cloudRunning = [];
+const remoteRunning = [];
const archive = [];
+// One install can route to several peers, while each provider remains the
+// authority on its own capacity. This bound prevents corrupted persisted state
+// from creating unbounded local polling loops without serializing independent
+// peers behind the local GPU lane.
+export const REMOTE_MEDIA_PARALLEL_LIMIT = 20;
+
export const CODEX_PARALLEL_MIN = 1;
export const CODEX_PARALLEL_MAX = 10;
export const CODEX_PARALLEL_DEFAULT = 1;
@@ -238,6 +255,8 @@ function findJob(jobId) {
if (running && running.id === jobId) return running;
const codexHit = cloudRunning.find((j) => j.id === jobId);
if (codexHit) return codexHit;
+ const remoteHit = remoteRunning.find((j) => j.id === jobId);
+ if (remoteHit) return remoteHit;
const inQueue = queue.find((j) => j.id === jobId);
if (inQueue) return inQueue;
return archive.find((j) => j.id === jobId) || null;
@@ -266,6 +285,7 @@ export function listJobs({ status, kind, owner } = {}) {
const all = [
...(running ? [running] : []),
...cloudRunning,
+ ...remoteRunning,
...queue,
...archive,
];
@@ -309,6 +329,7 @@ async function persistImpl() {
const live = [
...(running ? [running] : []),
...cloudRunning,
+ ...remoteRunning,
...queue,
...archive,
];
@@ -363,6 +384,27 @@ export async function initMediaJobQueue() {
for (const j of persistedJobs) {
if (j.status === 'running') {
+ // A remote provider job survives this process: its local queue id is
+ // also the stable Idempotency-Key. Re-enqueue the same record and let
+ // the remote adapter replay the submission, recover the provider job,
+ // and continue polling (or deliver a persisted cancellation intent).
+ if (isRemoteMediaJob(j)) {
+ const marker = j.params?.remoteMedia;
+ queue.push({
+ ...j,
+ status: 'queued',
+ cancelRequested: marker?.cancelRequested === true,
+ params: {
+ ...j.params,
+ remoteMedia: {
+ ...(marker && typeof marker === 'object' && !Array.isArray(marker) ? marker : {}),
+ reconcile: true,
+ },
+ },
+ });
+ console.log(`🔁 media-job [${j.id.slice(0, 8)}] remote audio interrupted — re-enqueued for reconciliation`);
+ continue;
+ }
// #1332: a LoRA trainer is a detached child (spawnDetached) that can
// SURVIVE this restart. If its run still has a live (or just-finished-
// but-unprocessed) trainer, re-enqueue the SAME job flagged for
@@ -412,14 +454,11 @@ export async function initMediaJobQueue() {
// event report accurate slots. Positions are lane-scoped: Codex image
// jobs and GPU jobs each get their own counter so a queued Codex job
// behind a running GPU job is restored as position 1 (not position 2).
- let cloudCounter = 0;
- let gpuCounter = 0;
+ const counters = { cloud: 0, gpu: 0, remote: 0 };
for (const q of queue) {
- if (isCloudImageJob(q)) {
- q.position = ++cloudCounter;
- } else {
- q.position = ++gpuCounter;
- }
+ const lane = jobLane(q);
+ counters[lane] += 1;
+ q.position = counters[lane];
}
if (persistedJobs.length) {
console.log(`📦 mediaJobQueue restored: ${queue.length} queued, ${archive.length} archived`);
@@ -460,11 +499,9 @@ function startWorker() {
});
}
-// Both lanes use fire-and-forget so the poll loop is never blocked by a
-// running job. This lets a Codex job that arrives while a GPU render is in
-// flight be picked up immediately on the next 150 ms tick instead of having
-// to wait for the entire GPU job to finish first.
-function startLaneJob(job, { isCloud }) {
+// Every lane uses fire-and-forget so the poll loop is never blocked by a
+// running job in another lane.
+function startLaneJob(job, { lane }) {
// If the job isn't in the queue, it was already promoted (e.g. by a parallel
// runJobNow). Skip — promoting again would double-start the job and corrupt
// the lane (push it onto cloudRunning/running twice). Silently splice(-1)
@@ -480,13 +517,17 @@ function startLaneJob(job, { isCloud }) {
job.position = 1;
job.progress = typeof job.progress === 'number' && Number.isFinite(job.progress) ? job.progress : 0;
job.statusMsg = job.statusMsg || 'Starting';
- if (isCloud) {
+ if (lane === 'cloud') {
cloudRunning.push(job);
+ } else if (lane === 'remote') {
+ remoteRunning.push(job);
} else {
running = job;
}
recomputeQueuePositions();
- const label = isCloud ? (job.params?.mode || 'cloud') : job.kind;
+ const label = lane === 'cloud'
+ ? (job.params?.mode || 'cloud')
+ : lane === 'remote' ? 'remote audio' : job.kind;
persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on ${label} start failed: ${e.message}`));
broadcastSse(ensureSseEntry(job.id), { type: 'started', kind: job.kind });
mediaJobEvents.emit('started', job);
@@ -507,9 +548,12 @@ function startLaneJob(job, { isCloud }) {
mediaJobEvents.emit('failed', job);
}
}
- if (isCloud) {
+ if (lane === 'cloud') {
const idx = cloudRunning.indexOf(job);
if (idx >= 0) cloudRunning.splice(idx, 1);
+ } else if (lane === 'remote') {
+ const idx = remoteRunning.indexOf(job);
+ if (idx >= 0) remoteRunning.splice(idx, 1);
} else {
running = null;
}
@@ -524,22 +568,28 @@ function startLaneJob(job, { isCloud }) {
async function drainLoop() {
while (true) {
- // Single queue scan, promote eligible codex jobs while there's room and a
- // GPU job if the lane is open. Stops cleanly on an empty queue.
+ // Single queue scan, promoting work independently into each open lane.
let gpuOpen = !running;
let cloudSlots = codexParallelLimit - cloudRunning.length;
- if ((gpuOpen || cloudSlots > 0) && queue.length > 0) {
+ let remoteSlots = REMOTE_MEDIA_PARALLEL_LIMIT - remoteRunning.length;
+ if ((gpuOpen || cloudSlots > 0 || remoteSlots > 0) && queue.length > 0) {
for (const job of queue.slice()) {
- if (isCloudImageJob(job)) {
+ const lane = jobLane(job);
+ if (lane === 'remote') {
+ if (remoteSlots > 0) {
+ startLaneJob(job, { lane });
+ remoteSlots -= 1;
+ }
+ } else if (lane === 'cloud') {
if (cloudSlots > 0) {
- startLaneJob(job, { isCloud: true });
+ startLaneJob(job, { lane });
cloudSlots -= 1;
}
} else if (gpuOpen) {
- startLaneJob(job, { isCloud: false });
+ startLaneJob(job, { lane });
gpuOpen = false;
}
- if (!gpuOpen && cloudSlots <= 0) break;
+ if (!gpuOpen && cloudSlots <= 0 && remoteSlots <= 0) break;
}
}
await sleep(150);
@@ -577,7 +627,7 @@ export function runJobNow(jobId) {
if (!isCloudImageJob(job)) {
return { ok: false, code: 'NOT_CODEX', error: 'Only cloud-CLI image jobs can be run now; GPU jobs serialize on the MLX runtime' };
}
- startLaneJob(job, { isCloud: true });
+ startLaneJob(job, { lane: 'cloud' });
return { ok: true, status: 'running' };
}
@@ -588,7 +638,8 @@ export function runJobNow(jobId) {
// frame even after the line ahead of it cleared.
function recomputeQueuePositions() {
const cloudJobs = queue.filter(isCloudImageJob);
- const gpuJobs = queue.filter((j) => !isCloudImageJob(j));
+ const remoteJobs = queue.filter(isRemoteMediaJob);
+ const gpuJobs = queue.filter((j) => jobLane(j) === 'gpu');
cloudJobs.forEach((q, i) => {
const newPosition = i + 1 + cloudRunning.length;
@@ -599,6 +650,15 @@ function recomputeQueuePositions() {
}
});
+ remoteJobs.forEach((q, i) => {
+ const newPosition = i + 1 + remoteRunning.length;
+ if (q.position !== newPosition) {
+ q.position = newPosition;
+ const entry = sseJobs.get(q.id);
+ if (entry) broadcastSse(entry, { type: 'queued', position: newPosition });
+ }
+ });
+
gpuJobs.forEach((q, i) => {
const newPosition = i + 1 + (running ? 1 : 0);
if (q.position !== newPosition) {
@@ -940,6 +1000,13 @@ async function runJob(job) {
} else if (job.kind === 'training') {
await mod.runTraining({ ...safeParams, jobId: job.id });
} else if (job.kind === 'audio') {
+ if (isRemoteMediaJob(job)) {
+ safeParams.remoteMedia = {
+ ...(safeParams.remoteMedia && typeof safeParams.remoteMedia === 'object'
+ ? safeParams.remoteMedia : {}),
+ cancelRequested: job.params?.remoteMedia?.cancelRequested === true,
+ };
+ }
await mod.generateAudio({ ...safeParams, jobId: job.id });
} else {
await mod.generateImage({ ...safeParams, jobId: job.id });
@@ -980,12 +1047,15 @@ export function enqueueJob({ kind, params, owner = null }) {
queuedAt: new Date().toISOString(),
params,
// position counts "where you sit in your lane" — a running job in the
- // same lane occupies slot 1, then same-lane queued jobs follow. Codex
- // jobs only count Codex ahead-of-them; GPU jobs only count GPU jobs.
+ // same lane occupies slot 1, then same-lane queued jobs follow.
position: (() => {
- const isCloud = isCloudImageJob({ kind, params });
- const laneQueue = queue.filter((j) => isCloudImageJob(j) === isCloud);
- return laneQueue.length + (isCloud ? cloudRunning.length : (running ? 1 : 0)) + 1;
+ const candidate = { kind, params };
+ const lane = jobLane(candidate);
+ const laneQueue = queue.filter((j) => jobLane(j) === lane);
+ const liveCount = lane === 'cloud'
+ ? cloudRunning.length
+ : lane === 'remote' ? remoteRunning.length : (running ? 1 : 0);
+ return laneQueue.length + liveCount + 1;
})(),
};
queue.push(job);
@@ -1057,9 +1127,10 @@ export async function cancelJob(jobId) {
console.log(`🛑 media-job [${jobId.slice(0, 8)}] canceled (was queued)`);
return { ok: true, status: 'canceled' };
}
- // Cancel-while-running — check the GPU slot and every parallel codex slot.
+ // Cancel-while-running — check every lane.
const runningJob = (running?.id === jobId ? running : null)
?? cloudRunning.find((j) => j.id === jobId)
+ ?? remoteRunning.find((j) => j.id === jobId)
?? null;
if (runningJob) {
// A terminal transition already started (completed/failed/watchdog): its
@@ -1072,6 +1143,18 @@ export async function cancelJob(jobId) {
// cancelRequested flips the dispatcher's `failed` handler into the
// `canceled` branch instead of marking it failed.
runningJob.cancelRequested = true;
+ if (isRemoteMediaJob(runningJob)) {
+ // Remote cancellation can outlive this process when the peer is down.
+ // Persist the intent before signaling the adapter so boot reconciliation
+ // replays the stable submission and resumes cancellation instead of
+ // silently resurrecting the render.
+ runningJob.params.remoteMedia = {
+ ...(runningJob.params.remoteMedia && typeof runningJob.params.remoteMedia === 'object'
+ ? runningJob.params.remoteMedia : {}),
+ cancelRequested: true,
+ };
+ await persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on remote cancel failed: ${e.message}`));
+ }
const mod = await getGenModuleForJob(runningJob);
if (mod?.cancel) mod.cancel(jobId);
console.log(`🛑 media-job [${jobId.slice(0, 8)}] cancel signal sent (was running)`);
@@ -1144,6 +1227,7 @@ export function __resetForTests() {
// `cloudRunning` is a const array — clear it in place rather than reassigning,
// which would throw TypeError and break `findJob()` (.find on null).
cloudRunning.length = 0;
+ remoteRunning.length = 0;
archive.length = 0;
sseJobs.clear();
workerStarted = false;
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index 4883c35f48..dfa94ddf04 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -43,10 +43,12 @@ tryReadFile: vi.fn().mockResolvedValue(null), jobId: 'whatever' })),
generateImage: vi.fn(async () => ({ jobId: 'whatever' })),
generateImageCodex: vi.fn(async () => ({ jobId: 'whatever' })),
generateAudio: vi.fn(async () => ({ jobId: 'whatever' })),
+ generateAudioRemote: vi.fn(async () => ({ jobId: 'whatever' })),
cancelVideo: vi.fn(),
cancelImage: vi.fn(),
cancelImageCodex: vi.fn(),
cancelAudio: vi.fn(),
+ cancelAudioRemote: vi.fn(),
// #1332: loraTraining is dynamically imported by the queue for runTraining
// (worker) and hasSurvivingTrainer (boot reconcile). Stub both so the boot
// re-attach decision is testable without loading the real trainer module.
@@ -75,6 +77,11 @@ vi.mock('../audioGen/local.js', () => ({
cancel: (...args) => stubs.cancelAudio(...args),
}));
+vi.mock('../audioGen/remote.js', () => ({
+ generateAudio: (...args) => stubs.generateAudioRemote(...args),
+ cancel: (...args) => stubs.cancelAudioRemote(...args),
+}));
+
vi.mock('../loraTraining/index.js', () => ({
runTraining: (...args) => stubs.runTraining(...args),
hasSurvivingTrainer: (...args) => stubs.hasSurvivingTrainer(...args),
@@ -102,6 +109,13 @@ const flush = async () => {
await mediaJobQueue?.__drainForTests();
};
+const remoteMediaParams = () => ({
+ wireVersion: 1,
+ peerId: '00000000-0000-4000-8000-000000000001',
+ profile: { style: 'ambient', mood: 'calm', tempo: 'slow', energy: 'low', instruments: [] },
+ request: { engine: 'remote-audio', modelId: 'example/model' },
+});
+
beforeEach(async () => {
tempDataDir = mkdtempSync(join(tmpdir(), 'mediaJobQueue-test-'));
Object.values(stubs).forEach((fn) => fn.mockReset());
@@ -800,6 +814,7 @@ describe('Audio kind (#1928)', () => {
// gen modules must not have been invoked.
expect(stubs.generateVideo).not.toHaveBeenCalled();
expect(stubs.generateImage).not.toHaveBeenCalled();
+ expect(stubs.generateAudioRemote).not.toHaveBeenCalled();
audioGenEvents.emit('completed', { generationId: job.jobId, filename: `${job.jobId}.wav`, durationSec: 12 });
await waitFor(() => mediaJobQueue.getJob(job.jobId)?.status === 'completed');
@@ -808,6 +823,82 @@ describe('Audio kind (#1928)', () => {
expect(settled.result).toEqual({ generationId: job.jobId, filename: `${job.jobId}.wav`, durationSec: 12 });
});
+ it('runs remote audio in its own lane without occupying the local GPU', async () => {
+ stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
+ stubs.generateAudioRemote.mockImplementation(() => new Promise(() => {}));
+
+ const video = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'local render' } });
+ const remote = mediaJobQueue.enqueueJob({
+ kind: 'audio',
+ params: {
+ prompt: '',
+ engine: 'remote-audio',
+ modelId: 'example/model',
+ remoteMedia: remoteMediaParams(),
+ },
+ });
+
+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1
+ && stubs.generateAudioRemote.mock.calls.length === 1);
+ expect(stubs.generateAudio).not.toHaveBeenCalled();
+ expect(mediaJobQueue.getJob(video.jobId).status).toBe('running');
+ expect(mediaJobQueue.getJob(remote.jobId).status).toBe('running');
+
+ audioGenEvents.emit('completed', { generationId: remote.jobId, filename: `${remote.jobId}.wav` });
+ videoGenEvents.emit('failed', { generationId: video.jobId, error: 'cleanup' });
+ await waitFor(() => mediaJobQueue.getJob(remote.jobId)?.status === 'completed');
+ });
+
+ it('persists cancellation intent before signaling a running remote adapter', async () => {
+ stubs.generateAudioRemote.mockImplementation(() => new Promise(() => {}));
+ const remote = mediaJobQueue.enqueueJob({
+ kind: 'audio',
+ params: {
+ prompt: '',
+ remoteMedia: remoteMediaParams(),
+ },
+ });
+ await waitFor(() => stubs.generateAudioRemote.mock.calls.length === 1);
+
+ await expect(mediaJobQueue.cancelJob(remote.jobId)).resolves.toMatchObject({ ok: true, status: 'canceling' });
+ expect(stubs.cancelAudioRemote).toHaveBeenCalledWith(remote.jobId);
+ expect(mediaJobQueue.getJob(remote.jobId).params.remoteMedia.cancelRequested).toBe(true);
+
+ audioGenEvents.emit('failed', { generationId: remote.jobId, error: 'canceled remotely' });
+ await waitFor(() => mediaJobQueue.getJob(remote.jobId)?.status === 'canceled');
+ });
+
+ it('re-enqueues a persisted running remote job with reconciliation enabled', async () => {
+ const id = '00000000-0000-4000-8000-000000000002';
+ writeFileSync(join(tempDataDir, 'media-jobs.json'), JSON.stringify({
+ jobs: [{
+ id,
+ kind: 'audio',
+ owner: null,
+ status: 'running',
+ queuedAt: '2026-08-17T12:00:00.000Z',
+ startedAt: '2026-08-17T12:00:01.000Z',
+ params: {
+ prompt: '',
+ engine: 'remote-audio',
+ modelId: 'example/model',
+ remoteMedia: remoteMediaParams(),
+ },
+ }],
+ }));
+ stubs.generateAudioRemote.mockImplementation(() => new Promise(() => {}));
+
+ await mediaJobQueue.initMediaJobQueue();
+ await waitFor(() => stubs.generateAudioRemote.mock.calls.length === 1);
+
+ expect(stubs.generateAudioRemote).toHaveBeenCalledWith(expect.objectContaining({
+ jobId: id,
+ remoteMedia: expect.objectContaining({ reconcile: true }),
+ }));
+ audioGenEvents.emit('completed', { generationId: id, filename: `${id}.wav` });
+ await waitFor(() => mediaJobQueue.getJob(id)?.status === 'completed');
+ });
+
// cancelJob's dispatch-by-kind (mod.cancel(jobId)) is exercised generically
// by the Codex lane's cancel test below via the same getGenModuleForJob
// mechanism; audioGen/local.js#cancel's own behavior (aborting the in-flight
diff --git a/server/services/mediaJobQueue/sanitizeJob.js b/server/services/mediaJobQueue/sanitizeJob.js
index 9e34dfb44d..6fa33c784a 100644
--- a/server/services/mediaJobQueue/sanitizeJob.js
+++ b/server/services/mediaJobQueue/sanitizeJob.js
@@ -1,3 +1,5 @@
+import { renderFederatedMediaAudioPrompt } from '../../lib/federatedMediaWire.js';
+
// Public projection of a media job. Keep worker-only paths and subprocess
// details out of both the queue API and the processing dashboard.
const PARAM_ALLOWLIST = new Set([
@@ -25,6 +27,14 @@ export function sanitizeJob(job) {
: value,
]))
: undefined;
+ // Remote jobs keep only a fixed-vocabulary profile inside their versioned
+ // marker so free-form personal text never reaches the provider. Rebuild the
+ // actual conditioning prompt for the public projection without exposing
+ // private peer routing state.
+ const remotePrompt = renderFederatedMediaAudioPrompt(job.params?.remoteMedia?.profile);
+ if (safeParams && remotePrompt) {
+ safeParams.prompt = remotePrompt;
+ }
return {
id: job.id,
kind: job.kind,
diff --git a/server/services/mediaJobQueue/sanitizeJob.test.js b/server/services/mediaJobQueue/sanitizeJob.test.js
index 0fad4d7cd6..efc8355623 100644
--- a/server/services/mediaJobQueue/sanitizeJob.test.js
+++ b/server/services/mediaJobQueue/sanitizeJob.test.js
@@ -22,4 +22,37 @@ describe('sanitizeJob', () => {
expect(job.params.musicStudio).toEqual({ trackId: 'track-1', instrumentalOnly: true });
expect(job.params).not.toHaveProperty('lyrics');
});
+
+ it('restores the public prompt without exposing private peer routing fields', () => {
+ const sanitized = sanitizeJob({
+ id: 'job-example',
+ kind: 'audio',
+ status: 'queued',
+ params: {
+ prompt: '',
+ modelId: 'example/model',
+ remoteMedia: {
+ wireVersion: 1,
+ peerId: '00000000-0000-4000-8000-000000000001',
+ profile: {
+ style: 'orchestral',
+ mood: 'triumphant',
+ tempo: 'moderate',
+ energy: 'high',
+ instruments: ['brass', 'strings'],
+ },
+ request: {
+ engine: 'remote-audio',
+ modelId: 'example/model',
+ },
+ },
+ },
+ });
+
+ expect(sanitized.params).toEqual({
+ prompt: 'Instrumental orchestral music with a triumphant mood, moderate tempo, high energy, featuring brass and strings. No vocals or spoken words.',
+ modelId: 'example/model',
+ });
+ expect(sanitized.params).not.toHaveProperty('remoteMedia');
+ });
});
diff --git a/server/services/musicStudioHook.js b/server/services/musicStudioHook.js
index f51a3804ec..3f25c5b582 100644
--- a/server/services/musicStudioHook.js
+++ b/server/services/musicStudioHook.js
@@ -2,6 +2,7 @@
* Files completed Music Studio audio jobs onto their track, even when the
* browser that started the render has unmounted (#4353).
*/
+import { renderFederatedMediaAudioPrompt } from '../lib/federatedMediaWire.js';
import { createMediaJobImageHook } from './mediaJobImageHook.js';
import { updateJobResult } from './mediaJobQueue/index.js';
import * as tracks from './tracks/index.js';
@@ -22,14 +23,15 @@ const hook = createMediaJobImageHook({
const tag = job.params.musicStudio;
const authoredPrompt = typeof tag.authoredPrompt === 'string' ? tag.authoredPrompt : job.params.prompt;
const authoredLyrics = typeof tag.authoredLyrics === 'string' ? tag.authoredLyrics : job.params.lyrics;
+ const remotePrompt = renderFederatedMediaAudioPrompt(job.params.remoteMedia?.profile);
return {
filename,
durationSec: Number.isFinite(job.result?.durationSec) ? Math.round(job.result.durationSec) : null,
engine: typeof job.result?.engine === 'string' ? job.result.engine : null,
modelId: typeof job.result?.modelId === 'string' ? job.result.modelId : null,
- prompt: job.params.prompt,
+ prompt: remotePrompt || job.params.prompt,
authoredPrompt,
- lyrics: job.params.lyrics,
+ lyrics: remotePrompt ? '' : job.params.lyrics,
authoredLyrics,
lyricsEnabled: tag.lyricsEnabled === true,
lyricsProvided: tag.lyricsProvided === true,
diff --git a/server/services/musicStudioHook.test.js b/server/services/musicStudioHook.test.js
index 377f43cac3..af3a438c81 100644
--- a/server/services/musicStudioHook.test.js
+++ b/server/services/musicStudioHook.test.js
@@ -126,4 +126,29 @@ describe('music studio completion hook', () => {
await new Promise((resolve) => setImmediate(resolve));
expect(trackStore.updateTrack).not.toHaveBeenCalledWith('deleted-track', expect.anything());
});
+
+ it('files the privacy-safe profile prompt instead of the rollback-safe empty prompt', async () => {
+ trackStore.getTrack.mockResolvedValue({ id: 'track-1', renders: [] });
+ queue.events.emit('completed', {
+ id: 'job-remote', kind: 'audio', queuedAt: new Date().toISOString(),
+ params: {
+ prompt: '',
+ lyrics: '',
+ remoteMedia: {
+ wireVersion: 1,
+ peerId: '00000000-0000-4000-8000-000000000001',
+ profile: { style: 'ambient', mood: 'calm', tempo: 'slow', energy: 'low', instruments: ['piano'] },
+ request: { engine: 'remote-audio', modelId: 'example/model' },
+ },
+ musicStudio: { trackId: 'track-1', lyricsEnabled: true, lyricsProvided: false },
+ },
+ result: { filename: 'remote.wav', durationSec: 30, engine: 'remote-audio', modelId: 'example/model' },
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+
+ expect(trackStore.buildRenderAppend).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
+ prompt: 'Instrumental ambient music with a calm mood, slow tempo, low energy, featuring piano. No vocals or spoken words.',
+ lyrics: '',
+ }));
+ });
});