import React, { useState, useRef, useEffect } from 'react'; import ReactMarkdown from 'react-markdown'; import remarkGfm from 'remark-gfm'; import { apiUrl } from '../../lib/api'; import { Send, MessageSquareCode, Sparkles, Bot, User, RefreshCw, FileCode, AlertTriangle, ChevronDown, ChevronUp, Copy, CheckCircle2, StopCircle, } from 'lucide-react'; import { tokenizeCode, type Token } from '../../lib/tokenizer'; import { sanitizeMarkdown } from '../../lib/sanitizer'; // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- interface Message { id: string; sender: 'user' | 'assistant'; text: string; timestamp?: string; /** Sources attached to this assistant message (from the done event). */ sources?: string[]; /** 0-100 confidence score attached to this assistant message. */ confidence?: number; /** True when the LLM was unavailable and we fell back to retrieval-only. */ fallbackMode?: boolean; /** True when this is an inline error (no_repo_selected, etc.). */ isError?: boolean; } interface ChatInterfaceProps { repoName: string; /** * A question pushed in from elsewhere in the dashboard (e.g. "Ask about this * file" in the reading path). The `token` allows the same text to be sent * again. Consumed once, then reported back via `onPendingPromptConsumed`. */ pendingPrompt?: { text: string; token: number } | null; onPendingPromptConsumed?: () => void; } const createChatSessionId = (): string => typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function' ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(36).slice(2)}`; // --------------------------------------------------------------------------- // Custom Sub-components for Markdown & Layout // --------------------------------------------------------------------------- /** Custom helper to inject a blinking cursor element where %%CURSOR%% is found */ const renderChildrenWithCursor = (children: React.ReactNode): React.ReactNode => { if (typeof children === 'string' && children.includes('%%CURSOR%%')) { const parts = children.split('%%CURSOR%%'); return ( <> {parts[0]} {parts[1]} ); } if (Array.isArray(children)) { return React.Children.map(children, (child) => renderChildrenWithCursor(child)); } return children; }; /** Safe Token Syntax Renderer - Converts AST tokens into native React elements */ const SafeSyntaxHighlighter: React.FC<{ codeText: string }> = ({ codeText }) => { const cleanText = codeText.includes('%%CURSOR%%') ? codeText.split('%%CURSOR%%')[0] : codeText; const hasCursor = codeText.includes('%%CURSOR%%'); const tokens = tokenizeCode(cleanText); const getTokenClassName = (type: Token['type']): string => { switch (type) { case 'comment': return 'text-text-subtle italic'; case 'keyword': return 'text-indigo-400 font-semibold'; case 'string': return 'text-emerald-400'; case 'number': return 'text-amber-400'; case 'operator': return 'text-primary/80'; default: return ''; } }; return ( <> {tokens.map((t, idx) => ( {t.text} ))} {hasCursor && } ); }; /** Premium CodeBlock with safe syntax highlighting, copy button, and wrap options */ const CodeBlock: React.FC<{ inline?: boolean; className?: string; children: React.ReactNode }> = ({ inline, className, children, }) => { const [copied, setCopied] = useState(false); const [wrapLines, setWrapLines] = useState(false); const match = /language-(\w+)/.exec(className || ''); const lang = match ? match[1] : ''; const codeText = String(children).replace(/\n$/, ''); if (inline) { return ( {children} ); } const handleCopy = () => { navigator.clipboard.writeText(codeText.includes('%%CURSOR%%') ? codeText.split('%%CURSOR%%')[0] : codeText); setCopied(true); setTimeout(() => setCopied(false), 2000); }; return (
{lang || 'code'}
        
          
        
      
); }; /** Markdown Component mapping GFM styles to Tailwind classes */ const Markdown: React.FC<{ content: string; isStreaming: boolean }> = ({ content, isStreaming }) => { const sanitized = sanitizeMarkdown(content); const textWithCursor = isStreaming ? sanitized + ' %%CURSOR%%' : sanitized; // Debug logging when DEBUG_RENDERING is set if (typeof window !== 'undefined' && (window as any).DEBUG_RENDERING) { console.log('[DEBUG_RENDERING]', { raw: content, sanitized, textWithCursor }); } return ( { const match = /language-(\w+)/.exec(className || ''); const isInline = !match; return ( {children} ); }, table: ({ children }) => (
{children}
), thead: ({ children }) => {children}, tbody: ({ children }) => {children}, tr: ({ children }) => {children}, th: ({ children }) => {children}, td: ({ children }) => {children}, ul: ({ children }) =>
    {children}
