import React, { useState, useEffect, useCallback } from 'react'; import ReactMarkdown from 'react-markdown'; import remarkGfm from 'remark-gfm'; import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'; import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism'; import { Search, Plus, X, Trash2, Edit3, ShieldCheck, Zap, Info, Radio, ChevronLeft, ChevronRight, Eye, Send, Lock, Globe, Sparkles } from 'lucide-react'; import { motion, AnimatePresence } from 'framer-motion'; import { api, useAuth } from '@nexus/shared'; import mermaid from 'mermaid'; import styles from './KnowledgeBase.module.css'; // Pre-defined role groups for UI visibility const SHRED_ROLES = ['3sc_admin', '3sc_lead', '3sc_agent']; const EDIT_ROLES = ['3sc_admin', '3sc_lead', '3sc_agent']; // Initialize Mermaid mermaid.initialize({ startOnLoad: false, theme: 'dark', securityLevel: 'loose', fontFamily: 'Inter, system-ui, sans-serif', }); // Enhanced Mermaid Component const Mermaid: React.FC<{ chart: string }> = ({ chart }) => { const [svg, setSvg] = useState(''); const [error, setError] = useState(null); const [isRendering, setIsRendering] = useState(true); const [showRaw, setShowRaw] = useState(false); const [id] = useState(() => `mermaid-${Math.random().toString(36).substr(2, 9)}`); useEffect(() => { let isMounted = true; const renderChart = async () => { if (!chart) return; setIsRendering(true); setError(null); // Sanitize input to handle model artifacts or accidental wrappers const sanitized = chart .replace(/```mermaid/g, '') .replace(/```/g, '') .trim(); try { // Clear previous error and SVG before re-rendering const { svg: renderedSvg } = await mermaid.render(id, sanitized); if (isMounted) { setSvg(renderedSvg); setIsRendering(false); setError(null); } } catch (err: any) { console.error("Mermaid synthesis failed:", err); if (isMounted) { setError(err.message || 'The diagram syntax is incompatible with the Nexus rendering engine.'); setIsRendering(false); } } }; renderChart(); return () => { isMounted = false; }; }, [chart, id]); if (isRendering) { return (
SYNTHESIZING ARCHITECTURE...
); } if (error) { return (
SYNTHESIS FAILURE

Diagram Engine Interrupted

{error}

{showRaw && ( {chart} )}
); } return (
); }; 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; match_type?: string; snippet?: string; } interface KnowledgeBaseProps { workspaceId?: string; } export const KnowledgeBase: React.FC = ({ workspaceId }) => { const { user } = useAuth(); const canEdit = user?.role && EDIT_ROLES.includes(user.role); const canShred = user?.role && SHRED_ROLES.includes(user.role); const [articles, setArticles] = useState([]); const [categories, setCategories] = useState(['All']); const [loading, setLoading] = useState(true); // Search State const [searchInput, setSearchInput] = useState(''); const [activeQuery, setActiveQuery] = useState(''); const [selectedCategory, setSelectedCategory] = useState('All'); // Pagination State const [currentPage, setCurrentPage] = useState(1); const itemsPerPage = 4; // Dossier State const [drawerOpen, setDrawerOpen] = useState(false); const [selectedArticle, setSelectedArticle] = useState
(null); const [selectedInsight, setSelectedInsight] = useState(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); // AI Search Enhanced State const [suggestions, setSuggestions] = useState([]); const [aiSuggestion, setAiSuggestion] = useState(null); const [aiAnswer, setAiAnswer] = useState(null); const [isAiSynthetic, setIsAiSynthetic] = useState(false); // AI Growth Center State const [activeTab, setActiveTab] = useState<'library' | 'growth'>('library'); const [insights, setInsights] = useState([]); const [insightsLoading, setInsightsLoading] = useState(false); // 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) { console.error('Failed to fetch categories:', err); } }, [workspaceId]); // 2. Fetch Articles const fetchArticles = useCallback(async (query: string = '', cat: string = 'All') => { setLoading(true); try { const params: any = { 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 || []); setSuggestions(resp.data.expanded_queries || []); 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 || []); setSuggestions([]); setAiSuggestion(null); setAiAnswer(null); setIsAiSynthetic(false); } setCurrentPage(1); // Reset to first page on search/filter } catch (err) { console.error('Failed to fetch articles:', err); } finally { setLoading(false); } }, [workspaceId]); // 3. Fetch Insights const fetchInsights = useCallback(async () => { setInsightsLoading(true); try { const resp = await api.get('kb/insights/', { params: { workspace_id: workspaceId } }); setInsights(resp.data); } catch (err) { console.error('Failed to fetch insights:', err); } finally { setInsightsLoading(false); } }, [workspaceId]); useEffect(() => { fetchCategories(); fetchArticles('', 'All'); }, [fetchCategories, fetchArticles]); // Reactive Search Reset useEffect(() => { if (searchInput.trim() === '') { setActiveQuery(''); setAiAnswer(null); setSuggestions([]); setAiSuggestion(null); setIsAiSynthetic(false); // Optional: fetchArticles('', selectedCategory); // But fetchArticles is already called by the next useEffect if we change activeQuery } }, [searchInput]); useEffect(() => { if (activeTab === 'growth') { fetchInsights(); } }, [activeTab, fetchInsights]); const handleSearchTrigger = (e?: React.FormEvent) => { if (e) e.preventDefault(); setActiveQuery(searchInput); fetchArticles(searchInput, selectedCategory); }; // Article Actions const openDossier = (article: Article) => { setSelectedArticle(article); setSelectedInsight(null); setEditTitle(article.title); setEditContent(article.content); setEditCategory(article.category); setEditPublished(article.is_published); setIsEditing(false); setDrawerOpen(true); }; const openInsightDossier = (insight: any) => { 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); 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); }; const [isSaving, setIsSaving] = useState(false); const [saveStatus, setSaveStatus] = useState<'idle' | 'success' | 'error'>('idle'); 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); 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) => { if (!window.confirm('Retract this strategic asset from the library?')) 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: any) => { 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 Logic const totalPages = Math.ceil(articles.length / itemsPerPage); const paginatedArticles = articles.slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage); return (

{activeTab === 'library' ? 'KNOWLEDGE LIBRARY' : 'KNOWLEDGE GROWTH'}

{activeTab === 'library' ? 'Strategic intelligence gathering and architectural documentation.' : 'AI-detected blindspots and documentation suggestions.'}

setSearchInput(e.target.value)} /> {loading && searchInput.length > 0 && (
NEURAL SCANNING
)}
{canEdit && ( )}
{suggestions.length > 0 && ( SUGGESTIONS: {suggestions.map(s => ( ))} )}
{activeTab === 'growth' ? ( {insightsLoading ? (

Scanning knowledge topology for gaps...

) : insights.length === 0 ? (

Knowledge Equilibrium Reached

The AI Sentinel has analyzed all recent ticket resolutions and historical patterns. No critical knowledge blindspots or documentation gaps are currently detected.

CONTINUOUS MONITORING ACTIVE
) : ( insights.map((insight) => ( openInsightDossier(insight)}>
{insight.insight_type.replace('_', ' ')} {insight.category}

{insight.suggested_title}

AI REASONING

{insight.reasoning}

{Math.round(insight.confidence_score * 100)}%
)) )} ) : loading && articles.length === 0 ? (

RECONNAISSANCE IN PROGRESS...

) : articles.length === 0 ? (

Intelligence Pool Clear

No documentation found matching current operational filters.

{aiSuggestion && (
Did you mean: ?
)}
) : (
{aiAnswer && (
AI DIRECT ANSWER
{isAiSynthetic && GENERATED IN REAL-TIME}
{aiAnswer}
Based on the top documentation matches below.
)}
{paginatedArticles.map((article, i) => ( openDossier(article)} >
{article.match_type === 'visual' ? : } {article.match_type?.toUpperCase() || 'DOCUMENT'}
{article.category}

{article.title}

{article.snippet || article.content.replace(/[#*`|>\-]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 140)}...

TELEMETRY: {new Date(article.updated_at).toLocaleDateString()} {article.score && MATCH: {Math.round(article.score)}%}
))}
)} {totalPages > 1 && (
PAGE {currentPage} OF {totalPages}
)}
{/* STRATEGIC DOSSIER DRAWER */} {drawerOpen && ( <> setDrawerOpen(false)} />
{selectedInsight ? 'AI KNOWLEDGE INSIGHT' : 'DOCUMENT INTEL'}
{canEdit && (
)}
{isEditing ? (
setEditTitle(e.target.value)} placeholder="Article Title" />
) : (

{editTitle}

{selectedInsight ? ( ) : ( {selectedArticle?.is_published ? : } {selectedArticle?.is_published ? 'LIVE' : 'DRAFT'} )}
)}
{isEditing ? (
{canShred && ( )}