Spaces:
Paused

dushyantsingh0 commited on
Commit
bc1617c
·
1 Parent(s): 0f0e878

fix: allow staff cross-workspace live events via WebSockets

Browse files
api/v1/reports.py CHANGED
@@ -63,33 +63,41 @@ async def get_csat_report(
63
  current_user: User = Depends(get_current_user),
64
  db: AsyncSession = Depends(get_db)
65
  ) -> Any:
66
- # Strictly enforce current user's workspace, allowing override for authorized staff
67
- target_ws = current_user.workspace_id
68
- if workspace_id:
69
- if current_user.role == UserRole.SC_ADMIN:
70
- target_ws = workspace_id
71
- else:
72
- from models.user_workspace import UserWorkspace
73
- ws_check = await db.execute(
74
- select(UserWorkspace).where(
75
- UserWorkspace.user_id == current_user.id,
76
- UserWorkspace.workspace_id == workspace_id
77
- )
78
- )
79
- if ws_check.scalar_one_or_none():
80
  target_ws = workspace_id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
- stmt = (
83
- select(func.avg(Feedback.rating), func.count(Feedback.id))
84
- .where(Feedback.workspace_id == target_ws)
85
- )
86
- result = await db.execute(stmt)
87
- avg_rating, count = result.one()
88
-
89
- return {
90
- "average_rating": float(avg_rating) if avg_rating else 0,
91
- "total_responses": count
92
- }
93
 
94
  @router.get("/sla/", dependencies=[Depends(require_roles(EVERYBODY_ROLES))])
95
  async def get_sla_compliance(
 
63
  current_user: User = Depends(get_current_user),
64
  db: AsyncSession = Depends(get_db)
65
  ) -> Any:
66
+ try:
67
+ # Strictly enforce current user's workspace, allowing override for authorized staff
68
+ target_ws = current_user.workspace_id
69
+ if workspace_id:
70
+ if current_user.role == UserRole.SC_ADMIN:
 
 
 
 
 
 
 
 
 
71
  target_ws = workspace_id
72
+ else:
73
+ from models.user_workspace import UserWorkspace
74
+ ws_check = await db.execute(
75
+ select(UserWorkspace).where(
76
+ UserWorkspace.user_id == current_user.id,
77
+ UserWorkspace.workspace_id == workspace_id
78
+ )
79
+ )
80
+ if ws_check.scalar_one_or_none():
81
+ target_ws = workspace_id
82
+
83
+ if not target_ws:
84
+ return {"average_rating": 0, "total_responses": 0}
85
+
86
+ stmt = (
87
+ select(func.avg(Feedback.rating), func.count(Feedback.id))
88
+ .where(Feedback.workspace_id == target_ws)
89
+ )
90
+ result = await db.execute(stmt)
91
+ avg_rating, count = result.one()
92
+
93
+ return {
94
+ "average_rating": float(avg_rating) if avg_rating else 0,
95
+ "total_responses": count or 0
96
+ }
97
+ except Exception as e:
98
+ logger.error(f"CSAT Report Error: {str(e)}")
99
+ return {"average_rating": 0, "total_responses": 0}
100
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
  @router.get("/sla/", dependencies=[Depends(require_roles(EVERYBODY_ROLES))])
