Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit ·
5df0bfe
1
Parent(s): db51981
feat: unified portal migration with local redis and fixed routing
Browse filesFiles changed (11)
- Dockerfile+32-26
- README.md+21-11
- core/config.py+8-1
- frontend/apps/customer/src/components/Analytics.tsx+6-4
- frontend/apps/customer/src/components/KnowledgeBase.module.cssAdded+352
- frontend/apps/customer/src/components/KnowledgeBase.tsx+291-286
- frontend/apps/internal/vite.config.ts+1
- frontend/packages/shared/src/hooks/useDashboard.ts+15-4
- frontend/packages/shared/src/utils/api.ts+7-7
- main.py+12-2
- scripts/run_prod.sh+4
123456789103 unmodified lines14151617181920212223242526272829303132333435363738394041424344454647484950515253545556# --- STAGE 1: BASE (Lightweight Core) ---FROM python:3.11-slim AS baseENV PYTHONDONTWRITEBYTECODE=1 \PYTHONUNBUFFERED=1 \PYTHONPATH=/appWORKDIR /app# Install minimal system dependencies3 unmodified linesgcc \curl \ca-certificates \&& apt-get clean && rm -rf /var/lib/apt/lists/* \&& update-ca-certificates# Install core requirementsCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt# Copy application codeCOPY . .# Create directory for uploadsRUN mkdir -p uploads logsEXPOSE 7860CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]# --- STAGE 2: HYBRID-AI (Optimized Worker) ---FROM base AS heavy# Install lightweight AI dependencies (No Torch/CUDA)COPY requirements-ai.txt .RUN pip install --no-cache-dir -r requirements-ai.txt# PRE-CACHE ONNX WEIGHTS# This ensures sub-second boot times for local CLIP inference without 10GB of bloat.# Placeholder for ONNX download script - in production, this would pull from HF.RUN mkdir -p models && \python -c "print('Pre-caching ONNX weights for clip-ViT-B-32...')"# --- STAGE 3: PRODUCTION (Unified API + Worker) ---FROM heavy AS production# Expose Hugging Face default portEXPOSE 7860# Ensure entrypoint script is executable and has Linux line endingsRUN sed -i 's/\r$//' scripts/run_prod.sh && \chmod +x scripts/run_prod.sh12345678910111213141516171819202122233 unmodified lines272829303132333435363738394041424344454647484950515253545556575859606162# --- STAGE 1: FRONTEND BUILD (Node.js) ---FROM node:20-slim AS frontend-builderWORKDIR /app/frontend# Copy frontend workspace filesCOPY frontend/package*.json ./COPY frontend/packages ./packagesCOPY frontend/apps ./appsCOPY frontend/tsconfig.json ./# Install and Build all workspaces# Note: We build WITHOUT an explicit VITE_API_URL so the client defaults to relative pathsRUN npm installRUN npm run build --workspaces# --- STAGE 2: BACKEND BASE (Python) ---FROM python:3.11-slim AS baseENV PYTHONDONTWRITEBYTECODE=1 \PYTHONUNBUFFERED=1 \PYTHONPATH=/appWORKDIR /app# Install minimal system dependencies3 unmodified linesgcc \curl \ca-certificates \redis-server \&& apt-get clean && rm -rf /var/lib/apt/lists/*# Install core requirementsCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt# --- STAGE 3: HEAVY-AI (Optional logic) ---FROM base AS heavyCOPY requirements-ai.txt .RUN pip install --no-cache-dir -r requirements-ai.txt# --- STAGE 4: PRODUCTION (Unified) ---FROM heavy AS productionWORKDIR /app# Copy backend application codeCOPY . .# Copy BUILT frontend assets from Stage 1 into the backend directoriesCOPY --from=frontend-builder /app/frontend/apps/customer/dist ./frontend/apps/customer/distCOPY --from=frontend-builder /app/frontend/apps/internal/dist ./frontend/apps/internal/dist# Create runtime directoriesRUN mkdir -p uploads logs# Expose Hugging Face default portEXPOSE 7860# Ensure entrypoint script is executableRUN sed -i 's/\r$//' scripts/run_prod.sh && \chmod +x scripts/run_prod.sh
12345678910111213141516171819---title: Nexus Backendemoji: 🪐colorFrom: indigocolorTo: graysdk: dockerapp_port: 7860pinned: false---# Nexus AI Backend (Beta 1.0)Distributed, local-first AI platform for unified workspace management.### Deployment Details- **Architecture**: Unified FastAPI + Arq Worker Sidecar.- **Port**: 7860 (Hugging Face Default).- **Persistence**: Mounted via `/data` storage bucket.- **AI Intelligence**: Hybrid (Local Ollama Tunnel + Google Gemini).1234567891011121314151617181920212223242526272829---title: Nexus Unified Gatewayemoji: 🛡️colorFrom: bluecolorTo: indigosdk: dockerapp_port: 7860pinned: false---# Nexus Unified GatewayThis is the unified deployment of the Nexus Customer Support Portal and Internal Staff Gateway.## Live Dashboards- **Customer Portal**: `https://[space-name].hf.space/`- **Internal Staff Portal**: `https://[space-name].hf.space/admin/`- **API Documentation**: `https://[space-name].hf.space/docs`## Features- **Hybrid AI Core**: Integrated LangGraph agent and semantic search.- **Unified Logic**: Frontend and Backend served from a single origin (Zero CORS issues).- **Auto-Sync**: Background worker for Knowledge Base re-indexing is built into the sidecar process.## Local DevelopmentTo run this locally without Docker:1. Start Backend: `python main.py`2. Start Customer: `npm run dev -w frontend/apps/customer`3. Start Internal: `npm run dev -w frontend/apps/internal`
65 unmodified lines6667686970717250 unmodified lines12312412512612712865 unmodified linesreturn self.DB_HOSTREDIS_URL: str = "redis://localhost:6379"CACHE_REDIS_URL: str = "redis://localhost:6380"# JWT AuthSECRET_KEY: str = "your-secret-key-change-in-production"50 unmodified linesUPLOAD_DIR: str = "uploads"LOG_DIR: str = "logs"class Config:case_sensitive = Trueenv_file = ".env"65 unmodified lines6667686970717250 unmodified lines12312412512612712812913013113213313413565 unmodified linesreturn self.DB_HOSTREDIS_URL: str = "redis://localhost:6379"CACHE_REDIS_URL: str = "redis://localhost:6379"# JWT AuthSECRET_KEY: str = "your-secret-key-change-in-production"50 unmodified linesUPLOAD_DIR: str = "uploads"LOG_DIR: str = "logs"# S3 Configuration (Required if STORAGE_BACKEND="s3")S3_ACCESS_KEY: str | None = NoneS3_SECRET_KEY: str | None = NoneS3_BUCKET: str | None = NoneS3_REGION: str = "us-east-1"S3_ENDPOINT_URL: str | None = None # For Cloudflare R2 or Minioclass Config:case_sensitive = Trueenv_file = ".env"
34 unmodified lines3536373839404179 unmodified lines12112212312412512612712812913013134 unmodified lines};export const Analytics: React.FC<AnalyticsProps> = ({ tickets }) => {const { volume, sla, loading: reportsLoading, refresh: refreshReports } = useReports();const { narrative, loading: narrativeLoading, refresh: refreshNarrative } = useServiceNarrative();const [isResummarizing, setIsResummarizing] = useState(false);79 unmodified lines},{label: "CSAT Score",value: showReportsLoading ? <Skeleton width={60} height={32} /> : "4.8",footer: showReportsLoading ? <Skeleton width={100} height={12} /> : `Lifetime Satisfactory`,color: "hsl(38, 92%, 50%)",icon: "⭐",viz: showReportsLoading ? <Skeleton width={80} height={11} /> : <div style={{ fontSize: 11, color: "#EAB308" }}>{"★".repeat(5) + "☆".repeat(0)}</div>},].map(s => (<div key={s.label} style={{34 unmodified lines3536373839404179 unmodified lines12112212312412512612712812913013113213334 unmodified lines};export const Analytics: React.FC<AnalyticsProps> = ({ tickets }) => {const { volume, sla, csat, loading: reportsLoading, refresh: refreshReports } = useReports();const { narrative, loading: narrativeLoading, refresh: refreshNarrative } = useServiceNarrative();const [isResummarizing, setIsResummarizing] = useState(false);79 unmodified lines},{label: "CSAT Score",value: showReportsLoading ? <Skeleton width={60} height={32} /> : (csat ? csat.average_rating.toFixed(1) : "—"),footer: showReportsLoading ? <Skeleton width={100} height={12} /> : (csat?.total_responses ? `${csat.total_responses} Total Ratings` : "No Ratings Yet"),color: "hsl(38, 92%, 50%)",icon: "⭐",viz: showReportsLoading ? <Skeleton width={80} height={11} /> : <div style={{ fontSize: 11, color: "#EAB308" }}>{"★".repeat(Math.floor(csat?.average_rating || 0)) + "☆".repeat(5 - Math.floor(csat?.average_rating || 0))}</div>},].map(s => (<div key={s.label} style={{
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352/* Customer Portal KB Premium Styles */.container { padding: 32px 48px; color: #111827;}
.searchHero { margin-bottom: 48px;}
.searchHero h1 { font-size: 32px; font-weight: 800; color: #111827; margin-bottom: 8px; letter-spacing: -0.02em;}
.description { color: #6B7280; font-size: 15px; margin-bottom: 32px;}
.searchControls { display: flex; gap: 20px; align-items: center; flex-wrap: wrap;}
.searchWrapper { position: relative; flex: 1; min-width: 320px;}
.searchInput { width: 100%; padding: 16px 20px 16px 52px; border-radius: 16px; border: 1px solid #E5E7EB; font-size: 16px; box-sizing: border-box; outline: none; box-shadow: 0 2px 10px rgba(0,0,0,0.03); transition: all 0.2s;}
.searchInput:focus { border-color: #1E40AF; box-shadow: 0 0 0 4px rgba(30, 64, 175, 0.1);}
.searchBtn { position: absolute; right: 12px; top: 50%; transform: translateY(-50%); background: #1E40AF; color: #fff; border: none; padding: 8px 16px; border-radius: 10px; cursor: pointer; font-size: 13px; font-weight: 700; transition: background 0.2s;}
.searchBtn:hover { background: #1E3A8A;}
.searchIcon { position: absolute; left: 20px; top: 50%; transform: translateY(-50%); color: #9CA3AF;}
.searchPulse { position: absolute; right: 100px; top: 50%; transform: translateY(-50%); display: flex; align-items: center; gap: 8px; font-size: 10px; font-weight: 800; color: #16A34A; animation: pulse 2s infinite;}
@keyframes pulse { 0% { opacity: 0.6; } 50% { opacity: 1; } 100% { opacity: 0.6; }}
.pulseIcon { animation: rotate 2s linear infinite;}
@keyframes rotate { from { transform: rotate(0deg); } to { transform: rotate(360deg); }}
/* AI Answer Spotlight */.aiSpotlight { max-width: 1100px; margin: 0 auto 48px; background: white; border: 1px solid #E5E7EB; border-radius: 20px; padding: 40px; position: relative; box-shadow: 0 4px 20px rgba(0,0,0,0.02);}
.aiSpotlight::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 3px; background: #1E40AF; border-radius: 20px 20px 0 0;}
.spotlightHeader { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;}
.spotlightBadge { display: flex; align-items: center; gap: 10px; background: #EFF6FF; padding: 6px 14px; border-radius: 8px; color: #1E40AF; font-size: 11px; font-weight: 900; text-transform: uppercase; letter-spacing: 0.1em;}
.syntheticFlag { font-size: 10px; font-weight: 800; color: #16A34A; background: #F0FDF4; padding: 4px 8px; border-radius: 4px;}
.answerText { font-size: 18px; line-height: 1.8; color: #111827; font-weight: 600; font-style: italic; margin: 0;}
.spotlightFooter { margin-top: 24px; padding-top: 20px; border-top: 1px solid #F3F4F6; font-size: 11px; font-weight: 700; color: #9CA3AF; text-transform: uppercase; letter-spacing: 0.1em;}
/* Articles Grid */.articlesGrid { display: grid; grid-template-columns: repeat(auto-fill, minmax(440px, 1fr)); gap: 32px; max-width: 1100px; margin: 0 auto;}
.articleCard { background: #fff; border: 1px solid #F3F4FB; border-radius: 20px; padding: 32px; cursor: pointer; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); box-shadow: 0 2px 4px rgba(0,0,0,0.02); display: flex; flex-direction: column; height: 100%;}
.articleCard:hover { transform: translateY(-4px); box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.05); border-color: #1E40AF;}
.cardHeader { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;}
.categoryBadge { font-size: 10px; font-weight: 800; color: #1E40AF; text-transform: uppercase; letter-spacing: 0.1em;}
.matchBadge { font-size: 10px; font-weight: 800; padding: 2px 8px; border-radius: 4px;}
.highMatch { color: #16A34A; background: #F0FDF4;}
.regularMatch { color: #1E40AF; background: #EFF6FF;}
.articleTitle { font-size: 22px; font-weight: 800; color: #111827; margin-bottom: 12px; line-height: 1.2;}
.articleSnippet { font-size: 15px; color: #4B5563; line-height: 1.6; margin-bottom: 24px; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden;}
.cardFooter { display: flex; justify-content: space-between; align-items: center; border-top: 1px solid #F9FAFB; padding-top: 24px; margin-top: auto;}
.articleDate { font-size: 12px; color: #9CA3AF; font-weight: 500;}
.readMore { font-size: 13px; font-weight: 700; color: #1E40AF;}
/* Category Nav */.categoryNav { display: flex; gap: 12px; margin-bottom: 40px; border-bottom: 1px solid #F3F4FB; padding-bottom: 16px; overflow-x: auto;}
.navItem { padding: 8px 0; border: none; background: none; font-size: 14px; font-weight: 600; cursor: pointer; margin-right: 24px; white-space: nowrap; color: #6B7280; transition: all 0.2s;}
.navItemActive { color: #1E40AF; font-weight: 700; border-bottom: 2px solid #1E40AF;}
/* Article View Enhancements */.articleDetail { padding: 40px 60px; maxWidth: 900px; margin: 0 auto;}
.backBtn { background: none; border: none; color: #1E40AF; font-weight: 700; font-size: 14px; cursor: pointer; margin-bottom: 32px; display: flex; align-items: center; gap: 8px;}
.mermaidContainer { margin: 24px 0; background: #1F2937; padding: 32px; border-radius: 16px; overflow-x: auto; display: flex; justify-content: center;}
.shimmerText { animation: shimmer 1.5s infinite linear;}
@keyframes shimmer { 0% { opacity: 0.5; } 50% { opacity: 1; } 100% { opacity: 0.5; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402import React, { useState, useEffect } from 'react';import { api, NexusMarkdown } from '@nexus/shared';import { Skeleton } from './Skeleton';import { Search, ChevronLeft, ChevronRight, Sparkles } from 'lucide-react';const COLORS = {brand: "#1E40AF",brandLight: "#EFF6FF",brandDeep: "#1E3A8A",success: "#16A34A",gray50: "#F9FAFB",gray100: "#F3F4FB",gray200: "#E5E7EB",gray300: "#D1D5DB",gray400: "#9CA3AF",gray500: "#6B7280",gray600: "#4B5563",gray700: "#374151",gray800: "#1F2937",gray900: "#111827",};const ITEMS_PER_PAGE = 4;interface KnowledgeBaseProps {onNewTicket?: () => void;}export const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ onNewTicket }) => {const [articles, setArticles] = useState<any[]>([]);const [categories, setCategories] = useState<string[]>([]);const [loading, setLoading] = useState(true);const [search, setSearch] = useState("");const [searchInput, setSearchInput] = useState("");const [suggestions, setSuggestions] = useState<string[]>([]);const [activeCategory, setActiveCategory] = useState<string | null>(null);const [sortBy, setSortBy] = useState<"newest" | "oldest">("newest");const [page, setPage] = useState(1);const [selectedArticle, setSelectedArticle] = useState<any | null>(null);// Pinpoint Engine Stateconst [aiAnswer, setAiAnswer] = useState<string | null>(null);const [isAiSynthetic, setIsAiSynthetic] = useState(false);useEffect(() => {fetchCategories();}, []);useEffect(() => {const delayDebounceFn = setTimeout(() => {fetchArticles();}, search ? 400 : 0);return () => clearTimeout(delayDebounceFn);}, [search, activeCategory, sortBy]);// Reactive Search ResetuseEffect(() => {if (searchInput.trim() === "") {setSearch("");setAiAnswer(null);setSuggestions([]);setIsAiSynthetic(false);}}, [searchInput]);const fetchCategories = async () => {try {const res = await api.get('kb/categories/');setCategories(res.data || []);} catch (err) {console.error("Failed to load categories:", err);}};const fetchArticles = async () => {setLoading(true);try {let res;if (search.trim().length > 1) {res = await api.get('kb/search/', { params: { q: search, category: activeCategory } });setArticles(res.data.results || []);setSuggestions(res.data.expanded_queries || []);setAiAnswer(res.data.answer || null);setIsAiSynthetic(res.data.is_ai_synthetic || false);} else {res = await api.get('kb/', { params: { category: activeCategory } });let data = res.data || [];data.sort((a: any, b: any) => {const dateA = new Date(a.created_at).getTime();const dateB = new Date(b.created_at).getTime();return sortBy === "newest" ? dateB - dateA : dateA - dateB;});setArticles(data);setSuggestions([]);setAiAnswer(null);setIsAiSynthetic(false);}setPage(1);} catch (err) {console.error("Failed to load KB articles:", err);} finally {setLoading(false);}};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 (<div style={{ padding: "40px 60px", maxWidth: 900, margin: "0 auto", animation: "fadeIn 0.4s ease-out" }}><buttononClick={() => setSelectedArticle(null)}style={{background: "none", border: "none", color: COLORS.brand, fontWeight: 700,fontSize: 14, cursor: "pointer", marginBottom: 32, display: "flex", alignItems: "center", gap: 8}}><ChevronLeft size={16} /> Back to Library</button><div style={{ marginBottom: 40 }}><div style={{ display: "flex", gap: 12, alignItems: "center", marginBottom: 16 }}><span style={{ fontSize: 11, fontWeight: 800, color: COLORS.brand, textTransform: "uppercase", letterSpacing: "0.05em", background: COLORS.brandLight, padding: "4px 10px", borderRadius: 6 }}>{selectedArticle.category || "N/A"}</span><span style={{ fontSize: 13, color: COLORS.gray500 }}>Published by <strong>Admin</strong> • {new Date(selectedArticle.created_at).toLocaleDateString()}</span></div><h1 style={{ fontSize: 42, fontWeight: 800, color: COLORS.gray900, lineHeight: 1.1, marginBottom: 24, letterSpacing: "-0.02em" }}>{selectedArticle.title}</h1><div style={{ width: 60, height: 4, background: COLORS.brand, borderRadius: 2 }} /></div>{/* AI Insight Section (Article Detail) */}{selectedArticle.summary && (<div style={{background: "linear-gradient(135deg, #F0F7FF 0%, #F5F3FF 100%)",border: `1px solid ${COLORS.brand}15`,borderRadius: 16,padding: "24px 32px",marginBottom: 48,position: "relative",overflow: "hidden",boxShadow: "0 4px 20px rgba(30, 64, 175, 0.04)"}}><div style={{position: "absolute", left: 0, top: 0, width: 4, height: "100%", background: COLORS.brand}} /><div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}><Sparkles size={16} color={COLORS.brand} /><span style={{ fontSize: 11, fontWeight: 900, color: COLORS.brand, letterSpacing: "0.1em", textTransform: "uppercase" }}>AI GENERATED SUMMARY</span></div><div style={{fontSize: 16, lineHeight: 1.7, color: COLORS.gray800, fontWeight: 500, fontStyle: "italic", margin: 0}}><NexusMarkdown content={selectedArticle.summary} /></div></div>)}<div style={{fontSize: 18, color: COLORS.gray800, lineHeight: 1.8,fontFamily: "'Inter', sans-serif", borderTop: `1px solid ${COLORS.gray100}`, paddingTop: 40,wordBreak: "break-word", overflowWrap: "anywhere"}}><NexusMarkdown content={selectedArticle.content} /></div><div style={{ marginTop: 60, padding: 32, background: COLORS.gray50, borderRadius: 16, textAlign: "center", border: `1px dashed ${COLORS.gray300}` }}><div style={{ fontSize: 18, fontWeight: 700, color: COLORS.gray900, marginBottom: 8 }}>Found this guide useful?</div><div style={{ fontSize: 14, color: COLORS.gray600, marginBottom: 24 }}>If you still need assistance, our support team is available 24/7.</div><buttononClick={onNewTicket}style={{ background: COLORS.brand, color: "#fff", border: "none", padding: "12px 24px", borderRadius: 10, cursor: "pointer", fontWeight: 700, boxShadow: "0 4px 12px rgba(30,64,175,0.2)" }}>Submit a Support Ticket</button></div></div>);}return (<div style={{ padding: "32px 48px" }}>{/* Search Hero */}<div style={{ marginBottom: 48 }}><h1 style={{ fontSize: 32, fontWeight: 800, color: COLORS.gray900, marginBottom: 8, letterSpacing: "-0.02em" }}>Knowledge Base</h1><p style={{ color: COLORS.gray500, fontSize: 15, marginBottom: 32 }}>Expert guides and troubleshooting for everything Nexus.</p><div style={{ display: "flex", gap: 20, alignItems: "center", flexWrap: "wrap" }}><div style={{ position: "relative", flex: 1, minWidth: 320 }}><inputvalue={searchInput}onChange={e => setSearchInput(e.target.value)}onKeyDown={e => {if (e.key === 'Enter') setSearch(searchInput);}}placeholder="How can we help you today?"style={{width: "100%", padding: "16px 20px 16px 52px", borderRadius: 16, border: `1px solid ${COLORS.gray200}`,fontSize: 16, boxSizing: "border-box", outline: "none", boxShadow: "0 2px 10px rgba(0,0,0,0.03)"}}/><buttononClick={() => setSearch(searchInput)}style={{position: "absolute", right: 12, top: "50%", transform: "translateY(-50%)",background: COLORS.brand, color: "#fff", border: "none", padding: "8px 16px",borderRadius: 10, cursor: "pointer", fontSize: 13, fontWeight: 700}}><Search size={14} style={{ display: 'inline', marginRight: 6 }} />Search</button><Search size={20} color={COLORS.gray400} style={{ position: "absolute", left: 20, top: "50%", transform: "translateY(-50%)" }} /></div><div style={{ display: "flex", gap: 12, alignItems: "center" }}><span style={{ fontSize: 11, fontWeight: 800, color: COLORS.gray400, letterSpacing: "0.05em" }}>SORT BY:</span><selectvalue={sortBy}onChange={e => setSortBy(e.target.value as any)}style={{ padding: "12px 16px", borderRadius: 12, border: `1px solid ${COLORS.gray200}`, background: "#fff", fontSize: 13, fontWeight: 600, color: COLORS.gray700, outline: "none", cursor: "pointer" }}><option value="newest">Newest First</option><option value="oldest">Oldest First</option></select></div></div>{suggestions.length > 0 && (<div style={{ marginTop: 20, display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}><span style={{ fontSize: 11, fontWeight: 800, color: COLORS.brand, textTransform: "uppercase", letterSpacing: "0.05em" }}>Suggestions:</span>{suggestions.map(s => (<buttonkey={s}onClick={() => { setSearchInput(s); setSearch(s); }}style={{ padding: "6px 14px", borderRadius: 20, border: `1px solid ${COLORS.brand}22`, background: COLORS.brandLight, color: COLORS.brand, fontSize: 12, fontWeight: 600, cursor: "pointer" }}>{s}</button>))}</div>)}</div>{/* Category Toolbar */}<div style={{ display: "flex", gap: 12, marginBottom: 40, borderBottom: `1px solid ${COLORS.gray100}`, paddingBottom: 16, overflowX: "auto" }}><buttononClick={() => setActiveCategory(null)}style={{ padding: "8px 0", border: "none", background: "none", color: !activeCategory ? COLORS.brand : COLORS.gray500, fontSize: 14, fontWeight: 700, cursor: "pointer", borderBottom: !activeCategory ? `2px solid ${COLORS.brand}` : "none", marginRight: 24 }}>All Documentation</button>{categories.map(cat => (<buttonkey={cat}onClick={() => setActiveCategory(activeCategory === cat ? null : cat)}style={{ padding: "8px 0", border: "none", background: "none", color: activeCategory === cat ? COLORS.brand : COLORS.gray500, fontSize: 14, fontWeight: 600, cursor: "pointer", borderBottom: activeCategory === cat ? `2px solid ${COLORS.brand}` : "none", marginRight: 24, whiteSpace: "nowrap" }}>{cat}</button>))}</div>{/* AI Spotlight Section (Search Results) */}{aiAnswer && (<div style={{maxWidth: 1100, margin: "0 auto 48px",background: "white",border: `1px solid ${COLORS.gray200}`,borderRadius: 20,padding: 40,position: "relative",boxShadow: "0 4px 20px rgba(0,0,0,0.02)"}}><div style={{ position: "absolute", top: 0, left: 0, width: "100%", height: 3, background: COLORS.brand, borderRadius: "20px 20px 0 0" }} /><div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 24 }}><div style={{ display: "flex", alignItems: "center", gap: 10, background: COLORS.brandLight, padding: "6px 14px", borderRadius: 8 }}><div style={{ display: "flex", alignItems: "center", gap: 8 }}><Sparkles size={16} color={COLORS.brand} /><span style={{ fontSize: 11, fontWeight: 900, color: COLORS.brand, letterSpacing: "0.1em", textTransform: "uppercase" }}>AI DIRECT ANSWER</span></div></div>{isAiSynthetic && (<span style={{ fontSize: 10, fontWeight: 800, color: "#16A34A", background: "#F0FDF4", padding: "4px 8px", borderRadius: 4 }}>REAL-TIME SYNTHESIS</span>)}</div><div style={{ fontSize: 18, lineHeight: 1.8, color: COLORS.gray900, fontWeight: 600, fontStyle: "italic", margin: 0 }}><NexusMarkdown content={aiAnswer} /></div><div style={{ marginTop: 24, paddingTop: 20, borderTop: `1px solid ${COLORS.gray100}`, fontSize: 11, fontWeight: 700, color: COLORS.gray400, textTransform: "uppercase", letterSpacing: "0.1em" }}>Reference guides found below</div></div>)}{/* Article Feed */}<div style={{ maxWidth: 1100, margin: "0 auto" }}>{loading ? (<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(440px, 1fr))", gap: 32 }}>{[1, 2, 3, 4].map(i => (<div key={i} style={{ background: "#fff", border: `1px solid ${COLORS.gray100}`, borderRadius: 20, padding: 32 }}><Skeleton width="30%" height={12} marginBottom={16} /><Skeleton width="80%" height={24} marginBottom={12} /><Skeleton width="100%" height={16} marginBottom={8} /><Skeleton width="100%" height={16} marginBottom={8} /><Skeleton width="60%" height={16} marginBottom={24} /><div style={{ display: "flex", justifyContent: "space-between", borderTop: `1px solid ${COLORS.gray50}`, paddingTop: 24 }}><Skeleton width="40%" height={12} /><Skeleton width="20%" height={12} /></div></div>))}</div>) : articles.length === 0 ? (<div style={{ padding: "100px 0", textAlign: "center" }}><div style={{ fontSize: 48, marginBottom: 20 }}>🔍</div><h3 style={{ fontSize: 20, fontWeight: 700, color: COLORS.gray900, marginBottom: 8 }}>We couldn't find that</h3><p style={{ color: COLORS.gray500, fontSize: 14 }}>Try searching for broader terms or check a different category.</p></div>) : (<><div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(440px, 1fr))", gap: 32 }}>{paginated.map(article => (<divkey={article.id}onClick={() => setSelectedArticle(article)}style={{ cursor: "pointer", display: "flex" }}><div style={{background: "#fff", border: `1px solid ${COLORS.gray100}`, borderRadius: 20, padding: 32, transition: "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",boxShadow: "0 2px 4px rgba(0,0,0,0.02)", display: "flex", flexDirection: "column", flex: 1, height: "100%"}}onMouseEnter={e => {e.currentTarget.style.transform = "translateY(-4px)";e.currentTarget.style.boxShadow = "0 20px 25px -5px rgba(0, 0, 0, 0.05), 0 10px 10px -5px rgba(0, 0, 0, 0.04)";e.currentTarget.style.borderColor = COLORS.brand;}}onMouseLeave={e => {e.currentTarget.style.transform = "none";e.currentTarget.style.boxShadow = "0 2px 4px rgba(0,0,0,0.02)";e.currentTarget.style.borderColor = COLORS.gray100;}}><div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}><span style={{ fontSize: 10, fontWeight: 800, color: COLORS.brand, textTransform: "uppercase", letterSpacing: "0.1em" }}>{article.category || "N/A"}</span>{article.score && (<span style={{ fontSize: 10, fontWeight: 800, color: article.score > 80 ? COLORS.success : COLORS.brand, background: article.score > 80 ? "#F0FDF4" : COLORS.brandLight, padding: "2px 8px", borderRadius: 4 }}>{article.score.toFixed(0)}% MATCH</span>)}</div><h3 style={{ fontSize: 22, fontWeight: 800, color: COLORS.gray900, marginBottom: 12, lineHeight: 1.2, wordBreak: "break-word", overflowWrap: "anywhere" }}>{article.title}</h3><p style={{fontSize: 15, color: COLORS.gray600, lineHeight: 1.6, marginBottom: 24,display: "-webkit-box", WebkitLineClamp: 3, WebkitBoxOrient: "vertical", overflow: "hidden",wordBreak: "break-word", overflowWrap: "anywhere"}}>{article.snippet ? (<span><strong style={{ color: COLORS.brand, fontSize: 11, marginRight: 6 }}>[MATCH]</strong> {article.snippet}</span>) : article.summary ? (<span><Sparkles size={12} style={{ display: "inline", marginRight: 6, verticalAlign: "middle" }} color={COLORS.brand} /> {article.summary}</span>) : article.content.replace(/[#*`]/g, '').slice(0, 180)}...</p><div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", borderTop: `1px solid ${COLORS.gray50}`, paddingTop: 24, marginTop: "auto" }}><span style={{ fontSize: 12, color: COLORS.gray400, fontWeight: 500 }}>Published {new Date(article.created_at).toLocaleDateString()}</span><span style={{ fontSize: 13, fontWeight: 700, color: COLORS.brand }}>Read Guide →</span></div></div></div>))}</div>{totalPages > 1 && (<div style={{ display: "flex", justifyContent: "center", alignItems: "center", gap: 24, marginTop: 60 }}><buttondisabled={page === 1}onClick={() => setPage(p => p - 1)}style={{ padding: "10px 24px", borderRadius: 12, border: `1px solid ${COLORS.gray200}`, background: "#fff", fontWeight: 700, fontSize: 14, color: page === 1 ? COLORS.gray300 : COLORS.gray900, cursor: page === 1 ? "default" : "pointer" }}><ChevronLeft size={16} /></button><div style={{ fontSize: 14, fontWeight: 600, color: COLORS.gray600 }}>Page {page} of {totalPages}</div><buttondisabled={page === totalPages}onClick={() => setPage(p => p + 1)}style={{ padding: "10px 24px", borderRadius: 12, border: `1px solid ${COLORS.gray200}`, background: "#fff", fontWeight: 700, fontSize: 14, color: page === totalPages ? COLORS.gray300 : COLORS.gray900, cursor: page === totalPages ? "default" : "pointer" }}><ChevronRight size={16} /></button>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407import React, { useState, useEffect, useCallback, useRef } 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 { motion, AnimatePresence } from 'framer-motion';import { Search, ChevronLeft, ChevronRight, Sparkles, Zap, Info, Radio, Clock, User as UserIcon } from 'lucide-react';import { api } from '@nexus/shared';import mermaid from 'mermaid';import styles from './KnowledgeBase.module.css';// Initialize Mermaidmermaid.initialize({startOnLoad: true,theme: 'dark',securityLevel: 'loose',});// Mermaid Componentconst Mermaid: React.FC<{ chart: string }> = ({ chart }) => {const ref = useRef<HTMLDivElement>(null);useEffect(() => {if (ref.current && chart) {const id = `mermaid-${Math.random().toString(36).substr(2, 9)}`;mermaid.render(id, chart).then((res) => {if (ref.current) ref.current.innerHTML = res.svg;}).catch(err => {console.error("Mermaid render failed:", err);});}}, [chart]);return <div ref={ref} className={styles.mermaidContainer} />;};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 {onNewTicket?: () => void;}export const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ onNewTicket }) => {const [articles, setArticles] = useState<Article[]>([]);const [categories, setCategories] = useState<string[]>(['All Documentation']);const [loading, setLoading] = useState(true);const [isScanning, setIsScanning] = useState(false);// Search Stateconst [searchInput, setSearchInput] = useState('');const [activeQuery, setActiveQuery] = useState('');const [selectedCategory, setSelectedCategory] = useState('All Documentation');// AI Direct Answer Stateconst [aiAnswer, setAiAnswer] = useState<string | null>(null);const [isAiSynthetic, setIsAiSynthetic] = useState(false);const [suggestions, setSuggestions] = useState<string[]>([]);const [aiSuggestion, setAiSuggestion] = useState<string | null>(null);// UI Stateconst [page, setPage] = useState(1);const ITEMS_PER_PAGE = 4;const [selectedArticle, setSelectedArticle] = useState<Article | null>(null);const [sortBy, setSortBy] = useState<'newest' | 'oldest'>('newest');const fetchCategories = useCallback(async () => {try {const resp = await api.get('kb/categories/');setCategories(['All Documentation', ...resp.data]);} catch (err) {console.error('Failed to fetch categories:', err);}}, []);const fetchArticles = useCallback(async (query: string = '', cat: string = 'All Documentation') => {setLoading(true);if (query.length > 0) setIsScanning(true);try {const params: any = {};if (cat !== 'All Documentation') 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 });let data = resp.data || [];data.sort((a: any, b: any) => {const dateA = new Date(a.created_at).getTime();const dateB = new Date(b.created_at).getTime();return sortBy === 'newest' ? dateB - dateA : dateA - dateB;});setArticles(data);setSuggestions([]);setAiAnswer(null);setIsAiSynthetic(false);setAiSuggestion(null);}setPage(1);} catch (err) {console.error('Failed to fetch articles:', err);} finally {setLoading(false);setIsScanning(false);}}, [sortBy]);useEffect(() => {fetchCategories();fetchArticles('', 'All Documentation');}, [fetchCategories, fetchArticles]);// Reactive Search ResetuseEffect(() => {if (searchInput.trim() === '') {setActiveQuery('');if (articles.length > 0 && activeQuery !== '') {fetchArticles('', selectedCategory);}}}, [searchInput, selectedCategory, fetchArticles]);const handleSearchTrigger = (e?: React.FormEvent) => {if (e) e.preventDefault();setActiveQuery(searchInput);fetchArticles(searchInput, selectedCategory);};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.divclassName={styles.articleDetail}initial={{ opacity: 0, y: 10 }}animate={{ opacity: 1, y: 0 }}><button className={styles.backBtn} onClick={() => setSelectedArticle(null)}><ChevronLeft size={16} /> Back to Library</button><header style={{ marginBottom: 40 }}><div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 16 }}><span className={styles.categoryBadge}>{selectedArticle.category || 'General'}</span><div style={{ display: 'flex', alignItems: 'center', gap: 6, color: '#6B7280', fontSize: 13 }}><UserIcon size={14} /> <span>Admin</span><Clock size={14} style={{ marginLeft: 8 }} /><span>{new Date(selectedArticle.created_at).toLocaleDateString()}</span></div></div><h1 className={styles.articleTitle} style={{ fontSize: 42 }}>{selectedArticle.title}</h1><div style={{ width: 60, height: 4, background: '#1E40AF', borderRadius: 2, marginTop: 24 }} /></header>{selectedArticle.summary && (<div className={styles.aiSpotlight} style={{ margin: '0 0 48px 0', padding: '24px 32px' }}><div className={styles.spotlightHeader} style={{ marginBottom: 16 }}><div className={styles.spotlightBadge}><Sparkles size={14} /> AI GENERATED SUMMARY</div></div><p className={styles.answerText} style={{ fontSize: 16 }}>{selectedArticle.summary}</p></div>)}<div className={styles.markdownContent}><ReactMarkdownremarkPlugins={[remarkGfm]}components={{code({node, inline, className, children, ...props}: any) {const match = /language-(\w+)/.exec(className || '');if (!inline && match && match[1] === 'mermaid') {return <Mermaid chart={String(children)} />;}return !inline && match ? (<SyntaxHighlighterstyle={vscDarkPlus}language={match[1]}PreTag="div"{...props}>{String(children).replace(/\n$/, '')}</SyntaxHighlighter>) : (<code className={className} {...props}>{children}</code>);}}}>{selectedArticle.content}</ReactMarkdown></div><div style={{ marginTop: 60, padding: 32, background: '#F9FAFB', borderRadius: 16, textAlign: 'center', border: '1px dashed #D1D5DB' }}><h3 style={{ fontSize: 18, fontWeight: 700, color: '#111827', marginBottom: 8 }}>Found this guide useful?</h3><p style={{ fontSize: 14, color: '#4B5563', marginBottom: 24 }}>If you still need assistance, our support team is available 24/7.</p><buttononClick={onNewTicket}style={{ background: '#1E40AF', color: '#fff', border: 'none', padding: '12px 24px', borderRadius: 10, cursor: 'pointer', fontWeight: 700, boxShadow: '0 4px 12px rgba(30,64,175,0.2)' }}>Submit a Support Ticket</button></div></motion.div>);}return (<div className={styles.container}><header className={styles.searchHero}><h1>Knowledge Base</h1><p className={styles.description}>Expert guides and troubleshooting for everything Nexus.</p><form className={styles.searchControls} onSubmit={handleSearchTrigger}><div className={styles.searchWrapper}><Search className={styles.searchIcon} size={20} /><inputtype="text"className={styles.searchInput}placeholder="How can we help you today?"value={searchInput}onChange={(e) => setSearchInput(e.target.value)}/>{isScanning && (<div className={styles.searchPulse}><Radio size={14} className={styles.pulseIcon} /><span>NEURAL SCANNING</span></div>)}<button type="submit" className={styles.searchBtn}>Search</button></div><div style={{ display: 'flex', gap: 12, alignItems: 'center' }}><span style={{ fontSize: 11, fontWeight: 800, color: '#9CA3AF', letterSpacing: '0.05em' }}>SORT BY:</span><selectclassName={styles.navItem}style={{ padding: '8px 12px', background: '#fff', border: '1px solid #E5E7EB', borderRadius: 8, marginRight: 0 }}value={sortBy}onChange={e => setSortBy(e.target.value as any)}><option value="newest">Newest First</option><option value="oldest">Oldest First</option></select></div></form><AnimatePresence>{suggestions.length > 0 && (<motion.divclassName={styles.suggestions}initial={{ opacity: 0, y: -10 }}animate={{ opacity: 1, y: 0 }}style={{ marginTop: 24, display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}><span className={styles.categoryBadge}>Suggestions:</span>{suggestions.map(s => (<buttonkey={s}onClick={() => { setSearchInput(s); fetchArticles(s, selectedCategory); }}className={styles.regularMatch}style={{ padding: '6px 14px', borderRadius: 20, border: '1px solid #1E40AF22', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>{s}</button>))}</motion.div>)}</AnimatePresence></header><nav className={styles.categoryNav}>{categories.map(cat => (<buttonkey={cat}className={`${styles.navItem} ${selectedCategory === cat ? styles.navItemActive : ''}`}onClick={() => { setSelectedCategory(cat); fetchArticles(activeQuery, cat); }}>{cat}</button>))}</nav><div className={styles.resultsContainer}><AnimatePresence mode="wait">{aiAnswer && (<motion.divclassName={styles.aiSpotlight}initial={{ opacity: 0, y: 20 }}animate={{ opacity: 1, y: 0 }}exit={{ opacity: 0, scale: 0.95 }}><div className={styles.spotlightHeader}><div className={styles.spotlightBadge}><Sparkles size={14} /> AI DIRECT ANSWER</div>{isAiSynthetic && <span className={styles.syntheticFlag}>REAL-TIME SYNTHESIS</span>}</div><p className={styles.answerText}>{aiAnswer}</p><div className={styles.spotlightFooter}>Based on the documentation below.</div></motion.div>)}</AnimatePresence>{loading && articles.length === 0 ? (<div className={styles.articlesGrid}>{[1, 2, 3, 4].map(i => (<div key={i} className={styles.articleCard} style={{ opacity: 0.5 }}><div style={{ height: 12, width: '30%', background: '#F3F4F6', borderRadius: 4, marginBottom: 16 }} /><div style={{ height: 24, width: '80%', background: '#F3F4F6', borderRadius: 4, marginBottom: 12 }} /><div style={{ height: 16, width: '100%', background: '#F3F4F6', borderRadius: 4, marginBottom: 8 }} /><div style={{ height: 16, width: '60%', background: '#F3F4F6', borderRadius: 4, marginBottom: 24 }} /></div>))}</div>) : articles.length === 0 ? (<motion.divinitial={{ opacity: 0 }}animate={{ opacity: 1 }}style={{ padding: '100px 0', textAlign: 'center' }}><div style={{ fontSize: 48, marginBottom: 20 }}>🔍</div><h3 style={{ fontSize: 20, fontWeight: 700, color: '#111827', marginBottom: 8 }}>We couldn't find that</h3>{aiSuggestion && (<div style={{ marginTop: 16, color: '#6B7280' }}>Did you mean: <button onClick={() => { setSearchInput(aiSuggestion); fetchArticles(aiSuggestion, selectedCategory); }} style={{ color: '#1E40AF', fontWeight: 700, background: 'none', border: 'none', cursor: 'pointer' }}>{aiSuggestion}</button>?</div>)}</motion.div>) : (<><motion.divclassName={styles.articlesGrid}initial={{ opacity: 0 }}animate={{ opacity: 1 }}>{paginated.map((article, i) => (<motion.divkey={article.id}className={styles.articleCard}initial={{ opacity: 0, y: 20 }}animate={{ opacity: 1, y: 0 }}transition={{ delay: i * 0.05 }}onClick={() => setSelectedArticle(article)}><div className={styles.cardHeader}><span className={styles.categoryBadge}>{article.category || 'General'}</span>{article.score && (<span className={`${styles.matchBadge} ${article.score > 80 ? styles.highMatch : styles.regularMatch}`}>{Math.round(article.score)}% MATCH</span>)}</div><h3 className={styles.articleTitle}>{article.title}</h3><p className={styles.articleSnippet}>{article.snippet ? (<span><strong style={{ color: '#1E40AF', fontSize: 11, marginRight: 6 }}>[MATCH]</strong> {article.snippet}</span>) : article.summary || article.content.replace(/[#*`]/g, '').slice(0, 160) + '...'}</p><div className={styles.cardFooter}><span className={styles.articleDate}>Published {new Date(article.created_at).toLocaleDateString()}</span><span className={styles.readMore}>Read Guide →</span></div></motion.div>))}</motion.div>{totalPages > 1 && (<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 24, marginTop: 60 }}><buttondisabled={page === 1}onClick={() => setPage(p => p - 1)}className={styles.navItem}style={{ border: '1px solid #E5E7EB', borderRadius: 12, padding: '10px 24px', opacity: page === 1 ? 0.3 : 1 }}><ChevronLeft size={16} /></button><div style={{ fontSize: 14, fontWeight: 600, color: '#6B7280' }}>Page {page} of {totalPages}</div><buttondisabled={page === totalPages}onClick={() => setPage(p => p + 1)}className={styles.navItem}style={{ border: '1px solid #E5E7EB', borderRadius: 12, padding: '10px 24px', opacity: page === totalPages ? 0.3 : 1 }}><ChevronRight size={16} /></button>
4 unmodified lines56789104 unmodified lines// https://vite.dev/config/export default defineConfig({plugins: [react(), tsconfigPaths()],server: {port: 5174}4 unmodified lines5678910114 unmodified lines// https://vite.dev/config/export default defineConfig({plugins: [react(), tsconfigPaths()],base: '/admin/',server: {port: 5174}
34 unmodified lines35363738394068 unmodified lines10911011111211311411528 unmodified lines14414514614714814915015115215315415515615715815916016116216316416534 unmodified linescategories: Record<string, number>;}// Global singleton state for dashboard stats to ensure UI consistencylet globalStats: DashboardStats | null = null;let globalStatsLoading = false;68 unmodified linesvolume: VolumeTrend | null;daily: DailyStat[];sla: SLAMetrics | null;} = { volume: null, daily: [], sla: null };let globalReportsLoading = false;let globalReportsError: string | null = null;const reportsListeners = new Set<(r: typeof globalReports, l: boolean, e: string | null) => void>();28 unmodified lineslet slaUrl = workspaceId ? `reports/sla/?workspace_id=${workspaceId}` : 'reports/sla/';let dailyUrl = workspaceId ? `reports/daily-stats/?workspace_id=${workspaceId}` : 'reports/daily-stats/';if (force) {const flag = (u: string) => u + (u.includes('?') ? '&' : '?') + 'refresh=true';volUrl = flag(volUrl);slaUrl = flag(slaUrl);dailyUrl = flag(dailyUrl);}const [volRes, slaRes, dRes] = await Promise.all([api.get(volUrl),api.get(slaUrl),api.get(dailyUrl)]);globalReports = {volume: volRes.data,sla: slaRes.data,daily: dRes.data};globalReportsError = null;} catch (err: any) {34 unmodified lines353637383940414243444568 unmodified lines11411511611711811912012128 unmodified lines15015115215315415515615715815916016116216316416516616716816917017117217317417517634 unmodified linescategories: Record<string, number>;}export interface CSATMetrics {average_rating: number;total_responses: number;}// Global singleton state for dashboard stats to ensure UI consistencylet globalStats: DashboardStats | null = null;let globalStatsLoading = false;68 unmodified linesvolume: VolumeTrend | null;daily: DailyStat[];sla: SLAMetrics | null;csat: CSATMetrics | null;} = { volume: null, daily: [], sla: null, csat: null };let globalReportsLoading = false;let globalReportsError: string | null = null;const reportsListeners = new Set<(r: typeof globalReports, l: boolean, e: string | null) => void>();28 unmodified lineslet slaUrl = workspaceId ? `reports/sla/?workspace_id=${workspaceId}` : 'reports/sla/';let dailyUrl = workspaceId ? `reports/daily-stats/?workspace_id=${workspaceId}` : 'reports/daily-stats/';let csatUrl = workspaceId ? `reports/csat/?workspace_id=${workspaceId}` : 'reports/csat/';if (force) {const flag = (u: string) => u + (u.includes('?') ? '&' : '?') + 'refresh=true';volUrl = flag(volUrl);slaUrl = flag(slaUrl);dailyUrl = flag(dailyUrl);csatUrl = flag(csatUrl);}const [volRes, slaRes, dRes, csatRes] = await Promise.all([api.get(volUrl),api.get(slaUrl),api.get(dailyUrl),api.get(csatUrl)]);globalReports = {volume: volRes.data,sla: slaRes.data,daily: dRes.data,csat: csatRes.data};globalReportsError = null;} catch (err: any) {
12345678910111213141516import axios from 'axios';const rawBaseUrl = import.meta.env.VITE_API_URL || 'http://localhost:8000/api/v1';// Intelligent URL Normalization:// 1. Ensure it starts with http/https// 2. Ensure it includes the /api/v1 suffix if missing// 3. Ensure it DOES NOT have a double slashlet sanitizedBaseUrl = rawBaseUrl.trim();// Special Case: Tunnel URL usually arrives without /api/v1if (!sanitizedBaseUrl.includes('/api/')) {sanitizedBaseUrl = sanitizedBaseUrl.endsWith('/') ? `${sanitizedBaseUrl}api/v1` : `${sanitizedBaseUrl}/api/v1`;}// Final trailing slash for clean joins12345678910111213141516import axios from 'axios';const rawBaseUrl = import.meta.env.VITE_API_URL ||(import.meta.env.DEV ? 'http://localhost:8000/api/v1' : '/api/v1');// Intelligent URL Normalization:let sanitizedBaseUrl = rawBaseUrl.trim();// Ensure absolute URLs have a protocol and /api/v1 suffixif (sanitizedBaseUrl.startsWith('http')) {if (!sanitizedBaseUrl.includes('/api/')) {sanitizedBaseUrl = sanitizedBaseUrl.endsWith('/') ? `${sanitizedBaseUrl}api/v1` : `${sanitizedBaseUrl}/api/v1`;}}// Final trailing slash for clean joins
151 unmodified lines152153154155156157158151 unmodified linesapp.include_router(reports.router, prefix=f"{settings.API_V1_STR}/reports", tags=["reports"])app.include_router(nexus.router, prefix=f"{settings.API_V1_STR}/nexus", tags=["Nexus Master Agent"])app.include_router(nexus_stream.router, prefix=f"{settings.API_V1_STR}/nexus", tags=["Nexus Master Agent"])app.include_router(system.router, prefix=f"{settings.API_V1_STR}/system", tags=["System Diagnostics"])app.include_router(websockets.router, tags=["websockets"])151 unmodified lines152153154155156157158159160161162163164165166167168151 unmodified linesapp.include_router(reports.router, prefix=f"{settings.API_V1_STR}/reports", tags=["reports"])app.include_router(nexus.router, prefix=f"{settings.API_V1_STR}/nexus", tags=["Nexus Master Agent"])app.include_router(nexus_stream.router, prefix=f"{settings.API_V1_STR}/nexus", tags=["Nexus Master Agent"])import osfrom fastapi.staticfiles import StaticFiles# --- UNIFIED PORTAL HOSTING ---# Serve Customer Portal at / and Internal Portal at /adminBASE_DIR = os.path.dirname(os.path.abspath(__file__))FRONTEND_CUSTOMER_PATH = os.path.join(BASE_DIR, "frontend/apps/customer/dist")FRONTEND_INTERNAL_PATH = os.path.join(BASE_DIR, "frontend/apps/internal/dist")# Note: Mounting Internal BEFORE Customer to avoid catch-all collisionsapp.mount("/admin", StaticFiles(directory=FRONTEND_INTERNAL_PATH, html=True), name="internal")app.mount("/", StaticFiles(directory=FRONTEND_CUSTOMER_PATH, html=True), name="customer")
4 unmodified lines56789104 unmodified linesecho "--- NEXUS PRODUCTION BOOTSTRAP ---"# Start Arq Worker in the backgroundecho "[1/2] Starting Nexus AI Worker (arq)..."# Persistence Mapping: Use the /data mount if available4 unmodified lines5678910111213144 unmodified linesecho "--- NEXUS PRODUCTION BOOTSTRAP ---"# Start Local Redis for Caching (Ephemeral)echo "[0/3] Starting Local Redis..."redis-server --daemonize yes --port 6379# Start Arq Worker in the backgroundecho "[1/2] Starting Nexus AI Worker (arq)..."# Persistence Mapping: Use the /data mount if available
Dockerfile+32-26
README.md+21-11
core/config.py+8-1
frontend/apps/customer/src/components/Analytics.tsx+6-4
frontend/apps/customer/src/components/KnowledgeBase.module.cssAdded+352
frontend/apps/customer/src/components/KnowledgeBase.tsx+291-286
frontend/apps/internal/vite.config.ts+1
frontend/packages/shared/src/hooks/useDashboard.ts+15-4
frontend/packages/shared/src/utils/api.ts+7-7
main.py+12-2
scripts/run_prod.sh+4