Skip to content

🎥 Make videos programmatically with React

Add follow-up edits feature with conversation history

ASchwadbba54c2db27f
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.ts
index d3bbfe80e9..ee3dbfd3d4 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
@@ -105,8 +105,47 @@ NEVER use these as variable names - they shadow imports:
`;
+const FOLLOW_UP_PROMPT_ADDITION = `
+
+## FOLLOW-UP EDIT MODE
+
+You are refining an existing animation component. The user has provided:
+1. The current code (which may include their manual edits)
+2. Their new request for changes
+
+CRITICAL RULES FOR FOLLOW-UP EDITS:
+- Preserve the overall structure and working parts of the existing code
+- Only modify what the user specifically asks to change
+- Keep existing variable names, colors, and timing unless asked to change them
+- If the user made manual edits, incorporate and respect those changes
+- Never start from scratch unless explicitly asked
+- Maintain existing imports and only add new ones if needed
+- Output the COMPLETE updated code, not just the changed parts
+`;
+
+interface ConversationContextMessage {
+ role: "user" | "assistant";
+ content: string;
+}
+
+interface GenerateRequest {
+ prompt: string;
+ model?: string;
+ currentCode?: string;
+ conversationHistory?: ConversationContextMessage[];
+ isFollowUp?: boolean;
+ hasManualEdits?: boolean;
+}
+
export async function POST(req: Request) {
- const { prompt, model = "gpt-5-mini" } = await req.json();
+ const {
+ prompt,
+ model = "gpt-5-mini",
+ currentCode,
+ conversationHistory = [],
+ isFollowUp = false,
+ hasManualEdits = false,
+ }: GenerateRequest = await req.json();
const apiKey = process.env.OPENAI_API_KEY;
@@ -128,28 +167,30 @@ export async function POST(req: Request) {
const openai = createOpenAI({ apiKey });
- // Validate the prompt first
- try {
- const validationResult = await generateObject({
- model: openai("gpt-5.2"),
- system: VALIDATION_PROMPT,
- prompt: `User prompt: "${prompt}"`,
- schema: z.object({ valid: z.boolean() }),
- });
-
- if (!validationResult.object.valid) {
- return new Response(
- JSON.stringify({
- error:
- "No valid motion graphics prompt. Please describe an animation or visual content you'd like to create.",
- type: "validation",
- }),
- { status: 400, headers: { "Content-Type": "application/json" } },
- );
+ // Validate the prompt first (skip for follow-ups with existing code)
+ if (!isFollowUp) {
+ try {
+ const validationResult = await generateObject({
+ model: openai("gpt-5.2"),
+ system: VALIDATION_PROMPT,
+ prompt: `User prompt: "${prompt}"`,
+ schema: z.object({ valid: z.boolean() }),
+ });
+
+ if (!validationResult.object.valid) {
+ return new Response(
+ JSON.stringify({
+ error:
+ "No valid motion graphics prompt. Please describe an animation or visual content you'd like to create.",
+ type: "validation",
+ }),
+ { status: 400, headers: { "Content-Type": "application/json" } },
+ );
+ }
+ } catch (validationError) {
+ // On validation error, allow through rather than blocking
+ console.error("Validation error:", validationError);
}
- } catch (validationError) {
- // On validation error, allow through rather than blocking
- console.error("Validation error:", validationError);
}
// Detect which skills apply to this prompt
@@ -171,15 +212,53 @@ export async function POST(req: Request) {
// Load skill-specific content and enhance the system prompt
const skillContent = getCombinedSkillContent(detectedSkills);
- const enhancedSystemPrompt = skillContent
+ let enhancedSystemPrompt = skillContent
? `${SYSTEM_PROMPT}\n\n## SKILL-SPECIFIC GUIDANCE\n${skillContent}`
: SYSTEM_PROMPT;
+ // Add follow-up mode instructions if applicable
+ if (isFollowUp && currentCode) {
+ enhancedSystemPrompt += FOLLOW_UP_PROMPT_ADDITION;
+ }
+
+ // Build the full prompt with context for follow-up edits
+ let fullPrompt = prompt;
+
+ if (isFollowUp && currentCode) {
+ // Include conversation context (last 3 exchanges)
+ const contextMessages = conversationHistory.slice(-6);
+ let conversationContext = "";
+ if (contextMessages.length > 0) {
+ conversationContext =
+ "\n\n## RECENT CONVERSATION:\n" +
+ contextMessages
+ .map((m) => `${m.role.toUpperCase()}: ${m.content}`)
+ .join("\n");
+ }
+
+ // Include manual edit notice
+ const manualEditNotice = hasManualEdits
+ ? "\n\nNOTE: The user has made manual edits to the code. Preserve these changes while applying the new request."
+ : "";
+
+ fullPrompt = `## CURRENT CODE:
+\`\`\`tsx
+${currentCode}
+\`\`\`
+${conversationContext}
+${manualEditNotice}
+
+## USER REQUEST:
+${prompt}
+
+Please modify the existing code according to the user's request. Output only the complete updated code.`;
+ }
+
try {
const result = streamText({
model: openai(modelName),
system: enhancedSystemPrompt,
- prompt,
+ prompt: fullPrompt,
...(reasoningEffort && {
providerOptions: {
openai: {
@@ -196,6 +275,8 @@ export async function POST(req: Request) {
modelName,
"skills:",
detectedSkills.length > 0 ? detectedSkills.join(", ") : "general",
+ "isFollowUp:",
+ isFollowUp,
reasoningEffort ? `reasoning_effort: ${reasoningEffort}` : "",
);
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.tsx
index fddbe411e8..a584293498 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
@@ -7,6 +7,7 @@ import { Loader2 } from "lucide-react";
import { CodeEditor } from "../../components/CodeEditor";
import { AnimationPlayer } from "../../components/AnimationPlayer";
import { PageLayout } from "../../components/PageLayout";
+import { ChatHistory } from "../../components/ChatHistory";
import {
PromptInput,
type StreamPhase,
@@ -15,6 +16,7 @@ import {
} from "../../components/PromptInput";
import { examples } from "../../examples/code";
import { useAnimationState } from "../../hooks/useAnimationState";
+import { useConversationState } from "../../hooks/useConversationState";
function GeneratePageContent() {
const searchParams = useSearchParams();
@@ -40,6 +42,21 @@ function GeneratePageContent() {
type: GenerationErrorType;
} | null>(null);
+ // Conversation state for follow-up edits
+ const {
+ messages,
+ hasManualEdits,
+ addUserMessage,
+ addAssistantMessage,
+ markManualEdit,
+ clearConversation,
+ getRecentContext,
+ isFirstGeneration,
+ } = useConversationState();
+
+ // Sidebar collapse state
+ const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);
+
const { code, Component, error, isCompiling, setCode, compileCode } =
useAnimationState(examples[0]?.code || "");
@@ -68,6 +85,11 @@ function GeneratePageContent() {
setCode(newCode);
setHasGeneratedOnce(true);
+ // Mark as manual edit if not streaming (user typing)
+ if (!isStreamingRef.current) {
+ markManualEdit(newCode);
+ }
+
// Clear existing debounce
if (debounceRef.current) {
clearTimeout(debounceRef.current);
@@ -83,7 +105,23 @@ function GeneratePageContent() {
compileCode(newCode);
}, 500);
},
- [setCode, compileCode],
+ [setCode, compileCode, markManualEdit],
+ );
+
+ // Handle message sent for history
+ const handleMessageSent = useCallback(
+ (promptText: string) => {
+ addUserMessage(promptText);
+ },
+ [addUserMessage],
+ );
+
+ // Handle generation complete for history
+ const handleGenerationComplete = useCallback(
+ (generatedCode: string) => {
+ addAssistantMessage("Generated code", generatedCode);
+ },
+ [addAssistantMessage],
);
// Cleanup debounce on unmount
@@ -125,39 +163,57 @@ function GeneratePageContent() {
return (
<PageLayout showLogoAsLink>
- <div className="flex-1 flex flex-col min-w-0 px-12 pb-8 gap-8 overflow-hidden">
- <div className="flex-1 flex flex-col lg:flex-row overflow-auto lg:overflow-hidden gap-8">
- <CodeEditor
- code={hasGeneratedOnce && !generationError ? code : ""}
- onChange={handleCodeChange}
- isStreaming={isStreaming}
- streamPhase={streamPhase}
- />
- <div className="shrink-0 lg:shrink lg:flex-[2.5] lg:min-w-0 lg:h-full">
- <AnimationPlayer
- Component={generationError ? null : Component}
- durationInFrames={durationInFrames}
- fps={fps}
- onDurationChange={setDurationInFrames}
- onFpsChange={setFps}
- isCompiling={isCompiling}
+ <div className="flex-1 flex min-w-0 overflow-hidden">
+ {/* Chat History Sidebar */}
+ <ChatHistory
+ messages={messages}
+ isCollapsed={isSidebarCollapsed}
+ onToggleCollapse={() => setIsSidebarCollapsed(!isSidebarCollapsed)}
+ onClear={clearConversation}
+ hasManualEdits={hasManualEdits}
+ />
+
+ {/* Main content area */}
+ <div className="flex-1 flex flex-col min-w-0 px-12 pb-8 gap-8 overflow-hidden">
+ <div className="flex-1 flex flex-col lg:flex-row overflow-auto lg:overflow-hidden gap-8">
+ <CodeEditor
+ code={hasGeneratedOnce && !generationError ? code : ""}
+ onChange={handleCodeChange}
isStreaming={isStreaming}
- error={generationError?.message || error}
- errorType={generationError?.type || "compilation"}
- code={code}
+ streamPhase={streamPhase}
/>
+ <div className="shrink-0 lg:shrink lg:flex-[2.5] lg:min-w-0 lg:h-full">
+ <AnimationPlayer
+ Component={generationError ? null : Component}
+ durationInFrames={durationInFrames}
+ fps={fps}
+ onDurationChange={setDurationInFrames}
+ onFpsChange={setFps}
+ isCompiling={isCompiling}
+ isStreaming={isStreaming}
+ error={generationError?.message || error}
+ errorType={generationError?.type || "compilation"}
+ code={code}
+ />
+ </div>
</div>
- </div>
- <PromptInput
- ref={promptInputRef}
- onCodeGenerated={handleCodeChange}
- onStreamingChange={handleStreamingChange}
- onStreamPhaseChange={setStreamPhase}
- onError={handleError}
- prompt={prompt}
- onPromptChange={setPrompt}
- />
+ <PromptInput
+ ref={promptInputRef}
+ onCodeGenerated={handleCodeChange}
+ onStreamingChange={handleStreamingChange}
+ onStreamPhaseChange={setStreamPhase}
+ onError={handleError}
+ prompt={prompt}
+ onPromptChange={setPrompt}
+ currentCode={code}
+ conversationHistory={getRecentContext(3)}
+ isFollowUp={!isFirstGeneration}
+ hasManualEdits={hasManualEdits}
+ onMessageSent={handleMessageSent}
+ onGenerationComplete={handleGenerationComplete}
+ />
+ </div>
</div>
</PageLayout>
);
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.tsx
new file mode 100644
index 0000000000..134356758f
--- /dev/null
+++ b/packages/template-prompt-to-motion-graphics/src/components/ChatHistory/ChatHistory.tsx
@@ -0,0 +1,113 @@
+"use client";
+
+import {
+ MessageSquare,
+ ChevronLeft,
+ ChevronRight,
+ Trash2,
+ Pencil,
+} from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import type { ConversationMessage } from "@/types/conversation";
+
+interface ChatHistoryProps {
+ messages: ConversationMessage[];
+ isCollapsed: boolean;
+ onToggleCollapse: () => void;
+ onClear: () => void;
+ hasManualEdits: boolean;
+}
+
+export function ChatHistory({
+ messages,
+ isCollapsed,
+ onToggleCollapse,
+ onClear,
+ hasManualEdits,
+}: ChatHistoryProps) {
+ if (messages.length === 0) {
+ return null;
+ }
+
+ return (
+ <div
+ className={cn(
+ "flex flex-col bg-background-elevated border-r border-border transition-all duration-300 shrink-0",
+ isCollapsed ? "w-12" : "w-72",
+ )}
+ >
+ {/* Header */}
+ <div className="flex items-center justify-between p-3 border-b border-border">
+ {!isCollapsed && (
+ <>
+ <div className="flex items-center gap-2">
+ <MessageSquare className="w-4 h-4 text-muted-foreground" />
+ <span className="text-sm font-medium text-foreground">
+ History
+ </span>
+ </div>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={onClear}
+ title="Clear history"
+ >
+ <Trash2 className="w-4 h-4" />
+ </Button>
+ </>
+ )}
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={onToggleCollapse}
+ className={cn(isCollapsed && "mx-auto")}
+ >
+ {isCollapsed ? (
+ <ChevronRight className="w-4 h-4" />
+ ) : (
+ <ChevronLeft className="w-4 h-4" />
+ )}
+ </Button>
+ </div>
+
+ {/* Messages */}
+ {!isCollapsed && (
+ <div className="flex-1 overflow-y-auto p-3 space-y-3">
+ {hasManualEdits && (
+ <div className="text-xs text-muted-foreground-dim bg-accent rounded px-2 py-1 flex items-center gap-1">
+ <Pencil className="w-3 h-3" />
+ Code has been manually edited
+ </div>
+ )}
+ {messages.map((message) => (
+ <ChatMessage key={message.id} message={message} />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function ChatMessage({ message }: { message: ConversationMessage }) {
+ const isUser = message.role === "user";
+
+ return (
+ <div
+ className={cn(
+ "rounded-lg p-2 text-sm",
+ isUser
+ ? "bg-primary/10 text-foreground"
+ : "bg-secondary text-secondary-foreground",
+ )}
+ >
+ <div className="text-xs text-muted-foreground-dim mb-1">
+ {isUser ? "You" : "AI"}
+ </div>
+ <div className="line-clamp-3">{message.content}</div>
+ <div className="text-xs text-muted-foreground-dim mt-1">
+ {new Date(message.timestamp).toLocaleTimeString()}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/template-prompt-to-motion-graphics/src/components/ChatHistory/index.ts b/packages/template-prompt-to-motion-graphics/src/components/ChatHistory/index.ts
new file mode 100644
index 0000000000..ef737bca1f
--- /dev/null
+++ b/packages/template-prompt-to-motion-graphics/src/components/ChatHistory/index.ts
@@ -0,0 +1 @@
+export { ChatHistory } from "./ChatHistory";
diff --git a/packages/template-prompt-to-motion-graphics/src/components/PromptInput.tsx b/packages/template-prompt-to-motion-graphics/src/components/PromptInput.tsx
index 0017dcd179..15822008d7 100644
--- a/packages/template-prompt-to-motion-graphics/src/components/PromptInput.tsx
+++ b/packages/template-prompt-to-motion-graphics/src/components/PromptInput.tsx
@@ -10,8 +10,10 @@ import {
Hash,
BarChart3,
Disc,
+ Pencil,
type LucideIcon,
} from "lucide-react";
+import type { ConversationContextMessage } from "@/types/conversation";
import {
Select,
SelectContent,
@@ -68,6 +70,18 @@ interface PromptInputProps {
isNavigating?: boolean;
/** Whether to show the "View Code examples" link (landing variant) */
showCodeExamplesLink?: boolean;
+ /** Current code in the editor for follow-up context */
+ currentCode?: string;
+ /** Conversation history for context */
+ conversationHistory?: ConversationContextMessage[];
+ /** Whether this is a follow-up edit (has existing code) */
+ isFollowUp?: boolean;
+ /** Whether the code has manual edits */
+ hasManualEdits?: boolean;
+ /** Callback when a message is sent (for history tracking) */
+ onMessageSent?: (prompt: string) => void;
+ /** Callback when generation completes (for history tracking) */
+ onGenerationComplete?: (code: string) => void;
}
export const PromptInput = forwardRef<PromptInputRef, PromptInputProps>(
@@ -83,6 +97,12 @@ export const PromptInput = forwardRef<PromptInputRef, PromptInputProps>(
onNavigate,
isNavigating = false,
showCodeExamplesLink = false,
+ currentCode,
+ conversationHistory = [],
+ isFollowUp = false,
+ hasManualEdits = false,
+ onMessageSent,
+ onGenerationComplete,
},
ref,
) {
@@ -101,11 +121,22 @@ export const PromptInput = forwardRef<PromptInputRef, PromptInputProps>(
setIsLoading(true);
onStreamingChange?.(true);
onStreamPhaseChange?.("reasoning");
+
+ // Track the message for history
+ onMessageSent?.(prompt);
+
try {
const response = await fetch("/api/generate", {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ prompt, model }),
+ body: JSON.stringify({
+ prompt,
+ model,
+ currentCode: isFollowUp ? currentCode : undefined,
+ conversationHistory: isFollowUp ? conversationHistory : [],
+ isFollowUp,
+ hasManualEdits,
+ }),
});
if (!response.ok) {
@@ -183,6 +214,9 @@ export const PromptInput = forwardRef<PromptInputRef, PromptInputProps>(
// Update the editor with the cleaned code
onCodeGenerated?.(finalCode);
+ // Track generation completion for history
+ onGenerationComplete?.(finalCode);
+
const validation = validateGptResponse(finalCode);
if (!validation.isValid && validation.error) {
onError?.(validation.error, "validation");
@@ -249,6 +283,13 @@ 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 && (
+ <div className="text-xs text-muted-foreground-dim mb-2 flex items-center gap-1">
+ <Pencil className="w-3 h-3" />
+ Editing existing animation
+ {hasManualEdits && " (includes your edits)"}
+ </div>
+ )}
<textarea
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
diff --git a/packages/template-prompt-to-motion-graphics/src/hooks/useConversationState.ts b/packages/template-prompt-to-motion-graphics/src/hooks/useConversationState.ts
new file mode 100644
index 0000000000..ece15a907e
--- /dev/null
+++ b/packages/template-prompt-to-motion-graphics/src/hooks/useConversationState.ts
@@ -0,0 +1,93 @@
+import { useState, useCallback, useRef } from "react";
+import type {
+ ConversationMessage,
+ ConversationState,
+ ConversationContextMessage,
+} from "@/types/conversation";
+
+export function useConversationState() {
+ const [state, setState] = useState<ConversationState>({
+ messages: [],
+ hasManualEdits: false,
+ lastGenerationTimestamp: null,
+ });
+
+ // Track the last AI-generated code to detect manual edits
+ const lastAiCodeRef = useRef<string>("");
+
+ const addUserMessage = useCallback((content: string) => {
+ const message: ConversationMessage = {
+ id: `user-${Date.now()}`,
+ role: "user",
+ content,
+ timestamp: Date.now(),
+ };
+ setState((prev) => ({
+ ...prev,
+ messages: [...prev.messages, message],
+ }));
+ return message.id;
+ }, []);
+
+ const addAssistantMessage = useCallback(
+ (content: string, codeSnapshot: string) => {
+ const message: ConversationMessage = {
+ id: `assistant-${Date.now()}`,
+ role: "assistant",
+ content,
+ timestamp: Date.now(),
+ codeSnapshot,
+ };
+ lastAiCodeRef.current = codeSnapshot;
+ setState((prev) => ({
+ ...prev,
+ messages: [...prev.messages, message],
+ hasManualEdits: false,
+ lastGenerationTimestamp: Date.now(),
+ }));
+ return message.id;
+ },
+ [],
+ );
+
+ const markManualEdit = useCallback((currentCode: string) => {
+ // Only mark as manual edit if code differs from last AI generation
+ if (currentCode !== lastAiCodeRef.current && lastAiCodeRef.current !== "") {
+ setState((prev) => ({
+ ...prev,
+ hasManualEdits: true,
+ }));
+ }
+ }, []);
+
+ const clearConversation = useCallback(() => {
+ lastAiCodeRef.current = "";
+ setState({
+ messages: [],
+ hasManualEdits: false,
+ lastGenerationTimestamp: null,
+ });
+ }, []);
+
+ // Get the last N conversation exchanges for context
+ const getRecentContext = useCallback(
+ (count: number = 3): ConversationContextMessage[] => {
+ const recentMessages = state.messages.slice(-count * 2);
+ return recentMessages.map((m) => ({
+ role: m.role,
+ content: m.role === "user" ? m.content : "[Generated Code]",
+ }));
+ },
+ [state.messages],
+ );
+
+ return {
+ ...state,
+ addUserMessage,
+ addAssistantMessage,
+ markManualEdit,
+ clearConversation,
+ getRecentContext,
+ isFirstGeneration: state.messages.length === 0,
+ };
+}
diff --git a/packages/template-prompt-to-motion-graphics/src/types/conversation.ts b/packages/template-prompt-to-motion-graphics/src/types/conversation.ts
new file mode 100644
index 0000000000..1b3fec1ddb
--- /dev/null
+++ b/packages/template-prompt-to-motion-graphics/src/types/conversation.ts
@@ -0,0 +1,21 @@
+export interface ConversationMessage {
+ id: string;
+ role: "user" | "assistant";
+ content: string;
+ timestamp: number;
+ /** For assistant messages, store the code snapshot at time of generation */
+ codeSnapshot?: string;
+}
+
+export interface ConversationState {
+ messages: ConversationMessage[];
+ /** Track if the current code has been manually edited since last generation */
+ hasManualEdits: boolean;
+ /** Timestamp of last AI generation - compare with code changes to detect manual edits */
+ lastGenerationTimestamp: number | null;
+}
+
+export interface ConversationContextMessage {
+ role: "user" | "assistant";
+ content: string;
+}