Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript

feat(kieai): retry logic, failed state, and manual retry button

lvalicsacb192881d76
diff --git a/.serena/project.local.yml b/.serena/project.local.yml
new file mode 100644
index 00000000..36cd3def
--- /dev/null
+++ b/.serena/project.local.yml
@@ -0,0 +1,5 @@
+# This file allows you to locally override settings in project.yml for development purposes.
+#
+# Use the same keys as in project.yml here. Any setting you specify will override the corresponding
+# setting in project.yml, allowing you to customise the configuration for your local development environment
+# without affecting the project configuration in project.yml (which is intended to be versioned).
diff --git a/apps/web/src/components/editor/AssetsPanel.tsx b/apps/web/src/components/editor/AssetsPanel.tsx
index f2bef59f..db93e399 100644
--- a/apps/web/src/components/editor/AssetsPanel.tsx
+++ b/apps/web/src/components/editor/AssetsPanel.tsx
@@ -48,6 +48,7 @@ import {
} from "@openreel/ui";
import { KieAIImageDialog } from "./kieai/KieAIImageDialog";
import { loadMediaBlob } from "../../services/media-storage";
+import { useKieAIStore } from "../../stores/kieai-store";
const formatDuration = (seconds: number): string => {
const mins = Math.floor(seconds / 60);
@@ -73,6 +74,7 @@ const MediaThumbnail: React.FC<{
onDragStart: (e: React.DragEvent) => void;
onAddToTimeline: () => void;
onKieAI?: () => void;
+ onRetryKieAI?: () => void;
}> = ({
item,
isSelected,
@@ -83,6 +85,7 @@ const MediaThumbnail: React.FC<{
onDragStart,
onAddToTimeline,
onKieAI,
+ onRetryKieAI,
}) => {
const [isHovered, setIsHovered] = useState(false);
@@ -121,7 +124,9 @@ const MediaThumbnail: React.FC<{
? "text-primary/50"
: "text-status-info/50";
- const borderClass = item.isPending
+ const borderClass = item.kieaiError
+ ? "border-red-500 ring-1 ring-red-500/50 shadow-[0_0_10px_rgba(239,68,68,0.3)]"
+ : item.isPending
? "border-purple-500 ring-1 ring-purple-500/50 shadow-[0_0_10px_rgba(168,85,247,0.3)]"
: item.isPlaceholder
? "border-yellow-500 ring-1 ring-yellow-500/50 shadow-[0_0_10px_rgba(234,179,8,0.3)]"
@@ -131,7 +136,15 @@ const MediaThumbnail: React.FC<{
const hoverOverlay = (
<div className="absolute inset-0 bg-black/40 backdrop-blur-[1px] flex items-center justify-center gap-2 animate-in fade-in duration-200">
- {item.isPending ? (
+ {item.kieaiError ? (
+ <button
+ onClick={(e) => { e.stopPropagation(); onRetryKieAI?.(); }}
+ title="Generation failed — click to retry"
+ className="p-2 bg-red-500/20 rounded-full hover:bg-red-500/40 backdrop-blur-sm transition-colors"
+ >
+ <RefreshCw size={14} className="text-red-400" />
+ </button>
+ ) : item.isPending ? (
<div title="KieAI generation in progress…" className="p-2">
<div className="h-5 w-5 animate-spin rounded-full border-2 border-purple-400 border-t-transparent" />
</div>
@@ -196,12 +209,17 @@ const MediaThumbnail: React.FC<{
<Icon size={14} className={iconColor} />
</div>
)}
- {item.isPending && (
+ {item.kieaiError && (
+ <div className="absolute inset-0 flex items-center justify-center bg-red-500/10">
+ <AlertTriangle size={12} className="text-red-400" />
+ </div>
+ )}
+ {!item.kieaiError && item.isPending && (
<div className="absolute inset-0 flex items-center justify-center bg-purple-500/10">
<div className="h-4 w-4 animate-spin rounded-full border-2 border-purple-400 border-t-transparent" />
</div>
)}
- {!item.isPending && item.isPlaceholder && (
+ {!item.kieaiError && !item.isPending && item.isPlaceholder && (
<div className="absolute inset-0 flex items-center justify-center bg-yellow-500/10">
<AlertTriangle size={12} className="text-yellow-500/70" />
</div>
@@ -228,7 +246,15 @@ const MediaThumbnail: React.FC<{
{/* Hover actions */}
{isHovered && (
<div className="flex items-center gap-1 flex-shrink-0">
- {item.isPending ? (
+ {item.kieaiError ? (
+ <button
+ onClick={(e) => { e.stopPropagation(); onRetryKieAI?.(); }}
+ title="Retry generation"
+ className="p-1 bg-red-500/20 rounded hover:bg-red-500/40 transition-colors"
+ >
+ <RefreshCw size={12} className="text-red-400" />
+ </button>
+ ) : item.isPending ? (
<div className="p-1" title="Generating…">
<div className="h-3 w-3 animate-spin rounded-full border-2 border-purple-400 border-t-transparent" />
</div>
@@ -341,8 +367,16 @@ const MediaThumbnail: React.FC<{
</div>
)}
+ {/* KieAI Error Badge */}
+ {item.kieaiError && (
+ <div className="absolute top-1 left-1 px-1.5 py-0.5 bg-red-500 rounded text-[8px] text-white font-bold flex items-center gap-1">
+ <AlertTriangle size={8} />
+ Failed
+ </div>
+ )}
+
{/* Pending KieAI Badge */}
- {item.isPending && (
+ {!item.kieaiError && item.isPending && (
<div className="absolute top-1 left-1 px-1.5 py-0.5 bg-purple-500 rounded text-[8px] text-white font-bold flex items-center gap-1">
<div className="h-2 w-2 animate-spin rounded-full border border-white border-t-transparent" />
AI
@@ -350,7 +384,7 @@ const MediaThumbnail: React.FC<{
)}
{/* Missing Asset Badge */}
- {!item.isPending && item.isPlaceholder && (
+ {!item.kieaiError && !item.isPending && item.isPlaceholder && (
<div className="absolute top-1 left-1 px-1.5 py-0.5 bg-yellow-500 rounded text-[8px] text-black font-bold flex items-center gap-1">
<AlertTriangle size={10} />
Missing
@@ -364,15 +398,22 @@ const MediaThumbnail: React.FC<{
</div>
)}
+ {/* Error overlay */}
+ {item.kieaiError && !isHovered && (
+ <div className="absolute inset-0 flex items-center justify-center bg-red-500/10">
+ <AlertTriangle size={viewMode === "small" ? 20 : 32} className="text-red-400/60" />
+ </div>
+ )}
+
{/* Pending overlay */}
- {item.isPending && !isHovered && (
+ {!item.kieaiError && item.isPending && !isHovered && (
<div className="absolute inset-0 flex items-center justify-center bg-purple-500/10">
<div className="h-8 w-8 animate-spin rounded-full border-4 border-purple-400 border-t-transparent" />
</div>
)}
{/* Warning icon overlay for placeholders */}
- {!item.isPending && item.isPlaceholder && !isHovered && (
+ {!item.kieaiError && !item.isPending && item.isPlaceholder && !isHovered && (
<div className="absolute inset-0 flex items-center justify-center bg-yellow-500/10">
<AlertTriangle size={viewMode === "small" ? 20 : 32} className="text-yellow-500/50" />
</div>
@@ -737,6 +778,16 @@ export const AssetsPanel: React.FC = () => {
}
}, []);
+ const { retryTask } = useKieAIStore();
+ const { setKieAIItemState } = useProjectStore();
+
+ const handleRetryKieAI = useCallback((item: MediaItem) => {
+ if (!item.kieaiTaskId) return;
+ // Reset error state and re-activate polling
+ setKieAIItemState(item.id, true, false);
+ retryTask(item.kieaiTaskId);
+ }, [retryTask, setKieAIItemState]);
+
return (
<div
data-tour="assets"
@@ -916,7 +967,8 @@ export const AssetsPanel: React.FC = () => {
onReplace={() => handleReplaceAsset(item.id)}
onDragStart={(e) => handleItemDragStart(e, item)}
onAddToTimeline={() => handleAddToTimeline(item)}
- onKieAI={item.type === "image" ? () => handleOpenKieAI(item) : undefined}
+ onKieAI={item.type === "image" && !item.isPending && !item.kieaiError ? () => handleOpenKieAI(item) : undefined}
+ onRetryKieAI={item.kieaiError && item.kieaiTaskId ? () => handleRetryKieAI(item) : undefined}
/>
))}
{/* Add more media tile */}
diff --git a/apps/web/src/hooks/useKieAIPoller.ts b/apps/web/src/hooks/useKieAIPoller.ts
index 12742dec..74a6f13d 100644
--- a/apps/web/src/hooks/useKieAIPoller.ts
+++ b/apps/web/src/hooks/useKieAIPoller.ts
@@ -1,112 +1,126 @@
/**
* useKieAIPoller
*
- * Runs in the background (mounted at app root) and periodically polls KieAI
- * for pending task results:
- * - Images: every 30 seconds
- * - Videos: every 2 minutes
+ * Background poller for KieAI generation tasks.
*
- * On success, downloads the result and replaces the placeholder.
- * The task is ALWAYS removed once the API reports success or failure — even
- * if the local download/processing step fails, so the user is never stuck.
+ * - First poll: 5 s after task creation
+ * - Subsequent polls: 30 s (image) / 2 min (video)
+ * - Up to MAX_POLL_RETRIES consecutive errors before giving up
+ * - On exhaustion: marks task as failed; UI shows a manual retry button
+ * - On API success: downloads result, replaces placeholder, removes task
+ * - Task is ALWAYS removed on API success/fail — never left stuck
*/
import { useEffect, useRef } from "react";
import { useProjectStore } from "../stores/project-store";
-import { useKieAIStore } from "../stores/kieai-store";
+import { useKieAIStore, MAX_POLL_RETRIES } from "../stores/kieai-store";
import { pollTaskOnce, getResultUrl } from "../services/kieai/image-generation";
import { KieAIError } from "../services/kieai/types";
-const FIRST_POLL_DELAY_MS = 5_000; // Check quickly after task creation
-const POLL_INTERVAL_IMAGE_MS = 30_000; // 30 s between subsequent polls
-const POLL_INTERVAL_VIDEO_MS = 120_000; // 2 min
+const FIRST_POLL_DELAY_MS = 5_000;
+const POLL_INTERVAL_IMAGE_MS = 30_000;
+const POLL_INTERVAL_VIDEO_MS = 120_000;
export function useKieAIPoller() {
- const tasks = useKieAIStore((s) => s.tasks);
- const removeTask = useKieAIStore((s) => s.removeTask);
- const replacePlaceholderMedia = useProjectStore((s) => s.replacePlaceholderMedia);
- const projectId = useProjectStore((s) => s.project?.id);
-
- // Track per-task poll timers so we can cancel them cleanly
- const timersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());
+ const tasks = useKieAIStore((s) => s.tasks);
+ const removeTask = useKieAIStore((s) => s.removeTask);
+ const incrementRetry = useKieAIStore((s) => s.incrementRetry);
+ const markFailed = useKieAIStore((s) => s.markFailed);
+ const projectId = useProjectStore((s) => s.project?.id);
+ const replacePlaceholder = useProjectStore((s) => s.replacePlaceholderMedia);
+ const setKieAIItemState = useProjectStore((s) => s.setKieAIItemState);
+
+ const timersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());
const inFlightRef = useRef<Set<string>>(new Set());
useEffect(() => {
- const projectTasks = tasks.filter((t) => t.projectId === projectId);
+ const activeTasks = tasks.filter(
+ (t) => t.projectId === projectId && !t.failed,
+ );
- // Start polling for any task that doesn't already have a timer
- for (const task of projectTasks) {
- if (timersRef.current.has(task.taskId)) continue; // already scheduled
+ // Start a polling loop for each new active task
+ for (const task of activeTasks) {
+ if (timersRef.current.has(task.taskId)) continue;
const interval =
task.type === "video" ? POLL_INTERVAL_VIDEO_MS : POLL_INTERVAL_IMAGE_MS;
- const elapsed = Date.now() - task.createdAt;
+ const elapsed = Date.now() - task.createdAt;
const firstDelay = elapsed < FIRST_POLL_DELAY_MS
? FIRST_POLL_DELAY_MS - elapsed
: Math.max(0, interval - (elapsed % interval));
- console.log(`[KieAIPoller] scheduling task ${task.taskId} — first poll in ${Math.round(firstDelay / 1000)}s`);
+ console.log(
+ `[KieAIPoller] scheduling ${task.taskId} — first poll in ${Math.round(firstDelay / 1000)}s`,
+ );
const doPoll = async () => {
timersRef.current.delete(task.taskId);
-
if (inFlightRef.current.has(task.taskId)) return;
inFlightRef.current.add(task.taskId);
try {
- console.log(`[KieAIPoller] polling task ${task.taskId}`);
const record = await pollTaskOnce(task.taskId);
- console.log(`[KieAIPoller] task ${task.taskId} state: ${record.state}`);
+ console.log(`[KieAIPoller] ${task.taskId} state: ${record.state}`);
if (record.state === "success") {
- // Log raw record so we can inspect the actual resultJson shape
- console.log(`[KieAIPoller] raw success record:`, JSON.stringify(record, null, 2));
-
- // API says done — fetch result and replace placeholder.
- // ALWAYS remove the task even if download/replace fails.
+ // API says done — always remove the task, even if download fails
try {
const url = getResultUrl(record);
console.log(`[KieAIPoller] downloading result: ${url}`);
const res = await fetch(url);
const blob = await res.blob();
- await replacePlaceholderMedia(task.mediaId, blob, task.suggestedName);
- console.log(`[KieAIPoller] ✓ replaced placeholder for task ${task.taskId}`);
+ await replacePlaceholder(task.mediaId, blob, task.suggestedName);
+ console.log(`[KieAIPoller] ✓ replaced placeholder for ${task.taskId}`);
} catch (downloadErr) {
- console.error(`[KieAIPoller] download/replace failed for ${task.taskId}:`, downloadErr);
- // Fallback: at minimum clear the pending flag so the user isn't stuck
- try {
- const url = getResultUrl(record);
- replacePlaceholderMedia(
- task.mediaId,
- new Blob([], { type: "image/png" }),
- task.suggestedName,
- ).catch(() => {}); // best effort
- console.warn(`[KieAIPoller] falling back — result URL: ${url}`);
- } catch {
- // ignore
- }
+ console.error(`[KieAIPoller] download failed for ${task.taskId}:`, downloadErr);
+ // At minimum clear the pending spinner so the user isn't stuck
+ setKieAIItemState(task.mediaId, false, true);
} finally {
removeTask(task.taskId);
}
} else if (record.state === "fail") {
console.warn(`[KieAIPoller] task ${task.taskId} failed: ${record.failMsg}`);
+ setKieAIItemState(task.mediaId, false, true);
removeTask(task.taskId);
} else {
- // Still generating — schedule next poll
- console.log(`[KieAIPoller] task ${task.taskId} still ${record.state}, retry in ${interval / 1000}s`);
+ // Still generating — schedule next poll (no error, don't touch retries)
+ console.log(`[KieAIPoller] ${task.taskId} still ${record.state}, retry in ${interval / 1000}s`);
const t = setTimeout(doPoll, interval);
timersRef.current.set(task.taskId, t);
}
} catch (err) {
+ // Auth error — give up immediately, don't count as a retry
if (err instanceof KieAIError && err.code === 401) {
console.warn("[KieAIPoller] auth error — stopping poll for", task.taskId);
+ setKieAIItemState(task.mediaId, false, true);
removeTask(task.taskId);
+ return;
+ }
+
+ // Network / transient error — increment retry counter
+ incrementRetry(task.taskId);
+
+ // Re-read current task state from the store (retries may have just incremented)
+ const currentTask = useKieAIStore
+ .getState()
+ .tasks.find((t) => t.taskId === task.taskId);
+
+ const currentRetries = currentTask ? currentTask.retries : MAX_POLL_RETRIES;
+
+ if (currentRetries >= MAX_POLL_RETRIES) {
+ console.warn(
+ `[KieAIPoller] ${task.taskId} exhausted ${MAX_POLL_RETRIES} retries — marking failed`,
+ );
+ markFailed(task.taskId);
+ setKieAIItemState(task.mediaId, false, true);
} else {
- // Network error — retry
- console.warn(`[KieAIPoller] poll error for ${task.taskId}, retrying:`, err);
+ console.warn(
+ `[KieAIPoller] poll error for ${task.taskId} (retry ${currentRetries}/${MAX_POLL_RETRIES}):`,
+ err,
+ );
const t = setTimeout(doPoll, interval);
timersRef.current.set(task.taskId, t);
}
@@ -119,16 +133,17 @@ export function useKieAIPoller() {
timersRef.current.set(task.taskId, t);
}
- // Cancel timers for tasks that are no longer in the list
+ // Cancel timers for tasks removed from the active list
for (const [taskId, timer] of timersRef.current) {
- if (!projectTasks.some((t) => t.taskId === taskId)) {
+ const stillActive = activeTasks.some((t) => t.taskId === taskId);
+ if (!stillActive) {
clearTimeout(timer);
timersRef.current.delete(taskId);
}
}
- }, [tasks, projectId, removeTask, replacePlaceholderMedia]);
+ }, [tasks, projectId, removeTask, incrementRetry, markFailed, replacePlaceholder, setKieAIItemState]);
- // Cleanup all timers on unmount
+ // Cleanup on unmount
useEffect(() => {
return () => {
for (const timer of timersRef.current.values()) clearTimeout(timer);
diff --git a/apps/web/src/services/kieai/image-generation.ts b/apps/web/src/services/kieai/image-generation.ts
index 20c75871..7124dbc4 100644
--- a/apps/web/src/services/kieai/image-generation.ts
+++ b/apps/web/src/services/kieai/image-generation.ts
@@ -190,10 +190,11 @@ export async function pollTaskOnce(taskId: string): Promise<TaskRecord> {
* KieAI's resultJson shape varies by model — we try all known field paths.
*/
export function getResultUrl(record: TaskRecord): string {
- // Log the full record so we can see the real shape during development
- console.log("[KieAI] getResultUrl — full record:", JSON.stringify(record, null, 2));
-
- const rj = record.resultJson as Record<string, unknown> | null;
+ // resultJson is returned as a JSON string by the API — parse it if needed
+ const rj: Record<string, unknown> | null =
+ typeof record.resultJson === "string"
+ ? (JSON.parse(record.resultJson) as Record<string, unknown>)
+ : (record.resultJson as Record<string, unknown> | null);
// Try every known field path
const candidates: unknown[] = [
diff --git a/apps/web/src/stores/kieai-store.ts b/apps/web/src/stores/kieai-store.ts
index 18c4dd7e..ce60c802 100644
--- a/apps/web/src/stores/kieai-store.ts
+++ b/apps/web/src/stores/kieai-store.ts
@@ -2,15 +2,19 @@
* KieAI background task store
*
* Tracks pending KieAI generation tasks so the poller can resume them across
- * dialog closes, page refreshes, etc.
+ * dialog closes and page refreshes (tasks live on KieAI servers for ~3 days).
*
- * Persisted to localStorage so tasks survive a page reload while they're
- * still generating (KieAI tasks live on the server for ~3 days).
+ * Task lifecycle:
+ * pending → (poll ok) → removed (success / API fail)
+ * pending → (10 poll errors) → failed ← user can retry
+ * failed → (user clicks retry) → pending (retries reset)
*/
import { create } from "zustand";
import { persist } from "zustand/middleware";
+export const MAX_POLL_RETRIES = 10;
+
export interface PendingKieAITask {
/** KieAI task ID returned by createImageTask */
taskId: string;
@@ -24,12 +28,19 @@ export interface PendingKieAITask {
suggestedName: string;
/** Unix timestamp (ms) when the task was created */
createdAt: number;
+ /** Number of consecutive poll/download errors */
+ retries: number;
+ /** Set to true when retries >= MAX_POLL_RETRIES — poller stops, UI shows retry button */
+ failed: boolean;
}
interface KieAIStore {
tasks: PendingKieAITask[];
- addTask: (task: PendingKieAITask) => void;
+ addTask: (task: Omit<PendingKieAITask, "retries" | "failed">) => void;
removeTask: (taskId: string) => void;
+ incrementRetry: (taskId: string) => void;
+ markFailed: (taskId: string) => void;
+ retryTask: (taskId: string) => void;
getTasksForProject: (projectId: string) => PendingKieAITask[];
}
@@ -39,16 +50,37 @@ export const useKieAIStore = create<KieAIStore>()(
tasks: [],
addTask: (task) =>
- set((s) => ({ tasks: [...s.tasks, task] })),
+ set((s) => ({
+ tasks: [...s.tasks, { ...task, retries: 0, failed: false }],
+ })),
removeTask: (taskId) =>
set((s) => ({ tasks: s.tasks.filter((t) => t.taskId !== taskId) })),
+ incrementRetry: (taskId) =>
+ set((s) => ({
+ tasks: s.tasks.map((t) =>
+ t.taskId === taskId ? { ...t, retries: t.retries + 1 } : t,
+ ),
+ })),
+
+ markFailed: (taskId) =>
+ set((s) => ({
+ tasks: s.tasks.map((t) =>
+ t.taskId === taskId ? { ...t, failed: true } : t,
+ ),
+ })),
+
+ retryTask: (taskId) =>
+ set((s) => ({
+ tasks: s.tasks.map((t) =>
+ t.taskId === taskId ? { ...t, retries: 0, failed: false } : t,
+ ),
+ })),
+
getTasksForProject: (projectId) =>
get().tasks.filter((t) => t.projectId === projectId),
}),
- {
- name: "kieai-pending-tasks",
- },
+ { name: "kieai-pending-tasks" },
),
);
diff --git a/apps/web/src/stores/project-store.ts b/apps/web/src/stores/project-store.ts
index 3729bd26..8f346c95 100644
--- a/apps/web/src/stores/project-store.ts
+++ b/apps/web/src/stores/project-store.ts
@@ -110,6 +110,8 @@ export interface ProjectState {
addPlaceholderMedia: (item: MediaItem) => void;
/** Replace a pending placeholder with the actual result blob */
replacePlaceholderMedia: (mediaId: string, blob: Blob, name: string) => Promise<void>;
+ /** Flip isPending / kieaiError flags on a placeholder without full replacement */
+ setKieAIItemState: (mediaId: string, isPending: boolean, kieaiError: boolean) => void;
// Track actions
addTrack: (
@@ -862,6 +864,20 @@ export const useProjectStore = create<ProjectState>()(
});
},
+ setKieAIItemState: (mediaId: string, isPending: boolean, kieaiError: boolean) => {
+ const { project } = get();
+ const updatedItems = project.mediaLibrary.items.map((item) =>
+ item.id === mediaId ? { ...item, isPending, kieaiError } : item,
+ );
+ set({
+ project: {
+ ...project,
+ mediaLibrary: { items: updatedItems },
+ modifiedAt: Date.now(),
+ },
+ });
+ },
+
replacePlaceholderMedia: async (mediaId: string, blob: Blob, name: string) => {
const { project } = get();
diff --git a/packages/core/src/types/project.ts b/packages/core/src/types/project.ts
index d6f6a73b..d6e65cc5 100644
--- a/packages/core/src/types/project.ts
+++ b/packages/core/src/types/project.ts
@@ -42,6 +42,8 @@ export interface MediaItem {
readonly originalUrl?: string;
/** True while a background KieAI generation task is in progress */
readonly isPending?: boolean;
+ /** True when polling exhausted all retries — shows manual retry button */
+ readonly kieaiError?: boolean;
/** KieAI task ID used to poll for completion */
readonly kieaiTaskId?: string;
}