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: ,
run_all: ,
retry_step: ,
skip_step: ,
modify_request: ,
explain: ,
generate_tests: ,
reply: ,
};
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: },
{ label: 'Why did this fail?', icon: },
{ label: 'Retry last step', icon: },
{ label: 'Generate test cases', icon: },
];
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 (
{!isUser && (
)}
{/* Main bubble */}
{!isUser && action !== 'reply' && (
{ACTION_ICONS[action]}
{ACTION_LABELS[action] || action}
{step && — Step {step}}
)}
{msg.content}
{/* Explanation block */}
{explanation && (
)}
{/* Changes block for modify_request */}
{changes && Object.keys(changes).length > 0 && (
Proposed Changes
{Object.entries(changes).map(([k, v]) => (
{k}:
"{String(v)}"
))}
)}
{/* Test assertions block */}
{assertions && assertions.length > 0 && (
Generated Assertions
{assertions.map((a, i) => (
-
{String(a)}
))}
)}
{/* Action button */}
{isActionable && (
)}
{formatTime(msg.timestamp)}
{isUser && (
U
)}
);
}
// ─────────────────────────────────────────────
// TypingIndicator
// ─────────────────────────────────────────────
function TypingIndicator() {
return (
{[0, 150, 300].map((delay, i) => (
))}
);
}
// ─────────────────────────────────────────────
// 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 && (
setModifyDiff(null)}
/>
)}
{/* ── LEFT SIDEBAR: Sessions list (hidden in compact/embedded mode) ── */}
{!compact && (
{/* Header */}
{/* Session list */}
{isFetchingSessions && (
Loading...
)}
{!isFetchingSessions && chatSessions.length === 0 && (
No chats yet. Start a new conversation!
)}
{chatSessions.map(session => (
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)]'
}`}
>
{renamingId === session.id ? (
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"
/>
) : (
<>
{session.name}
{session.message_count} msg{session.message_count !== 1 ? 's' : ''} · {
session.updated_at ? new Date(session.updated_at).toLocaleDateString() : ''
}
>
)}
{/* Actions */}
))}
)}
{/* ── MAIN PANEL: Chat messages ── */}
{/* Chat header */}
{globalChatId
? (chatSessions.find(s => s.id === globalChatId)?.name || 'Chat')
: 'New Chat'}
{/* Action button to continue in execution panel */}
{!compact && globalChatId && onOpenInExecutionPanel && (
)}
{/* In compact mode show a new-chat button since sidebar is hidden */}
{compact && (
)}
{activeSpecName && activeSpecName !== 'None' && (
{activeSpecName}
)}
{/* Messages area */}
{messages.length === 0 && (
{!compact && (
API Test Assistant
Control your entire testing workflow through natural language. Execute steps, debug errors, modify requests — just ask.
)}
{compact && (
Ask me to run steps, debug errors, or generate tests.
)}
{/* Quick commands */}
{QUICK_COMMANDS.map(cmd => (
))}
)}
{messages.map(msg => (
))}
{isLoading &&
}
{/* Input bar */}
{!compact && (
Enter to send · Shift+Enter for new line
)}
{/* CSS for dot bounce animation */}
>
);
}