Spaces:
Paused

miracle / frontend /apps /internal /src /components /KnowledgeBase.tsx
dushyantsingh0
fix: allow superadmin to edit and delete articles in KB UI
a4c08a4
Raw History Blame Contribute Delete
52.1 kB
import React, { useState, useEffect, useCallback, useRef } from 'react'; import { Search, Plus, X, Trash2, Edit3, ShieldCheck, Zap, Info, Radio, ChevronLeft, ChevronRight, Eye, Send, Lock, Globe, Sparkles, UploadCloud, History, RotateCcw, Clock, ChevronDown } from 'lucide-react'; import { motion, AnimatePresence } from 'framer-motion'; import { api, useAuth, computeDiff, useNotification, NexusMarkdown } from '@nexus/shared'; import styles from './KnowledgeBase.module.css'; // Pre-defined role groups for UI visibility const SHRED_ROLES = ['superadmin', '3sc_admin', '3sc_lead', '3sc_agent']; const EDIT_ROLES = ['superadmin', '3sc_admin', '3sc_lead', '3sc_agent']; interface KBArticle { id: string; title: string; content: string; category: string; is_published: boolean; updated_at: string; author_id?: string; view_count: number; citation_count: number; score?: number; snippet?: string; match_type?: string; created_at?: string; summary?: string; version?: number; } interface KnowledgeBaseProps { workspaceId?: string; } interface KBInsight { id: string; insight_type: 'DEPTH_IMPROVEMENT' | 'NEW_TOPIC'; suggested_title: string; suggested_content: string; reasoning: string; confidence_score: number; category: string; evidence_count: number; } interface KBArticleVersion { id: string; version_number: number; title: string; content: string; category: string; created_at: string; author_id: string; author_name: string; } // Mermaid logic moved to centralized NexusMermaid.tsx component in @nexus/shared export const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ workspaceId }) => { const { user } = useAuth(); const { alert, confirm } = useNotification(); const canEdit = user?.role && EDIT_ROLES.includes(user.role); const canShred = user?.role && SHRED_ROLES.includes(user.role); const [articles, setArticles] = useState<KBArticle[]>([]); const [categories, setCategories] = useState<string[]>(['All']); const [loading, setLoading] = useState(true); const [error, setError] = useState<string | null>(null); // Search State const [searchInput, setSearchInput] = useState(''); const [activeQuery, setActiveQuery] = useState(''); const [selectedCategory, setSelectedCategory] = useState('All'); // Pagination State const [currentPage, setCurrentPage] = useState(1); const itemsPerPage = 6; // Dossier State const [drawerOpen, setDrawerOpen] = useState(false); const [selectedArticle, setSelectedArticle] = useState<KBArticle | null>(null); const [selectedInsight, setSelectedInsight] = useState<KBInsight | null>(null); const [isEditing, setIsEditing] = useState(false); // Edit Buffer const [editTitle, setEditTitle] = useState(''); const [editContent, setEditContent] = useState(''); const [editCategory, setEditCategory] = useState(''); const [editPublished, setEditPublished] = useState(true); // Version History State const [showHistory, setShowHistory] = useState(false); const [versions, setVersions] = useState<KBArticleVersion[]>([]); const [versionsLoading, setVersionsLoading] = useState(false); const [comparingVersion, setComparingVersion] = useState<KBArticleVersion | null>(null); // File Upload State const [isDropdownOpen, setIsDropdownOpen] = useState(false); const [isParsingFile, setIsParsingFile] = useState(false); const fileInputRef = useRef<HTMLInputElement>(null); // AI Search Enhanced State const [aiSuggestion, setAiSuggestion] = useState<string | null>(null); const [aiAnswer, setAiAnswer] = useState<string | null>(null); const [isAiSynthetic, setIsAiSynthetic] = useState(false); // AI Growth Center State const [activeTab, setActiveTab] = useState<'library' | 'growth'>('library'); const [insights, setInsights] = useState<KBInsight[]>([]); const [insightsLoading, setInsightsLoading] = useState(false); const [insightsPage, setInsightsPage] = useState(0); const [hasMoreInsights, setHasMoreInsights] = useState(true); const loadingRef = useRef<HTMLDivElement>(null); // 1. Fetch Categories const fetchCategories = useCallback(async () => { try { const resp = await api.get('kb/categories/', { params: { workspace_id: workspaceId } }); setCategories(['All', ...resp.data]); } catch (err: unknown) { console.error('Failed to fetch categories:', err); } }, [workspaceId]); // 2. Fetch Articles const fetchArticles = useCallback(async (query: string = '', cat: string = 'All') => { setLoading(true); setError(null); try { const params: Record<string, string | undefined> = { workspace_id: workspaceId }; if (cat !== 'All') params.category = cat; if (query.trim().length > 0) { params.q = query; const resp = await api.get('kb/search/', { params }); setArticles(resp.data.results || []); setAiSuggestion(resp.data.suggestion || null); setAiAnswer(resp.data.answer || null); setIsAiSynthetic(resp.data.is_ai_synthetic || false); } else { const resp = await api.get('kb/', { params }); setArticles(resp.data || []); setAiSuggestion(null); setAiAnswer(null); setIsAiSynthetic(false); } setCurrentPage(1); // Reset to first page on search/filter } catch (err: unknown) { const errorObj = err as { code?: string; message?: string; response?: { data?: { detail?: string } } }; console.error('Failed to fetch articles:', err); const isTimeout = errorObj.code === 'ECONNABORTED' || errorObj.message?.includes('timeout'); setError(isTimeout ? 'Neural core processing exceeded 120s deadline. High-load detected. Retrying from cache recommended.' : 'Search intelligence interrupted. Regional grid may be unstable.'); } finally { setLoading(false); } }, [workspaceId]); // 3. Fetch Insights (Paginated for Infinite Scroll) const fetchInsights = useCallback(async (reset: boolean = false) => { if (insightsLoading || (!hasMoreInsights && !reset)) return; setInsightsLoading(true); const nextPage = reset ? 0 : insightsPage; try { const resp = await api.get('kb/insights/', { params: { workspace_id: workspaceId, skip: nextPage * 10, limit: 10 } }); const newInsights = resp.data || []; if (reset) { setInsights(newInsights); } else { setInsights(prev => [...prev, ...newInsights]); } setHasMoreInsights(newInsights.length === 10); setInsightsPage(nextPage + 1); } catch (err: unknown) { console.error('Failed to fetch insights:', err); } finally { setInsightsLoading(false); } }, [workspaceId, insightsPage, insightsLoading, hasMoreInsights]); // Infinite Scroll Observer useEffect(() => { if (activeTab !== 'growth' || !hasMoreInsights) return; const observer = new IntersectionObserver((entries) => { if (entries[0].isIntersecting && !insightsLoading) { fetchInsights(); } }, { threshold: 1.0 }); if (loadingRef.current) { observer.observe(loadingRef.current); } return () => observer.disconnect(); }, [activeTab, hasMoreInsights, insightsLoading, fetchInsights]); useEffect(() => { fetchCategories(); fetchArticles('', 'All'); }, [fetchCategories, fetchArticles]); // Reactive Search Reset useEffect(() => { if (searchInput.trim() === '') { setActiveQuery(''); setAiAnswer(null); setAiSuggestion(null); setIsAiSynthetic(false); // Trigger reset fetch to show all articles again fetchArticles('', selectedCategory); } else if (searchInput.trim() !== activeQuery.trim()) { // Clear AI results on change to avoid stale context setAiAnswer(null); setAiSuggestion(null); setIsAiSynthetic(false); } }, [searchInput, activeQuery, selectedCategory, fetchArticles]); useEffect(() => { if (activeTab === 'growth') { fetchInsights(); } }, [activeTab, fetchInsights]); // Scroll to top on search/filter/pagination useEffect(() => { const viewport = document.querySelector('.admin-content'); if (viewport) viewport.scrollTop = 0; }, [activeQuery, selectedCategory, currentPage]); // Scroll drawer to top on article change useEffect(() => { if (drawerOpen) { const viewArea = document.querySelector(`.${styles.viewScrollArea}`); const editArea = document.querySelector(`.${styles.editScrollArea}`); if (viewArea) viewArea.scrollTop = 0; if (editArea) editArea.scrollTop = 0; } }, [selectedArticle, selectedInsight, drawerOpen]); const handleSearchTrigger = (e?: React.FormEvent) => { if (e) e.preventDefault(); setActiveQuery(searchInput); fetchArticles(searchInput, selectedCategory); }; // Article Actions const openDossier = (article: KBArticle) => { setSelectedArticle(article); setSelectedInsight(null); setEditTitle(article.title); setEditContent(article.content); setEditCategory(article.category); setEditPublished(article.is_published); setIsEditing(false); setDrawerOpen(true); }; const openInsightDossier = (insight: KBInsight) => { setSelectedInsight(insight); setSelectedArticle(null); setEditTitle(insight.suggested_title); setEditContent(insight.suggested_content); setEditCategory(insight.category || 'General'); setEditPublished(false); setIsEditing(false); setDrawerOpen(true); }; const handleCreateNew = () => { setSelectedArticle(null); setSelectedInsight(null); setShowHistory(false); setEditTitle('NEW STRATEGIC ASSET'); setEditContent('# Technical Directive\n\nStart your documentation here...\n\n```mermaid\ngraph TD;\n A-->B;\n```'); setEditCategory('General'); setEditPublished(false); setIsEditing(true); setDrawerOpen(true); setIsDropdownOpen(false); }; const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => { const files = event.target.files; if (!files || files.length === 0) return; setIsDropdownOpen(false); // Check for any file over 1MB const tooLarge = Array.from(files).find(f => f.size > 1024 * 1024); if (tooLarge) { alert(`File "${tooLarge.name}" is too large (Limit: 1MB for background ingestion).`, { type: 'error', title: 'Upload Restriction' }); return; } setIsParsingFile(true); const formData = new FormData(); Array.from(files).forEach(f => formData.append('files', f)); try { // Transitioning to background ingestion job for stability (GAP-4 / Hardening) const resp = await api.post('kb/ingest/', formData, { params: { workspace_id: workspaceId } }); if (resp.data.created_drafts && resp.data.created_drafts.length > 0) { // Only inject into grid if it matches current filter or 'All' const relevantDrafts = resp.data.created_drafts.filter((d: KBArticle) => selectedCategory === 'All' || d.category === selectedCategory ); if (relevantDrafts.length > 0) { setArticles(prev => [...relevantDrafts, ...prev]); } } // No alert needed if we have immediate drafts, the UI handles it if (!resp.data.created_drafts || resp.data.created_drafts.length === 0) { alert(resp.data.message || `${files.length} documents queued for neural ingestion.`); } // Auto-refresh library after a small delay to show processing articles setTimeout(() => fetchArticles(activeQuery, selectedCategory), 2000); } catch (err: unknown) { const errorObj = err as { response?: { data?: { detail?: string } } }; console.error('Ingestion failed:', err); alert(errorObj.response?.data?.detail || 'Failed to initiate neural ingestion.', { type: 'error', title: 'Ingestion Failure' }); } finally { setIsParsingFile(false); if (fileInputRef.current) fileInputRef.current.value = ''; } }; const loadVersions = async () => { if (!selectedArticle) return; setVersionsLoading(true); try { const resp = await api.get(`kb/${selectedArticle.id}/versions/`); setVersions(resp.data || []); } catch (err) { console.error('Failed to load version history', err); } finally { setVersionsLoading(false); } }; const handleRestoreVersion = async (versionId: string) => { if (!selectedArticle) return; const confirmed = await confirm("Restore this version? This will overwrite the current article with this historical snapshot.", { title: "Restore Version", confirmLabel: "Restore", type: "warning" }); if (!confirmed) return; try { const resp = await api.post(`kb/${selectedArticle.id}/restore/${versionId}/`); setArticles(prev => prev.map(a => a.id === selectedArticle.id ? { ...a, ...resp.data } : a)); setSelectedArticle({ ...selectedArticle, ...resp.data }); setEditTitle(resp.data.title); setEditContent(resp.data.content); setEditCategory(resp.data.category); // Reload versions to show current newly created snapshot await loadVersions(); } catch (err) { console.error('Failed to restore version', err); alert('Failed to restore version.', { type: 'error', title: 'System Error' }); } }; const handleCompareVersion = (version: KBArticleVersion) => { setComparingVersion(version); setShowHistory(false); setIsEditing(false); }; const [isSaving, setIsSaving] = useState(false); const [saveStatus, setSaveStatus] = useState<'idle' | 'success' | 'error'>('idle'); const [isAutoDrafting, setIsAutoDrafting] = useState(false); const handleAutoDraft = async () => { if (!editContent.trim()) return; setIsAutoDrafting(true); try { const resp = await api.post('kb/autodraft/', { content: editContent }); if (resp.data.formatted_content) { setEditContent(resp.data.formatted_content); alert('Neural formatting applied successfully.', { type: 'success', title: 'Auto Draft' }); } } catch (err) { console.error('Auto draft failed:', err); alert('Failed to apply neural formatting.', { type: 'error', title: 'System Error' }); } finally { setIsAutoDrafting(false); } }; const handleSaveDossier = async () => { setIsSaving(true); setSaveStatus('idle'); try { if (selectedInsight) { // Save Insight Edit const payload = { suggested_title: editTitle, suggested_content: editContent, category: editCategory }; const resp = await api.patch(`kb/insights/${selectedInsight.id}/`, payload); setInsights(prev => prev.map(i => i.id === selectedInsight.id ? { ...i, ...resp.data } : i)); setSelectedInsight({ ...selectedInsight, ...resp.data }); } else if (selectedArticle?.id) { // Save Article Update const payload = { title: editTitle, content: editContent, category: editCategory, is_published: editPublished }; const resp = await api.patch(`kb/${selectedArticle.id}`, payload); setArticles(prev => prev.map(a => a.id === selectedArticle.id ? { ...a, ...resp.data } : a)); setSelectedArticle({ ...selectedArticle, ...resp.data }); } else { // Create New Article const payload = { title: editTitle, content: editContent, category: editCategory, is_published: editPublished }; const resp = await api.post('kb/', payload, { params: { workspace_id: workspaceId } }); setArticles(prev => [resp.data, ...prev]); setSelectedArticle(resp.data); } setSaveStatus('success'); setTimeout(() => { setIsEditing(false); setSaveStatus('idle'); }, 1000); fetchCategories(); } catch (err) { console.error('Dossier save failed:', err); setSaveStatus('error'); } finally { setIsSaving(false); } }; const handleDeleteArticle = async (id: string) => { const confirmed = await confirm('Retract this strategic asset from the library?', { title: 'Retract Asset', confirmLabel: 'Retract', type: 'error', danger: true }); if (!confirmed) return; try { await api.delete(`/kb/${id}`); setArticles(prev => prev.filter(a => a.id !== id)); setDrawerOpen(false); } catch (err) { console.error('Retraction failed:', err); } }; // Insight Actions const handleApplyInsight = async (insight: KBInsight) => { try { await api.post(`kb/insights/${insight.id}/apply/`); setInsights(prev => prev.filter(i => i.id !== insight.id)); setActiveTab('library'); fetchArticles('', selectedCategory); } catch (err) { console.error('Failed to apply insight:', err); } }; const handleDismissInsight = async (id: string) => { try { await api.post(`kb/insights/${id}/dismiss/`); setInsights(prev => prev.filter(i => i.id !== id)); } catch (err) { console.error('Failed to dismiss insight:', err); } }; // Pagination & Drafts Logic const allDrafts = articles.filter(a => !a.is_published); const draftsToDisplay = allDrafts; const publishedArticles = articles.filter(a => a.is_published); const totalPages = Math.ceil(publishedArticles.length / itemsPerPage); const paginatedArticles = publishedArticles.slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage); return ( <div className={styles.container}> <header className={styles.missionBanner}> <div className={styles.bannerContent}> <div className={styles.headerMainRow}> <h1>{activeTab === 'library' ? 'KNOWLEDGE LIBRARY' : 'KNOWLEDGE GROWTH'}</h1> <div className={styles.headerTabs}> <button className={`${styles.tab} ${activeTab === 'library' ? styles.activeTab : ''}`} onClick={() => setActiveTab('library')} > <Globe size={14} /> LIBRARY </button> <button className={`${styles.tab} ${activeTab === 'growth' ? styles.activeTab : ''}`} onClick={() => setActiveTab('growth')} > <Sparkles size={14} /> AI GROWTH CENTER </button> </div> </div> <p className={styles.description}> {activeTab === 'library' ? 'Strategic intelligence gathering and architectural documentation.' : 'AI-detected blindspots and documentation suggestions.'} </p> <form className={styles.searchControls} onSubmit={handleSearchTrigger}> <div className={styles.searchWrapper}> <Search className={styles.searchIcon} size={20} /> <input type="text" placeholder="Type query and press Enter..." value={searchInput} onChange={(e) => setSearchInput(e.target.value)} /> {loading && searchInput.length > 0 && ( <div className={styles.searchPulse}> <Radio size={14} className={styles.pulseIcon} /> <span>NEURAL SCANNING</span> </div> )} </div> {canEdit && ( <div className={styles.newIntelDropdownWrapper}> <button type="button" className={styles.newIntelBtn} onClick={() => setIsDropdownOpen(!isDropdownOpen)} disabled={isParsingFile} > {isParsingFile ? ( <><Radio size={18} className={styles.pulseIcon} /> PARSING</> ) : ( <><Plus size={18} /> NEW INTEL</> )} </button> <AnimatePresence> {isDropdownOpen && ( <motion.div className={styles.newIntelDropdown} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, scale: 0.95 }} > <button type="button" onClick={handleCreateNew} className={styles.intelOption}> <Edit3 size={16} /> Write Article <span>Start from an empty technical directive</span> </button> <button type="button" onClick={() => fileInputRef.current?.click()} className={styles.intelOption}> <UploadCloud size={16} /> Upload & Parse (AI) <span>Convert .txt / .md into structured article</span> </button> </motion.div> )} </AnimatePresence> <input type="file" ref={fileInputRef} onChange={handleFileUpload} accept=".txt,.md" multiple style={{ display: 'none' }} /> </div> )} </form> {activeTab === 'library' && ( <div className={styles.categoryDropdownRow} style={{ marginTop: '40px' }}> <div className={styles.categorySelectWrapper}> <span className={styles.categoryLabel}>OPERATIONAL FOCUS:</span> <div className={styles.customSelect}> <select value={selectedCategory} onChange={(e) => { setSelectedCategory(e.target.value); fetchArticles(activeQuery, e.target.value); }} > <option value="All">ALL DEPARTMENTS</option> {categories.filter(c => c !== 'All').map(cat => ( <option key={cat} value={cat}> {(cat || 'general').toUpperCase()} </option> ))} </select> <ChevronDown size={14} className={styles.selectIcon} /> </div> </div> </div> )} </div> </header> <div className={styles.contentArea}> <AnimatePresence> {draftsToDisplay.length > 0 && activeTab === 'library' && ( <motion.aside className={styles.draftSidebar} initial={{ opacity: 0, x: -50 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: -50 }} > <div className={styles.sidebarHeader}> <Clock size={16} /> <h3>RECENT DRAFTS</h3> </div> <div className={styles.draftList}> {draftsToDisplay.map(draft => ( <div key={draft.id} className={styles.draftItem} onClick={() => openDossier(draft)} > <div className={styles.draftTitle}>{draft.title}</div> <div className={styles.draftMeta}> {draft.score ? ( <><Eye size={10} /> VIEW EXISTING</> ) : ( <><Zap size={10} /> READY FOR REVIEW</> )} </div> </div> ))} </div> </motion.aside> )} </AnimatePresence> <div className={styles.mainLibrary}> <AnimatePresence mode="wait"> {activeTab === 'growth' ? ( <motion.div key="growth" className={styles.growthGrid} initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -20 }} > {insightsLoading ? ( <div className={styles.emptyState}> <div className={styles.loadingPulse} /> <p>Scanning knowledge topology for gaps...</p> </div> ) : insights.length === 0 ? ( <motion.div key="growth-empty" initial={{ opacity: 0, scale: 0.95 }} animate={{ opacity: 1, scale: 1 }} className={styles.emptyState} > <div className={styles.emptyVisual} style={{ background: 'var(--bg2)', borderRadius: '50%', padding: '40px', marginBottom: '24px' }}> <ShieldCheck size={64} color="var(--primary)" /> </div> <h3>Knowledge Equilibrium Reached</h3> <p style={{ maxWidth: 450, margin: '0 auto' }}> The AI Sentinel has analyzed all recent ticket resolutions and historical patterns. No critical knowledge blindspots or documentation gaps are currently detected. </p> <div className={styles.searchPulse} style={{ marginTop: '30px', position: 'static', transform: 'none' }}> <Radio size={14} className={styles.pulseIcon} /> <span>CONTINUOUS MONITORING ACTIVE</span> </div> </motion.div> ) : ( <> {insights.map((insight) => <motion.div key={insight.id} className={styles.insightCard} onClick={() => openInsightDossier(insight)}> <div className={styles.insightHeaderRow}> <span className={styles.insightType}> {insight.insight_type === 'DEPTH_IMPROVEMENT' ? 'Increase in depth of article' : 'New topics'} </span> <span className={styles.insightDept}>{insight.category}</span> </div> <div className={styles.insightContent}> <h3>{insight.suggested_title}</h3> <div className={styles.reasoningBox}> <span className={styles.reasoningLabel}>AI REASONING</span> <p className={styles.reasoningText}>{insight.reasoning}</p> </div> </div> <div className={styles.confidenceSection}> <div className={styles.confHeader}> <label>PRIORITY SCORE</label> <span className={styles.confValue}>{Math.round(insight.confidence_score * 100)}%</span> </div> <div className={styles.confMeter}> <div className={styles.confFill} style={{ width: `${insight.confidence_score * 100}%` }} /> </div> </div> <div className={styles.insightActions}> <button className={styles.applyBtn} onClick={(e) => { e.stopPropagation(); handleApplyInsight(insight); }} > <Send size={14} /> DEPLOY </button> <button className={styles.dismissBtn} onClick={(e) => { e.stopPropagation(); handleDismissInsight(insight.id); }} > DISMISS </button> </div> </motion.div> )} <div ref={loadingRef} style={{ height: '2px', width: '100%' }} /> {insightsLoading && ( <div className={styles.emptyState}> <div className={styles.loadingPulse} /> </div> )} </> )} </motion.div> ) : error ? ( <motion.div key="error" initial={{ opacity: 0 }} animate={{ opacity: 1 }} className={styles.emptyState}> <div className={styles.emptyVisual} style={{ background: 'rgba(239, 68, 68, 0.1)' }}> <Info size={64} color="#ef4444" /> </div> <h3 style={{ color: '#ef4444' }}>Operational Failure</h3> <p>{error}</p> <button className={styles.newIntelBtn} onClick={() => fetchArticles(searchInput, selectedCategory)} style={{ marginTop: '20px' }} > RE-INITIALIZE SCAN </button> </motion.div> ) : loading && articles.length === 0 ? ( <motion.div key="loading" initial={{ opacity: 0 }} animate={{ opacity: 1 }} className={styles.emptyState}> <div className={styles.loadingPulse} /> <p>RECONNAISSANCE IN PROGRESS...</p> </motion.div> ) : articles.length === 0 ? ( <motion.div key="empty" initial={{ opacity: 0 }} animate={{ opacity: 1 }} className={styles.emptyState}> <div className={styles.emptyVisual}><ShieldCheck size={64} /></div> <h3>Intelligence Pool Clear</h3> <p>No documentation found matching current operational filters.</p> {aiSuggestion && ( <div className={styles.queryNudge}> Did you mean: <button onClick={() => { setSearchInput(aiSuggestion); fetchArticles(aiSuggestion, selectedCategory); }}>{aiSuggestion}</button>? </div> )} </motion.div> ) : ( <div className={styles.resultsContainer}> <AnimatePresence> {aiAnswer && ( <motion.div className={styles.aiSpotlight} 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={14} /> AI DIRECT ANSWER </div> {isAiSynthetic && <span className={styles.syntheticLag}>GENERATED IN REAL-TIME</span>} </div> <div className={styles.answerText}> <NexusMarkdown content={aiAnswer} /> </div> <div className={styles.spotlightFooter}> Based on the top documentation matches below. </div> </motion.div> )} </AnimatePresence> <motion.div key="grid" className={styles.articlesGrid} initial={{ opacity: 0 }} animate={{ opacity: 1 }} > {paginatedArticles.map((article, i) => ( <motion.div key={article.id} className={styles.articleCard} initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: i * 0.05 }} onClick={() => openDossier(article)} > <div className={styles.cardHeader}> <div className={styles.typeBadge}> {article.match_type === 'visual' ? <Zap size={10} /> : <Info size={10} />} {article.match_type?.toUpperCase() || 'DOCUMENT'} </div> <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}> {typeof article.score === 'number' && !Number.isNaN(article.score) && ( <span className={`${styles.matchBadge} ${article.score > 80 ? styles.highMatch : styles.regularMatch}`}> {Math.round(article.score)}% CONFIDENCE </span> )} <div className={`${styles.statusDot} ${article.is_published ? styles.live : styles.draft}`} /> </div> </div> <div className={styles.cardBody}> <span className={styles.catBadge}>{article.category}</span> <h3>{article.title}</h3> <p className={styles.snippet}> {article.snippet || (article.content || '').replace(/[#*`|> -]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 140)}... </p> </div> <div className={styles.cardFooter}> <div className={styles.telemetry}> <span title="Last updated"><Radio size={12} /> {article.updated_at ? new Date(article.updated_at).toLocaleDateString() : 'Just now'}</span> {article.view_count > 0 && <span title="Article Views"><Eye size={12} /> {article.view_count}</span>} {article.citation_count > 0 && <span title="Cited by AI"><Sparkles size={12} /> {article.citation_count}</span>} </div> </div> </motion.div> ))} </motion.div> </div> )} </AnimatePresence> {activeTab === 'library' && totalPages > 1 && ( <div className={styles.pagination}> <button disabled={currentPage === 1} onClick={() => setCurrentPage(p => p - 1)} className={styles.pageBtn} > <ChevronLeft size={18} /> </button> <div className={styles.pageInfo}> <span>PAGE</span> <span className={styles.pageNum}>{currentPage}</span> <span>OF</span> <span className={styles.pageNum}>{totalPages}</span> </div> <button disabled={currentPage === totalPages} onClick={() => setCurrentPage(p => p + 1)} className={styles.pageBtn} > <ChevronRight size={18} /> </button> </div> )} </div> </div> {/* STRATEGIC DOSSIER DRAWER */} <AnimatePresence> {drawerOpen && ( <> <motion.div className={styles.drawerBackdrop} initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} onClick={() => setDrawerOpen(false)} /> <motion.div className={styles.dossierDrawer} initial={{ x: '100%' }} animate={{ x: 0 }} exit={{ x: '100%' }} transition={{ type: 'spring', damping: 25, stiffness: 200 }} > <header className={styles.dossierHeader}> <div className={styles.dossierMeta}> <div className={styles.metaTop}> <span className={styles.metaLabel}>{selectedInsight ? 'AI KNOWLEDGE INSIGHT' : 'DOCUMENT INTEL'}</span> <div className={styles.headerRight}> {canEdit && !selectedInsight && ( <div className={styles.modeToggle}> <button className={`${styles.modeBtn} ${!isEditing && !showHistory ? styles.activeMode : ''}`} onClick={() => { setIsEditing(false); setShowHistory(false); }} > <Eye size={14} /> VIEW </button> <button className={`${styles.modeBtn} ${!isEditing && showHistory ? styles.activeMode : ''}`} onClick={() => { setIsEditing(false); setShowHistory(true); setComparingVersion(null); loadVersions(); }} > <History size={14} /> HISTORY </button> {comparingVersion && ( <button className={`${styles.modeBtn} ${comparingVersion ? styles.activeMode : ''}`} onClick={() => { setIsEditing(false); setShowHistory(false); }} > <Search size={14} /> DIFF v{comparingVersion.version_number} </button> )} <button className={`${styles.modeBtn} ${isEditing ? styles.activeMode : ''}`} onClick={() => { setIsEditing(true); setShowHistory(false); }} > <Edit3 size={14} /> EDIT </button> </div> )} {canEdit && selectedInsight && ( <div className={styles.modeToggle}> <button className={`${styles.modeBtn} ${!isEditing ? styles.activeMode : ''}`} onClick={() => setIsEditing(false)} > <Eye size={14} /> VIEW </button> <button className={`${styles.modeBtn} ${isEditing ? styles.activeMode : ''}`} onClick={() => setIsEditing(true)} > <Edit3 size={14} /> EDIT </button> </div> )} <button className={styles.closeDrawer} onClick={() => setDrawerOpen(false)}> <X size={18} /> </button> </div> </div> {isEditing ? ( <div className={styles.titleEditRow}> <input className={styles.editTitleInput} value={editTitle} onChange={e => setEditTitle(e.target.value)} placeholder="Article Title..." disabled={isAutoDrafting} /> <button className={`${styles.deployBtn} ${saveStatus === 'success' ? styles.btnSuccess : ''} ${saveStatus === 'error' ? styles.btnError : ''}`} onClick={handleSaveDossier} disabled={isSaving || isAutoDrafting} > {isSaving ? <Radio size={14} className={styles.spin} /> : <Send size={14} />} {saveStatus === 'success' ? 'UPDATED' : saveStatus === 'error' ? 'RETRY' : 'SAVE DRAFT'} </button> </div> ) : ( <div className={styles.titleViewRow}> <h2>{editTitle}</h2> {selectedInsight ? ( <button className={styles.deployInsightBtn} onClick={() => handleApplyInsight(selectedInsight)}> <Send size={14} /> DEPLOY TO KB </button> ) : ( <span className={`${styles.statusBadge} ${selectedArticle?.is_published ? styles.badgeLive : styles.badgeDraft}`}> {selectedArticle?.is_published ? <Globe size={12} /> : <Lock size={12} />} {selectedArticle?.is_published ? 'LIVE' : 'DRAFT'} </span> )} </div> )} </div> </header> <div className={styles.dossierBody}> {isEditing ? ( <div className={styles.editInterface}> <div className={styles.compactToolbar}> <div className={styles.toolbarGroup}> <label>CAT</label> <select value={editCategory} onChange={e => setEditCategory(e.target.value)} disabled={isAutoDrafting}> {categories.filter(c => c !== 'All').map(c => <option key={c} value={c}>{c}</option>)} {!categories.includes('General') && <option value="General">General</option>} </select> </div> <div className={styles.toolbarGroup}> <label>VISIBILITY</label> <div className={styles.miniToggles}> <button className={`${styles.miniToggle} ${editPublished ? styles.activeToggle : ''}`} onClick={() => !isAutoDrafting && setEditPublished(true)} disabled={isAutoDrafting} > <Globe size={12} /> LIVE </button> <button className={`${styles.miniToggle} ${!editPublished ? styles.activeToggle : ''}`} onClick={() => !isAutoDrafting && setEditPublished(false)} disabled={isAutoDrafting} > <Lock size={12} /> DRAFT </button> </div> </div> <div className={styles.toolbarGroup}> <button className={`${styles.autoDraftBtn} ${isAutoDrafting ? styles.btnPulse : ''}`} onClick={handleAutoDraft} disabled={isAutoDrafting} title="Apply neural formatting to content" > {isAutoDrafting ? <Radio size={12} className={styles.spin} /> : <Sparkles size={12} />} {isAutoDrafting ? 'FORMATTING...' : 'AUTO DRAFT'} </button> </div> {canShred && ( <button className={styles.miniRetract} onClick={() => selectedArticle && !isAutoDrafting && handleDeleteArticle(selectedArticle.id)} disabled={isAutoDrafting} > <Trash2 size={12} /> SHRED </button> )} </div> <div className={styles.editScrollArea}> {isAutoDrafting && ( <div className={styles.editorOverlay}> <Radio className={styles.spin} size={32} color="var(--primary)" /> <span className={styles.overlayText}>Neural Formatting in Progress...</span> </div> )} <textarea className={styles.editArea} value={editContent} onChange={e => setEditContent(e.target.value)} placeholder="Enter strategic content in Markdown..." readOnly={isAutoDrafting} /> </div> </div> ) : ( <div className={styles.viewInterface}> {showHistory && !isEditing && selectedArticle ? ( <div className={styles.historyContainer}> <div className={styles.historyHeader}> <History size={18} /> <h3>Article Version Ledger</h3> </div> <p className={styles.historySub}>Previous iterations automatically snapshotted upon modification.</p> {versionsLoading ? ( <div className={styles.emptyState}> <div className={styles.loadingPulse} /> </div> ) : versions.length === 0 ? ( <div className={styles.emptyState}> <p>No historical versions found.</p> </div> ) : ( <div className={styles.timelineList}> {versions.map((ver, idx) => ( <div key={ver.id} className={styles.timelineNode}> <div className={styles.nodeLine} /> <div className={styles.nodeDot}>{versions.length - idx === selectedArticle.version ? '★' : ''}</div> <div className={styles.nodeContent}> <div className={styles.nodeHeader}> <span className={styles.nodeVersion}>v{ver.version_number}</span> <span className={styles.nodeDate}>{new Date(ver.created_at).toLocaleString()}</span> </div> <div className={styles.nodeMeta}> <span>Author: {ver.author_name}</span> <span>Title: {ver.title}</span> </div> <div className={styles.historyActions}> <button className={styles.restoreBtn} onClick={() => handleRestoreVersion(ver.id)} > <RotateCcw size={14} /> RESTORE </button> <button className={styles.compareBtn} onClick={() => handleCompareVersion(ver)} > <Search size={14} /> COMPARE </button> </div> </div> </div> ))} </div> )} </div> ) : ( <> <div className={styles.telemetryBar}> <div className={styles.telItem}> <label>{selectedInsight ? 'CONFIDENCE' : 'AUTHOR ID'}</label> <span>{selectedInsight ? `${Math.round(selectedInsight.confidence_score * 100)}%` : (selectedArticle?.author_id || 'REDACTED')}</span> </div> <div className={styles.telItem}> <label>{selectedInsight ? 'EVIDENCE COUNT' : 'LAST SYNC'}</label> <span>{selectedInsight ? selectedInsight.evidence_count : (selectedArticle ? new Date(selectedArticle.updated_at).toLocaleString() : 'N/A')}</span> </div> {!selectedInsight && ( <div className={styles.telItem}> <label>MATCH SCORE</label> <span>{selectedArticle?.score ? `${Math.round(selectedArticle.score)}%` : 'STATIC'}</span> </div> )} </div> <div className={styles.viewScrollArea}> <AnimatePresence> {(selectedArticle?.summary || selectedInsight?.reasoning) && !comparingVersion && ( <motion.div className={styles.aiInsightBox} initial={{ opacity: 0, y: -20 }} animate={{ opacity: 1, y: 0 }} > <div className={styles.insightHeader}> <Sparkles size={14} className={styles.zapIcon} /> <span className={styles.insightLabel}>{selectedInsight ? 'AI GAP ANALYSIS' : 'AI INSIGHT'}</span> </div> <p className={styles.insightText}>{selectedInsight ? selectedInsight.reasoning : selectedArticle?.summary}</p> </motion.div> )} </AnimatePresence> <div className={`${styles.markdownContent} ${styles.markdownBody}`}> {comparingVersion ? ( <div className={styles.diffView}> <div className={styles.diffHeader}> <span>Comparing Current vs v{comparingVersion.version_number}</span> <button className={styles.exitDiff} onClick={() => setComparingVersion(null)}>EXIT DIFF</button> </div> <div className={styles.diffLines}> {(() => { const diffs = computeDiff(comparingVersion.content, selectedArticle?.content || ''); const hasChanges = diffs.some(d => d.type !== 'unchanged'); if (!hasChanges) { return ( <div className={styles.noChangesMsg}> <ShieldCheck size={20} /> <span>Current version is identical to v{comparingVersion.version_number}. No structural changes detected.</span> </div> ); } return diffs.map((line, idx) => ( <div key={idx} className={`${styles.diffLine} ${styles[line.type]}`}> <span className={styles.diffMarker}> {line.type === 'added' ? '+' : line.type === 'removed' ? '-' : ' '} </span> <pre>{line.value || ' '}</pre> </div> )); })()} </div> </div> ) : ( <NexusMarkdown content={selectedArticle?.content || editContent} /> )} </div> </div> </> )} </div> )} </div> </motion.div> </> )} </AnimatePresence> </div> ); };
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Search, Plus, X, Trash2, Edit3, ShieldCheck, Zap, Info, Radio, ChevronLeft, ChevronRight, Eye, Send, Lock, Globe, Sparkles, UploadCloud, History, RotateCcw, Clock, ChevronDown } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { api, useAuth, computeDiff, useNotification, NexusMarkdown } from '@nexus/shared';
import styles from './KnowledgeBase.module.css';
// Pre-defined role groups for UI visibility
const SHRED_ROLES = ['superadmin', '3sc_admin', '3sc_lead', '3sc_agent'];
const EDIT_ROLES = ['superadmin', '3sc_admin', '3sc_lead', '3sc_agent'];
interface KBArticle {
id: string;
title: string;
content: string;
category: string;
is_published: boolean;
updated_at: string;
author_id?: string;
view_count: number;
citation_count: number;
score?: number;
snippet?: string;
match_type?: string;
created_at?: string;
summary?: string;
version?: number;
}
interface KnowledgeBaseProps {
workspaceId?: string;
}
interface KBInsight {
id: string;
insight_type: 'DEPTH_IMPROVEMENT' | 'NEW_TOPIC';
suggested_title: string;
suggested_content: string;
reasoning: string;
confidence_score: number;
category: string;
evidence_count: number;
}
interface KBArticleVersion {
id: string;
version_number: number;
title: string;
content: string;
category: string;
created_at: string;
author_id: string;
author_name: string;
}
// Mermaid logic moved to centralized NexusMermaid.tsx component in @nexus/shared
export const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ workspaceId }) => {
const { user } = useAuth();
const { alert, confirm } = useNotification();
const canEdit = user?.role && EDIT_ROLES.includes(user.role);
const canShred = user?.role && SHRED_ROLES.includes(user.role);
const [articles, setArticles] = useState<KBArticle[]>([]);
const [categories, setCategories] = useState<string[]>(['All']);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// Search State
const [searchInput, setSearchInput] = useState('');
const [activeQuery, setActiveQuery] = useState('');
const [selectedCategory, setSelectedCategory] = useState('All');
// Pagination State
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 6;
// Dossier State
const [drawerOpen, setDrawerOpen] = useState(false);
const [selectedArticle, setSelectedArticle] = useState<KBArticle | null>(null);
const [selectedInsight, setSelectedInsight] = useState<KBInsight | null>(null);
const [isEditing, setIsEditing] = useState(false);
// Edit Buffer
const [editTitle, setEditTitle] = useState('');
const [editContent, setEditContent] = useState('');
const [editCategory, setEditCategory] = useState('');
const [editPublished, setEditPublished] = useState(true);
// Version History State
const [showHistory, setShowHistory] = useState(false);
const [versions, setVersions] = useState<KBArticleVersion[]>([]);
const [versionsLoading, setVersionsLoading] = useState(false);
const [comparingVersion, setComparingVersion] = useState<KBArticleVersion | null>(null);
// File Upload State
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
const [isParsingFile, setIsParsingFile] = useState(false);