Skip to content

Unrestricted Open-source alternative to AI video platforms — Free AI image & video generation studio with 600+ models (Flux, Midjourney, Kling, Sora, Veo). No content filters. Self-hosted, MIT licensed.

fix(studio): handle failed async generations

antilyac4629695ce6f
diff --git a/components/StandaloneShell.js b/components/StandaloneShell.js
index 62137403..701ea5ff 100644
--- a/components/StandaloneShell.js
+++ b/components/StandaloneShell.js
@@ -418,6 +418,15 @@ export default function StandaloneShell() {
return () => window.clearTimeout(timer);
}, [notifications]);
+ const fetchBalance = useCallback(async (key) => {
+ try {
+ const data = await getUserBalance(key);
+ setBalance(data.balance);
+ } catch (err) {
+ console.error('Balance fetch failed:', err);
+ }
+ }, []);
+
const makeSuccessCallback = useCallback((tabId) => (data) => {
const tab = TABS.find(t => t.id === tabId);
pushNotification({
@@ -434,7 +443,8 @@ export default function StandaloneShell() {
? errorOrMessage
: (errorOrMessage?.message || errorOrMessage?.error || String(errorOrMessage || 'Generation failed'));
pushNotification({ type: 'error', tabId, label: tab?.label || tabId, message });
- }, [pushNotification]);
+ if (apiKey) void fetchBalance(apiKey);
+ }, [apiKey, fetchBalance, pushNotification]);
const makeGenerationStartCallback = useCallback((tabId) => () => {
setGenerationCounts((previous) => ({
@@ -530,15 +540,6 @@ export default function StandaloneShell() {
}
}, [activeTab]);
- const fetchBalance = useCallback(async (key) => {
- try {
- const data = await getUserBalance(key);
- setBalance(data.balance);
- } catch (err) {
- console.error('Balance fetch failed:', err);
- }
- }, []);
-
useEffect(() => {
setHasMounted(true);
const stored = localStorage.getItem(STORAGE_KEY);
diff --git a/packages/studio/src/components/ImageStudio.jsx b/packages/studio/src/components/ImageStudio.jsx
index 7e667a22..e26d9d54 100644
--- a/packages/studio/src/components/ImageStudio.jsx
+++ b/packages/studio/src/components/ImageStudio.jsx
@@ -5,6 +5,7 @@ import toast, { Toaster } from "react-hot-toast";
import { generateImage, generateI2I, uploadFile } from "../muapi.js";
import { formatErrorMessage } from "../utils/formatError.js";
import { downloadImage } from "../utils/downloadImage.js";
+import { appendGenerationRefundNotice } from "../utils/generationLifecycle.js";
import { scopedPersistKey, migrateLegacyPersistKey } from "../persistKey.js";
import DrawModal from "./DrawModal.jsx";
import MobileGenerationActions, {
@@ -1318,7 +1319,10 @@ export default function ImageStudio({
});
} catch (e) {
console.error("[ImageStudio] Generation failed:", e);
- const errMsg = formatErrorMessage(e, "Image generation failed");
+ const errMsg = appendGenerationRefundNotice(
+ formatErrorMessage(e, "Image generation failed"),
+ e,
+ );
if (onGenerationError) onGenerationError(errMsg);
else toast.error(errMsg);
} finally {
diff --git a/packages/studio/src/muapi.js b/packages/studio/src/muapi.js
index 036c7d2f..076e6890 100644
--- a/packages/studio/src/muapi.js
+++ b/packages/studio/src/muapi.js
@@ -1,4 +1,5 @@
import { getModelById, getVideoModelById, getI2IModelById, getI2VModelById, getV2VModelById, getRecastModelById, getLipSyncModelById, getAudioModelById } from './models.js';
+import { pollForGenerationResult } from './utils/generationLifecycle.js';
// In an http(s) browser we route through the host app's proxy (Next.js routes
// under /api/* re-issue the call server-side) so api.muapi.ai CORS is bypassed.
@@ -17,28 +18,14 @@ function notifyAuthRequired(status, detail) {
}
async function pollForResult(requestId, key, maxAttempts = 900, interval = 2000) {
- const pollUrl = `${BASE_URL}/api/v1/predictions/${requestId}/result`;
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
- await new Promise(resolve => setTimeout(resolve, interval));
- try {
- const response = await fetch(pollUrl, {
- headers: { 'Content-Type': 'application/json', 'x-api-key': key }
- });
- if (!response.ok) {
- const errText = await response.text();
- if (response.status >= 500) continue;
- notifyAuthRequired(response.status, errText);
- throw new Error(`Poll Failed: ${response.status} - ${errText.slice(0, 100)}`);
- }
- const data = await response.json();
- const status = data.status?.toLowerCase();
- if (status === 'completed' || status === 'succeeded' || status === 'success') return data;
- if (status === 'failed' || status === 'error') throw new Error(`Generation failed: ${data.error || 'Unknown error'}`);
- } catch (error) {
- if (attempt === maxAttempts) throw error;
- }
- }
- throw new Error('Generation timed out after polling.');
+ return pollForGenerationResult({
+ baseUrl: BASE_URL,
+ requestId,
+ apiKey: key,
+ maxAttempts,
+ interval,
+ onAuthRequired: notifyAuthRequired,
+ });
}
async function submitAndPoll(endpoint, payload, key, onRequestId, maxAttempts = 60) {
@@ -925,4 +912,3 @@ export async function expandImage(apiKey, { image_url, onRequestId }) {
return submitAndPoll(endpoint, payload, apiKey, onRequestId, 90);
}
-
diff --git a/packages/studio/src/utils/generationLifecycle.js b/packages/studio/src/utils/generationLifecycle.js
new file mode 100644
index 00000000..5085cf45
--- /dev/null
+++ b/packages/studio/src/utils/generationLifecycle.js
@@ -0,0 +1,81 @@
+const SUCCESS_STATUSES = new Set(["completed", "succeeded", "success"]);
+const FAILURE_STATUSES = new Set(["failed", "error", "cancelled", "canceled"]);
+
+const wait = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
+
+function getGenerationErrorDetail(result) {
+ if (typeof result?.error === "string") return result.error;
+ if (typeof result?.error?.message === "string") return result.error.message;
+ if (typeof result?.message === "string") return result.message;
+ return "Unknown error";
+}
+
+function createGenerationError(result, requestId) {
+ const error = new Error(`Generation failed: ${getGenerationErrorDetail(result)}`);
+ error.requestId = requestId;
+ error.generationResult = result;
+ return error;
+}
+
+export function appendGenerationRefundNotice(message, error) {
+ const cost = error?.generationResult?.cost;
+ if (cost?.refunded !== true) return message;
+
+ const credits = cost.amount_credits;
+ const notice = Number.isFinite(credits)
+ ? `Refunded ${credits} credit${credits === 1 ? "" : "s"}.`
+ : "The generation cost was refunded.";
+ return `${message} ${notice}`;
+}
+
+export async function pollForGenerationResult({
+ baseUrl,
+ requestId,
+ apiKey,
+ maxAttempts = 900,
+ interval = 2000,
+ onAuthRequired,
+ fetchImpl = fetch,
+}) {
+ const pollUrl = `${baseUrl}/api/v1/predictions/${requestId}/result`;
+
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
+ await wait(interval);
+
+ let response;
+ try {
+ response = await fetchImpl(pollUrl, {
+ headers: { "Content-Type": "application/json", "x-api-key": apiKey },
+ });
+ } catch (error) {
+ if (attempt === maxAttempts) throw error;
+ continue;
+ }
+
+ if (!response.ok) {
+ const detail = await response.text();
+ const error = new Error(`Poll Failed: ${response.status} - ${detail.slice(0, 100)}`);
+ error.requestId = requestId;
+
+ if (response.status >= 500 && attempt < maxAttempts) continue;
+ onAuthRequired?.(response.status, detail);
+ throw error;
+ }
+
+ let result;
+ try {
+ result = await response.json();
+ } catch (error) {
+ if (attempt === maxAttempts) throw error;
+ continue;
+ }
+
+ const status = result.status?.toLowerCase();
+ if (SUCCESS_STATUSES.has(status)) return result;
+ if (FAILURE_STATUSES.has(status)) throw createGenerationError(result, requestId);
+ }
+
+ const error = new Error(`Generation timed out after polling. Request ID: ${requestId}`);
+ error.requestId = requestId;
+ throw error;
+}
diff --git a/src/components/ImageStudio.js b/src/components/ImageStudio.js
index d0e8d0e1..81ec5fde 100644
--- a/src/components/ImageStudio.js
+++ b/src/components/ImageStudio.js
@@ -12,6 +12,7 @@ import { t } from '../lib/i18n.js';
import { createUploadPicker } from './UploadPicker.js';
import { savePendingJob, removePendingJob, getPendingJobs } from '../lib/pendingJobs.js';
import { downloadImage } from '../../packages/studio/src/utils/downloadImage.js';
+import { appendGenerationRefundNotice } from '../../packages/studio/src/utils/generationLifecycle.js';
function createInlineInstructions(type) {
const el = document.createElement('div');
@@ -1289,7 +1290,8 @@ export function ImageStudio() {
console.error(e);
// Restore hero so the page doesn't look broken after a failed generation
hero.classList.remove('opacity-0', 'scale-95', '-translate-y-10', 'pointer-events-none');
- generateBtn.innerHTML = `Error: ${e.message.slice(0, 60)}`;
+ const errorMessage = appendGenerationRefundNotice(e.message, e);
+ generateBtn.textContent = `Error: ${errorMessage.slice(0, 100)}`;
setTimeout(() => {
generateBtn.innerHTML = t('common.generate');
}, 4000);
diff --git a/src/lib/muapi.js b/src/lib/muapi.js
index d57ce73d..6a3885df 100644
--- a/src/lib/muapi.js
+++ b/src/lib/muapi.js
@@ -1,4 +1,5 @@
import { getModelById, getVideoModelById, getI2IModelById, getI2VModelById, getV2VModelById, getLipSyncModelById } from './models.js';
+import { pollForGenerationResult } from '../../packages/studio/src/utils/generationLifecycle.js';
export class MuapiClient {
constructor() {
@@ -121,51 +122,13 @@ export class MuapiClient {
* @param {number} interval - Polling interval in ms (default 2000)
*/
async pollForResult(requestId, key, maxAttempts = 60, interval = 2000) {
- const pollUrl = `${this.baseUrl}/api/v1/predictions/${requestId}/result`;
-
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
- await new Promise(resolve => setTimeout(resolve, interval));
-
- console.log(`[Muapi] Polling attempt ${attempt}/${maxAttempts}...`);
-
- try {
- const response = await fetch(pollUrl, {
- method: 'GET',
- headers: {
- 'Content-Type': 'application/json',
- 'x-api-key': key
- }
- });
-
- if (!response.ok) {
- const errText = await response.text();
- console.warn(`[Muapi] Poll error (${response.status}):`, errText);
- // Continue polling on non-fatal errors
- if (response.status >= 500) continue;
- throw new Error(`Poll Failed: ${response.status} - ${errText.slice(0, 100)}`);
- }
-
- const data = await response.json();
- console.log('[Muapi] Poll Response:', data);
-
- const status = data.status?.toLowerCase();
-
- if (status === 'completed' || status === 'succeeded' || status === 'success') {
- return data;
- }
-
- if (status === 'failed' || status === 'error') {
- throw new Error(`Generation failed: ${data.error || 'Unknown error'}`);
- }
-
- // Otherwise (processing, pending, etc.) keep polling
- } catch (error) {
- if (attempt === maxAttempts) throw error;
- console.warn('[Muapi] Poll attempt failed, retrying...', error.message);
- }
- }
-
- throw new Error('Generation timed out after polling.');
+ return pollForGenerationResult({
+ baseUrl: this.baseUrl,
+ requestId,
+ apiKey: key,
+ maxAttempts,
+ interval,
+ });
}
async generateVideo(params) {