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

fix(issue-4348): cross-field wire validation + capability gating for federated image/video jobs

[._.]/ Adam Eivy30bc23e4222e
diff --git a/server/lib/federatedMediaWire.js b/server/lib/federatedMediaWire.js
index 5e8526dfe5..98b9ceb2a9 100644
--- a/server/lib/federatedMediaWire.js
+++ b/server/lib/federatedMediaWire.js
@@ -119,6 +119,12 @@ export const FEDERATED_MEDIA_RESULT_EXTENSION = Object.freeze({
'video/mp4': 'mp4',
});
+const FEDERATED_MEDIA_RESULT_MIME = Object.freeze({
+ audio: 'audio/wav',
+ image: 'image/png',
+ video: 'video/mp4',
+});
+
const federatedMediaCapabilitySchema = z.object({
kind: mediaKindSchema,
engine: z.string().trim().min(1).max(80),
@@ -159,6 +165,20 @@ export const federatedMediaProviderStatusSchema = z.object({
kinds: z.array(mediaKindSchema).max(KNOWN_MEDIA_KINDS.length),
queue: federatedMediaQueueStatusSchema,
capabilities: z.array(federatedMediaCapabilitySchema).max(300),
+}).superRefine((value, ctx) => {
+ const kinds = new Set(value.kinds);
+ if (kinds.size !== value.kinds.length) {
+ ctx.addIssue({ code: 'custom', path: ['kinds'], message: 'kinds must not contain duplicates' });
+ }
+ value.capabilities.forEach((capability, index) => {
+ if (!kinds.has(capability.kind)) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['capabilities', index, 'kind'],
+ message: 'capability kind must be listed in kinds',
+ });
+ }
+ });
});
const federatedMediaResultSchema = z.object({
@@ -192,6 +212,14 @@ export const federatedMediaProviderJobSchema = z.object({
message: z.string().trim().min(1).max(500),
}).optional(),
result: federatedMediaResultSchema.optional(),
+}).superRefine((value, ctx) => {
+ if (value.result && value.result.mimeType !== FEDERATED_MEDIA_RESULT_MIME[value.kind]) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['result', 'mimeType'],
+ message: 'result mimeType must match the job kind',
+ });
+ }
});
/**
diff --git a/server/lib/federatedMediaWire.test.js b/server/lib/federatedMediaWire.test.js
index f2ba3bc92b..dbb0b83463 100644
--- a/server/lib/federatedMediaWire.test.js
+++ b/server/lib/federatedMediaWire.test.js
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import {
federatedMediaAudioProfileSchema,
+ federatedMediaProviderStatusSchema,
federatedMediaProviderJobSchema,
isFederatedMediaAudioPrompt,
normalizeRequestedMediaKinds,
@@ -62,10 +63,52 @@ describe('federated media provider job wire projection', () => {
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.
+ expect(federatedMediaProviderJobSchema.safeParse(job({
+ kind: 'image',
+ status: 'completed',
+ completedAt: '2026-08-17T12:01:00.000Z',
+ result: {
+ available: true,
+ mimeType: 'video/mp4',
+ sizeBytes: 10,
+ sha256: 'a'.repeat(64),
+ downloadUrl: '/result',
+ engine: 'local',
+ modelId: 'example/model',
+ durationSec: null,
+ },
+ })).success).toBe(false);
+ });
+});
+
+describe('federated media status kind projection', () => {
+ const status = (overrides = {}) => ({
+ wireVersion: 1,
+ generatedAt: '2026-08-17T12:00:00.000Z',
+ staleAfterMs: 60_000,
+ status: 'ready',
+ kinds: ['audio'],
+ queue: {
+ totalActive: 0,
+ providerActive: 0,
+ queued: 0,
+ running: 0,
+ maxQueuedJobs: 2,
+ accepting: true,
+ },
+ capabilities: [],
+ ...overrides,
+ });
+
+ it('rejects a capability kind omitted from the negotiated projection', () => {
+ expect(federatedMediaProviderStatusSchema.safeParse(status({
+ capabilities: [{
+ kind: 'image', engine: 'local', engineName: 'Local', modelId: 'example/model', modelName: 'Example',
+ ready: true, unavailableReason: null, runtimeReady: true, platformSupported: true,
+ cudaRequired: false, cudaState: 'available', minDurationSec: null, maxDurationSec: null,
+ defaultDurationSec: null, lyrics: false, autoDuration: false,
+ }],
+ })).success).toBe(false);
});
});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 0384382795..f503e61f61 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -796,12 +796,12 @@ const federatedMediaImageJobSubmissionSchema = federatedMediaJobRoutingSchema.om
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(),
+ width: imageEdgeSchema,
+ height: imageEdgeSchema,
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();
+}).strict().refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });
const federatedMediaVideoJobSubmissionSchema = federatedMediaJobRoutingSchema.omit({
durationSec: true, durationMode: true,
diff --git a/server/routes/federatedMedia.test.js b/server/routes/federatedMedia.test.js
index 2e5ed5fb9f..907e35ad5a 100644
--- a/server/routes/federatedMedia.test.js
+++ b/server/routes/federatedMedia.test.js
@@ -168,4 +168,14 @@ describe('federated media routes', () => {
expect(response.status).toBe(400);
expect(provider.submit).not.toHaveBeenCalled();
});
+
+ it('rejects an image submission over the shared pixel ceiling', async () => {
+ const response = await request(buildApp()).post('/api/federation/media/v1/jobs')
+ .set('Idempotency-Key', 'commission-image-too-large').send({
+ kind: 'image', engine: 'local', modelId: 'flux-dev', prompt: 'a lighthouse at dawn',
+ width: 4096, height: 4096,
+ });
+ expect(response.status).toBe(400);
+ expect(provider.submit).not.toHaveBeenCalled();
+ });
});
diff --git a/server/services/audioGen/remote.js b/server/services/audioGen/remote.js
index ff91d2f146..3f2d95ad24 100644
--- a/server/services/audioGen/remote.js
+++ b/server/services/audioGen/remote.js
@@ -156,7 +156,7 @@ async function requestJson(state, path, options = {}, requestOptions = {}) {
function parseProviderJob(body, expectedId) {
const parsed = federatedMediaProviderJobSchema.safeParse(body);
- if (!parsed.success || (expectedId && parsed.data.id !== expectedId)) {
+ if (!parsed.success || parsed.data.kind !== 'audio' || (expectedId && parsed.data.id !== expectedId)) {
throw remoteError('Remote media provider returned an invalid wire-v1 job projection', {
code: 'MEDIA_PROVIDER_INVALID_JOB_RESPONSE',
});
diff --git a/server/services/federatedMediaProvider.js b/server/services/federatedMediaProvider.js
index ce28698f06..51ff3b6815 100644
--- a/server/services/federatedMediaProvider.js
+++ b/server/services/federatedMediaProvider.js
@@ -14,8 +14,9 @@ import { canonicalStringify } from '../lib/objects.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 { findCachedRepoFiles, inspectModelCache } from '../lib/hfCache.js';
+import { getImageModels, getVideoModels, isEditOnly, isFlux2, repoForModel } from '../lib/mediaModels.js';
+import { isMiniMaxH3Runtime, usesDiffusersRunner } from '../lib/runners.js';
import {
FEDERATED_MEDIA_RESULT_EXTENSION,
FEDERATED_MEDIA_STALE_AFTER_MS,
@@ -31,6 +32,8 @@ import {
listJobs,
} from './mediaJobQueue/index.js';
import { listMusicEngineCapabilities } from './musicEngineCapabilities.js';
+import { BYOV_VIDEO_RUNTIMES, isByovRuntimeReady } from './videoGen/runtimes.js';
+import { minimaxH3ControlError } from './videoGen/minimaxH3Controls.js';
import { readCallerInstanceId } from './sharing/peerPullAuthorization.js';
import { findPeerById } from './sharing/peerSyncShared.js';
@@ -62,6 +65,79 @@ const sanitizeModelList = (models) => (Array.isArray(models)
.filter(({ engine, modelId }) => typeof engine === 'string' && typeof modelId === 'string')
: []);
+const requiresConfiguredPython = (kind, model) => {
+ if (kind === 'image') return !isFlux2(model) && !usesDiffusersRunner(model);
+ if (kind === 'video') return !BYOV_VIDEO_RUNTIMES.has(model?.runtime);
+ return false;
+};
+
+// The federated wire intentionally carries no source image, keyframes, or
+// semantic video mode. Do not advertise a catalog model that cannot render a
+// text-only request through this contract; otherwise the provider accepts the
+// job, persists it, and only rejects it after a worker starts.
+const supportsFederatedInput = (kind, model) => {
+ if (kind === 'image') return !isEditOnly(model);
+ if (kind === 'video') {
+ return !Array.isArray(model?.supportedModes) || model.supportedModes.includes('text');
+ }
+ return true;
+};
+
+const requiredModelCacheGroups = (model) => {
+ const groups = [];
+ if (Array.isArray(model?.repoFiles)) {
+ groups.push({ repo: model.repo, revision: model.revision, files: model.repoFiles });
+ }
+ if (Array.isArray(model?.requiredWeights)) groups.push(...model.requiredWeights);
+ return groups;
+};
+
+const inspectFederatedModelCache = async (model, repo) => {
+ const revision = model?.revision ? { revision: model.revision } : undefined;
+ const base = repo
+ ? await inspectModelCache(repo, revision).catch(() => ({ cached: false }))
+ : { cached: requiredModelCacheGroups(model).length === 0 };
+ if (base.cached !== true) return false;
+
+ // Some video profiles are deliberately selective: the main snapshot is not
+ // sufficient without the exact pinned Wan adapters, H3 checkpoint files, or
+ // H3 CUDA repo-file subset that the runner will load.
+ for (const group of requiredModelCacheGroups(model)) {
+ if (!group || typeof group.repo !== 'string' || !group.repo
+ || !Array.isArray(group.files) || group.files.length === 0
+ || typeof group.revision !== 'string' || !group.revision) return false;
+ if (!await findCachedRepoFiles(group.repo, group.files, { revision: group.revision })) return false;
+ }
+ return true;
+};
+
+const FEDERATED_DEFAULT_VIDEO_FRAMES = 121;
+
+const validateFederatedVideoControls = (input, model) => {
+ if (input.kind !== 'video') return;
+ const numFrames = input.numFrames ?? model.defaultFrames ?? FEDERATED_DEFAULT_VIDEO_FRAMES;
+ const fps = input.fps ?? 24;
+ if (isMiniMaxH3Runtime(model.runtime)) {
+ const controlError = minimaxH3ControlError({
+ model,
+ negativePrompt: input.negativePrompt,
+ numFrames,
+ fps,
+ });
+ if (controlError) throw controlError;
+ }
+ if (model.runtime === 'wan22') {
+ const frameStride = Number(model.frameStride);
+ if (Number.isFinite(frameStride) && frameStride > 0 && (Number(numFrames) - 1) % frameStride !== 0) {
+ unavailable(
+ `${model.name} requires a ${frameStride}n+1 frame count; got ${numFrames}.`,
+ 'WAN22_INVALID_FRAME_COUNT',
+ 400,
+ );
+ }
+ }
+};
+
export function normalizeFederatedMediaProviderConfig(settings) {
const raw = settings?.federation?.mediaProvider;
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
@@ -174,14 +250,19 @@ async function localGeneratorCapabilities(kind, pythonPath, { models, configured
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 modelSupportsInput = supportsFederatedInput(kind, model);
+ const needsPython = requiresConfiguredPython(kind, model);
+ const modelReady = !model ? false : await inspectFederatedModelCache(model, repo);
+ const runtimeReady = !isLocal ? false
+ : needsPython ? !!pythonPath
+ : kind === 'video' ? await isByovRuntimeReady(model?.runtime)
+ : true;
const reason = !isLocal ? 'unknown-engine'
- : !pythonPath ? 'runtime-unavailable'
- : !model ? 'unknown-model'
- : !modelReady ? 'model-unavailable'
- : null;
+ : !model ? 'unknown-model'
+ : !modelSupportsInput ? 'unsupported-input'
+ : !runtimeReady ? 'runtime-unavailable'
+ : !modelReady ? 'model-unavailable'
+ : null;
return {
kind,
engine: selected.engine,
@@ -190,7 +271,7 @@ async function localGeneratorCapabilities(kind, pythonPath, { models, configured
modelName: model?.name ?? selected.modelId,
ready: reason === null,
unavailableReason: reason,
- runtimeReady: isLocal && !!pythonPath,
+ runtimeReady,
platformSupported: isLocal,
cudaRequired: false,
cudaState: 'available',
@@ -299,6 +380,18 @@ function findIdempotentJob(callerId, idempotencyKey) {
) || null;
}
+// The audio wire predates the explicit `kind` field. Its old idempotency hash
+// was computed from the kind-less parsed body, while the compatibility
+// preprocessor now adds `kind: 'audio'` before this service sees it. Keep the
+// canonical audio hash kind-less so an ambiguous submission can still replay
+// a queued job across this upgrade; image/video hashes retain their kind to
+// prevent cross-kind key reuse.
+const requestHashInput = (input) => {
+ if (input?.kind !== 'audio') return input;
+ const { kind: _kind, ...legacyAudioInput } = input;
+ return legacyAudioInput;
+};
+
// 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
@@ -318,7 +411,10 @@ const RESULT_BY_KIND = {
async function describeResult(job) {
if (job.status !== 'completed') return null;
- const shape = RESULT_BY_KIND[job.kind] || RESULT_BY_KIND.audio;
+ const shape = RESULT_BY_KIND[job.kind];
+ if (!shape) {
+ unavailable('Provider result is unavailable', 'MEDIA_PROVIDER_RESULT_UNAVAILABLE', 410);
+ }
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 its own generator creates;
@@ -386,7 +482,7 @@ export async function describeFederatedMediaJob(callerId, jobOrId) {
export async function submitFederatedMediaJob({ callerId, config, input, idempotencyKey }) {
return withAdmissionLock(async () => {
- const requestHash = sha256Text(canonicalStringify(input));
+ const requestHash = sha256Text(canonicalStringify(requestHashInput(input)));
const existing = findIdempotentJob(callerId, idempotencyKey);
if (existing) {
if (existing.params?.federatedMedia?.requestHash !== requestHash) {
@@ -416,6 +512,7 @@ export async function submitFederatedMediaJob({ callerId, config, input, idempot
reason: capability.unavailableReason,
});
}
+ validateFederatedVideoControls(input, capability._model);
if (input.durationMode === 'auto' && !capability.autoDuration) {
unavailable('Requested engine does not support automatic duration', 'MEDIA_PROVIDER_AUTO_DURATION_UNSUPPORTED', 400);
}
diff --git a/server/services/federatedMediaProvider.test.js b/server/services/federatedMediaProvider.test.js
index 6a701f2f8b..459403ad24 100644
--- a/server/services/federatedMediaProvider.test.js
+++ b/server/services/federatedMediaProvider.test.js
@@ -22,13 +22,23 @@ vi.mock('./settings.js', () => ({
vi.mock('../lib/mediaModels.js', () => ({
getImageModels: vi.fn(() => state.imageModels),
getVideoModels: vi.fn(() => state.videoModels),
+ isEditOnly: (model) => model?.editOnly === true,
+ isFlux2: (model) => model?.runner === 'flux2',
repoForModel: (model) => model?.repo ?? null,
}));
vi.mock('../lib/hfCache.js', () => ({
inspectModelCache: vi.fn(async (repo) => ({ cached: state.cachedRepos.has(repo) })),
+ findCachedRepoFiles: vi.fn(async (repo, files) => (
+ state.cachedRepos.has(repo) ? files.map((file) => `/cached/${file}`) : null
+ )),
}));
+vi.mock('./videoGen/runtimes.js', async () => {
+ const actual = await vi.importActual('./videoGen/runtimes.js');
+ return { ...actual, isByovRuntimeReady: vi.fn(async () => true) };
+});
+
vi.mock('./sharing/peerPullAuthorization.js', () => ({
readCallerInstanceId: (req) => req.headers?.['x-portos-instance-id'] || null,
}));
@@ -75,6 +85,7 @@ import {
} from './federatedMediaProvider.js';
import { enqueueJob } from './mediaJobQueue/index.js';
import { PATHS, sha256Text } from '../lib/fileUtils.js';
+import { canonicalStringify } from '../lib/objects.js';
const originalMusicPath = PATHS.music;
const originalImagesPath = PATHS.images;
@@ -232,6 +243,33 @@ describe('federated media provider capacity and idempotency', () => {
})).rejects.toMatchObject({ status: 409, code: 'MEDIA_PROVIDER_IDEMPOTENCY_CONFLICT' });
});
+ it('replays a kind-less audio job created before the explicit kind field existed', async () => {
+ const legacyInput = { ...input() };
+ delete legacyInput.kind;
+ state.jobs = [{
+ id: '00000000-0000-4000-8000-000000000099',
+ kind: 'audio',
+ owner: 'federated-media:peer-example',
+ status: 'queued',
+ queuedAt: '2026-08-16T00:00:00.000Z',
+ params: {
+ federatedMedia: {
+ wireVersion: 1,
+ callerInstanceId: 'peer-example',
+ idempotencyKey: 'legacy-audio',
+ requestHash: sha256Text(canonicalStringify(legacyInput)),
+ },
+ },
+ }];
+
+ const replay = await submitFederatedMediaJob({
+ callerId: 'peer-example', config: config(), input: input(), idempotencyKey: 'legacy-audio',
+ });
+ expect(replay.replayed).toBe(true);
+ expect(replay.job.id).toBe('00000000-0000-4000-8000-000000000099');
+ expect(enqueueJob).not.toHaveBeenCalled();
+ });
+
it('counts all active local media work against the conservative provider cap', async () => {
state.jobs = [
{ id: 'local-1', owner: null, status: 'running' },
@@ -351,6 +389,59 @@ describe('federated media provider — image/video kinds', () => {
expect(status.status).toBe('ready');
});
+ it('does not gate bundled image runtimes on the legacy mflux python path', async () => {
+ state.settings = { federation: { mediaProvider: imageConfig() } };
+ state.imageModels = [{
+ id: 'flux-dev', name: 'FLUX.2', runner: 'flux2', repo: 'example/flux2',
+ }];
+ state.cachedRepos = new Set(['example/flux2']);
+ const status = await getFederatedMediaProviderStatus(imageConfig(), { kinds: ['image'] });
+ expect(status.capabilities[0]).toMatchObject({
+ ready: true, runtimeReady: true, unavailableReason: null,
+ });
+ });
+
+ it('does not gate BYOV video runtimes on the legacy mflux python path', async () => {
+ const videoConfig = () => ({
+ enabled: true, maxQueuedJobs: 2, audioModels: [], imageModels: [],
+ videoModels: [{ engine: 'local', modelId: 'ltx2' }],
+ });
+ state.settings = { federation: { mediaProvider: videoConfig() } };
+ state.cachedRepos = new Set(['example/ltx2']);
+ state.videoModels = [{
+ id: 'ltx2', name: 'LTX2', runtime: 'ltx2', repo: 'example/ltx2', supportedModes: ['text'],
+ }];
+ const status = await getFederatedMediaProviderStatus(videoConfig(), { kinds: ['video'] });
+ expect(status.capabilities[0]).toMatchObject({
+ ready: true, runtimeReady: true, unavailableReason: null,
+ });
+ });
+
+ it('does not advertise image-edit or image-only video models for this text-only wire', async () => {
+ const incompatibleImageConfig = () => ({
+ enabled: true, maxQueuedJobs: 2, audioModels: [], videoModels: [],
+ imageModels: [{ engine: 'local', modelId: 'edit-only' }],
+ });
+ state.settings = { federation: { mediaProvider: incompatibleImageConfig() }, imageGen: { local: { pythonPath: '/usr/bin/python3' } } };
+ state.imageModels = [{
+ id: 'edit-only', name: 'Edit only', repo: 'example/edit', editOnly: true,
+ }];
+ state.cachedRepos = new Set(['example/edit']);
+ const imageStatus = await getFederatedMediaProviderStatus(incompatibleImageConfig(), { kinds: ['image'] });
+ expect(imageStatus.capabilities[0]).toMatchObject({ ready: false, unavailableReason: 'unsupported-input' });
+
+ const incompatibleVideoConfig = () => ({
+ enabled: true, maxQueuedJobs: 2, audioModels: [], imageModels: [],
+ videoModels: [{ engine: 'local', modelId: 'image-only' }],
+ });
+ state.videoModels = [{
+ id: 'image-only', name: 'Image only', runtime: 'ltx2', repo: 'example/image-only', supportedModes: ['image'],
+ }];
+ state.cachedRepos = new Set(['example/image-only']);
+ const videoStatus = await getFederatedMediaProviderStatus(incompatibleVideoConfig(), { kinds: ['video'] });
+ expect(videoStatus.capabilities[0]).toMatchObject({ ready: false, unavailableReason: 'unsupported-input' });
+ });
+
it('does not report image/video capabilities unless the caller opts into that kind', async () => {
state.settings = {
federation: { mediaProvider: imageConfig() },