Spaces:
Runtime error
Runtime error
Download frontend-react/src/components/ChatAssistant.jsx from Amitkasar/ai-api-testing: direct link, hf CLI and curl.
- Browser
- Download file 30.4 kB
-
https://huggingface.co/spaces/Amitkasar/ai-api-testing/resolve/main/frontend-react/src/components/ChatAssistant.jsx
- Command line
-
hf download hf://spaces/Amitkasar/ai-api-testing/frontend-react/src/components/ChatAssistant.jsx
-
curl -L -o ChatAssistant.jsx https://huggingface.co/spaces/Amitkasar/ai-api-testing/resolve/main/frontend-react/src/components/ChatAssistant.jsx
30.4 kB
| import React, { useState, useEffect, useRef, useCallback } from 'react'; | |
| import { | |
| Bot, Send, Plus, Trash2, Edit3, Check, X, MessageSquare, | |
| Zap, SkipForward, RefreshCw, TestTube, AlertCircle, | |
| ChevronRight, Sparkles, Play, PlayCircle | |
| } from 'lucide-react'; | |
| import { ChatService } from '../services/api'; | |
| import { useAppContext } from './AppContext'; | |
| import ModifyDiffModal from './workflow/ModifyDiffModal'; | |
| // βββββββββββββββββββββββββββββββββββββββββββββ | |
| // Helpers | |
| // βββββββββββββββββββββββββββββββββββββββββββββ | |
| const ACTION_ICONS = { | |
| execute_step: <Play size={13} className="text-blue-400" />, | |
| run_all: <PlayCircle size={13} className="text-emerald-400" />, | |
| retry_step: <RefreshCw size={13} className="text-yellow-400" />, | |
| skip_step: <SkipForward size={13} className="text-slate-400" />, | |
| modify_request: <Edit3 size={13} className="text-purple-400" />, | |
| explain: <AlertCircle size={13} className="text-orange-400" />, | |
| generate_tests: <TestTube size={13} className="text-pink-400" />, | |
| reply: <Bot size={13} className="text-[var(--accent-primary)]" />, | |
| }; | |
| const ACTION_LABELS = { | |
| execute_step: 'Execute Step', | |
| run_all: 'Run Full Flow', | |
| retry_step: 'Retry Step', | |
| skip_step: 'Skip Step', | |
| modify_request: 'Modify Request', | |
| explain: 'Explanation', | |
| generate_tests: 'Test Cases', | |
| reply: 'Reply', | |
| }; | |
| const ACTION_COLORS = { | |
| execute_step: 'border-blue-500/30 bg-blue-500/5', | |
| run_all: 'border-emerald-500/30 bg-emerald-500/5', | |
| retry_step: 'border-yellow-500/30 bg-yellow-500/5', | |
| skip_step: 'border-slate-500/30 bg-slate-500/5', | |
| modify_request: 'border-purple-500/30 bg-purple-500/5', | |
| explain: 'border-orange-500/30 bg-orange-500/5', | |
| generate_tests: 'border-pink-500/30 bg-pink-500/5', | |
| reply: 'border-[var(--border-subtle)] bg-transparent', | |
| }; | |
| const QUICK_COMMANDS = [ | |
| { label: 'Run full flow', icon: <PlayCircle size={13} /> }, | |
| { label: 'Why did this fail?', icon: <AlertCircle size={13} /> }, | |
| { label: 'Retry last step', icon: <RefreshCw size={13} /> }, | |
| { label: 'Generate test cases', icon: <TestTube size={13} /> }, | |
| ]; | |
| function formatTime(ts) { | |
| if (!ts) return ''; | |
| const d = new Date(ts); | |
| return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββ | |
| // MessageBubble | |
| // βββββββββββββββββββββββββββββββββββββββββββββ | |
| function MessageBubble({ msg, onAction }) { | |
| const isUser = msg.role === 'user'; | |
| const action = msg.action_json?.action || 'reply'; | |
| const isActionable = !isUser && ['execute_step', 'run_all', 'retry_step', 'skip_step', 'modify_request'].includes(action); | |
| const assertions = msg.action_json?.assertions; | |
| const changes = msg.action_json?.changes; | |
| const explanation = msg.action_json?.explanation; | |
| const step = msg.action_json?.step; | |
| return ( | |
| <div className={`flex ${isUser ? 'justify-end' : 'justify-start'} mb-4 animate-in fade-in slide-in-from-bottom-2 duration-200`}> | |
| {!isUser && ( | |
| <div className="w-7 h-7 rounded-full bg-gradient-to-br from-[var(--accent-primary)] to-[var(--accent-secondary)] flex items-center justify-center flex-shrink-0 mr-2 mt-1 shadow-md"> | |
| <Bot size={14} className="text-white" /> | |
| </div> | |
| )} | |
| <div className={`max-w-[78%] space-y-2 ${isUser ? 'items-end' : 'items-start'} flex flex-col`}> | |
| {/* Main bubble */} | |
| <div | |
| className={`px-3 py-2.5 rounded-xl text-sm leading-relaxed ${ | |
| isUser | |
| ? 'bg-[var(--accent-primary)] text-white rounded-tr-sm shadow-md' | |
| : `bg-[var(--bg-secondary)] border ${ACTION_COLORS[action] || 'border-[var(--border-subtle)]'} text-[var(--text-primary)] rounded-tl-sm shadow-sm` | |
| }`} | |
| > | |
| {!isUser && action !== 'reply' && ( | |
| <div className="flex items-center gap-1.5 mb-1.5 text-[10px] uppercase tracking-wider font-semibold opacity-70"> | |
| {ACTION_ICONS[action]} | |
| <span>{ACTION_LABELS[action] || action}</span> | |
| {step && <span className="font-mono">β Step {step}</span>} | |
| </div> | |
| )} | |
| <p className="whitespace-pre-wrap">{msg.content}</p> | |
| </div> | |
| {/* Explanation block */} | |
| {explanation && ( | |
| <div className="bg-[var(--bg-tertiary)] border border-orange-500/20 rounded-lg px-3 py-2.5 text-xs text-[var(--text-secondary)] leading-relaxed w-full"> | |
| <div className="flex items-center gap-1 text-orange-400 font-semibold mb-1 text-[10px] uppercase tracking-wider"> | |
| <AlertCircle size={11} /> Detailed Analysis | |
| </div> | |
| <p className="whitespace-pre-wrap">{explanation}</p> | |
| </div> | |
| )} | |
| {/* Changes block for modify_request */} | |
| {changes && Object.keys(changes).length > 0 && ( | |
| <div className="bg-[var(--bg-tertiary)] border border-purple-500/20 rounded-lg px-3 py-2.5 text-xs w-full font-mono"> | |
| <div className="text-purple-400 font-semibold mb-1 text-[10px] uppercase tracking-wider">Proposed Changes</div> | |
| {Object.entries(changes).map(([k, v]) => ( | |
| <div key={k} className="flex gap-2"> | |
| <span className="text-purple-400">{k}:</span> | |
| <span className="text-[var(--text-primary)]">"{String(v)}"</span> | |
| </div> | |
| ))} | |
| </div> | |
| )} | |
| {/* Test assertions block */} | |
| {assertions && assertions.length > 0 && ( | |
| <div className="bg-[var(--bg-tertiary)] border border-pink-500/20 rounded-lg px-3 py-2.5 text-xs w-full"> | |
| <div className="text-pink-400 font-semibold mb-2 text-[10px] uppercase tracking-wider flex items-center gap-1"> | |
| <TestTube size={11} /> Generated Assertions | |
| </div> | |
| <ul className="space-y-1"> | |
| {assertions.map((a, i) => ( | |
| <li key={i} className="flex items-start gap-2 text-[var(--text-secondary)]"> | |
| <Check size={11} className="text-emerald-400 mt-0.5 flex-shrink-0" /> | |
| <span>{String(a)}</span> | |
| </li> | |
| ))} | |
| </ul> | |
| </div> | |
| )} | |
| {/* Action button */} | |
| {isActionable && ( | |
| <button | |
| onClick={() => onAction(msg.action_json)} | |
| className="flex items-center gap-2 text-xs px-3 py-1.5 rounded-lg border border-[var(--accent-primary)]/40 bg-[var(--accent-primary)]/10 text-[var(--accent-primary)] hover:bg-[var(--accent-primary)]/20 transition-all font-medium active:scale-95" | |
| > | |
| {ACTION_ICONS[action]} | |
| <span> | |
| {action === 'execute_step' && `Execute Step ${step}`} | |
| {action === 'run_all' && 'Run All Steps'} | |
| {action === 'retry_step' && `Retry Step ${step || 'last'}`} | |
| {action === 'skip_step' && `Skip Step ${step}`} | |
| {action === 'modify_request' && 'Apply & Execute'} | |
| </span> | |
| <ChevronRight size={12} /> | |
| </button> | |
| )} | |
| <div className="text-[10px] text-[var(--text-secondary)] opacity-50 px-1"> | |
| {formatTime(msg.timestamp)} | |
| </div> | |
| </div> | |
| {isUser && ( | |
| <div className="w-7 h-7 rounded-full bg-[var(--bg-tertiary)] border border-[var(--border-subtle)] flex items-center justify-center flex-shrink-0 ml-2 mt-1"> | |
| <span className="text-[10px] font-bold text-[var(--text-secondary)]">U</span> | |
| </div> | |
| )} | |
| </div> | |
| ); | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββ | |
| // TypingIndicator | |
| // βββββββββββββββββββββββββββββββββββββββββββββ | |
| function TypingIndicator() { | |
| return ( | |
| <div className="flex justify-start mb-4"> | |
| <div className="w-7 h-7 rounded-full bg-gradient-to-br from-[var(--accent-primary)] to-[var(--accent-secondary)] flex items-center justify-center flex-shrink-0 mr-2 mt-1"> | |
| <Bot size={14} className="text-white" /> | |
| </div> | |
| <div className="bg-[var(--bg-secondary)] border border-[var(--border-subtle)] px-4 py-3 rounded-xl rounded-tl-sm shadow-sm"> | |
| <div className="flex gap-1 items-center h-4"> | |
| {[0, 150, 300].map((delay, i) => ( | |
| <div | |
| key={i} | |
| className="w-1.5 h-1.5 rounded-full bg-[var(--accent-primary)] opacity-70" | |
| style={{ animation: `bounce 1s ${delay}ms infinite` }} | |
| /> | |
| ))} | |
| </div> | |
| </div> | |
| </div> | |
| ); | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββ | |
| // ChatAssistant (main page + compact sidebar component) | |
| // βββββββββββββββββββββββββββββββββββββββββββββ | |
| /** | |
| * Props: | |
| * compact (bool) β When true: sessions sidebar is hidden. | |
| * lastStepResultProp (obj) β Auto-injects the last executed step result from the parent. | |
| * allStepResultsProp (obj) β Dict of ALL step results keyed by step number. | |
| * executeStepFromChat (fn) β Callback to trigger actual step execution from chat. | |
| */ | |
| export default function ChatAssistant({ executeStepFromChat, compact = false, lastStepResultProp = null, allStepResultsProp = null, onOpenInExecutionPanel = null }) { | |
| const { | |
| activeSpecId, activeSpecName, sessionId, | |
| executionPlan, sessionContextVars, | |
| globalChatId, setGlobalChatId | |
| } = useAppContext(); | |
| const [chatSessions, setChatSessions] = useState([]); | |
| // activeChatId is replaced by globalChatId | |
| const [messages, setMessages] = useState([]); | |
| const [inputText, setInputText] = useState(''); | |
| const [isLoading, setIsLoading] = useState(false); | |
| const [isFetchingSessions, setIsFetchingSessions] = useState(false); | |
| const [lastStepResult, setLastStepResult] = useState(lastStepResultProp); | |
| const [allStepResults, setAllStepResults] = useState(allStepResultsProp || {}); | |
| const [modifyDiff, setModifyDiff] = useState(null); // { stepDef, changes } | |
| // Sync externally-provided results | |
| useEffect(() => { | |
| if (lastStepResultProp) setLastStepResult(lastStepResultProp); | |
| }, [lastStepResultProp]); | |
| useEffect(() => { | |
| if (allStepResultsProp) setAllStepResults(allStepResultsProp); | |
| }, [allStepResultsProp]); | |
| // Inline rename state | |
| const [renamingId, setRenamingId] = useState(null); | |
| const [renameValue, setRenameValue] = useState(''); | |
| const messagesEndRef = useRef(null); | |
| const inputRef = useRef(null); | |
| // ββ Scroll to bottom on new messages ββ | |
| useEffect(() => { | |
| messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); | |
| }, [messages]); | |
| const fetchSessions = useCallback(async () => { | |
| setIsFetchingSessions(true); | |
| try { | |
| const data = await ChatService.getSessions(activeSpecId || null); | |
| setChatSessions(data); | |
| } catch (e) { | |
| console.error('Failed to fetch chat sessions', e); | |
| } finally { | |
| setIsFetchingSessions(false); | |
| } | |
| }, [activeSpecId]); | |
| const startNewChat = () => { | |
| setGlobalChatId(null); | |
| inputRef.current?.focus(); | |
| }; | |
| const loadSession = (id) => { | |
| setGlobalChatId(id); | |
| }; | |
| // ββ Re-fetch sessions and clear chat when active spec changes ββ | |
| useEffect(() => { | |
| fetchSessions(); | |
| startNewChat(); | |
| }, [activeSpecId]); | |
| // ββ Auto-load messages when globalChatId changes ββ | |
| useEffect(() => { | |
| if (globalChatId) { | |
| ChatService.getSession(globalChatId).then(data => { | |
| setMessages(data.messages || []); | |
| }).catch(e => console.error('Failed to load session', e)); | |
| } else { | |
| setMessages([]); | |
| } | |
| }, [globalChatId]); | |
| // ββ Send a message ββ | |
| const sendMessage = useCallback(async (text = inputText) => { | |
| const msg = text.trim(); | |
| if (!msg || isLoading) return; | |
| setInputText(''); | |
| const optimisticUserMsg = { | |
| id: `opt_${Date.now()}`, | |
| role: 'user', | |
| content: msg, | |
| timestamp: new Date().toISOString(), | |
| }; | |
| setMessages(prev => [...prev, optimisticUserMsg]); | |
| setIsLoading(true); | |
| try { | |
| const payload = { | |
| message: msg, | |
| chat_session_id: globalChatId || undefined, | |
| spec_id: activeSpecId || undefined, | |
| spec_name: activeSpecName || undefined, | |
| session_id: sessionId || undefined, | |
| execution_plan: executionPlan || [], | |
| context_variables: sessionContextVars || {}, | |
| last_step_result: lastStepResult || undefined, | |
| // Send ALL step results so the AI can diagnose any specific step | |
| all_step_results: Object.keys(allStepResults).length > 0 ? allStepResults : undefined, | |
| }; | |
| const data = await ChatService.sendMessage(payload); | |
| if (!globalChatId || globalChatId !== data.chat_session_id) { | |
| setGlobalChatId(data.chat_session_id); | |
| await fetchSessions(); // Will now fetch using activeSpecId | |
| } else { | |
| setChatSessions(prev => prev.map(s => | |
| s.id === data.chat_session_id ? { ...s, name: data.chat_session_name, updated_at: new Date().toISOString() } : s | |
| )); | |
| } | |
| const aiMsg = { | |
| id: `ai_${Date.now()}`, | |
| role: 'assistant', | |
| content: data.message, | |
| action_json: data, | |
| timestamp: new Date().toISOString(), | |
| }; | |
| setMessages(prev => { | |
| const withoutOpt = prev.filter(m => m.id !== optimisticUserMsg.id); | |
| return [...withoutOpt, optimisticUserMsg, aiMsg]; | |
| }); | |
| } catch (e) { | |
| console.error('Chat send failed', e); | |
| const errMsg = { | |
| id: `err_${Date.now()}`, | |
| role: 'assistant', | |
| content: 'β Failed to get a response. Please check the backend and try again.', | |
| timestamp: new Date().toISOString(), | |
| }; | |
| setMessages(prev => [...prev, errMsg]); | |
| } finally { | |
| setIsLoading(false); | |
| } | |
| }, [inputText, isLoading, globalChatId, activeSpecId, activeSpecName, sessionId, executionPlan, sessionContextVars, lastStepResult, allStepResults, fetchSessions]); | |
| // ββ Handle action button clicks ββ | |
| const handleAction = useCallback(async (actionJson) => { | |
| const { action, step, changes } = actionJson; | |
| if (!executeStepFromChat) { | |
| sendMessage(`Please ${action === 'run_all' ? 'run all steps' : `execute step ${step}`} β go to the Testing page to trigger execution.`); | |
| return; | |
| } | |
| if (action === 'execute_step' && step) { | |
| const stepDef = (executionPlan || []).find(s => s.step === step); | |
| if (stepDef) { | |
| const result = await executeStepFromChat(stepDef, null); | |
| setLastStepResult(result); | |
| const confirmMsg = { | |
| id: `confirm_${Date.now()}`, | |
| role: 'user', | |
| content: `βΆ Executed Step ${step}: ${stepDef.endpoint}`, | |
| timestamp: new Date().toISOString(), | |
| }; | |
| setMessages(prev => [...prev, confirmMsg]); | |
| await sendMessage(`Step ${step} executed. Analyze the result and tell me if it succeeded or what went wrong.`); | |
| } | |
| } else if (action === 'run_all') { | |
| for (const stepDef of (executionPlan || [])) { | |
| const result = await executeStepFromChat(stepDef, null); | |
| setLastStepResult(result); | |
| } | |
| await sendMessage('All steps have been executed. Give me a summary of what passed and what failed.'); | |
| } else if (action === 'retry_step') { | |
| const targetStep = step || Math.max(...Object.keys(allStepResults).map(Number)); | |
| const stepDef = (executionPlan || []).find(s => s.step === targetStep); | |
| if (stepDef) { | |
| const result = await executeStepFromChat(stepDef, null); | |
| setLastStepResult(result); | |
| await sendMessage(`Step ${targetStep} retried. Did it succeed this time?`); | |
| } | |
| } else if (action === 'modify_request') { | |
| // Show diff preview first; actual execution happens when user confirms | |
| const targetStep = step || Math.max(...Object.keys(allStepResults).map(Number)); | |
| const stepDef = (executionPlan || []).find(s => s.step === targetStep); | |
| if (stepDef && changes) { | |
| setModifyDiff({ stepDef, changes }); | |
| } | |
| } | |
| }, [executionPlan, executeStepFromChat, sendMessage, allStepResults]); | |
| // ββ Rename ββ | |
| const startRename = (session) => { | |
| setRenamingId(session.id); | |
| setRenameValue(session.name); | |
| }; | |
| const commitRename = async (id) => { | |
| if (!renameValue.trim()) return; | |
| try { | |
| await ChatService.renameSession(id, renameValue.trim()); | |
| setChatSessions(prev => prev.map(s => s.id === id ? { ...s, name: renameValue.trim() } : s)); | |
| } catch (e) { console.error(e); } | |
| setRenamingId(null); | |
| }; | |
| // ββ Delete session ββ | |
| const deleteSession = async (id) => { | |
| try { | |
| await ChatService.deleteSession(id); | |
| setChatSessions(prev => prev.filter(s => s.id !== id)); | |
| if (globalChatId === id) startNewChat(); | |
| } catch (e) { console.error(e); } | |
| }; | |
| const handleKeyDown = (e) => { | |
| if (e.key === 'Enter' && !e.shiftKey) { | |
| e.preventDefault(); | |
| sendMessage(); | |
| } | |
| }; | |
| // βββ RENDER βββββββββββββββββββββββββββββββ | |
| const handleDiffConfirm = async (modifiedStep) => { | |
| setModifyDiff(null); | |
| if (!executeStepFromChat) return; | |
| const result = await executeStepFromChat(modifiedStep, {}); | |
| setLastStepResult(result); | |
| const confirmMsg = { | |
| id: `mod_${Date.now()}`, | |
| role: 'user', | |
| content: `Modified & re-executed Step ${modifiedStep.step}: ${modifiedStep.endpoint}`, | |
| timestamp: new Date().toISOString(), | |
| }; | |
| setMessages(prev => [...prev, confirmMsg]); | |
| await sendMessage(`Step ${modifiedStep.step} was modified with your suggested changes and re-executed. Did it succeed?`); | |
| }; | |
| return ( | |
| <> | |
| {modifyDiff && ( | |
| <ModifyDiffModal | |
| original={modifyDiff.stepDef} | |
| changes={modifyDiff.changes} | |
| onConfirm={handleDiffConfirm} | |
| onCancel={() => setModifyDiff(null)} | |
| /> | |
| )} | |
| <div className="flex h-full min-h-0 overflow-hidden animate-in fade-in duration-300"> | |
| {/* ββ LEFT SIDEBAR: Sessions list (hidden in compact/embedded mode) ββ */} | |
| {!compact && ( | |
| <div className="w-64 flex-shrink-0 border-r border-[var(--border-subtle)] bg-[var(--bg-secondary)] flex flex-col"> | |
| {/* Header */} | |
| <div className="h-10 flex items-center justify-between px-3 border-b border-[var(--border-subtle)] shrink-0"> | |
| <div className="flex items-center gap-2"> | |
| <Sparkles size={14} className="text-[var(--accent-primary)]" /> | |
| <span className="text-xs font-semibold text-[var(--text-primary)] uppercase tracking-wider">Chats</span> | |
| </div> | |
| <button | |
| onClick={startNewChat} | |
| className="p-1 rounded-md text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-tertiary)] transition" | |
| title="New Chat" | |
| > | |
| <Plus size={15} /> | |
| </button> | |
| </div> | |
| {/* Session list */} | |
| <div className="flex-1 overflow-y-auto py-2"> | |
| {isFetchingSessions && ( | |
| <div className="px-3 py-2 text-xs text-[var(--text-secondary)] opacity-50">Loading...</div> | |
| )} | |
| {!isFetchingSessions && chatSessions.length === 0 && ( | |
| <div className="flex flex-col items-center justify-center h-32 text-center px-4"> | |
| <MessageSquare size={24} className="text-[var(--text-secondary)] opacity-30 mb-2" /> | |
| <p className="text-xs text-[var(--text-secondary)] opacity-50">No chats yet. Start a new conversation!</p> | |
| </div> | |
| )} | |
| {chatSessions.map(session => ( | |
| <div | |
| key={session.id} | |
| onClick={() => loadSession(session.id)} | |
| className={`group flex items-center gap-2 px-3 py-2.5 cursor-pointer transition-colors border-l-2 ${ | |
| globalChatId === session.id | |
| ? 'bg-[var(--accent-primary)]/10 border-[var(--accent-primary)] text-[var(--text-primary)]' | |
| : 'border-transparent hover:bg-[var(--bg-tertiary)] text-[var(--text-secondary)] hover:text-[var(--text-primary)]' | |
| }`} | |
| > | |
| <MessageSquare size={13} className="flex-shrink-0 opacity-60" /> | |
| <div className="flex-1 min-w-0"> | |
| {renamingId === session.id ? ( | |
| <input | |
| autoFocus | |
| value={renameValue} | |
| onChange={e => setRenameValue(e.target.value)} | |
| onBlur={() => commitRename(session.id)} | |
| onKeyDown={e => { | |
| if (e.key === 'Enter') commitRename(session.id); | |
| if (e.key === 'Escape') setRenamingId(null); | |
| e.stopPropagation(); | |
| }} | |
| onClick={e => e.stopPropagation()} | |
| className="w-full bg-[var(--bg-primary)] border border-[var(--accent-primary)] rounded px-1 py-0.5 text-xs text-[var(--text-primary)] outline-none" | |
| /> | |
| ) : ( | |
| <> | |
| <p className="text-xs font-medium truncate">{session.name}</p> | |
| <p className="text-[10px] opacity-40 truncate"> | |
| {session.message_count} msg{session.message_count !== 1 ? 's' : ''} Β· { | |
| session.updated_at ? new Date(session.updated_at).toLocaleDateString() : '' | |
| } | |
| </p> | |
| </> | |
| )} | |
| </div> | |
| {/* Actions */} | |
| <div className="flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity shrink-0"> | |
| <button | |
| onClick={e => { e.stopPropagation(); startRename(session); }} | |
| className="p-0.5 rounded hover:text-[var(--text-primary)] transition" | |
| title="Rename" | |
| > | |
| <Edit3 size={11} /> | |
| </button> | |
| <button | |
| onClick={e => { e.stopPropagation(); deleteSession(session.id); }} | |
| className="p-0.5 rounded hover:text-red-400 transition" | |
| title="Delete" | |
| > | |
| <Trash2 size={11} /> | |
| </button> | |
| </div> | |
| </div> | |
| ))} | |
| </div> | |
| </div> | |
| )} | |
| {/* ββ MAIN PANEL: Chat messages ββ */} | |
| <div className="flex-1 flex flex-col min-w-0 min-h-0"> | |
| {/* Chat header */} | |
| <div className="h-10 flex items-center justify-between px-4 border-b border-[var(--border-subtle)] bg-[var(--bg-secondary)] shrink-0"> | |
| <div className="flex items-center gap-2"> | |
| <Bot size={15} className="text-[var(--accent-primary)]" /> | |
| <span className="text-xs font-semibold text-[var(--text-primary)]"> | |
| {globalChatId | |
| ? (chatSessions.find(s => s.id === globalChatId)?.name || 'Chat') | |
| : 'New Chat'} | |
| </span> | |
| </div> | |
| <div className="flex items-center gap-2"> | |
| {/* Action button to continue in execution panel */} | |
| {!compact && globalChatId && onOpenInExecutionPanel && ( | |
| <button | |
| onClick={() => onOpenInExecutionPanel(globalChatId)} | |
| className="flex items-center gap-1.5 px-2.5 py-1 text-[10px] uppercase tracking-wider font-semibold bg-[var(--accent-primary)]/10 text-[var(--accent-primary)] hover:bg-[var(--accent-primary)]/20 border border-[var(--accent-primary)]/30 rounded-md transition-all active:scale-95" | |
| title="Continue this chat in the Execution Panel" | |
| > | |
| Continue in Execution <Play size={11} /> | |
| </button> | |
| )} | |
| {/* In compact mode show a new-chat button since sidebar is hidden */} | |
| {compact && ( | |
| <button | |
| onClick={startNewChat} | |
| className="flex items-center gap-1 px-2 py-1 rounded text-[10px] font-semibold uppercase tracking-wider text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-tertiary)] border border-[var(--border-subtle)] transition active:scale-95" | |
| title="New Chat" | |
| > | |
| <Plus size={11} /> New Chat | |
| </button> | |
| )} | |
| {activeSpecName && activeSpecName !== 'None' && ( | |
| <span className="text-[10px] text-[var(--accent-primary)] font-mono bg-[var(--accent-primary)]/10 px-2 py-0.5 rounded border border-[var(--accent-primary)]/20 truncate max-w-32"> | |
| {activeSpecName} | |
| </span> | |
| )} | |
| </div> | |
| </div> | |
| {/* Messages area */} | |
| <div className="flex-1 overflow-y-auto px-3 py-3 min-h-0"> | |
| {messages.length === 0 && ( | |
| <div className="flex flex-col items-center justify-center h-full text-center space-y-4 pb-8"> | |
| <div className={`rounded-2xl bg-gradient-to-br from-[var(--accent-primary)] to-[var(--accent-secondary)] flex items-center justify-center shadow-xl shadow-[var(--accent-primary)]/20 ${compact ? 'w-10 h-10' : 'w-16 h-16'}`}> | |
| <Bot size={compact ? 20 : 30} className="text-white" /> | |
| </div> | |
| {!compact && ( | |
| <div> | |
| <h2 className="text-lg font-semibold text-[var(--text-primary)] mb-1">API Test Assistant</h2> | |
| <p className="text-sm text-[var(--text-secondary)] max-w-sm"> | |
| Control your entire testing workflow through natural language. Execute steps, debug errors, modify requests β just ask. | |
| </p> | |
| </div> | |
| )} | |
| {compact && ( | |
| <p className="text-xs text-[var(--text-secondary)] opacity-60 max-w-[180px]"> | |
| Ask me to run steps, debug errors, or generate tests. | |
| </p> | |
| )} | |
| {/* Quick commands */} | |
| <div className={`grid gap-2 w-full ${compact ? 'grid-cols-1 max-w-full' : 'grid-cols-2 max-w-sm'}`}> | |
| {QUICK_COMMANDS.map(cmd => ( | |
| <button | |
| key={cmd.label} | |
| onClick={() => sendMessage(cmd.label)} | |
| className="flex items-center gap-2 text-xs px-3 py-2 rounded-xl border border-[var(--border-subtle)] bg-[var(--bg-secondary)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:border-[var(--accent-primary)]/40 hover:bg-[var(--accent-primary)]/5 transition-all active:scale-95 text-left" | |
| > | |
| <span className="text-[var(--accent-primary)]">{cmd.icon}</span> | |
| <span>{cmd.label}</span> | |
| </button> | |
| ))} | |
| </div> | |
| </div> | |
| )} | |
| {messages.map(msg => ( | |
| <MessageBubble | |
| key={msg.id || msg.timestamp} | |
| msg={msg} | |
| onAction={handleAction} | |
| /> | |
| ))} | |
| {isLoading && <TypingIndicator />} | |
| <div ref={messagesEndRef} /> | |
| </div> | |
| {/* Input bar */} | |
| <div className="px-3 py-2 border-t border-[var(--border-subtle)] bg-[var(--bg-primary)] shrink-0"> | |
| <div className="flex items-end gap-2 bg-[var(--bg-secondary)] border border-[var(--border-subtle)] rounded-xl focus-within:border-[var(--accent-primary)] transition-all duration-200 shadow-sm p-2 group"> | |
| <div className="ml-1 mb-0.5 text-[var(--accent-primary)] opacity-30 group-focus-within:opacity-100 transition-opacity"> | |
| <Sparkles size={14} /> | |
| </div> | |
| <textarea | |
| ref={inputRef} | |
| value={inputText} | |
| onChange={e => setInputText(e.target.value)} | |
| onKeyDown={handleKeyDown} | |
| disabled={isLoading} | |
| placeholder={ | |
| !activeSpecId | |
| ? 'Load a spec first...' | |
| : compact | |
| ? 'Ask about any step, diagnose errors, or request modifications...' | |
| : 'Ask me to run tests, debug errors, modify requests...' | |
| } | |
| rows={1} | |
| className="flex-1 bg-transparent text-sm resize-none outline-none py-1 px-1 max-h-24 min-h-[22px] text-[var(--text-primary)] placeholder-[var(--text-secondary)] disabled:opacity-40" | |
| style={{ fieldSizing: 'content' }} | |
| /> | |
| <button | |
| onClick={() => sendMessage()} | |
| disabled={!inputText.trim() || isLoading} | |
| className="p-1.5 mb-0.5 rounded-lg bg-[var(--accent-gradient)] hover:opacity-90 disabled:opacity-40 transition-all text-white shadow active:scale-95 flex-shrink-0" | |
| > | |
| {isLoading ? <RefreshCw size={14} className="animate-spin" /> : <Send size={14} />} | |
| </button> | |
| </div> | |
| {!compact && ( | |
| <p className="text-[10px] text-[var(--text-secondary)] opacity-30 mt-1 px-1"> | |
| Enter to send Β· Shift+Enter for new line | |
| </p> | |
| )} | |
| </div> | |
| </div> | |
| {/* CSS for dot bounce animation */} | |
| <style>{` | |
| @keyframes bounce { | |
| 0%, 60%, 100% { transform: translateY(0); } | |
| 30% { transform: translateY(-5px); } | |
| } | |
| `}</style> | |
| </div> | |
| </> | |
| ); | |
| } | |