Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

feat: add kie media provider support

wauputr44920295e3e54
diff --git a/open-sse/config/imageRegistry.ts b/open-sse/config/imageRegistry.ts
index f33f8e2955..d40e3e1023 100644
--- a/open-sse/config/imageRegistry.ts
+++ b/open-sse/config/imageRegistry.ts
@@ -231,6 +231,16 @@ export const IMAGE_PROVIDERS: Record<string, ImageProviderConfig> = {
supportedSizes: ["1024x1024", "1024x1280", "1024x1536", "1536x1024", "1280x1024"],
},
+ kie: {
+ id: "kie",
+ baseUrl: "https://api.kie.ai/api/v1/gpt4o-image/generate",
+ authType: "apikey",
+ authHeader: "bearer",
+ format: "kie-image",
+ models: [{ id: "gpt4o-image", name: "KIE 4o Image" }],
+ supportedSizes: ["1:1", "16:9", "9:16", "4:3", "3:4"],
+ },
+
sdwebui: {
id: "sdwebui",
baseUrl: "http://localhost:7860/sdapi/v1/txt2img",
diff --git a/open-sse/config/musicRegistry.ts b/open-sse/config/musicRegistry.ts
index 40cd950308..72f9681023 100644
--- a/open-sse/config/musicRegistry.ts
+++ b/open-sse/config/musicRegistry.ts
@@ -22,6 +22,19 @@ interface MusicProvider {
}
export const MUSIC_PROVIDERS: Record<string, MusicProvider> = {
+ kie: {
+ id: "kie",
+ baseUrl: "https://api.kie.ai",
+ authType: "apikey",
+ authHeader: "bearer",
+ format: "kie-music",
+ models: [
+ { id: "V4", name: "Suno V4" },
+ { id: "V4_5", name: "Suno V4.5" },
+ { id: "V5", name: "Suno V5" },
+ ],
+ },
+
comfyui: {
id: "comfyui",
baseUrl: "http://localhost:8188",
diff --git a/open-sse/config/videoRegistry.ts b/open-sse/config/videoRegistry.ts
index 809cc7f591..caf6de0c9f 100644
--- a/open-sse/config/videoRegistry.ts
+++ b/open-sse/config/videoRegistry.ts
@@ -22,6 +22,18 @@ interface VideoProvider {
}
export const VIDEO_PROVIDERS: Record<string, VideoProvider> = {
+ kie: {
+ id: "kie",
+ baseUrl: "https://api.kie.ai",
+ authType: "apikey",
+ authHeader: "bearer",
+ format: "kie-video",
+ models: [
+ { id: "kling-2.6/text-to-video", name: "Kling 2.6 Text to Video" },
+ { id: "wan/2-6-text-to-video", name: "Wan 2.6 Text to Video" },
+ ],
+ },
+
comfyui: {
id: "comfyui",
baseUrl: "http://localhost:8188",
diff --git a/open-sse/handlers/imageGeneration.ts b/open-sse/handlers/imageGeneration.ts
index 743c67762c..e41f967dd7 100644
--- a/open-sse/handlers/imageGeneration.ts
+++ b/open-sse/handlers/imageGeneration.ts
@@ -267,6 +267,17 @@ export async function handleImageGeneration({ body, credentials, log, resolvedPr
});
}
+ if (providerConfig.format === "kie-image") {
+ return handleKieImageGeneration({
+ model,
+ provider,
+ providerConfig,
+ body,
+ credentials,
+ log,
+ });
+ }
+
if (providerConfig.format === "sdwebui") {
return handleSDWebUIImageGeneration({ model, provider, providerConfig, body, log });
}
@@ -278,6 +289,153 @@ export async function handleImageGeneration({ body, credentials, log, resolvedPr
return handleOpenAIImageGeneration({ model, provider, providerConfig, body, credentials, log });
}
+async function handleKieImageGeneration({
+ model,
+ provider,
+ providerConfig,
+ body,
+ credentials,
+ log,
+}) {
+ const startTime = Date.now();
+ const token = credentials.apiKey || credentials.accessToken;
+ const timeoutMs = normalizePositiveNumber(body.timeout_ms, 180000);
+ const pollIntervalMs = normalizePositiveNumber(body.poll_interval_ms, 2500);
+ const payload: Record<string, unknown> = {
+ prompt: body.prompt,
+ size: typeof body.size === "string" ? body.size : "1:1",
+ nVariants: Number(body.n) > 0 ? Number(body.n) : 1,
+ };
+
+ try {
+ if (log) {
+ const promptPreview = String(body.prompt ?? "").slice(0, 60);
+ log.info("IMAGE", `${provider}/${model} (kie-image) | prompt: "${promptPreview}..."`);
+ }
+
+ const createRes = await fetch(providerConfig.baseUrl, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${token}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(payload),
+ });
+
+ if (!createRes.ok) {
+ const errorText = await createRes.text();
+ return saveImageErrorResult({
+ provider,
+ model,
+ status: createRes.status,
+ startTime,
+ error: errorText,
+ requestBody: payload,
+ });
+ }
+
+ const createData = await createRes.json();
+ const taskId = createData?.data?.taskId || createData?.taskId;
+ if (!taskId) {
+ return saveImageErrorResult({
+ provider,
+ model,
+ status: 502,
+ startTime,
+ error: "KIE image generation did not return taskId",
+ requestBody: payload,
+ });
+ }
+
+ const statusUrl = "https://api.kie.ai/api/v1/gpt4o-image/record-info";
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const recordRes = await fetch(`${statusUrl}?taskId=${encodeURIComponent(taskId)}`, {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ });
+
+ if (!recordRes.ok) {
+ const errorText = await recordRes.text();
+ return saveImageErrorResult({
+ provider,
+ model,
+ status: recordRes.status,
+ startTime,
+ error: errorText,
+ requestBody: payload,
+ });
+ }
+
+ const recordData = await recordRes.json();
+ const state = String(
+ recordData?.data?.status ?? recordData?.data?.successFlag ?? recordData?.msg ?? "PENDING"
+ ).toUpperCase();
+
+ if (state === "SUCCESS" || state === "1") {
+ const urls = Array.isArray(recordData?.data?.response?.resultUrls)
+ ? recordData.data.response.resultUrls
+ : [];
+ const images = urls
+ .filter((url) => typeof url === "string" && url.length > 0)
+ .map((url) => ({ url, revised_prompt: body.prompt }));
+ return saveImageSuccessResult({
+ provider,
+ model,
+ startTime,
+ requestBody: payload,
+ responseBody: { images_count: images.length },
+ images,
+ });
+ }
+
+ if (
+ state.includes("FAIL") ||
+ state.includes("ERROR") ||
+ state === "2" ||
+ state === "3" ||
+ state === "CREATE_TASK_FAILED" ||
+ state === "GENERATE_FAILED"
+ ) {
+ const errorMessage =
+ recordData?.data?.errorMessage ||
+ recordData?.msg ||
+ `KIE image task failed with status: ${state}`;
+ return saveImageErrorResult({
+ provider,
+ model,
+ status: 502,
+ startTime,
+ error: errorMessage,
+ requestBody: payload,
+ });
+ }
+
+ await sleep(pollIntervalMs);
+ }
+
+ return saveImageErrorResult({
+ provider,
+ model,
+ status: 504,
+ startTime,
+ error: `KIE image polling timed out after ${timeoutMs}ms`,
+ requestBody: payload,
+ });
+ } catch (err) {
+ return saveImageErrorResult({
+ provider,
+ model,
+ status: 502,
+ startTime,
+ error: `Image provider error: ${err.message}`,
+ requestBody: payload,
+ });
+ }
+}
+
/**
* Handle Gemini-format image generation (Antigravity / Nano Banana)
* Uses Gemini's generateContent API with responseModalities: ["TEXT", "IMAGE"]
diff --git a/open-sse/handlers/musicGeneration.ts b/open-sse/handlers/musicGeneration.ts
index b544fa18be..4d610ccc1e 100644
--- a/open-sse/handlers/musicGeneration.ts
+++ b/open-sse/handlers/musicGeneration.ts
@@ -50,6 +50,10 @@ export async function handleMusicGeneration({ body, credentials, log }) {
return handleComfyUIMusicGeneration({ model, provider, providerConfig, body, log });
}
+ if (providerConfig.format === "kie-music") {
+ return handleKieMusicGeneration({ model, provider, providerConfig, body, credentials, log });
+ }
+
return {
success: false,
status: 400,
@@ -164,3 +168,122 @@ async function handleComfyUIMusicGeneration({ model, provider, providerConfig, b
return { success: false, status: 502, error: `Music provider error: ${err.message}` };
}
}
+
+async function handleKieMusicGeneration({
+ model,
+ provider,
+ providerConfig,
+ body,
+ credentials,
+ log,
+}) {
+ const startTime = Date.now();
+ const timeoutMs = Number(body.timeout_ms) > 0 ? Number(body.timeout_ms) : 300000;
+ const pollIntervalMs = Number(body.poll_interval_ms) > 0 ? Number(body.poll_interval_ms) : 2500;
+ const token = credentials?.apiKey || credentials?.accessToken;
+ const baseUrl = providerConfig.baseUrl.replace(/\/$/, "");
+ const payload = {
+ prompt: body.prompt,
+ customMode: false,
+ instrumental: true,
+ model,
+ };
+
+ if (log) {
+ const promptPreview = String(body.prompt ?? "").slice(0, 60);
+ log.info("MUSIC", `${provider}/${model} (kie-music) | prompt: "${promptPreview}..."`);
+ }
+
+ try {
+ const createRes = await fetch(`${baseUrl}/api/v1/generate`, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${token}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(payload),
+ });
+
+ if (!createRes.ok) {
+ const errorText = await createRes.text();
+ return { success: false, status: createRes.status, error: errorText };
+ }
+
+ const createData = await createRes.json();
+ const taskId = createData?.data?.taskId || createData?.taskId;
+ if (!taskId) {
+ return { success: false, status: 502, error: "KIE music generation did not return taskId" };
+ }
+
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const recordRes = await fetch(
+ `${baseUrl}/api/v1/generate/record-info?taskId=${encodeURIComponent(taskId)}`,
+ {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ }
+ );
+
+ if (!recordRes.ok) {
+ const errorText = await recordRes.text();
+ return { success: false, status: recordRes.status, error: errorText };
+ }
+
+ const recordData = await recordRes.json();
+ const state = String(recordData?.data?.status || "PENDING").toUpperCase();
+
+ if (state === "SUCCESS") {
+ const tracks = Array.isArray(recordData?.data?.response?.sunoData)
+ ? recordData.data.response.sunoData
+ : [];
+ const audioFiles = tracks
+ .map((track) => track?.audioUrl)
+ .filter((url) => typeof url === "string" && url.length > 0)
+ .map((url) => ({ url, format: "mp3" }));
+
+ saveCallLog({
+ method: "POST",
+ path: "/v1/music/generations",
+ status: 200,
+ model: `${provider}/${model}`,
+ provider,
+ duration: Date.now() - startTime,
+ responseBody: { audio_count: audioFiles.length },
+ }).catch(() => {});
+
+ return {
+ success: true,
+ data: { created: Math.floor(Date.now() / 1000), data: audioFiles },
+ };
+ }
+
+ if (
+ state.includes("FAILED") ||
+ state.includes("ERROR") ||
+ state === "CREATE_TASK_FAILED" ||
+ state === "GENERATE_AUDIO_FAILED"
+ ) {
+ const errorMessage =
+ recordData?.data?.errorMessage || recordData?.msg || "KIE music task failed";
+ return { success: false, status: 502, error: errorMessage };
+ }
+
+ await sleep(pollIntervalMs);
+ }
+
+ return {
+ success: false,
+ status: 504,
+ error: `KIE music polling timed out after ${timeoutMs}ms`,
+ };
+ } catch (err) {
+ return { success: false, status: 502, error: `Music provider error: ${err.message}` };
+ }
+}
+
+function sleep(ms: number) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
diff --git a/open-sse/handlers/videoGeneration.ts b/open-sse/handlers/videoGeneration.ts
index 44b01f9fce..84b69d4111 100644
--- a/open-sse/handlers/videoGeneration.ts
+++ b/open-sse/handlers/videoGeneration.ts
@@ -55,6 +55,10 @@ export async function handleVideoGeneration({ body, credentials, log }) {
return handleSDWebUIVideoGeneration({ model, provider, providerConfig, body, log });
}
+ if (providerConfig.format === "kie-video") {
+ return handleKieVideoGeneration({ model, provider, providerConfig, body, credentials, log });
+ }
+
return {
success: false,
status: 400,
@@ -262,3 +266,131 @@ async function handleSDWebUIVideoGeneration({ model, provider, providerConfig, b
return { success: false, status: 502, error: `Video provider error: ${err.message}` };
}
}
+
+async function handleKieVideoGeneration({
+ model,
+ provider,
+ providerConfig,
+ body,
+ credentials,
+ log,
+}) {
+ const startTime = Date.now();
+ const timeoutMs = Number(body.timeout_ms) > 0 ? Number(body.timeout_ms) : 300000;
+ const pollIntervalMs = Number(body.poll_interval_ms) > 0 ? Number(body.poll_interval_ms) : 2500;
+ const token = credentials?.apiKey || credentials?.accessToken;
+ const baseUrl = providerConfig.baseUrl.replace(/\/$/, "");
+
+ const payload = {
+ model,
+ input: {
+ prompt: body.prompt,
+ duration: body.duration ? String(body.duration) : "5",
+ aspect_ratio: body.aspect_ratio || "16:9",
+ sound: body.sound === true,
+ },
+ };
+
+ if (log) {
+ const promptPreview = String(body.prompt ?? "").slice(0, 60);
+ log.info("VIDEO", `${provider}/${model} (kie-video) | prompt: "${promptPreview}..."`);
+ }
+
+ try {
+ const createRes = await fetch(`${baseUrl}/api/v1/jobs/createTask`, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${token}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(payload),
+ });
+
+ if (!createRes.ok) {
+ const errorText = await createRes.text();
+ return { success: false, status: createRes.status, error: errorText };
+ }
+
+ const createData = await createRes.json();
+ const taskId = createData?.data?.taskId || createData?.taskId;
+ if (!taskId) {
+ return { success: false, status: 502, error: "KIE video generation did not return taskId" };
+ }
+
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const recordRes = await fetch(
+ `${baseUrl}/api/v1/jobs/recordInfo?taskId=${encodeURIComponent(taskId)}`,
+ {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ }
+ );
+
+ if (!recordRes.ok) {
+ const errorText = await recordRes.text();
+ return { success: false, status: recordRes.status, error: errorText };
+ }
+
+ const recordData = await recordRes.json();
+ const state = String(recordData?.data?.state || "generating").toLowerCase();
+
+ if (state === "success") {
+ let resultJson: any = {};
+ try {
+ resultJson =
+ typeof recordData?.data?.resultJson === "string"
+ ? JSON.parse(recordData.data.resultJson)
+ : recordData?.data?.resultJson || {};
+ } catch {
+ resultJson = {};
+ }
+ const urls = Array.isArray(resultJson?.resultUrls)
+ ? resultJson.resultUrls
+ : Array.isArray(resultJson?.videoUrls)
+ ? resultJson.videoUrls
+ : [];
+ const videos = urls
+ .filter((url) => typeof url === "string" && url.length > 0)
+ .map((url) => ({ url, format: "mp4" }));
+
+ saveCallLog({
+ method: "POST",
+ path: "/v1/videos/generations",
+ status: 200,
+ model: `${provider}/${model}`,
+ provider,
+ duration: Date.now() - startTime,
+ responseBody: { videos_count: videos.length },
+ }).catch(() => {});
+
+ return {
+ success: true,
+ data: { created: Math.floor(Date.now() / 1000), data: videos },
+ };
+ }
+
+ if (state === "fail") {
+ const errorMessage =
+ recordData?.data?.failMsg || recordData?.msg || "KIE video task failed";
+ return { success: false, status: 502, error: errorMessage };
+ }
+
+ await sleep(pollIntervalMs);
+ }
+
+ return {
+ success: false,
+ status: 504,
+ error: `KIE video polling timed out after ${timeoutMs}ms`,
+ };
+ } catch (err) {
+ return { success: false, status: 502, error: `Video provider error: ${err.message}` };
+ }
+}
+
+function sleep(ms: number) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
diff --git a/src/app/(dashboard)/dashboard/cache/media/MediaPageClient.tsx b/src/app/(dashboard)/dashboard/cache/media/MediaPageClient.tsx
index 333fa67186..578196443a 100644
--- a/src/app/(dashboard)/dashboard/cache/media/MediaPageClient.tsx
+++ b/src/app/(dashboard)/dashboard/cache/media/MediaPageClient.tsx
@@ -53,7 +53,7 @@ const MODALITY_CONFIG: Record<
label: "Video Generation",
placeholder: "A timelapse of a flower blooming...",
color: "from-blue-500 to-cyan-500",
- needsCredentials: [],
+ needsCredentials: ["kie"],
},
music: {
icon: "music_note",
@@ -61,7 +61,7 @@ const MODALITY_CONFIG: Record<
label: "Music Generation",
placeholder: "Upbeat electronic music with synth pads...",
color: "from-orange-500 to-yellow-500",
- needsCredentials: [],
+ needsCredentials: ["kie"],
},
speech: {
icon: "record_voice_over",
@@ -89,6 +89,14 @@ const PROVIDER_MODELS: Record<
> = {
image: IMAGE_PROVIDER_MODELS,
video: [
+ {
+ id: "kie",
+ name: "KIE.AI",
+ models: [
+ { id: "kie/kling-2.6/text-to-video", name: "Kling 2.6 Text to Video" },
+ { id: "kie/wan/2-6-text-to-video", name: "Wan 2.6 Text to Video" },
+ ],
+ },
{
id: "comfyui",
name: "ComfyUI",
@@ -104,6 +112,15 @@ const PROVIDER_MODELS: Record<
},
],
music: [
+ {
+ id: "kie",
+ name: "KIE.AI",
+ models: [
+ { id: "kie/V4", name: "Suno V4" },
+ { id: "kie/V4_5", name: "Suno V4.5" },
+ { id: "kie/V5", name: "Suno V5" },
+ ],
+ },
{
id: "comfyui",
name: "ComfyUI",
diff --git a/src/shared/constants/providers.ts b/src/shared/constants/providers.ts
index 535477becb..1a4fc0f913 100644
--- a/src/shared/constants/providers.ts
+++ b/src/shared/constants/providers.ts
@@ -364,6 +364,15 @@ export const APIKEY_PROVIDERS = {
textIcon: "NB",
website: "https://nanobananaapi.ai",
},
+ kie: {
+ id: "kie",
+ alias: "kie",
+ name: "KIE.AI",
+ icon: "hub",
+ color: "#2563EB",
+ textIcon: "KIE",
+ website: "https://kie.ai",
+ },
"ollama-cloud": {
id: "ollama-cloud",
alias: "ollamacloud",
diff --git a/tests/unit/image-generation-handler.test.ts b/tests/unit/image-generation-handler.test.ts
index 91d1da0e32..b26e60c7ab 100644
--- a/tests/unit/image-generation-handler.test.ts
+++ b/tests/unit/image-generation-handler.test.ts
@@ -128,6 +128,66 @@ test("handleImageGeneration uses synthetic OpenAI-compatible routing for resolve
}
});
+test("handleImageGeneration polls KIE image tasks and returns URLs on success", async () => {
+ const originalFetch = globalThis.fetch;
+ let createPayload;
+ let pollUrl = "";
+
+ globalThis.fetch = async (url, options = {}) => {
+ const stringUrl = String(url);
+ if (stringUrl === "https://api.kie.ai/api/v1/gpt4o-image/generate") {
+ createPayload = JSON.parse(String(options.body || "{}"));
+ return new Response(JSON.stringify({ code: 200, data: { taskId: "kie-task-1" } }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ }
+
+ if (stringUrl.startsWith("https://api.kie.ai/api/v1/gpt4o-image/record-info")) {
+ pollUrl = stringUrl;
+ return new Response(
+ JSON.stringify({
+ code: 200,
+ data: {
+ status: "SUCCESS",
+ response: {
+ resultUrls: ["https://example.com/kie-image.png"],
+ },
+ },
+ }),
+ {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ }
+ );
+ }
+
+ throw new Error(`Unexpected URL: ${stringUrl}`);
+ };
+
+ try {
+ const result = await handleImageGeneration({
+ body: {
+ model: "kie/gpt4o-image",
+ prompt: "city skyline at dusk",
+ size: "1:1",
+ n: 1,
+ },
+ credentials: { apiKey: "kie-key" },
+ log: null,
+ });
+
+ assert.equal(result.success, true);
+ assert.equal(createPayload.prompt, "city skyline at dusk");
+ assert.equal(createPayload.size, "1:1");
+ assert.equal(createPayload.nVariants, 1);
+ assert.match(pollUrl, /taskId=kie-task-1/);
+ assert.equal(result.data.data[0].url, "https://example.com/kie-image.png");
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
test("handleImageGeneration maps Hyperbolic size parameters and normalizes base64 images", async () => {
const originalFetch = globalThis.fetch;
let captured;
diff --git a/tests/unit/music-generation-handler.test.ts b/tests/unit/music-generation-handler.test.ts
index 690eb708f4..d3ca004182 100644
--- a/tests/unit/music-generation-handler.test.ts
+++ b/tests/unit/music-generation-handler.test.ts
@@ -104,6 +104,64 @@ test("handleMusicGeneration executes ComfyUI audio workflow and normalizes wav o
}
});
+test("handleMusicGeneration polls KIE music tasks and returns audio URLs", async () => {
+ const originalFetch = globalThis.fetch;
+ let createBody;
+ let pollUrl = "";
+
+ globalThis.fetch = async (url, options = {}) => {
+ const stringUrl = String(url);
+
+ if (stringUrl === "https://api.kie.ai/api/v1/generate") {
+ createBody = JSON.parse(String(options.body || "{}"));
+ return new Response(JSON.stringify({ code: 200, data: { taskId: "kie-music-task" } }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ }
+
+ if (stringUrl.startsWith("https://api.kie.ai/api/v1/generate/record-info")) {
+ pollUrl = stringUrl;
+ return new Response(
+ JSON.stringify({
+ code: 200,
+ data: {
+ status: "SUCCESS",
+ response: {
+ sunoData: [{ audioUrl: "https://example.com/kie-music.mp3" }],
+ },
+ },
+ }),
+ { status: 200, headers: { "content-type": "application/json" } }
+ );
+ }
+
+ throw new Error(`Unexpected URL: ${stringUrl}`);
+ };
+
+ try {
+ const result = await handleMusicGeneration({
+ body: {
+ model: "kie/V4",
+ prompt: "relaxing piano ambience",
+ },
+ credentials: { apiKey: "kie-key" },
+ log: null,
+ });
+
+ assert.equal(createBody.model, "V4");
+ assert.equal(createBody.customMode, false);
+ assert.equal(createBody.instrumental, true);
+ assert.equal(createBody.prompt, "relaxing piano ambience");
+ assert.match(pollUrl, /taskId=kie-music-task/);
+ assert.equal(result.success, true);
+ assert.equal(result.data.data[0].url, "https://example.com/kie-music.mp3");
+ assert.equal(result.data.data[0].format, "mp3");
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
test("handleMusicGeneration rejects unsupported provider formats", async () => {
const originalProvider = MUSIC_PROVIDERS.fakeprovider;
diff --git a/tests/unit/video-generation-handler.test.ts b/tests/unit/video-generation-handler.test.ts
index 2c85ed396f..f3c1d0a835 100644
--- a/tests/unit/video-generation-handler.test.ts
+++ b/tests/unit/video-generation-handler.test.ts
@@ -90,6 +90,60 @@ test("handleVideoGeneration routes SD WebUI payloads and normalizes mp4 output",
}
});
+test("handleVideoGeneration polls KIE market tasks and returns video URLs", async () => {
+ const originalFetch = globalThis.fetch;
+ let createBody;
+ let pollUrl = "";
+
+ globalThis.fetch = async (url, options = {}) => {
+ const stringUrl = String(url);
+
+ if (stringUrl === "https://api.kie.ai/api/v1/jobs/createTask") {
+ createBody = JSON.parse(String(options.body || "{}"));
+ return new Response(JSON.stringify({ code: 200, data: { taskId: "kie-video-task" } }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ }
+
+ if (stringUrl.startsWith("https://api.kie.ai/api/v1/jobs/recordInfo")) {
+ pollUrl = stringUrl;
+ return new Response(
+ JSON.stringify({
+ code: 200,
+ data: {
+ state: "success",
+ resultJson: '{"resultUrls":["https://example.com/kie-video.mp4"]}',
+ },
+ }),
+ { status: 200, headers: { "content-type": "application/json" } }
+ );
+ }
+
+ throw new Error(`Unexpected URL: ${stringUrl}`);
+ };
+
+ try {
+ const result = await handleVideoGeneration({
+ body: {
+ model: "kie/kling-2.6/text-to-video",
+ prompt: "cinematic shot of neon city rain",
+ },
+ credentials: { apiKey: "kie-key" },
+ log: null,
+ });
+
+ assert.equal(createBody.model, "kling-2.6/text-to-video");
+ assert.equal(createBody.input.prompt, "cinematic shot of neon city rain");
+ assert.match(pollUrl, /taskId=kie-video-task/);
+ assert.equal(result.success, true);
+ assert.equal(result.data.data[0].url, "https://example.com/kie-video.mp4");
+ assert.equal(result.data.data[0].format, "mp4");
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
test("handleVideoGeneration executes ComfyUI workflow and returns fetched output files", async () => {
const originalFetch = globalThis.fetch;
const originalSetTimeout = globalThis.setTimeout;