103
  async def get_sla_compliance(
core/cache.py CHANGED
@@ -90,8 +90,19 @@ class SemanticCacheManager:
90
  """
91
  Manages semantic LLM response caching using pgvector.
92
  Bypasses entirely the LangGraph orchestration if an idential query was asked before.
 
 
 
93
  """
94
 
 
 
 
 
 
 
 
 
95
  @staticmethod
96
  async def check_cache(workspace_id: str, query: str, is_agent: bool = False, user_role: str = "customer_user", user_id: Optional[str] = None) -> Optional[str]:
97
  from core.llm import get_embeddings
@@ -101,6 +112,7 @@ class SemanticCacheManager:
101
  import logging
102
 
103
  logger = logging.getLogger(__name__)
 
104
 
105
  try:
106
  # OPTIMIZATION: Skip embedding generation for very short queries (greetings, etc.)
@@ -111,6 +123,7 @@ class SemanticCacheManager:
111
  query_vector = await embedder.aembed_query(query)
112
 
113
  async with async_session_factory() as db:
 
114
  stmt = (
115
  select(
116
  NexusSemanticCache,
@@ -119,8 +132,9 @@ class SemanticCacheManager:
119
  .where(
120
  and_(
121
  NexusSemanticCache.workspace_id == workspace_id,
122
- NexusSemanticCache.is_agent == is_agent,
123
- NexusSemanticCache.user_role == user_role
 
124
  )
125
  )
126
  .order_by("distance")
@@ -140,6 +154,7 @@ class SemanticCacheManager:
140
  .values(hit_count=NexusSemanticCache.hit_count + 1)
141
  )
142
  await db.commit()
 
143
  return cache_hit.response_text
144
  except Exception as e:
145
  logger.error(f"Semantic Cache Check Failed: {str(e)}")
@@ -154,6 +169,7 @@ class SemanticCacheManager:
154
  import logging
155
 
156
  logger = logging.getLogger(__name__)
 
157
 
158
  try:
159
  # OPTIMIZATION: Skip embedding generation for very short queries
@@ -167,13 +183,15 @@ class SemanticCacheManager:
167
  cache_entry = NexusSemanticCache(
168
  workspace_id=workspace_id,
169
  user_id=user_id, # Keep user_id in record for audit, but not lookup
170
- is_agent=is_agent,
171
- user_role=user_role,
172
  query_text=query,
173
  query_embedding=query_vector,
174
  response_text=response_text
175
  )
176
  db.add(cache_entry)
177
  await db.commit()
 
178
  except Exception as e:
179
  logger.error(f"Semantic Cache Set Failed: {str(e)}")
 
 
90
  """
91
  Manages semantic LLM response caching using pgvector.
92
  Bypasses entirely the LangGraph orchestration if an idential query was asked before.
93
+
94
+ PARTITION KEY: (workspace_id, role_class)
95
+ - role_class is normalized to 'staff' or 'customer' to prevent cross-persona cache leaks.
96
  """
97
 
98
+ @staticmethod
99
+ def _normalize_role_class(user_role: str = "", is_agent: bool = False) -> str:
100
+ """Normalize any role string to a strict partition class."""
101
+ role_lower = str(user_role).lower()
102
+ if is_agent or "3sc" in role_lower or "agent" in role_lower or "lead" in role_lower or role_lower == "admin":
103
+ return "staff"
104
+ return "customer"
105
+
106
  @staticmethod
107
  async def check_cache(workspace_id: str, query: str, is_agent: bool = False, user_role: str = "customer_user", user_id: Optional[str] = None) -> Optional[str]:
108
  from core.llm import get_embeddings
 
112
  import logging
113
 
114
  logger = logging.getLogger(__name__)
115
+ role_class = SemanticCacheManager._normalize_role_class(user_role, is_agent)
116
 
117
  try:
118
  # OPTIMIZATION: Skip embedding generation for very short queries (greetings, etc.)
 
123
  query_vector = await embedder.aembed_query(query)
124
 
125
  async with async_session_factory() as db:
126
+ from sqlalchemy import text
127
  stmt = (
128
  select(
129
  NexusSemanticCache,
 
132
  .where(
133
  and_(
134
  NexusSemanticCache.workspace_id == workspace_id,
135
+ NexusSemanticCache.is_agent == (role_class == "staff"),
136
+ NexusSemanticCache.user_role == role_class,
137
+ NexusSemanticCache.created_at >= (func.now() - text("INTERVAL '6 hours'"))
138
  )
139
  )
140
  .order_by("distance")
 
154
  .values(hit_count=NexusSemanticCache.hit_count + 1)
155
  )
156
  await db.commit()
157
+ logger.info(f"🧠 Semantic Cache HIT [{role_class}]: ws={workspace_id[:8]} q='{query[:40]}'")
158
  return cache_hit.response_text
159
  except Exception as e:
160
  logger.error(f"Semantic Cache Check Failed: {str(e)}")
 
169
  import logging
170
 
171
  logger = logging.getLogger(__name__)
172
+ role_class = SemanticCacheManager._normalize_role_class(user_role, is_agent)
173
 
174
  try:
175
  # OPTIMIZATION: Skip embedding generation for very short queries
 
183
  cache_entry = NexusSemanticCache(
184
  workspace_id=workspace_id,
185
  user_id=user_id, # Keep user_id in record for audit, but not lookup
186
+ is_agent=(role_class == "staff"),
187
+ user_role=role_class,
188
  query_text=query,
189
  query_embedding=query_vector,
190
  response_text=response_text
191
  )
192
  db.add(cache_entry)
193
  await db.commit()
194
+ logger.info(f"🧠 Semantic Cache SET [{role_class}]: ws={workspace_id[:8]} q='{query[:40]}'")
195
  except Exception as e:
196
  logger.error(f"Semantic Cache Set Failed: {str(e)}")
197
+
core/tasks.py CHANGED
@@ -1139,3 +1139,26 @@ async def generate_global_insight(ctx):
1139
  except Exception as e:
1140
  logger.error(f"FAILURE: Global Insight generation failed: {str(e)}")
1141
  await db.rollback()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1139
  except Exception as e:
1140
  logger.error(f"FAILURE: Global Insight generation failed: {str(e)}")
1141
  await db.rollback()
1142
+
1143
+ async def purge_stale_semantic_cache(ctx):
1144
+ """
1145
+ Periodic task to physically delete semantic cache records older than 12 hours.
1146
+ Maintains a 6-hour functional TTL buffer for troubleshooting.
1147
+ """
1148
+ from models.nexus_semantic_cache import NexusSemanticCache
1149
+ from sqlalchemy import text, delete
1150
+
1151
+ logger.info("Executing Semantic Cache Purge...")
1152
+ async with async_session_factory() as db:
1153
+ try:
1154
+ # Delete records older than 12 hours
1155
+ stmt = delete(NexusSemanticCache).where(
1156
+ NexusSemanticCache.created_at < (func.now() - text("INTERVAL '12 hours'"))
1157
+ )
1158
+ result = await db.execute(stmt)
1159
+ count = result.rowcount
1160
+ await db.commit()
1161
+ logger.info(f"SUCCESS: Purged {count} stale semantic cache entries.")
1162
+ except Exception as e:
1163
+ logger.error(f"FAILURE: Semantic Cache Purge failed: {e}")
1164
+ await db.rollback()
frontend/apps/internal/src/App.tsx CHANGED
@@ -76,9 +76,23 @@ function App() {
76
 
77
  // Pre-load logic: We wait for auth AND for the first set of stats to arrive.
78
  // AI/Narrative loading is now "soft" to avoid navigation flickers.
79
- const isInitialLoading = (authLoading && !user) || (user && (
80
- (statsLoading && !stats)
81
- ));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
  if (isInitialLoading) {
84
  return (
@@ -92,6 +106,7 @@ function App() {
92
  );
93
  }
94
 
 
95
  const renderContent = () => {
96
  // 403 Forbidden check for direct navigation or state manipulation
97
  const forbidden = <div className="forbidden-view">403: Forbidden — Insufficient Permissions</div>;
 
76
 
77
  // Pre-load logic: We wait for auth AND for the first set of stats to arrive.
78
  // AI/Narrative loading is now "soft" to avoid navigation flickers.
79
+ // SAFETY: 5-second hard timeout prevents infinite loading if a backend endpoint 500s.
80
+ const [bootstrapComplete, setBootstrapComplete] = useState(false);
81
+
82
+ useEffect(() => {
83
+ const timer = setTimeout(() => setBootstrapComplete(true), 5000);
84
+ return () => clearTimeout(timer);
85
+ }, []);
86
+
87
+ useEffect(() => {
88
+ if (stats || (!statsLoading && user)) {
89
+ setBootstrapComplete(true);
90
+ }
91
+ }, [stats, statsLoading, user]);
92
+
93
+ const isInitialLoading = !bootstrapComplete && (
94
+ (authLoading && !user) || (user && (statsLoading && !stats))
95
+ );
96
 
97
  if (isInitialLoading) {
98
  return (
 
106
  );
107
  }
108
 
109
+
110
  const renderContent = () => {
111
  // 403 Forbidden check for direct navigation or state manipulation
112
  const forbidden = <div className="forbidden-view">403: Forbidden — Insufficient Permissions</div>;
frontend/apps/internal/src/components/TopBar.tsx CHANGED
@@ -45,16 +45,23 @@ export const TopBar: React.FC<TopBarProps> = ({ title, subtitle, onTicketSelect
45
  fetchNotifications();
46
  const token = localStorage.getItem(getStorageKey('token'));
47
  if (token && user?.workspace_id) {
48
- const ws = new WebSocket(getWsUrl(`ws/${user.workspace_id}?token=${token}`));
49
- ws.onmessage = (event) => {
50
- const data = JSON.parse(event.data);
51
- if (data.type === 'notification' || data.event === 'ticket_updated') {
52
- setHasUnread(true);
53
- fetchNotifications();
54
- }
55
- };
56
- return () => ws.close();
 
 
 
 
 
 
57
  }
 
58
  }, [user?.workspace_id]);
59
 
60
  useEffect(() => {
 
45
  fetchNotifications();
46
  const token = localStorage.getItem(getStorageKey('token'));
47
  if (token && user?.workspace_id) {
48
+ try {
49
+ const ws = new WebSocket(getWsUrl(`ws/${user.workspace_id}?token=${token}`));
50
+ ws.onmessage = (event) => {
51
+ const data = JSON.parse(event.data);
52
+ if (data.type === 'notification' || data.event === 'ticket_updated') {
53
+ setHasUnread(true);
54
+ fetchNotifications();
55
+ }
56
+ };
57
+ ws.onerror = () => console.warn('[WS] Connection error — notifications may be delayed');
58
+ ws.onclose = () => console.info('[WS] Connection closed');
59
+ return () => ws.close();
60
+ } catch (e) {
61
+ console.warn('[WS] Failed to initialize:', e);
62
+ }
63
  }
64
+
65
  }, [user?.workspace_id]);
66
 
67
  useEffect(() => {
nexus_worker.py CHANGED
@@ -20,7 +20,8 @@ from core.tasks import (
20
  generate_global_insight,
21
  crystallize_memory,
22
  nexus_pulse_check,
23
- send_triple_notification
 
24
  )
25
  from agents.workflow import run_ai_workflow
26
 
@@ -65,7 +66,8 @@ class WorkerSettings:
65
  generate_global_insight,
66
  crystallize_memory,
67
  nexus_pulse_check,
68
- send_triple_notification
 
69
  ]
70
 
71
  # Concurrency / Performance
@@ -84,7 +86,8 @@ class WorkerSettings:
84
  cron(monitor_sla_thresholds, minute={0, 20, 40}), # Every 10 minutes (Improved resolution)
85
  cron(record_system_heartbeat, hour={0, 12}, minute=0), # Twice a day
86
  cron(generate_global_insight, hour=3, minute=0), # Once a day at 3 AM
87
- cron(nexus_pulse_check, minute=set(range(0, 60, 15))) # Every 15 minutes
 
88
  ]
89
 
90
  on_startup = startup
 
20
  generate_global_insight,
21
  crystallize_memory,
22
  nexus_pulse_check,
23
+ send_triple_notification,
24
+ purge_stale_semantic_cache
25
  )
26
  from agents.workflow import run_ai_workflow
27
 
 
66
  generate_global_insight,
67
  crystallize_memory,
68
  nexus_pulse_check,
69
+ send_triple_notification,
70
+ purge_stale_semantic_cache
71
  ]
72
 
73
  # Concurrency / Performance
 
86
  cron(monitor_sla_thresholds, minute={0, 20, 40}), # Every 10 minutes (Improved resolution)
87
  cron(record_system_heartbeat, hour={0, 12}, minute=0), # Twice a day
88
  cron(generate_global_insight, hour=3, minute=0), # Once a day at 3 AM
89
+ cron(nexus_pulse_check, minute=set(range(0, 60, 15))), # Every 15 minutes
90
+ cron(purge_stale_semantic_cache, hour={0, 6, 12, 18}, minute=0) # Every 6 hours
91
  ]
92
 
93
  on_startup = startup
scratch/test_cache_lifecycle.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import os
3
+ import sys
4
+ from datetime import datetime, timedelta
5
+ from uuid import uuid4
6
+ from unittest.mock import MagicMock, AsyncMock
7
+
8
+ # Add project root to path
9
+ sys.path.append(os.getcwd())
10
+
11
+ from core.database import async_session_factory
12
+ from models.workspace import Workspace
13
+ from models.user import User, UserRole
14
+ from models.nexus_semantic_cache import NexusSemanticCache
15
+ from core.cache import SemanticCacheManager
16
+ from core.tasks import purge_stale_semantic_cache
17
+ from sqlalchemy import select, delete
18
+
19
+ async def test_cache_lifecycle():
20
+ print("\n--- NEXUS: SEMANTIC CACHE LIFECYCLE TEST (MOCKED) ---")
21
+
22
+ # 0. MOCK EMBEDDINGS to avoid Ollama connection issues
23
+ mock_vector = [0.1] * 768
24
+ from core import llm
25
+ original_get_embeddings = llm.get_embeddings
26
+
27
+ mock_embedder = MagicMock()
28
+ mock_embedder.aembed_query = AsyncMock(return_value=mock_vector)
29
+ llm.get_embeddings = MagicMock(return_value=mock_embedder)
30
+
31
+ try:
32
+ async with async_session_factory() as db:
33
+ # 1. Setup Mock User/WS
34
+ ws_res = await db.execute(select(Workspace).limit(1))
35
+ ws = ws_res.scalar_one_or_none()
36
+ if not ws:
37
+ ws = Workspace(name="Test WS", slug="test-ws")
38
+ db.add(ws)
39
+ await db.commit()
40
+ await db.refresh(ws)
41
+
42
+ user_res = await db.execute(select(User).limit(1))
43
+ user = user_res.scalar_one_or_none()
44
+ if not user:
45
+ user = User(email="test@example.com", full_name="Test User", workspace_id=ws.id)
46
+ db.add(user)
47
+ await db.commit()
48
+ await db.refresh(user)
49
+
50
+ test_query = "how do i reset my nexus password for testing?"
51
+ await db.execute(delete(NexusSemanticCache).where(NexusSemanticCache.query_text == test_query))
52
+ await db.commit()
53
+
54
+ # 2. SEED STALE CACHE (7 hours ago)
55
+ stale_entry = NexusSemanticCache(
56
+ workspace_id=ws.id,
57
+ user_id=user.id,
58
+ user_role="customer_user",
59
+ is_agent=False,
60
+ query_text=test_query,
61
+ query_embedding=mock_vector,
62
+ response_text="STALE ANSWER",
63
+ created_at=datetime.utcnow() - timedelta(hours=7)
64
+ )
65
+ db.add(stale_entry)
66
+ await db.commit()
67
+ print("SUCCESS: Seeded STALE cache entry (7h old).")
68
+
69
+ # 3. VERIFY STALE HIT FAILS (Freshness Check)
70
+ hit = await SemanticCacheManager.check_cache(
71
+ workspace_id=str(ws.id),
72
+ query=test_query,
73
+ is_agent=False,
74
+ user_role="customer_user"
75
+ )
76
+
77
+ if hit is None:
78
+ print("SUCCESS: Stale cache ignored (Returned None as expected).")
79
+ else:
80
+ print(f"FAILURE: Stale cache was returned: {hit}")
81
+
82
+ # 4. SEED FRESH CACHE (1 hour ago)
83
+ await db.execute(delete(NexusSemanticCache).where(NexusSemanticCache.query_text == test_query))
84
+ await db.commit()
85
+
86
+ fresh_entry = NexusSemanticCache(
87
+ workspace_id=ws.id,
88
+ user_id=user.id,
89
+ user_role="customer_user",
90
+ is_agent=False,
91
+ query_text=test_query,
92
+ query_embedding=mock_vector,
93
+ response_text="FRESH ANSWER",
94
+ created_at=datetime.utcnow() - timedelta(hours=1)
95
+ )
96
+ db.add(fresh_entry)
97
+ await db.commit()
98
+ print("SUCCESS: Seeded FRESH cache entry (1h old).")
99
+
100
+ # 5. VERIFY FRESH HIT WORKS (Mocked distance should be 0)
101
+ hit = await SemanticCacheManager.check_cache(
102
+ workspace_id=str(ws.id),
103
+ query=test_query,
104
+ is_agent=False,
105
+ user_role="customer_user"
106
+ )
107
+
108
+ if hit == "FRESH ANSWER":
109
+ print(f"SUCCESS: Fresh cache HIT: {hit}")
110
+ else:
111
+ print(f"FAILURE: Fresh cache not found or found wrong entry: {hit}")
112
+
113
+ # 6. TEST PURGE TASK (13-hour old record)
114
+ purge_query = "purge test question"
115
+ purge_entry = NexusSemanticCache(
116
+ workspace_id=ws.id,
117
+ user_id=user.id,
118
+ user_role="customer_user",
119
+ is_agent=False,
120
+ query_text=purge_query,
121
+ query_embedding=mock_vector,
122
+ response_text="EXPIRED",
123
+ created_at=datetime.utcnow() - timedelta(hours=13)
124
+ )
125
+ db.add(purge_entry)
126
+ await db.commit()
127
+
128
+ await purge_stale_semantic_cache(ctx=None)
129
+
130
+ res = await db.execute(select(NexusSemanticCache).where(NexusSemanticCache.query_text == purge_query))
131
+ if res.scalar_one_or_none() is None:
132
+ print("SUCCESS: 13h old record physically purged.")
133
+ else:
134
+ print("FAILURE: 13h old record still exists.")
135
+
136
+ finally:
137
+ # Restore
138
+ llm.get_embeddings = original_get_embeddings
139
+
140
+ if __name__ == "__main__":
141
+ asyncio.run(test_cache_lifecycle())