π₯ Make videos programmatically with React
Add self-correction loop and separate chat bubbles for edits/skills
ASchwad305a6a551ecf
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 51f60a11cc..55c95b170c 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@@ -248,6 +248,12 @@ interface ConversationContextMessage {content: string;}+interface ErrorCorrectionContext {+ error: string;+ attemptNumber: number;+ maxAttempts: number;+}+interface GenerateRequest {prompt: string;model?: string;@@ -255,6 +261,8 @@ interface GenerateRequest {conversationHistory?: ConversationContextMessage[];isFollowUp?: boolean;hasManualEdits?: boolean;+ /** Error correction context for self-healing loops */+ errorCorrection?: ErrorCorrectionContext;}interface GenerateResponse {@@ -271,11 +279,12 @@ interface GenerateResponse {export async function POST(req: Request) {const {prompt,- model = "gpt-5-mini",+ model = "gpt-5.2",currentCode,conversationHistory = [],isFollowUp = false,hasManualEdits = false,+ errorCorrection,}: GenerateRequest = await req.json();const apiKey = process.env.OPENAI_API_KEY;@@ -365,12 +374,33 @@ export async function POST(req: Request) {? "\n\nNOTE: The user has made manual edits to the code. Preserve these changes.": "";+ // Error correction context for self-healing+ let errorCorrectionNotice = "";+ if (errorCorrection) {+ errorCorrectionNotice = `++## COMPILATION ERROR (ATTEMPT ${errorCorrection.attemptNumber}/${errorCorrection.maxAttempts})+The previous code failed to compile with this error:+\`\`\`+${errorCorrection.error}+\`\`\`++CRITICAL: Fix this compilation error. Common issues include:+- Syntax errors (missing brackets, semicolons)+- Invalid JSX (unclosed tags, invalid attributes)+- Undefined variables or imports+- TypeScript type errors++Focus ONLY on fixing the error. Do not make other changes.`;+ }+const editPrompt = `## CURRENT CODE:\`\`\`tsx${currentCode}\`\`\`${conversationContext}${manualEditNotice}+${errorCorrectionNotice}## USER REQUEST:${prompt}diff --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 9b677e94f9..b7211254d0 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@@ -17,7 +17,10 @@ import {import { examples } from "../../examples/code";import { useAnimationState } from "../../hooks/useAnimationState";import { useConversationState } from "../../hooks/useConversationState";-import type { AssistantMetadata } from "../../types/conversation";+import type {+ AssistantMetadata,+ ErrorCorrectionContext,+} from "../../types/conversation";function GeneratePageContent() {const searchParams = useSearchParams();@@ -43,6 +46,11 @@ function GeneratePageContent() {type: GenerationErrorType;} | null>(null);+ // Self-correction state+ const MAX_CORRECTION_ATTEMPTS = 3;+ const [errorCorrection, setErrorCorrection] =+ useState<ErrorCorrectionContext | null>(null);+// Conversation state for follow-up editsconst {messages,@@ -82,6 +90,69 @@ function GeneratePageContent() {}}, [isStreaming, compileCode]);+ // Auto-correction effect: trigger when compilation error occurs after generation+ const lastPromptRef = useRef<string>("");+ useEffect(() => {+ // Only auto-correct if:+ // 1. There's a compilation error (not generation error)+ // 2. We're not currently streaming+ // 3. We haven't exceeded max attempts+ // 4. We have code to correct+ if (+ error &&+ !isStreaming &&+ !isCompiling &&+ !generationError &&+ hasGeneratedOnce &&+ code.trim()+ ) {+ const currentAttempt = errorCorrection?.attemptNumber ?? 0;++ if (currentAttempt < MAX_CORRECTION_ATTEMPTS) {+ // Set up auto-correction+ const nextAttempt = currentAttempt + 1;+ console.log(+ `Auto-correction attempt ${nextAttempt}/${MAX_CORRECTION_ATTEMPTS} for error:`,+ error+ );++ // Add error to conversation history+ addErrorMessage(`Compilation error: ${error}`, "validation");++ setErrorCorrection({+ error,+ attemptNumber: nextAttempt,+ maxAttempts: MAX_CORRECTION_ATTEMPTS,+ });++ // Store prompt for auto-trigger and set it+ const correctionPrompt = "Fix the compilation error";+ lastPromptRef.current = correctionPrompt;+ setPrompt(correctionPrompt);++ // Trigger generation after a short delay+ setTimeout(() => {+ promptInputRef.current?.triggerGeneration();+ }, 100);+ }+ }++ // Clear error correction state on successful compilation+ if (!error && !isCompiling && errorCorrection) {+ setErrorCorrection(null);+ }+ }, [+ error,+ isStreaming,+ isCompiling,+ generationError,+ hasGeneratedOnce,+ code,+ errorCorrection,+ addErrorMessage,+ setPrompt,+ ]);+const handleCodeChange = useCallback((newCode: string) => {setCode(newCode);@@ -216,6 +287,7 @@ function GeneratePageContent() {onMessageSent={handleMessageSent}onGenerationComplete={handleGenerationComplete}onErrorMessage={addErrorMessage}+ errorCorrection={errorCorrection ?? undefined}/></div></div>diff --git a/packages/template-prompt-to-motion-graphics/src/components/ChatHistory/ChatHistory.tsx b/packages/template-prompt-to-motion-graphics/src/components/ChatHistory/ChatHistory.tsxindex 63a46821d8..d62d2f0dbe 100644--- a/packages/template-prompt-to-motion-graphics/src/components/ChatHistory/ChatHistory.tsx+++ b/packages/template-prompt-to-motion-graphics/src/components/ChatHistory/ChatHistory.tsx@@ -84,7 +84,26 @@ export function ChatHistory({</div>)}{messages.map((message) => (- <ChatMessage key={message.id} message={message} />+ <div key={message.id} className="space-y-2">+ <ChatMessage message={message} />+ {/* Show skills as separate bubble */}+ {message.role === "assistant" &&+ message.metadata?.skills &&+ message.metadata.skills.length > 0 && (+ <SkillsBubble skills={message.metadata.skills} />+ )}+ {/* Show each edit as separate bubble */}+ {message.role === "assistant" &&+ message.metadata?.editType === "tool_edit" &&+ message.metadata.edits?.map((edit, i) => (+ <EditBubble key={i} edit={edit} />+ ))}+ {/* Show full replacement indicator */}+ {message.role === "assistant" &&+ message.metadata?.editType === "full_replacement" && (+ <FullReplacementBubble />+ )}+ </div>))}</div>)}@@ -95,7 +114,6 @@ export function ChatHistory({function ChatMessage({ message }: { message: ConversationMessage }) {const isUser = message.role === "user";const isError = message.role === "error";- const metadata = message.metadata;// User messages - simple displayif (isUser) {@@ -126,65 +144,68 @@ function ChatMessage({ message }: { message: ConversationMessage }) {);}- // Assistant messages - Claude Code style with details+ // Assistant messages - just summary, edits/skills shown as separate bubblesreturn (- <div className="rounded-lg p-2 text-sm bg-secondary text-secondary-foreground space-y-2">- {/* Summary as main content */}+ <div className="rounded-lg p-2 text-sm bg-secondary text-secondary-foreground"><div className="font-medium text-foreground">{message.content}</div>+ <div className="text-[10px] text-muted-foreground-dim mt-1">+ {new Date(message.timestamp).toLocaleTimeString()}+ </div>+ </div>+ );+}- {/* Edit details - Claude Code style with line numbers */}- {metadata?.editType === "tool_edit" && metadata.edits && (- <div className="space-y-1 border-l-2 border-green-500/30 pl-2">- <div className="text-[10px] uppercase tracking-wide text-muted-foreground-dim font-medium">- Changes- </div>- {metadata.edits.map((edit, i) => (- <div- key={i}- className="flex items-start gap-1.5 text-xs text-muted-foreground"- >- <CheckCircle2 className="w-3 h-3 text-green-500 mt-0.5 shrink-0" />- <span className="flex-1">{edit.description}</span>- {edit.lineNumber && (- <span className="text-[10px] text-muted-foreground-dim font-mono">- L{edit.lineNumber}- </span>- )}- </div>- ))}- </div>- )}-- {/* Full replacement indicator */}- {metadata?.editType === "full_replacement" && (- <div className="flex items-center gap-1.5 text-xs text-muted-foreground border-l-2 border-blue-500/30 pl-2">- <FileCode className="w-3 h-3 text-blue-500" />- <span>Full code rewrite</span>- </div>- )}+function SkillsBubble({ skills }: { skills: string[] }) {+ return (+ <div className="rounded-lg p-2 text-sm bg-purple-500/10 border border-purple-500/20">+ <div className="flex items-center gap-1.5 text-purple-400 mb-1.5">+ <FileCode className="w-3 h-3" />+ <span className="text-[10px] uppercase tracking-wide font-medium">+ Skills Used+ </span>+ </div>+ <div className="flex items-center gap-1 flex-wrap">+ {skills.map((skill) => (+ <span+ key={skill}+ className="text-[10px] px-1.5 py-0.5 rounded bg-purple-500/20 text-purple-300 font-medium"+ >+ {skill}+ </span>+ ))}+ </div>+ </div>+ );+}- {/* Used Skills section */}- {metadata?.skills && metadata.skills.length > 0 && (- <div className="border-l-2 border-purple-500/30 pl-2">- <div className="text-[10px] uppercase tracking-wide text-muted-foreground-dim font-medium mb-1">- Used Skills- </div>- <div className="flex items-center gap-1 flex-wrap">- {metadata.skills.map((skill) => (- <span- key={skill}- className="text-[10px] px-1.5 py-0.5 rounded bg-purple-500/15 text-purple-400 font-medium"- >- {skill}- </span>- ))}- </div>+function EditBubble({+ edit,+}: {+ edit: { description: string; lineNumber?: number };+}) {+ return (+ <div className="rounded-lg p-2 text-sm bg-green-500/10 border border-green-500/20">+ <div className="flex items-start gap-1.5">+ <CheckCircle2 className="w-3.5 h-3.5 text-green-500 mt-0.5 shrink-0" />+ <div className="flex-1 min-w-0">+ <div className="text-xs text-green-300">{edit.description}</div>+ {edit.lineNumber && (+ <div className="text-[10px] text-muted-foreground-dim font-mono mt-0.5">+ Line {edit.lineNumber}+ </div>+ )}</div>- )}+ </div>+ </div>+ );+}- {/* Timestamp */}- <div className="text-[10px] text-muted-foreground-dim pt-1 border-t border-border/30">- {new Date(message.timestamp).toLocaleTimeString()}+function FullReplacementBubble() {+ return (+ <div className="rounded-lg p-2 text-sm bg-blue-500/10 border border-blue-500/20">+ <div className="flex items-center gap-1.5 text-blue-400">+ <FileCode className="w-3.5 h-3.5" />+ <span className="text-xs">Full code rewrite</span></div></div>);diff --git a/packages/template-prompt-to-motion-graphics/src/components/PromptInput.tsx b/packages/template-prompt-to-motion-graphics/src/components/PromptInput.tsxindex 7c98964769..c3f1bc8fd1 100644--- a/packages/template-prompt-to-motion-graphics/src/components/PromptInput.tsx+++ b/packages/template-prompt-to-motion-graphics/src/components/PromptInput.tsx@@ -11,11 +11,13 @@ import {BarChart3,Disc,Pencil,+ AlertTriangle,type LucideIcon,} from "lucide-react";import type {ConversationContextMessage,AssistantMetadata,+ ErrorCorrectionContext,} from "@/types/conversation";import {Select,@@ -94,6 +96,8 @@ interface PromptInputProps {message: string,errorType: "edit_failed" | "api" | "validation") => void;+ /** Error correction context for self-healing loops */+ errorCorrection?: ErrorCorrectionContext;}export const PromptInput = forwardRef<PromptInputRef, PromptInputProps>(@@ -116,6 +120,7 @@ export const PromptInput = forwardRef<PromptInputRef, PromptInputProps>(onMessageSent,onGenerationComplete,onErrorMessage,+ errorCorrection,},ref,) {@@ -149,6 +154,7 @@ export const PromptInput = forwardRef<PromptInputRef, PromptInputProps>(conversationHistory: isFollowUp ? conversationHistory : [],isFollowUp,hasManualEdits,+ errorCorrection,}),});@@ -327,7 +333,14 @@ export const PromptInput = forwardRef<PromptInputRef, PromptInputProps>(className={isLanding ? "w-full max-w-3xl" : ""}><div className="bg-background-elevated rounded-xl border border-border p-4">- {isFollowUp && !isLanding && (+ {errorCorrection && !isLanding && (+ <div className="text-xs text-amber-500 mb-2 flex items-center gap-1">+ <AlertTriangle className="w-3 h-3" />+ Auto-fixing error (attempt {errorCorrection.attemptNumber}/+ {errorCorrection.maxAttempts})+ </div>+ )}+ {isFollowUp && !errorCorrection && !isLanding && (<div className="text-xs text-muted-foreground-dim mb-2 flex items-center gap-1"><Pencil className="w-3 h-3" />Editing existing animationdiff --git a/packages/template-prompt-to-motion-graphics/src/examples/code/typewriter-highlight.ts b/packages/template-prompt-to-motion-graphics/src/examples/code/typewriter-highlight.tsindex 61bb092992..6cb773ff46 100644--- a/packages/template-prompt-to-motion-graphics/src/examples/code/typewriter-highlight.ts+++ b/packages/template-prompt-to-motion-graphics/src/examples/code/typewriter-highlight.ts@@ -10,131 +10,129 @@ export const typewriterHighlightCode = `import {export const MyAnimation = () => {/*- * Typewriter with blinking cursor, dramatic pause, spring-based highlight, and layer crossfade.+ * Centered "Hello world" appears with a typewriter reveal and a smoothly blinking caret.+ * After the full phrase is typed, the word "world" crossfades into a yellow-highlighted final state.*/const frame = useCurrentFrame();- const { fps } = useVideoConfig();+ const { fps, width } = useVideoConfig();- const COLOR_BG = "#ffffff";+ const COLOR_BG = "#FFFFFF";const COLOR_TEXT = "#000000";- const COLOR_HIGHLIGHT = "#A7C7E7";+ const COLOR_HIGHLIGHT = "#FFE44D";- const FULL_TEXT = "From prompt to motion graphics. This is Remotion.";- const HIGHLIGHT_WORD = "Remotion";- const CARET_SYMBOL = "\u258C";- const SPLIT_AFTER = " This is Remotion.";+ const FULL_TEXT = "Hello world";+ const HIGHLIGHT_WORD = "world";+ const CARET_SYMBOL = "β";- const FONT_SIZE = 72;- const FONT_WEIGHT = 700;- const CHAR_FRAMES = 2;+ const FONT_SIZE = Math.max(54, Math.round(width * 0.07));+ const FONT_WEIGHT = 800;+ const LINE_HEIGHT = 1.05;++ const CHAR_FRAMES = 3;const CURSOR_BLINK_FRAMES = 16;- const HIGHLIGHT_DELAY = 6;++ const HIGHLIGHT_DELAY = 10;const HIGHLIGHT_WIPE_DURATION = 18;- const CROSSFADE_DURATION = 8;- const WAIT_AFTER_PRE_SECONDS = 1;-- const WAIT_AFTER_PRE_FRAMES = Math.round(fps * WAIT_AFTER_PRE_SECONDS);- const f = frame;-- const splitIndex = FULL_TEXT.indexOf(SPLIT_AFTER);- const preLen = splitIndex >= 0 ? splitIndex : FULL_TEXT.length;- const postLen = FULL_TEXT.length - preLen;-- let typedChars = 0;- if (f < preLen * CHAR_FRAMES) {- typedChars = Math.floor(f / CHAR_FRAMES);- } else if (f < preLen * CHAR_FRAMES + WAIT_AFTER_PRE_FRAMES) {- typedChars = preLen;- } else {- const postPhase = f - preLen * CHAR_FRAMES - WAIT_AFTER_PRE_FRAMES;- typedChars = Math.min(- FULL_TEXT.length,- preLen + Math.floor(postPhase / CHAR_FRAMES),- );- }+ const CROSSFADE_DURATION = 10;++ const entranceProgress = spring({+ fps,+ frame,+ config: { damping: 18, stiffness: 140, mass: 0.9 },+ durationInFrames: 26,+ });++ const containerTranslateX = interpolate(entranceProgress, [0, 1], [18, 0], {+ extrapolateLeft: "clamp",+ extrapolateRight: "clamp",+ });+ const containerOpacity = interpolate(entranceProgress, [0, 1], [0, 1], {+ extrapolateLeft: "clamp",+ extrapolateRight: "clamp",+ });++ const typedChars = Math.min(+ FULL_TEXT.length,+ Math.floor(frame / CHAR_FRAMES),+ );const typedText = FULL_TEXT.slice(0, typedChars);const typingDone = typedChars >= FULL_TEXT.length;const caretOpacity = !typingDone? interpolate(- f % CURSOR_BLINK_FRAMES,+ frame % CURSOR_BLINK_FRAMES,[0, CURSOR_BLINK_FRAMES / 2, CURSOR_BLINK_FRAMES],[1, 0, 1],{ extrapolateLeft: "clamp", extrapolateRight: "clamp" },): 0;- const highlightIndex = FULL_TEXT.indexOf(HIGHLIGHT_WORD);- const hasHighlight = highlightIndex >= 0;- const preText = hasHighlight ? FULL_TEXT.slice(0, highlightIndex) : FULL_TEXT;- const postText = hasHighlight- ? FULL_TEXT.slice(highlightIndex + HIGHLIGHT_WORD.length)- : "";-- const typeEnd =- preLen * CHAR_FRAMES + WAIT_AFTER_PRE_FRAMES + postLen * CHAR_FRAMES;- const highlightStart = typeEnd + HIGHLIGHT_DELAY;+ const typeEndFrame = FULL_TEXT.length * CHAR_FRAMES;+ const highlightStart = typeEndFrame + HIGHLIGHT_DELAY;- const typedOpacity = interpolate(- f,- [highlightStart - CROSSFADE_DURATION, highlightStart + CROSSFADE_DURATION],- [1, 0],- { extrapolateLeft: "clamp", extrapolateRight: "clamp" },- );- const finalOpacity = interpolate(- f,+ const typedLayerOpacity = 1;+ const finalLayerOpacity = interpolate(+ frame,[highlightStart, highlightStart + CROSSFADE_DURATION],[0, 1],{ extrapolateLeft: "clamp", extrapolateRight: "clamp" },);- const entrance = spring({- fps,- frame: f,- config: { damping: 200, stiffness: 120 },- durationInFrames: 20,- });- const containerScale = interpolate(entrance, [0, 1], [0.98, 1], {- extrapolateLeft: "clamp",- extrapolateRight: "clamp",- });+ const highlightWordIndex = FULL_TEXT.indexOf(HIGHLIGHT_WORD);+ const hasHighlight = highlightWordIndex >= 0;++ const preText = hasHighlight ? FULL_TEXT.slice(0, highlightWordIndex) : "";+ const postText = hasHighlight+ ? FULL_TEXT.slice(highlightWordIndex + HIGHLIGHT_WORD.length)+ : "";const highlightProgress = spring({fps,- frame: f - highlightStart,- config: { damping: 200, stiffness: 180 },+ frame: frame - highlightStart,+ config: { damping: 22, stiffness: 180, mass: 0.9 },durationInFrames: HIGHLIGHT_WIPE_DURATION,});- const highlightScaleX = Math.max(0, Math.min(1, highlightProgress));++ const highlightScaleX = interpolate(highlightProgress, [0, 1], [0, 1], {+ extrapolateLeft: "clamp",+ extrapolateRight: "clamp",+ });return (<AbsoluteFillstyle={{backgroundColor: COLOR_BG,+ fontFamily: "Inter, sans-serif",+ padding: Math.max(44, Math.round(width * 0.06)),display: "flex",alignItems: "center",justifyContent: "center",- fontFamily: "Inter, sans-serif",}}><div- style={{ position: "relative", transform: \`scale(\${containerScale})\` }}+ style={{+ position: "relative",+ opacity: containerOpacity,+ transform: \`translateX(\${containerTranslateX}px)\`,+ }}>- {/* Typing layer */}+ {/* Typewriter layer */}<divstyle={{color: COLOR_TEXT,fontSize: FONT_SIZE,fontWeight: FONT_WEIGHT,- lineHeight: 1.15,- whiteSpace: "pre-wrap",- opacity: typedOpacity,+ lineHeight: LINE_HEIGHT,+ letterSpacing: -0.5,+ whiteSpace: "pre",+ opacity: typedLayerOpacity,}}><span>{typedText}</span><span style={{ opacity: caretOpacity }}>{CARET_SYMBOL}</span></div>- {/* Final layer with highlight */}++ {/* Final highlighted layer */}<divstyle={{position: "absolute",@@ -142,9 +140,10 @@ export const MyAnimation = () => {color: COLOR_TEXT,fontSize: FONT_SIZE,fontWeight: FONT_WEIGHT,- lineHeight: 1.15,- whiteSpace: "pre-wrap",- opacity: finalOpacity,+ lineHeight: LINE_HEIGHT,+ letterSpacing: -0.5,+ whiteSpace: "pre",+ opacity: finalLayerOpacity,}}>{hasHighlight ? (@@ -154,14 +153,14 @@ export const MyAnimation = () => {<spanstyle={{position: "absolute",- left: 0,- right: 0,+ left: "-0.12em",+ right: "-0.12em",top: "50%",height: "1.05em",transform: \`translateY(-50%) scaleX(\${highlightScaleX})\`,transformOrigin: "left center",backgroundColor: COLOR_HIGHLIGHT,- borderRadius: "0.18em",+ borderRadius: "0.2em",zIndex: 0,}}/>@@ -183,9 +182,9 @@ export const MyAnimation = () => {export const typewriterHighlightExample: RemotionExample = {id: "typewriter-highlight",name: "Typewriter with Highlight",- description: "Typewriter effect with blinking cursor, pause, and spring-animated word highlight",+ description: "Typewriter effect with blinking cursor and spring-animated word highlight",category: "Text",- durationInFrames: 180,+ durationInFrames: 90,fps: 30,code: typewriterHighlightCode,};diff --git a/packages/template-prompt-to-motion-graphics/src/types/conversation.ts b/packages/template-prompt-to-motion-graphics/src/types/conversation.tsindex b1d971dca7..0417b6cd66 100644--- a/packages/template-prompt-to-motion-graphics/src/types/conversation.ts+++ b/packages/template-prompt-to-motion-graphics/src/types/conversation.ts@@ -41,3 +41,12 @@ export interface ConversationContextMessage {role: "user" | "assistant";content: string;}++export interface ErrorCorrectionContext {+ /** The compilation error message */+ error: string;+ /** Number of correction attempts so far */+ attemptNumber: number;+ /** Maximum correction attempts allowed */+ maxAttempts: number;+}