, ol: ({ children }) =>
    {children}
, li: ({ children }) =>
  • {renderChildrenWithCursor(children)}
  • , p: ({ children }) =>

    {renderChildrenWithCursor(children)}

    , h1: ({ children }) =>

    {children}

    , h2: ({ children }) =>

    {children}

    , h3: ({ children }) =>

    {children}

    , blockquote: ({ children }) =>
    {children}
    , a: ({ href, children }) => {children}, }} > {textWithCursor}
    ); }; /** Streaming Typing indicator */ const TypingIndicator: React.FC = () => (
    ); /** Citations, Grounded Evidence, and Structural Sources container */ const SourcesPanel: React.FC<{ sources: string[]; confidence: number; fallbackMode: boolean; activeRepo?: string }> = ({ sources, confidence, fallbackMode, activeRepo, }) => { const [open, setOpen] = useState(true); const displayConfidence = Math.min(Math.max(Math.round(confidence), 0), 100); const handleNavigateToGraph = (filePath: string) => { if (typeof window !== 'undefined') { const [owner, repo] = (activeRepo || '').split('/'); window.dispatchEvent( new CustomEvent('aria-open-graph', { detail: { owner: owner || undefined, repo: repo || undefined, file: filePath, path: filePath, source: 'chat', }, }) ); // If we are on standalone /chat, offer direct link if (window.location.pathname === '/chat' && activeRepo) { if (owner && repo) { window.location.href = `/analysis?owner=${owner}&repo=${repo}&tab=graph&file=${encodeURIComponent(filePath)}`; } } } }; return (
    {open && (
    {sources.map((src, i) => { const fileName = src.split('/').pop() || src; const dir = src.includes('/') ? src.substring(0, src.lastIndexOf('/')) : ''; return (

    {fileName}

    {dir && (

    {dir}/

    )}
    ); })}
    )}
    ); }; // --------------------------------------------------------------------------- // Main Component // --------------------------------------------------------------------------- export const ChatInterface: React.FC = ({ repoName, pendingPrompt, onPendingPromptConsumed, }) => { const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); const [isStreaming, setIsStreaming] = useState(false); const [activeRepo, setActiveRepo] = useState(() => { if (repoName) return repoName; if (typeof window !== 'undefined') { const urlParams = new URLSearchParams(window.location.search); const owner = urlParams.get('owner'); const repo = urlParams.get('repo'); if (owner && repo) return `${owner}/${repo}`; if (urlParams.get('repo')) return urlParams.get('repo')!; const stored = localStorage.getItem('activeRepo'); if (stored) return stored; } return ''; }); const [copiedAnswerId, setCopiedAnswerId] = useState(null); const [noRepoError, setNoRepoError] = useState(false); const bottomRef = useRef(null); const abortControllerRef = useRef(null); const sessionIdRef = useRef(createChatSessionId()); const suggestedQuestions = [ 'What does this codebase do, and what are its main entry points?', 'Show me any circular dependencies in this project.', 'Are there any dead/unused functions, and where are they located?', 'What is the architectural overview of this repository?', ]; // Sync active repo changes from prop useEffect(() => { if (repoName) { setActiveRepo(repoName); setNoRepoError(false); } }, [repoName]); // Fallback: If still no activeRepo on mount, look up recent analyzed repos from the backend useEffect(() => { if (!activeRepo) { fetch(apiUrl('/api/v1/repos/recent')) .then((res) => res.json()) .then((data) => { if (Array.isArray(data) && data.length > 0 && data[0].name) { const foundRepo = data[0].name; setActiveRepo(foundRepo); if (typeof window !== 'undefined') { localStorage.setItem('activeRepo', foundRepo); window.dispatchEvent(new CustomEvent('active-repo-changed', { detail: foundRepo })); } } else { setNoRepoError(true); } }) .catch(() => { setNoRepoError(true); }); } }, [activeRepo]); // Window events useEffect(() => { const handleRepoChanged = (e: Event) => { const customEvent = e as CustomEvent; if (customEvent.detail) { setActiveRepo(customEvent.detail); setNoRepoError(false); } }; const handleRepoCleared = () => { setActiveRepo(''); setNoRepoError(true); }; window.addEventListener('active-repo-changed', handleRepoChanged); window.addEventListener('active-repo-cleared', handleRepoCleared); return () => { window.removeEventListener('active-repo-changed', handleRepoChanged); window.removeEventListener('active-repo-cleared', handleRepoCleared); }; }, []); // Reset conversation on active repo change useEffect(() => { if (!activeRepo) { setMessages([]); return; } setNoRepoError(false); setMessages([]); }, [activeRepo]); // Scroll bottom useEffect(() => { bottomRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages]); const handleCopyAnswer = (text: string, id: string) => { navigator.clipboard.writeText(text); setCopiedAnswerId(id); setTimeout(() => setCopiedAnswerId(null), 2000); }; const triggerStreamResponse = async (userPrompt: string, updatedHistory: Message[]) => { setIsStreaming(true); const assistantId = Math.random().toString(); const timestamp = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); setMessages((prev) => [ ...prev, { id: assistantId, sender: 'assistant', text: '', timestamp }, ]); const controller = new AbortController(); abortControllerRef.current = controller; let accumulatedText = ''; try { const response = await fetch(apiUrl('/api/v1/chat'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ repo: activeRepo, message: userPrompt, session_id: sessionIdRef.current, history: updatedHistory.map((m) => ({ role: m.sender === 'user' ? 'user' : 'model', parts: [m.text], })), }), signal: controller.signal, }); if (!response.ok) { let detail = `Backend error ${response.status}`; try { const errBody = await response.json(); if (errBody?.detail) { if (Array.isArray(errBody.detail)) { detail = errBody.detail.map((d: any) => d.msg).join('; '); } else { detail = String(errBody.detail); } } } catch { /* ignore */ } setMessages((prev) => prev.map((msg) => msg.id === assistantId ? { ...msg, text: detail, isError: true } : msg, ), ); return; } if (!response.body) throw new Error('ReadableStream not available'); const reader = response.body.getReader(); const decoder = new TextDecoder(); let finished = false; while (!finished) { const { value, done } = await reader.read(); finished = done; if (!value) continue; const raw = decoder.decode(value); const lines = raw.split('\n'); for (const line of lines) { if (!line.startsWith('data: ')) continue; try { const data = JSON.parse(line.slice(6)); if (data.error) { setMessages((prev) => prev.map((msg) => msg.id === assistantId ? { ...msg, text: data.message ?? data.error, isError: true } : msg, ), ); continue; } if (data.text) { accumulatedText += data.text; setMessages((prev) => prev.map((msg) => msg.id === assistantId ? { ...msg, text: msg.text + data.text } : msg, ), ); } if (data.status === 'done') { setMessages((prev) => prev.map((msg) => { if (msg.id !== assistantId) return msg; const finalTxt = msg.text.trim() || accumulatedText.trim() || '⚠️ The AI provider returned an empty response. Repository intelligence fallback applied.'; return { ...msg, text: finalTxt, sources: data.sources ?? [], confidence: data.confidence ?? 0, fallbackMode: data.fallback_mode ?? false, }; }), ); } } catch { /* ignore JSON parse errors */ } } } // Final check: if stream finished cleanly but accumulatedText is empty if (!accumulatedText.trim()) { setMessages((prev) => prev.map((msg) => msg.id === assistantId && !msg.text.trim() ? { ...msg, text: '⚠️ The AI provider returned an empty response. Repository intelligence fallback applied.', isError: true } : msg, ), ); } } catch (err: any) { if (err.name === 'AbortError') { setMessages((prev) => prev.map((msg) => msg.id === assistantId ? { ...msg, text: msg.text + '\n\n*Stream generation stopped.*' } : msg, ), ); } else { console.error('Chat stream error:', err); setMessages((prev) => prev.map((msg) => msg.id === assistantId ? { ...msg, text: 'Could not reach the agent backend. Please verify that the backend server is running and reachable.', isError: true, } : msg, ), ); } } finally { setIsStreaming(false); abortControllerRef.current = null; } }; const handleSend = async (textToSend: string) => { if (!textToSend.trim() || isStreaming) return; const timestamp = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); const userMessage: Message = { id: Math.random().toString(), sender: 'user', text: textToSend, timestamp, }; const nextHistory = [...messages, userMessage]; setMessages(nextHistory); setInput(''); await triggerStreamResponse(textToSend, nextHistory); }; /** * Dispatches a question handed in from another panel. Kept as a thin trigger * around the existing send path so request/streaming behaviour is unchanged. */ const consumedPromptTokenRef = useRef(null); useEffect(() => { if (!pendingPrompt?.text) return; if (consumedPromptTokenRef.current === pendingPrompt.token) return; if (isStreaming) return; consumedPromptTokenRef.current = pendingPrompt.token; onPendingPromptConsumed?.(); void handleSend(pendingPrompt.text); // handleSend is recreated each render; depending on it would re-fire the // effect, so the token guard above is what makes this run exactly once. // eslint-disable-next-line react-hooks/exhaustive-deps }, [pendingPrompt?.text, pendingPrompt?.token, isStreaming]); const handleStop = () => { if (abortControllerRef.current) { abortControllerRef.current.abort(); } }; const handleRegenerate = async () => { const userMsgs = messages.filter((m) => m.sender === 'user'); if (userMsgs.length === 0) return; const lastUserMsg = userMsgs[userMsgs.length - 1]; let nextMsgs = [...messages]; if (nextMsgs[nextMsgs.length - 1].sender === 'assistant') { nextMsgs.pop(); } setMessages(nextMsgs); await triggerStreamResponse(lastUserMsg.text, nextMsgs); }; return (
    {/* Header */}
    Codebase Companion
    {activeRepo || 'no repo'}
    {/* No-repo state */} {noRepoError && (

    No active repository found

    Please analyze a repository on the homepage to start asking questions about its codebase.

    )} {/* Empty State Welcome Dashboard */} {!noRepoError && messages.length === 0 && (

    Chat with {activeRepo}

    Ask about function callers, class inheritances, endpoints, or planned code refactors.

    Suggested Prompts

    {suggestedQuestions.map((q) => ( ))}
    )} {/* Message thread */} {!noRepoError && messages.length > 0 && (
    {messages.map((msg, idx) => (
    {/* Avatar */}
    {msg.sender === 'user' ? ( ) : ( )}
    {/* Bubble + Citations */}
    {msg.sender === 'user' ? (

    {msg.text}

    ) : msg.text === '' ? ( ) : (
    )}
    {/* Message Timestamp */} {msg.timestamp && ( {msg.timestamp} )} {/* Toolbar under assistant bubble */} {msg.sender === 'assistant' && msg.text !== '' && (
    {idx === messages.length - 1 && !isStreaming && ( )}
    )} {/* Collapsible citations & grounded evidence panel */} {msg.sender === 'assistant' && msg.sources && msg.sources.length > 0 && ( )}
    ))} {/* Inline Stop button while streaming */} {isStreaming && (
    )}
    )} {/* Input bar */} {!noRepoError && (
    { e.preventDefault(); handleSend(input); }} className="flex gap-2 items-end" >