Spaces:
Paused
Paused
File size: 20,864 Bytes
1c7f590 5df0bfe 12cea4b 907d8c5 5df0bfe 9483939 5eb4857 5df0bfe 918d162 5df0bfe 5eb4857 16bf212 053ff4c 5eb4857 053ff4c b91e6a1 053ff4c bffb8f7 b91e6a1 5df0bfe 38aa417 bffb8f7 5df0bfe bffb8f7 dfcbb7c 5df0bfe 3407ff5 bffb8f7 5df0bfe 2f50ab0 5df0bfe dfcbb7c bffb8f7 907d8c5 b91e6a1 5eb4857 5df0bfe 5eb4857 38aa417 5df0bfe bffb8f7 5eb4857 053ff4c 882eb03 053ff4c 5df0bfe 882eb03 3407ff5 882eb03 3407ff5 882eb03 5eb4857 5df0bfe 907d8c5 5eb4857 5df0bfe 5eb4857 b91e6a1 dfcbb7c 3407ff5 dfcbb7c 5df0bfe 5eb4857 5df0bfe 38aa417 5eb4857 5df0bfe 5eb4857 5df0bfe b91e6a1 5eb4857 5df0bfe 04b3d6d 5df0bfe 04b3d6d 5df0bfe 16bf212 72fac6f 16bf212 87d5f80 6ca5716 5df0bfe 5eb4857 bffb8f7 5df0bfe 907d8c5 5df0bfe 907d8c5 5df0bfe 907d8c5 5eb4857 deb08b1 b83c98a f63e1ff 9483939 5df0bfe b83c98a 9483939 5eb4857 9483939 b83c98a 907d8c5 9483939 907d8c5 9483939 5df0bfe b83c98a 79a5f2f 9483939 dfcbb7c 9483939 907d8c5 9483939 deb08b1 c66d2a6 bffb8f7 5eb4857 c66d2a6 5eb4857 c66d2a6 5eb4857 5df0bfe 5eb4857 5df0bfe 907d8c5 bffb8f7 5df0bfe 907d8c5 bffb8f7 5df0bfe 907d8c5 5df0bfe 5eb4857 907d8c5 bffb8f7 811af88 907d8c5 811af88 5eb4857 907d8c5 bffb8f7 5eb4857 907d8c5 e79b7f5 907d8c5 5df0bfe 5eb4857 5df0bfe bffb8f7 5df0bfe 907d8c5 48d775a 5df0bfe 907d8c5 f3292d9 829f259 5df0bfe e6dd383 907d8c5 e6dd383 907d8c5 5df0bfe dfcbb7c 907d8c5 5df0bfe 907d8c5 5eb4857 38aa417 bffb8f7 907d8c5 38aa417 907d8c5 38aa417 907d8c5 bffb8f7 38aa417 907d8c5 38aa417 907d8c5 38aa417 d02993d bffb8f7 907d8c5 5df0bfe 907d8c5 5df0bfe 907d8c5 5df0bfe d02993d bffb8f7 5df0bfe bffb8f7 5df0bfe 907d8c5 d02993d 5df0bfe 9483939 d02993d 5df0bfe 9483939 5df0bfe b83c98a 9483939 5df0bfe 12cea4b 918d162 12cea4b 829f259 918d162 12cea4b 5df0bfe d02993d 5df0bfe d02993d 907d8c5 bffb8f7 811af88 87d5f80 9483939 520582b d02993d 907d8c5 d02993d 907d8c5 bffb8f7 811af88 87d5f80 9483939 520582b d02993d 907d8c5 d02993d 5eb4857 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 | 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>
);
};
|