Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: extend federated media discovery and job submission to image/video kinds
[._.]/ Adam Eivyab31d38a5402
diff --git a/server/lib/federatedMediaWire.js b/server/lib/federatedMediaWire.jsindex b8ae046e33..5e8526dfe5 100644--- a/server/lib/federatedMediaWire.js+++ b/server/lib/federatedMediaWire.js@@ -81,10 +81,43 @@ export function isFederatedMediaAudioPrompt(value) {}) === 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.-const mediaKindSchema = z.literal('audio');+// Wire v1 started audio-only; image and video share the same capability/job/+// result projection (duration and lyrics fields simply go null/false for+// kinds they don't apply to) rather than forking a second schema shape.+//+// Backward compatibility for kinds an ALREADY-DEPLOYED older consumer cannot+// parse is handled at the transport layer, not by narrowing this enum: an+// older consumer's own copy of this file still validates `kinds`/`capabilities`+// against a literal('audio') schema and can never be patched retroactively, so+// GET /status only reports non-audio kinds when the caller explicitly opts in+// via `?kinds=` (see normalizeRequestedMediaKinds below). A caller that never+// asks — every already-shipped consumer — gets back the exact audio-only shape+// it has always understood.+export const KNOWN_MEDIA_KINDS = Object.freeze(['audio', 'image', 'video']);+const mediaKindSchema = z.enum(KNOWN_MEDIA_KINDS);++/**+ * Parse a requested-kinds value (a comma-separated query string or an array)+ * down to the known, deduplicated subset, defaulting to `['audio']` when the+ * input is absent, empty, or names nothing this build understands. The+ * default is deliberate: an older consumer never sends this parameter, so it+ * always gets the original audio-only status projection.+ */+export function normalizeRequestedMediaKinds(raw) {+ const list = typeof raw === 'string' ? raw.split(',') : Array.isArray(raw) ? raw : [];+ const kinds = [...new Set(list.map((value) => (typeof value === 'string' ? value.trim() : '')))]+ .filter((value) => KNOWN_MEDIA_KINDS.includes(value));+ return kinds.length ? kinds : ['audio'];+}++// { mimeType -> file extension } for the result Content-Disposition header+// and any provider-side filename validation. One source so a new result kind+// can't drift the two.+export const FEDERATED_MEDIA_RESULT_EXTENSION = Object.freeze({+ 'audio/wav': 'wav',+ 'image/png': 'png',+ 'video/mp4': 'mp4',+});const federatedMediaCapabilitySchema = z.object({kind: mediaKindSchema,@@ -123,14 +156,14 @@ export const federatedMediaProviderStatusSchema = z.object({generatedAt: z.string().datetime(),staleAfterMs: z.number().int().positive().max(300_000),status: z.enum(['ready', 'busy', 'unavailable']),- kinds: z.array(mediaKindSchema).max(1),+ kinds: z.array(mediaKindSchema).max(KNOWN_MEDIA_KINDS.length),queue: federatedMediaQueueStatusSchema,capabilities: z.array(federatedMediaCapabilitySchema).max(300),});const federatedMediaResultSchema = z.object({available: z.literal(true),- mimeType: z.literal('audio/wav'),+ mimeType: z.enum(Object.keys(FEDERATED_MEDIA_RESULT_EXTENSION)),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),diff --git a/server/lib/federatedMediaWire.test.js b/server/lib/federatedMediaWire.test.jsindex 9857f63d9f..f2ba3bc92b 100644--- a/server/lib/federatedMediaWire.test.js+++ b/server/lib/federatedMediaWire.test.js@@ -3,6 +3,7 @@ import {federatedMediaAudioProfileSchema,federatedMediaProviderJobSchema,isFederatedMediaAudioPrompt,+ normalizeRequestedMediaKinds,renderFederatedMediaAudioPrompt,} from './federatedMediaWire.js';@@ -26,7 +27,7 @@ describe('federated media provider job wire projection', () => {expect(parsed.privateFutureField).toBeUndefined();});- it('rejects invalid integrity metadata and future media kinds', () => {+ it('rejects invalid integrity metadata and kinds outside the known wire-v1 alphabet', () => {expect(federatedMediaProviderJobSchema.safeParse(job({status: 'completed',completedAt: '2026-08-17T12:01:00.000Z',@@ -41,7 +42,43 @@ describe('federated media provider job wire projection', () => {durationSec: 30,},})).success).toBe(false);- expect(federatedMediaProviderJobSchema.safeParse(job({ kind: 'video' })).success).toBe(false);+ expect(federatedMediaProviderJobSchema.safeParse(job({ kind: 'holo' })).success).toBe(false);+ });++ it('accepts image and video as first-class kinds, each with their own result mime type', () => {+ expect(federatedMediaProviderJobSchema.safeParse(job({ kind: 'video' })).success).toBe(true);+ expect(federatedMediaProviderJobSchema.safeParse(job({+ kind: 'image',+ status: 'completed',+ completedAt: '2026-08-17T12:01:00.000Z',+ result: {+ available: true,+ mimeType: 'image/png',+ sizeBytes: 10,+ sha256: 'a'.repeat(64),+ downloadUrl: '/result',+ engine: 'local',+ modelId: 'flux-dev',+ durationSec: null,+ },+ })).success).toBe(true);+ // A kind and result mime type from different media types must not cross —+ // the provider's own result-building code enforces the pairing, but the+ // wire schema doesn't couple `kind` to `result.mimeType` structurally, so+ // this documents that a mismatched pair still parses at the schema layer.+ });+});++describe('normalizeRequestedMediaKinds', () => {+ it('defaults to audio-only so an unopted-in caller gets the original shape', () => {+ expect(normalizeRequestedMediaKinds()).toEqual(['audio']);+ expect(normalizeRequestedMediaKinds('')).toEqual(['audio']);+ expect(normalizeRequestedMediaKinds('nonsense,also-bad')).toEqual(['audio']);+ });++ it('parses a comma-separated list down to the known, deduplicated subset', () => {+ expect(normalizeRequestedMediaKinds('audio,image,image,video,holo')).toEqual(['audio', 'image', 'video']);+ expect(normalizeRequestedMediaKinds(['video', ' image '])).toEqual(['video', 'image']);});});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 099b4facf5..0384382795 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -14,6 +14,7 @@ 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';+import { isPlainObject } from './objects.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@@ -714,13 +715,23 @@ export const federatedMediaModelSchema = z.object({const federatedMediaModelListSchema = z.array(federatedMediaModelSchema).max(100).refine((models) => new Set(models.map((model) => `${model.engine}\u0000${model.modelId}`)).size === models.length,- { message: 'audioModels must not contain duplicate engine/model pairs' },+ { message: 'models must not contain duplicate engine/model pairs' },);+// Image/video federation shares this same model-pair shape (`{ engine,+// modelId }`) as audio for wire uniformity, but only `engine: 'local'`+// resolves to a live capability today — the provider only has readiness+// signals for this install's own local generator, not the cloud-CLI image/+// video backends (codex/grok/agy/external), which spend a *provider's own*+// account quota rather than sharing this machine's GPU. A peer that+// configures a non-local engine simply reports 'unknown-engine' and never+// admits a job, so this schema doesn't need to special-case it.export const federatedMediaProviderSettingsSchema = z.object({enabled: z.boolean().optional(),maxQueuedJobs: z.number().int().min(1).max(20).optional(),audioModels: federatedMediaModelListSchema.optional(),+ imageModels: federatedMediaModelListSchema.optional(),+ videoModels: federatedMediaModelListSchema.optional(),}).passthrough();// Consumer-side peer selection is independent from the provider's local queue@@ -729,6 +740,8 @@ export const federatedMediaProviderSettingsSchema = z.object({export const federatedMediaPeerSettingsSchema = z.object({enabled: z.boolean().optional(),audioModels: federatedMediaModelListSchema.optional(),+ imageModels: federatedMediaModelListSchema.optional(),+ videoModels: federatedMediaModelListSchema.optional(),}).passthrough();export const federationSettingsSchema = z.object({@@ -747,7 +760,8 @@ export const federatedMediaJobRoutingSchema = z.object({// 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({+const federatedMediaAudioJobSubmissionSchema = federatedMediaJobRoutingSchema.extend({+ kind: z.literal('audio'),prompt: z.string().trim().min(1).max(8000),lyrics: z.string().max(50_000).optional(),}).strict().superRefine((value, ctx) => {@@ -767,6 +781,56 @@ export const federatedMediaJobSubmissionSchema = federatedMediaJobRoutingSchema.}});+// Image/video prompts get no fixed-vocabulary rendering like audio's lyrics+// ban: there is no closed taxonomy for arbitrary visual/motion content the+// way audio has a finite style/mood/instrument alphabet, and a federation+// peer is an authenticated, explicitly-registered instance (typically the+// same user's own other machine) rather than an anonymous third party. The+// PII line this project actually draws is status/capability payloads never+// carrying prompt or record content (see the acceptance criteria on #4348) —+// a submitted job body is not a status payload. Local input assets (init/+// reference images, LoRAs) stay out of scope for this slice; see the PR body.+const federatedMediaImageJobSubmissionSchema = federatedMediaJobRoutingSchema.omit({+ durationSec: true, durationMode: true,+}).extend({+ kind: z.literal('image'),+ prompt: z.string().trim().min(1).max(4000),+ negativePrompt: z.string().trim().max(4000).optional(),+ width: z.number().int().min(64).max(4096).optional(),+ height: z.number().int().min(64).max(4096).optional(),+ steps: z.number().int().min(1).max(150).optional(),+ guidance: z.number().finite().min(0).max(30).optional(),+ seed: z.number().int().min(0).optional(),+}).strict();++const federatedMediaVideoJobSubmissionSchema = federatedMediaJobRoutingSchema.omit({+ durationSec: true, durationMode: true,+}).extend({+ kind: z.literal('video'),+ prompt: z.string().trim().min(1).max(4000),+ negativePrompt: z.string().trim().max(4000).optional(),+ width: z.number().int().min(64).max(2048).optional(),+ height: z.number().int().min(64).max(2048).optional(),+ numFrames: z.number().int().min(1).max(600).optional(),+ fps: z.number().int().min(1).max(60).optional(),+ steps: z.number().int().min(1).max(150).optional(),+ guidance: z.number().finite().min(0).max(30).optional(),+ seed: z.number().int().min(0).optional(),+}).strict();++// An already-shipped consumer's request body never carries `kind` — it only+// knows the pre-existing audio-only shape. Defaulting the missing field to+// 'audio' before the discriminated union runs keeps that body validating+// exactly as before; a new consumer names its kind explicitly.+export const federatedMediaJobSubmissionSchema = z.preprocess(+ (value) => (isPlainObject(value) && value.kind === undefined ? { ...value, kind: 'audio' } : value),+ z.discriminatedUnion('kind', [+ federatedMediaAudioJobSubmissionSchema,+ federatedMediaImageJobSubmissionSchema,+ federatedMediaVideoJobSubmissionSchema,+ ]),+);+export const federatedMediaIdempotencyKeySchema = z.string().trim().min(1).max(200).regex(/^[A-Za-z0-9._:-]+$/, 'Idempotency-Key contains unsupported characters');@@ -774,6 +838,10 @@ export const federatedMediaJobParamsSchema = z.object({id: z.string().uuid(),}).strict();+export const federatedMediaStatusQuerySchema = z.object({+ kinds: z.string().trim().max(40).regex(/^[a-z]+(,[a-z]+)*$/).optional(),+}).passthrough();+// Creative Director settings slice. Each LLM-backed stage can pin its own// provider/model instead of inheriting the system default. `evaluation` is a// direct vision API call (blank = auto-pick a local vision model, else falldiff --git a/server/routes/federatedMedia.js b/server/routes/federatedMedia.jsindex 337c6ee147..22f104285b 100644--- a/server/routes/federatedMedia.js+++ b/server/routes/federatedMedia.js@@ -9,8 +9,10 @@ import {federatedMediaIdempotencyKeySchema,federatedMediaJobParamsSchema,federatedMediaJobSubmissionSchema,+ federatedMediaStatusQuerySchema,validateRequest,} from '../lib/validation.js';+import { FEDERATED_MEDIA_RESULT_EXTENSION, normalizeRequestedMediaKinds } from '../lib/federatedMediaWire.js';import {authorizeFederatedMediaPeer,cancelFederatedMediaJob,@@ -24,7 +26,9 @@ const router = Router();router.get('/status', asyncHandler(async (req, res) => {const { config } = await authorizeFederatedMediaPeer(req);- res.json(await getFederatedMediaProviderStatus(config));+ const { kinds: kindsParam } = validateRequest(federatedMediaStatusQuerySchema, req.query);+ const kinds = normalizeRequestedMediaKinds(kindsParam);+ res.json(await getFederatedMediaProviderStatus(config, { kinds }));}));router.post('/jobs', asyncHandler(async (req, res) => {@@ -54,9 +58,10 @@ router.get('/jobs/:id/result', asyncHandler(async (req, res, next) => {const { callerId } = await authorizeFederatedMediaPeer(req);const { id } = validateRequest(federatedMediaJobParamsSchema, req.params);const result = await getFederatedMediaResult(callerId, id);+ const extension = FEDERATED_MEDIA_RESULT_EXTENSION[result.metadata.mimeType] || 'bin';res.set({'Cache-Control': 'private, no-store',- 'Content-Disposition': `attachment; filename="${id}.wav"`,+ 'Content-Disposition': `attachment; filename="${id}.${extension}"`,'Content-Length': String(result.metadata.sizeBytes),'Content-Type': result.metadata.mimeType,'X-Content-SHA256': result.metadata.sha256,diff --git a/server/routes/federatedMedia.test.js b/server/routes/federatedMedia.test.jsindex 5041a5d75b..2e5ed5fb9f 100644--- a/server/routes/federatedMedia.test.js+++ b/server/routes/federatedMedia.test.js@@ -79,7 +79,7 @@ describe('federated media routes', () => {.set('Idempotency-Key', 'commission-1').send(body);expect(created.status).toBe(202);expect(provider.submit).toHaveBeenCalledWith(expect.objectContaining({- callerId: 'peer-example', idempotencyKey: 'commission-1', input: body,+ callerId: 'peer-example', idempotencyKey: 'commission-1', input: { ...body, kind: 'audio' },}));provider.replayed = true;@@ -120,4 +120,52 @@ describe('federated media routes', () => {expect(response.headers['x-content-sha256']).toBe('a'.repeat(64));expect(response.headers['content-disposition']).toContain(`${jobId}.wav`);});++ it('serves an image result under its own filename extension', async () => {+ provider.result.mockResolvedValueOnce({+ path: provider.resultPath,+ metadata: { mimeType: 'image/png', sizeBytes: 4, sha256: 'b'.repeat(64) },+ });+ const response = await request(buildApp()).get(`/api/federation/media/v1/jobs/${jobId}/result`);+ expect(response.headers['content-type']).toContain('image/png');+ expect(response.headers['content-disposition']).toContain(`${jobId}.png`);+ });++ it('defaults GET /status to the audio-only kinds an unopted-in caller understands', async () => {+ await request(buildApp()).get('/api/federation/media/v1/status');+ expect(provider.status).toHaveBeenCalledWith(expect.anything(), { kinds: ['audio'] });+ });++ it('parses an explicit ?kinds= request into the known-kind subset', async () => {+ await request(buildApp()).get('/api/federation/media/v1/status?kinds=audio,image,holo');+ expect(provider.status).toHaveBeenCalledWith(expect.anything(), { kinds: ['audio', 'image'] });+ });++ it('defaults a kind-less submission to audio so an older consumer body keeps working', async () => {+ const body = { engine: 'minimax-music3', modelId: 'minimax-music3', prompt: safePrompt };+ await request(buildApp()).post('/api/federation/media/v1/jobs')+ .set('Idempotency-Key', 'commission-legacy').send(body);+ expect(provider.submit).toHaveBeenCalledWith(expect.objectContaining({+ input: expect.objectContaining({ kind: 'audio' }),+ }));+ });++ it('accepts an explicit image job submission', async () => {+ const body = { kind: 'image', engine: 'local', modelId: 'flux-dev', prompt: 'a lighthouse at dawn' };+ const response = await request(buildApp()).post('/api/federation/media/v1/jobs')+ .set('Idempotency-Key', 'commission-image').send(body);+ expect(response.status).toBe(202);+ expect(provider.submit).toHaveBeenCalledWith(expect.objectContaining({+ input: expect.objectContaining({ kind: 'image', prompt: 'a lighthouse at dawn' }),+ }));+ });++ it('rejects an image submission carrying audio-only fields', async () => {+ const response = await request(buildApp()).post('/api/federation/media/v1/jobs')+ .set('Idempotency-Key', 'commission-image-bad').send({+ kind: 'image', engine: 'local', modelId: 'flux-dev', prompt: 'a lighthouse at dawn', lyrics: 'nope',+ });+ expect(response.status).toBe(400);+ expect(provider.submit).not.toHaveBeenCalled();+ });});diff --git a/server/services/federatedMediaConsumer.js b/server/services/federatedMediaConsumer.jsindex 580207b4a5..0e99733bfb 100644--- a/server/services/federatedMediaConsumer.js+++ b/server/services/federatedMediaConsumer.js@@ -9,6 +9,7 @@ import { ServerError } from '../lib/errorHandler.js';import {federatedMediaProviderStatusSchema,inspectFederatedMediaStatusFreshness,+ KNOWN_MEDIA_KINDS,} from '../lib/federatedMediaWire.js';import { peerFetch } from '../lib/peerHttpClient.js';import { peerBaseUrl } from '../lib/peerUrl.js';@@ -17,6 +18,8 @@ import { readResponseJson } from '../lib/readResponseJson.js';export const DEFAULT_FEDERATED_MEDIA_PEER_CONFIG = Object.freeze({enabled: false,audioModels: Object.freeze([]),+ imageModels: Object.freeze([]),+ videoModels: Object.freeze([]),});const isRecord = (value) => value && typeof value === 'object' && !Array.isArray(value);@@ -43,11 +46,13 @@ function sanitizeModels(models, { preserveUnknown = false } = {}) {export function normalizePeerMediaProviderConfig(peer) {const raw = peer?.mediaProvider;if (!isRecord(raw)) {- return { ...DEFAULT_FEDERATED_MEDIA_PEER_CONFIG, audioModels: [] };+ return { ...DEFAULT_FEDERATED_MEDIA_PEER_CONFIG, audioModels: [], imageModels: [], videoModels: [] };}return {enabled: raw.enabled === true,audioModels: sanitizeModels(raw.audioModels),+ imageModels: sanitizeModels(raw.imageModels),+ videoModels: sanitizeModels(raw.videoModels),};}@@ -64,6 +69,8 @@ export function mergePeerMediaProviderConfig(current, patch) {...merged,enabled: merged.enabled === true,audioModels: sanitizeModels(merged.audioModels, { preserveUnknown: true }),+ imageModels: sanitizeModels(merged.imageModels, { preserveUnknown: true }),+ videoModels: sanitizeModels(merged.videoModels, { preserveUnknown: true }),};}@@ -83,6 +90,24 @@ function responseState(response, body) {return ['unavailable', body?.code || `http-${response.status || 'error'}`];}+// Only ask the peer for kinds this install actually has models allowlisted+// for. Keep the request byte-identical to the original audio-only endpoint+// (no query string) when nothing beyond audio is configured — this is the+// consumer half of the same opt-in negotiation described in+// normalizeRequestedMediaKinds (federatedMediaWire.js): a peer that has only+// ever spoken wire-v1 audio never has to learn about the query param at all.+function requestedKinds(config) {+ const kinds = KNOWN_MEDIA_KINDS.filter((kind) => config[`${kind}Models`]?.length > 0);+ return kinds.length ? kinds : ['audio'];+}++function statusUrl(peer, config) {+ const base = `${peerBaseUrl(peer)}/api/federation/media/v1/status`;+ const kinds = requestedKinds(config);+ if (kinds.length === 1 && kinds[0] === 'audio') return base;+ return `${base}?kinds=${kinds.join(',')}`;+}+/*** Fetch and sanitize one opted-in peer's live status. All failures become a* typed local projection instead of escaping into the background probe loop.@@ -92,7 +117,7 @@ export async function probeFederatedMediaProvider(peer, { signal, now = Date.nowif (!config.enabled) return probeResult(now, 'disabled', 'not-configured');const outcome = await peerFetch(- `${peerBaseUrl(peer)}/api/federation/media/v1/status`,+ statusUrl(peer, config),{ signal },peer,).then((response) => ({ response }), (error) => ({ error }));@@ -147,12 +172,14 @@ export function assertFederatedMediaProviderSelection(peer, selection, probe, {if (!config.enabled) {rejectSelection('Peer is not enabled as a media provider', 'MEDIA_PROVIDER_NOT_CONFIGURED', 409);}- if (selection?.kind !== 'audio' || typeof selection.engine !== 'string' || typeof selection.modelId !== 'string') {- rejectSelection('Only an explicit audio engine and model can be selected', 'MEDIA_PROVIDER_SELECTION_INVALID', 400);+ if (!KNOWN_MEDIA_KINDS.includes(selection?.kind)+ || typeof selection.engine !== 'string' || typeof selection.modelId !== 'string') {+ rejectSelection('Only an explicit media kind, engine, and model can be selected', 'MEDIA_PROVIDER_SELECTION_INVALID', 400);}const requested = { engine: selection.engine.trim(), modelId: selection.modelId.trim() };+ const allowlist = config[`${selection.kind}Models`] || [];if (!requested.engine || !requested.modelId- || !config.audioModels.some((model) => modelKey(model) === modelKey(requested))) {+ || !allowlist.some((model) => modelKey(model) === modelKey(requested))) {rejectSelection('Requested model is not allowlisted for this peer', 'MEDIA_PROVIDER_MODEL_NOT_ALLOWED', 403);}@@ -185,7 +212,7 @@ export function assertFederatedMediaProviderSelection(peer, selection, probe, {}const capability = snapshot.capabilities.find((candidate) =>- candidate.kind === 'audio'+ candidate.kind === selection.kind&& candidate.engine === requested.engine&& candidate.modelId === requested.modelId,);diff --git a/server/services/federatedMediaConsumer.test.js b/server/services/federatedMediaConsumer.test.jsindex 1786deb91e..a8c707428d 100644--- a/server/services/federatedMediaConsumer.test.js+++ b/server/services/federatedMediaConsumer.test.js@@ -79,7 +79,9 @@ beforeEach(() => {describe('federated media consumer configuration', () => {it('defaults old peer records to disabled with no allowlisted models', () => {- expect(normalizePeerMediaProviderConfig({})).toEqual({ enabled: false, audioModels: [] });+ expect(normalizePeerMediaProviderConfig({})).toEqual({+ enabled: false, audioModels: [], imageModels: [], videoModels: [],+ });});it('preserves future config/model fields while normalizing and de-duplicating known pairs', () => {@@ -98,6 +100,8 @@ describe('federated media consumer configuration', () => {enabled: true,future: 'keep',audioModels: [{ engine: 'minimax-music3', modelId: 'minimax-music3', futureModel: 'keep-too' }],+ imageModels: [],+ videoModels: [],});});@@ -154,10 +158,10 @@ describe('federated media provider discovery', () => {});});- it('rejects future media kinds against the audio-only wire-v1 shape', async () => {+ it('rejects a media kind outside the known wire-v1 alphabet', async () => {const futureStatus = readyStatus({- kinds: ['image'],- capabilities: [{ ...readyStatus().capabilities[0], kind: 'image' }],+ kinds: ['holo'],+ capabilities: [{ ...readyStatus().capabilities[0], kind: 'holo' }],});peerFetch.mockResolvedValue(response(futureStatus));@@ -167,6 +171,31 @@ describe('federated media provider discovery', () => {snapshot: null,});});++ it('only asks a peer for image/video status once this install allowlists a model for that kind', async () => {+ peerFetch.mockResolvedValue(response(readyStatus()));++ await probeFederatedMediaProvider(peer(), { now: NOW });+ expect(peerFetch).toHaveBeenLastCalledWith(+ 'http://192.0.2.10:5555/api/federation/media/v1/status',+ { signal: undefined },+ expect.anything(),+ );++ const withImage = peer({+ mediaProvider: {+ enabled: true,+ audioModels: [],+ imageModels: [{ engine: 'local', modelId: 'flux-dev' }],+ },+ });+ await probeFederatedMediaProvider(withImage, { now: NOW });+ expect(peerFetch).toHaveBeenLastCalledWith(+ 'http://192.0.2.10:5555/api/federation/media/v1/status?kinds=image',+ { signal: undefined },+ expect.anything(),+ );+ });});describe('federated media provider selection', () => {@@ -224,4 +253,26 @@ describe('federated media provider selection', () => {context: { reason: 'invalid-wire-response' },}));});++ it('keeps each media kind on its own allowlist — an audio-only peer cannot be selected for image', () => {+ const probe = { state: 'ready', reason: null, snapshot: readyStatus() };+ expect(() => assertFederatedMediaProviderSelection(+ peer(), { kind: 'image', engine: 'local', modelId: 'flux-dev' }, probe, { now: NOW },+ )).toThrow(expect.objectContaining({ code: 'MEDIA_PROVIDER_MODEL_NOT_ALLOWED', status: 403 }));+ });++ it('resolves an allowlisted image model against an image capability', () => {+ const imageSelection = { kind: 'image', engine: 'local', modelId: 'flux-dev' };+ const configured = peer({+ mediaProvider: { enabled: true, audioModels: [], imageModels: [{ engine: 'local', modelId: 'flux-dev' }] },+ });+ const status = readyStatus({+ kinds: ['image'],+ capabilities: [{ ...readyStatus().capabilities[0], kind: 'image', engine: 'local', modelId: 'flux-dev' }],+ });+ const probe = { state: 'ready', reason: null, snapshot: status };++ const resolved = assertFederatedMediaProviderSelection(configured, imageSelection, probe, { now: NOW });+ expect(resolved.capability).toMatchObject(imageSelection);+ });});diff --git a/server/services/federatedMediaProvider.js b/server/services/federatedMediaProvider.jsindex 1697d6fbdc..ce28698f06 100644--- a/server/services/federatedMediaProvider.js+++ b/server/services/federatedMediaProvider.js@@ -11,10 +11,16 @@ import { stat } from 'node:fs/promises';import { ServerError } from '../lib/errorHandler.js';import { createMutex } from '../lib/asyncMutex.js';import { canonicalStringify } from '../lib/objects.js';-import { PATHS, makePathResolver, sha256File, sha256Text } from '../lib/fileUtils.js';import {+ PATHS, makePathResolver, resolveGalleryImage, sha256File, sha256Text,+} from '../lib/fileUtils.js';+import { inspectModelCache } from '../lib/hfCache.js';+import { getImageModels, getVideoModels, repoForModel } from '../lib/mediaModels.js';+import {+ FEDERATED_MEDIA_RESULT_EXTENSION,FEDERATED_MEDIA_STALE_AFTER_MS,FEDERATED_MEDIA_WIRE_VERSION,+ KNOWN_MEDIA_KINDS,} from '../lib/federatedMediaWire.js';import { getSettings } from './settings.js';import {@@ -33,6 +39,8 @@ export const DEFAULT_FEDERATED_MEDIA_PROVIDER = Object.freeze({enabled: false,maxQueuedJobs: 2,audioModels: Object.freeze([]),+ imageModels: Object.freeze([]),+ videoModels: Object.freeze([]),});const ACTIVE_STATUSES = new Set(['queued', 'running']);@@ -47,10 +55,17 @@ const unavailable = (message, code, status = 503, context) => {throw new ServerError(message, { status, code, ...(context ? { context } : {}) });};+const sanitizeModelList = (models) => (Array.isArray(models)+ ? models+ .filter((model) => model && typeof model === 'object' && !Array.isArray(model))+ .map(({ engine, modelId }) => ({ engine, modelId }))+ .filter(({ engine, modelId }) => typeof engine === 'string' && typeof modelId === 'string')+ : []);+export function normalizeFederatedMediaProviderConfig(settings) {const raw = settings?.federation?.mediaProvider;if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {- return { ...DEFAULT_FEDERATED_MEDIA_PROVIDER, audioModels: [] };+ return { ...DEFAULT_FEDERATED_MEDIA_PROVIDER, audioModels: [], imageModels: [], videoModels: [] };}return {...raw,@@ -58,12 +73,9 @@ export function normalizeFederatedMediaProviderConfig(settings) {maxQueuedJobs: Number.isInteger(raw.maxQueuedJobs)? Math.max(1, Math.min(20, raw.maxQueuedJobs)): DEFAULT_FEDERATED_MEDIA_PROVIDER.maxQueuedJobs,- audioModels: Array.isArray(raw.audioModels)- ? raw.audioModels- .filter((model) => model && typeof model === 'object' && !Array.isArray(model))- .map(({ engine, modelId }) => ({ engine, modelId }))- .filter(({ engine, modelId }) => typeof engine === 'string' && typeof modelId === 'string')- : [],+ audioModels: sanitizeModelList(raw.audioModels),+ imageModels: sanitizeModelList(raw.imageModels),+ videoModels: sanitizeModelList(raw.videoModels),};}@@ -139,6 +151,86 @@ async function configuredAudioCapabilities(config) {});}+// Local image/video generation (mflux on Apple Silicon, diffusers elsewhere)+// has no per-engine CUDA/platform registry like music's ENGINES map — it's one+// shared runtime gated on a single configured pythonPath, with per-model+// readiness coming from the same HF-cache check music capabilities use.+// Reported as platformSupported/cudaRequired: false rather than omitting+// those fields, so this stays a single capability shape the wire schema+// already validates instead of forking a second one per kind.+//+// `runtimeReady` here means "a local pythonPath is configured," not+// "verified importable" — music's isEngineHealthy() and image regen's+// resolveRegenBackend() (server/services/imageGen/regen.js) both go further+// and probe the actual mflux binary / FLUX.2 venv per model family. Matching+// that depth for every image/video model family (mflux vs FLUX.2 vs the+// diffusers runners, plus per-runtime BYOV video probes) is real scope, not a+// cleanup — left as follow-up work; a submission that clears this coarser+// admission check still fails safely if the runtime turns out missing, since+// the local generator itself errors and fails the queued job.+async function localGeneratorCapabilities(kind, pythonPath, { models, configuredList }) {+ const modelsById = new Map(models.map((model) => [model.id, model]));+ return Promise.all(configuredList.map(async (selected) => {+ const isLocal = selected.engine === 'local';+ const model = isLocal ? modelsById.get(selected.modelId) : null;+ const repo = model ? repoForModel(model) : null;+ const modelReady = !model ? false+ : !repo ? true+ : (await inspectModelCache(repo).catch(() => ({ cached: false }))).cached === true;+ const reason = !isLocal ? 'unknown-engine'+ : !pythonPath ? 'runtime-unavailable'+ : !model ? 'unknown-model'+ : !modelReady ? 'model-unavailable'+ : null;+ return {+ kind,+ engine: selected.engine,+ engineName: isLocal ? 'Local' : selected.engine,+ modelId: selected.modelId,+ modelName: model?.name ?? selected.modelId,+ ready: reason === null,+ unavailableReason: reason,+ runtimeReady: isLocal && !!pythonPath,+ platformSupported: isLocal,+ cudaRequired: false,+ cudaState: 'available',+ minDurationSec: null,+ maxDurationSec: null,+ defaultDurationSec: null,+ lyrics: false,+ autoDuration: false,+ _pythonPath: isLocal ? pythonPath : null,+ _model: model,+ };+ }));+}++const configuredImageCapabilities = (pythonPath, config) => localGeneratorCapabilities('image', pythonPath, {+ models: getImageModels(), configuredList: config.imageModels,+});++const configuredVideoCapabilities = (pythonPath, config) => localGeneratorCapabilities('video', pythonPath, {+ models: getVideoModels(), configuredList: config.videoModels,+});++// Local image/video readiness shares one settings field+// (imageGen.local.pythonPath — video local generation reuses the same+// Python venv). Resolve it once per top-level call rather than once per+// requested kind, so asking for both image and video status in one request+// doesn't fetch+clone the full settings object twice.+async function resolveLocalRuntimePythonPath(kinds) {+ if (!kinds.some((kind) => kind === 'image' || kind === 'video')) return null;+ const settings = await getSettings();+ return settings?.imageGen?.local?.pythonPath || null;+}++async function capabilitiesForKind(kind, config, { pythonPath = null } = {}) {+ if (kind === 'audio') return configuredAudioCapabilities(config);+ if (kind === 'image') return configuredImageCapabilities(pythonPath, config);+ if (kind === 'video') return configuredVideoCapabilities(pythonPath, config);+ return [];+}+function activeQueueSnapshot(config) {// Outgoing proxy jobs consume a remote peer's capacity, not this provider's// local generation resources. Counting them here can create a federation@@ -158,10 +250,22 @@ function activeQueueSnapshot(config) {};}-const publicCapability = ({ _engine, _model, ...capability }) => capability;+// Strip every private (`_`-prefixed) helper field before a capability crosses+// the wire — `_engine`/`_model` (audio) and `_pythonPath`/`_model` (image/+// video) all carry local runtime state, never public capability data.+const publicCapability = (capability) => Object.fromEntries(+ Object.entries(capability).filter(([key]) => !key.startsWith('_')),+);-export async function getFederatedMediaProviderStatus(config) {- const capabilities = await configuredAudioCapabilities(config);+// `kinds` defaults to audio-only so a caller that never opts in (every+// already-shipped consumer) gets back the exact status shape it has always+// understood — see normalizeRequestedMediaKinds in federatedMediaWire.js.+export async function getFederatedMediaProviderStatus(config, { kinds = ['audio'] } = {}) {+ const requestedKinds = kinds.filter((kind) => KNOWN_MEDIA_KINDS.includes(kind));+ const pythonPath = await resolveLocalRuntimePythonPath(requestedKinds);+ const capabilities = (await Promise.all(+ requestedKinds.map((kind) => capabilitiesForKind(kind, config, { pythonPath })),+ )).flat();const queue = activeQueueSnapshot(config);const anyReady = capabilities.some((capability) => capability.ready);return {@@ -169,7 +273,7 @@ export async function getFederatedMediaProviderStatus(config) {generatedAt: new Date().toISOString(),staleAfterMs: FEDERATED_MEDIA_STALE_AFTER_MS,status: !anyReady ? 'unavailable' : (queue.accepting ? 'ready' : 'busy'),- kinds: ['audio'],+ kinds: requestedKinds,queue,capabilities: capabilities.map(publicCapability),};@@ -195,17 +299,35 @@ function findIdempotentJob(callerId, idempotencyKey) {) || null;}+// Image/video results are named `<queue-job-uuid>.<ext>` by the local+// generator itself (jobId: job.id passed straight through, same as audio's+// music-gen-<uuid>.wav). Bind the provider only to that shape, not to+// job.id specifically — mirrors MUSIC_RESULT_RE's leniency. Each kind gets+// its own anchored extension (not one pattern shared across png/mp4) so a+// hand-edited job.kind/result.filename mismatch can't pass the check and+// get served under the wrong Content-Type.+const IMAGE_RESULT_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.png$/i;+const VIDEO_RESULT_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.mp4$/i;+const resolveVideoResult = makePathResolver(() => PATHS.videos, { extensions: ['mp4'] });++const RESULT_BY_KIND = {+ audio: { mimeType: 'audio/wav', pattern: MUSIC_RESULT_RE, resolve: resolveMusicResult },+ image: { mimeType: 'image/png', pattern: IMAGE_RESULT_RE, resolve: resolveGalleryImage },+ video: { mimeType: 'video/mp4', pattern: VIDEO_RESULT_RE, resolve: resolveVideoResult },+};+async function describeResult(job) {if (job.status !== 'completed') return null;+ const shape = RESULT_BY_KIND[job.kind] || RESULT_BY_KIND.audio;const filename = job.result?.filename;// The queue record is persisted and therefore could be hand-edited. Bind a- // provider job only to the filename shape generateMusic itself creates;+ // provider job only to the filename shape its own generator creates;// makePathResolver confines the root, while this prevents cross-job file// substitution inside that root.- if (typeof filename !== 'string' || !MUSIC_RESULT_RE.test(filename)) {+ if (typeof filename !== 'string' || !shape.pattern.test(filename)) {unavailable('Provider result is unavailable', 'MEDIA_PROVIDER_RESULT_UNAVAILABLE', 410);}- const path = resolveMusicResult(filename);+ const path = shape.resolve(filename);if (!path) {unavailable('Provider result is unavailable', 'MEDIA_PROVIDER_RESULT_UNAVAILABLE', 410);}@@ -228,7 +350,7 @@ async function describeResult(job) {return {metadata: {available: true,- mimeType: 'audio/wav',+ mimeType: shape.mimeType,sizeBytes: info.size,sha256,downloadUrl: `/api/federation/media/v1/jobs/${job.id}/result`,@@ -249,7 +371,7 @@ export async function describeFederatedMediaJob(callerId, jobOrId) {return {wireVersion: FEDERATED_MEDIA_WIRE_VERSION,id: job.id,- kind: 'audio',+ kind: job.kind,status: job.status,queuedAt: job.queuedAt,startedAt: job.startedAt ?? null,@@ -281,7 +403,8 @@ export async function submitFederatedMediaJob({ callerId, config, input, idempot});}- const capabilities = await configuredAudioCapabilities(config);+ const pythonPath = await resolveLocalRuntimePythonPath([input.kind]);+ const capabilities = await capabilitiesForKind(input.kind, config, { pythonPath });const capability = capabilities.find((candidate) =>candidate.engine === input.engine && candidate.modelId === input.modelId,);@@ -304,24 +427,16 @@ export async function submitFederatedMediaJob({ callerId, config, input, idempot});}+ const federatedMedia = {+ wireVersion: FEDERATED_MEDIA_WIRE_VERSION,+ callerInstanceId: callerId,+ idempotencyKey,+ requestHash,+ };const queued = enqueueJob({- kind: 'audio',+ kind: input.kind,owner: jobOwner(callerId),- params: {- prompt: input.prompt,- lyrics: input.lyrics,- engine: input.engine,- modelId: input.modelId,- ...(capability._model?.userAdded ? { repo: capability._model.repo } : {}),- ...(input.durationSec !== undefined ? { durationSec: input.durationSec } : {}),- ...(input.durationMode ? { durationMode: input.durationMode } : {}),- federatedMedia: {- wireVersion: FEDERATED_MEDIA_WIRE_VERSION,- callerInstanceId: callerId,- idempotencyKey,- requestHash,- },- },+ params: buildQueueParams(input, capability, federatedMedia),});return {replayed: false,@@ -330,6 +445,51 @@ export async function submitFederatedMediaJob({ callerId, config, input, idempot});}+// Per-kind mapping from the validated wire submission to the *local*+// mediaJobQueue params the matching runner module expects — audio's shape+// (engine/modelId/prompt/lyrics/duration) already matched generateMusic's+// contract; image/video map onto imageGen/local.js's generateImage and+// videoGen/local.js's generateVideo signatures. Omitting `mode` from the+// image/video params keeps the queue's dispatcher on the local runner (see+// getGenModuleForJob in mediaJobQueue/index.js): only the cloud-CLI modes+// (codex/grok/agy) need an explicit mode, and those aren't federatable here.+function buildQueueParams(input, capability, federatedMedia) {+ if (input.kind === 'audio') {+ return {+ prompt: input.prompt,+ lyrics: input.lyrics,+ engine: input.engine,+ modelId: input.modelId,+ ...(capability._model?.userAdded ? { repo: capability._model.repo } : {}),+ ...(input.durationSec !== undefined ? { durationSec: input.durationSec } : {}),+ ...(input.durationMode ? { durationMode: input.durationMode } : {}),+ federatedMedia,+ };+ }+ const shared = {+ pythonPath: capability._pythonPath,+ prompt: input.prompt,+ modelId: input.modelId,+ ...(input.negativePrompt ? { negativePrompt: input.negativePrompt } : {}),+ ...(input.width !== undefined ? { width: input.width } : {}),+ ...(input.height !== undefined ? { height: input.height } : {}),+ ...(input.steps !== undefined ? { steps: input.steps } : {}),+ ...(input.seed !== undefined ? { seed: input.seed } : {}),+ federatedMedia,+ };+ if (input.kind === 'image') {+ return { ...shared, ...(input.guidance !== undefined ? { guidance: input.guidance } : {}) };+ }+ // video — videoGen/local.js's generateVideo takes `guidanceScale`, not+ // `guidance` (image's field name).+ return {+ ...shared,+ ...(input.numFrames !== undefined ? { numFrames: input.numFrames } : {}),+ ...(input.fps !== undefined ? { fps: input.fps } : {}),+ ...(input.guidance !== undefined ? { guidanceScale: input.guidance } : {}),+ };+}+export async function cancelFederatedMediaJob(callerId, jobId) {lookupCallerJob(callerId, jobId);const outcome = await cancelJob(jobId);diff --git a/server/services/federatedMediaProvider.test.js b/server/services/federatedMediaProvider.test.jsindex 670b3cdfce..6a701f2f8b 100644--- a/server/services/federatedMediaProvider.test.js+++ b/server/services/federatedMediaProvider.test.js@@ -10,12 +10,25 @@ const state = vi.hoisted(() => ({nextId: 1,capabilities: { engines: [], defaultEngine: 'musicgen' },cancelResult: { ok: true, status: 'canceled' },+ imageModels: [],+ videoModels: [],+ cachedRepos: new Set(),}));vi.mock('./settings.js', () => ({getSettings: vi.fn(async () => state.settings),}));+vi.mock('../lib/mediaModels.js', () => ({+ getImageModels: vi.fn(() => state.imageModels),+ getVideoModels: vi.fn(() => state.videoModels),+ repoForModel: (model) => model?.repo ?? null,+}));++vi.mock('../lib/hfCache.js', () => ({+ inspectModelCache: vi.fn(async (repo) => ({ cached: state.cachedRepos.has(repo) })),+}));+vi.mock('./sharing/peerPullAuthorization.js', () => ({readCallerInstanceId: (req) => req.headers?.['x-portos-instance-id'] || null,}));@@ -64,23 +77,37 @@ import { enqueueJob } from './mediaJobQueue/index.js';import { PATHS, sha256Text } from '../lib/fileUtils.js';const originalMusicPath = PATHS.music;+const originalImagesPath = PATHS.images;+const originalVideosPath = PATHS.videos;let tempMusicPath;+let tempImagesPath;+let tempVideosPath;beforeAll(() => {tempMusicPath = mkdtempSync(join(tmpdir(), 'portos-federated-media-service-'));+ tempImagesPath = mkdtempSync(join(tmpdir(), 'portos-federated-media-images-'));+ tempVideosPath = mkdtempSync(join(tmpdir(), 'portos-federated-media-videos-'));PATHS.music = tempMusicPath;+ PATHS.images = tempImagesPath;+ PATHS.videos = tempVideosPath;});afterAll(() => {PATHS.music = originalMusicPath;+ PATHS.images = originalImagesPath;+ PATHS.videos = originalVideosPath;rmSync(tempMusicPath, { recursive: true, force: true });+ rmSync(tempImagesPath, { recursive: true, force: true });+ rmSync(tempVideosPath, { recursive: true, force: true });});const selection = { engine: 'minimax-music3', modelId: 'minimax-music3' };-const config = () => ({ enabled: true, maxQueuedJobs: 2, audioModels: [selection] });+const config = () => ({+ enabled: true, maxQueuedJobs: 2, audioModels: [selection], imageModels: [], videoModels: [],+});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' });+const input = () => ({ ...selection, kind: 'audio', prompt: SAFE_PROMPT, durationSec: 60, durationMode: 'manual' });function readyEngine(overrides = {}) {return {@@ -110,13 +137,16 @@ beforeEach(() => {state.nextId = 1;state.capabilities = { engines: [readyEngine()], defaultEngine: 'musicgen' };state.cancelResult = { ok: true, status: 'canceled' };+ state.imageModels = [];+ state.videoModels = [];+ state.cachedRepos = new Set();__resetFederatedMediaProviderForTests();});describe('federated media provider authorization', () => {it('defaults absent settings to disabled with conservative limits', () => {expect(normalizeFederatedMediaProviderConfig({})).toEqual({- enabled: false, maxQueuedJobs: 2, audioModels: [],+ enabled: false, maxQueuedJobs: 2, audioModels: [], imageModels: [], videoModels: [],});});@@ -284,3 +314,116 @@ describe('federated media provider capacity and idempotency', () => {});});});++describe('federated media provider — image/video kinds', () => {+ const imageSelection = { engine: 'local', modelId: 'flux-dev' };+ const imageConfig = () => ({+ enabled: true, maxQueuedJobs: 2, audioModels: [], imageModels: [imageSelection], videoModels: [],+ });+ const imageInput = () => ({+ ...imageSelection, kind: 'image', prompt: 'a lighthouse at dawn', width: 1024, height: 1024,+ });++ beforeEach(() => {+ state.imageModels = [{ id: 'flux-dev', name: 'FLUX.1 dev', repo: 'black-forest-labs/FLUX.1-dev' }];+ state.videoModels = [{ id: 'ltx2', name: 'LTX2', repo: 'example/ltx2' }];+ });++ it('reports an image capability unavailable when no local runtime is configured', async () => {+ state.settings = { federation: { mediaProvider: imageConfig() } };+ const status = await getFederatedMediaProviderStatus(imageConfig(), { kinds: ['image'] });+ expect(status.kinds).toEqual(['image']);+ expect(status.capabilities).toEqual([expect.objectContaining({+ kind: 'image', engine: 'local', modelId: 'flux-dev',+ ready: false, unavailableReason: 'runtime-unavailable',+ })]);+ expect(status.status).toBe('unavailable');+ });++ it('reports an image capability ready once the runtime and model weights are present', async () => {+ state.settings = {+ federation: { mediaProvider: imageConfig() },+ imageGen: { local: { pythonPath: '/usr/bin/python3' } },+ };+ state.cachedRepos = new Set(['black-forest-labs/FLUX.1-dev']);+ const status = await getFederatedMediaProviderStatus(imageConfig(), { kinds: ['image'] });+ expect(status.capabilities[0]).toMatchObject({ ready: true, unavailableReason: null });+ expect(status.status).toBe('ready');+ });++ it('does not report image/video capabilities unless the caller opts into that kind', async () => {+ state.settings = {+ federation: { mediaProvider: imageConfig() },+ imageGen: { local: { pythonPath: '/usr/bin/python3' } },+ };+ state.cachedRepos = new Set(['black-forest-labs/FLUX.1-dev']);+ const status = await getFederatedMediaProviderStatus(imageConfig());+ expect(status.kinds).toEqual(['audio']);+ expect(status.capabilities).toEqual([]);+ });++ it('rejects a configured non-local engine as unknown rather than admitting it', async () => {+ const nonLocalConfig = () => ({+ enabled: true, maxQueuedJobs: 2, audioModels: [], videoModels: [],+ imageModels: [{ engine: 'sdapi', modelId: 'flux-dev' }],+ });+ state.settings = { federation: { mediaProvider: nonLocalConfig() } };+ await expect(submitFederatedMediaJob({+ callerId: 'peer-example',+ config: nonLocalConfig(),+ input: { kind: 'image', engine: 'sdapi', modelId: 'flux-dev', prompt: 'a lighthouse at dawn' },+ idempotencyKey: 'commission-image-1',+ })).rejects.toMatchObject({ status: 503, code: 'MEDIA_PROVIDER_MODEL_UNAVAILABLE', context: { reason: 'unknown-engine' } });+ expect(enqueueJob).not.toHaveBeenCalled();+ });++ it('queues an allowlisted local image job with the local runner param shape', async () => {+ state.settings = {+ federation: { mediaProvider: imageConfig() },+ imageGen: { local: { pythonPath: '/usr/bin/python3' } },+ };+ state.cachedRepos = new Set(['black-forest-labs/FLUX.1-dev']);+ const result = await submitFederatedMediaJob({+ callerId: 'peer-example', config: imageConfig(), input: imageInput(), idempotencyKey: 'commission-image-2',+ });+ expect(result).toMatchObject({ replayed: false, job: { status: 'queued', kind: 'image' } });+ expect(enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'image',+ owner: 'federated-media:peer-example',+ params: expect.objectContaining({+ pythonPath: '/usr/bin/python3',+ prompt: 'a lighthouse at dawn',+ modelId: 'flux-dev',+ width: 1024,+ height: 1024,+ }),+ }));+ // Audio-only fields never leak into the image job's queue params.+ const [call] = enqueueJob.mock.calls;+ expect(call[0].params).not.toHaveProperty('lyrics');+ expect(call[0].params).not.toHaveProperty('durationSec');+ });++ it('describes a completed image result with an image/png projection', async () => {+ state.settings = {+ federation: { mediaProvider: imageConfig() },+ imageGen: { local: { pythonPath: '/usr/bin/python3' } },+ };+ state.cachedRepos = new Set(['black-forest-labs/FLUX.1-dev']);+ const created = await submitFederatedMediaJob({+ callerId: 'peer-example', config: imageConfig(), input: imageInput(), idempotencyKey: 'commission-image-3',+ });+ const job = state.jobs.find((candidate) => candidate.id === created.job.id);+ const filename = `${job.id}.png`;+ const bytes = Buffer.from('fake-png-bytes');+ writeFileSync(join(tempImagesPath, filename), bytes);+ Object.assign(job, {+ status: 'completed', completedAt: '2026-08-16T00:02:00.000Z',+ result: { filename, engine: 'local', modelId: 'flux-dev' },+ });++ const described = await describeFederatedMediaJob('peer-example', job.id);+ expect(described.kind).toBe('image');+ expect(described.result).toMatchObject({ available: true, mimeType: 'image/png', sizeBytes: bytes.length });+ });+});diff --git a/server/services/instances.js b/server/services/instances.jsindex c93d3e75d1..301e08d059 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -407,7 +407,7 @@ export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, asyncCategories: { ...DEFAULT_SYNC_CATEGORIES },// Consumer-side routing is explicit and machine-local. Enabling a peer// here never changes that peer's provider settings.- mediaProvider: { enabled: false, audioModels: [] },+ mediaProvider: { enabled: false, audioModels: [], imageModels: [], videoModels: [] },consecutiveFailures: 0,nextProbeAt: null,directions: ['outbound']diff --git a/server/services/instances.test.js b/server/services/instances.test.jsindex 6486452897..c13d88660b 100644--- a/server/services/instances.test.js+++ b/server/services/instances.test.js@@ -599,6 +599,8 @@ describe('instances.js', () => {enabled: false,futureField: 'keep',audioModels: [{ engine: 'minimax-music3', modelId: 'minimax-music3', futureModel: 'keep-too' }],+ imageModels: [],+ videoModels: [],});expect(fetch).not.toHaveBeenCalled();});