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): background polling architecture with placeholder media items

lvalics3b8caaeecf91
diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx
index 2a57f7f6..872f208e 100644
--- a/apps/web/src/App.tsx
+++ b/apps/web/src/App.tsx
@@ -10,6 +10,7 @@ import { useUIStore } from "./stores/ui-store";
import { useProjectStore } from "./stores/project-store";
import { useRouter } from "./hooks/use-router";
import { useProjectRecovery } from "./hooks/useProjectRecovery";
+import { useKieAIPoller } from "./hooks/useKieAIPoller";
import { SOCIAL_MEDIA_PRESETS, type SocialMediaCategory } from "@openreel/core";
import { TooltipProvider } from "@openreel/ui";
@@ -43,6 +44,8 @@ function App() {
const { route, params, navigate, parsedDimensions, fps } = useRouter();
const hasHandledInitialRoute = useRef(false);
+ useKieAIPoller();
+
useEffect(() => {
if (hasHandledInitialRoute.current) return;
diff --git a/apps/web/src/components/editor/AssetsPanel.tsx b/apps/web/src/components/editor/AssetsPanel.tsx
index d0a3c61c..f2bef59f 100644
--- a/apps/web/src/components/editor/AssetsPanel.tsx
+++ b/apps/web/src/components/editor/AssetsPanel.tsx
@@ -22,6 +22,7 @@ import {
LayoutGrid,
Grid2x2,
List,
+ Sparkles,
} from "lucide-react";
import {
BACKGROUND_PRESETS,
@@ -36,7 +37,17 @@ import { AspectRatioMatchDialog } from "./dialogs/AspectRatioMatchDialog";
import { AIGenTab } from "./AIGenTab";
import { useTtsAudioStore } from "../../stores/tts-store";
import { toast } from "../../stores/notification-store";
-import { IconButton, Input, ScrollArea } from "@openreel/ui";
+import {
+ IconButton,
+ Input,
+ ScrollArea,
+ ContextMenu,
+ ContextMenuContent,
+ ContextMenuItem,
+ ContextMenuTrigger,
+} from "@openreel/ui";
+import { KieAIImageDialog } from "./kieai/KieAIImageDialog";
+import { loadMediaBlob } from "../../services/media-storage";
const formatDuration = (seconds: number): string => {
const mins = Math.floor(seconds / 60);
@@ -61,6 +72,7 @@ const MediaThumbnail: React.FC<{
onReplace: () => void;
onDragStart: (e: React.DragEvent) => void;
onAddToTimeline: () => void;
+ onKieAI?: () => void;
}> = ({
item,
isSelected,
@@ -70,6 +82,7 @@ const MediaThumbnail: React.FC<{
onReplace,
onDragStart,
onAddToTimeline,
+ onKieAI,
}) => {
const [isHovered, setIsHovered] = useState(false);
@@ -108,15 +121,21 @@ const MediaThumbnail: React.FC<{
? "text-primary/50"
: "text-status-info/50";
- const borderClass = item.isPlaceholder
- ? "border-yellow-500 ring-1 ring-yellow-500/50 shadow-[0_0_10px_rgba(234,179,8,0.3)]"
- : isSelected
- ? "border-primary ring-1 ring-primary/50 shadow-[0_0_10px_rgba(34,197,94,0.2)]"
- : "border-border hover:border-text-secondary";
+ const borderClass = 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)]"
+ : isSelected
+ ? "border-primary ring-1 ring-primary/50 shadow-[0_0_10px_rgba(34,197,94,0.2)]"
+ : "border-border hover:border-text-secondary";
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.isPlaceholder ? (
+ {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>
+ ) : item.isPlaceholder ? (
<button
onClick={(e) => { e.stopPropagation(); onReplace(); }}
title="Replace asset"
@@ -126,6 +145,15 @@ const MediaThumbnail: React.FC<{
</button>
) : (
<>
+ {item.type === "image" && onKieAI && (
+ <button
+ onClick={(e) => { e.stopPropagation(); onKieAI(); }}
+ title="Create with KieAI"
+ className="p-2 bg-purple-500/20 rounded-full hover:bg-purple-500/40 backdrop-blur-sm transition-colors"
+ >
+ <Sparkles size={14} className="text-purple-300" />
+ </button>
+ )}
<button
onClick={(e) => { e.stopPropagation(); onAddToTimeline(); }}
title="Add to timeline"
@@ -148,6 +176,8 @@ const MediaThumbnail: React.FC<{
// --- List view ---
if (viewMode === "list") {
return (
+ <ContextMenu>
+ <ContextMenuTrigger asChild>
<div
draggable
onDragStart={onDragStart}
@@ -166,7 +196,12 @@ const MediaThumbnail: React.FC<{
<Icon size={14} className={iconColor} />
</div>
)}
- {item.isPlaceholder && (
+ {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 && (
<div className="absolute inset-0 flex items-center justify-center bg-yellow-500/10">
<AlertTriangle size={12} className="text-yellow-500/70" />
</div>
@@ -193,7 +228,11 @@ const MediaThumbnail: React.FC<{
{/* Hover actions */}
{isHovered && (
<div className="flex items-center gap-1 flex-shrink-0">
- {item.isPlaceholder ? (
+ {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>
+ ) : item.isPlaceholder ? (
<button
onClick={(e) => { e.stopPropagation(); onReplace(); }}
title="Replace asset"
@@ -203,6 +242,15 @@ const MediaThumbnail: React.FC<{
</button>
) : (
<>
+ {item.type === "image" && onKieAI && (
+ <button
+ onClick={(e) => { e.stopPropagation(); onKieAI(); }}
+ title="Create with KieAI"
+ className="p-1 bg-purple-500/20 rounded hover:bg-purple-500/40 transition-colors"
+ >
+ <Sparkles size={12} className="text-purple-300" />
+ </button>
+ )}
<button
onClick={(e) => { e.stopPropagation(); onAddToTimeline(); }}
title="Add to timeline"
@@ -226,6 +274,24 @@ const MediaThumbnail: React.FC<{
<div className="w-2 h-2 bg-primary rounded-full shadow-[0_0_8px_#22c55e] flex-shrink-0" />
)}
</div>
+ </ContextMenuTrigger>
+ <ContextMenuContent>
+ {item.type === "image" && onKieAI && (
+ <ContextMenuItem onClick={onKieAI}>
+ <Sparkles size={13} className="mr-2 text-primary" />
+ Create with KieAI
+ </ContextMenuItem>
+ )}
+ <ContextMenuItem onClick={(e) => { (e as React.MouseEvent).stopPropagation?.(); onAddToTimeline(); }}>
+ <Plus size={13} className="mr-2" />
+ Add to Timeline
+ </ContextMenuItem>
+ <ContextMenuItem onClick={(e) => { (e as React.MouseEvent).stopPropagation?.(); onDelete(); }} className="text-red-400 focus:text-red-400">
+ <Trash2 size={13} className="mr-2" />
+ Delete
+ </ContextMenuItem>
+ </ContextMenuContent>
+ </ContextMenu>
);
}
@@ -233,6 +299,8 @@ const MediaThumbnail: React.FC<{
const thumbnailIconSize = viewMode === "small" ? 16 : 24;
return (
+ <ContextMenu>
+ <ContextMenuTrigger asChild>
<div className="flex flex-col">
{/* Thumbnail container */}
<div
@@ -273,8 +341,16 @@ const MediaThumbnail: React.FC<{
</div>
)}
+ {/* Pending KieAI Badge */}
+ {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
+ </div>
+ )}
+
{/* Missing Asset Badge */}
- {item.isPlaceholder && (
+ {!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
@@ -288,8 +364,15 @@ const MediaThumbnail: React.FC<{
</div>
)}
+ {/* Pending overlay */}
+ {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.isPlaceholder && !isHovered && (
+ {!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>
@@ -327,6 +410,24 @@ const MediaThumbnail: React.FC<{
)}
</div>
</div>
+ </ContextMenuTrigger>
+ <ContextMenuContent>
+ {item.type === "image" && onKieAI && (
+ <ContextMenuItem onClick={onKieAI}>
+ <Sparkles size={13} className="mr-2 text-primary" />
+ Create with KieAI
+ </ContextMenuItem>
+ )}
+ <ContextMenuItem onClick={() => onAddToTimeline()}>
+ <Plus size={13} className="mr-2" />
+ Add to Timeline
+ </ContextMenuItem>
+ <ContextMenuItem onClick={() => onDelete()} className="text-red-400 focus:text-red-400">
+ <Trash2 size={13} className="mr-2" />
+ Delete
+ </ContextMenuItem>
+ </ContextMenuContent>
+ </ContextMenu>
);
};
@@ -390,6 +491,9 @@ export const AssetsPanel: React.FC = () => {
"all" | "solid" | "gradient" | "pattern" | "mesh"
>("all");
+ // KieAI image generation dialog
+ const [kieaiDialog, setKieaiDialog] = useState<{ file: File; previewUrl: string | null } | null>(null);
+
// Project store
const {
project,
@@ -616,6 +720,23 @@ export const AssetsPanel: React.FC = () => {
backgroundCategory === "all" || preset.category === backgroundCategory,
);
+ // Open KieAI dialog for an image asset
+ const handleOpenKieAI = useCallback(async (item: MediaItem) => {
+ try {
+ const blob = await loadMediaBlob(item.id);
+ if (!blob) {
+ toast.error("Asset not found", "Cannot load the image data for this asset.");
+ return;
+ }
+ const mimeType = blob.type || item.name.match(/\.png$/i) ? "image/png" : "image/jpeg";
+ const file = new File([blob], item.name, { type: mimeType as string });
+ setKieaiDialog({ file, previewUrl: item.thumbnailUrl });
+ } catch (err) {
+ console.error("[KieAI] Failed to load media blob:", err);
+ toast.error("Failed to open KieAI", err instanceof Error ? err.message : "Unknown error");
+ }
+ }, []);
+
return (
<div
data-tour="assets"
@@ -795,6 +916,7 @@ export const AssetsPanel: React.FC = () => {
onReplace={() => handleReplaceAsset(item.id)}
onDragStart={(e) => handleItemDragStart(e, item)}
onAddToTimeline={() => handleAddToTimeline(item)}
+ onKieAI={item.type === "image" ? () => handleOpenKieAI(item) : undefined}
/>
))}
{/* Add more media tile */}
@@ -1177,6 +1299,15 @@ export const AssetsPanel: React.FC = () => {
onCancel={handleCancelAspectRatioMatch}
/>
)}
+
+ {kieaiDialog && (
+ <KieAIImageDialog
+ open={true}
+ onClose={() => setKieaiDialog(null)}
+ sourceFile={kieaiDialog.file}
+ previewUrl={kieaiDialog.previewUrl}
+ />
+ )}
</div>
);
};
diff --git a/apps/web/src/components/editor/kieai/KieAIImageDialog.tsx b/apps/web/src/components/editor/kieai/KieAIImageDialog.tsx
new file mode 100644
index 00000000..d9536774
--- /dev/null
+++ b/apps/web/src/components/editor/kieai/KieAIImageDialog.tsx
@@ -0,0 +1,314 @@
+import { useState, useCallback, useRef } from "react";
+import { v4 as uuidv4 } from "uuid";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ Button,
+} from "@openreel/ui";
+import {
+ IMAGE_MODELS,
+ type ImageModelId,
+ type SeedreamInput,
+ type ZImageInput,
+ type NanoBanana2Input,
+ type Flux2Input,
+ type GrokInput,
+ type QwenInput,
+ createImageTask,
+} from "../../../services/kieai/image-generation";
+import { uploadFileStream } from "../../../services/kieai/file-upload";
+import { useProjectStore } from "../../../stores/project-store";
+import { useKieAIStore } from "../../../stores/kieai-store";
+import { ModelPicker } from "./ModelPicker";
+import { SeedreamForm } from "./forms/SeedreamForm";
+import { ZImageForm } from "./forms/ZImageForm";
+import { NanoBanana2Form } from "./forms/NanoBanana2Form";
+import { Flux2Form } from "./forms/Flux2Form";
+import { GrokForm } from "./forms/GrokForm";
+import { QwenForm } from "./forms/QwenForm";
+
+// ─── Default inputs per model ────────────────────────────────────────────────
+
+function defaultSeedream(): SeedreamInput {
+ return { prompt: "", image_urls: [], aspect_ratio: "1:1", quality: "basic" };
+}
+function defaultZImage(): ZImageInput {
+ return { prompt: "", aspect_ratio: "1:1" };
+}
+function defaultNanoBanana2(): NanoBanana2Input {
+ return { prompt: "", aspect_ratio: "1:1", resolution: "2K", output_format: "png" };
+}
+function defaultFlux2(): Flux2Input {
+ return { prompt: "", input_urls: [], aspect_ratio: "1:1", resolution: "1K" };
+}
+function defaultGrok(): GrokInput {
+ return { image_urls: [] };
+}
+function defaultQwen(imageUrl: string): QwenInput {
+ return { prompt: "", image_url: imageUrl, strength: 0.8, output_format: "png", acceleration: "regular" };
+}
+
+// ─── Step types ───────────────────────────────────────────────────────────────
+
+type Step = "pick" | "form" | "submitting" | "error";
+
+interface Props {
+ open: boolean;
+ onClose: () => void;
+ /** The source image file that was right-clicked */
+ sourceFile: File;
+ /** Thumbnail data URL for preview (avoids blob URL lifecycle issues) */
+ previewUrl: string | null;
+}
+
+export function KieAIImageDialog({ open, onClose, sourceFile, previewUrl }: Props) {
+ const [step, setStep] = useState<Step>("pick");
+ const [selectedModel, setSelectedModel] = useState<ImageModelId | null>(null);
+ const [errorMsg, setErrorMsg] = useState<string>("");
+ const abortRef = useRef<AbortController | null>(null);
+ const { project, addPlaceholderMedia } = useProjectStore();
+ const { addTask } = useKieAIStore();
+
+ // Per-model form state
+ const [seedream, setSeedream] = useState<SeedreamInput>(defaultSeedream);
+ const [zimage, setZimage] = useState<ZImageInput>(defaultZImage);
+ const [nanoBanana2, setNanoBanana2] = useState<NanoBanana2Input>(defaultNanoBanana2);
+ const [flux2, setFlux2] = useState<Flux2Input>(defaultFlux2);
+ const [grok, setGrok] = useState<GrokInput>(defaultGrok);
+ const [qwen, setQwen] = useState<QwenInput>(() => defaultQwen(""));
+
+ const handleClose = useCallback(() => {
+ abortRef.current?.abort();
+ // Reset state for next open
+ setStep("pick");
+ setSelectedModel(null);
+ setErrorMsg("");
+ setSeedream(defaultSeedream());
+ setZimage(defaultZImage());
+ setNanoBanana2(defaultNanoBanana2());
+ setFlux2(defaultFlux2());
+ setGrok(defaultGrok());
+ setQwen(defaultQwen(""));
+ onClose();
+ }, [onClose]);
+
+ const handleModelSelect = useCallback((model: ImageModelId) => {
+ setSelectedModel(model);
+ setStep("form");
+ }, []);
+
+ const handleBack = useCallback(() => {
+ setStep("pick");
+ setSelectedModel(null);
+ }, []);
+
+ const handleSubmit = useCallback(async () => {
+ if (!selectedModel || !project) return;
+
+ setStep("submitting");
+ setErrorMsg("");
+
+ const ac = new AbortController();
+ abortRef.current = ac;
+
+ try {
+ // Upload source image first (for models that need it)
+ let uploadedUrl = "";
+ const needsUpload = selectedModel !== IMAGE_MODELS.Z_IMAGE;
+
+ if (needsUpload) {
+ const uploaded = await uploadFileStream(sourceFile);
+ console.log("[KieAI] upload response:", uploaded);
+ // KieAI API may return url under different field names
+ uploadedUrl =
+ uploaded.fileUrl ||
+ uploaded.downloadUrl ||
+ (uploaded as unknown as Record<string, string>)["url"] ||
+ "";
+ if (!uploadedUrl) {
+ throw new Error("Upload succeeded but returned no file URL. Check console for response.");
+ }
+ }
+
+ // Build model-specific input
+ let input: Parameters<typeof createImageTask>[1];
+ switch (selectedModel) {
+ case IMAGE_MODELS.SEEDREAM:
+ input = { ...seedream, image_urls: [uploadedUrl] };
+ break;
+ case IMAGE_MODELS.Z_IMAGE:
+ input = zimage;
+ break;
+ case IMAGE_MODELS.NANO_BANANA2:
+ input = { ...nanoBanana2, image_input: [uploadedUrl] };
+ break;
+ case IMAGE_MODELS.FLUX2:
+ input = { ...flux2, input_urls: [uploadedUrl] };
+ break;
+ case IMAGE_MODELS.GROK:
+ input = { ...grok, image_urls: [uploadedUrl] };
+ break;
+ case IMAGE_MODELS.QWEN:
+ input = { ...qwen, image_url: uploadedUrl };
+ break;
+ default:
+ throw new Error("Unknown model");
+ }
+
+ console.log("[KieAI] createTask payload:", { model: selectedModel, input });
+ const taskId = await createImageTask(selectedModel, input);
+
+ // Create a placeholder in the media library immediately
+ const ext = "png"; // optimistic; poller will use actual blob mime
+ const base = sourceFile.name.replace(/\.[^.]+$/, "");
+ const suggestedName = `${base}_kieai.${ext}`;
+ const mediaId = uuidv4();
+
+ const placeholder = {
+ id: mediaId,
+ name: suggestedName,
+ type: "image" as const,
+ fileHandle: null,
+ blob: null,
+ metadata: {
+ duration: 0,
+ width: 0,
+ height: 0,
+ frameRate: 0,
+ codec: "",
+ sampleRate: 0,
+ channels: 0,
+ fileSize: 0,
+ },
+ thumbnailUrl: previewUrl,
+ waveformData: null,
+ isPlaceholder: true,
+ isPending: true,
+ kieaiTaskId: taskId,
+ };
+
+ addPlaceholderMedia(placeholder);
+ addTask({
+ taskId,
+ mediaId,
+ projectId: project.id,
+ type: "image",
+ suggestedName,
+ createdAt: Date.now(),
+ });
+
+ // Close the dialog immediately — background poller takes it from here
+ handleClose();
+ } catch (err) {
+ if (err instanceof Error && err.name === "AbortError") return;
+ setErrorMsg(err instanceof Error ? err.message : String(err));
+ setStep("error");
+ }
+ }, [selectedModel, project, sourceFile, previewUrl, seedream, zimage, nanoBanana2, flux2, grok, qwen, addPlaceholderMedia, addTask, handleClose]);
+
+ // ─── Derived display ──────────────────────────────────────────────────────
+
+ const modelLabel = selectedModel
+ ? selectedModel.split("/")[0].replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())
+ : "";
+
+ return (
+ <Dialog open={open} onOpenChange={(o) => { if (!o) handleClose(); }}>
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <DialogTitle>
+ {step === "pick" && "Create with KieAI"}
+ {step === "form" && `${modelLabel}`}
+ {step === "submitting" && "Submitting…"}
+ {step === "error" && "Submission Failed"}
+ </DialogTitle>
+ </DialogHeader>
+
+ <div className="mt-2 max-h-[70vh] overflow-y-auto pr-1">
+ {/* Source image preview strip */}
+ {(
+ <div className="mb-4 flex items-center gap-2 rounded-lg border border-border bg-background-elevated p-2">
+ {previewUrl ? (
+ <img
+ src={previewUrl}
+ alt="Source"
+ className="h-10 w-10 rounded object-cover flex-shrink-0"
+ />
+ ) : (
+ <div className="h-10 w-10 rounded bg-background-tertiary flex items-center justify-center flex-shrink-0">
+ <svg className="h-5 w-5 text-text-muted" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5}>
+ <rect x="3" y="3" width="18" height="18" rx="2" /><path d="m3 9 4-4 4 4 4-4 4 4" /><circle cx="8.5" cy="14.5" r="1.5" />
+ </svg>
+ </div>
+ )}
+ <div className="min-w-0">
+ <p className="truncate text-xs font-medium text-text-primary">{sourceFile.name}</p>
+ <p className="text-[10px] text-text-muted">Source image</p>
+ </div>
+ </div>
+ )}
+
+ {step === "pick" && <ModelPicker onSelect={handleModelSelect} />}
+
+ {step === "form" && selectedModel === IMAGE_MODELS.SEEDREAM && (
+ <SeedreamForm value={seedream} onChange={setSeedream} onSubmit={handleSubmit} isLoading={false} />
+ )}
+ {step === "form" && selectedModel === IMAGE_MODELS.Z_IMAGE && (
+ <ZImageForm value={zimage} onChange={setZimage} onSubmit={handleSubmit} isLoading={false} />
+ )}
+ {step === "form" && selectedModel === IMAGE_MODELS.NANO_BANANA2 && (
+ <NanoBanana2Form value={nanoBanana2} onChange={setNanoBanana2} onSubmit={handleSubmit} isLoading={false} />
+ )}
+ {step === "form" && selectedModel === IMAGE_MODELS.FLUX2 && (
+ <Flux2Form value={flux2} onChange={setFlux2} onSubmit={handleSubmit} isLoading={false} />
+ )}
+ {step === "form" && selectedModel === IMAGE_MODELS.GROK && (
+ <GrokForm value={grok} onChange={setGrok} onSubmit={handleSubmit} isLoading={false} />
+ )}
+ {step === "form" && selectedModel === IMAGE_MODELS.QWEN && (
+ <QwenForm value={qwen} onChange={setQwen} onSubmit={handleSubmit} isLoading={false} />
+ )}
+
+ {step === "submitting" && (
+ <div className="space-y-4 py-4 text-center">
+ <div className="mx-auto h-10 w-10 animate-spin rounded-full border-4 border-border border-t-primary" />
+ <p className="text-sm text-text-secondary">Uploading & submitting task…</p>
+ <Button variant="outline" size="sm" onClick={() => { abortRef.current?.abort(); handleClose(); }}>
+ Cancel
+ </Button>
+ </div>
+ )}
+
+ {step === "error" && (
+ <div className="space-y-4 py-2">
+ <div className="rounded-lg border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-400">
+ {errorMsg}
+ </div>
+ <div className="flex gap-2">
+ <Button variant="outline" className="flex-1" onClick={handleClose}>
+ Close
+ </Button>
+ <Button className="flex-1" onClick={() => setStep("form")}>
+ Try Again
+ </Button>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {step === "form" && (
+ <div className="mt-2 flex justify-start">
+ <button
+ onClick={handleBack}
+ className="text-xs text-text-muted hover:text-text-primary transition-colors"
+ >
+ ← Back to model selection
+ </button>
+ </div>
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/components/editor/kieai/ModelPicker.tsx b/apps/web/src/components/editor/kieai/ModelPicker.tsx
new file mode 100644
index 00000000..b221c3cf
--- /dev/null
+++ b/apps/web/src/components/editor/kieai/ModelPicker.tsx
@@ -0,0 +1,89 @@
+import { IMAGE_MODELS, type ImageModelId } from "../../../services/kieai/image-generation";
+
+interface ModelInfo {
+ id: ImageModelId;
+ name: string;
+ description: string;
+ badge?: string;
+}
+
+const MODELS: ModelInfo[] = [
+ {
+ id: IMAGE_MODELS.SEEDREAM,
+ name: "Seedream 5 Lite",
+ description: "High-quality image-to-image with aspect ratio and quality control. Up to 4K output.",
+ badge: "4K",
+ },
+ {
+ id: IMAGE_MODELS.Z_IMAGE,
+ name: "Z-Image",
+ description: "Text-to-image generation. Source image is used as inspiration only.",
+ badge: "Text→Image",
+ },
+ {
+ id: IMAGE_MODELS.NANO_BANANA2,
+ name: "Nano Banana 2",
+ description: "Versatile generation with wide aspect ratio support and flexible resolution.",
+ badge: "Versatile",
+ },
+ {
+ id: IMAGE_MODELS.FLUX2,
+ name: "Flux 2 Pro",
+ description: "Professional image-to-image with up to 8 reference images and 2K output.",
+ badge: "Pro",
+ },
+ {
+ id: IMAGE_MODELS.GROK,
+ name: "Grok Imagine",
+ description: "Style and composition transfer with optional prompt guidance.",
+ badge: "Style",
+ },
+ {
+ id: IMAGE_MODELS.QWEN,
+ name: "Qwen",
+ description: "Fine-grained control over image transformation strength and quality.",
+ badge: "Control",
+ },
+];
+
+interface Props {
+ onSelect: (model: ImageModelId) => void;
+}
+
+export function ModelPicker({ onSelect }: Props) {
+ return (
+ <div className="space-y-3">
+ <p className="text-xs text-text-muted">Select a model to generate a new image from your source.</p>
+ <div className="grid grid-cols-1 gap-2">
+ {MODELS.map((m) => (
+ <button
+ key={m.id}
+ onClick={() => onSelect(m.id)}
+ className="flex items-start gap-3 rounded-lg border border-border bg-background-elevated p-3 text-left hover:border-primary hover:bg-primary/5 transition-colors"
+ >
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium text-text-primary">{m.name}</span>
+ {m.badge && (
+ <span className="rounded px-1.5 py-0.5 text-[10px] font-medium bg-primary/15 text-primary">
+ {m.badge}
+ </span>
+ )}
+ </div>
+ <p className="mt-0.5 text-xs text-text-muted leading-relaxed">{m.description}</p>
+ </div>
+ <svg
+ className="mt-0.5 h-4 w-4 flex-shrink-0 text-text-muted"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={2}
+ >
+ <path d="M9 18l6-6-6-6" strokeLinecap="round" strokeLinejoin="round" />
+ </svg>
+ </button>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/editor/kieai/forms/Flux2Form.tsx b/apps/web/src/components/editor/kieai/forms/Flux2Form.tsx
new file mode 100644
index 00000000..da7e3289
--- /dev/null
+++ b/apps/web/src/components/editor/kieai/forms/Flux2Form.tsx
@@ -0,0 +1,58 @@
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Button } from "@openreel/ui";
+import type { Flux2Input } from "../../../../services/kieai/image-generation";
+import { ASPECT_RATIO_OPTIONS } from "./shared";
+
+interface Props {
+ value: Flux2Input;
+ onChange: (v: Flux2Input) => void;
+ onSubmit: () => void;
+ isLoading: boolean;
+}
+
+export function Flux2Form({ value, onChange, onSubmit, isLoading }: Props) {
+ return (
+ <div className="space-y-4">
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-text-secondary">Prompt *</label>
+ <textarea
+ value={value.prompt}
+ onChange={(e) => onChange({ ...value, prompt: e.target.value })}
+ placeholder="Describe the image you want to generate…"
+ maxLength={2000}
+ rows={4}
+ className="w-full rounded-lg border border-border bg-background-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted resize-none outline-none focus:border-primary"
+ />
+ <p className="text-[10px] text-text-muted text-right">{value.prompt.length}/2000</p>
+ </div>
+
+ <div className="grid grid-cols-2 gap-3">
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-text-secondary">Aspect Ratio</label>
+ <Select value={value.aspect_ratio} onValueChange={(v) => onChange({ ...value, aspect_ratio: v as Flux2Input["aspect_ratio"] })}>
+ <SelectTrigger className="h-8 text-sm"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ {ASPECT_RATIO_OPTIONS.map((o) => (
+ <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-text-secondary">Resolution</label>
+ <Select value={value.resolution} onValueChange={(v) => onChange({ ...value, resolution: v as Flux2Input["resolution"] })}>
+ <SelectTrigger className="h-8 text-sm"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="1K">1K</SelectItem>
+ <SelectItem value="2K">2K</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+
+ <Button onClick={onSubmit} disabled={isLoading || !value.prompt.trim()} className="w-full">
+ {isLoading ? "Generating…" : "Generate with Flux 2"}
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/editor/kieai/forms/GrokForm.tsx b/apps/web/src/components/editor/kieai/forms/GrokForm.tsx
new file mode 100644
index 00000000..c47d926f
--- /dev/null
+++ b/apps/web/src/components/editor/kieai/forms/GrokForm.tsx
@@ -0,0 +1,36 @@
+import { Button } from "@openreel/ui";
+import type { GrokInput } from "../../../../services/kieai/image-generation";
+
+interface Props {
+ value: GrokInput;
+ onChange: (v: GrokInput) => void;
+ onSubmit: () => void;
+ isLoading: boolean;
+}
+
+export function GrokForm({ value, onChange, onSubmit, isLoading }: Props) {
+ return (
+ <div className="space-y-4">
+ <div className="p-2 rounded-lg bg-blue-500/10 border border-blue-500/30 text-xs text-blue-400">
+ Grok Imagine uses the source image as a reference for style and composition. An optional prompt can guide the transformation.
+ </div>
+
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-text-secondary">Prompt (optional)</label>
+ <textarea
+ value={value.prompt ?? ""}
+ onChange={(e) => onChange({ ...value, prompt: e.target.value || undefined })}
+ placeholder="Optional: describe what you want to change or emphasize…"
+ maxLength={1000}
+ rows={3}
+ className="w-full rounded-lg border border-border bg-background-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted resize-none outline-none focus:border-primary"
+ />
+ <p className="text-[10px] text-text-muted text-right">{(value.prompt ?? "").length}/1000</p>
+ </div>
+
+ <Button onClick={onSubmit} disabled={isLoading} className="w-full">
+ {isLoading ? "Generating…" : "Generate with Grok Imagine"}
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/editor/kieai/forms/NanoBanana2Form.tsx b/apps/web/src/components/editor/kieai/forms/NanoBanana2Form.tsx
new file mode 100644
index 00000000..153c0ba1
--- /dev/null
+++ b/apps/web/src/components/editor/kieai/forms/NanoBanana2Form.tsx
@@ -0,0 +1,79 @@
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Button } from "@openreel/ui";
+import type { NanoBanana2Input } from "../../../../services/kieai/image-generation";
+import { ASPECT_RATIO_OPTIONS_AUTO } from "./shared";
+
+interface Props {
+ value: NanoBanana2Input;
+ onChange: (v: NanoBanana2Input) => void;
+ onSubmit: () => void;
+ isLoading: boolean;
+}
+
+export function NanoBanana2Form({ value, onChange, onSubmit, isLoading }: Props) {
+ return (
+ <div className="space-y-4">
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-text-secondary">Prompt *</label>
+ <textarea
+ value={value.prompt}
+ onChange={(e) => onChange({ ...value, prompt: e.target.value })}
+ placeholder="Describe the image you want to generate…"
+ maxLength={2000}
+ rows={4}
+ className="w-full rounded-lg border border-border bg-background-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted resize-none outline-none focus:border-primary"
+ />
+ <p className="text-[10px] text-text-muted text-right">{value.prompt.length}/2000</p>
+ </div>
+
+ <div className="grid grid-cols-3 gap-3">
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-text-secondary">Aspect Ratio</label>
+ <Select
+ value={value.aspect_ratio ?? "1:1"}
+ onValueChange={(v) => onChange({ ...value, aspect_ratio: v as NanoBanana2Input["aspect_ratio"] })}
+ >
+ <SelectTrigger className="h-8 text-sm"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ {ASPECT_RATIO_OPTIONS_AUTO.map((o) => (
+ <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-text-secondary">Resolution</label>
+ <Select
+ value={value.resolution ?? "2K"}
+ onValueChange={(v) => onChange({ ...value, resolution: v as NanoBanana2Input["resolution"] })}
+ >
+ <SelectTrigger className="h-8 text-sm"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="1K">1K</SelectItem>
+ <SelectItem value="2K">2K</SelectItem>
+ <SelectItem value="4K">4K</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-text-secondary">Format</label>
+ <Select
+ value={value.output_format ?? "png"}
+ onValueChange={(v) => onChange({ ...value, output_format: v as NanoBanana2Input["output_format"] })}
+ >
+ <SelectTrigger className="h-8 text-sm"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="png">PNG</SelectItem>
+ <SelectItem value="jpg">JPG</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+
+ <Button onClick={onSubmit} disabled={isLoading || !value.prompt.trim()} className="w-full">
+ {isLoading ? "Generating…" : "Generate with Nano Banana 2"}
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/editor/kieai/forms/QwenForm.tsx b/apps/web/src/components/editor/kieai/forms/QwenForm.tsx
new file mode 100644
index 00000000..9ea6cfb7
--- /dev/null
+++ b/apps/web/src/components/editor/kieai/forms/QwenForm.tsx
@@ -0,0 +1,97 @@
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Button } from "@openreel/ui";
+import type { QwenInput } from "../../../../services/kieai/image-generation";
+
+interface Props {
+ value: QwenInput;
+ onChange: (v: QwenInput) => void;
+ onSubmit: () => void;
+ isLoading: boolean;
+}
+
+export function QwenForm({ value, onChange, onSubmit, isLoading }: Props) {
+ const strength = value.strength ?? 0.8;
+
+ return (
+ <div className="space-y-4">
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-text-secondary">Prompt *</label>
+ <textarea
+ value={value.prompt}
+ onChange={(e) => onChange({ ...value, prompt: e.target.value })}
+ placeholder="Describe the image you want to generate…"
+ maxLength={2000}
+ rows={4}
+ className="w-full rounded-lg border border-border bg-background-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted resize-none outline-none focus:border-primary"
+ />
+ <p className="text-[10px] text-text-muted text-right">{value.prompt.length}/2000</p>
+ </div>
+
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-text-secondary">
+ Strength — {strength.toFixed(1)}
+ <span className="ml-2 text-text-muted font-normal">(0 = preserve original, 1 = full remake)</span>
+ </label>
+ <input
+ type="range"
+ min={0}
+ max={1}
+ step={0.05}
+ value={strength}
+ onChange={(e) => onChange({ ...value, strength: parseFloat(e.target.value) })}
+ className="w-full accent-primary"
+ />
+ <div className="flex justify-between text-[10px] text-text-muted">
+ <span>Preserve</span>
+ <span>Remake</span>
+ </div>
+ </div>
+
+ <div className="grid grid-cols-2 gap-3">
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-text-secondary">Format</label>
+ <Select
+ value={value.output_format ?? "png"}
+ onValueChange={(v) => onChange({ ...value, output_format: v as QwenInput["output_format"] })}
+ >
+ <SelectTrigger className="h-8 text-sm"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="png">PNG</SelectItem>
+ <SelectItem value="jpeg">JPEG</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-text-secondary">Acceleration</label>
+ <Select
+ value={value.acceleration ?? "regular"}
+ onValueChange={(v) => onChange({ ...value, acceleration: v as QwenInput["acceleration"] })}
+ >
+ <SelectTrigger className="h-8 text-sm"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="none">None (best quality)</SelectItem>
+ <SelectItem value="regular">Regular</SelectItem>
+ <SelectItem value="high">High (fastest)</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-text-secondary">Negative Prompt (optional)</label>
+ <textarea
+ value={value.negative_prompt ?? ""}
+ onChange={(e) => onChange({ ...value, negative_prompt: e.target.value || undefined })}
+ placeholder="Describe what you don't want in the result…"
+ maxLength={500}
+ rows={2}
+ className="w-full rounded-lg border border-border bg-background-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted resize-none outline-none focus:border-primary"
+ />
+ </div>
+
+ <Button onClick={onSubmit} disabled={isLoading || !value.prompt.trim()} className="w-full">
+ {isLoading ? "Generating…" : "Generate with Qwen"}
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/editor/kieai/forms/SeedreamForm.tsx b/apps/web/src/components/editor/kieai/forms/SeedreamForm.tsx
new file mode 100644
index 00000000..12e4ca03
--- /dev/null
+++ b/apps/web/src/components/editor/kieai/forms/SeedreamForm.tsx
@@ -0,0 +1,58 @@
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Button } from "@openreel/ui";
+import type { SeedreamInput } from "../../../../services/kieai/image-generation";
+import { ASPECT_RATIO_OPTIONS } from "./shared";
+
+interface Props {
+ value: SeedreamInput;
+ onChange: (v: SeedreamInput) => void;
+ onSubmit: () => void;
+ isLoading: boolean;
+}
+
+export function SeedreamForm({ value, onChange, onSubmit, isLoading }: Props) {
+ return (
+ <div className="space-y-4">
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-text-secondary">Prompt *</label>
+ <textarea
+ value={value.prompt}
+ onChange={(e) => onChange({ ...value, prompt: e.target.value })}
+ placeholder="Describe the image you want to generate…"
+ maxLength={3000}
+ rows={4}
+ className="w-full rounded-lg border border-border bg-background-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted resize-none outline-none focus:border-primary"
+ />
+ <p className="text-[10px] text-text-muted text-right">{value.prompt.length}/3000</p>
+ </div>
+
+ <div className="grid grid-cols-2 gap-3">
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-text-secondary">Aspect Ratio</label>
+ <Select value={value.aspect_ratio} onValueChange={(v) => onChange({ ...value, aspect_ratio: v as SeedreamInput["aspect_ratio"] })}>
+ <SelectTrigger className="h-8 text-sm"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ {ASPECT_RATIO_OPTIONS.map((o) => (
+ <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-text-secondary">Quality</label>
+ <Select value={value.quality} onValueChange={(v) => onChange({ ...value, quality: v as SeedreamInput["quality"] })}>
+ <SelectTrigger className="h-8 text-sm"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="basic">Basic (2K)</SelectItem>
+ <SelectItem value="high">High (4K)</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+
+ <Button onClick={onSubmit} disabled={isLoading || !value.prompt.trim()} className="w-full">
+ {isLoading ? "Generating…" : "Generate with Seedream"}
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/editor/kieai/forms/ZImageForm.tsx b/apps/web/src/components/editor/kieai/forms/ZImageForm.tsx
new file mode 100644
index 00000000..b827f48b
--- /dev/null
+++ b/apps/web/src/components/editor/kieai/forms/ZImageForm.tsx
@@ -0,0 +1,49 @@
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Button } from "@openreel/ui";
+import type { ZImageInput } from "../../../../services/kieai/image-generation";
+import { ASPECT_RATIO_OPTIONS_BASIC } from "./shared";
+
+interface Props {
+ value: ZImageInput;
+ onChange: (v: ZImageInput) => void;
+ onSubmit: () => void;
+ isLoading: boolean;
+}
+
+export function ZImageForm({ value, onChange, onSubmit, isLoading }: Props) {
+ return (
+ <div className="space-y-4">
+ <div className="p-2 rounded-lg bg-yellow-500/10 border border-yellow-500/30 text-xs text-yellow-400">
+ Z-Image is text-to-image — the source image is used as inspiration only, not as a direct reference.
+ </div>
+
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-text-secondary">Prompt *</label>
+ <textarea
+ value={value.prompt}
+ onChange={(e) => onChange({ ...value, prompt: e.target.value })}
+ placeholder="Describe the image you want to generate…"
+ maxLength={1000}
+ rows={4}
+ className="w-full rounded-lg border border-border bg-background-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted resize-none outline-none focus:border-primary"
+ />
+ <p className="text-[10px] text-text-muted text-right">{value.prompt.length}/1000</p>
+ </div>
+
+ <div className="space-y-1.5">
+ <label className="text-xs font-medium text-text-secondary">Aspect Ratio</label>
+ <Select value={value.aspect_ratio} onValueChange={(v) => onChange({ ...value, aspect_ratio: v as ZImageInput["aspect_ratio"] })}>
+ <SelectTrigger className="h-8 text-sm"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ {ASPECT_RATIO_OPTIONS_BASIC.map((o) => (
+ <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+
+ <Button onClick={onSubmit} disabled={isLoading || !value.prompt.trim()} className="w-full">
+ {isLoading ? "Generating…" : "Generate with Z-Image"}
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/editor/kieai/forms/shared.ts b/apps/web/src/components/editor/kieai/forms/shared.ts
new file mode 100644
index 00000000..3346f618
--- /dev/null
+++ b/apps/web/src/components/editor/kieai/forms/shared.ts
@@ -0,0 +1,31 @@
+/** Shared constants and helpers for KieAI model forms */
+
+export const ASPECT_RATIO_OPTIONS = [
+ { value: "1:1", label: "1:1 Square" },
+ { value: "4:3", label: "4:3 Landscape" },
+ { value: "3:4", label: "3:4 Portrait" },
+ { value: "16:9", label: "16:9 Wide" },
+ { value: "9:16", label: "9:16 Story" },
+ { value: "2:3", label: "2:3 Portrait" },
+ { value: "3:2", label: "3:2 Landscape" },
+ { value: "21:9", label: "21:9 Cinematic" },
+] as const;
+
+export const ASPECT_RATIO_OPTIONS_AUTO = [
+ { value: "auto", label: "Auto" },
+ ...ASPECT_RATIO_OPTIONS,
+ { value: "1:4", label: "1:4 Tall" },
+ { value: "4:1", label: "4:1 Wide" },
+ { value: "1:8", label: "1:8 Very Tall" },
+ { value: "8:1", label: "8:1 Very Wide" },
+ { value: "4:5", label: "4:5 Portrait" },
+ { value: "5:4", label: "5:4 Landscape" },
+] as const;
+
+export const ASPECT_RATIO_OPTIONS_BASIC = [
+ { value: "1:1", label: "1:1 Square" },
+ { value: "4:3", label: "4:3 Landscape" },
+ { value: "3:4", label: "3:4 Portrait" },
+ { value: "16:9", label: "16:9 Wide" },
+ { value: "9:16", label: "9:16 Story" },
+] as const;
diff --git a/apps/web/src/hooks/useKieAIPoller.ts b/apps/web/src/hooks/useKieAIPoller.ts
new file mode 100644
index 00000000..12742dec
--- /dev/null
+++ b/apps/web/src/hooks/useKieAIPoller.ts
@@ -0,0 +1,138 @@
+/**
+ * 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
+ *
+ * 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.
+ */
+
+import { useEffect, useRef } from "react";
+import { useProjectStore } from "../stores/project-store";
+import { useKieAIStore } 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
+
+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 inFlightRef = useRef<Set<string>>(new Set());
+
+ useEffect(() => {
+ const projectTasks = tasks.filter((t) => t.projectId === projectId);
+
+ // 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
+
+ const interval =
+ task.type === "video" ? POLL_INTERVAL_VIDEO_MS : POLL_INTERVAL_IMAGE_MS;
+
+ 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`);
+
+ 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}`);
+
+ 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.
+ 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}`);
+ } 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
+ }
+ } finally {
+ removeTask(task.taskId);
+ }
+
+ } else if (record.state === "fail") {
+ console.warn(`[KieAIPoller] task ${task.taskId} failed: ${record.failMsg}`);
+ removeTask(task.taskId);
+
+ } else {
+ // Still generating — schedule next poll
+ console.log(`[KieAIPoller] task ${task.taskId} still ${record.state}, retry in ${interval / 1000}s`);
+ const t = setTimeout(doPoll, interval);
+ timersRef.current.set(task.taskId, t);
+ }
+ } catch (err) {
+ if (err instanceof KieAIError && err.code === 401) {
+ console.warn("[KieAIPoller] auth error — stopping poll for", task.taskId);
+ removeTask(task.taskId);
+ } else {
+ // Network error — retry
+ console.warn(`[KieAIPoller] poll error for ${task.taskId}, retrying:`, err);
+ const t = setTimeout(doPoll, interval);
+ timersRef.current.set(task.taskId, t);
+ }
+ } finally {
+ inFlightRef.current.delete(task.taskId);
+ }
+ };
+
+ const t = setTimeout(doPoll, firstDelay);
+ timersRef.current.set(task.taskId, t);
+ }
+
+ // Cancel timers for tasks that are no longer in the list
+ for (const [taskId, timer] of timersRef.current) {
+ if (!projectTasks.some((t) => t.taskId === taskId)) {
+ clearTimeout(timer);
+ timersRef.current.delete(taskId);
+ }
+ }
+ }, [tasks, projectId, removeTask, replacePlaceholderMedia]);
+
+ // Cleanup all timers on unmount
+ useEffect(() => {
+ return () => {
+ for (const timer of timersRef.current.values()) clearTimeout(timer);
+ timersRef.current.clear();
+ };
+ }, []);
+}
diff --git a/apps/web/src/services/kieai/client.ts b/apps/web/src/services/kieai/client.ts
index 68be627e..f44e0f4d 100644
--- a/apps/web/src/services/kieai/client.ts
+++ b/apps/web/src/services/kieai/client.ts
@@ -12,8 +12,11 @@ import { getSecret } from "../secure-storage";
import { KieAIError } from "./types";
import type { KieAIResponse } from "./types";
+/** File upload API base (kieai.redpandaai.co) */
export const KIEAI_BASE_URL = "https://kieai.redpandaai.co";
-export const KIEAI_SECRET_ID = "kieai-api-key";
+/** Generation API base (api.kie.ai) */
+export const KIEAI_API_BASE_URL = "https://api.kie.ai";
+export const KIEAI_SECRET_ID = "kie-ai";
async function getApiKey(): Promise<string> {
const key = await getSecret(KIEAI_SECRET_ID);
@@ -26,14 +29,15 @@ async function getApiKey(): Promise<string> {
return key;
}
-/** POST JSON — used by URL upload and Base64 upload */
+/** POST JSON — used by URL upload, Base64 upload, and task creation */
export async function kieaiPostJson<TBody extends object, TData>(
path: string,
body: TBody,
+ baseUrl = KIEAI_BASE_URL,
): Promise<TData> {
const apiKey = await getApiKey();
- const res = await fetch(`${KIEAI_BASE_URL}${path}`, {
+ const res = await fetch(`${baseUrl}${path}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -44,13 +48,34 @@ export async function kieaiPostJson<TBody extends object, TData>(
const json = (await res.json()) as KieAIResponse<TData>;
- if (!json.success) {
+ if (!json.success && json.code !== 200) {
throw new KieAIError(json.code, json.msg);
}
return json.data;
}
+/** GET with query params — used for task status polling */
+export async function kieaiGet<TData>(
+ path: string,
+ params: Record<string, string>,
+ baseUrl = KIEAI_API_BASE_URL,
+): Promise<TData> {
+ const apiKey = await getApiKey();
+ const url = new URL(`${baseUrl}${path}`);
+ for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
+
+ const res = await fetch(url.toString(), {
+ headers: { Authorization: `Bearer ${apiKey}` },
+ });
+
+ const json = (await res.json()) as KieAIResponse<TData>;
+ if (!json.success && json.code !== 200) {
+ throw new KieAIError(json.code, json.msg);
+ }
+ return json.data;
+}
+
/** POST multipart/form-data — used by stream upload */
export async function kieaiPostForm<TData>(
path: string,
@@ -69,7 +94,7 @@ export async function kieaiPostForm<TData>(
const json = (await res.json()) as KieAIResponse<TData>;
- if (!json.success) {
+ if (!json.success && json.code !== 200) {
throw new KieAIError(json.code, json.msg);
}
diff --git a/apps/web/src/services/kieai/file-upload.ts b/apps/web/src/services/kieai/file-upload.ts
index be66f8fe..342bd301 100644
--- a/apps/web/src/services/kieai/file-upload.ts
+++ b/apps/web/src/services/kieai/file-upload.ts
@@ -53,8 +53,8 @@ export async function uploadFileStream(
): Promise<UploadedFile> {
const form = new FormData();
form.append("file", file);
- if (options.uploadPath) form.append("uploadPath", options.uploadPath);
- if (options.fileName) form.append("fileName", options.fileName);
+ form.append("uploadPath", options.uploadPath ?? "openreel");
+ if (options.fileName) form.append("fileName", options.fileName);
return kieaiPostForm<UploadedFile>(UPLOAD_STREAM_PATH, form);
}
diff --git a/apps/web/src/services/kieai/image-generation.ts b/apps/web/src/services/kieai/image-generation.ts
new file mode 100644
index 00000000..20c75871
--- /dev/null
+++ b/apps/web/src/services/kieai/image-generation.ts
@@ -0,0 +1,232 @@
+/**
+ * KieAI Image Generation API
+ *
+ * Supports 6 image models. All use the same createTask endpoint and the same
+ * polling endpoint. Each model has its own typed input shape.
+ *
+ * Flow:
+ * 1. Upload source image via uploadFileStream → get fileUrl
+ * 2. createTask(model, input) → taskId
+ * 3. pollTask(taskId) → result image URL
+ *
+ * Docs: https://docs.kie.ai/market/common/get-task-detail
+ */
+
+import { kieaiPostJson, kieaiGet, KIEAI_API_BASE_URL } from "./client";
+import { KieAIError } from "./types";
+
+// ─── Model identifiers ────────────────────────────────────────────────────────
+
+export const IMAGE_MODELS = {
+ SEEDREAM: "seedream/5-lite-image-to-image",
+ Z_IMAGE: "z-image",
+ NANO_BANANA2: "nano-banana-2",
+ FLUX2: "flux-2/pro-image-to-image",
+ GROK: "grok-imagine/image-to-image",
+ QWEN: "qwen/image-to-image",
+} as const;
+
+export type ImageModelId = typeof IMAGE_MODELS[keyof typeof IMAGE_MODELS];
+
+// ─── Per-model input types ────────────────────────────────────────────────────
+
+export type AspectRatio =
+ | "1:1" | "4:3" | "3:4" | "16:9" | "9:16"
+ | "2:3" | "3:2" | "21:9" | "auto";
+
+export interface SeedreamInput {
+ prompt: string;
+ /** Uploaded image URLs (max 14). Use uploadFileStream first. */
+ image_urls: string[];
+ aspect_ratio: AspectRatio;
+ /** basic = 2K, high = 4K */
+ quality: "basic" | "high";
+}
+
+export interface ZImageInput {
+ prompt: string;
+ /** Z-Image is text-to-image — no image_url field */
+ aspect_ratio: "1:1" | "4:3" | "3:4" | "16:9" | "9:16";
+}
+
+export interface NanoBanana2Input {
+ prompt: string;
+ /** Optional reference images (max 14) */
+ image_input?: string[];
+ aspect_ratio?: AspectRatio | "1:4" | "1:8" | "4:1" | "4:5" | "5:4" | "8:1";
+ resolution?: "1K" | "2K" | "4K";
+ output_format?: "png" | "jpg";
+}
+
+export interface Flux2Input {
+ /** Reference images (1–8). Use uploadFileStream first. */
+ input_urls: string[];
+ prompt: string;
+ aspect_ratio: AspectRatio;
+ resolution: "1K" | "2K";
+}
+
+export interface GrokInput {
+ /** Single reference image URL. Use uploadFileStream first. */
+ image_urls: string[];
+ prompt?: string;
+}
+
+export interface QwenInput {
+ prompt: string;
+ /** Single reference image URL. Use uploadFileStream first. */
+ image_url: string;
+ /** 0 = preserve original, 1 = full remake. Default 0.8 */
+ strength?: number;
+ output_format?: "png" | "jpeg";
+ acceleration?: "none" | "regular" | "high";
+ negative_prompt?: string;
+ seed?: number;
+ /** 2–250. Default 30 */
+ num_inference_steps?: number;
+ /** 0–20. Default 2.5 */
+ guidance_scale?: number;
+ enable_safety_checker?: boolean;
+}
+
+export type ImageModelInput =
+ | SeedreamInput
+ | ZImageInput
+ | NanoBanana2Input
+ | Flux2Input
+ | GrokInput
+ | QwenInput;
+
+// ─── Task lifecycle ───────────────────────────────────────────────────────────
+
+export type TaskState = "waiting" | "queuing" | "generating" | "success" | "fail";
+
+export interface TaskRecord {
+ taskId: string;
+ model: string;
+ state: TaskState;
+ resultJson: { resultUrls?: string[]; resultObject?: unknown } | null;
+ failCode?: number;
+ failMsg?: string;
+ costTime?: number;
+ completeTime?: string;
+ createTime: string;
+ updateTime: string;
+ progress?: number;
+}
+
+// ─── Create task ──────────────────────────────────────────────────────────────
+
+export async function createImageTask(
+ model: ImageModelId,
+ input: ImageModelInput,
+): Promise<string> {
+ const data = await kieaiPostJson<object, { taskId: string }>(
+ "/api/v1/jobs/createTask",
+ { model, input },
+ KIEAI_API_BASE_URL,
+ );
+ return data.taskId;
+}
+
+// ─── Poll task ────────────────────────────────────────────────────────────────
+
+const POLL_INTERVALS = [2000, 2000, 3000, 3000, 5000]; // ms, last value repeats
+
+/**
+ * Poll the task until it reaches `success` or `fail`.
+ * Calls `onProgress` with the latest record on each poll.
+ *
+ * @param signal - AbortSignal to cancel polling
+ */
+export async function pollTask(
+ taskId: string,
+ onProgress?: (record: TaskRecord) => void,
+ signal?: AbortSignal,
+): Promise<TaskRecord> {
+ let attempt = 0;
+
+ while (!signal?.aborted) {
+ const record = await kieaiGet<TaskRecord>(
+ "/api/v1/jobs/recordInfo",
+ { taskId },
+ KIEAI_API_BASE_URL,
+ );
+
+ onProgress?.(record);
+
+ if (record.state === "success") return record;
+ if (record.state === "fail") {
+ throw new KieAIError(record.failCode ?? 500, record.failMsg ?? "Generation failed");
+ }
+
+ // Wait before next poll
+ const delay = POLL_INTERVALS[Math.min(attempt, POLL_INTERVALS.length - 1)];
+ attempt++;
+ await new Promise<void>((res, rej) => {
+ const t = setTimeout(res, delay);
+ signal?.addEventListener("abort", () => { clearTimeout(t); rej(new DOMException("Aborted", "AbortError")); });
+ });
+ }
+
+ throw new DOMException("Polling cancelled", "AbortError");
+}
+
+/**
+ * Single poll — returns the latest TaskRecord without looping.
+ * Use this in background polling hooks that manage their own interval.
+ */
+export async function pollTaskOnce(taskId: string): Promise<TaskRecord> {
+ return kieaiGet<TaskRecord>(
+ "/api/v1/jobs/recordInfo",
+ { taskId },
+ KIEAI_API_BASE_URL,
+ );
+}
+
+/**
+ * Extract the first result image URL from a completed task.
+ *
+ * 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;
+
+ // Try every known field path
+ const candidates: unknown[] = [
+ rj?.resultUrls,
+ rj?.result_urls,
+ rj?.images,
+ rj?.outputs,
+ rj?.urls,
+ ];
+
+ for (const candidate of candidates) {
+ if (Array.isArray(candidate) && typeof candidate[0] === "string" && candidate[0]) {
+ return candidate[0];
+ }
+ }
+
+ // Single-string fields
+ const stringFields = ["resultUrl", "result_url", "url", "image_url", "output", "imageUrl"];
+ for (const field of stringFields) {
+ const val = rj?.[field];
+ if (typeof val === "string" && val) return val;
+ }
+
+ // Nested: resultJson.result.url or resultJson.data.url
+ for (const wrapper of ["result", "data", "output"]) {
+ const nested = rj?.[wrapper] as Record<string, unknown> | undefined;
+ if (nested && typeof nested === "object") {
+ for (const field of ["url", "image_url", "imageUrl", "resultUrl"]) {
+ if (typeof nested[field] === "string" && nested[field]) return nested[field] as string;
+ }
+ if (Array.isArray(nested.urls) && typeof nested.urls[0] === "string") return nested.urls[0];
+ }
+ }
+
+ throw new KieAIError(500, "No result URL in completed task — check console for raw record");
+}
diff --git a/apps/web/src/services/kieai/index.ts b/apps/web/src/services/kieai/index.ts
index 71505b20..28b8d066 100644
--- a/apps/web/src/services/kieai/index.ts
+++ b/apps/web/src/services/kieai/index.ts
@@ -27,3 +27,24 @@ export {
uploadFileStream,
uploadFileBase64,
} from "./file-upload";
+
+export {
+ IMAGE_MODELS,
+ createImageTask,
+ pollTask,
+ pollTaskOnce,
+ getResultUrl,
+} from "./image-generation";
+
+export type {
+ ImageModelId,
+ ImageModelInput,
+ SeedreamInput,
+ ZImageInput,
+ NanoBanana2Input,
+ Flux2Input,
+ GrokInput,
+ QwenInput,
+ TaskRecord,
+ TaskState,
+} from "./image-generation";
diff --git a/apps/web/src/stores/kieai-store.ts b/apps/web/src/stores/kieai-store.ts
new file mode 100644
index 00000000..18c4dd7e
--- /dev/null
+++ b/apps/web/src/stores/kieai-store.ts
@@ -0,0 +1,54 @@
+/**
+ * KieAI background task store
+ *
+ * Tracks pending KieAI generation tasks so the poller can resume them across
+ * dialog closes, page refreshes, etc.
+ *
+ * Persisted to localStorage so tasks survive a page reload while they're
+ * still generating (KieAI tasks live on the server for ~3 days).
+ */
+
+import { create } from "zustand";
+import { persist } from "zustand/middleware";
+
+export interface PendingKieAITask {
+ /** KieAI task ID returned by createImageTask */
+ taskId: string;
+ /** The MediaItem placeholder ID in the project's media library */
+ mediaId: string;
+ /** The project this task belongs to */
+ projectId: string;
+ /** "image" | "video" — determines polling interval */
+ type: "image" | "video";
+ /** Suggested file name for the result (e.g. "photo_kieai.png") */
+ suggestedName: string;
+ /** Unix timestamp (ms) when the task was created */
+ createdAt: number;
+}
+
+interface KieAIStore {
+ tasks: PendingKieAITask[];
+ addTask: (task: PendingKieAITask) => void;
+ removeTask: (taskId: string) => void;
+ getTasksForProject: (projectId: string) => PendingKieAITask[];
+}
+
+export const useKieAIStore = create<KieAIStore>()(
+ persist(
+ (set, get) => ({
+ tasks: [],
+
+ addTask: (task) =>
+ set((s) => ({ tasks: [...s.tasks, task] })),
+
+ removeTask: (taskId) =>
+ set((s) => ({ tasks: s.tasks.filter((t) => t.taskId !== taskId) })),
+
+ getTasksForProject: (projectId) =>
+ get().tasks.filter((t) => t.projectId === projectId),
+ }),
+ {
+ name: "kieai-pending-tasks",
+ },
+ ),
+);
diff --git a/apps/web/src/stores/project-store.ts b/apps/web/src/stores/project-store.ts
index 9dbf23d6..3729bd26 100644
--- a/apps/web/src/stores/project-store.ts
+++ b/apps/web/src/stores/project-store.ts
@@ -106,6 +106,10 @@ export interface ProjectState {
replaceMediaAsset: (mediaId: string, file: File) => Promise<ActionResult>;
renameMedia: (mediaId: string, name: string) => Promise<ActionResult>;
getMediaItem: (mediaId: string) => MediaItem | undefined;
+ /** Add a pending placeholder for a background KieAI task */
+ addPlaceholderMedia: (item: MediaItem) => void;
+ /** Replace a pending placeholder with the actual result blob */
+ replacePlaceholderMedia: (mediaId: string, blob: Blob, name: string) => Promise<void>;
// Track actions
addTrack: (
@@ -844,6 +848,99 @@ export const useProjectStore = create<ProjectState>()(
return project.mediaLibrary.items.find((item) => item.id === mediaId);
},
+ addPlaceholderMedia: (item: MediaItem) => {
+ const { project } = get();
+ set({
+ project: {
+ ...project,
+ mediaLibrary: {
+ ...project.mediaLibrary,
+ items: [...project.mediaLibrary.items, item],
+ },
+ modifiedAt: Date.now(),
+ },
+ });
+ },
+
+ replacePlaceholderMedia: async (mediaId: string, blob: Blob, name: string) => {
+ const { project } = get();
+
+ // For images use createImageBitmap (no mediaBridge dependency).
+ // This avoids WASM initialisation races and works immediately in any context.
+ let thumbnailUrl: string | null = null;
+ let width = 0;
+ let height = 0;
+
+ if (blob.size > 0 && blob.type.startsWith("image/")) {
+ try {
+ const bitmap = await createImageBitmap(blob);
+ width = bitmap.width;
+ height = bitmap.height;
+
+ const THUMB_SIZE = 320;
+ const scale = Math.min(THUMB_SIZE / bitmap.width, THUMB_SIZE / bitmap.height, 1);
+ const tw = Math.round(bitmap.width * scale);
+ const th = Math.round(bitmap.height * scale);
+
+ const canvas = new OffscreenCanvas(tw, th);
+ const ctx = canvas.getContext("2d")!;
+ ctx.drawImage(bitmap, 0, 0, tw, th);
+ bitmap.close();
+
+ const thumbBlob = await canvas.convertToBlob({ type: "image/jpeg", quality: 0.75 });
+ thumbnailUrl = await new Promise<string>((resolve) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(reader.result as string);
+ reader.readAsDataURL(thumbBlob);
+ });
+ } catch (thumbErr) {
+ console.warn("[ProjectStore] KieAI thumbnail generation failed:", thumbErr);
+ }
+ }
+
+ const file = new File([blob], name, { type: blob.type || "image/png" });
+
+ const updatedItem: MediaItem = {
+ id: mediaId,
+ name,
+ type: "image",
+ fileHandle: null,
+ blob: file,
+ metadata: {
+ duration: 0,
+ width,
+ height,
+ frameRate: 0,
+ codec: "",
+ sampleRate: 0,
+ channels: 0,
+ fileSize: file.size,
+ },
+ thumbnailUrl,
+ waveformData: null,
+ isPlaceholder: false,
+ isPending: false,
+ };
+
+ const updatedItems = project.mediaLibrary.items.map((item) =>
+ item.id === mediaId ? updatedItem : item,
+ );
+
+ set({
+ project: {
+ ...project,
+ mediaLibrary: { items: updatedItems },
+ modifiedAt: Date.now(),
+ },
+ });
+
+ try {
+ await saveMediaBlob(project.id, mediaId, file, updatedItem.metadata);
+ } catch (err) {
+ console.error("[ProjectStore] Failed to persist KieAI result blob:", err);
+ }
+ },
+
// Track actions
addTrack: async (
trackType: "video" | "audio" | "image" | "text" | "graphics",
diff --git a/packages/core/src/storage/types.ts b/packages/core/src/storage/types.ts
index 75dfdb10..67477f5a 100644
--- a/packages/core/src/storage/types.ts
+++ b/packages/core/src/storage/types.ts
@@ -1,6 +1,6 @@
import type { Project, MediaMetadata } from "../types";
-export const DB_VERSION = 1;
+export const DB_VERSION = 3;
export const DB_NAME = "openreel-db";
diff --git a/packages/core/src/types/project.ts b/packages/core/src/types/project.ts
index e8d81fe3..d6f6a73b 100644
--- a/packages/core/src/types/project.ts
+++ b/packages/core/src/types/project.ts
@@ -40,6 +40,10 @@ export interface MediaItem {
readonly filmstripThumbnails?: FilmstripThumbnail[];
readonly isPlaceholder?: boolean;
readonly originalUrl?: string;
+ /** True while a background KieAI generation task is in progress */
+ readonly isPending?: boolean;
+ /** KieAI task ID used to poll for completion */
+ readonly kieaiTaskId?: string;
}
/** Thumbnail for filmstrip display in timeline */