🎥 Make videos programmatically with React
Enhance follow-up edits with targeted edit mode and rich chat history
ASchwadcabfc7e57583
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 ee3dbfd3d4..51f60a11cc 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,24 +105,144 @@ 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+const FOLLOW_UP_SYSTEM_PROMPT = `+You are an expert at making targeted edits to React/Remotion animation components.++Given the current code and a user request, decide whether to:+1. Use targeted edits (for small, specific changes)+2. Provide full replacement code (for major restructuring)++## WHEN TO USE TARGETED EDITS (type: "edit")+- Changing colors, text, numbers, timing values+- Adding or removing a single element+- Modifying styles or properties+- Small additions (new variable, new element)+- Changes affecting <30% of the code++## WHEN TO USE FULL REPLACEMENT (type: "full")+- Completely different animation style+- Major structural reorganization+- User asks to "start fresh" or "rewrite"+- Changes affect >50% of the code++## EDIT FORMAT+For targeted edits, each edit needs:+- old_string: The EXACT string to find (including whitespace/indentation)+- new_string: The replacement string++CRITICAL:+- old_string must match the code EXACTLY character-for-character+- Include enough surrounding context to make old_string unique+- If multiple similar lines exist, include more surrounding code+- Preserve indentation exactly as it appears in the original++## PRESERVING USER EDITS+If the user has made manual edits, preserve them unless explicitly asked to change.`;+// Schema for follow-up edit responses+// Note: Using a flat object schema because OpenAI doesn't support discriminated unions+const FollowUpResponseSchema = z.object({+ type: z+ .enum(["edit", "full"])+ .describe('Use "edit" for small targeted changes, "full" for major restructuring'),+ summary: z+ .string()+ .describe(+ "A brief 1-sentence summary of what changes were made, e.g. 'Changed background color to blue and increased font size'"+ ),+ edits: z+ .array(+ z.object({+ description: z+ .string()+ .describe(+ "Brief description of this edit, e.g. 'Update background color', 'Increase animation duration'"+ ),+ old_string: z+ .string()+ .describe("The exact string to find (must match exactly)"),+ new_string: z.string().describe("The replacement string"),+ })+ )+ .optional()+ .describe("Required when type is 'edit': array of search-replace operations"),+ code: z+ .string()+ .optional()+ .describe(+ "Required when type is 'full': the complete replacement code starting with imports"+ ),+});++type EditOperation = {+ description: string;+ old_string: string;+ new_string: string;+ lineNumber?: number;+};++// Calculate line number where a string occurs in code+function getLineNumber(code: string, searchString: string): number {+ const index = code.indexOf(searchString);+ if (index === -1) return -1;+ return code.substring(0, index).split("\n").length;+}++// Apply edit operations to code and enrich with line numbers+function applyEdits(+ code: string,+ edits: EditOperation[]+): {+ success: boolean;+ result: string;+ error?: string;+ enrichedEdits?: EditOperation[];+} {+ let result = code;+ const enrichedEdits: EditOperation[] = [];++ for (let i = 0; i < edits.length; i++) {+ const edit = edits[i];+ const { old_string, new_string, description } = edit;++ // Check if the old_string exists+ if (!result.includes(old_string)) {+ return {+ success: false,+ result: code,+ error: `Edit ${i + 1} failed: Could not find the specified text`,+ };+ }++ // Check for multiple matches (ambiguous)+ const matches = result.split(old_string).length - 1;+ if (matches > 1) {+ return {+ success: false,+ result: code,+ error: `Edit ${i + 1} failed: Found ${matches} matches. The edit target is ambiguous.`,+ };+ }++ // Get line number before applying edit+ const lineNumber = getLineNumber(result, old_string);++ // Apply the edit+ result = result.replace(old_string, new_string);++ // Store enriched edit with line number+ enrichedEdits.push({+ description,+ old_string,+ new_string,+ lineNumber,+ });+ }++ return { success: true, result, enrichedEdits };+}+interface ConversationContextMessage {role: "user" | "assistant";content: string;@@ -137,6 +257,17 @@ interface GenerateRequest {hasManualEdits?: boolean;}+interface GenerateResponse {+ code: string;+ summary: string;+ metadata: {+ skills: string[];+ editType: "tool_edit" | "full_replacement";+ edits?: EditOperation[];+ model: string;+ };+}+export async function POST(req: Request) {const {prompt,@@ -212,36 +343,29 @@ export async function POST(req: Request) {// Load skill-specific content and enhance the system promptconst skillContent = getCombinedSkillContent(detectedSkills);- let enhancedSystemPrompt = skillContent+ const 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;-+ // FOLLOW-UP MODE: Use non-streaming generateObject for faster editsif (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");- }+ try {+ // Build context for the edit request+ 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."- : "";+ const manualEditNotice = hasManualEdits+ ? "\n\nNOTE: The user has made manual edits to the code. Preserve these changes."+ : "";- fullPrompt = `## CURRENT CODE:+ const editPrompt = `## CURRENT CODE:\`\`\`tsx${currentCode}\`\`\`@@ -251,14 +375,96 @@ ${manualEditNotice}## USER REQUEST:${prompt}-Please modify the existing code according to the user's request. Output only the complete updated code.`;+Analyze the request and decide: use targeted edits (type: "edit") for small changes, or full replacement (type: "full") for major restructuring.`;++ console.log(+ "Follow-up edit with prompt:",+ prompt,+ "model:",+ modelName,+ "skills:",+ detectedSkills.length > 0 ? detectedSkills.join(", ") : "general"+ );++ const editResult = await generateObject({+ model: openai(modelName),+ system: FOLLOW_UP_SYSTEM_PROMPT,+ prompt: editPrompt,+ schema: FollowUpResponseSchema,+ });++ const response = editResult.object;+ let finalCode: string;+ let editType: "tool_edit" | "full_replacement";+ let appliedEdits: EditOperation[] | undefined;++ if (response.type === "edit" && response.edits) {+ // Apply the edits to the current code+ const result = applyEdits(currentCode, response.edits);+ if (!result.success) {+ // If edits fail, return error+ return new Response(+ JSON.stringify({+ error: result.error,+ type: "edit_failed",+ }),+ { status: 400, headers: { "Content-Type": "application/json" } }+ );+ }+ finalCode = result.result;+ editType = "tool_edit";+ // Use enriched edits with line numbers+ appliedEdits = result.enrichedEdits;+ console.log(`Applied ${response.edits.length} edit(s) successfully`);+ } else if (response.type === "full" && response.code) {+ // Full replacement+ finalCode = response.code;+ editType = "full_replacement";+ console.log("Using full code replacement");+ } else {+ // Invalid response - missing required fields+ return new Response(+ JSON.stringify({+ error: "Invalid AI response: missing required fields",+ type: "edit_failed",+ }),+ { status: 400, headers: { "Content-Type": "application/json" } }+ );+ }++ // Return the result with metadata+ const responseData: GenerateResponse = {+ code: finalCode,+ summary: response.summary,+ metadata: {+ skills: detectedSkills,+ editType,+ edits: appliedEdits,+ model: modelName,+ },+ };++ return new Response(JSON.stringify(responseData), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ } catch (error) {+ console.error("Error in follow-up edit:", error);+ return new Response(+ JSON.stringify({+ error: "Something went wrong while processing the edit request.",+ }),+ { status: 500, headers: { "Content-Type": "application/json" } }+ );+ }}+ // INITIAL GENERATION: Use streaming for new animationstry {const result = streamText({model: openai(modelName),system: enhancedSystemPrompt,- prompt: fullPrompt,+ prompt,...(reasoningEffort && {providerOptions: {openai: {@@ -275,9 +481,7 @@ Please modify the existing code according to the user's request. Output only themodelName,"skills:",detectedSkills.length > 0 ? detectedSkills.join(", ") : "general",- "isFollowUp:",- isFollowUp,- reasoningEffort ? `reasoning_effort: ${reasoningEffort}` : "",+ reasoningEffort ? `reasoning_effort: ${reasoningEffort}` : "");return result.toUIMessageStreamResponse({@@ -289,7 +493,7 @@ Please modify the existing code according to the user's request. Output only theJSON.stringify({error: "Something went wrong while trying to reach OpenAI APIs.",}),- { status: 500, headers: { "Content-Type": "application/json" } },+ { status: 500, headers: { "Content-Type": "application/json" } });}}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 a584293498..9b677e94f9 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,6 +17,7 @@ import {import { examples } from "../../examples/code";import { useAnimationState } from "../../hooks/useAnimationState";import { useConversationState } from "../../hooks/useConversationState";+import type { AssistantMetadata } from "../../types/conversation";function GeneratePageContent() {const searchParams = useSearchParams();@@ -48,6 +49,7 @@ function GeneratePageContent() {hasManualEdits,addUserMessage,addAssistantMessage,+ addErrorMessage,markManualEdit,clearConversation,getRecentContext,@@ -118,8 +120,9 @@ function GeneratePageContent() {// Handle generation complete for historyconst handleGenerationComplete = useCallback(- (generatedCode: string) => {- addAssistantMessage("Generated code", generatedCode);+ (generatedCode: string, summary?: string, metadata?: AssistantMetadata) => {+ const content = summary || "Generated animation";+ addAssistantMessage(content, generatedCode, metadata);},[addAssistantMessage],);@@ -212,6 +215,7 @@ function GeneratePageContent() {hasManualEdits={hasManualEdits}onMessageSent={handleMessageSent}onGenerationComplete={handleGenerationComplete}+ onErrorMessage={addErrorMessage}/></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 134356758f..63a46821d8 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@@ -6,6 +6,9 @@ import {ChevronRight,Trash2,Pencil,+ FileCode,+ CheckCircle2,+ AlertTriangle,} from "lucide-react";import { Button } from "@/components/ui/button";import { cn } from "@/lib/utils";@@ -91,21 +94,96 @@ 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 display+ if (isUser) {+ return (+ <div className="rounded-lg p-2 text-sm bg-primary/10 text-foreground">+ <div className="text-xs text-muted-foreground-dim mb-1">You</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>+ );+ }++ // Error messages - show the error with retry hint+ if (isError) {+ return (+ <div className="rounded-lg p-2 text-sm bg-red-500/10 border border-red-500/20 text-foreground space-y-1">+ <div className="flex items-center gap-1.5 text-red-400">+ <AlertTriangle className="w-3.5 h-3.5" />+ <span className="font-medium text-xs">Edit Failed</span>+ </div>+ <div className="text-xs text-red-300/80">{message.content}</div>+ <div className="text-[10px] text-muted-foreground-dim pt-1">+ Try rephrasing your request or be more specific+ </div>+ </div>+ );+ }++ // Assistant messages - Claude Code style with detailsreturn (- <div- className={cn(- "rounded-lg p-2 text-sm",- isUser- ? "bg-primary/10 text-foreground"- : "bg-secondary text-secondary-foreground",+ <div className="rounded-lg p-2 text-sm bg-secondary text-secondary-foreground space-y-2">+ {/* Summary as main content */}+ <div className="font-medium text-foreground">{message.content}</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>)}- >- <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">++ {/* 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>+ )}++ {/* 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>+ </div>+ )}++ {/* Timestamp */}+ <div className="text-[10px] text-muted-foreground-dim pt-1 border-t border-border/30">{new Date(message.timestamp).toLocaleTimeString()}</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 15822008d7..7c98964769 100644--- a/packages/template-prompt-to-motion-graphics/src/components/PromptInput.tsx+++ b/packages/template-prompt-to-motion-graphics/src/components/PromptInput.tsx@@ -13,7 +13,10 @@ import {Pencil,type LucideIcon,} from "lucide-react";-import type { ConversationContextMessage } from "@/types/conversation";+import type {+ ConversationContextMessage,+ AssistantMetadata,+} from "@/types/conversation";import {Select,SelectContent,@@ -81,7 +84,16 @@ interface PromptInputProps {/** Callback when a message is sent (for history tracking) */onMessageSent?: (prompt: string) => void;/** Callback when generation completes (for history tracking) */- onGenerationComplete?: (code: string) => void;+ onGenerationComplete?: (+ code: string,+ summary?: string,+ metadata?: AssistantMetadata+ ) => void;+ /** Callback when an error occurs (for history tracking) */+ onErrorMessage?: (+ message: string,+ errorType: "edit_failed" | "api" | "validation"+ ) => void;}export const PromptInput = forwardRef<PromptInputRef, PromptInputProps>(@@ -103,6 +115,7 @@ export const PromptInput = forwardRef<PromptInputRef, PromptInputProps>(hasManualEdits = false,onMessageSent,onGenerationComplete,+ onErrorMessage,},ref,) {@@ -143,14 +156,42 @@ export const PromptInput = forwardRef<PromptInputRef, PromptInputProps>(const errorData = await response.json().catch(() => ({}));const errorMessage =errorData.error || `API error: ${response.status}`;- // Check if this is a validation error from the API+ // Check if this is a validation error or edit failure from the API+ if (errorData.type === "edit_failed") {+ onError?.(errorMessage, "validation");+ onErrorMessage?.(errorMessage, "edit_failed");+ return;+ }if (errorData.type === "validation") {onError?.(errorMessage, "validation");+ onErrorMessage?.(errorMessage, "validation");return;}throw new Error(errorMessage);}+ // Check content type to determine response format+ const contentType = response.headers.get("content-type") || "";++ // FOLLOW-UP: Non-streaming JSON response with metadata+ if (contentType.includes("application/json")) {+ const data = await response.json();+ const { code, summary, metadata } = data;++ // Update the editor with the code+ onCodeGenerated?.(code);++ // Track generation completion with metadata and summary+ onGenerationComplete?.(code, summary, metadata);++ const validation = validateGptResponse(code);+ if (!validation.isValid && validation.error) {+ onError?.(validation.error, "validation");+ }+ return;+ }++ // INITIAL: Streaming SSE responseconst reader = response.body?.getReader();if (!reader) {throw new Error("No response body");@@ -198,7 +239,10 @@ export const PromptInput = forwardRef<PromptInputRef, PromptInputProps>(}} catch (parseError) {// Only re-throw if it's an actual Error we created, not a JSON parse error- if (parseError instanceof Error && parseError.message !== "Unexpected token") {+ if (+ parseError instanceof Error &&+ parseError.message !== "Unexpected token"+ ) {throw parseError;}}@@ -214,7 +258,7 @@ export const PromptInput = forwardRef<PromptInputRef, PromptInputProps>(// Update the editor with the cleaned codeonCodeGenerated?.(finalCode);- // Track generation completion for history+ // Track generation completion for history (no metadata for streaming)onGenerationComplete?.(finalCode);const validation = validateGptResponse(finalCode);diff --git a/packages/template-prompt-to-motion-graphics/src/hooks/useConversationState.ts b/packages/template-prompt-to-motion-graphics/src/hooks/useConversationState.tsindex ece15a907e..a6da496a3f 100644--- a/packages/template-prompt-to-motion-graphics/src/hooks/useConversationState.ts+++ b/packages/template-prompt-to-motion-graphics/src/hooks/useConversationState.ts@@ -3,6 +3,7 @@ import type {ConversationMessage,ConversationState,ConversationContextMessage,+ AssistantMetadata,} from "@/types/conversation";export function useConversationState() {@@ -30,13 +31,14 @@ export function useConversationState() {}, []);const addAssistantMessage = useCallback(- (content: string, codeSnapshot: string) => {+ (content: string, codeSnapshot: string, metadata?: AssistantMetadata) => {const message: ConversationMessage = {id: `assistant-${Date.now()}`,role: "assistant",content,timestamp: Date.now(),codeSnapshot,+ metadata,};lastAiCodeRef.current = codeSnapshot;setState((prev) => ({@@ -50,6 +52,24 @@ export function useConversationState() {[],);+ const addErrorMessage = useCallback(+ (content: string, errorType: "edit_failed" | "api" | "validation") => {+ const message: ConversationMessage = {+ id: `error-${Date.now()}`,+ role: "error",+ content,+ timestamp: Date.now(),+ errorType,+ };+ setState((prev) => ({+ ...prev,+ messages: [...prev.messages, message],+ }));+ return message.id;+ },+ [],+ );+const markManualEdit = useCallback((currentCode: string) => {// Only mark as manual edit if code differs from last AI generationif (currentCode !== lastAiCodeRef.current && lastAiCodeRef.current !== "") {@@ -69,12 +89,16 @@ export function useConversationState() {});}, []);- // Get the last N conversation exchanges for context+ // Get the last N conversation exchanges for context (excludes error messages)const getRecentContext = useCallback((count: number = 3): ConversationContextMessage[] => {- const recentMessages = state.messages.slice(-count * 2);+ // Filter out error messages - they're not part of the conversation context for the AI+ const conversationMessages = state.messages.filter(+ (m) => m.role === "user" || m.role === "assistant",+ );+ const recentMessages = conversationMessages.slice(-count * 2);return recentMessages.map((m) => ({- role: m.role,+ role: m.role as "user" | "assistant",content: m.role === "user" ? m.content : "[Generated Code]",}));},@@ -85,6 +109,7 @@ export function useConversationState() {...state,addUserMessage,addAssistantMessage,+ addErrorMessage,markManualEdit,clearConversation,getRecentContext,diff --git a/packages/template-prompt-to-motion-graphics/src/types/conversation.ts b/packages/template-prompt-to-motion-graphics/src/types/conversation.tsindex 1b3fec1ddb..b1d971dca7 100644--- a/packages/template-prompt-to-motion-graphics/src/types/conversation.ts+++ b/packages/template-prompt-to-motion-graphics/src/types/conversation.ts@@ -1,10 +1,32 @@+export interface EditOperation {+ description: string;+ old_string: string;+ new_string: string;+ lineNumber?: number;+}++export interface AssistantMetadata {+ /** Which skills were detected for this generation */+ skills?: string[];+ /** Whether this was a tool-based edit or full replacement */+ editType?: "tool_edit" | "full_replacement";+ /** The edit operations applied (if tool_edit) */+ edits?: EditOperation[];+ /** Model used for generation */+ model?: string;+}+export interface ConversationMessage {id: string;- role: "user" | "assistant";+ role: "user" | "assistant" | "error";content: string;timestamp: number;/** For assistant messages, store the code snapshot at time of generation */codeSnapshot?: string;+ /** For assistant messages, store metadata about the generation */+ metadata?: AssistantMetadata;+ /** For error messages, store the error type */+ errorType?: "edit_failed" | "api" | "validation";}export interface ConversationState {