'use client'; import { useState, useMemo } from 'react'; import { cn } from '@/lib/utils'; import { ChevronDown, ChevronUp, Copy, Check, Brain, Search, Settings, FileText, Globe, Clock, Database, Code2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; <<<<<<< HEAD import { Message, ThinkingMessageMetadata } from '@/hooks/use-chat'; ======= import { Message } from '@/hooks/use-chat'; >>>>>>> 593efd42e091a845dea82ee6646e027bce1e18c5 import type { DeepResearchState } from '@/hooks/use-deep-research'; import type { ScrapedContent } from '@/services/webSearch'; export interface DebugData { model: string; timestamp: number; latency?: number; systemPrompt: string; userQuery: string; contextUsed: Message[]; webResearch?: { queries: string[]; enrichedQueries?: { literal: string[]; semantic: string[]; related: string[]; expanded: string[]; contextual: string[]; }; sources: ScrapedContent[]; <<<<<<< HEAD sitesResearched?: Array<{ url: string; title: string; status: string; source: string; duration?: number; contentLength: number; scrapedAt: number; }>; ======= >>>>>>> 593efd42e091a845dea82ee6646e027bce1e18c5 logs: Array<{ stage: string; timestamp: number; input: string; rawOutput?: string; parsedOutput?: any; error?: string; }>; plan?: string[]; knowledgeBase?: Array<{ sourceUrl: string; title: string; content: string; }>; <<<<<<< HEAD activeQueries?: Array<{ query: string; source: string; round?: number; startedAt: number; }>; activeUrls?: Array<{ url: string; title?: string; status: string; source?: string; startedAt: number; duration?: number; }>; }; deepResearchState?: DeepResearchState; thinkingSteps?: ThinkingMessageMetadata[]; reasoning?: { steps?: string[]; intermediateResults?: any[]; }; finalResponse: string; rawResponse: string; tokenUsage?: { input: number; output: number; total: number; ======= }; deepResearchState?: DeepResearchState; finalResponse: string; rawResponse?: string; tokenUsage?: { input: number; output: number; >>>>>>> 593efd42e091a845dea82ee6646e027bce1e18c5 }; } interface DebugConsoleProps { data: DebugData; } export function DebugConsole({ data }: DebugConsoleProps) { const [expandedSections, setExpandedSections] = useState>(new Set()); const [copied, setCopied] = useState(false); const toggleSection = (section: string) => { setExpandedSections(prev => { const next = new Set(prev); if (next.has(section)) { next.delete(section); } else { next.add(section); } return next; }); }; const copyFullDump = async () => { try { await navigator.clipboard.writeText(JSON.stringify(data, null, 2)); setCopied(true); setTimeout(() => setCopied(false), 2000); } catch (error) { console.error('Failed to copy:', error); } }; const formatTimestamp = (ts: number) => { return new Date(ts).toLocaleString('pt-BR', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', }); }; const formatDuration = (ms?: number) => { if (!ms) return 'N/A'; if (ms < 1000) return `${ms}ms`; return `${(ms / 1000).toFixed(2)}s`; }; const isExpanded = (section: string) => expandedSections.has(section); return (
{/* Header Bar */}
Debug Console
{data.model || 'N/A'} {data.latency !== undefined && ( {formatDuration(data.latency)} )} {data.tokenUsage && ( Tokens: {data.tokenUsage.input}/{data.tokenUsage.output} )}
{/* Sections */}
{/* Section A: Contexto & Memória */}
} isExpanded={isExpanded('context')} onToggle={() => toggleSection('context')} >

System Prompt

                  {data.systemPrompt}
                

Injetado em: {formatTimestamp(data.timestamp)}

Histórico da Sessão ({data.contextUsed.length} mensagens)

Expandir JSON
                    {JSON.stringify(data.contextUsed, null, 2)}
                  
{/* Section B: Deep Research */} {data.webResearch && (
} isExpanded={isExpanded('research')} onToggle={() => toggleSection('research')} >
{/* Pipeline Status */}

Status do Pipeline

{/* Decomposition */} {data.webResearch.plan && data.webResearch.plan.length > 0 && (
Decomposition
{data.webResearch.plan.map((query, idx) => (
{idx + 1}. {query}
))}
)} {/* Query Expansion */} {data.webResearch.enrichedQueries && (
Query Expansion
{data.webResearch.queries.map((original, idx) => { const eq = data.webResearch?.enrichedQueries; const allEnriched = eq ? [ ...(eq.literal || []), ...(eq.semantic || []), ...(eq.related || []), ...(eq.expanded || []), ...(eq.contextual || []), ] : []; return (
Original: {original}
{allEnriched.length > 0 && (
Enriquecidas ({allEnriched.length}):
{allEnriched.slice(0, 5).map((q, qIdx) => (
• {q}
))} {allEnriched.length > 5 && (
... e mais {allEnriched.length - 5}
)}
)}
); })}
)} {/* Web Crawling */} {data.webResearch.sources && data.webResearch.sources.length > 0 && (
Web Crawling ({data.webResearch.sources.length} fontes)
{data.webResearch.sources.map((source, idx) => (
{source.content && source.content.length > 0 ? ( ✓ ) : ( ✗ )}
{source.title || source.url} {source.cached && ( Cached )}
{source.url} {source.content && (

{source.content.substring(0, 150)}...

)}
))}
)} {/* Knowledge Base */} {data.webResearch.knowledgeBase && data.webResearch.knowledgeBase.length > 0 && (
Knowledge Base
{data.webResearch.knowledgeBase.length} chunks extraídos
)}
{/* Research Logs */} {data.webResearch.logs && data.webResearch.logs.length > 0 && (

Logs Internos ({data.webResearch.logs.length} entradas)

{data.webResearch.logs.map((log, idx) => (
{log.stage} {formatTimestamp(log.timestamp)}
Input: {log.input}
{log.rawOutput && (
Output:{' '} {log.rawOutput.substring(0, 200)}...
)} {log.error && (
Erro: {log.error}
)}
))}
)}
)} {/* Section C: Dados Processados */} {data.deepResearchState && (
} isExpanded={isExpanded('processed')} onToggle={() => toggleSection('processed')} >

Estado do Deep Research

Step: {data.deepResearchState.step}
{data.deepResearchState.validationReport && (
Validation Report:
                          {data.deepResearchState.validationReport}
                        
)} {data.deepResearchState.error && (
Erro: {data.deepResearchState.error}
)}
)} {/* Section D: Resposta Raw */}
} isExpanded={isExpanded('response')} onToggle={() => toggleSection('response')} >
                {data.rawResponse || data.finalResponse}
              
); } interface SectionProps { id: string; title: string; icon: React.ReactNode; isExpanded: boolean; onToggle: () => void; children: React.ReactNode; } function Section({ id, title, icon, isExpanded, onToggle, children }: SectionProps) { return (
{isExpanded && (
{children}
)}
); }