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 lines262728293031323334356 unmodified lines4243444546474856 unmodified lines10510610710810911045 unmodified lines156157158159160161162163164349 unmodified lines51451551651751851925 unmodified lines"""Search the Knowledge Base using the advanced Hybrid Multimodal engine."""async with async_session_factory() as db:# 1. Prepare Mock User for the search helperuser_role_mapped = UserRole.CUSTOMER_USERif "3sc" in role.lower():user_role_mapped = UserRole.SC_AGENTif "admin" in role.lower(): user_role_mapped = UserRole.SC_ADMINif "lead" in role.lower(): user_role_mapped = UserRole.SC_LEAD6 unmodified linesq=query,current_user=mock_user,category=None,project_id=None)if not search_results:56 unmodified linesawait db.commit()await db.refresh(new_ticket)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 linesawait db.commit()msg = f"Successfully updated ticket `{ticket.id}`."if status and ticket.status != old_status:msg += f" Status changed from {old_status} to {ticket.status}."return msg349 unmodified linest.assigned_to = user_idawait db.commit()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:25 unmodified lines262728293031323334353637383940414243444546474849505152536 unmodified lines606162636465666756 unmodified lines12412512612712812913013113213313413513613713813914014114214314414514645 unmodified lines192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226349 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 SemanticCacheManagerfrom core.permissions import ALL_SC_ROLESis_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 helperuser_role_mapped = UserRole.CUSTOMER_USERif is_agent_role:user_role_mapped = UserRole.SC_AGENTif "admin" in role.lower(): user_role_mapped = UserRole.SC_ADMINif "lead" in role.lower(): user_role_mapped = UserRole.SC_LEAD6 unmodified linesq=query,current_user=mock_user,category=None,project_id=None,workspace_id=workspace_id)if not search_results:56 unmodified linesawait db.commit()await db.refresh(new_ticket)# 3. Notify Creator (AI Acknowledgement)try:from core.config import get_redis_settingsfrom arq import create_poolpool = 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 linesawait db.commit()# 4. Notify Creator of Status Changeif status and ticket.status != old_status:try:from core.config import get_redis_settingsfrom arq import create_poolpool = 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.value.upper()} to {ticket.status.value.upper()}."return msg349 unmodified linest.assigned_to = user_idawait db.commit()# 3. Notify Assignee (Comprehensive Coverage)try:from core.config import get_redis_settingsfrom arq import create_poolpool = 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 lines19519619719819920020113 unmodified lines2152162172182192202212222232242252262272282291 unmodified line23123223323423523623723823924024124224359 unmodified lines30330430530630730830931087 unmodified lines39839940040140240340440540640740840941041141241341441541641741841942042142242333 unmodified lines457458459460461462463464465466467194 unmodified linescurrent_user: User,category: Optional[str],project_id: Optional[UUID],workspace_id: Optional[UUID] = None):"""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 inflationsem_start = time.perf_counter()semantic_stmt = (select(KBArticle,KBArticleChunk.content.label("chunk_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 lineKBArticle.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)# 3. SEARCH B: Visual Caption Match (Attachments)# Uses pg_trgm for fuzzy similarity + search_vector for keyword relevance59 unmodified linesresults_map = {}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) > 1 and isinstance(row[1], str) else Nonerrf_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)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:# Launch AI expansion taskexpansion_task = generate_query_variations(q)# Await BOTH original search and the LLM expansion resultsorig_res, expanded_queries = await asyncio.gather(original_search_task, expansion_task)all_local_results.append(orig_res)if expanded_queries:# Launch searches for new variations in parallelasync 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 linesfinal_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 answersdirect_answer = Noneis_ai_synthetic = False# 5. Final Response Payloadend_time = time.perf_counter()search_time_s = end_time - start_time194 unmodified lines19519619719819920020113 unmodified lines2152162172182192202212222232242252262271 unmodified line22923023123223323423523623723859 unmodified lines29829930030130230330430530630730830931031187 unmodified lines39940040140240340440540640740840941041141241341441541641741841942042142242342442533 unmodified lines459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509194 unmodified linescurrent_user: User,category: Optional[str],project_id: Optional[UUID],workspace_id: UUID):"""Internal helper to execute factual hybrid search + visual attachment search."""import uuid13 unmodified lines)# 2. SEACH A: Text Semantic Match (Articles)sem_start = time.perf_counter()semantic_stmt = (select(KBArticle,KBArticleChunk.content,(1 - KBArticleChunk.embedding.cosine_distance(query_vector)).label("sim_score")).join(KBArticleChunk, KBArticle.id == KBArticleChunk.article_id).where(KBArticle.deleted_at.is_(None),1 unmodified lineKBArticle.duplicate_of_id.is_(None),KBArticle.workspace_id == workspace_id))if category: semantic_stmt = semantic_stmt.where(KBArticle.category == category)if project_id: semantic_stmt = semantic_stmt.where(KBArticle.project_id == project_id)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 linesresults_map = {}def apply_fusion(list_hits, weight, score_attr):# Best-Hit Deduplication: Ensure an article only scores once per search branchseen_in_branch = set()for rank, row in enumerate(list_hits):art = row[0]if art.id in seen_in_branch:continueseen_in_branch.add(art.id)chunk_txt = row[1] if len(row) > 1 and isinstance(row[1], str) else Nonerrf_score = weight * (1.0 / (60 + rank + 1))87 unmodified lines"durationMs": (time.perf_counter() - start_time) * 1000}# 1. Execute Original Searchorig_res = await execute_multimodal_search(db, q, current_user, category, project_id, target_ws)all_local_results = [orig_res]expanded_queries = []# 2. Performance Optimization: High Confidence Early Exit# If original search has a near-perfect match (>80%), skip expensive LLM variationsmax_orig_score = max([r["score"] for r in orig_res.values()]) if orig_res else 0.0is_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 taskexpanded_queries = await generate_query_variations(q)if expanded_queries:# Launch searches for variations in parallelasync 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 linesfinal_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 = Noneis_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 documentationif is_complex and top_results:try:from core.llm import get_llmfrom langchain_core.messages import SystemMessage, HumanMessage# Construct context from TOP CHUNKScontext_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.contentis_ai_synthetic = True# Asynchronously Cache to Semantic Cacheawait 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 Payloadend_time = time.perf_counter()search_time_s = end_time - start_time
143 unmodified lines1441451461471481491501511521534 unmodified lines158159160161162163143 unmodified lines# --- 4. Notify Customer of Expert Response ---# Only if sender is staff and message is publicif 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 availabletry:# Correct arq call: do NOT pass ctx/None explicitlyawait arq_pool.enqueue_job("send_triple_notification",str(ticket.created_by),str(ticket.workspace_id),4 unmodified linesexcept Exception as e:logger.error(f"Failed to queue customer response notification: {e}")return await sanitize_message_response(new_message, db)143 unmodified lines1441451461471481491504 unmodified lines155156157158159160161162163164165166167168169170171172173174143 unmodified lines# --- 4. Notify Customer of Expert Response ---# Only if sender is staff and message is publicif is_staff and not payload.is_internal and ticket.created_by != current_user.id:try:await arq_pool.enqueue_job("send_triple_notification",str(ticket.created_by),str(ticket.workspace_id),4 unmodified linesexcept 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 notifyif 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 lines415416417418419420421312 unmodified lines734735736737738739740741742743744745746747218 unmodified lines96696796896997097197255 unmodified lines1028102910301031103210331034103510361037103810391040104110427 unmodified lines105010511052105310541055414 unmodified lines# KB search integrated into the parallel flowasync def run_kb_search():async with async_session_factory() as session:return await execute_multimodal_search(session, q, current_user, None, project_id)kb_task = run_kb_search()312 unmodified linesticket.resolution_text = "This issue has been resolved. Thanks!"# Notify Creator of Resolutionbackground_tasks.add_task(send_triple_notification,None,ticket.created_by,ticket.workspace_id,"✅ Ticket Resolved",f"Great news! Your ticket '{ticket.title}' has been marked as {new_status}.")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)) -> 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 Protocolfrom agents.utils import get_workspace_managerfrom core.tasks import send_triple_notificationmanager_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 ituser_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.",link=f"/dashboard?ticket={ticket.id}")7 unmodified lineslink=f"/dashboard?ticket={ticket.id}")logger.info(f"Ticket {ticket.id} manually escalated by {current_user.id}")# Refresh to pick up lead info in sanitizer414 unmodified lines415416417418419420421422423312 unmodified lines736737738739740741742743744745746747748749750751752753754755756757218 unmodified lines97697797897998098198298355 unmodified lines103910401041104210431044104510461047104810491050105110527 unmodified lines10601061106210631064106510661067106810691070107110721073107410751076414 unmodified lines# KB search integrated into the parallel flowasync def run_kb_search():async with async_session_factory() as session:return await execute_multimodal_search(session, q, current_user, None, project_id, current_user.workspace_id)kb_task = run_kb_search()312 unmodified linesticket.resolution_text = "This issue has been resolved. Thanks!"# Notify Creator of Resolutionawait 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 startedawait 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),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 Protocolfrom agents.utils import get_workspace_managermanager_user = await get_workspace_manager(db, ticket.workspace_id)if manager_user: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 lineslink=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 sanitizer
59 unmodified lines60616263646566672 unmodified lines7071727374752 unmodified lines787980818283848 unmodified lines93949596979859 unmodified linescurrent_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)}")stmt = select(Workspace).where(Workspace.id == current_user.workspace_id,Workspace.deleted_at.is_(None)2 unmodified linesworkspace = result.scalar_one_or_none()if not workspace:raise HTTPException(status_code=404, detail="Workspace not found")return workspace@router.patch("/", response_model=WorkspaceResponse, dependencies=[Depends(require_roles(WORKSPACE_ADMIN_ROLES))])2 unmodified linescurrent_user: User = Depends(get_current_user),db: AsyncSession = Depends(get_db)) -> Any:"""Admin only: Update workspace settings/branding."""stmt = select(Workspace).where(Workspace.id == current_user.workspace_id,Workspace.deleted_at.is_(None)8 unmodified linesdb.add(workspace)await db.commit()await db.refresh(workspace)return workspace@router.get("/branding/")59 unmodified lines60616263646566676869707172732 unmodified lines767778798081828384852 unmodified lines888990919293948 unmodified lines10310410510610710810911011111211359 unmodified linescurrent_user: User = Depends(get_current_user),db: AsyncSession = Depends(get_db)) -> Any:"""Get current workspace details (Cached)."""from core.cache import get_cached_object, set_cached_objectcache_key = f"ws:meta:{current_user.workspace_id}"cached = await get_cached_object(cache_key)if cached:return cachedstmt = select(Workspace).where(Workspace.id == current_user.workspace_id,Workspace.deleted_at.is_(None)2 unmodified linesworkspace = 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_encoderawait 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 linescurrent_user: User = Depends(get_current_user),db: AsyncSession = Depends(get_db)) -> Any:"""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 linesdb.add(workspace)await db.commit()await db.refresh(workspace)# Invalidate Cachefrom core.cache import invalidate_cacheawait invalidate_cache(f"ws:meta:{current_user.workspace_id}")return workspace@router.get("/branding/")
56 unmodified lines57585960616256 unmodified linesexcept Exception:passclass SemanticCacheManager:"""Manages semantic LLM response caching using pgvector.56 unmodified lines575859606162636465666768697071727374757677787980818283848586878889909156 unmodified linesexcept 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:passreturn Noneasync 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:passasync def invalidate_cache(key: str) -> None:"""Explicitly purges a cache key."""try:client = get_redis_client()await client.delete(key)except Exception:passclass SemanticCacheManager:"""Manages semantic LLM response caching using pgvector.
19 unmodified lines20212223242526274 unmodified lines3233343536373839404119 unmodified linesconst { user, token, loading: authLoading, error: authError, login, logout, refreshUser } = useAuth();const { tickets, loading: ticketsLoading, createTicket } = useTickets();const { stats, loading: statsLoading } = useDashboardStats();useAIInsights();useServiceNarrative();const [active, setActive] = useState<"dashboard" | "tickets" | "kb" | "analytics" | "thread" | "workspace">("dashboard");const [showNewTicket, setShowNewTicket] = useState(false);4 unmodified linesreturn <LoginCard onLogin={login} loading={authLoading} portal="customer" error={authError} />;}// Pre-load logic: Wait for auth, tickets, stats, and AI before revealing the portalconst isInitialLoading = (authLoading && !user) || (user && ((ticketsLoading && tickets.length === 0) ||(statsLoading && !stats)));if (isInitialLoading) {19 unmodified lines20212223242526274 unmodified lines32333435363738394041424319 unmodified linesconst { user, token, loading: authLoading, error: authError, login, logout, refreshUser } = useAuth();const { tickets, loading: ticketsLoading, createTicket } = useTickets();const { stats, loading: statsLoading } = useDashboardStats();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 linesreturn <LoginCard onLogin={login} loading={authLoading} portal="customer" error={authError} />;}// Pre-load logic: Wait for auth, tickets, stats, insights AND narrative before revealing the portalconst isInitialLoading = (authLoading && !user) || (user && ((ticketsLoading && tickets.length === 0) ||(statsLoading && !stats) ||(insightsLoading && !insights) ||(narrativeLoading && !narrative)));if (isInitialLoading) {
116 unmodified lines117118119120121122123124116 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: "✅" }].map(s => (<div key={s.label} style={{background: "rgba(255, 255, 255, 0.12)",116 unmodified lines117118119120121122123124116 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?.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 lines151617181920212223242 unmodified lines272829303132333435363738394041424344454647484928 unmodified lines7879808182838414 unmodified lineserror: "#DC2626",};export const WorkspaceView: React.FC<{ user: any }> = ({ user }) => {const [workspace, setWorkspace] = useState<any>(null);const [members, setMembers] = useState<any[]>([]);const [loading, setLoading] = useState(true);// New User Formconst [showAddForm, setShowAddForm] = useState(false);2 unmodified linesconst isAdmin = user.role.includes('admin');useEffect(() => {fetchWorkspaceData();}, []);const fetchWorkspaceData = async () => {setLoading(true);try {const [wsResp, usersResp] = await Promise.all([api.get('workspace/'),api.get('users/')]);setWorkspace(wsResp.data);setMembers(usersResp.data);} catch (err) {console.error("Failed to fetch workspace data:", err);} finally {setLoading(false);}};28 unmodified lines}};if (loading) return <div style={{ padding: 40, color: COLORS.gray400 }}>Loading workspace intelligence...</div>;return (<div style={{ padding: "40px", maxWidth: 1200, margin: "0 auto" }}>14 unmodified lines15161718192021222324252 unmodified lines2829303132333435363738394041424344454647484950515228 unmodified lines8182838485868714 unmodified lineserror: "#DC2626",};import { useWorkspace, useUsers } from '@nexus/shared';export const WorkspaceView: React.FC<{ user: any }> = ({ user }) => {const { workspace, loading: workspaceLoading, refresh: refreshWorkspace } = useWorkspace();const { users: members, loading: usersLoading, refresh: refreshUsers, addUser } = useUsers();// New User Formconst [showAddForm, setShowAddForm] = useState(false);2 unmodified linesconst isAdmin = user.role.includes('admin');// 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 handleCreateUser = async (e: React.FormEvent) => {e.preventDefault();setSubmitting(true);try {await addUser(form);setForm({ email: '', full_name: '', password: '', role: 'customer_user' });// Brief delay before closing for better feedbacksetTimeout(() => {setShowAddForm(false);setSubmitting(false);}, 500);} catch (err) {console.error("Failed to create user:", err);alert("Error creating user. Check email uniqueness and permissions.");setSubmitting(false);}};28 unmodified lines}};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 lines989910010110210397 unmodified linesreturn <KnowledgeBase workspaceId={selectedWorkspaceId} />;case 'escalation':return isAdminOrLead ? <EscalationCentre /> : forbidden;return (<AnalyticsDashboardworkspaceId={selectedWorkspaceId}97 unmodified lines989910010110210310497 unmodified linesreturn <KnowledgeBase workspaceId={selectedWorkspaceId} />;case 'escalation':return isAdminOrLead ? <EscalationCentre /> : forbidden;case 'analytics':return (<AnalyticsDashboardworkspaceId={selectedWorkspaceId}
846 unmodified lines847848849850851852853854855856857858859860861846 unmodified lines}.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;846 unmodified lines847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887846 unmodified lines}.answerText {font-size: 16px;line-height: 1.8;color: var(--text-main);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 lines456457458459460461455 unmodified lines</motion.div>) : (<div className={styles.resultsContainer}><motion.divkey="grid"className={styles.articlesGrid}455 unmodified lines456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487455 unmodified lines</motion.div>) : (<div className={styles.resultsContainer}><AnimatePresence>{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.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.divkey="grid"className={styles.articlesGrid}
7 unmodified lines8910111213141516171819207 unmodified linesbranding?: 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>();const notifyWorkspaces = () => workspacesListeners.forEach(l => l(globalWorkspaces, globalWorkspacesLoading, globalWorkspacesError));export const useWorkspaces = () => {const [localWorkspaces, setLocalWorkspaces] = useState(globalWorkspaces);7 unmodified lines89101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657587 unmodified linesbranding?: any;}// 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 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