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 = ({ 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([]); const [categories, setCategories] = useState(['All']); const [loading, setLoading] = useState(true); const [error, setError] = useState(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(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); // Version History State const [showHistory, setShowHistory] = useState(false); const [versions, setVersions] = useState([]); const [versionsLoading, setVersionsLoading] = useState(false); const [comparingVersion, setComparingVersion] = useState(null); // File Upload State const [isDropdownOpen, setIsDropdownOpen] = useState(false); const [isParsingFile, setIsParsingFile] = useState(false); const fileInputRef = useRef(null); // AI Search Enhanced State 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); const [insightsPage, setInsightsPage] = useState(0); const [hasMoreInsights, setHasMoreInsights] = useState(true); const loadingRef = useRef(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 = { 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) => { 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 (

{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 && (
{isDropdownOpen && ( )}
)}
{activeTab === 'library' && (
OPERATIONAL FOCUS:
)}
{draftsToDisplay.length > 0 && activeTab === 'library' && (

RECENT DRAFTS

{draftsToDisplay.map(draft => (
openDossier(draft)} >
{draft.title}
{draft.score ? ( <> VIEW EXISTING ) : ( <> READY FOR REVIEW )}
))}
)}
{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 === 'DEPTH_IMPROVEMENT' ? 'Increase in depth of article' : 'New topics'} {insight.category}

{insight.suggested_title}

AI REASONING

{insight.reasoning}

{Math.round(insight.confidence_score * 100)}%
)}
{insightsLoading && (
)} )} ) : error ? (

Operational Failure

{error}

) : 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}
Based on the top documentation matches below.
)}
{paginatedArticles.map((article, i) => ( openDossier(article)} >
{article.match_type === 'visual' ? : } {article.match_type?.toUpperCase() || 'DOCUMENT'}
{typeof article.score === 'number' && !Number.isNaN(article.score) && ( 80 ? styles.highMatch : styles.regularMatch}`}> {Math.round(article.score)}% CONFIDENCE )}
{article.category}

{article.title}

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

{article.updated_at ? new Date(article.updated_at).toLocaleDateString() : 'Just now'} {article.view_count > 0 && {article.view_count}} {article.citation_count > 0 && {article.citation_count}}
))}
)} {activeTab === 'library' && totalPages > 1 && (
PAGE {currentPage} OF {totalPages}
)}
{/* STRATEGIC DOSSIER DRAWER */} {drawerOpen && ( <> setDrawerOpen(false)} />
{selectedInsight ? 'AI KNOWLEDGE INSIGHT' : 'DOCUMENT INTEL'}
{canEdit && !selectedInsight && (
{comparingVersion && ( )}
)} {canEdit && selectedInsight && (
)}
{isEditing ? (
setEditTitle(e.target.value)} placeholder="Article Title..." disabled={isAutoDrafting} />
) : (

{editTitle}

{selectedInsight ? ( ) : ( {selectedArticle?.is_published ? : } {selectedArticle?.is_published ? 'LIVE' : 'DRAFT'} )}
)}
{isEditing ? (
{canShred && ( )}
{isAutoDrafting && (
Neural Formatting in Progress...
)}