Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit ·
ca7df66
1
Parent(s): dfcbb7c
backend stabilization
Browse filesFiles changed (15)
- agents/nexus_master.py+15-16
- agents/prompts.py+16-4
- agents/tools/langchain_tools.py+4-5
- agents/tools/tool_registry.py+5-9
- api/v1/dashboard.py+58-4
- api/v1/kb.py+61-19
- api/v1/nexus.py+37-11
- api/v1/nexus_stream.py+36-7
- api/v1/reports.py+17
- core/cache.py+11-2
- frontend/apps/internal/src/App.tsx+2-2
- frontend/apps/internal/src/components/KnowledgeBase.tsx+11-5
- frontend/apps/internal/src/components/NexusMasterAgent.tsx+69-21
- frontend/packages/shared/src/hooks/useDashboard.ts+24-9
- frontend/packages/shared/src/hooks/useTickets.ts+8-3
181 unmodified lines182183184185186187196 unmodified lines384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416181 unmodified lines"ticket_context": state.get("ticket_context", "None")})# 5. Extract Native Tool Callsreturn {"messages": [response]}196 unmodified linesprompt = ChatPromptTemplate.from_messages([("system", system_prompt),# Memory Layer: Full conversation history, including tool calls and outputs!MessagesPlaceholder(variable_name="messages")])chain = prompt | llmfrom langchain_core.exceptions import OutputParserExceptiontry:# We pass the full message list to the placeholderstructured_response = await chain.ainvoke({"messages": state["messages"]})text_content = structured_response.responseconf = structured_response.confidence_scoreexcept OutputParserException as e:# Local LLMs (Ollama) frequently ignore structured output instructions and return raw text.# We catch the parser exception, extract the generated text, and default the confidence score.text_content = str(getattr(e, 'llm_output', e.args[0]))if text_content.startswith("Invalid json output: "):text_content = text_content[len("Invalid json output: "):]conf = 0.9 # Default to high confidence to avert false escalation promptsexcept Exception as e:import tracebacktraceback.print_exc()text_content = "I encountered an internal formatting error trying to generate a response."conf = 0.0# AI Fallback Escalation Nudge181 unmodified lines182183184185186187188189190196 unmodified lines387388389390391392393394395396397398399400401402403404405406407408409410411412413414415181 unmodified lines"ticket_context": state.get("ticket_context", "None")})# Fast-Path: If NO tool calls but very short message, bypass responder loop if needed?# Actually, LangGraph's router node works best by just returning the message with tool_calls.# 5. Extract Native Tool Callsreturn {"messages": [response]}196 unmodified linesprompt = ChatPromptTemplate.from_messages([("system", system_prompt),MessagesPlaceholder(variable_name="messages")])chain = prompt | get_llm()try:# OPTIMIZED PATH: Standard ainvoke (5x faster on local Ollama than structured output)response = await chain.ainvoke({"messages": state["messages"]})text_content = response.content if hasattr(response, 'content') else str(response)# Heuristic Confidence Evaluation (replaces expensive structured inference)conf = 0.95if "i don't know" in text_content.lower() or "not sure" in text_content.lower():conf = 0.3elif len(text_content) < 10:conf = 0.5except Exception as e:import tracebacktraceback.print_exc()text_content = "I encountered an internal error trying to generate a response."conf = 0.0# AI Fallback Escalation Nudge
43 unmodified lines44454647484950512 unmodified lines545556575859606143 unmodified lines"""ROUTER_PROMPT_V2 = """You are the Nexus Intent Resolver.Analyze the conversation history and invoke the appropriate tools to help the user.Persona: {persona} (Is internal staff: {is_agent})Context: {{ "ticket_id": "{ticket_id}" }}2 unmodified linesTICKET_DATA (AUTOMATICALLY LOADED):{ticket_context}Constraint: For any request involving visualization or trends, prioritize the ANALYTICS tool alone. Avoid redundant SIMILAR_INCIDENTS calls unless explicitly troubleshoot-related.If the request requires no tools, use the CONVERSE tool to respond natively, or if you need to ask clarifying questions."""RESPONDER_SYSTEM_PROMPT_V1 = """43 unmodified lines4445464748495051525354555657585960616263642 unmodified lines6768697071727343 unmodified lines"""ROUTER_PROMPT_V2 = """You are the Nexus Intelligence Router. Your goal is to resolve user requests by orchestrating the most appropriate specialized tools.CORE ARCHITECTURE:1. KB_SEARCH: MUST use for any technical questions, "how-to" queries, or searching documentation.- Keywords: search, find, how, what, why, article, docs.2. TICKETS: Use to check status, history, or recent activity of support tickets.- Keywords: status, active, recent, my tickets, update on.3. SIMILAR_INCIDENTS: Use ONLY when troubleshooting a specific technical error to find past resolutions.4. ANALYTICS: Use for any request involving data visualization, trends, charts, or "heatmaps".5. CONVERSE: Use ONLY if no data retrieval is needed, or for asking clarifying questions.STRATEGIC DIRECTIVES:- SEARCH FIRST: Never guess. If a user asks a factual question, your FIRST instinct must be to call KB_SEARCH or TICKETS.- CONTEXTUAL AWARENESS: You have access to active ticket data below. Use it to skip redundant questions.- RBAC: You are operating as {persona}. Respect boundaries.Persona: {persona} (Is internal staff: {is_agent})Context: {{ "ticket_id": "{ticket_id}" }}2 unmodified linesTICKET_DATA (AUTOMATICALLY LOADED):{ticket_context}Respond ONLY with the tool call. If the request requires no specialized data, respond with CONVERSE."""RESPONDER_SYSTEM_PROMPT_V1 = """
25 unmodified lines26272829303132333435363738393 unmodified lines4344454647484925 unmodified lines@tool(args_schema=KBSearchInput)async def kb_search(query: str, **kwargs) -> str:"""Search the Knowledge Base for relevant articles and technical solutions."""# Note: Execution logic expects workspace_id to be injected dynamically in the executor# so we will actually still handle execution manually in the executor for Stage 1B.pass@tool(args_schema=TicketQueryInput)async def tickets(ticket_id: Optional[str] = None, status_filter: Optional[str] = None, **kwargs) -> str:"""Retrieve ticket status, AI summaries, and recent activity."""pass@tool(args_schema=AnalyticsInput)3 unmodified lines@tool(args_schema=SimilarIncidentsInput)async def similar_incidents(query: str, **kwargs) -> str:"""Find top 3 similar resolved tickets for troubleshooting. USE ONLY for troubleshooting."""pass@tool(args_schema=ProjectPulseInput)25 unmodified lines262728293031323334353637383 unmodified lines4243444546474825 unmodified lines@tool(args_schema=KBSearchInput)async def kb_search(query: str, **kwargs) -> str:"""Search the Knowledge Base for relevant articles, technical documentation, and 'how-to' guides. USE THIS for any technical or process-related questions."""# Execution logic is handled in the graph executorpass@tool(args_schema=TicketQueryInput)async def tickets(ticket_id: Optional[str] = None, status_filter: Optional[str] = None, **kwargs) -> str:"""Retrieve ticket status, AI summaries, and recent activity. USE THIS to check on active issues or historical ticket data."""pass@tool(args_schema=AnalyticsInput)3 unmodified lines@tool(args_schema=SimilarIncidentsInput)async def similar_incidents(query: str, **kwargs) -> str:"""Find top 3 similar resolved tickets for troubleshooting. USE ONLY for matching current errors against past known resolutions."""pass@tool(args_schema=ProjectPulseInput)
238 unmodified lines23924024124224324424524624724824917 unmodified lines267268269270271272273274275276277238 unmodified lines"sc_admin": ToolPermission.SUPER_ADMIN,}# Permission hierarchy for inclusion checks_PERMISSION_HIERARCHY = {ToolPermission.ALL: {ToolPermission.ALL, ToolPermission.STAFF, ToolPermission.SUPER_ADMIN},ToolPermission.STAFF: {ToolPermission.STAFF, ToolPermission.SUPER_ADMIN},ToolPermission.SUPER_ADMIN: {ToolPermission.SUPER_ADMIN},}17 unmodified linesuser_perm = ToolPermission.STAFF# Which tool permissions can this user access?allowed_perms = _PERMISSION_HIERARCHY.get(ToolPermission.ALL, {ToolPermission.ALL})if user_perm == ToolPermission.STAFF:allowed_perms = {ToolPermission.ALL, ToolPermission.STAFF}elif user_perm == ToolPermission.SUPER_ADMIN:allowed_perms = {ToolPermission.ALL, ToolPermission.STAFF, ToolPermission.SUPER_ADMIN}return [t for t in TOOL_CATALOG if t.permission in allowed_perms]238 unmodified lines23924024124224324424524624724824917 unmodified lines267268269270271272273238 unmodified lines"sc_admin": ToolPermission.SUPER_ADMIN,}# Permission hierarchy for inclusion checks (Strict Upward Model)_PERMISSION_HIERARCHY = {ToolPermission.ALL: {ToolPermission.ALL},ToolPermission.STAFF: {ToolPermission.ALL, ToolPermission.STAFF},ToolPermission.SUPER_ADMIN: {ToolPermission.ALL, ToolPermission.STAFF, ToolPermission.SUPER_ADMIN},}17 unmodified linesuser_perm = ToolPermission.STAFF# Which tool permissions can this user access?allowed_perms = _PERMISSION_HIERARCHY.get(user_perm, {ToolPermission.ALL})return [t for t in TOOL_CATALOG if t.permission in allowed_perms]
22 unmodified lines232425262728293031123 unmodified lines15515615715815916031 unmodified lines19219319419519619719819920020143 unmodified lines24524624724824925025125225325425525625725825927 unmodified lines28728828929029129229329429529629747 unmodified lines34534634734834935035135235335422 unmodified lines@router.get("/stats/")async def get_dashboard_stats(workspace_id: str = None,current_user: User = Depends(get_current_user),db: AsyncSession = Depends(get_db)) -> Any:from datetime import datetimeis_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]123 unmodified lines"personnel_load": personnel_load})return response31 unmodified lines@router.get("/agent-queue/", response_model=List[Union[TicketInternalResponse, TicketResponse]])async def get_agent_queue(workspace_id: str = None,current_user: User = Depends(get_current_user),db: AsyncSession = Depends(get_db)) -> Any:"""Get the active ticket queue. Restricted to internal staff only."""from fastapi import HTTPExceptionfrom sqlalchemy.orm import joinedloadfrom api.v1.tickets import sanitize_ticket_response43 unmodified linestickets = result.scalars().all()# Process each through sanitizer (will return full forensic view for staff)return [await sanitize_ticket_response(t, current_user, db) for t in tickets]@router.get("/ai-insights/")async def get_ai_insights(workspace_id: str = None,current_user: User = Depends(get_current_user),db: AsyncSession = Depends(get_db)) -> Any:"""Generates a live AI summary and suggested actions for the landing screen.Special Mode: For Super-Admins, returns the cached global platform strategic analysis.27 unmodified lines# 2. Standard Workspace Mode (Isolated)# Gather contextstats = await get_dashboard_stats(workspace_id, current_user, db)# Context varies by role: Staff get the full Queue, Customers get their recent activityif is_staff:queue = await get_agent_queue(workspace_id, current_user, db)else:# Fallback for CUSTOMER_ADMIN/USER: Get their workspace-visible ticketsfrom api.v1.tickets import list_tickets47 unmodified linesinsights = json.loads(json_str)# Ensure schema compliancereturn {"summary": insights.get("summary", "Analysis complete."),"actions": insights.get("actions", ["Review unassigned tickets", "Check SLA trends", "Balance personnel load"])[:3]}except Exception as e:logger.error(f"AI Insights Failure: {e}")return {22 unmodified lines2324252627282930313233343536373839404142434445123 unmodified lines16917017117217317417517617731 unmodified lines20921021121221321421521621721821922022122222322422522622722822923023123243 unmodified lines27627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730827 unmodified lines33633733833934034134234334434534647 unmodified lines39439539639739839940040140240340440540640740822 unmodified lines@router.get("/stats/")async def get_dashboard_stats(workspace_id: str = None,refresh: bool = False,current_user: User = Depends(get_current_user),db: AsyncSession = Depends(get_db)) -> Any:from core.cache import get_cached_search, set_cached_search, delete_cached_search# Cache lookuptarget_ws = workspace_id or str(current_user.workspace_id)cache_key = f"dashboard:stats:{target_ws}:{current_user.id}"if refresh:await delete_cached_search(cache_key)else:cached_data = await get_cached_search(cache_key)if cached_data:return cached_datafrom datetime import datetimeis_staff = current_user.role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]123 unmodified lines"personnel_load": personnel_load})# Store in cache (60s TTL for stats)await set_cached_search(cache_key, response, ttl=60)return response31 unmodified lines@router.get("/agent-queue/", response_model=List[Union[TicketInternalResponse, TicketResponse]])async def get_agent_queue(workspace_id: str = None,refresh: bool = False,current_user: User = Depends(get_current_user),db: AsyncSession = Depends(get_db)) -> Any:"""Get the active ticket queue. Restricted to internal staff only."""from core.cache import get_cached_search, set_cached_search, delete_cached_search# 0. Cache lookuptarget_ws = workspace_id or str(current_user.workspace_id)cache_key = f"dashboard:queue:{target_ws}:{current_user.id}"if refresh:await delete_cached_search(cache_key)else:cached_data = await get_cached_search(cache_key)if cached_data:return cached_datafrom fastapi import HTTPExceptionfrom sqlalchemy.orm import joinedloadfrom api.v1.tickets import sanitize_ticket_response43 unmodified linestickets = result.scalars().all()# Process each through sanitizer (will return full forensic view for staff)res_data = [await sanitize_ticket_response(t, current_user, db) for t in tickets]# Store in cache (60s TTL)await set_cached_search(cache_key, res_data, ttl=60)return res_data@router.get("/ai-insights/")async def get_ai_insights(workspace_id: str = None,refresh: bool = False,current_user: User = Depends(get_current_user),db: AsyncSession = Depends(get_db)) -> Any:from core.cache import get_cached_search, set_cached_search, delete_cached_searchtarget_ws = workspace_id or str(current_user.workspace_id)cache_key = f"dashboard:insights:{target_ws}:{current_user.id}"if refresh:await delete_cached_search(cache_key)else:cached_data = await get_cached_search(cache_key)if cached_data:return cached_data"""Generates a live AI summary and suggested actions for the landing screen.Special Mode: For Super-Admins, returns the cached global platform strategic analysis.27 unmodified lines# 2. Standard Workspace Mode (Isolated)# Gather contextstats = await get_dashboard_stats(workspace_id, refresh=refresh, current_user=current_user, db=db)# Context varies by role: Staff get the full Queue, Customers get their recent activityif is_staff:queue = await get_agent_queue(workspace_id, refresh=refresh, current_user=current_user, db=db)else:# Fallback for CUSTOMER_ADMIN/USER: Get their workspace-visible ticketsfrom api.v1.tickets import list_tickets47 unmodified linesinsights = json.loads(json_str)# Ensure schema complianceresult = {"summary": insights.get("summary", "Analysis complete."),"actions": insights.get("actions", ["Review unassigned tickets", "Check SLA trends", "Balance personnel load"])[:3]}# Store in cache (300s TTL for insights)await set_cached_search(cache_key, result, ttl=300)return resultexcept Exception as e:logger.error(f"AI Insights Failure: {e}")return {
1234517 unmodified lines23242526272861 unmodified lines9091929394959620 unmodified lines11711811912012112212323 unmodified lines14714814915015115215323 unmodified lines17717817918018118218318418518618713 unmodified lines20120220320420520620720820921021110 unmodified lines22222322422522622722822923023123281 unmodified lines3143153163173183193203213223233243253263273283 unmodified lines3323333343353363373384 unmodified lines34334434534634734834914 unmodified lines36436536636736836937053 unmodified lines424425426427428429430431432import asyncioimport asyncioimport timefrom datetime import datetimefrom typing import Any, List, Optional17 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_search, SemanticCacheManagerfrom schemas.kb import KBArticleCreate, KBArticleResponse, KBArticleUpdate, KBSearchResponse, KBBulkActionRequest, KBBulkSyncRequest61 unmodified lines)if not is_global:target_ws = workspace_id if (workspace_id and current_user.role == UserRole.SC_ADMIN) else current_user.workspace_idstmt = stmt.where(KBArticle.workspace_id == target_ws)if category:20 unmodified lines)if not is_global:target_ws = workspace_id if (workspace_id and current_user.role == UserRole.SC_ADMIN) else current_user.workspace_idstmt = stmt.where(KBArticle.workspace_id == target_ws)result = await db.execute(stmt)23 unmodified lineslogger.error(f"Query expansion failed: {e}")return []async def execute_multimodal_search(db: AsyncSession, q: str, current_user: User, category: Optional[str], project_id: Optional[UUID]):"""Internal helper to execute factual hybrid search + visual attachment search."""import uuidimport time23 unmodified lines.where(KBArticle.deleted_at.is_(None),KBArticle.is_published == True,KBArticle.duplicate_of_id.is_(None)))if current_user.role != UserRole.SC_ADMIN:semantic_stmt = semantic_stmt.where(KBArticle.workspace_id == current_user.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)13 unmodified lines.where(KBArticle.deleted_at.is_(None),KBArticle.is_published == True,Attachment.search_vector.op("@@")(func.plainto_tsquery('english', q))))if current_user.role != UserRole.SC_ADMIN:visual_stmt = visual_stmt.where(KBArticle.workspace_id == current_user.workspace_id)visual_stmt = visual_stmt.order_by(desc("vis_score")).limit(10)# 4. SEARCH C: Keyword Match (FTS on Title/Content)10 unmodified lines.where(KBArticle.deleted_at.is_(None),KBArticle.is_published == True,KBArticle.search_vector.op("@@")(func.plainto_tsquery('english', q))))if current_user.role != UserRole.SC_ADMIN:keyword_stmt = keyword_stmt.where(KBArticle.workspace_id == current_user.workspace_id)if category: keyword_stmt = keyword_stmt.where(KBArticle.category == category)if project_id: keyword_stmt = keyword_stmt.where(KBArticle.project_id == project_id)keyword_stmt = keyword_stmt.order_by(desc("kw_score")).limit(15)81 unmodified linesq: str,category: Optional[str] = None,project_id: Optional[UUID] = None,current_user: User = Depends(get_current_user),db: AsyncSession = Depends(get_db)) -> Any:"""Advanced Search with LLM Multi-Query Expansion for maximum reliability."""start_time = time.perf_counter()# 0. Local Search Cache Lookup (Dual-Redis Architecture)cache_filters = {"category": category, "project_id": str(project_id) if project_id else None}cache_key = generate_cache_key("kb", str(current_user.workspace_id), q, cache_filters)cached_res = await get_cached_search(cache_key)if cached_res:logger.info(f"⚡ Search Cache HIT [KB]: {q}")3 unmodified linesis_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))4 unmodified linespass # 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)# 2. Start LLM Expansion concurrently (if not a trivial query)expanded_queries = []14 unmodified lines# 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)var_tasks = [run_variation_search(v) for v in expanded_queries if v != q]if var_tasks:53 unmodified linesis_ai_synthetic = True# Persist to Semantic Cacheimport asyncioasyncio.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)))123417 unmodified lines2223242526272861 unmodified lines9091929394959697989910010110210310410510610710820 unmodified lines12913013113213313413513613713813914014114214314414514614723 unmodified lines17117217317417517617717817918018118218318423 unmodified lines20820921021121221321421521621713 unmodified lines23123223323423523623723823924010 unmodified lines25125225325425525625725825926081 unmodified lines3423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713 unmodified lines3753763773783793803814 unmodified lines38638738838939039139214 unmodified lines40740840941041141241353 unmodified lines467468469470471472473474import asyncioimport timefrom datetime import datetimefrom typing import Any, List, Optional17 unmodified linesfrom core.search import chunk_textfrom core.vision import extract_visual_contextfrom core.sync import sync_markdown_imagesfrom models.user_workspace import UserWorkspacefrom core.cache import generate_cache_key, get_cached_search, set_cached_search, SemanticCacheManagerfrom schemas.kb import KBArticleCreate, KBArticleResponse, KBArticleUpdate, KBSearchResponse, KBBulkActionRequest, KBBulkSyncRequest61 unmodified lines)if not is_global:target_ws = current_user.workspace_idif workspace_id and current_user.role in ALL_SC_ROLES:if current_user.role == UserRole.SC_ADMIN:target_ws = workspace_idelse: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_idstmt = stmt.where(KBArticle.workspace_id == target_ws)if category:20 unmodified lines)if not is_global:target_ws = current_user.workspace_idif workspace_id and current_user.role in ALL_SC_ROLES:if current_user.role == UserRole.SC_ADMIN:target_ws = workspace_idelse: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_idstmt = stmt.where(KBArticle.workspace_id == target_ws)result = await db.execute(stmt)23 unmodified lineslogger.error(f"Query expansion failed: {e}")return []async def execute_multimodal_search(db: AsyncSession,q: str,current_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 uuidimport time23 unmodified lines.where(KBArticle.deleted_at.is_(None),KBArticle.is_published == True,KBArticle.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)13 unmodified lines.where(KBArticle.deleted_at.is_(None),KBArticle.is_published == True,Attachment.search_vector.op("@@")(func.plainto_tsquery('english', q)),KBArticle.workspace_id == workspace_id))visual_stmt = visual_stmt.order_by(desc("vis_score")).limit(10)# 4. SEARCH C: Keyword Match (FTS on Title/Content)10 unmodified lines.where(KBArticle.deleted_at.is_(None),KBArticle.is_published == True,KBArticle.search_vector.op("@@")(func.plainto_tsquery('english', q)),KBArticle.workspace_id == workspace_id))if category: keyword_stmt = keyword_stmt.where(KBArticle.category == category)if project_id: keyword_stmt = keyword_stmt.where(KBArticle.project_id == project_id)keyword_stmt = keyword_stmt.order_by(desc("kw_score")).limit(15)81 unmodified linesq: str,category: Optional[str] = None,project_id: Optional[UUID] = None,workspace_id: Optional[UUID] = None,current_user: User = Depends(get_current_user),db: AsyncSession = Depends(get_db)) -> Any:"""Advanced Search with LLM Multi-Query Expansion for maximum reliability."""start_time = time.perf_counter()target_ws = current_user.workspace_idif workspace_id and current_user.role in ALL_SC_ROLES:if current_user.role == UserRole.SC_ADMIN:target_ws = workspace_idelse: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# 0. Local Search Cache Lookup (Dual-Redis Architecture)cache_filters = {"category": category, "project_id": str(project_id) if project_id else None}cache_key = generate_cache_key("kb", str(target_ws), q, cache_filters)cached_res = await get_cached_search(cache_key)if cached_res:logger.info(f"⚡ Search Cache HIT [KB]: {q}")3 unmodified linesis_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(target_ws), 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))4 unmodified linespass # 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, workspace_id=target_ws)# 2. Start LLM Expansion concurrently (if not a trivial query)expanded_queries = []14 unmodified lines# 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)var_tasks = [run_variation_search(v) for v in expanded_queries if v != q]if var_tasks:53 unmodified linesis_ai_synthetic = True# Persist to Semantic Cacheasyncio.create_task(SemanticCacheManager.set_cache(str(target_ws), 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)))
20 unmodified lines21222324252614 unmodified lines41424344454647484950515253545556575859606162636427 unmodified lines929394959697989928 unmodified lines12812913013113213313413513613713813920 unmodified linesquery: strchat_history: List[Dict[str, str]] = [] # [{"role": "user", "content": "..."}, ...]thread_id: Optional[UUID] = Noneticket_id: Optional[UUID] = Noneaction_approved: bool = False14 unmodified linesfrom sqlalchemy import selectfrom models.nexus_interaction import NexusInteraction# 1. Prepare Initial Stateis_agent = current_user.role in [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN, UserRole.CUSTOMER_ADMIN]# 0. Semantic Cache Interception (Zero-Latency Bypassing)cache_hit = await SemanticCacheManager.check_cache(str(current_user.workspace_id),payload.query,is_agent=is_agent,user_role=current_user.role)if cache_hit:return NexusResponse(answer=cache_hit, sources=["Semantic Cache (Bypassed Computation)"])# Validation: If ticket_id provided, it MUST exist in this workspaceif payload.ticket_id:from models.ticket import Ticketfrom sqlalchemy import selectstmt = select(Ticket).where(Ticket.id == payload.ticket_id, Ticket.workspace_id == current_user.workspace_id)res = await db.execute(stmt)if not res.scalar_one_or_none():raise HTTPException(27 unmodified linesinitial_state = {"messages": messages,"workspace_id": current_user.workspace_id,"user_role": current_user.role,"is_agent": is_agent,"user_name": current_user.full_name,"user_id": current_user.id,28 unmodified lines# 4. Fire-and-forget Cache Populationimport asyncioasyncio.create_task(SemanticCacheManager.set_cache(workspace_id=str(current_user.workspace_id),user_id=str(current_user.id),query=payload.query,response_text=sanitized_msg,is_agent=is_agent,user_role=current_user.role))return NexusResponse(20 unmodified lines2122232425262714 unmodified lines4243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899027 unmodified lines11811912012112212312412528 unmodified lines15415515615715815916016116216316416520 unmodified linesquery: strchat_history: List[Dict[str, str]] = [] # [{"role": "user", "content": "..."}, ...]thread_id: Optional[UUID] = Noneworkspace_id: Optional[UUID] = Noneticket_id: Optional[UUID] = Noneaction_approved: bool = False14 unmodified linesfrom sqlalchemy import selectfrom models.nexus_interaction import NexusInteraction# 1. Prepare Initial State & Identity Bifurcation# Strictly isolate Staff (Master Agent) from Customers (Customer Agent)is_agent = current_user.role in [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]# Contextual Workspace & Role Overridetarget_workspace_id = payload.workspace_id or current_user.workspace_idtarget_role = current_user.roleif payload.workspace_id:# Security Verification: Ensure user has access to the requested workspacefrom models.user_workspace import UserWorkspacews_stmt = select(UserWorkspace).where(UserWorkspace.user_id == current_user.id,UserWorkspace.workspace_id == payload.workspace_id)ws_res = await db.execute(ws_stmt)active_link = ws_res.scalar_one_or_none()if not active_link:raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,detail=f"Access Denied: You are not a member of workspace {payload.workspace_id}")# Override role based on context (Crucial for 3SC Staff acting in Customer Workspaces)target_role = active_link.role# 0. Semantic Cache Interception (Zero-Latency Bypassing)cache_hit = await SemanticCacheManager.check_cache(workspace_id=str(target_workspace_id),query=payload.query,is_agent=is_agent,user_role=str(target_role),user_id=str(current_user.id) # Include user_id for strict identity isolation)if cache_hit:return NexusResponse(answer=cache_hit, sources=["Semantic Cache (Bypassed Computation)"])# Validation: If ticket_id provided, it MUST exist in this targeted workspaceif payload.ticket_id:from models.ticket import Ticketfrom sqlalchemy import selectstmt = select(Ticket).where(Ticket.id == payload.ticket_id, Ticket.workspace_id == target_workspace_id)res = await db.execute(stmt)if not res.scalar_one_or_none():raise HTTPException(27 unmodified linesinitial_state = {"messages": messages,"workspace_id": target_workspace_id,"user_role": str(target_role),"is_agent": is_agent,"user_name": current_user.full_name,"user_id": current_user.id,28 unmodified lines# 4. Fire-and-forget Cache Populationimport asyncioasyncio.create_task(SemanticCacheManager.set_cache(workspace_id=str(target_workspace_id),user_id=str(current_user.id),query=payload.query,response_text=sanitized_msg,is_agent=is_agent,user_role=str(target_role)))return NexusResponse(
64 unmodified lines6566676869707110 unmodified lines8283848586878889909192933 unmodified lines97989910010110210326 unmodified lines13013113213313413513613764 unmodified linesworkspace_id=str(initial_state["workspace_id"]),user_id=str(initial_state["user_id"]),query=initial_state["messages"][-1].content,response_text=final_text))except Exception as e:10 unmodified linesStreaming entry point for natural language workspace interaction.Delivers token-by-token responses and live tool updates via SSE."""# 1. Prepare Initial State (duplicated core setup from nexus.py)is_agent = current_user.role in [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN, UserRole.CUSTOMER_ADMIN]# 0. Semantic Cache Interception (Zero-Latency SSE Masking)from core.cache import SemanticCacheManagercache_hit = await SemanticCacheManager.check_cache(str(current_user.workspace_id), payload.query)if cache_hit:async def cached_event_generator():3 unmodified linesreturn StreamingResponse(cached_event_generator(), media_type="text/event-stream")if payload.ticket_id:stmt = select(Ticket).where(Ticket.id == payload.ticket_id, Ticket.workspace_id == current_user.workspace_id)res = await db.execute(stmt)if not res.scalar_one_or_none():raise HTTPException(26 unmodified linesinitial_state = {"messages": messages,"workspace_id": current_user.workspace_id,"user_role": current_user.role,"is_agent": is_agent,"user_name": current_user.full_name,"user_id": current_user.id,64 unmodified lines65666768697071727310 unmodified lines848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201213 unmodified lines12512612712812913013113226 unmodified lines15916016116216316416516664 unmodified linesworkspace_id=str(initial_state["workspace_id"]),user_id=str(initial_state["user_id"]),query=initial_state["messages"][-1].content,response_text=final_text,is_agent=initial_state["is_agent"],user_role=initial_state["user_role"]))except Exception as e:10 unmodified linesStreaming entry point for natural language workspace interaction.Delivers token-by-token responses and live tool updates via SSE."""# 1. Prepare Initial State & Identity Bifurcationis_agent = current_user.role in [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]# Contextual Workspace & Role Overridetarget_workspace_id = payload.workspace_id or current_user.workspace_idtarget_role = current_user.roleif payload.workspace_id:from models.user_workspace import UserWorkspacews_stmt = select(UserWorkspace).where(UserWorkspace.user_id == current_user.id,UserWorkspace.workspace_id == payload.workspace_id)ws_res = await db.execute(ws_stmt)active_link = ws_res.scalar_one_or_none()if not active_link:raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,detail=f"Access Denied: You are not a member of workspace {payload.workspace_id}")target_role = active_link.role# 0. Semantic Cache Interception (Zero-Latency SSE Masking)from core.cache import SemanticCacheManagercache_hit = await SemanticCacheManager.check_cache(workspace_id=str(target_workspace_id),query=payload.query,is_agent=is_agent,user_role=str(target_role),user_id=str(current_user.id))if cache_hit:async def cached_event_generator():3 unmodified linesreturn StreamingResponse(cached_event_generator(), media_type="text/event-stream")if payload.ticket_id:from models.ticket import Ticketstmt = select(Ticket).where(Ticket.id == payload.ticket_id, Ticket.workspace_id == target_workspace_id)res = await db.execute(stmt)if not res.scalar_one_or_none():raise HTTPException(26 unmodified linesinitial_state = {"messages": messages,"workspace_id": target_workspace_id,"user_role": str(target_role),"is_agent": is_agent,"user_name": current_user.full_name,"user_id": current_user.id,
231 unmodified lines23223323423523623723823924024159 unmodified lines301302303304231 unmodified lines@router.get("/daily-stats/", dependencies=[Depends(require_roles(ALL_SC_ROLES))])async def get_daily_stats(workspace_id: str = None,current_user: User = Depends(get_current_user),db: AsyncSession = Depends(get_db)) -> Any:"""Unified endpoint for daily trends and category distribution (last 30 days)."""# Strictly enforce current user's workspace, allowing override for Global Admintarget_ws = current_user.workspace_idif workspace_id:59 unmodified lines"categories": categories})return buckets231 unmodified lines23223323423523623723823924024124224324424524624724824925025125225325425559 unmodified lines315316317318319320321231 unmodified lines@router.get("/daily-stats/", dependencies=[Depends(require_roles(ALL_SC_ROLES))])async def get_daily_stats(workspace_id: str = None,refresh: bool = False,current_user: User = Depends(get_current_user),db: AsyncSession = Depends(get_db)) -> Any:"""Unified endpoint for daily trends and category distribution (last 30 days)."""from core.cache import get_cached_search, set_cached_search, delete_cached_search# 0. Cache lookuptarget_ws = workspace_id or str(current_user.workspace_id)cache_key = f"reports:daily:{target_ws}" # Static trends can be shared per workspaceif refresh:await delete_cached_search(cache_key)else:cached_data = await get_cached_search(cache_key)if cached_data:return cached_data# Strictly enforce current user's workspace, allowing override for Global Admintarget_ws = current_user.workspace_idif workspace_id:59 unmodified lines"categories": categories})# Store in cache (300s TTL)await set_cached_search(cache_key, buckets, ttl=300)return buckets
48 unmodified lines4950515253541 unmodified line5657585960616215 unmodified lines7879808182838448 unmodified lines# Fail safepassclass SemanticCacheManager:"""Manages semantic LLM response caching using pgvector.1 unmodified line"""@staticmethodasync def check_cache(workspace_id: str, query: str, is_agent: bool, user_role: str) -> Optional[str]:from core.llm import get_embeddingsfrom core.database import async_session_factoryfrom models.nexus_semantic_cache import NexusSemanticCache15 unmodified lines.where(NexusSemanticCache.workspace_id == workspace_id,NexusSemanticCache.is_agent == is_agent,NexusSemanticCache.user_role == user_role).order_by("distance").limit(1)48 unmodified lines49505152535455565758596061621 unmodified line6465666768697015 unmodified lines868788899091929348 unmodified lines# Fail safepassasync def delete_cached_search(key: str) -> None:"""Removes a specific cache key from Redis."""try:client = get_redis_client()await client.delete(key)except Exception:passclass SemanticCacheManager:"""Manages semantic LLM response caching using pgvector.1 unmodified line"""@staticmethodasync def check_cache(workspace_id: str, query: str, is_agent: bool, user_role: str, user_id: str) -> Optional[str]:from core.llm import get_embeddingsfrom core.database import async_session_factoryfrom models.nexus_semantic_cache import NexusSemanticCache15 unmodified lines.where(NexusSemanticCache.workspace_id == workspace_id,NexusSemanticCache.is_agent == is_agent,NexusSemanticCache.user_role == user_role,NexusSemanticCache.user_id == user_id # Strict Identity Partitioning).order_by("distance").limit(1)
78 unmodified lines7980818283848583 unmodified lines16917017117217317417578 unmodified lines/>);case 'kb':return <KnowledgeBase />;case 'escalation':return isAdminOrLead ? <EscalationCentre /> : forbidden;case 'analytics':83 unmodified lines)}{/* Persistent AI Master Hub */}<NexusMasterAgent /></div>);}78 unmodified lines7980818283848583 unmodified lines16917017117217317417578 unmodified lines/>);case 'kb':return <KnowledgeBase workspaceId={selectedWorkspaceId} />;case 'escalation':return isAdminOrLead ? <EscalationCentre /> : forbidden;case 'analytics':83 unmodified lines)}{/* Persistent AI Master Hub */}<NexusMasterAgent workspaceId={selectedWorkspaceId} /></div>);}
49 unmodified lines5051525354555636 unmodified lines9394959697989910010110210310410510610710810911018 unmodified lines12913013113213313413549 unmodified linessnippet?: string;}export const KnowledgeBase: React.FC = () => {const { user } = useAuth();const canEdit = user?.role && EDIT_ROLES.includes(user.role);const canShred = user?.role && SHRED_ROLES.includes(user.role);36 unmodified lines// 1. Fetch Categoriesconst fetchCategories = useCallback(async () => {try {const resp = await api.get('kb/categories/');setCategories(['All', ...resp.data]);} catch (err) {console.error('Failed to fetch categories:', err);}}, []);// 2. Fetch Articlesconst fetchArticles = useCallback(async (query: string = '', cat: string = 'All') => {setLoading(true);try {const params: any = {};if (cat !== 'All') params.category = cat;if (query.trim().length > 0) {18 unmodified lines} finally {setLoading(false);}}, []);// 3. Fetch Insightsconst fetchInsights = useCallback(async () => {49 unmodified lines505152535455565758596036 unmodified lines97989910010110210310410510610710810911011111211311411511618 unmodified lines13513613713813914014149 unmodified linessnippet?: string;}interface KnowledgeBaseProps {workspaceId?: string;}export const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ workspaceId }) => {const { user } = useAuth();const canEdit = user?.role && EDIT_ROLES.includes(user.role);const canShred = user?.role && SHRED_ROLES.includes(user.role);36 unmodified lines// 1. Fetch Categoriesconst fetchCategories = useCallback(async () => {try {const resp = await api.get('kb/categories/', {params: { workspace_id: workspaceId }});setCategories(['All', ...resp.data]);} catch (err) {console.error('Failed to fetch categories:', err);}}, [workspaceId]);// 2. Fetch Articlesconst fetchArticles = useCallback(async (query: string = '', cat: string = 'All') => {setLoading(true);try {const params: any = { workspace_id: workspaceId };if (cat !== 'All') params.category = cat;if (query.trim().length > 0) {18 unmodified lines} finally {setLoading(false);}}, [workspaceId]);// 3. Fetch Insightsconst fetchInsights = useCallback(async () => {
123456711 unmodified lines19202122232425262728293031323334353637383940136 unmodified lines177178179180181182183184185186187188189190191192193194import React, { useState, useEffect, useRef } from 'react';import { api, NexusMarkdown } from '@nexus/shared';export const NexusMasterAgent: React.FC = () => {const [isOpen, setIsOpen] = useState(false);const [query, setQuery] = useState("");const [messages, setMessages] = useState<any[]>([]);11 unmodified linesif (!query.trim()) return;const userMsg = { role: "user", content: query };setMessages(prev => [...prev, userMsg]);setQuery("");setLoading(true);try {const resp = await api.post('nexus/query/', {query: userMsg.content,chat_history: messages.slice(-5).map(m => ({role: m.role,content: m.content}))});setMessages(prev => [...prev, { role: "assistant", content: resp.data.answer }]);} catch (err) {console.error("Nexus Query Failed:", err);setMessages(prev => [...prev, { role: "assistant", content: "I encountered an error connecting to the Nexus Master engine. Our internal neural network may be experiencing high telemetry load." }]);} finally {setLoading(false);}136 unmodified lineswordBreak: 'break-word',fontWeight: 500}}><NexusMarkdown content={m.content} isMe={m.role === 'user'} /></div>))}{loading && (<div style={{ alignSelf: 'flex-start', background: 'var(--bg2)', padding: '16px 24px', borderRadius: 24, boxShadow: '0 4px 20px rgba(0,0,0,0.06)', border: `1px solid var(--border)` }}><div style={{ display: 'flex', gap: 6 }}>{[0,1,2].map(d => (<div key={d} style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)', animation: 'nexus-typing 1.2s infinite', animationDelay: `${d * 0.2}s` }} />))}</div></div>)}</div>{/* Footer Input */}123456711 unmodified lines1920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889136 unmodified lines226227228229230231232233234235236237238239240241242import React, { useState, useEffect, useRef } from 'react';import { api, NexusMarkdown } from '@nexus/shared';export const NexusMasterAgent: React.FC<{ workspaceId?: string }> = ({ workspaceId }) => {const [isOpen, setIsOpen] = useState(false);const [query, setQuery] = useState("");const [messages, setMessages] = useState<any[]>([]);11 unmodified linesif (!query.trim()) return;const userMsg = { role: "user", content: query };const assistantId = Date.now().toString(); // Use timestamp as temporary IDsetMessages(prev => [...prev, userMsg, { id: assistantId, role: "assistant", content: "", isLoading: true }]);setQuery("");setLoading(true);try {const token = localStorage.getItem('token');const response = await fetch(`${api.defaults.baseURL}nexus/stream/`, {method: 'POST',headers: {'Content-Type': 'application/json','Authorization': `Bearer ${token}`},body: JSON.stringify({query: userMsg.content,workspace_id: workspaceId,chat_history: messages.slice(-5).map(m => ({role: m.role,content: m.content}))})});if (!response.ok) throw new Error('Stream request failed');const reader = response.body?.getReader();const decoder = new TextDecoder();let accumulatedResponse = "";if (reader) {setLoading(false); // Switch from total loading to token streamingwhile (true) {const { done, value } = await reader.read();if (done) break;const chunk = decoder.decode(value, { stream: true });const lines = chunk.split('\n');for (const line of lines) {if (line.startsWith('data: ')) {try {const data = JSON.parse(line.slice(6));if (data.type === 'token') {accumulatedResponse += data.content;setMessages(prev => prev.map(m =>m.id === assistantId ? { ...m, content: accumulatedResponse, isLoading: false } : m));} else if (data.type === 'status') {// Optional: Show status updates in the UIconsole.log("Nexus Status:", data.message);} else if (data.type === 'error') {throw new Error(data.message);}} catch (e) {// Ignore partial JSON or keep log}}}}}} catch (err: any) {console.error("Nexus Query Failed:", err);setMessages(prev => prev.map(m =>m.id === assistantId ? { ...m, content: "I encountered an error connecting to the Nexus Master engine. Our internal neural network may be experiencing high telemetry load.", isLoading: false } : m));} finally {setLoading(false);}136 unmodified lineswordBreak: 'break-word',fontWeight: 500}}>{m.isLoading && !m.content ? (<div style={{ display: 'flex', gap: 6, padding: '4px 0' }}>{[0,1,2].map(d => (<div key={d} style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)', animation: 'nexus-typing 1.2s infinite', animationDelay: `${d * 0.2}s` }} />))}</div>) : (<NexusMarkdown content={m.content} isMe={m.role === 'user'} />)}</div>))}</div>{/* Footer Input */}
60 unmodified lines6162636465666768697071727319 unmodified lines939495969798994 unmodified lines10410510610710810911011111211311411518 unmodified lines134135136137138139140122 unmodified lines26326426526626726826960 unmodified lines};}, []);const fetchStats = useCallback(async () => {globalStatsLoading = true;notifyStats();try {const url = workspaceId? `dashboard/stats/?workspace_id=${workspaceId}`: 'dashboard/stats/';const response = await api.get(url);globalStats = response.data;globalStatsError = null;19 unmodified linesstats: localStats,loading: localLoading,error: localError,refresh: fetchStats};};4 unmodified linesconst [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);const fetchReports = useCallback(async () => {setLoading(true);try {const volUrl = workspaceId ? `reports/volume/?workspace_id=${workspaceId}` : 'reports/volume/';const slaUrl = workspaceId ? `reports/sla/?workspace_id=${workspaceId}` : 'reports/sla/';const dailyUrl = workspaceId ? `reports/daily-stats/?workspace_id=${workspaceId}` : 'reports/daily-stats/';const [volRes, slaRes, dRes] = await Promise.all([api.get(volUrl),18 unmodified lines}}, [fetchReports]);return { volume, daily, sla, loading, error, refresh: fetchReports };};export interface Breach {122 unmodified linessetLoading(true);try {const url = workspaceId ? `dashboard/ai-insights/?workspace_id=${workspaceId}` : 'dashboard/ai-insights/';const response = await api.get(url);insightsCache[key] = response.data;setInsights(response.data);60 unmodified lines61626364656667686970717273747576777819 unmodified lines98991001011021031044 unmodified lines10911011111211311411511611711811912012112212312412512612718 unmodified lines146147148149150151152122 unmodified lines27527627727827928028128228328460 unmodified lines};}, []);const fetchStats = useCallback(async (force: boolean = false) => {globalStatsLoading = true;notifyStats();try {let url = workspaceId? `dashboard/stats/?workspace_id=${workspaceId}`: 'dashboard/stats/';if (force) {url += (url.includes('?') ? '&' : '?') + 'refresh=true';}const response = await api.get(url);globalStats = response.data;globalStatsError = null;19 unmodified linesstats: localStats,loading: localLoading,error: localError,refresh: () => fetchStats(true)};};4 unmodified linesconst [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);const fetchReports = useCallback(async (force: boolean = false) => {setLoading(true);try {let volUrl = workspaceId ? `reports/volume/?workspace_id=${workspaceId}` : 'reports/volume/';let slaUrl = workspaceId ? `reports/sla/?workspace_id=${workspaceId}` : 'reports/sla/';let dailyUrl = workspaceId ? `reports/daily-stats/?workspace_id=${workspaceId}` : 'reports/daily-stats/';if (force) {const flag = (u: string) => u + (u.includes('?') ? '&' : '?') + 'refresh=true';volUrl = flag(volUrl);slaUrl = flag(slaUrl);dailyUrl = flag(dailyUrl);}const [volRes, slaRes, dRes] = await Promise.all([api.get(volUrl),18 unmodified lines}}, [fetchReports]);return { volume, daily, sla, loading, error, refresh: () => fetchReports(true) };};export interface Breach {122 unmodified linessetLoading(true);try {let url = workspaceId ? `dashboard/ai-insights/?workspace_id=${workspaceId}` : 'dashboard/ai-insights/';if (force) {url += (url.includes('?') ? '&' : '?') + 'refresh=true';}const response = await api.get(url);insightsCache[key] = response.data;setInsights(response.data);
77 unmodified lines78798081828384858687888911 unmodified lines10110210310410510610777 unmodified linesconst [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);const fetchQueue = useCallback(async () => {setLoading(true);try {const url = workspaceId? `dashboard/agent-queue/?workspace_id=${workspaceId}`: 'dashboard/agent-queue/';const response = await api.get(url);setTickets(response.data);setError(null);11 unmodified lines}}, [fetchQueue]);return { tickets, loading, error, refresh: fetchQueue };};export const useTicketStatuses = () => {77 unmodified lines787980818283848586878889909192939411 unmodified lines10610710810911011111277 unmodified linesconst [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);const fetchQueue = useCallback(async (force: boolean = false) => {setLoading(true);try {let url = workspaceId? `dashboard/agent-queue/?workspace_id=${workspaceId}`: 'dashboard/agent-queue/';if (force) {url += (url.includes('?') ? '&' : '?') + 'refresh=true';}const response = await api.get(url);setTickets(response.data);setError(null);11 unmodified lines}}, [fetchQueue]);return { tickets, loading, error, refresh: () => fetchQueue(true) };};export const useTicketStatuses = () => {
agents/nexus_master.py+15-16
agents/prompts.py+16-4
agents/tools/langchain_tools.py+4-5
agents/tools/tool_registry.py+5-9
api/v1/dashboard.py+58-4
api/v1/kb.py+61-19
api/v1/nexus.py+37-11
api/v1/nexus_stream.py+36-7
api/v1/reports.py+17
core/cache.py+11-2
frontend/apps/internal/src/App.tsx+2-2
frontend/apps/internal/src/components/KnowledgeBase.tsx+11-5
frontend/apps/internal/src/components/NexusMasterAgent.tsx+69-21
frontend/packages/shared/src/hooks/useDashboard.ts+24-9
frontend/packages/shared/src/hooks/useTickets.ts+8-3