🎥 Make videos programmatically with React
Use Remotion client/render frame, Add image attachment support and properly propagate model selection from LandingPage
ASchwadb3020ce93749
diff --git a/bun.lock b/bun.lockindex d88bcd0b33..7cddb0bccd 100644--- a/bun.lock+++ b/bun.lock@@ -1685,6 +1685,7 @@"@remotion/tailwind-v4": "workspace:*","@remotion/three": "workspace:*","@remotion/transitions": "workspace:*",+ "@remotion/web-renderer": "workspace:*","ai": "5.0.104","class-variance-authority": "0.7.1","clsx": "2.1.1",diff --git a/packages/template-prompt-to-motion-graphics/package.json b/packages/template-prompt-to-motion-graphics/package.jsonindex 2cafd65baf..0cb8c43cc8 100644--- a/packages/template-prompt-to-motion-graphics/package.json+++ b/packages/template-prompt-to-motion-graphics/package.json@@ -38,6 +38,7 @@"@remotion/tailwind-v4": "workspace:*","@remotion/three": "workspace:*","@remotion/transitions": "workspace:*",+ "@remotion/web-renderer": "workspace:*","ai": "5.0.104","class-variance-authority": "0.7.1","clsx": "2.1.1",diff --git a/packages/template-prompt-to-motion-graphics/src/app/api/generate/route.ts b/packages/template-prompt-to-motion-graphics/src/app/api/generate/route.tsindex ca37f289ad..accd5bcc3d 100644--- a/packages/template-prompt-to-motion-graphics/src/app/api/generate/route.ts+++ b/packages/template-prompt-to-motion-graphics/src/app/api/generate/route.ts@@ -273,6 +273,8 @@ interface GenerateRequest {errorCorrection?: ErrorCorrectionContext;/** Skills already used in this conversation (to avoid redundant skill content) */previouslyUsedSkills?: string[];+ /** Base64 image data URL for visual context */+ frameImage?: string;}interface GenerateResponse {@@ -296,6 +298,7 @@ export async function POST(req: Request) {hasManualEdits = false,errorCorrection,previouslyUsedSkills = [],+ frameImage,}: GenerateRequest = await req.json();const apiKey = process.env.OPENAI_API_KEY;@@ -442,7 +445,7 @@ Focus ONLY on fixing the error. Do not make other changes.`;}}- const editPrompt = `## CURRENT CODE:+ const editPromptText = `## CURRENT CODE:\`\`\`tsx${currentCode}\`\`\`@@ -452,6 +455,7 @@ ${errorCorrectionNotice}## USER REQUEST:${prompt}+${frameImage ? "\n(See the attached image for visual reference)" : ""}Analyze the request and decide: use targeted edits (type: "edit") for small changes, or full replacement (type: "full") for major restructuring.`;@@ -461,13 +465,30 @@ Analyze the request and decide: use targeted edits (type: "edit") for small chan"model:",modelName,"skills:",- detectedSkills.length > 0 ? detectedSkills.join(", ") : "general"+ detectedSkills.length > 0 ? detectedSkills.join(", ") : "general",+ frameImage ? "(with image)" : "");+ // Build messages array - include image if provided+ const editMessages: Array<{+ role: "user";+ content: Array<{ type: "text"; text: string } | { type: "image"; image: string }>;+ }> = [+ {+ role: "user" as const,+ content: frameImage+ ? [+ { type: "text" as const, text: editPromptText },+ { type: "image" as const, image: frameImage },+ ]+ : [{ type: "text" as const, text: editPromptText }],+ },+ ];+const editResult = await generateObject({model: openai(modelName),system: FOLLOW_UP_SYSTEM_PROMPT,- prompt: editPrompt,+ messages: editMessages,schema: FollowUpResponseSchema,});@@ -540,10 +561,30 @@ Analyze the request and decide: use targeted edits (type: "edit") for small chan// INITIAL GENERATION: Use streaming for new animationstry {+ // Build messages for initial generation (supports image reference)+ const initialPromptText = frameImage+ ? `${prompt}\n\n(See the attached image for visual reference)`+ : prompt;++ const initialMessages: Array<{+ role: "user";+ content: Array<{ type: "text"; text: string } | { type: "image"; image: string }>;+ }> = [+ {+ role: "user" as const,+ content: frameImage+ ? [+ { type: "text" as const, text: initialPromptText },+ { type: "image" as const, image: frameImage },+ ]+ : [{ type: "text" as const, text: initialPromptText }],+ },+ ];+const result = streamText({model: openai(modelName),system: enhancedSystemPrompt,- prompt,+ messages: initialMessages,...(reasoningEffort && {providerOptions: {openai: {@@ -560,7 +601,8 @@ Analyze the request and decide: use targeted edits (type: "edit") for small chanmodelName,"skills:",detectedSkills.length > 0 ? detectedSkills.join(", ") : "general",- reasoningEffort ? `reasoning_effort: ${reasoningEffort}` : ""+ reasoningEffort ? `reasoning_effort: ${reasoningEffort}` : "",+ frameImage ? "(with image)" : "");// Get the original stream responsediff --git a/packages/template-prompt-to-motion-graphics/src/app/generate/page.tsx b/packages/template-prompt-to-motion-graphics/src/app/generate/page.tsxindex 1335bc1fce..8cb6887ffd 100644--- a/packages/template-prompt-to-motion-graphics/src/app/generate/page.tsx+++ b/packages/template-prompt-to-motion-graphics/src/app/generate/page.tsx@@ -8,7 +8,8 @@ import { CodeEditor } from "../../components/CodeEditor";import { AnimationPlayer } from "../../components/AnimationPlayer";import { PageLayout } from "../../components/PageLayout";import { ChatSidebar, type ChatSidebarRef } from "../../components/ChatSidebar";-import type { StreamPhase, GenerationErrorType } from "../../types/generation";+import type { StreamPhase, GenerationErrorType, ModelId } from "../../types/generation";+import { MODELS } from "../../types/generation";import { examples } from "../../examples/code";import { useAnimationState } from "../../hooks/useAnimationState";import { useConversationState } from "../../hooks/useConversationState";@@ -24,6 +25,7 @@ const MAX_CORRECTION_ATTEMPTS = 3;function GeneratePageContent() {const searchParams = useSearchParams();const initialPrompt = searchParams.get("prompt") || "";+ const initialModel = (searchParams.get("model") as ModelId) || MODELS[2].id;// If we have an initial prompt from URL, start in streaming state// so syntax highlighting is disabled from the beginning@@ -33,6 +35,7 @@ function GeneratePageContent() {examples[0]?.durationInFrames || 150,);const [fps, setFps] = useState(examples[0]?.fps || 30);+ const [currentFrame, setCurrentFrame] = useState(0);const [isStreaming, setIsStreaming] = useState(willAutoStart);const [streamPhase, setStreamPhase] = useState<StreamPhase>(willAutoStart ? "reasoning" : "idle",@@ -154,8 +157,8 @@ function GeneratePageContent() {// Handle message sent for historyconst handleMessageSent = useCallback(- (promptText: string) => {- addUserMessage(promptText);+ (promptText: string, attachedImage?: string) => {+ addUserMessage(promptText, attachedImage);},[addUserMessage],);@@ -185,6 +188,8 @@ function GeneratePageContent() {if (streaming) {setGenerationError(null);setRuntimeError(null);+ // Reset error correction state for fresh retry attempts+ setErrorCorrection(null);}}, []);@@ -209,8 +214,13 @@ function GeneratePageContent() {useEffect(() => {if (initialPrompt && !hasAutoStarted && chatSidebarRef.current) {setHasAutoStarted(true);+ // Check for initial attached image from sessionStorage+ const storedImage = sessionStorage.getItem("initialAttachedImage");+ if (storedImage) {+ sessionStorage.removeItem("initialAttachedImage");+ }setTimeout(() => {- chatSidebarRef.current?.triggerGeneration();+ chatSidebarRef.current?.triggerGeneration({ attachedImage: storedImage ?? undefined });}, 100);}}, [initialPrompt, hasAutoStarted]);@@ -243,6 +253,13 @@ function GeneratePageContent() {errorCorrection={errorCorrection ?? undefined}onPendingMessage={setPendingMessage}onClearPendingMessage={clearPendingMessage}+ // Frame capture props+ Component={Component}+ fps={fps}+ durationInFrames={durationInFrames}+ currentFrame={currentFrame}+ // Initial model from URL+ initialModel={initialModel}/>{/* Main content area */}@@ -267,6 +284,7 @@ function GeneratePageContent() {errorType={generationError?.type || "compilation"}code={code}onRuntimeError={handleRuntimeError}+ onFrameChange={setCurrentFrame}/></div></div>diff --git a/packages/template-prompt-to-motion-graphics/src/app/page.tsx b/packages/template-prompt-to-motion-graphics/src/app/page.tsxindex f22633ede0..708c55a343 100644--- a/packages/template-prompt-to-motion-graphics/src/app/page.tsx+++ b/packages/template-prompt-to-motion-graphics/src/app/page.tsx@@ -11,8 +11,14 @@ const Home: NextPage = () => {const router = useRouter();const [isNavigating, setIsNavigating] = useState(false);- const handleNavigate = (prompt: string, model: ModelId) => {+ const handleNavigate = (prompt: string, model: ModelId, attachedImage?: string) => {setIsNavigating(true);+ // Store image in sessionStorage (too large for URL params)+ if (attachedImage) {+ sessionStorage.setItem("initialAttachedImage", attachedImage);+ } else {+ sessionStorage.removeItem("initialAttachedImage");+ }const params = new URLSearchParams({ prompt, model });router.push(`/generate?${params.toString()}`);};diff --git a/packages/template-prompt-to-motion-graphics/src/components/AnimationPlayer/index.tsx b/packages/template-prompt-to-motion-graphics/src/components/AnimationPlayer/index.tsxindex c2dabdf233..9b0283d786 100644--- a/packages/template-prompt-to-motion-graphics/src/components/AnimationPlayer/index.tsx+++ b/packages/template-prompt-to-motion-graphics/src/components/AnimationPlayer/index.tsx@@ -33,6 +33,7 @@ interface AnimationPlayerProps {errorType?: ErrorType;code: string;onRuntimeError?: (error: string) => void;+ onFrameChange?: (frame: number) => void;}export const AnimationPlayer: React.FC<AnimationPlayerProps> = ({@@ -47,10 +48,12 @@ export const AnimationPlayer: React.FC<AnimationPlayerProps> = ({errorType = "compilation",code,onRuntimeError,+ onFrameChange,}) => {const playerRef = useRef<PlayerRef>(null);// Listen for runtime errors from the Player's error boundary+ // Component is included in deps because the Player remounts when Component changes (via key={Component.toString()})useEffect(() => {const player = playerRef.current;if (!player || !onRuntimeError) return;@@ -63,7 +66,25 @@ export const AnimationPlayer: React.FC<AnimationPlayerProps> = ({return () => {player.removeEventListener("error", handleError);};- }, [onRuntimeError]);+ }, [onRuntimeError, Component]);++ // Listen for frame changes and report to parent+ // Component is included in deps because the Player remounts when Component changes (via key={Component.toString()})+ useEffect(() => {+ const player = playerRef.current;+ if (!player || !onFrameChange) return;++ const handleFrameUpdate = (e: {+ detail: { frame: number };+ }) => {+ onFrameChange(e.detail.frame);+ };++ player.addEventListener("frameupdate", handleFrameUpdate);+ return () => {+ player.removeEventListener("frameupdate", handleFrameUpdate);+ };+ }, [onFrameChange, Component]);const renderContent = () => {if (isStreaming) {diff --git a/packages/template-prompt-to-motion-graphics/src/components/ChatSidebar/ChatInput.tsx b/packages/template-prompt-to-motion-graphics/src/components/ChatSidebar/ChatInput.tsxindex 0759f394ce..7637926274 100644--- a/packages/template-prompt-to-motion-graphics/src/components/ChatSidebar/ChatInput.tsx+++ b/packages/template-prompt-to-motion-graphics/src/components/ChatSidebar/ChatInput.tsx@@ -1,6 +1,7 @@"use client";-import { ArrowUp } from "lucide-react";+import { useState, type ComponentType, type DragEvent } from "react";+import { ArrowUp, Camera, X } from "lucide-react";import { Button } from "@/components/ui/button";import {Select,@@ -10,6 +11,7 @@ import {SelectValue,} from "@/components/ui/select";import { type ModelId, MODELS } from "@/types/generation";+import { captureFrame, fileToBase64 } from "@/helpers/capture-frame";interface ChatInputProps {prompt: string;@@ -17,7 +19,12 @@ interface ChatInputProps {model: ModelId;onModelChange: (model: ModelId) => void;isLoading: boolean;- onSubmit: () => void;+ onSubmit: (attachedImage?: string) => void;+ // Frame capture props+ Component?: ComponentType | null;+ fps?: number;+ durationInFrames?: number;+ currentFrame?: number;}export function ChatInput({@@ -27,11 +34,20 @@ export function ChatInput({onModelChange,isLoading,onSubmit,+ Component,+ fps = 30,+ durationInFrames = 150,+ currentFrame = 0,}: ChatInputProps) {+ const [attachedImage, setAttachedImage] = useState<string | null>(null);+ const [isCapturing, setIsCapturing] = useState(false);+ const [isDragging, setIsDragging] = useState(false);+const handleSubmit = (e: React.FormEvent) => {e.preventDefault();if (!prompt.trim()) return;- onSubmit();+ onSubmit(attachedImage ?? undefined);+ setAttachedImage(null); // Clear after submit};const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {@@ -42,15 +58,104 @@ export function ChatInput({}};+ const handleCapture = async () => {+ if (!Component || isCapturing) return;++ setIsCapturing(true);+ try {+ const base64 = await captureFrame(Component, currentFrame, {+ width: 1920,+ height: 1080,+ fps,+ durationInFrames,+ });+ setAttachedImage(base64);+ } catch (error) {+ console.error("Failed to capture frame:", error);+ } finally {+ setIsCapturing(false);+ }+ };++ const handlePaste = async (e: React.ClipboardEvent) => {+ const items = Array.from(e.clipboardData.items);+ for (const item of items) {+ if (item.type.startsWith("image/")) {+ e.preventDefault();+ const file = item.getAsFile();+ if (file) {+ const base64 = await fileToBase64(file);+ setAttachedImage(base64);+ }+ break;+ }+ }+ };++ const handleDragOver = (e: DragEvent) => {+ e.preventDefault();+ setIsDragging(true);+ };++ const handleDragLeave = (e: DragEvent) => {+ e.preventDefault();+ setIsDragging(false);+ };++ const handleDrop = async (e: DragEvent) => {+ e.preventDefault();+ setIsDragging(false);++ const files = Array.from(e.dataTransfer.files);+ for (const file of files) {+ if (file.type.startsWith("image/")) {+ const base64 = await fileToBase64(file);+ setAttachedImage(base64);+ break;+ }+ }+ };++ const canCapture = Component && !isLoading && !isCapturing;+return (<div className="p-4"><form onSubmit={handleSubmit}>- <div className="bg-background-elevated rounded-xl border border-border p-3">+ <div+ className={`bg-background-elevated rounded-xl border p-3 transition-colors ${+ isDragging ? "border-blue-500 bg-blue-500/10" : "border-border"+ }`}+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ >+ {/* Image preview */}+ {attachedImage && (+ <div className="mb-2 relative inline-block">+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img+ src={attachedImage}+ alt="Attached"+ className="h-16 w-auto rounded border border-border object-cover"+ />+ <button+ type="button"+ onClick={() => setAttachedImage(null)}+ className="absolute -top-1.5 -right-1.5 bg-background border border-border rounded-full p-0.5 hover:bg-destructive hover:text-destructive-foreground transition-colors"+ >+ <X className="w-3 h-3" />+ </button>+ </div>+ )}+<textareavalue={prompt}onChange={(e) => onPromptChange(e.target.value)}onKeyDown={handleKeyDown}- placeholder="Tune your animation..."+ onPaste={handlePaste}+ placeholder={+ isDragging ? "Drop image here..." : "Tune your animation..."+ }className="w-full bg-transparent text-foreground placeholder:text-muted-foreground-dim focus:outline-none resize-none text-sm min-h-[36px] max-h-[120px]"style={{ fieldSizing: "content" } as React.CSSProperties}disabled={isLoading}@@ -77,15 +182,29 @@ export function ChatInput({</SelectContent></Select>- <Button- type="submit"- size="icon-sm"- disabled={!prompt.trim() || isLoading}- loading={isLoading}- className="bg-foreground text-background hover:bg-gray-200 h-7 w-7"- >- <ArrowUp className="w-4 h-4" />- </Button>+ <div className="flex items-center gap-1">+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ disabled={!canCapture}+ onClick={handleCapture}+ className="text-muted-foreground hover:text-foreground h-7 w-7"+ title="Capture current frame"+ >+ <Camera className="w-4 h-4" />+ </Button>++ <Button+ type="submit"+ size="icon-sm"+ disabled={!prompt.trim() || isLoading}+ loading={isLoading}+ className="bg-foreground text-background hover:bg-gray-200 h-7 w-7"+ >+ <ArrowUp className="w-4 h-4" />+ </Button>+ </div></div></div></form>diff --git a/packages/template-prompt-to-motion-graphics/src/components/ChatSidebar/ChatSidebar.tsx b/packages/template-prompt-to-motion-graphics/src/components/ChatSidebar/ChatSidebar.tsxindex aac29b3395..83d48eb5e5 100644--- a/packages/template-prompt-to-motion-graphics/src/components/ChatSidebar/ChatSidebar.tsx+++ b/packages/template-prompt-to-motion-graphics/src/components/ChatSidebar/ChatSidebar.tsx@@ -6,6 +6,7 @@ import {useImperativeHandle,useRef,useEffect,+ type ComponentType,} from "react";import {PanelLeftClose,@@ -40,7 +41,7 @@ import { ChatInput } from "./ChatInput";import { useGenerationApi } from "@/hooks/useGenerationApi";export interface ChatSidebarRef {- triggerGeneration: (options?: { silent?: boolean }) => void;+ triggerGeneration: (options?: { silent?: boolean; attachedImage?: string }) => void;}interface ChatSidebarProps {@@ -63,7 +64,7 @@ interface ChatSidebarProps {conversationHistory?: ConversationContextMessage[];previouslyUsedSkills?: string[];isFollowUp?: boolean;- onMessageSent?: (prompt: string) => void;+ onMessageSent?: (prompt: string, attachedImage?: string) => void;onGenerationComplete?: (code: string,summary?: string,@@ -76,6 +77,13 @@ interface ChatSidebarProps {errorCorrection?: ErrorCorrectionContext;onPendingMessage?: (skills?: string[]) => void;onClearPendingMessage?: () => void;+ // Frame capture props+ Component?: ComponentType | null;+ fps?: number;+ durationInFrames?: number;+ currentFrame?: number;+ // Initial model from URL+ initialModel?: ModelId;}export const ChatSidebar = forwardRef<ChatSidebarRef, ChatSidebarProps>(@@ -102,10 +110,15 @@ export const ChatSidebar = forwardRef<ChatSidebarRef, ChatSidebarProps>(errorCorrection,onPendingMessage,onClearPendingMessage,+ Component,+ fps = 30,+ durationInFrames = 150,+ currentFrame = 0,+ initialModel,},ref,) {- const [model, setModel] = useState<ModelId>(MODELS[2].id);+ const [model, setModel] = useState<ModelId>(initialModel ?? MODELS[2].id);const messagesEndRef = useRef<HTMLDivElement>(null);const promptRef = useRef<string>("");@@ -121,7 +134,10 @@ export const ChatSidebar = forwardRef<ChatSidebarRef, ChatSidebarProps>(messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });}, [messages]);- const handleGeneration = async (options?: { silent?: boolean }) => {+ const handleGeneration = async (options?: {+ silent?: boolean;+ attachedImage?: string;+ }) => {const currentPrompt = promptRef.current;if (!currentPrompt.trim()) return;@@ -137,6 +153,7 @@ export const ChatSidebar = forwardRef<ChatSidebarRef, ChatSidebarProps>(isFollowUp,hasManualEdits,errorCorrection,+ frameImage: options?.attachedImage,},{onCodeGenerated,@@ -231,7 +248,13 @@ export const ChatSidebar = forwardRef<ChatSidebarRef, ChatSidebarProps>(model={model}onModelChange={setModel}isLoading={isLoading}- onSubmit={handleGeneration}+ onSubmit={(attachedImage) =>+ handleGeneration({ attachedImage })+ }+ Component={Component}+ fps={fps}+ durationInFrames={durationInFrames}+ currentFrame={currentFrame}/></>)}@@ -259,6 +282,14 @@ function ChatMessage({ message }: { message: ConversationMessage }) {</div><div className="text-sm text-foreground leading-relaxed bg-secondary/50 rounded-lg px-3 py-2">{message.content}+ {message.attachedImage && (+ // eslint-disable-next-line @next/next/no-img-element+ <img+ src={message.attachedImage}+ alt="Attached"+ className="h-20 w-auto rounded border border-border object-cover mt-2"+ />+ )}</div></div>);diff --git a/packages/template-prompt-to-motion-graphics/src/components/LandingPageInput.tsx b/packages/template-prompt-to-motion-graphics/src/components/LandingPageInput.tsxindex 07f1018f53..b5ba240042 100644--- a/packages/template-prompt-to-motion-graphics/src/components/LandingPageInput.tsx+++ b/packages/template-prompt-to-motion-graphics/src/components/LandingPageInput.tsx@@ -1,6 +1,6 @@"use client";-import { useState } from "react";+import { useState, type DragEvent } from "react";import Link from "next/link";import {ArrowUp,@@ -10,8 +10,10 @@ import {Hash,BarChart3,Disc,+ X,type LucideIcon,} from "lucide-react";+import { fileToBase64 } from "@/helpers/capture-frame";import {Select,SelectContent,@@ -32,7 +34,7 @@ const iconMap: Record<string, LucideIcon> = {};interface LandingPageInputProps {- onNavigate: (prompt: string, model: ModelId) => void;+ onNavigate: (prompt: string, model: ModelId, attachedImage?: string) => void;isNavigating?: boolean;showCodeExamplesLink?: boolean;}@@ -44,11 +46,13 @@ export function LandingPageInput({}: LandingPageInputProps) {const [prompt, setPrompt] = useState("");const [model, setModel] = useState<ModelId>("gpt-5.2:medium");+ const [attachedImage, setAttachedImage] = useState<string | null>(null);+ const [isDragging, setIsDragging] = useState(false);const handleSubmit = (e: React.FormEvent) => {e.preventDefault();if (!prompt.trim() || isNavigating) return;- onNavigate(prompt, model);+ onNavigate(prompt, model, attachedImage ?? undefined);};const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {@@ -59,6 +63,45 @@ export function LandingPageInput({}};+ const handlePaste = async (e: React.ClipboardEvent) => {+ const items = Array.from(e.clipboardData.items);+ for (const item of items) {+ if (item.type.startsWith("image/")) {+ e.preventDefault();+ const file = item.getAsFile();+ if (file) {+ const base64 = await fileToBase64(file);+ setAttachedImage(base64);+ }+ break;+ }+ }+ };++ const handleDragOver = (e: DragEvent) => {+ e.preventDefault();+ setIsDragging(true);+ };++ const handleDragLeave = (e: DragEvent) => {+ e.preventDefault();+ setIsDragging(false);+ };++ const handleDrop = async (e: DragEvent) => {+ e.preventDefault();+ setIsDragging(false);++ const files = Array.from(e.dataTransfer.files);+ for (const file of files) {+ if (file.type.startsWith("image/")) {+ const base64 = await fileToBase64(file);+ setAttachedImage(base64);+ break;+ }+ }+ };+return (<div className="flex flex-col items-center justify-center flex-1 px-4"><h1 className="text-5xl font-bold text-white mb-10 text-center">@@ -66,12 +109,39 @@ export function LandingPageInput({</h1><form onSubmit={handleSubmit} className="w-full max-w-3xl">- <div className="bg-background-elevated rounded-xl border border-border p-4">+ <div+ className={`bg-background-elevated rounded-xl border p-4 transition-colors ${+ isDragging ? "border-blue-500 bg-blue-500/10" : "border-border"+ }`}+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ >+ {/* Image preview */}+ {attachedImage && (+ <div className="mb-3 relative inline-block">+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img+ src={attachedImage}+ alt="Attached"+ className="h-20 w-auto rounded border border-border object-cover"+ />+ <button+ type="button"+ onClick={() => setAttachedImage(null)}+ className="absolute -top-1.5 -right-1.5 bg-background border border-border rounded-full p-0.5 hover:bg-destructive hover:text-destructive-foreground transition-colors"+ >+ <X className="w-3 h-3" />+ </button>+ </div>+ )}+<textareavalue={prompt}onChange={(e) => setPrompt(e.target.value)}onKeyDown={handleKeyDown}- placeholder="Describe your animation..."+ onPaste={handlePaste}+ placeholder={isDragging ? "Drop image here..." : "Describe your animation..."}className="w-full bg-transparent text-foreground placeholder:text-muted-foreground-dim focus:outline-none resize-none overflow-y-auto text-base min-h-[60px] max-h-[200px]"style={{ fieldSizing: "content" }}disabled={isNavigating}diff --git a/packages/template-prompt-to-motion-graphics/src/helpers/capture-frame.ts b/packages/template-prompt-to-motion-graphics/src/helpers/capture-frame.tsnew file mode 100644index 0000000000..1a69148eae--- /dev/null+++ b/packages/template-prompt-to-motion-graphics/src/helpers/capture-frame.ts@@ -0,0 +1,55 @@+import { renderStillOnWeb } from "@remotion/web-renderer";+import type { ComponentType } from "react";++interface CaptureConfig {+ width: number;+ height: number;+ fps: number;+ durationInFrames: number;+}++/**+ * Captures a frame from a Remotion composition and returns it as a base64 data URL.+ */+export async function captureFrame(+ Component: ComponentType,+ frame: number,+ config: CaptureConfig,+): Promise<string> {+ const { blob } = await renderStillOnWeb({+ composition: {+ component: Component,+ id: "frame-capture",+ width: config.width,+ height: config.height,+ fps: config.fps,+ durationInFrames: config.durationInFrames,+ },+ frame,+ imageFormat: "jpeg",+ scale: 0.5, // 960x540 - good enough for AI context+ inputProps: {},+ });++ // Convert blob to base64 data URL+ const buffer = await blob.arrayBuffer();+ const bytes = new Uint8Array(buffer);+ let binary = "";+ for (let i = 0; i < bytes.length; i++) {+ binary += String.fromCharCode(bytes[i]);+ }+ const base64 = btoa(binary);+ return `data:image/jpeg;base64,${base64}`;+}++/**+ * Converts a File to a base64 data URL.+ */+export async function fileToBase64(file: File): Promise<string> {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => resolve(reader.result as string);+ reader.onerror = reject;+ reader.readAsDataURL(file);+ });+}diff --git a/packages/template-prompt-to-motion-graphics/src/hooks/useConversationState.ts b/packages/template-prompt-to-motion-graphics/src/hooks/useConversationState.tsindex c4ec2e5c46..c6f88a6415 100644--- a/packages/template-prompt-to-motion-graphics/src/hooks/useConversationState.ts+++ b/packages/template-prompt-to-motion-graphics/src/hooks/useConversationState.ts@@ -18,12 +18,13 @@ export function useConversationState() {// Track the last AI-generated code to detect manual editsconst lastAiCodeRef = useRef<string>("");- const addUserMessage = useCallback((content: string) => {+ const addUserMessage = useCallback((content: string, attachedImage?: string) => {const message: ConversationMessage = {id: `user-${Date.now()}`,role: "user",content,timestamp: Date.now(),+ attachedImage,};setState((prev) => ({...prev,diff --git a/packages/template-prompt-to-motion-graphics/src/hooks/useGenerationApi.ts b/packages/template-prompt-to-motion-graphics/src/hooks/useGenerationApi.tsindex c58e04403b..2e286d3f24 100644--- a/packages/template-prompt-to-motion-graphics/src/hooks/useGenerationApi.ts+++ b/packages/template-prompt-to-motion-graphics/src/hooks/useGenerationApi.ts@@ -22,7 +22,7 @@ interface GenerationCallbacks {onStreamingChange?: (isStreaming: boolean) => void;onStreamPhaseChange?: (phase: StreamPhase) => void;onError?: (error: string, type: GenerationErrorType, failedEdit?: FailedEditInfo) => void;- onMessageSent?: (prompt: string) => void;+ onMessageSent?: (prompt: string, attachedImage?: string) => void;onGenerationComplete?: (code: string,summary?: string,@@ -44,6 +44,7 @@ interface GenerationContext {isFollowUp: boolean;hasManualEdits: boolean;errorCorrection?: ErrorCorrectionContext;+ frameImage?: string;}interface UseGenerationApiReturn {@@ -77,6 +78,7 @@ export function useGenerationApi(): UseGenerationApiReturn {isFollowUp,hasManualEdits,errorCorrection,+ frameImage,} = context;const {@@ -97,7 +99,7 @@ export function useGenerationApi(): UseGenerationApiReturn {// Only add user message if not a silent retryif (!options?.silent) {- onMessageSent?.(prompt);+ onMessageSent?.(prompt, frameImage);}try {@@ -113,6 +115,7 @@ export function useGenerationApi(): UseGenerationApiReturn {isFollowUp,hasManualEdits,errorCorrection,+ frameImage,}),});diff --git a/packages/template-prompt-to-motion-graphics/src/types/conversation.ts b/packages/template-prompt-to-motion-graphics/src/types/conversation.tsindex 8dfc3cc421..9806b3c7c4 100644--- a/packages/template-prompt-to-motion-graphics/src/types/conversation.ts+++ b/packages/template-prompt-to-motion-graphics/src/types/conversation.ts@@ -21,6 +21,8 @@ export interface ConversationMessage {role: "user" | "assistant" | "error";content: string;timestamp: number;+ /** For user messages, store attached image as base64 data URL */+ attachedImage?: string;/** For assistant messages, store the code snapshot at time of generation */codeSnapshot?: string;/** For assistant messages, store metadata about the generation */