Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit Β·
dfcbb7c
1
Parent(s): 951cf3b
backend stabilization
Browse filesFiles changed (12)
- api/v1/dashboard.py+36-11
- api/v1/kb.py+62-2
- api/v1/reports.py+70-8
- frontend/apps/customer/package.json+1
- frontend/apps/customer/src/components/KnowledgeBase.tsx+89-5
- frontend/apps/internal/src/components/KnowledgeBase.module.css+80
- frontend/apps/internal/src/components/KnowledgeBase.tsx+52-8
- frontend/apps/internal/src/components/TopBar.module.css+46-10
- frontend/apps/internal/src/components/TopBar.tsx+32-18
- frontend/package-lock.json+6-7
- schemas/kb.py+4
- scripts/backfill_kb_summaries.pyAdded+58
33 unmodified lines34353637383738394041424041424344454647484950515253545556575859146 unmodified lines20620720819519619719819920020921021121221321421521621721821922022122222322422522622722833 unmodified lines is_super_admin = (current_user.role == UserRole.SC_ADMIN) is_global = False if is_super_admin: if workspace_id == "all": if workspace_id: if is_super_admin and workspace_id == "all": is_global = True elif workspace_id: target_ws = workspace_id else: # Multi-workspace Agent/Lead Check: Ensure they are authorized for the requested workspace if is_super_admin: target_ws = workspace_id else: from models.user_workspace import UserWorkspace ws_check = await db.execute( select(UserWorkspace).where( UserWorkspace.user_id == current_user.id, UserWorkspace.workspace_id == workspace_id ) ) if ws_check.scalar_one_or_none(): target_ws = workspace_id else: # Silently fallback to primary if not authorized, or raise 403 pass now = datetime.utcnow()
# 1. Basic Status Counts (Optimized SQL)146 unmodified lines target_ws = current_user.workspace_id is_super_admin = (current_user.role == UserRole.SC_ADMIN) is_global = (is_super_admin and workspace_id == "all") if is_super_admin and workspace_id and workspace_id != "all": target_ws = workspace_id elif not is_super_admin: target_ws = current_user.workspace_id is_global = False
if is_super_admin and workspace_id == "all": is_global = True elif workspace_id: if is_super_admin: target_ws = workspace_id else: from models.user_workspace import UserWorkspace ws_check = await db.execute( select(UserWorkspace).where( UserWorkspace.user_id == current_user.id, UserWorkspace.workspace_id == workspace_id ) ) if ws_check.scalar_one_or_none(): target_ws = workspace_id
stmt = ( select(Ticket)22 unmodified lines2324252626272829140 unmodified lines17017117217317417517681 unmodified lines25825926026126226326426526426626726826927027127227327427516 unmodified lines29229329429529629729829 unmodified lines32832933033133233333433533633733833934034134234334434534634744 unmodified lines3923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394402 unmodified lines44344444544644744844945022 unmodified linesfrom core.search import chunk_textfrom core.vision import extract_visual_contextfrom core.sync import sync_markdown_imagesfrom core.cache import generate_cache_key, get_cached_search, set_cached_searchfrom core.cache import generate_cache_key, get_cached_search, set_cached_search, SemanticCacheManagerfrom schemas.kb import KBArticleCreate, KBArticleResponse, KBArticleUpdate, KBSearchResponse, KBBulkActionRequest, KBBulkSyncRequest
router = APIRouter()140 unmodified lines semantic_stmt = ( select( KBArticle, KBArticleChunk.content, (1 - KBArticleChunk.embedding.cosine_distance(query_vector)).label("sim_score") ) .join(KBArticleChunk, KBArticle.id == KBArticleChunk.article_id)81 unmodified lines def apply_fusion(list_hits, weight, score_attr): for rank, row in enumerate(list_hits): art = row[0] chunk_txt = row[1] if len(row) > 2 else None # Only semantic hits have this # RRF formula with weights rrf_score = weight * (1.0 / (60 + rank + 1)) if art.id not in results_map: results_map[art.id] = {"obj": art, "score": rrf_score, "types": {score_attr}} results_map[art.id] = {"obj": art, "score": rrf_score, "types": {score_attr}, "chunk": chunk_txt} else: results_map[art.id]["score"] += rrf_score results_map[art.id]["types"].add(score_attr) # Keep the best chunk if we hit it again via keyword if not results_map[art.id]["chunk"] and chunk_txt: results_map[art.id]["chunk"] = chunk_txt
apply_fusion(hits, 0.5, "sim_score") apply_fusion(kw_hits, 0.3, "kw_score")16 unmodified lines "obj": art, "score": round(norm_score, 1), "type": m_type, "snippet": r["chunk"], "search_id": str(search_id) }
29 unmodified lines logger.info(f"β‘ Search Cache HIT [KB]: {q}") return cached_res # 0.5 Semantic Cache Check for pin-point Answer (if NL query) is_question = q.strip().endswith('?') or any(q.lower().startswith(w) for w in ["how", "what", "where", "why", "who", "tell"]) if is_question: sem_answer = await SemanticCacheManager.check_cache( str(current_user.workspace_id), q, is_agent=(current_user.role in ALL_SC_ROLES), user_role=current_user.role.value if hasattr(current_user.role, 'value') else str(current_user.role) ) if sem_answer: logger.info(f"π§ Semantic Cache HIT [KB]: {q}") # Still need the document results, but we'll return the answer from cache # For speed, if we have a semantic answer, we might still want to refresh the docs pass # We'll check again after doc retrieval # 1. Start Original Search Branch IMMEDIATELY (Don't wait for LLM) original_search_task = execute_multimodal_search(db, q, current_user, category, project_id) 44 unmodified lines res_dict = KBArticleResponse.model_validate(article_obj).model_dump() res_dict["score"] = score res_dict["match_type"] = data.get("type", "semantic") # Safe access to avoid KeyError res_dict["snippet"] = data.get("snippet") final_results.append(res_dict)
final_results.sort(key=lambda x: float(x.get("score") or 0.0), reverse=True) top_results = final_results[:5]
# 4.5 Synthesis Branch (The "Direct Answer" Engine) direct_answer = None is_ai_synthetic = False
if is_question and top_results: # Check semantic cache first (redundant but safe) direct_answer = await SemanticCacheManager.check_cache( str(current_user.workspace_id), q, is_agent=(current_user.role in ALL_SC_ROLES), user_role=current_user.role.value if hasattr(current_user.role, 'value') else str(current_user.role) ) if not direct_answer: # Construct context from top snippets context_txt = "\n\n".join([f"DOC {i+1} [{r['title']}]: {r['snippet'] or r['content'][:200]}" for i, r in enumerate(top_results)]) try: llm = get_llm() prompt = [ SystemMessage(content="You are a technical support expert. Provide a CONCISE 2-3 sentence direct answer based ONLY on the provided documentation context. If the answer isn't clear, say you don't know."), HumanMessage(content=f"Context:\n{context_txt}\n\nQuestion: {q}") ] synth_resp = await llm.ainvoke(prompt) direct_answer = synth_resp.content is_ai_synthetic = True # Persist to Semantic Cache import asyncio asyncio.create_task(SemanticCacheManager.set_cache( str(current_user.workspace_id), str(current_user.id), q, direct_answer, is_agent=(current_user.role in ALL_SC_ROLES), user_role=current_user.role.value if hasattr(current_user.role, 'value') else str(current_user.role) )) except Exception as e: logger.error(f"Synthesis failed: {e}") else: is_ai_synthetic = True
# 5. Suggestion for UI if results are still thin suggestion = expanded_queries[0] if expanded_queries and expanded_queries[0].lower() != q.lower() else None 2 unmodified lines
res_data = { "results": top_results, "answer": direct_answer, "is_ai_synthetic": is_ai_synthetic, "suggestion": suggestion if not top_results else None, "expanded_queries": expanded_queries, "search_time_s": round(search_time_s, 3)24 unmodified lines25262728293028293031323334353637383940414243444515 unmodified lines616263535464656667686970717273747576777879808113 unmodified lines95969775989910010110210310410510610710810911011111211311411549 unmodified lines16516616713216816917017117217317417517617717817918018118218318418550 unmodified lines23623723819023924024124224324424524624724824925025125225325425525624 unmodified lines) -> Any: """Get ticket volume trends over time.""" from models.workspace import Workspace is_staff = current_user.role in [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN] # Strictly enforce current user's workspace # Strictly enforce current user's workspace, allowing override for staff if they are authorized target_ws = current_user.workspace_id if workspace_id: if current_user.role == UserRole.SC_ADMIN: target_ws = workspace_id else: from models.user_workspace import UserWorkspace ws_check = await db.execute( select(UserWorkspace).where( UserWorkspace.user_id == current_user.id, UserWorkspace.workspace_id == workspace_id ) ) if ws_check.scalar_one_or_none(): target_ws = workspace_id
since = datetime.utcnow() - timedelta(days=days) stmt = (15 unmodified lines current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> Any: """Get CSAT score trends and average.""" # Strictly enforce current user's workspace # Strictly enforce current user's workspace, allowing override for authorized staff target_ws = current_user.workspace_id if workspace_id: if current_user.role == UserRole.SC_ADMIN: target_ws = workspace_id else: from models.user_workspace import UserWorkspace ws_check = await db.execute( select(UserWorkspace).where( UserWorkspace.user_id == current_user.id, UserWorkspace.workspace_id == workspace_id ) ) if ws_check.scalar_one_or_none(): target_ws = workspace_id
stmt = ( select(func.avg(Feedback.rating), func.count(Feedback.id))13 unmodified lines current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> Any: # Strictly enforce current user's workspace # Strictly enforce current user's workspace, allowing override for authorized staff target_ws = current_user.workspace_id if workspace_id: if current_user.role == UserRole.SC_ADMIN: target_ws = workspace_id else: from models.user_workspace import UserWorkspace ws_check = await db.execute( select(UserWorkspace).where( UserWorkspace.user_id == current_user.id, UserWorkspace.workspace_id == workspace_id ) ) if ws_check.scalar_one_or_none(): target_ws = workspace_id # Real logic: Join tickets with their priority-level escalation rules from models.escalation_rule import EscalationRule49 unmodified lines # 1. Get current SLA metrics metrics = await get_sla_compliance(workspace_id, current_user, db) # Strictly enforce current user's workspace # Strictly enforce current user's workspace, allowing override for Global Admin target_ws = current_user.workspace_id if workspace_id: if current_user.role == UserRole.SC_ADMIN: target_ws = workspace_id else: from models.user_workspace import UserWorkspace ws_check = await db.execute( select(UserWorkspace).where( UserWorkspace.user_id == current_user.id, UserWorkspace.workspace_id == workspace_id ) ) if ws_check.scalar_one_or_none(): target_ws = workspace_id # 2. Get recent tickets for context (last 48 hours only for SPEED) since_48h = datetime.utcnow() - timedelta(hours=48)50 unmodified lines db: AsyncSession = Depends(get_db)) -> Any: """Unified endpoint for daily trends and category distribution (last 30 days).""" # Strictly enforce current user's workspace # Strictly enforce current user's workspace, allowing override for Global Admin target_ws = current_user.workspace_id if workspace_id: if current_user.role == UserRole.SC_ADMIN: target_ws = workspace_id else: from models.user_workspace import UserWorkspace ws_check = await db.execute( select(UserWorkspace).where( UserWorkspace.user_id == current_user.id, UserWorkspace.workspace_id == workspace_id ) ) if ws_check.scalar_one_or_none(): target_ws = workspace_id
now = datetime.utcnow() since_30d = now - timedelta(days=30)10 unmodified lines1112131415161710 unmodified lines }, "dependencies": { "@nexus/shared": "*", "lucide-react": "^1.7.0", "mermaid": "^11.13.0", "react": "^19.2.4", "react-dom": "^19.2.4",12345678910111225 unmodified lines383940414243444546476 unmodified lines5455565758596061626364656667686911 unmodified lines81828384858687884 unmodified lines9394959697989910056 unmodified lines15715815914016016116216311 unmodified lines17517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820945 unmodified lines25525625725825926021126126226326444 unmodified lines30931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734849 unmodified lines39839940031740140240340411 unmodified lines4164174183354194204214221 unmodified line424425426343427428429430import React, { useState, useEffect } from 'react';import { api } 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",25 unmodified lines const [page, setPage] = useState(1); const [selectedArticle, setSelectedArticle] = useState<any | null>(null);
// Pinpoint Engine State const [aiAnswer, setAiAnswer] = useState<string | null>(null); const [isAiSynthetic, setIsAiSynthetic] = useState(false);
useEffect(() => { fetchCategories(); }, []);6 unmodified lines return () => clearTimeout(delayDebounceFn); }, [search, activeCategory, sortBy]);
// Reactive Search Reset useEffect(() => { if (searchInput.trim() === "") { setSearch(""); setAiAnswer(null); setSuggestions([]); setIsAiSynthetic(false); } }, [searchInput]);
const fetchCategories = async () => { try { const res = await api.get('kb/categories/');11 unmodified lines 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 || [];4 unmodified lines }); setArticles(data); setSuggestions([]); setAiAnswer(null); setIsAiSynthetic(false); } setPage(1); } catch (err) {56 unmodified lines fontSize: 14, cursor: "pointer", marginBottom: 32, display: "flex", alignItems: "center", gap: 8 }} > β Back to Library <ChevronLeft size={16} /> Back to Library </button>
<div style={{ marginBottom: 40 }}>11 unmodified lines <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> <p style={{ fontSize: 16, lineHeight: 1.7, color: COLORS.gray800, fontWeight: 500, fontStyle: "italic", margin: 0 }}> {selectedArticle.summary} </p> </div> )}
<div style={{ fontSize: 18, color: COLORS.gray800, lineHeight: 1.8, fontFamily: "'Inter', sans-serif", borderTop: `1px solid ${COLORS.gray100}`, paddingTop: 40,45 unmodified lines borderRadius: 10, cursor: "pointer", fontSize: 13, fontWeight: 700 }} > <Search size={14} style={{ display: 'inline', marginRight: 6 }} /> Search </button> <span style={{ position: "absolute", left: 20, top: "50%", transform: "translateY(-50%)", fontSize: 20, opacity: 0.4 }}>π</span> <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" }}>44 unmodified lines ))} </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 }}> <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> {isAiSynthetic && ( <span style={{ fontSize: 10, fontWeight: 800, color: "#16A34A", background: "#F0FDF4", padding: "4px 8px", borderRadius: 4 }}> REAL-TIME SYNTHESIS </span> )} </div> <p style={{ fontSize: 18, lineHeight: 1.8, color: COLORS.gray900, fontWeight: 600, fontStyle: "italic", margin: 0 }}> {aiAnswer} </p> <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 ? (49 unmodified lines display: "-webkit-box", WebkitLineClamp: 3, WebkitBoxOrient: "vertical", overflow: "hidden", wordBreak: "break-word", overflowWrap: "anywhere" }}> {article.summary || article.content.slice(0, 180)}... {article.snippet || article.summary || 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>11 unmodified lines 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" }} > Previous <ChevronLeft size={16} /> </button> <div style={{ fontSize: 14, fontWeight: 600, color: COLORS.gray600 }}>Page {page} of {totalPages}</div> <button 1 unmodified line 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" }} > Next <ChevronRight size={16} /> </button> </div> )}784 unmodified lines785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868784 unmodified lines background: #F1F5F9; padding: 2px 6px; border-radius: 4px;}
/* AI Answer Spotlight */.resultsContainer { display: flex; flex-direction: column; gap: 32px; width: 100%;}
.aiSpotlight { background: white; border: 1px solid var(--border-subtle); border-radius: var(--radius-lg); padding: 40px; position: relative; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.03); margin-bottom: 24px;}
.aiSpotlight::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 4px; background: var(--banner-gradient);}
.spotlightHeader { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;}
.spotlightBadge { display: flex; align-items: center; gap: 8px; font-size: 11px; font-weight: 800; color: var(--primary); background: var(--bg-hover); padding: 6px 14px; border-radius: 8px; letter-spacing: 0.1em;}
.syntheticLag { font-size: 9px; font-weight: 900; color: #10B981; background: #ECFDF5; padding: 4px 8px; border-radius: 4px; letter-spacing: 0.05em;}
.answerText { font-size: 18px; line-height: 1.8; color: var(--text-main); font-weight: 600; font-style: italic; margin: 0; max-width: 900px;}
.spotlightFooter { margin-top: 24px; padding-top: 20px; border-top: 1px solid var(--border-subtle); font-size: 11px; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.1em;}46 unmodified lines4748495051525328 unmodified lines828384858687888923 unmodified lines11311411511611711811912012112212312412512612721 unmodified lines149150151152153154155156157158159160161162163164165166167281 unmodified lines44945045145245345445545645745845946046146246346446546646746846947047147247347443243343443543643747547647747847948048148248315 unmodified lines4995005014595025035045055 unmodified lines51151251347151451551651751846 unmodified lines summary?: string; score?: number; match_type?: string; snippet?: string;}
export const KnowledgeBase: React.FC = () => {28 unmodified lines // AI Search Enhanced State const [suggestions, setSuggestions] = useState<string[]>([]); const [aiSuggestion, setAiSuggestion] = useState<string | null>(null); const [aiAnswer, setAiAnswer] = useState<string | null>(null); const [isAiSynthetic, setIsAiSynthetic] = useState(false);
// AI Growth Center State const [activeTab, setActiveTab] = useState<'library' | 'growth'>('library');23 unmodified lines 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) {21 unmodified lines 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();281 unmodified lines )} </motion.div> ) : ( <div className={styles.resultsContainer}> <AnimatePresence> {aiAnswer && ( <motion.div className={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.syntheticLag}>GENERATED IN REAL-TIME</span>} </div> <p className={styles.answerText}>{aiAnswer}</p> <div className={styles.spotlightFooter}> Based on the top documentation matches below. </div> </motion.div> )} </AnimatePresence>
<motion.div key="grid" className={styles.articlesGrid} initial={{ opacity: 0 }} animate={{ opacity: 1 }} > <motion.div key="grid" className={styles.articlesGrid} initial={{ opacity: 0 }} animate={{ opacity: 1 }} > {paginatedArticles.map((article, i) => ( <motion.div key={article.id} 15 unmodified lines <span className={styles.catBadge}>{article.category}</span> <h3>{article.title}</h3> <p className={styles.snippet}> {article.content.replace(/[#*`]/g, '').slice(0, 140)}... {article.snippet || article.content.replace(/[#*`]/g, '').slice(0, 140)}... </p> </div>
5 unmodified lines </div> </motion.div> ))} </motion.div> </motion.div> </div> )} </AnimatePresence>
105 unmodified lines10610710810910911011111211311411511611711811912012111512212312412512612712812913013113213313413513613713813914012212314114214314412612712814514614714814915015115215315415515615715815916016113316216316421 unmodified lines186187188161189190191192193166194195196197198199200201202203204205206207208209210211105 unmodified lines.resultMeta { display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px; margin-bottom: 8px;}
.resultMetaLeft { display: flex; align-items: center; gap: 8px;}
.resultId { font-size: 10px; font-weight: 800; color: var(--accent); color: #64748b; background: #f1f5f9; padding: 2px 6px; border-radius: 4px;}
.resultScore { font-size: 10px; font-weight: 800; color: #3b82f6; background: rgba(59, 130, 246, 0.1); padding: 2px 6px; border-radius: 4px;}
.resultStatus { font-size: 9px; font-weight: 900; text-transform: uppercase; padding: 2px 6px; border-radius: 4px; padding: 2px 8px; border-radius: 5px;}
.resultStatus[data-status="OPEN"] { color: var(--green); background: rgba(16, 185, 129, 0.1); }.resultStatus[data-status="IN_PROGRESS"] { color: var(--purple); background: rgba(99, 102, 241, 0.1); }.resultStatus[data-status="RESOLVED"] { color: var(--text3); background: var(--bg2); }.resultStatus[data-status="OPEN"] { color: #10b981; background: rgba(16, 185, 129, 0.1); }.resultStatus[data-status="IN_PROGRESS"] { color: #6366f1; background: rgba(99, 102, 241, 0.1); }.resultStatus[data-status="RESOLVED"] { color: #94a3b8; background: #f8fafc; }
.resultTitle { font-size: 13px; font-weight: 700; color: #1e293b; margin-bottom: 6px;}
.resultFooter { display: flex; justify-content: flex-end; font-size: 10px; color: #94a3b8; font-weight: 600; color: var(--text1);}
.searchLoader {21 unmodified lines padding: 10px; background: rgba(255, 255, 255, 0.9); backdrop-filter: blur(8px); border: 1px solid var(--border); border: 1px solid #e2e8f0; border-radius: 10px; font-size: 10px; font-weight: 800; text-align: center; color: var(--text3); color: #64748b; text-transform: uppercase; letter-spacing: 0.05em; z-index: 1000; animation: slideDown 0.2s ease-out;}
.noResults { padding: 32px 20px; text-align: center; color: #94a3b8; font-size: 12px; font-weight: 600;}
/* Live Indicator */.statusIndicator { display: flex;12 unmodified lines1314151617181956 unmodified lines767778798081821 unmodified line8485868788899050 unmodified lines14114214314114414514614314414514614714814915015115215315415514714814915015115215315415515615715815916016116216316416516616716816915715815917017117217317417517617717816517918018118212 unmodified lines const [searchQuery, setSearchQuery] = useState(''); const [results, setResults] = useState<any[]>([]); const [isSearching, setIsSearching] = useState(false); const [hasSearched, setHasSearched] = useState(false); const [showLogoutConfirm, setShowLogoutConfirm] = useState(false); const [showNotifications, setShowNotifications] = useState(false); const searchRef = React.useRef<HTMLFormElement>(null);56 unmodified lines if (e) e.preventDefault(); if (!searchQuery.trim()) { setResults([]); setHasSearched(false); return; }
1 unmodified line try { const resp = await api.get(`tickets/search/?q=${encodeURIComponent(searchQuery)}`); setResults(resp.data.results || []); setHasSearched(true); } catch (err) { console.error('Ticket search failed:', err); } finally {50 unmodified lines onChange={(e) => setSearchQuery(e.target.value)} /> {results.length > 0 && ( {hasSearched && ( <div className={styles.resultsDropdown}> {results.length > 0 ? ( {results.map(r => ( <div key={r.id} className={styles.resultItem} onClick={() => { onTicketSelect?.(r); setResults([]); setSearchQuery(''); }} > <div className={styles.resultMeta}> <span className={styles.resultId}>{r.id?.slice(0, 8).toUpperCase()}</span> <span className={styles.resultStatus} data-status={r.status?.toUpperCase()}>{r.status}</span> results.map(r => ( <div key={r.id} className={styles.resultItem} onClick={() => { onTicketSelect?.(r); setResults([]); setSearchQuery(''); setHasSearched(false); }} > <div className={styles.resultMeta}> <div className={styles.resultMetaLeft}> <span className={styles.resultScore}>{r.score}% Match</span> <span className={styles.resultId}>#{r.id?.slice(0, 8).toUpperCase()}</span> </div> <span className={styles.resultStatus} data-status={r.status?.toUpperCase()}>{r.status}</span> </div> <div className={styles.resultTitle}>{r.title}</div> <div className={styles.resultFooter}> Created {new Date(r.created_at).toLocaleDateString()} </div> </div> <div className={styles.resultTitle}>{r.title}</div> </div> ))} )) ) : ( <div className={styles.noResults}>No tickets found matching your query.</div> )} </div> )} {isSearching && ( <div className={styles.searchLoader}>Scanning network...</div> )} {results.length === 0 && searchQuery && !isSearching && ( {results.length === 0 && searchQuery && !isSearching && !hasSearched && ( <div className={styles.searchHint}>Press Enter to search</div> )} </form>19 unmodified lines2021222324252622 unmodified lines495051525354555657325 unmodified lines3833843853833843853863873883893903912819 unmodified lines32113212321332113214321532161906 unmodified lines51235124512551245126512751283 unmodified lines5132513351345134513551365137805 unmodified lines594359445945594659465947594819 unmodified lines "version": "0.0.0", "dependencies": { "@nexus/shared": "*", "lucide-react": "^1.7.0", "mermaid": "^11.13.0", "react": "^19.2.4", "react-dom": "^19.2.4",22 unmodified lines "version": "0.0.0", "dependencies": { "@nexus/shared": "*", "framer-motion": "^12.4.7", "lucide-react": "^1.7.0", "mermaid": "^11.4.1", "react": "^19.2.4", "react-dom": "^19.2.4", "react-markdown": "^10.1.0",325 unmodified lines "license": "Apache-2.0" }, "node_modules/@emnapi/wasi-threads": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.0.tgz", "integrity": "sha512-N10dEJNSsUx41Z6pZsXU8FjPjpBEplgH24sfkmITrBED1/U2Esum9F3lfLrMjKHHjmi557zQn7kR9R+XWXu5Rg==", "version": "1.2.1", "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz", "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==", "dev": true, "license": "MIT", "optional": true,2819 unmodified lines "version": "12.38.0", "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-12.38.0.tgz", "integrity": "sha512-rFYkY/pigbcswl1XQSb7q424kSTQ8q6eAC+YUsSKooHQYuLdzdHjrt6uxUC+PRAO++q5IS7+TamgIw1AphxR+g==", "dev": true, "license": "MIT", "dependencies": { "motion-dom": "^12.38.0",1906 unmodified lines "version": "12.38.0", "resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-12.38.0.tgz", "integrity": "sha512-pdkHLD8QYRp8VfiNLb8xIBJis1byQ9gPT3Jnh2jqfFtAsWUA3dEepDlsWe/xMpO8McV+VdpKVcp+E+TGJEtOoA==", "dev": true, "license": "MIT", "dependencies": { "motion-utils": "^12.36.0"3 unmodified lines "version": "12.36.0", "resolved": "https://registry.npmjs.org/motion-utils/-/motion-utils-12.36.0.tgz", "integrity": "sha512-eHWisygbiwVvf6PZ1vhaHCLamvkSbPIeAYxWUuL3a2PD/TROgE7FvfHWTIH4vMl798QLfMw15nRqIaRDXTlYRg==", "dev": true, "license": "MIT" }, "node_modules/ms": {805 unmodified lines "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "dev": true, "license": "0BSD" }, "node_modules/type-check": {31 unmodified lines32333435363738394041424344454631 unmodified lines created_at: datetime updated_at: datetime score: Optional[float] = None match_type: Optional[str] = None snippet: Optional[str] = None
model_config = ConfigDict(from_attributes=True)
class KBSearchResponse(BaseModel): results: List[KBArticleResponse] answer: Optional[str] = None is_ai_synthetic: bool = False suggestion: Optional[str] = None expanded_queries: Optional[List[str]] = None search_time_s: Optional[float] = None12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758import asynciofrom uuid import UUIDfrom sqlalchemy import selectfrom core.database import async_session_factoryfrom core.deps import get_arq_poolfrom models.kb_article import KBArticlefrom core.logging import get_logger
logger = get_logger(__name__)
async def backfill_summaries(): """ Identifies KB articles missing AI summaries and enqueues them for re-indexing. """ async with async_session_factory() as db: # 1. Find articles with NULL summary stmt = select(KBArticle.id).where( KBArticle.summary.is_(None), KBArticle.deleted_at.is_(None) ) result = await db.execute(stmt) article_ids = result.scalars().all() if not article_ids: print("β
All Knowledge Base articles already have summaries.") return
print(f"π Found {len(article_ids)} articles missing summaries. Enqueueing for AI processing...") # 2. Get ARQ pool # Mimic get_arq_pool dependency logic import redis.asyncio as redis from core.config import get_settings settings = get_settings() redis_pool = redis.from_url(settings.REDIS_URL, decode_responses=False) # We'll use a local mock or a real one if available. # But wait, I can just use the arq_pool if I can get it. # For a script, I'll connect to Redis directly. from arq import create_pool from arq.connections import RedisSettings # Extract host/port from REDIS_URL # redis://localhost:6379/0 redis_settings = RedisSettings.from_dsn(settings.REDIS_URL) arq_pool = await create_pool(redis_settings) # 3. Enqueue Jobs for a_id in article_ids: await arq_pool.enqueue_job("index_kb_article", a_id) print(f" -> Enqueued: {a_id}") await arq_pool.close() print(f"π Successfully enqueued {len(article_ids)} background tasks.")
if __name__ == "__main__": asyncio.run(backfill_summaries())api/v1/dashboard.py+36-11
api/v1/kb.py+62-2
api/v1/reports.py+70-8
frontend/apps/customer/package.json+1
frontend/apps/customer/src/components/KnowledgeBase.tsx+89-5
frontend/apps/internal/src/components/KnowledgeBase.module.css+80
frontend/apps/internal/src/components/KnowledgeBase.tsx+52-8
frontend/apps/internal/src/components/TopBar.module.css+46-10
frontend/apps/internal/src/components/TopBar.tsx+32-18
frontend/package-lock.json+6-7
schemas/kb.py+4
scripts/backfill_kb_summaries.pyAdded+58