🎥 Make videos programmatically with React
Extract auto-correction logic to useAutoCorrection hook
ASchwad7ea95b7bb16f
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 ccac8a46c2..8bdc21b619 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@@ -15,11 +15,14 @@ import {import { examples } from "../../examples/code";import { useAnimationState } from "../../hooks/useAnimationState";import { useConversationState } from "../../hooks/useConversationState";+import { useAutoCorrection } from "../../hooks/useAutoCorrection";import type {AssistantMetadata,ErrorCorrectionContext,} from "../../types/conversation";+const MAX_CORRECTION_ATTEMPTS = 3;+function GeneratePageContent() {const searchParams = useSearchParams();const initialPrompt = searchParams.get("prompt") || "";@@ -45,7 +48,6 @@ function GeneratePageContent() {} | null>(null);// Self-correction state- const MAX_CORRECTION_ATTEMPTS = 3;const [errorCorrection, setErrorCorrection] =useState<ErrorCorrectionContext | null>(null);@@ -67,12 +69,35 @@ function GeneratePageContent() {const { code, Component, error, isCompiling, setCode, compileCode } =useAnimationState(examples[0]?.code || "");- // Debounce compilation+ // Refsconst debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);-const isStreamingRef = useRef(isStreaming);const codeRef = useRef(code);+ const chatHistoryRef = useRef<ChatHistoryRef>(null);+ // Auto-correction hook+ const { markAsAiGenerated, markAsUserEdited } = useAutoCorrection({+ maxAttempts: MAX_CORRECTION_ATTEMPTS,+ compilationError: error,+ generationError,+ isStreaming,+ isCompiling,+ hasGeneratedOnce,+ code,+ errorCorrection,+ onTriggerCorrection: useCallback((correctionPrompt: string, context: ErrorCorrectionContext) => {+ setErrorCorrection(context);+ setPrompt(correctionPrompt);+ setTimeout(() => {+ chatHistoryRef.current?.triggerGeneration();+ }, 100);+ }, []),+ onAddErrorMessage: addErrorMessage,+ onClearGenerationError: useCallback(() => setGenerationError(null), []),+ onClearErrorCorrection: useCallback(() => setErrorCorrection(null), []),+ });++ // Sync refsuseEffect(() => {codeRef.current = code;}, [code]);@@ -81,74 +106,12 @@ function GeneratePageContent() {const wasStreaming = isStreamingRef.current;isStreamingRef.current = isStreaming;- // Compile when streaming ends+ // Compile when streaming ends - mark as AI changeif (wasStreaming && !isStreaming) {+ markAsAiGenerated();compileCode(codeRef.current);}- }, [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(() => {- chatHistoryRef.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,- ]);+ }, [isStreaming, compileCode, markAsAiGenerated]);const handleCodeChange = useCallback((newCode: string) => {@@ -158,6 +121,7 @@ function GeneratePageContent() {// Mark as manual edit if not streaming (user typing)if (!isStreamingRef.current) {markManualEdit(newCode);+ markAsUserEdited();}// Clear existing debounce@@ -175,7 +139,7 @@ function GeneratePageContent() {compileCode(newCode);}, 500);},- [setCode, compileCode, markManualEdit],+ [setCode, compileCode, markManualEdit, markAsUserEdited],);// Handle message sent for history@@ -191,8 +155,9 @@ function GeneratePageContent() {(generatedCode: string, summary?: string, metadata?: AssistantMetadata) => {const content = summary || "Generated your animation, any follow up edits?";addAssistantMessage(content, generatedCode, metadata);+ markAsAiGenerated();},- [addAssistantMessage],+ [addAssistantMessage, markAsAiGenerated],);// Cleanup debounce on unmount@@ -220,12 +185,9 @@ function GeneratePageContent() {);// Auto-trigger generation if prompt came from URL- const chatHistoryRef = useRef<ChatHistoryRef>(null);-useEffect(() => {if (initialPrompt && !hasAutoStarted && chatHistoryRef.current) {setHasAutoStarted(true);- // Small delay to ensure component is mountedsetTimeout(() => {chatHistoryRef.current?.triggerGeneration();}, 100);diff --git a/packages/template-prompt-to-motion-graphics/src/components/Header.tsx b/packages/template-prompt-to-motion-graphics/src/components/Header.tsxindex bda130957e..a5b9541174 100644--- a/packages/template-prompt-to-motion-graphics/src/components/Header.tsx+++ b/packages/template-prompt-to-motion-graphics/src/components/Header.tsx@@ -1,5 +1,4 @@/* eslint-disable @next/next/no-img-element */-import Image from "next/image";import Link from "next/link";interface HeaderProps {diff --git a/packages/template-prompt-to-motion-graphics/src/hooks/useAutoCorrection.ts b/packages/template-prompt-to-motion-graphics/src/hooks/useAutoCorrection.tsnew file mode 100644index 0000000000..43b579ca97--- /dev/null+++ b/packages/template-prompt-to-motion-graphics/src/hooks/useAutoCorrection.ts@@ -0,0 +1,137 @@+import { useEffect, useRef, useCallback } from "react";+import type { ErrorCorrectionContext } from "@/types/conversation";++interface AutoCorrectionConfig {+ maxAttempts: number;+ /** Compilation error from useAnimationState */+ compilationError: string | null;+ /** Generation/API error */+ generationError: { message: string; type: string } | null;+ /** Whether code is currently being generated */+ isStreaming: boolean;+ /** Whether code is currently being compiled */+ isCompiling: boolean;+ /** Whether any generation has occurred */+ hasGeneratedOnce: boolean;+ /** Current code content */+ code: string;+ /** Current error correction context */+ errorCorrection: ErrorCorrectionContext | null;+ /** Callbacks */+ onTriggerCorrection: (prompt: string, errorContext: ErrorCorrectionContext) => void;+ onAddErrorMessage: (message: string, type: "edit_failed" | "api" | "validation") => void;+ onClearGenerationError: () => void;+ onClearErrorCorrection: () => void;+}++/**+ * Hook to handle auto-correction of AI-generated code errors.+ * Tracks whether errors are from AI or user edits, and only auto-corrects AI errors.+ */+export function useAutoCorrection({+ maxAttempts,+ compilationError,+ generationError,+ isStreaming,+ isCompiling,+ hasGeneratedOnce,+ code,+ errorCorrection,+ onTriggerCorrection,+ onAddErrorMessage,+ onClearGenerationError,+ onClearErrorCorrection,+}: AutoCorrectionConfig) {+ // Track whether last code change was from AI or user+ const lastChangeSourceRef = useRef<"ai" | "user">("ai");++ // Mark code as AI-generated+ const markAsAiGenerated = useCallback(() => {+ lastChangeSourceRef.current = "ai";+ }, []);++ // Mark code as user-edited+ const markAsUserEdited = useCallback(() => {+ lastChangeSourceRef.current = "user";+ }, []);++ // Check if we should attempt auto-correction+ const shouldAutoCorrect = useCallback(() => {+ return (+ hasGeneratedOnce &&+ !isStreaming &&+ lastChangeSourceRef.current === "ai" &&+ (errorCorrection?.attemptNumber ?? 0) < maxAttempts+ );+ }, [hasGeneratedOnce, isStreaming, errorCorrection, maxAttempts]);++ // Handle compilation errors+ useEffect(() => {+ if (+ compilationError &&+ !isCompiling &&+ !generationError &&+ code.trim() &&+ shouldAutoCorrect()+ ) {+ const nextAttempt = (errorCorrection?.attemptNumber ?? 0) + 1;+ console.log(+ `Auto-correction attempt ${nextAttempt}/${maxAttempts} for compilation error:`,+ compilationError+ );++ onAddErrorMessage(`Compilation error: ${compilationError}`, "validation");+ onTriggerCorrection("Fix the compilation error", {+ error: compilationError,+ attemptNumber: nextAttempt,+ maxAttempts,+ });+ }++ // Clear error correction state on successful compilation+ if (!compilationError && !isCompiling && errorCorrection) {+ onClearErrorCorrection();+ }+ }, [+ compilationError,+ isCompiling,+ generationError,+ code,+ errorCorrection,+ maxAttempts,+ shouldAutoCorrect,+ onAddErrorMessage,+ onTriggerCorrection,+ onClearErrorCorrection,+ ]);++ // Handle generation/API errors+ useEffect(() => {+ if (generationError && shouldAutoCorrect()) {+ const nextAttempt = (errorCorrection?.attemptNumber ?? 0) + 1;+ console.log(+ `Auto-retry attempt ${nextAttempt}/${maxAttempts} for generation error:`,+ generationError.message+ );++ onClearGenerationError();+ onTriggerCorrection("Please try again", {+ error: generationError.message,+ attemptNumber: nextAttempt,+ maxAttempts,+ });+ }+ }, [+ generationError,+ errorCorrection,+ maxAttempts,+ shouldAutoCorrect,+ onClearGenerationError,+ onTriggerCorrection,+ ]);++ return {+ markAsAiGenerated,+ markAsUserEdited,+ };+}