Skip to content

Add chat interface BEN-1073 #23

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions app/builder/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { ChatInterface } from '@/components/ui-builder/chat-interface';
import { PreviewCard } from '@/components/ui-builder/preview-card';
import { benchifyFileSchema } from '@/lib/schemas';
import { z } from 'zod';

export default function BuilderPage() {
const router = useRouter();
const [result, setResult] = useState<{
repairedFiles?: z.infer<typeof benchifyFileSchema>;
originalFiles?: z.infer<typeof benchifyFileSchema>;
buildOutput: string;
previewUrl: string;
} | null>(null);
const [initialPrompt, setInitialPrompt] = useState<string>('');

useEffect(() => {
// Get the result from sessionStorage
const storedResult = sessionStorage.getItem('builderResult');
const storedPrompt = sessionStorage.getItem('initialPrompt');

if (storedResult && storedPrompt) {
setResult(JSON.parse(storedResult));
setInitialPrompt(storedPrompt);
} else {
// If no result found, redirect back to home
router.push('/');
}
}, [router]);

if (!result) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-32 w-32 border-b-2 border-primary mx-auto mb-4"></div>
<p className="text-muted-foreground">Loading your project...</p>
</div>
</div>
);
}

return (
<div className="min-h-screen bg-background flex">
{/* Chat Interface - Left Side */}
<div className="w-1/4 min-w-80 border-r border-border bg-card flex-shrink-0">
<ChatInterface
initialPrompt={initialPrompt}
onUpdateResult={setResult}
/>
</div>

{/* Preview Area - Right Side */}
<div className="flex-1 p-4 overflow-hidden">
<PreviewCard
previewUrl={result.previewUrl}
code={result.repairedFiles || result.originalFiles || []}
/>
</div>
</div>
);
}
34 changes: 5 additions & 29 deletions app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,10 @@
// app/page.tsx
'use client';

import { useEffect, useState } from 'react';
import { PromptForm } from '@/components/ui-builder/prompt-form';
import { PreviewCard } from '@/components/ui-builder/preview-card';
import { Card, CardContent } from '@/components/ui/card';
import { benchifyFileSchema } from '@/lib/schemas';
import { z } from 'zod';

