Spaces:
Paused
Paused
Download frontend/apps/customer/src/components/KnowledgeBase.tsx from 3SCError404/miracle: direct link, hf CLI and curl.
- Browser
- Download file 20.9 kB
-
https://huggingface.co/spaces/3SCError404/miracle/resolve/main/frontend/apps/customer/src/components/KnowledgeBase.tsx
- Command line
-
hf download hf://spaces/3SCError404/miracle/frontend/apps/customer/src/components/KnowledgeBase.tsx
-
curl -L -o KnowledgeBase.tsx https://huggingface.co/spaces/3SCError404/miracle/resolve/main/frontend/apps/customer/src/components/KnowledgeBase.tsx
20.9 kB
| import React, { useState, useEffect, useCallback } from 'react'; | |
| import { motion, AnimatePresence } from 'framer-motion'; | |
| import { Search, ChevronLeft, ChevronRight, Sparkles, Radio, User as UserIcon, LifeBuoy, ChevronDown, Eye } from 'lucide-react'; | |
| import { api, useKnowledgeBase, useWorkspace, NexusMarkdown } from '@nexus/shared'; | |
| import styles from './KnowledgeBase.module.css'; | |
| import { Skeleton } from './Skeleton'; | |
| interface Article { | |
| id: string; | |
| title: string; | |
| content: string; | |
| category: string; | |
| author_id: string; | |
| is_published: boolean; | |
| created_at: string; | |
| updated_at: string; | |
| summary?: string; | |
| score?: number; | |
| view_count?: number; | |
| match_type?: string; | |
| snippet?: string; | |
| } | |
| interface KnowledgeBaseProps { | |
| onNewTicket?: () => void; | |
| initialArticleId?: string | null; | |
| workspaceId?: string; | |
| } | |
| export const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ onNewTicket, initialArticleId, workspaceId }) => { | |
| const { workspace } = useWorkspace(); | |
| const { articles: globalArticles, categories: globalCategories, loading: globalLoading } = useKnowledgeBase(workspaceId || workspace?.id); | |
| const [localArticles, setLocalArticles] = useState<Article[]>([]); | |
| const [loading, setLoading] = useState(false); | |
| const [isScanning, setIsScanning] = useState(false); | |
| const [error, setError] = useState<string | null>(null); | |
| const [searchInput, setSearchInput] = useState(''); | |
| const [activeQuery, setActiveQuery] = useState(''); | |
| const [selectedCategory, setSelectedCategory] = useState('All Documentation'); | |
| const [aiAnswer, setAiAnswer] = useState<string | null>(null); | |
| const [isAiSynthetic, setIsAiSynthetic] = useState(false); | |
| const [aiSuggestion, setAiSuggestion] = useState<string | null>(null); | |
| const [confidence, setConfidence] = useState<number | null>(null); | |
| const [page, setPage] = useState(1); | |
| const ITEMS_PER_PAGE = 6; | |
| const [selectedArticle, setSelectedArticle] = useState<Article | null>(null); | |
| const [sortBy, setSortBy] = useState<'newest' | 'oldest'>('newest'); | |
| const articles = (activeQuery.trim().length > 0 || selectedCategory !== 'All Documentation') ? localArticles : globalArticles; | |
| const categories = globalCategories || ['All Documentation']; | |
| const isInitialLoading = globalLoading && globalArticles.length === 0; | |
| const fetchArticles = useCallback(async (query: string = '', cat: string = 'All Documentation') => { | |
| setLoading(true); | |
| setError(null); | |
| if (query.length > 0) setIsScanning(true); | |
| try { | |
| const targetWs = workspaceId || workspace?.id; | |
| const params: any = {}; | |
| if (targetWs) params.workspace_id = targetWs; | |
| if (cat !== 'All Documentation') params.category = cat; | |
| if (query.trim().length > 0) { | |
| params.q = query; | |
| // PHASE 1: Immediate Document Retrieval (Skip Synthesis for Speed) | |
| const docsResp = await api.get('kb/search/', { | |
| params: { ...params, skip_synthesis: true } | |
| }); | |
| setLocalArticles(docsResp.data.results || []); | |
| setAiSuggestion(docsResp.data.suggestion || null); | |
| setConfidence(docsResp.data.confidence || null); | |
| // Initial state for AI | |
| setAiAnswer(null); | |
| setIsAiSynthetic(false); | |
| // PHASE 2: Background AI Synthesis (Only if query is meaningful) | |
| const isComplex = query.split(' ').length >= 2; | |
| if (isComplex) { | |
| api.get('kb/search/', { params }).then(aiResp => { | |
| if (aiResp.data.answer) { | |
| setAiAnswer(aiResp.data.answer); | |
| setIsAiSynthetic(aiResp.data.is_ai_synthetic || false); | |
| if (aiResp.data.confidence) setConfidence(aiResp.data.confidence); | |
| } | |
| }).catch(e => console.warn("AI Synthesis skipped or timed out:", e)); | |
| } | |
| } else { | |
| const resp = await api.get('kb/', { params }); | |
| const data: Article[] = resp.data || []; | |
| data.sort((a: Article, b: Article) => { | |
| const dateA = new Date(a.created_at).getTime(); | |
| const dateB = new Date(b.created_at).getTime(); | |
| return sortBy === 'newest' ? dateB - dateA : dateA - dateB; | |
| }); | |
| setLocalArticles(data); | |
| setAiAnswer(null); | |
| setConfidence(null); | |
| setIsAiSynthetic(false); | |
| setAiSuggestion(null); | |
| } | |
| setPage(1); | |
| } catch (err) { | |
| console.error('Failed to fetch articles:', err); | |
| setError('Neural connection intermittent. Please recalibrate your query.'); | |
| } finally { | |
| setLoading(false); | |
| setIsScanning(false); | |
| } | |
| }, [sortBy]); | |
| useEffect(() => { | |
| if (activeQuery.trim().length > 0 || selectedCategory !== 'All Documentation') { | |
| fetchArticles(activeQuery, selectedCategory); | |
| } | |
| }, [selectedCategory, activeQuery, fetchArticles]); | |
| useEffect(() => { | |
| if (searchInput.trim() === '') { | |
| setActiveQuery(''); | |
| setAiAnswer(null); | |
| setConfidence(null); | |
| setIsAiSynthetic(false); | |
| setAiSuggestion(null); | |
| } else if (searchInput.trim() !== activeQuery.trim()) { | |
| // Clear AI results on change to avoid stale context | |
| setAiAnswer(null); | |
| setConfidence(null); | |
| setIsAiSynthetic(false); | |
| setAiSuggestion(null); | |
| } | |
| }, [searchInput, activeQuery]); | |
| useEffect(() => { | |
| const loadInitialArticle = async () => { | |
| if (initialArticleId) { | |
| try { | |
| const resp = await api.get(`kb/${initialArticleId}/`); | |
| setSelectedArticle(resp.data); | |
| } catch (err) { | |
| console.error("Failed to fetch initial article:", err); | |
| } | |
| } | |
| }; | |
| loadInitialArticle(); | |
| }, [initialArticleId]); | |
| // Scroll to top on search/filter/pagination/drilldown | |
| useEffect(() => { | |
| const viewport = document.querySelector('.nexus-viewport'); | |
| if (viewport) viewport.scrollTop = 0; | |
| }, [activeQuery, selectedCategory, page, selectedArticle]); | |
| const handleSearchTrigger = (e?: React.FormEvent) => { | |
| if (e) e.preventDefault(); | |
| setActiveQuery(searchInput); | |
| }; | |
| const paginated = articles.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE); | |
| const totalPages = Math.ceil(articles.length / ITEMS_PER_PAGE); | |
| if (selectedArticle) { | |
| return ( | |
| <motion.div | |
| className={styles.articleDetail} | |
| initial={{ opacity: 0, y: 20 }} | |
| animate={{ opacity: 1, y: 0 }} | |
| transition={{ duration: 0.6, ease: [0.19, 1, 0.22, 1] }} | |
| > | |
| <button className={styles.backBtn} onClick={() => setSelectedArticle(null)}> | |
| <ChevronLeft size={20} /> RETURN TO SEARCH | |
| </button> | |
| <div className={styles.zenArticleContainer}> | |
| <header className={styles.articleHeader}> | |
| <div className={styles.articleMeta}> | |
| <div className={styles.metaItem}> | |
| <span className={styles.categoryBadge}>{selectedArticle.category?.toUpperCase() || 'GENERAL'}</span> | |
| </div> | |
| <div className={styles.metaItem}> | |
| <UserIcon size={16} /> <span>Nexus Intelligence Core</span> | |
| </div> | |
| <div className={styles.metaItem}> | |
| <Radio size={16} /> <span>UPDATED: {new Date(selectedArticle.created_at).toLocaleDateString()}</span> | |
| </div> | |
| </div> | |
| <h1>{selectedArticle.title}</h1> | |
| <div className={styles.accentBar} /> | |
| </header> | |
| {selectedArticle.summary && ( | |
| <div className={styles.aiSpotlight}> | |
| <div className={styles.spotlightHeader}> | |
| <div className={styles.spotlightBadge}> | |
| <Sparkles size={18} /> EXECUTIVE SUMMARY | |
| </div> | |
| </div> | |
| <p className={styles.answerText}>{selectedArticle.summary}</p> | |
| </div> | |
| )} | |
| <div className={styles.markdownContent}> | |
| <NexusMarkdown content={selectedArticle.content} /> | |
| </div> | |
| </div> | |
| <div className={styles.assistanceSection}> | |
| <h3>Still need assistance?</h3> | |
| <p>Our neural-linked specialist team is standing by to resolve any operational discrepancies.</p> | |
| <button | |
| onClick={onNewTicket} | |
| className={styles.newTicketBtn} | |
| > | |
| <LifeBuoy size={20} /> Log New Incident | |
| </button> | |
| </div> | |
| </motion.div> | |
| ); | |
| } | |
| return ( | |
| <div className={styles.container}> | |
| <header className={styles.searchHero}> | |
| <motion.h1 initial={{ opacity: 0, y: -20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.8 }}>Knowledge Base</motion.h1> | |
| <motion.p className={styles.description} initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.2, duration: 0.8 }}> | |
| Access our comprehensive neural-indexed documentation to resolve incidents with maximum efficiency. | |
| </motion.p> | |
| <form className={styles.searchControls} onSubmit={handleSearchTrigger}> | |
| <div className={styles.searchWrapper}> | |
| <Search className={styles.searchIcon} size={28} /> | |
| <input | |
| type="text" | |
| className={styles.searchInput} | |
| placeholder="Query the system documentation..." | |
| value={searchInput} | |
| onChange={(e) => setSearchInput(e.target.value)} | |
| /> | |
| <AnimatePresence> | |
| {isScanning && ( | |
| <motion.div | |
| className={styles.searchPulse} | |
| initial={{ opacity: 0, scale: 0.9 }} | |
| animate={{ opacity: 1, scale: 1 }} | |
| exit={{ opacity: 0, scale: 0.9 }} | |
| > | |
| <Radio size={18} className={styles.pulseIcon} /> | |
| <span>NEURAL SCANNING...</span> | |
| </motion.div> | |
| )} | |
| </AnimatePresence> | |
| <button | |
| type="submit" | |
| className={styles.searchBtn} | |
| disabled={loading || isScanning || !searchInput.trim()} | |
| > | |
| SEARCH | |
| </button> | |
| </div> | |
| <div className={styles.filterBar}> | |
| <div className={styles.categorySelectWrapper}> | |
| <span className={styles.categoryLabel}>DOMAIN:</span> | |
| <div className={styles.customSelect}> | |
| <select | |
| value={selectedCategory} | |
| onChange={(e) => { | |
| const cat = e.target.value; | |
| setSelectedCategory(cat); | |
| }} | |
| disabled={loading} | |
| > | |
| <option value="All Documentation">ALL DOMAINS</option> | |
| {categories.filter(c => c !== 'All Documentation').map(cat => ( | |
| <option key={cat} value={cat}> | |
| {cat.toUpperCase()} | |
| </option> | |
| ))} | |
| </select> | |
| <ChevronDown size={16} className={styles.selectIcon} /> | |
| </div> | |
| </div> | |
| <div className={styles.categorySelectWrapper}> | |
| <span className={styles.categoryLabel}>SORT:</span> | |
| <div className={styles.customSelect}> | |
| <select | |
| value={sortBy} | |
| onChange={e => setSortBy(e.target.value as 'newest' | 'oldest')} | |
| > | |
| <option value="newest">NEWEST FIRST</option> | |
| <option value="oldest">OLDEST FIRST</option> | |
| </select> | |
| <ChevronDown size={16} className={styles.selectIcon} /> | |
| </div> | |
| </div> | |
| </div> | |
| </form> | |
| </header> | |
| <div className={styles.resultsContainer}> | |
| <AnimatePresence mode="wait"> | |
| {aiAnswer && ( | |
| <motion.div | |
| className={styles.aiSpotlight} | |
| key="ai-answer" | |
| initial={{ opacity: 0, y: 30, filter: 'blur(10px)' }} | |
| animate={{ opacity: 1, y: 0, filter: 'blur(0px)' }} | |
| exit={{ opacity: 0, scale: 0.98, filter: 'blur(5px)' }} | |
| transition={{ type: 'spring', damping: 25, stiffness: 120 }} | |
| > | |
| <div className={styles.spotlightHeader}> | |
| <div className={styles.spotlightBadge}> | |
| <Sparkles size={20} /> SYNTHETIC INSIGHT | |
| </div> | |
| <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}> | |
| {isAiSynthetic && <span className={styles.syntheticFlag}>REAL-TIME ANALYSIS</span>} | |
| {confidence && ( | |
| <span className={styles.confidenceTag}> | |
| {Math.round(confidence * (confidence <= 1 ? 100 : 1))}% CONFIDENCE | |
| </span> | |
| )} | |
| </div> | |
| </div> | |
| <div className={styles.answerText}> | |
| <NexusMarkdown content={aiAnswer} /> | |
| </div> | |
| <div className={styles.spotlightFooter}>Cross-referenced across {articles.length} verified documents</div> | |
| </motion.div> | |
| )} | |
| </AnimatePresence> | |
| {(loading || isScanning || isInitialLoading) ? ( | |
| <div className={styles.articlesGrid}> | |
| {[1, 2, 3, 4, 5, 6].map(i => ( | |
| <div key={i} className={styles.articleCard} style={{ opacity: 0.4 }}> | |
| <Skeleton width="40%" height={16} marginBottom={32} /> | |
| <Skeleton width="90%" height={32} marginBottom={24} /> | |
| <Skeleton width="100%" height={20} marginBottom={16} /> | |
| <Skeleton width="70%" height={20} marginBottom={48} /> | |
| <div style={{ display: 'flex', justifyContent: 'space-between', borderTop: '1px solid rgba(255,255,255,0.05)', paddingTop: 24 }}> | |
| <Skeleton width="30%" height={12} /> | |
| <Skeleton width="20%" height={12} /> | |
| </div> | |
| </div> | |
| ))} | |
| </div> | |
| ) : error ? ( | |
| <motion.div | |
| initial={{ opacity: 0 }} | |
| animate={{ opacity: 1 }} | |
| className={styles.loadingContainer} | |
| > | |
| <div style={{ width: 120, height: 120, borderRadius: '40px', background: 'rgba(239, 68, 68, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 32, border: '2px solid rgba(239, 68, 68, 0.2)' }}> | |
| <LifeBuoy size={56} color="#ef4444" /> | |
| </div> | |
| <h3 style={{ fontSize: 32, fontWeight: 900, color: '#ef4444', marginBottom: 16 }}>Connection Interrupted</h3> | |
| <p style={{ maxWidth: 440, textAlign: 'center', color: 'var(--text-muted)', fontSize: 18 }}>{error}</p> | |
| <button | |
| onClick={() => fetchArticles(activeQuery, selectedCategory)} | |
| className={styles.searchBtn} | |
| style={{ position: 'relative', top: 32, right: 0, transform: 'none' }} | |
| > | |
| RETRY SCAN | |
| </button> | |
| </motion.div> | |
| ) : articles.length === 0 ? ( | |
| <motion.div | |
| initial={{ opacity: 0, scale: 0.9 }} | |
| animate={{ opacity: 1, scale: 1 }} | |
| className={styles.loadingContainer} | |
| > | |
| <div style={{ width: 120, height: 120, borderRadius: '40px', background: 'rgba(255,255,255,0.03)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 32, border: '2px solid rgba(255,255,255,0.05)' }}> | |
| <Search size={56} opacity={0.2} /> | |
| </div> | |
| <h3 style={{ fontSize: 32, fontWeight: 900, color: 'var(--text-main)', marginBottom: 16 }}>No Intelligence Found</h3> | |
| <p style={{ maxWidth: 440, textAlign: 'center', color: 'var(--text-muted)', fontSize: 18 }}>Our neural index yielded no direct matches for your query. Try broadening your parameters.</p> | |
| {aiSuggestion && ( | |
| <div style={{ marginTop: 40, fontSize: 14, fontWeight: 900, color: 'var(--primary)', background: 'var(--primary-glow)', padding: '16px 32px', borderRadius: 16 }}> | |
| SUGGESTED QUERY: <button onClick={() => { setSearchInput(aiSuggestion); setActiveQuery(aiSuggestion); }} style={{ color: '#fff', fontWeight: 900, background: 'none', border: 'none', cursor: 'pointer', textDecoration: 'underline', marginLeft: 8 }}>{aiSuggestion.toUpperCase()}</button> | |
| </div> | |
| )} | |
| </motion.div> | |
| ) : ( | |
| <> | |
| <motion.div | |
| className={styles.articlesGrid} | |
| initial={{ opacity: 0 }} | |
| animate={{ opacity: 1 }} | |
| > | |
| {paginated.map((article, i) => ( | |
| <motion.div | |
| key={article.id} | |
| className={styles.articleCard} | |
| initial={{ opacity: 0, y: 30 }} | |
| whileInView={{ opacity: 1, y: 0 }} | |
| viewport={{ once: true }} | |
| transition={{ delay: (i % ITEMS_PER_PAGE) * 0.1, duration: 0.6, ease: [0.19, 1, 0.22, 1] }} | |
| onClick={() => setSelectedArticle(article)} | |
| > | |
| <div className={styles.cardHeader}> | |
| <span className={styles.categoryBadge}>{article.category?.toUpperCase() || 'GENERAL'}</span> | |
| </div> | |
| <h3 className={styles.articleTitle}>{article.title}</h3> | |
| <div className={styles.articleSnippet}> | |
| {article.snippet ? ( | |
| <span>{article.snippet}</span> | |
| ) : article.summary || article.content.replace(/[#*`]/g, '').slice(0, 160) + '...'} | |
| </div> | |
| <div className={styles.cardFooter}> | |
| <div className={styles.cardMetadata}> | |
| <span className={styles.metaItem}> | |
| <Radio size={14} /> {new Date(article.created_at).toLocaleDateString()} | |
| </span> | |
| <span className={styles.metaItem}> | |
| <Eye size={14} /> {article.view_count || 0} | |
| </span> | |
| {typeof article.score === 'number' && ( | |
| <span className={styles.metaItem} title="Neural Match Confidence" style={{ color: article.score > 80 ? 'var(--primary)' : 'var(--text-muted)' }}> | |
| <Sparkles size={14} /> {Math.round(article.score)}% | |
| </span> | |
| )} | |
| </div> | |
| </div> | |
| </motion.div> | |
| ))} | |
| </motion.div> | |
| {totalPages > 1 && ( | |
| <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 48, marginTop: 100 }}> | |
| <button | |
| disabled={page === 1 || loading} | |
| onClick={() => { setPage(p => p - 1); }} | |
| className="hover-lift" | |
| style={{ | |
| background: "var(--bg-card)", | |
| border: '1px solid var(--border-subtle)', | |
| borderRadius: 20, | |
| padding: '16px 40px', | |
| opacity: (page === 1 || loading) ? 0.3 : 1, | |
| cursor: "pointer", | |
| color: "var(--text-main)", | |
| fontWeight: 900, | |
| fontSize: 14, | |
| letterSpacing: '0.1em', | |
| boxShadow: 'var(--shadow-sm)' | |
| }} | |
| > | |
| <ChevronLeft size={20} style={{ marginRight: 12 }} /> PREV | |
| </button> | |
| <div className="metadata" style={{ fontSize: 12, fontWeight: 900, opacity: 0.6 }}>INDEX: <span style={{ color: 'var(--primary)', fontSize: 20, fontWeight: 900 }}>{page}</span> / {totalPages}</div> | |
| <button | |
| disabled={page === totalPages || loading} | |
| onClick={() => { setPage(p => p + 1); }} | |
| className="hover-lift" | |
| style={{ | |
| background: "var(--bg-card)", | |
| border: '1px solid var(--border-subtle)', | |
| borderRadius: 20, | |
| padding: '16px 40px', | |
| opacity: (page === totalPages || loading) ? 0.3 : 1, | |
| cursor: "pointer", | |
| color: "var(--text-main)", | |
| fontWeight: 900, | |
| fontSize: 14, | |
| letterSpacing: '0.1em', | |
| boxShadow: 'var(--shadow-sm)' | |
| }} | |
| > | |
| NEXT <ChevronRight size={20} style={{ marginLeft: 12 }} /> | |
| </button> | |
| </div> | |
| )} | |
| </> | |
| )} | |
| </div> | |
| </div> | |
| ); | |
| }; | |