Spaces:
Paused

dushyantsingh0 commited on
Commit
235f8ef
·
1 Parent(s): 06f7381

backend stabilization

Browse files
agents/tools/nexus_tools.py CHANGED
@@ -26,10 +26,28 @@ async def kb_search_tool(query: str, workspace_id: UUID, role: str = "customer_u
26
  """
27
  Search the Knowledge Base using the advanced Hybrid Multimodal engine.
28
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  async with async_session_factory() as db:
30
  # 1. Prepare Mock User for the search helper
31
  user_role_mapped = UserRole.CUSTOMER_USER
32
- if "3sc" in role.lower():
33
  user_role_mapped = UserRole.SC_AGENT
34
  if "admin" in role.lower(): user_role_mapped = UserRole.SC_ADMIN
35
  if "lead" in role.lower(): user_role_mapped = UserRole.SC_LEAD
@@ -42,7 +60,8 @@ async def kb_search_tool(query: str, workspace_id: UUID, role: str = "customer_u
42
  q=query,
43
  current_user=mock_user,
44
  category=None,
45
- project_id=None
 
46
  )
47
 
48
  if not search_results:
@@ -105,6 +124,23 @@ async def create_ticket_tool(title: str, description: str, workspace_id: UUID, u
105
  await db.commit()
106
  await db.refresh(new_ticket)
107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  logger.info(f"Ticket created via AI: {new_ticket.id}")
109
  return f"Successfully created ticket: **{new_ticket.title}** (ID: `{new_ticket.id}`). Status is OPEN."
110
 
@@ -156,9 +192,35 @@ async def update_ticket_tool(ticket_id: str, comment: str, workspace_id: UUID, u
156
 
157
  await db.commit()
158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
  msg = f"Successfully updated ticket `{ticket.id}`."
160
  if status and ticket.status != old_status:
161
- msg += f" Status changed from {old_status} to {ticket.status}."
162
 
163
  return msg
164
 
@@ -514,6 +576,24 @@ async def assign_ticket_tool(ticket_id: UUID, user_id: UUID, workspace_id: UUID)
514
 
515
  t.assigned_to = user_id
516
  await db.commit()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
517
  return f"Ticket {ticket_id} successfully assigned to user {user_id}."
518
 
519
  async def update_ticket_status_tool(ticket_id: UUID, new_status: str, workspace_id: UUID, role: str = "customer_user") -> str:
 
26
  """
27
  Search the Knowledge Base using the advanced Hybrid Multimodal engine.
28
  """
29
+ # 0. Semantic Cache Check (Blazing Fast Recall)
30
+ from core.cache import SemanticCacheManager
31
+ from core.permissions import ALL_SC_ROLES
32
+
33
+ is_agent_role = any(s in role.lower() for s in ["3sc", "agent", "lead", "admin"])
34
+
35
+ cached_answer = await SemanticCacheManager.check_cache(
36
+ workspace_id=str(workspace_id),
37
+ query=query,
38
+ is_agent=is_agent_role,
39
+ user_role=str(role),
40
+ user_id=None # Anonymous for cache lookup
41
+ )
42
+
43
+ if cached_answer:
44
+ logger.info(f"🧠 Semantic Cache HIT [Agent KB]: {query}")
45
+ return f"### AI DIRECT ANSWER (CACHED)\n{cached_answer}\n\n*Note: This answer was retrieved from the workspace semantic cache.*"
46
+
47
  async with async_session_factory() as db:
48
  # 1. Prepare Mock User for the search helper
49
  user_role_mapped = UserRole.CUSTOMER_USER
50
+ if is_agent_role:
51
  user_role_mapped = UserRole.SC_AGENT
52
  if "admin" in role.lower(): user_role_mapped = UserRole.SC_ADMIN
53
  if "lead" in role.lower(): user_role_mapped = UserRole.SC_LEAD
 
60
  q=query,
61
  current_user=mock_user,
62
  category=None,
63
+ project_id=None,
64
+ workspace_id=workspace_id
65
  )
66
 
67
  if not search_results:
 
124
  await db.commit()
125
  await db.refresh(new_ticket)
126
 
127
+ # 3. Notify Creator (AI Acknowledgement)
128
+ try:
129
+ from core.config import get_redis_settings
130
+ from arq import create_pool
131
+ pool = await create_pool(get_redis_settings())
132
+ await pool.enqueue_job(
133
+ "send_triple_notification",
134
+ str(user_id),
135
+ str(workspace_id),
136
+ "🎟️ Ticket Created",
137
+ f"Your ticket '{new_ticket.title}' has been successfully created by the Master Agent.",
138
+ link=f"/dashboard?ticket={new_ticket.id}"
139
+ )
140
+ await pool.close()
141
+ except Exception as e:
142
+ logger.error(f"Failed to notify creator in create_ticket_tool: {e}")
143
+
144
  logger.info(f"Ticket created via AI: {new_ticket.id}")
145
  return f"Successfully created ticket: **{new_ticket.title}** (ID: `{new_ticket.id}`). Status is OPEN."
146
 
 
192
 
193
  await db.commit()
194
 
195
+ # 4. Notify Creator of Status Change
196
+ if status and ticket.status != old_status:
197
+ try:
198
+ from core.config import get_redis_settings
199
+ from arq import create_pool
200
+ pool = await create_pool(get_redis_settings())
201
+
202
+ if ticket.status in [TicketStatus.RESOLVED, TicketStatus.CLOSED]:
203
+ title = "✅ Ticket Resolved"
204
+ msg = f"The Master Agent has resolved your ticket: '{ticket.title}'."
205
+ else:
206
+ title = "🎟️ Ticket Updated"
207
+ msg = f"Your ticket '{ticket.title}' has been moved to {ticket.status.value.upper()}."
208
+
209
+ await pool.enqueue_job(
210
+ "send_triple_notification",
211
+ str(ticket.created_by),
212
+ str(workspace_id),
213
+ title,
214
+ msg,
215
+ link=f"/dashboard?ticket={ticket.id}"
216
+ )
217
+ await pool.close()
218
+ except Exception as e:
219
+ logger.error(f"Failed to notify creator in update_ticket_tool: {e}")
220
+
221
  msg = f"Successfully updated ticket `{ticket.id}`."
222
  if status and ticket.status != old_status:
223
+ msg += f" Status changed from {old_status.value.upper()} to {ticket.status.value.upper()}."
224
 
225
  return msg
226
 
 
576
 
577
  t.assigned_to = user_id
578
  await db.commit()
579
+
580
+ # 3. Notify Assignee (Comprehensive Coverage)
581
+ try:
582
+ from core.config import get_redis_settings
583
+ from arq import create_pool
584
+ pool = await create_pool(get_redis_settings())
585
+ await pool.enqueue_job(
586
+ "send_triple_notification",
587
+ str(user_id),
588
+ str(workspace_id),
589
+ "Ticket Reassigned",
590
+ f"The Master Agent has reassigned ticket '{t.title}' to you. Please review the technical context.",
591
+ link=f"/dashboard?ticket={t.id}"
592
+ )
593
+ await pool.close()
594
+ except Exception as e:
595
+ logger.error(f"Failed to notify assignee in assign_ticket_tool: {e}")
596
+
597
  return f"Ticket {ticket_id} successfully assigned to user {user_id}."
598
 
599
  async def update_ticket_status_tool(ticket_id: UUID, new_status: str, workspace_id: UUID, role: str = "customer_user") -> str:
api/v1/kb.py CHANGED
@@ -195,7 +195,7 @@ async def execute_multimodal_search(
195
  current_user: User,
196
  category: Optional[str],
197
  project_id: Optional[UUID],
198
- workspace_id: Optional[UUID] = None
199
  ):
200
  """Internal helper to execute factual hybrid search + visual attachment search."""
201
  import uuid
@@ -215,15 +215,13 @@ async def execute_multimodal_search(
215
  )
216
 
217
  # 2. SEACH A: Text Semantic Match (Articles)
218
- # Optimized: Take only the BEST matching chunk per article to prevent score inflation
219
  sem_start = time.perf_counter()
220
  semantic_stmt = (
221
  select(
222
  KBArticle,
223
- KBArticleChunk.content.label("chunk_content"),
224
  (1 - KBArticleChunk.embedding.cosine_distance(query_vector)).label("sim_score")
225
  )
226
- .distinct(KBArticle.id)
227
  .join(KBArticleChunk, KBArticle.id == KBArticleChunk.article_id)
228
  .where(
229
  KBArticle.deleted_at.is_(None),
@@ -231,13 +229,10 @@ async def execute_multimodal_search(
231
  KBArticle.duplicate_of_id.is_(None),
232
  KBArticle.workspace_id == workspace_id
233
  )
234
- .order_by(KBArticle.id, desc("sim_score"))
235
  )
236
  if category: semantic_stmt = semantic_stmt.where(KBArticle.category == category)
237
  if project_id: semantic_stmt = semantic_stmt.where(KBArticle.project_id == project_id)
238
- # Use a subquery or wrap to limit after distinct if needed, but for RRF top 20 is fine
239
- # Actually, we want the top 20 articles by their BEST chunk score.
240
- semantic_stmt = select(semantic_stmt.subquery()).order_by(desc("sim_score")).limit(20)
241
 
242
  # 3. SEARCH B: Visual Caption Match (Attachments)
243
  # Uses pg_trgm for fuzzy similarity + search_vector for keyword relevance
@@ -303,8 +298,14 @@ async def execute_multimodal_search(
303
  results_map = {}
304
 
305
  def apply_fusion(list_hits, weight, score_attr):
 
 
306
  for rank, row in enumerate(list_hits):
307
  art = row[0]
 
 
 
 
308
  chunk_txt = row[1] if len(row) > 1 and isinstance(row[1], str) else None
309
  rrf_score = weight * (1.0 / (60 + rank + 1))
310
 
@@ -398,26 +399,27 @@ async def search_kb_articles(
398
  "durationMs": (time.perf_counter() - start_time) * 1000
399
  }
400
 
401
- # 1. Start Original Search Branch IMMEDIATELY (Don't wait for LLM)
402
- original_search_task = execute_multimodal_search(db, q, current_user, category, project_id, workspace_id=target_ws)
403
-
404
- # 2. Start LLM Expansion concurrently (if not a trivial query)
 
405
  expanded_queries = []
406
- all_local_results = []
407
 
408
- if len(q.strip()) < 5:
409
- # Bypass AI expansion for trivial "lazy" queries like "test"
410
- all_local_results.append(await original_search_task)
411
- else:
 
 
 
 
 
412
  # Launch AI expansion task
413
- expansion_task = generate_query_variations(q)
414
-
415
- # Await BOTH original search and the LLM expansion results
416
- orig_res, expanded_queries = await asyncio.gather(original_search_task, expansion_task)
417
- all_local_results.append(orig_res)
418
 
419
  if expanded_queries:
420
- # Launch searches for new variations in parallel
421
  async def run_variation_search(v):
422
  async with async_session_factory() as session:
423
  return await execute_multimodal_search(session, v, current_user, category, project_id, workspace_id=target_ws)
@@ -457,11 +459,51 @@ async def search_kb_articles(
457
  final_results.sort(key=lambda x: float(x.get("score") or 0.0), reverse=True)
458
  top_results = final_results[:5]
459
 
460
- # 4.5 Cleanup & Synthesis Removal
461
- # Per user request, we focus on high-fidelity retrieval and skip direct AI answers
462
  direct_answer = None
463
  is_ai_synthetic = False
464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465
  # 5. Final Response Payload
466
  end_time = time.perf_counter()
467
  search_time_s = end_time - start_time
 
195
  current_user: User,
196
  category: Optional[str],
197
  project_id: Optional[UUID],
198
+ workspace_id: UUID
199
  ):
200
  """Internal helper to execute factual hybrid search + visual attachment search."""
201
  import uuid
 
215
  )
216
 
217
  # 2. SEACH A: Text Semantic Match (Articles)
 
218
  sem_start = time.perf_counter()
219
  semantic_stmt = (
220
  select(
221
  KBArticle,
222
+ KBArticleChunk.content,
223
  (1 - KBArticleChunk.embedding.cosine_distance(query_vector)).label("sim_score")
224
  )
 
225
  .join(KBArticleChunk, KBArticle.id == KBArticleChunk.article_id)
226
  .where(
227
  KBArticle.deleted_at.is_(None),
 
229
  KBArticle.duplicate_of_id.is_(None),
230
  KBArticle.workspace_id == workspace_id
231
  )
 
232
  )
233
  if category: semantic_stmt = semantic_stmt.where(KBArticle.category == category)
234
  if project_id: semantic_stmt = semantic_stmt.where(KBArticle.project_id == project_id)
235
+ semantic_stmt = semantic_stmt.order_by(desc("sim_score")).limit(20)
 
 
236
 
237
  # 3. SEARCH B: Visual Caption Match (Attachments)
238
  # Uses pg_trgm for fuzzy similarity + search_vector for keyword relevance
 
298
  results_map = {}
299
 
300
  def apply_fusion(list_hits, weight, score_attr):
301
+ # Best-Hit Deduplication: Ensure an article only scores once per search branch
302
+ seen_in_branch = set()
303
  for rank, row in enumerate(list_hits):
304
  art = row[0]
305
+ if art.id in seen_in_branch:
306
+ continue
307
+ seen_in_branch.add(art.id)
308
+
309
  chunk_txt = row[1] if len(row) > 1 and isinstance(row[1], str) else None
310
  rrf_score = weight * (1.0 / (60 + rank + 1))
311
 
 
399
  "durationMs": (time.perf_counter() - start_time) * 1000
400
  }
401
 
402
+ # 1. Execute Original Search
403
+ orig_res = await execute_multimodal_search(
404
+ db, q, current_user, category, project_id, target_ws
405
+ )
406
+ all_local_results = [orig_res]
407
  expanded_queries = []
 
408
 
409
+ # 2. Performance Optimization: High Confidence Early Exit
410
+ # If original search has a near-perfect match (>80%), skip expensive LLM variations
411
+ max_orig_score = max([r["score"] for r in orig_res.values()]) if orig_res else 0.0
412
+ is_high_confidence = max_orig_score > 80.0
413
+
414
+ # Check if query is complex enough to warrant expansion (e.g., >3 words or technical)
415
+ is_complex = len(q.split()) >= 3 or any(w in q.lower() for w in ["how", "why", "steps", "explain"])
416
+
417
+ if not is_high_confidence and is_complex and len(q.strip()) >= 5:
418
  # Launch AI expansion task
419
+ expanded_queries = await generate_query_variations(q)
 
 
 
 
420
 
421
  if expanded_queries:
422
+ # Launch searches for variations in parallel
423
  async def run_variation_search(v):
424
  async with async_session_factory() as session:
425
  return await execute_multimodal_search(session, v, current_user, category, project_id, workspace_id=target_ws)
 
459
  final_results.sort(key=lambda x: float(x.get("score") or 0.0), reverse=True)
460
  top_results = final_results[:5]
461
 
462
+ # 4.5 Synthesis Branch (The "Direct Answer" Engine)
 
463
  direct_answer = None
464
  is_ai_synthetic = False
465
 
466
+ # Trigger synthesis if it's a complex query or we have high confidence hits
467
+ # This provides a quick "Direct Answer" summary of the top documentation
468
+ if is_complex and top_results:
469
+ try:
470
+ from core.llm import get_llm
471
+ from langchain_core.messages import SystemMessage, HumanMessage
472
+
473
+ # Construct context from TOP CHUNKS
474
+ context_txt = "\n\n".join([
475
+ f"DOC {i+1} [{r['title']}]:\n---\n{r.get('raw_chunk') or r.get('snippet') or r['content'][:500]}\n---"
476
+ for i, r in enumerate(top_results)
477
+ ])
478
+
479
+ llm = get_llm()
480
+ prompt = [
481
+ SystemMessage(content=(
482
+ "You are a technical support expert. Provide a concise, highly structured direct answer. "
483
+ "Use MARKDOWN for the following:\n"
484
+ "- Use **Bold** for key facts and product names.\n"
485
+ "- Use `inline code` for technical terms, database names, or variables.\n"
486
+ "- Use bulleted lists to cite evidence from provided documentation.\n"
487
+ "If the answer is not in the context, be honest. Keep it under 150 words."
488
+ )),
489
+ HumanMessage(content=f"Question: {q}\n\nDocumentation Context:\n{context_txt}")
490
+ ]
491
+ synth_resp = await llm.ainvoke(prompt)
492
+ direct_answer = synth_resp.content
493
+ is_ai_synthetic = True
494
+
495
+ # Asynchronously Cache to Semantic Cache
496
+ await SemanticCacheManager.set_cache(
497
+ workspace_id=str(target_ws),
498
+ user_id=str(current_user.id),
499
+ query=q,
500
+ response_text=direct_answer,
501
+ is_agent=current_user.role in ALL_SC_ROLES,
502
+ user_role=str(current_user.role)
503
+ )
504
+ except Exception as e:
505
+ logger.error(f"Synthesis failed: {e}")
506
+
507
  # 5. Final Response Payload
508
  end_time = time.perf_counter()
509
  search_time_s = end_time - start_time
api/v1/messages.py CHANGED
@@ -144,10 +144,7 @@ async def send_message(
144
  # --- 4. Notify Customer of Expert Response ---
145
  # Only if sender is staff and message is public
146
  if is_staff and not payload.is_internal and ticket.created_by != current_user.id:
147
- from core.tasks import send_triple_notification
148
- # Use arq to avoid blocking, or background_tasks if available
149
  try:
150
- # Correct arq call: do NOT pass ctx/None explicitly
151
  await arq_pool.enqueue_job("send_triple_notification",
152
  str(ticket.created_by),
153
  str(ticket.workspace_id),
@@ -158,6 +155,20 @@ async def send_message(
158
  except Exception as e:
159
  logger.error(f"Failed to queue customer response notification: {e}")
160
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  return await sanitize_message_response(new_message, db)
162
 
163
 
 
144
  # --- 4. Notify Customer of Expert Response ---
145
  # Only if sender is staff and message is public
146
  if is_staff and not payload.is_internal and ticket.created_by != current_user.id:
 
 
147
  try:
 
148
  await arq_pool.enqueue_job("send_triple_notification",
149
  str(ticket.created_by),
150
  str(ticket.workspace_id),
 
155
  except Exception as e:
156
  logger.error(f"Failed to queue customer response notification: {e}")
157
 
158
+ # --- 5. Notify Assigned Agent of Customer Reply ---
159
+ # Only if sender is NOT staff (i.e. is customer) and there is an assignee to notify
160
+ if not is_staff and ticket.assigned_to:
161
+ try:
162
+ await arq_pool.enqueue_job("send_triple_notification",
163
+ str(ticket.assigned_to),
164
+ str(ticket.workspace_id),
165
+ "📬 Customer Reply",
166
+ f"The customer has replied to ticket: '{ticket.title}'",
167
+ link=f"/dashboard?ticket={ticket.id}"
168
+ )
169
+ except Exception as e:
170
+ logger.error(f"Failed to queue agent reply notification: {e}")
171
+
172
  return await sanitize_message_response(new_message, db)
173
 
174
 
api/v1/tickets.py CHANGED
@@ -415,7 +415,9 @@ async def search_tickets(
415
  # KB search integrated into the parallel flow
416
  async def run_kb_search():
417
  async with async_session_factory() as session:
418
- return await execute_multimodal_search(session, q, current_user, None, project_id)
 
 
419
 
420
  kb_task = run_kb_search()
421
 
@@ -734,14 +736,22 @@ async def update_ticket(
734
  ticket.resolution_text = "This issue has been resolved. Thanks!"
735
 
736
  # Notify Creator of Resolution
737
- background_tasks.add_task(
738
- send_triple_notification,
739
- None,
740
- ticket.created_by,
741
- ticket.workspace_id,
742
  "✅ Ticket Resolved",
743
  f"Great news! Your ticket '{ticket.title}' has been marked as {new_status}."
744
  )
 
 
 
 
 
 
 
 
 
745
 
746
  if "priority" in update_data and update_data["priority"] != ticket.priority:
747
  # Recalculate SLA
@@ -966,7 +976,8 @@ async def reprocess_ticket_ai(
966
  async def escalate_ticket(
967
  ticket_id: UUID,
968
  current_user: User = Depends(get_current_user),
969
- db: AsyncSession = Depends(get_db)
 
970
  ) -> Any:
971
  """Manual Escalation: Force priority to P0 and mark as escalated."""
972
  from sqlalchemy.orm import joinedload
@@ -1028,15 +1039,14 @@ async def escalate_ticket(
1028
 
1029
  # 4. Notify Workspace Lead/Admin via Triple-Threat Protocol
1030
  from agents.utils import get_workspace_manager
1031
- from core.tasks import send_triple_notification
1032
  manager_user = await get_workspace_manager(db, ticket.workspace_id)
1033
  if manager_user:
1034
- await send_triple_notification(
1035
- None, # ctx not available in direct API call, but send_triple_notification handles it
1036
- user_id=manager_user.id,
1037
- workspace_id=ticket.workspace_id,
1038
- title="🚨 Manual Escalation Alert",
1039
- message=f"Ticket '{ticket.title}' has been manually escalated by {current_user.full_name}. Priority: P0.",
1040
  link=f"/dashboard?ticket={ticket.id}"
1041
  )
1042
 
@@ -1050,6 +1060,17 @@ async def escalate_ticket(
1050
  link=f"/dashboard?ticket={ticket.id}"
1051
  )
1052
 
 
 
 
 
 
 
 
 
 
 
 
1053
  logger.info(f"Ticket {ticket.id} manually escalated by {current_user.id}")
1054
 
1055
  # Refresh to pick up lead info in sanitizer
 
415
  # KB search integrated into the parallel flow
416
  async def run_kb_search():
417
  async with async_session_factory() as session:
418
+ return await execute_multimodal_search(
419
+ session, q, current_user, None, project_id, current_user.workspace_id
420
+ )
421
 
422
  kb_task = run_kb_search()
423
 
 
736
  ticket.resolution_text = "This issue has been resolved. Thanks!"
737
 
738
  # Notify Creator of Resolution
739
+ await arq_pool.enqueue_job(
740
+ "send_triple_notification",
741
+ str(ticket.created_by),
742
+ str(ticket.workspace_id),
 
743
  "✅ Ticket Resolved",
744
  f"Great news! Your ticket '{ticket.title}' has been marked as {new_status}."
745
  )
746
+ elif new_status in [TicketStatus.IN_PROGRESS, TicketStatus.ACKNOWLEDGED] and ticket.status == TicketStatus.OPEN:
747
+ # Notify Creator that work has started
748
+ await arq_pool.enqueue_job(
749
+ "send_triple_notification",
750
+ str(ticket.created_by),
751
+ str(ticket.workspace_id),
752
+ "🎟️ Work Started",
753
+ f"An agent has started reviewing your ticket '{ticket.title}'. Current status: {new_status.value.upper()}."
754
+ )
755
 
756
  if "priority" in update_data and update_data["priority"] != ticket.priority:
757
  # Recalculate SLA
 
976
  async def escalate_ticket(
977
  ticket_id: UUID,
978
  current_user: User = Depends(get_current_user),
979
+ db: AsyncSession = Depends(get_db),
980
+ arq_pool: ArqRedis = Depends(get_arq_pool)
981
  ) -> Any:
982
  """Manual Escalation: Force priority to P0 and mark as escalated."""
983
  from sqlalchemy.orm import joinedload
 
1039
 
1040
  # 4. Notify Workspace Lead/Admin via Triple-Threat Protocol
1041
  from agents.utils import get_workspace_manager
 
1042
  manager_user = await get_workspace_manager(db, ticket.workspace_id)
1043
  if manager_user:
1044
+ await arq_pool.enqueue_job(
1045
+ "send_triple_notification",
1046
+ str(manager_user.id),
1047
+ str(ticket.workspace_id),
1048
+ "🚨 Manual Escalation Alert",
1049
+ f"Ticket '{ticket.title}' has been manually escalated by {current_user.full_name}. Priority: P0.",
1050
  link=f"/dashboard?ticket={ticket.id}"
1051
  )
1052
 
 
1060
  link=f"/dashboard?ticket={ticket.id}"
1061
  )
1062
 
1063
+ # 5. Notify Assignee (if different from manager)
1064
+ if ticket.assigned_to and (not manager_user or ticket.assigned_to != manager_user.id):
1065
+ await arq_pool.enqueue_job(
1066
+ "send_triple_notification",
1067
+ str(ticket.assigned_to),
1068
+ str(ticket.workspace_id),
1069
+ "🚨 Urgent Escalation",
1070
+ f"A lead has manually escalated ticket '{ticket.title}' to P0. This is now a critical priority.",
1071
+ link=f"/dashboard?ticket={ticket.id}"
1072
+ )
1073
+
1074
  logger.info(f"Ticket {ticket.id} manually escalated by {current_user.id}")
1075
 
1076
  # Refresh to pick up lead info in sanitizer
api/v1/workspace.py CHANGED
@@ -60,8 +60,14 @@ async def get_my_workspace(
60
  current_user: User = Depends(get_current_user),
61
  db: AsyncSession = Depends(get_db)
62
  ) -> Any:
63
- """Get current workspace details."""
64
- print(f"DEBUG WORKSPACE: User={current_user.email}, WS_ID_ATTR={current_user.workspace_id}, TYPE={type(current_user.workspace_id)}")
 
 
 
 
 
 
65
  stmt = select(Workspace).where(
66
  Workspace.id == current_user.workspace_id,
67
  Workspace.deleted_at.is_(None)
@@ -70,6 +76,10 @@ async def get_my_workspace(
70
  workspace = result.scalar_one_or_none()
71
  if not workspace:
72
  raise HTTPException(status_code=404, detail="Workspace not found")
 
 
 
 
73
  return workspace
74
 
75
  @router.patch("/", response_model=WorkspaceResponse, dependencies=[Depends(require_roles(WORKSPACE_ADMIN_ROLES))])
@@ -78,7 +88,7 @@ async def update_workspace(
78
  current_user: User = Depends(get_current_user),
79
  db: AsyncSession = Depends(get_db)
80
  ) -> Any:
81
- """Admin only: Update workspace settings/branding."""
82
  stmt = select(Workspace).where(
83
  Workspace.id == current_user.workspace_id,
84
  Workspace.deleted_at.is_(None)
@@ -93,6 +103,11 @@ async def update_workspace(
93
  db.add(workspace)
94
  await db.commit()
95
  await db.refresh(workspace)
 
 
 
 
 
96
  return workspace
97
 
98
  @router.get("/branding/")
 
60
  current_user: User = Depends(get_current_user),
61
  db: AsyncSession = Depends(get_db)
62
  ) -> Any:
63
+ """Get current workspace details (Cached)."""
64
+ from core.cache import get_cached_object, set_cached_object
65
+ cache_key = f"ws:meta:{current_user.workspace_id}"
66
+
67
+ cached = await get_cached_object(cache_key)
68
+ if cached:
69
+ return cached
70
+
71
  stmt = select(Workspace).where(
72
  Workspace.id == current_user.workspace_id,
73
  Workspace.deleted_at.is_(None)
 
76
  workspace = result.scalar_one_or_none()
77
  if not workspace:
78
  raise HTTPException(status_code=404, detail="Workspace not found")
79
+
80
+ # Cache for 1 hour (workspace data is slow-changing)
81
+ from fastapi.encoders import jsonable_encoder
82
+ await set_cached_object(cache_key, jsonable_encoder(workspace), ttl=3600)
83
  return workspace
84
 
85
  @router.patch("/", response_model=WorkspaceResponse, dependencies=[Depends(require_roles(WORKSPACE_ADMIN_ROLES))])
 
88
  current_user: User = Depends(get_current_user),
89
  db: AsyncSession = Depends(get_db)
90
  ) -> Any:
91
+ """Admin only: Update workspace settings/branding (Invalidates Cache)."""
92
  stmt = select(Workspace).where(
93
  Workspace.id == current_user.workspace_id,
94
  Workspace.deleted_at.is_(None)
 
103
  db.add(workspace)
104
  await db.commit()
105
  await db.refresh(workspace)
106
+
107
+ # Invalidate Cache
108
+ from core.cache import invalidate_cache
109
+ await invalidate_cache(f"ws:meta:{current_user.workspace_id}")
110
+
111
  return workspace
112
 
113
  @router.get("/branding/")
core/cache.py CHANGED
@@ -57,6 +57,35 @@ async def delete_cached_search(key: str) -> None:
57
  except Exception:
58
  pass
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  class SemanticCacheManager:
61
  """
62
  Manages semantic LLM response caching using pgvector.
 
57
  except Exception:
58
  pass
59
 
60
+ # --- Generic Object Caching for API responses ---
61
+
62
+ async def get_cached_object(key: str) -> Optional[Any]:
63
+ """Retrieves a JSON-serialized object from Redis."""
64
+ try:
65
+ client = get_redis_client()
66
+ data = await client.get(key)
67
+ if data:
68
+ return json.loads(data)
69
+ except Exception:
70
+ pass
71
+ return None
72
+
73
+ async def set_cached_object(key: str, data: Any, ttl: int = 300) -> None:
74
+ """Stores a JSON-serializable object in Redis with TTL."""
75
+ try:
76
+ client = get_redis_client()
77
+ await client.set(key, json.dumps(data), ex=ttl)
78
+ except Exception:
79
+ pass
80
+
81
+ async def invalidate_cache(key: str) -> None:
82
+ """Explicitly purges a cache key."""
83
+ try:
84
+ client = get_redis_client()
85
+ await client.delete(key)
86
+ except Exception:
87
+ pass
88
+
89
  class SemanticCacheManager:
90
  """
91
  Manages semantic LLM response caching using pgvector.
frontend/apps/customer/src/App.tsx CHANGED
@@ -20,8 +20,8 @@ export default function App() {
20
  const { user, token, loading: authLoading, error: authError, login, logout, refreshUser } = useAuth();
21
  const { tickets, loading: ticketsLoading, createTicket } = useTickets();
22
  const { stats, loading: statsLoading } = useDashboardStats();
23
- useAIInsights();
24
- useServiceNarrative();
25
 
26
  const [active, setActive] = useState<"dashboard" | "tickets" | "kb" | "analytics" | "thread" | "workspace">("dashboard");
27
  const [showNewTicket, setShowNewTicket] = useState(false);
@@ -32,10 +32,12 @@ export default function App() {
32
  return <LoginCard onLogin={login} loading={authLoading} portal="customer" error={authError} />;
33
  }
34
 
35
- // Pre-load logic: Wait for auth, tickets, stats, and AI before revealing the portal
36
  const isInitialLoading = (authLoading && !user) || (user && (
37
  (ticketsLoading && tickets.length === 0) ||
38
- (statsLoading && !stats)
 
 
39
  ));
40
 
41
  if (isInitialLoading) {
 
20
  const { user, token, loading: authLoading, error: authError, login, logout, refreshUser } = useAuth();
21
  const { tickets, loading: ticketsLoading, createTicket } = useTickets();
22
  const { stats, loading: statsLoading } = useDashboardStats();
23
+ const { insights, loading: insightsLoading } = useAIInsights();
24
+ const { narrative, loading: narrativeLoading } = useServiceNarrative();
25
 
26
  const [active, setActive] = useState<"dashboard" | "tickets" | "kb" | "analytics" | "thread" | "workspace">("dashboard");
27
  const [showNewTicket, setShowNewTicket] = useState(false);
 
32
  return <LoginCard onLogin={login} loading={authLoading} portal="customer" error={authError} />;
33
  }
34
 
35
+ // Pre-load logic: Wait for auth, tickets, stats, insights AND narrative before revealing the portal
36
  const isInitialLoading = (authLoading && !user) || (user && (
37
  (ticketsLoading && tickets.length === 0) ||
38
+ (statsLoading && !stats) ||
39
+ (insightsLoading && !insights) ||
40
+ (narrativeLoading && !narrative)
41
  ));
42
 
43
  if (isInitialLoading) {
frontend/apps/customer/src/components/Dashboard.tsx CHANGED
@@ -117,8 +117,8 @@ export const Dashboard: React.FC<DashboardProps> = ({ setActive, setSelectedTick
117
  <div style={{ display: "flex", gap: 16, flexWrap: "wrap", justifyContent: "flex-end" }}>
118
  {[
119
  { label: "WORKSPACE VOLUME", value: showStatsLoading ? <Skeleton width={40} height={28} /> : (stats?.total_tickets ?? "0"), sub: "Lifetime Tickets", icon: "📊" },
120
- { 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: "⚡" },
121
- { 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: "✅" }
122
  ].map(s => (
123
  <div key={s.label} style={{
124
  background: "rgba(255, 255, 255, 0.12)",
 
117
  <div style={{ display: "flex", gap: 16, flexWrap: "wrap", justifyContent: "flex-end" }}>
118
  {[
119
  { label: "WORKSPACE VOLUME", value: showStatsLoading ? <Skeleton width={40} height={28} /> : (stats?.total_tickets ?? "0"), sub: "Lifetime Tickets", icon: "📊" },
120
+ { 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: "⚡" },
121
+ { 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: "✅" }
122
  ].map(s => (
123
  <div key={s.label} style={{
124
  background: "rgba(255, 255, 255, 0.12)",
frontend/apps/customer/src/components/WorkspaceView.tsx CHANGED
@@ -15,10 +15,11 @@ const COLORS = {
15
  error: "#DC2626",
16
  };
17
 
 
 
18
  export const WorkspaceView: React.FC<{ user: any }> = ({ user }) => {
19
- const [workspace, setWorkspace] = useState<any>(null);
20
- const [members, setMembers] = useState<any[]>([]);
21
- const [loading, setLoading] = useState(true);
22
 
23
  // New User Form
24
  const [showAddForm, setShowAddForm] = useState(false);
@@ -27,23 +28,25 @@ export const WorkspaceView: React.FC<{ user: any }> = ({ user }) => {
27
 
28
  const isAdmin = user.role.includes('admin');
29
 
30
- useEffect(() => {
31
- fetchWorkspaceData();
32
- }, []);
33
 
34
- const fetchWorkspaceData = async () => {
35
- setLoading(true);
 
36
  try {
37
- const [wsResp, usersResp] = await Promise.all([
38
- api.get('workspace/'),
39
- api.get('users/')
40
- ]);
41
- setWorkspace(wsResp.data);
42
- setMembers(usersResp.data);
 
43
  } catch (err) {
44
- console.error("Failed to fetch workspace data:", err);
45
- } finally {
46
- setLoading(false);
47
  }
48
  };
49
 
@@ -78,7 +81,7 @@ export const WorkspaceView: React.FC<{ user: any }> = ({ user }) => {
78
  }
79
  };
80
 
81
- if (loading) return <div style={{ padding: 40, color: COLORS.gray400 }}>Loading workspace intelligence...</div>;
82
 
83
  return (
84
  <div style={{ padding: "40px", maxWidth: 1200, margin: "0 auto" }}>
 
15
  error: "#DC2626",
16
  };
17
 
18
+ import { useWorkspace, useUsers } from '@nexus/shared';
19
+
20
  export const WorkspaceView: React.FC<{ user: any }> = ({ user }) => {
21
+ const { workspace, loading: workspaceLoading, refresh: refreshWorkspace } = useWorkspace();
22
+ const { users: members, loading: usersLoading, refresh: refreshUsers, addUser } = useUsers();
 
23
 
24
  // New User Form
25
  const [showAddForm, setShowAddForm] = useState(false);
 
28
 
29
  const isAdmin = user.role.includes('admin');
30
 
31
+ // Logic: "Loading workspace intelligence..." only shows if we have NO data.
32
+ // If we have cached data, we show it immediately (Instant-Sync).
33
+ const isInitialLoading = (workspaceLoading && !workspace) || (usersLoading && members.length === 0);
34
 
35
+ const handleCreateUser = async (e: React.FormEvent) => {
36
+ e.preventDefault();
37
+ setSubmitting(true);
38
  try {
39
+ await addUser(form);
40
+ setForm({ email: '', full_name: '', password: '', role: 'customer_user' });
41
+ // Brief delay before closing for better feedback
42
+ setTimeout(() => {
43
+ setShowAddForm(false);
44
+ setSubmitting(false);
45
+ }, 500);
46
  } catch (err) {
47
+ console.error("Failed to create user:", err);
48
+ alert("Error creating user. Check email uniqueness and permissions.");
49
+ setSubmitting(false);
50
  }
51
  };
52
 
 
81
  }
82
  };
83
 
84
+ if (isInitialLoading) return <div style={{ padding: 40, color: COLORS.gray400 }}>Loading workspace intelligence...</div>;
85
 
86
  return (
87
  <div style={{ padding: "40px", maxWidth: 1200, margin: "0 auto" }}>
frontend/apps/internal/src/App.tsx CHANGED
@@ -98,6 +98,7 @@ function App() {
98
  return <KnowledgeBase workspaceId={selectedWorkspaceId} />;
99
  case 'escalation':
100
  return isAdminOrLead ? <EscalationCentre /> : forbidden;
 
101
  return (
102
  <AnalyticsDashboard
103
  workspaceId={selectedWorkspaceId}
 
98
  return <KnowledgeBase workspaceId={selectedWorkspaceId} />;
99
  case 'escalation':
100
  return isAdminOrLead ? <EscalationCentre /> : forbidden;
101
+ case 'analytics':
102
  return (
103
  <AnalyticsDashboard
104
  workspaceId={selectedWorkspaceId}
frontend/apps/internal/src/components/KnowledgeBase.module.css CHANGED
@@ -847,15 +847,41 @@
847
  }
848
 
849
  .answerText {
850
- font-size: 18px;
851
  line-height: 1.8;
852
  color: var(--text-main);
853
- font-weight: 600;
854
- font-style: italic;
855
  margin: 0;
856
  max-width: 900px;
857
  }
858
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
859
  .spotlightFooter {
860
  margin-top: 24px;
861
  padding-top: 20px;
 
847
  }
848
 
849
  .answerText {
850
+ font-size: 16px;
851
  line-height: 1.8;
852
  color: var(--text-main);
853
+ font-weight: 500;
 
854
  margin: 0;
855
  max-width: 900px;
856
  }
857
 
858
+ .answerText p {
859
+ margin-bottom: 16px;
860
+ }
861
+
862
+ .answerText ul, .answerText ol {
863
+ margin-bottom: 16px;
864
+ padding-left: 24px;
865
+ }
866
+
867
+ .answerText li {
868
+ margin-bottom: 8px;
869
+ }
870
+
871
+ .answerText code {
872
+ background: var(--bg-hover);
873
+ padding: 2px 6px;
874
+ border-radius: 4px;
875
+ font-family: 'JetBrains Mono', monospace;
876
+ font-size: 0.9em;
877
+ color: var(--primary);
878
+ }
879
+
880
+ .answerText strong {
881
+ font-weight: 800;
882
+ color: var(--primary);
883
+ }
884
+
885
  .spotlightFooter {
886
  margin-top: 24px;
887
  padding-top: 20px;
frontend/apps/internal/src/components/KnowledgeBase.tsx CHANGED
@@ -456,6 +456,32 @@ export const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ workspaceId }) =>
456
  </motion.div>
457
  ) : (
458
  <div className={styles.resultsContainer}>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459
  <motion.div
460
  key="grid"
461
  className={styles.articlesGrid}
 
456
  </motion.div>
457
  ) : (
458
  <div className={styles.resultsContainer}>
459
+ <AnimatePresence>
460
+ {aiAnswer && (
461
+ <motion.div
462
+ className={styles.aiSpotlight}
463
+ initial={{ opacity: 0, y: 20 }}
464
+ animate={{ opacity: 1, y: 0 }}
465
+ exit={{ opacity: 0, scale: 0.95 }}
466
+ >
467
+ <div className={styles.spotlightHeader}>
468
+ <div className={styles.spotlightBadge}>
469
+ <Sparkles size={14} /> AI DIRECT ANSWER
470
+ </div>
471
+ {isAiSynthetic && <span className={styles.syntheticLag}>GENERATED IN REAL-TIME</span>}
472
+ </div>
473
+ <div className={styles.answerText}>
474
+ <ReactMarkdown remarkPlugins={[remarkGfm]}>
475
+ {aiAnswer}
476
+ </ReactMarkdown>
477
+ </div>
478
+ <div className={styles.spotlightFooter}>
479
+ Based on the top documentation matches below.
480
+ </div>
481
+ </motion.div>
482
+ )}
483
+ </AnimatePresence>
484
+
485
  <motion.div
486
  key="grid"
487
  className={styles.articlesGrid}
frontend/packages/shared/src/hooks/useWorkspaces.ts CHANGED
@@ -8,13 +8,51 @@ export interface Workspace {
8
  branding?: any;
9
  }
10
 
11
- // Global singleton for workspaces
12
- let globalWorkspaces: Workspace[] = [];
13
- let globalWorkspacesLoading = false;
14
- let globalWorkspacesError: string | null = null;
15
- const workspacesListeners = new Set<(w: Workspace[], l: boolean, e: string | null) => void>();
16
 
17
- const notifyWorkspaces = () => workspacesListeners.forEach(l => l(globalWorkspaces, globalWorkspacesLoading, globalWorkspacesError));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
  export const useWorkspaces = () => {
20
  const [localWorkspaces, setLocalWorkspaces] = useState(globalWorkspaces);
 
8
  branding?: any;
9
  }
10
 
11
+ // Global singleton for the ACTIVE workspace metadata
12
+ let globalActiveWorkspace: Workspace | null = null;
13
+ let globalActiveWorkspaceLoading = false;
14
+ const activeWorkspaceListeners = new Set<(w: Workspace | null, l: boolean) => void>();
 
15
 
16
+ const notifyActiveWorkspace = () => activeWorkspaceListeners.forEach(l => l(globalActiveWorkspace, globalActiveWorkspaceLoading));
17
+
18
+ export const useWorkspace = () => {
19
+ const [workspace, setWorkspace] = useState(globalActiveWorkspace);
20
+ const [loading, setLoading] = useState(globalActiveWorkspaceLoading);
21
+
22
+ useEffect(() => {
23
+ const listener = (w: Workspace | null, l: boolean) => {
24
+ setWorkspace(w);
25
+ setLoading(l);
26
+ };
27
+ activeWorkspaceListeners.add(listener);
28
+ return () => activeWorkspaceListeners.delete(listener);
29
+ }, []);
30
+
31
+ const fetchWorkspace = useCallback(async (force: boolean = false) => {
32
+ if (!force && globalActiveWorkspace) return;
33
+
34
+ globalActiveWorkspaceLoading = true;
35
+ notifyActiveWorkspace();
36
+ try {
37
+ const response = await api.get('workspace/');
38
+ globalActiveWorkspace = response.data;
39
+ } catch (err) {
40
+ console.error("Failed to fetch current workspace", err);
41
+ } finally {
42
+ globalActiveWorkspaceLoading = false;
43
+ notifyActiveWorkspace();
44
+ }
45
+ }, []);
46
+
47
+ useEffect(() => {
48
+ const token = localStorage.getItem('token');
49
+ if (token && !globalActiveWorkspace && !globalActiveWorkspaceLoading) {
50
+ fetchWorkspace();
51
+ }
52
+ }, [fetchWorkspace]);
53
+
54
+ return { workspace, loading, refresh: () => fetchWorkspace(true) };
55
+ };
56
 
57
  export const useWorkspaces = () => {
58
  const [localWorkspaces, setLocalWorkspaces] = useState(globalWorkspaces);