Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit ·
235f8ef
1
Parent(s): 06f7381
backend stabilization
Browse filesFiles changed (13)
- agents/tools/nexus_tools.py+83-3
- api/v1/kb.py+67-25
- api/v1/messages.py+14-3
- api/v1/tickets.py+35-14
- api/v1/workspace.py+18-3
- core/cache.py+29
- frontend/apps/customer/src/App.tsx+6-4
- frontend/apps/customer/src/components/Dashboard.tsx+2-2
- frontend/apps/customer/src/components/WorkspaceView.tsx+21-18
- frontend/apps/internal/src/App.tsx+1
- frontend/apps/internal/src/components/KnowledgeBase.module.css+29-3
- frontend/apps/internal/src/components/KnowledgeBase.tsx+26
- frontend/packages/shared/src/hooks/useWorkspaces.ts+44-6
25 unmodified lines26272829303132333435363738394041424344454647484932505152536 unmodified lines60616245636465666756 unmodified lines12412512612712812913013113213313413513613713813914014114214314414514645 unmodified lines192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222161223224225226349 unmodified lines57657757857958058158258358458558658758858959059159259359459559659759859925 unmodified lines """ Search the Knowledge Base using the advanced Hybrid Multimodal engine. """ # 0. Semantic Cache Check (Blazing Fast Recall) from core.cache import SemanticCacheManager from core.permissions import ALL_SC_ROLES is_agent_role = any(s in role.lower() for s in ["3sc", "agent", "lead", "admin"]) cached_answer = await SemanticCacheManager.check_cache( workspace_id=str(workspace_id), query=query, is_agent=is_agent_role, user_role=str(role), user_id=None # Anonymous for cache lookup ) if cached_answer: logger.info(f"🧠 Semantic Cache HIT [Agent KB]: {query}") return f"### AI DIRECT ANSWER (CACHED)\n{cached_answer}\n\n*Note: This answer was retrieved from the workspace semantic cache.*"
async with async_session_factory() as db: # 1. Prepare Mock User for the search helper user_role_mapped = UserRole.CUSTOMER_USER if "3sc" in role.lower(): if is_agent_role: user_role_mapped = UserRole.SC_AGENT if "admin" in role.lower(): user_role_mapped = UserRole.SC_ADMIN if "lead" in role.lower(): user_role_mapped = UserRole.SC_LEAD6 unmodified lines q=query, current_user=mock_user, category=None, project_id=None project_id=None, workspace_id=workspace_id ) if not search_results:56 unmodified lines await db.commit() await db.refresh(new_ticket) # 3. Notify Creator (AI Acknowledgement) try: from core.config import get_redis_settings from arq import create_pool pool = await create_pool(get_redis_settings()) await pool.enqueue_job( "send_triple_notification", str(user_id), str(workspace_id), "🎟️ Ticket Created", f"Your ticket '{new_ticket.title}' has been successfully created by the Master Agent.", link=f"/dashboard?ticket={new_ticket.id}" ) await pool.close() except Exception as e: logger.error(f"Failed to notify creator in create_ticket_tool: {e}")
logger.info(f"Ticket created via AI: {new_ticket.id}") return f"Successfully created ticket: **{new_ticket.title}** (ID: `{new_ticket.id}`). Status is OPEN."
45 unmodified lines
await db.commit() # 4. Notify Creator of Status Change if status and ticket.status != old_status: try: from core.config import get_redis_settings from arq import create_pool pool = await create_pool(get_redis_settings()) if ticket.status in [TicketStatus.RESOLVED, TicketStatus.CLOSED]: title = "✅ Ticket Resolved" msg = f"The Master Agent has resolved your ticket: '{ticket.title}'." else: title = "🎟️ Ticket Updated" msg = f"Your ticket '{ticket.title}' has been moved to {ticket.status.value.upper()}."
await pool.enqueue_job( "send_triple_notification", str(ticket.created_by), str(workspace_id), title, msg, link=f"/dashboard?ticket={ticket.id}" ) await pool.close() except Exception as e: logger.error(f"Failed to notify creator in update_ticket_tool: {e}")
msg = f"Successfully updated ticket `{ticket.id}`." if status and ticket.status != old_status: msg += f" Status changed from {old_status} to {ticket.status}." msg += f" Status changed from {old_status.value.upper()} to {ticket.status.value.upper()}." return msg
349 unmodified lines t.assigned_to = user_id await db.commit() # 3. Notify Assignee (Comprehensive Coverage) try: from core.config import get_redis_settings from arq import create_pool pool = await create_pool(get_redis_settings()) await pool.enqueue_job( "send_triple_notification", str(user_id), str(workspace_id), "Ticket Reassigned", f"The Master Agent has reassigned ticket '{t.title}' to you. Please review the technical context.", link=f"/dashboard?ticket={t.id}" ) await pool.close() except Exception as e: logger.error(f"Failed to notify assignee in assign_ticket_tool: {e}") return f"Ticket {ticket_id} successfully assigned to user {user_id}."
async def update_ticket_status_tool(ticket_id: UUID, new_status: str, workspace_id: UUID, role: str = "customer_user") -> str:194 unmodified lines19519619719819819920020113 unmodified lines2152162172182182192202212232222232242262252262271 unmodified line22923023123423223323423823924023523623723859 unmodified lines29829930030130230330430530630730830931031187 unmodified lines39940040140140240340440240340440540640740640840840941041140941041141241341441541641741841341441541641741942042142042242342442533 unmodified lines459460461460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509194 unmodified lines current_user: User, category: Optional[str], project_id: Optional[UUID], workspace_id: Optional[UUID] = None workspace_id: UUID): """Internal helper to execute factual hybrid search + visual attachment search.""" import uuid13 unmodified lines ) # 2. SEACH A: Text Semantic Match (Articles) # Optimized: Take only the BEST matching chunk per article to prevent score inflation sem_start = time.perf_counter() semantic_stmt = ( select( KBArticle, KBArticleChunk.content.label("chunk_content"), KBArticleChunk.content, (1 - KBArticleChunk.embedding.cosine_distance(query_vector)).label("sim_score") ) .distinct(KBArticle.id) .join(KBArticleChunk, KBArticle.id == KBArticleChunk.article_id) .where( KBArticle.deleted_at.is_(None),1 unmodified line KBArticle.duplicate_of_id.is_(None), KBArticle.workspace_id == workspace_id ) .order_by(KBArticle.id, desc("sim_score")) ) if category: semantic_stmt = semantic_stmt.where(KBArticle.category == category) if project_id: semantic_stmt = semantic_stmt.where(KBArticle.project_id == project_id) # Use a subquery or wrap to limit after distinct if needed, but for RRF top 20 is fine # Actually, we want the top 20 articles by their BEST chunk score. semantic_stmt = select(semantic_stmt.subquery()).order_by(desc("sim_score")).limit(20) semantic_stmt = semantic_stmt.order_by(desc("sim_score")).limit(20) # 3. SEARCH B: Visual Caption Match (Attachments) # Uses pg_trgm for fuzzy similarity + search_vector for keyword relevance59 unmodified lines results_map = {} def apply_fusion(list_hits, weight, score_attr): # Best-Hit Deduplication: Ensure an article only scores once per search branch seen_in_branch = set() for rank, row in enumerate(list_hits): art = row[0] if art.id in seen_in_branch: continue seen_in_branch.add(art.id) chunk_txt = row[1] if len(row) > 1 and isinstance(row[1], str) else None rrf_score = weight * (1.0 / (60 + rank + 1)) 87 unmodified lines "durationMs": (time.perf_counter() - start_time) * 1000 } # 1. Start Original Search Branch IMMEDIATELY (Don't wait for LLM) original_search_task = execute_multimodal_search(db, q, current_user, category, project_id, workspace_id=target_ws) # 2. Start LLM Expansion concurrently (if not a trivial query) # 1. Execute Original Search orig_res = await execute_multimodal_search( db, q, current_user, category, project_id, target_ws ) all_local_results = [orig_res] expanded_queries = [] all_local_results = [] if len(q.strip()) < 5: # Bypass AI expansion for trivial "lazy" queries like "test" all_local_results.append(await original_search_task) else: # 2. Performance Optimization: High Confidence Early Exit # If original search has a near-perfect match (>80%), skip expensive LLM variations max_orig_score = max([r["score"] for r in orig_res.values()]) if orig_res else 0.0 is_high_confidence = max_orig_score > 80.0 # Check if query is complex enough to warrant expansion (e.g., >3 words or technical) is_complex = len(q.split()) >= 3 or any(w in q.lower() for w in ["how", "why", "steps", "explain"]) if not is_high_confidence and is_complex and len(q.strip()) >= 5: # Launch AI expansion task expansion_task = generate_query_variations(q) # Await BOTH original search and the LLM expansion results orig_res, expanded_queries = await asyncio.gather(original_search_task, expansion_task) all_local_results.append(orig_res) expanded_queries = await generate_query_variations(q) if expanded_queries: # Launch searches for new variations in parallel # Launch searches for variations in parallel async def run_variation_search(v): async with async_session_factory() as session: return await execute_multimodal_search(session, v, current_user, category, project_id, workspace_id=target_ws)33 unmodified lines final_results.sort(key=lambda x: float(x.get("score") or 0.0), reverse=True) top_results = final_results[:5]
# 4.5 Cleanup & Synthesis Removal # Per user request, we focus on high-fidelity retrieval and skip direct AI answers # 4.5 Synthesis Branch (The "Direct Answer" Engine) direct_answer = None is_ai_synthetic = False
# Trigger synthesis if it's a complex query or we have high confidence hits # This provides a quick "Direct Answer" summary of the top documentation if is_complex and top_results: try: from core.llm import get_llm from langchain_core.messages import SystemMessage, HumanMessage # Construct context from TOP CHUNKS context_txt = "\n\n".join([ f"DOC {i+1} [{r['title']}]:\n---\n{r.get('raw_chunk') or r.get('snippet') or r['content'][:500]}\n---" for i, r in enumerate(top_results) ]) llm = get_llm() prompt = [ SystemMessage(content=( "You are a technical support expert. Provide a concise, highly structured direct answer. " "Use MARKDOWN for the following:\n" "- Use **Bold** for key facts and product names.\n" "- Use `inline code` for technical terms, database names, or variables.\n" "- Use bulleted lists to cite evidence from provided documentation.\n" "If the answer is not in the context, be honest. Keep it under 150 words." )), HumanMessage(content=f"Question: {q}\n\nDocumentation Context:\n{context_txt}") ] synth_resp = await llm.ainvoke(prompt) direct_answer = synth_resp.content is_ai_synthetic = True # Asynchronously Cache to Semantic Cache await SemanticCacheManager.set_cache( workspace_id=str(target_ws), user_id=str(current_user.id), query=q, response_text=direct_answer, is_agent=current_user.role in ALL_SC_ROLES, user_role=str(current_user.role) ) except Exception as e: logger.error(f"Synthesis failed: {e}")
# 5. Final Response Payload end_time = time.perf_counter() search_time_s = end_time - start_time143 unmodified lines1441451461471481471501481491504 unmodified lines155156157158159160161162163164165166167168169170171172173174143 unmodified lines # --- 4. Notify Customer of Expert Response --- # Only if sender is staff and message is public if is_staff and not payload.is_internal and ticket.created_by != current_user.id: from core.tasks import send_triple_notification # Use arq to avoid blocking, or background_tasks if available try: # Correct arq call: do NOT pass ctx/None explicitly await arq_pool.enqueue_job("send_triple_notification", str(ticket.created_by), str(ticket.workspace_id),4 unmodified lines except Exception as e: logger.error(f"Failed to queue customer response notification: {e}")
# --- 5. Notify Assigned Agent of Customer Reply --- # Only if sender is NOT staff (i.e. is customer) and there is an assignee to notify if not is_staff and ticket.assigned_to: try: await arq_pool.enqueue_job("send_triple_notification", str(ticket.assigned_to), str(ticket.workspace_id), "📬 Customer Reply", f"The customer has replied to ticket: '{ticket.title}'", link=f"/dashboard?ticket={ticket.id}" ) except Exception as e: logger.error(f"Failed to queue agent reply notification: {e}")
return await sanitize_message_response(new_message, db)
414 unmodified lines415416417418418419420421422423312 unmodified lines736737738737738739740741739740741742743744745746747748749750751752753754755756757218 unmodified lines97697797896997998098198298355 unmodified lines1039104010411031104210431034103510361037103810391044104510461047104810491050105110527 unmodified lines10601061106210631064106510661067106810691070107110721073107410751076414 unmodified lines # KB search integrated into the parallel flow async def run_kb_search(): async with async_session_factory() as session: return await execute_multimodal_search(session, q, current_user, None, project_id) return await execute_multimodal_search( session, q, current_user, None, project_id, current_user.workspace_id )
kb_task = run_kb_search() 312 unmodified lines ticket.resolution_text = "This issue has been resolved. Thanks!" # Notify Creator of Resolution background_tasks.add_task( send_triple_notification, None, ticket.created_by, ticket.workspace_id, await arq_pool.enqueue_job( "send_triple_notification", str(ticket.created_by), str(ticket.workspace_id), "✅ Ticket Resolved", f"Great news! Your ticket '{ticket.title}' has been marked as {new_status}." ) elif new_status in [TicketStatus.IN_PROGRESS, TicketStatus.ACKNOWLEDGED] and ticket.status == TicketStatus.OPEN: # Notify Creator that work has started await arq_pool.enqueue_job( "send_triple_notification", str(ticket.created_by), str(ticket.workspace_id), "🎟️ Work Started", f"An agent has started reviewing your ticket '{ticket.title}'. Current status: {new_status.value.upper()}." )
if "priority" in update_data and update_data["priority"] != ticket.priority: # Recalculate SLA218 unmodified linesasync def escalate_ticket( ticket_id: UUID, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) db: AsyncSession = Depends(get_db), arq_pool: ArqRedis = Depends(get_arq_pool)) -> Any: """Manual Escalation: Force priority to P0 and mark as escalated.""" from sqlalchemy.orm import joinedload55 unmodified lines
# 4. Notify Workspace Lead/Admin via Triple-Threat Protocol from agents.utils import get_workspace_manager from core.tasks import send_triple_notification manager_user = await get_workspace_manager(db, ticket.workspace_id) if manager_user: await send_triple_notification( None, # ctx not available in direct API call, but send_triple_notification handles it user_id=manager_user.id, workspace_id=ticket.workspace_id, title="🚨 Manual Escalation Alert", message=f"Ticket '{ticket.title}' has been manually escalated by {current_user.full_name}. Priority: P0.", await arq_pool.enqueue_job( "send_triple_notification", str(manager_user.id), str(ticket.workspace_id), "🚨 Manual Escalation Alert", f"Ticket '{ticket.title}' has been manually escalated by {current_user.full_name}. Priority: P0.", link=f"/dashboard?ticket={ticket.id}" ) 7 unmodified lines link=f"/dashboard?ticket={ticket.id}" )
# 5. Notify Assignee (if different from manager) if ticket.assigned_to and (not manager_user or ticket.assigned_to != manager_user.id): await arq_pool.enqueue_job( "send_triple_notification", str(ticket.assigned_to), str(ticket.workspace_id), "🚨 Urgent Escalation", f"A lead has manually escalated ticket '{ticket.title}' to P0. This is now a critical priority.", link=f"/dashboard?ticket={ticket.id}" )
logger.info(f"Ticket {ticket.id} manually escalated by {current_user.id}") # Refresh to pick up lead info in sanitizer59 unmodified lines606162636463646566676869707172732 unmodified lines767778798081828384852 unmodified lines88899081919293948 unmodified lines10310410510610710810911011111211359 unmodified lines current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> Any: """Get current workspace details.""" print(f"DEBUG WORKSPACE: User={current_user.email}, WS_ID_ATTR={current_user.workspace_id}, TYPE={type(current_user.workspace_id)}") """Get current workspace details (Cached).""" from core.cache import get_cached_object, set_cached_object cache_key = f"ws:meta:{current_user.workspace_id}" cached = await get_cached_object(cache_key) if cached: return cached
stmt = select(Workspace).where( Workspace.id == current_user.workspace_id, Workspace.deleted_at.is_(None)2 unmodified lines workspace = result.scalar_one_or_none() if not workspace: raise HTTPException(status_code=404, detail="Workspace not found") # Cache for 1 hour (workspace data is slow-changing) from fastapi.encoders import jsonable_encoder await set_cached_object(cache_key, jsonable_encoder(workspace), ttl=3600) return workspace
@router.patch("/", response_model=WorkspaceResponse, dependencies=[Depends(require_roles(WORKSPACE_ADMIN_ROLES))])2 unmodified lines current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)) -> Any: """Admin only: Update workspace settings/branding.""" """Admin only: Update workspace settings/branding (Invalidates Cache).""" stmt = select(Workspace).where( Workspace.id == current_user.workspace_id, Workspace.deleted_at.is_(None)8 unmodified lines db.add(workspace) await db.commit() await db.refresh(workspace)
# Invalidate Cache from core.cache import invalidate_cache await invalidate_cache(f"ws:meta:{current_user.workspace_id}") return workspace
@router.get("/branding/")56 unmodified lines575859606162636465666768697071727374757677787980818283848586878889909156 unmodified lines except Exception: pass
# --- Generic Object Caching for API responses ---
async def get_cached_object(key: str) -> Optional[Any]: """Retrieves a JSON-serialized object from Redis.""" try: client = get_redis_client() data = await client.get(key) if data: return json.loads(data) except Exception: pass return None
async def set_cached_object(key: str, data: Any, ttl: int = 300) -> None: """Stores a JSON-serializable object in Redis with TTL.""" try: client = get_redis_client() await client.set(key, json.dumps(data), ex=ttl) except Exception: pass
async def invalidate_cache(key: str) -> None: """Explicitly purges a cache key.""" try: client = get_redis_client() await client.delete(key) except Exception: pass
class SemanticCacheManager: """ Manages semantic LLM response caching using pgvector.19 unmodified lines202122232423242526274 unmodified lines323334353536373838394041424319 unmodified lines const { user, token, loading: authLoading, error: authError, login, logout, refreshUser } = useAuth(); const { tickets, loading: ticketsLoading, createTicket } = useTickets(); const { stats, loading: statsLoading } = useDashboardStats(); useAIInsights(); useServiceNarrative(); const { insights, loading: insightsLoading } = useAIInsights(); const { narrative, loading: narrativeLoading } = useServiceNarrative();
const [active, setActive] = useState<"dashboard" | "tickets" | "kb" | "analytics" | "thread" | "workspace">("dashboard"); const [showNewTicket, setShowNewTicket] = useState(false);4 unmodified lines return <LoginCard onLogin={login} loading={authLoading} portal="customer" error={authError} />; }
// Pre-load logic: Wait for auth, tickets, stats, and AI before revealing the portal // Pre-load logic: Wait for auth, tickets, stats, insights AND narrative before revealing the portal const isInitialLoading = (authLoading && !user) || (user && ( (ticketsLoading && tickets.length === 0) || (statsLoading && !stats) (statsLoading && !stats) || (insightsLoading && !insights) || (narrativeLoading && !narrative) ));
if (isInitialLoading) {116 unmodified lines117118119120121120121122123124116 unmodified lines <div style={{ display: "flex", gap: 16, flexWrap: "wrap", justifyContent: "flex-end" }}> {[ { label: "WORKSPACE VOLUME", value: showStatsLoading ? <Skeleton width={40} height={28} /> : (stats?.total_tickets ?? "0"), sub: "Lifetime Tickets", icon: "📊" }, { label: "ACTIVE LOAD", value: showStatsLoading ? <Skeleton width={40} height={28} /> : (stats ? (stats.by_status?.OPEN || 0) + (stats.by_status?.IN_PROGRESS || 0) + (stats.by_status?.ACKNOWLEDGED || 0) : 0), sub: "Open Cases", icon: "⚡" }, { label: "RESOLVED SUCCESS", value: showStatsLoading ? <Skeleton width={40} height={28} /> : (stats ? (stats.by_status?.RESOLVED || 0) + (stats.by_status?.CLOSED || 0) : 0), sub: "Completed Tasks", icon: "✅" } { label: "ACTIVE LOAD", value: showStatsLoading ? <Skeleton width={40} height={28} /> : (stats?.by_status ? (stats.by_status.OPEN || 0) + (stats.by_status.IN_PROGRESS || 0) + (stats.by_status.ACKNOWLEDGED || 0) : "0"), sub: "Open Cases", icon: "⚡" }, { label: "RESOLVED SUCCESS", value: showStatsLoading ? <Skeleton width={40} height={28} /> : (stats?.by_status ? (stats.by_status.RESOLVED || 0) + (stats.by_status.CLOSED || 0) : "0"), sub: "Completed Tasks", icon: "✅" } ].map(s => ( <div key={s.label} style={{ background: "rgba(255, 255, 255, 0.12)", 14 unmodified lines15161718192019202121222324252 unmodified lines28293030313231323334343535363738373839404142394041424344454644454647484950515228 unmodified lines818283818485868714 unmodified lines error: "#DC2626",};
import { useWorkspace, useUsers } from '@nexus/shared';
export const WorkspaceView: React.FC<{ user: any }> = ({ user }) => { const [workspace, setWorkspace] = useState<any>(null); const [members, setMembers] = useState<any[]>([]); const [loading, setLoading] = useState(true); const { workspace, loading: workspaceLoading, refresh: refreshWorkspace } = useWorkspace(); const { users: members, loading: usersLoading, refresh: refreshUsers, addUser } = useUsers(); // New User Form const [showAddForm, setShowAddForm] = useState(false);2 unmodified lines
const isAdmin = user.role.includes('admin');
useEffect(() => { fetchWorkspaceData(); }, []); // Logic: "Loading workspace intelligence..." only shows if we have NO data. // If we have cached data, we show it immediately (Instant-Sync). const isInitialLoading = (workspaceLoading && !workspace) || (usersLoading && members.length === 0);
const fetchWorkspaceData = async () => { setLoading(true); const handleCreateUser = async (e: React.FormEvent) => { e.preventDefault(); setSubmitting(true); try { const [wsResp, usersResp] = await Promise.all([ api.get('workspace/'), api.get('users/') ]); setWorkspace(wsResp.data); setMembers(usersResp.data); await addUser(form); setForm({ email: '', full_name: '', password: '', role: 'customer_user' }); // Brief delay before closing for better feedback setTimeout(() => { setShowAddForm(false); setSubmitting(false); }, 500); } catch (err) { console.error("Failed to fetch workspace data:", err); } finally { setLoading(false); console.error("Failed to create user:", err); alert("Error creating user. Check email uniqueness and permissions."); setSubmitting(false); } };
28 unmodified lines } };
if (loading) return <div style={{ padding: 40, color: COLORS.gray400 }}>Loading workspace intelligence...</div>; if (isInitialLoading) return <div style={{ padding: 40, color: COLORS.gray400 }}>Loading workspace intelligence...</div>;
return ( <div style={{ padding: "40px", maxWidth: 1200, margin: "0 auto" }}>97 unmodified lines989910010110210310497 unmodified lines return <KnowledgeBase workspaceId={selectedWorkspaceId} />; case 'escalation': return isAdminOrLead ? <EscalationCentre /> : forbidden; case 'analytics': return ( <AnalyticsDashboard workspaceId={selectedWorkspaceId}846 unmodified lines847848849850850851852853854853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887846 unmodified lines}
.answerText { font-size: 18px; font-size: 16px; line-height: 1.8; color: var(--text-main); font-weight: 600; font-style: italic; font-weight: 500; margin: 0; max-width: 900px;}
.answerText p { margin-bottom: 16px;}
.answerText ul, .answerText ol { margin-bottom: 16px; padding-left: 24px;}
.answerText li { margin-bottom: 8px;}
.answerText code { background: var(--bg-hover); padding: 2px 6px; border-radius: 4px; font-family: 'JetBrains Mono', monospace; font-size: 0.9em; color: var(--primary);}
.answerText strong { font-weight: 800; color: var(--primary);}
.spotlightFooter { margin-top: 24px; padding-top: 20px;455 unmodified lines456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487455 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> <div className={styles.answerText}> <ReactMarkdown remarkPlugins={[remarkGfm]}> {aiAnswer} </ReactMarkdown> </div> <div className={styles.spotlightFooter}> Based on the top documentation matches below. </div> </motion.div> )} </AnimatePresence>
<motion.div key="grid" className={styles.articlesGrid}7 unmodified lines89101112131415111213141517161718192021222324252627282930313233343536373839404142434445464748495051525354555657587 unmodified lines branding?: any;}
// Global singleton for workspaceslet globalWorkspaces: Workspace[] = [];let globalWorkspacesLoading = false;let globalWorkspacesError: string | null = null;const workspacesListeners = new Set<(w: Workspace[], l: boolean, e: string | null) => void>();// Global singleton for the ACTIVE workspace metadatalet globalActiveWorkspace: Workspace | null = null;let globalActiveWorkspaceLoading = false;const activeWorkspaceListeners = new Set<(w: Workspace | null, l: boolean) => void>();
const notifyWorkspaces = () => workspacesListeners.forEach(l => l(globalWorkspaces, globalWorkspacesLoading, globalWorkspacesError));const notifyActiveWorkspace = () => activeWorkspaceListeners.forEach(l => l(globalActiveWorkspace, globalActiveWorkspaceLoading));
export const useWorkspace = () => { const [workspace, setWorkspace] = useState(globalActiveWorkspace); const [loading, setLoading] = useState(globalActiveWorkspaceLoading);
useEffect(() => { const listener = (w: Workspace | null, l: boolean) => { setWorkspace(w); setLoading(l); }; activeWorkspaceListeners.add(listener); return () => activeWorkspaceListeners.delete(listener); }, []);
const fetchWorkspace = useCallback(async (force: boolean = false) => { if (!force && globalActiveWorkspace) return; globalActiveWorkspaceLoading = true; notifyActiveWorkspace(); try { const response = await api.get('workspace/'); globalActiveWorkspace = response.data; } catch (err) { console.error("Failed to fetch current workspace", err); } finally { globalActiveWorkspaceLoading = false; notifyActiveWorkspace(); } }, []);
useEffect(() => { const token = localStorage.getItem('token'); if (token && !globalActiveWorkspace && !globalActiveWorkspaceLoading) { fetchWorkspace(); } }, [fetchWorkspace]);
return { workspace, loading, refresh: () => fetchWorkspace(true) };};
export const useWorkspaces = () => { const [localWorkspaces, setLocalWorkspaces] = useState(globalWorkspaces);agents/tools/nexus_tools.py+83-3
api/v1/kb.py+67-25
api/v1/messages.py+14-3
api/v1/tickets.py+35-14
api/v1/workspace.py+18-3
core/cache.py+29
frontend/apps/customer/src/App.tsx+6-4
frontend/apps/customer/src/components/Dashboard.tsx+2-2
frontend/apps/customer/src/components/WorkspaceView.tsx+21-18
frontend/apps/internal/src/App.tsx+1
frontend/apps/internal/src/components/KnowledgeBase.module.css+29-3
frontend/apps/internal/src/components/KnowledgeBase.tsx+26
frontend/packages/shared/src/hooks/useWorkspaces.ts+44-6