export default function Home() {
const [result, setResult] = useState<{
repairedFiles?: z.infer<typeof benchifyFileSchema>;
originalFiles?: z.infer<typeof benchifyFileSchema>;
buildOutput: string;
previewUrl: string;
} | null>(null);

useEffect(() => {
if (result) {
console.log(result);
}
}, [result]);

return (
<main className="min-h-screen flex flex-col items-center justify-center bg-background">
<div className="w-full max-w-3xl mx-auto">
Expand All @@ -31,18 +14,11 @@ export default function Home() {
<p className="text-lg text-muted-foreground mb-8 text-center">
Generate UI components with AI and automatically repair issues with Benchify
</p>
{!result ? (
<Card className="border-border bg-card">
<CardContent className="pt-6">
<PromptForm onGenerate={setResult} />
</CardContent>
</Card>
) : (
<PreviewCard
previewUrl={result.previewUrl}
code={result.repairedFiles || result.originalFiles || []}
/>
)}
<Card className="border-border bg-card">
<CardContent className="pt-6">
<PromptForm />
</CardContent>
</Card>
</div>
</main>
);
Expand Down
191 changes: 191 additions & 0 deletions components/ui-builder/chat-interface.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
'use client';

import { useState, useRef, useEffect } from 'react';
import { Send, RotateCcw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { benchifyFileSchema } from '@/lib/schemas';
import { z } from 'zod';

interface Message {
id: string;
type: 'user' | 'assistant';
content: string;
timestamp: Date;
}

interface ChatInterfaceProps {
initialPrompt: string;
onUpdateResult: (result: {
repairedFiles?: z.infer<typeof benchifyFileSchema>;
originalFiles?: z.infer<typeof benchifyFileSchema>;
buildOutput: string;
previewUrl: string;
}) => void;
}

export function ChatInterface({ initialPrompt, onUpdateResult }: ChatInterfaceProps) {
const [messages, setMessages] = useState<Message[]>([
{
id: '1',
type: 'user',
content: initialPrompt,
timestamp: new Date(),
},
{
id: '2',
type: 'assistant',
content: "I've generated your UI component! You can see the preview on the right. What would you like to modify or improve?",
timestamp: new Date(),
},
]);
const [newMessage, setNewMessage] = useState('');
const [isLoading, setIsLoading] = useState(false);
const messagesEndRef = useRef<HTMLDivElement>(null);

const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};

useEffect(() => {
scrollToBottom();
}, [messages]);

const handleSendMessage = async () => {
if (!newMessage.trim() || isLoading) return;

const userMessage: Message = {
id: Date.now().toString(),
type: 'user',
content: newMessage,
timestamp: new Date(),
};

setMessages(prev => [...prev, userMessage]);
setNewMessage('');
setIsLoading(true);

try {
// Here you would call your API to process the new request
// For now, we'll add a placeholder response
const assistantMessage: Message = {
id: (Date.now() + 1).toString(),
type: 'assistant',
content: "I understand your request. Let me update the component for you...",
timestamp: new Date(),
};

setMessages(prev => [...prev, assistantMessage]);

// TODO: Implement actual regeneration with the new prompt
// This would call your generate API with the conversation context

} catch (error) {
console.error('Error processing message:', error);
const errorMessage: Message = {
id: (Date.now() + 1).toString(),
type: 'assistant',
content: "I'm sorry, there was an error processing your request. Please try again.",
timestamp: new Date(),
};
setMessages(prev => [...prev, errorMessage]);
} finally {
setIsLoading(false);
}
};

const handleKeyPress = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSendMessage();
}
};

const handleStartOver = () => {
// Clear session storage and redirect to home
sessionStorage.removeItem('builderResult');
sessionStorage.removeItem('initialPrompt');
window.location.href = '/';
};

return (
<Card className="h-full flex flex-col border-0 rounded-none">
<CardHeader className="pb-3 border-b">
<div className="flex items-center justify-between">
<CardTitle className="text-lg">Chat</CardTitle>
<Button
variant="ghost"
size="sm"
onClick={handleStartOver}
className="h-8 px-2"
>
<RotateCcw className="h-4 w-4 mr-1" />
Start Over
</Button>
</div>
</CardHeader>

<CardContent className="flex-1 flex flex-col p-0">
<ScrollArea className="flex-1 p-4">
<div className="space-y-4">
{messages.map((message) => (
<div
key={message.id}
className={`flex ${message.type === 'user' ? 'justify-end' : 'justify-start'}`}
>
<div
className={`max-w-[80%] p-3 rounded-lg ${message.type === 'user'
? 'bg-primary text-primary-foreground'
: 'bg-muted text-muted-foreground'
}`}
>
<p className="text-sm whitespace-pre-wrap">{message.content}</p>
<p className="text-xs opacity-70 mt-1">
{message.timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
</p>
</div>
</div>
))}
{isLoading && (
<div className="flex justify-start">
<div className="bg-muted text-muted-foreground p-3 rounded-lg">
<div className="flex items-center space-x-2">
<div className="animate-pulse flex space-x-1">
<div className="w-2 h-2 bg-current rounded-full"></div>
<div className="w-2 h-2 bg-current rounded-full"></div>
<div className="w-2 h-2 bg-current rounded-full"></div>
</div>
<span className="text-sm">Thinking...</span>
</div>
</div>
</div>
)}
</div>
<div ref={messagesEndRef} />
</ScrollArea>

<div className="p-4 border-t">
<div className="flex space-x-2">
<Input
value={newMessage}
onChange={(e) => setNewMessage(e.target.value)}
onKeyPress={handleKeyPress}
placeholder="Describe your changes..."
disabled={isLoading}
className="flex-1"
/>
<Button
onClick={handleSendMessage}
disabled={!newMessage.trim() || isLoading}
size="sm"
>
<Send className="h-4 w-4" />
</Button>
</div>
</div>
</CardContent>
</Card>
);
}
45 changes: 22 additions & 23 deletions components/ui-builder/preview-card.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { Card, CardContent } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { benchifyFileSchema } from "@/lib/schemas";
import { z } from "zod";
Expand All @@ -13,30 +12,30 @@ export function PreviewCard({ previewUrl, code }: PreviewCardProps) {
const files = code || [];

return (
<Card className="border-border bg-card">
<CardContent>
<Tabs defaultValue="preview" className="w-full">
<TabsList className="mb-4">
<TabsTrigger value="preview">Preview</TabsTrigger>
<TabsTrigger value="code">Code</TabsTrigger>
</TabsList>
<div className="h-full">
<Tabs defaultValue="preview" className="w-full h-full flex flex-col">
<TabsList className="mb-4 self-start">
<TabsTrigger value="preview">Preview</TabsTrigger>
<TabsTrigger value="code">Code</TabsTrigger>
</TabsList>

<TabsContent value="preview" className="w-full">
<div className="w-full overflow-hidden rounded-md border">
<iframe
title="Preview"
src={previewUrl}
className="w-full h-[700px]"
sandbox="allow-scripts allow-same-origin"
/>
</div>
</TabsContent>
<TabsContent value="preview" className="flex-1 m-0">
<div className="w-full h-full overflow-hidden rounded-md border bg-background">
<iframe
title="Preview"
src={previewUrl}
className="w-full h-full"
sandbox="allow-scripts allow-same-origin"
/>
</div>
</TabsContent>

<TabsContent value="code" className="w-full h-[700px]">
<TabsContent value="code" className="flex-1 m-0">
<div className="h-full">
<CodeEditor files={files} />
</TabsContent>
</Tabs>
</CardContent>
</Card>
</div>
</TabsContent>
</Tabs>
</div>
);
}
Loading