Spaces:
Paused

dushyantsingh0 commited on
Commit
c956e10
·
1 Parent(s): 18db802

backend stabilization

Browse files
agents/workflow.py CHANGED
@@ -319,6 +319,7 @@ async def run_ai_workflow(ctx: Any, ticket_id: Any, workspace_id: Any = None, **
319
 
320
  final_meta.update({
321
  "worker_version": v_tag,
 
322
  "summaries": {
323
  "internal_summary": internal_summary,
324
  "customer_summary": final_state.get("customer_summary") or "Technical analysis is complete. Our specialists are reviewing the findings to provide you with a resolution."
 
319
 
320
  final_meta.update({
321
  "worker_version": v_tag,
322
+ "kb_extracts": final_state.get("kb_extracts", []), # Persist full extracts for frontend
323
  "summaries": {
324
  "internal_summary": internal_summary,
325
  "customer_summary": final_state.get("customer_summary") or "Technical analysis is complete. Our specialists are reviewing the findings to provide you with a resolution."
api/v1/dashboard.py CHANGED
@@ -94,14 +94,31 @@ async def get_dashboard_hydration(
94
  except Exception as e:
95
  logger.error(f"Hydration Escalations Error: {e}")
96
  return {"rules": [], "breaches": [], "audit": []}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
 
99
  # return_exceptions=False (default) is fine here because we catch them inside the helpers
100
- stats, reports, queue, escalations = await asyncio.gather(
101
  run_stats(),
102
  run_reports(),
103
  run_queue(),
104
- run_escalations()
 
105
  )
106
 
107
  return {
@@ -109,12 +126,13 @@ async def get_dashboard_hydration(
109
  "reports": reports,
110
  "queue": queue,
111
  "escalations": escalations,
 
112
  "workspace_id": stats.get("workspace_id") if isinstance(stats, dict) else None
113
  }
114
 
115
  @router.get("/stats/")
116
  async def get_dashboard_stats(
117
- request: Request,
118
  workspace_id: str = None,
119
  refresh: bool = False,
120
  current_user: User = Depends(get_current_user),
@@ -124,7 +142,7 @@ async def get_dashboard_stats(
124
 
125
  # 0. Role Class Normalization
126
  role_class = SemanticCacheManager._normalize_role_class(str(current_user.role))
127
- portal = request.headers.get("X-Nexus-Portal", "unknown")
128
 
129
  # Cache lookup
130
  target_ws = workspace_id or str(current_user.workspace_id)
@@ -419,7 +437,7 @@ async def get_agent_queue(
419
  raise HTTPException(status_code=403, detail="Operational Access: Staff privilege required")
420
 
421
  role_class = SemanticCacheManager._normalize_role_class(str(current_user.role))
422
- portal = request.headers.get("X-Nexus-Portal", "unknown")
423
 
424
  # 0. Cache lookup (Context-Aware)
425
  target_ws = workspace_id or str(current_user.workspace_id)
@@ -525,40 +543,41 @@ async def get_ai_insights(
525
  from api.v1.tickets import list_tickets
526
  queue = await list_tickets(limit=5, current_user=current_user, db=db)
527
 
528
- # Prepare Prompt with strict 10s timeout for UI responsiveness
529
- llm = get_llm(timeout=10)
530
  prompt = ChatPromptTemplate.from_template("""
531
- You are the Nexus Workspace Intelligence Engine.
532
- Analyze the following workspace operational data and provide a high-fidelity summary.
533
 
534
  CONTEXT:
535
- - "OPEN" tokens/tickets are ALREADY assigned and handled by the AI Workflow Engine.
536
- - DO NOT count OPEN tickets as items requiring manual personnel action.
537
- - Focus only on ACKNOWLEDGED or IN_PROGRESS items for personnel burden.
538
- - Summaries must be clear, crisp and statistically correct based on available personnel.
539
 
540
- DATA:
541
- - Total Active Tickets: {total}
542
- - Breached/Urgent Items: {breached}
543
- - Status Distribution: {status_dist}
544
- - Available Internal Personnel: {agents}
 
 
 
545
 
546
  TICKET SAMPLE:
547
  {ticket_sample}
548
 
549
  GOALS:
550
- 1. A concise "Mission Summary" (Exactly 2 sentences).
551
- 2. Exactly 3 "Suggested Actions" for the lead user.
552
- 3. Three short metric insights for the visual dashboard cards (1 sentence each).
553
 
554
  Respond strictly in JSON format:
555
  {{
556
  "summary": "...",
557
  "actions": ["...", "...", "..."],
558
  "metric_insights": {{
559
- "intensity": "DEEP SCAN: ...",
560
- "velocity": "OUTPUT STEADY: ...",
561
- "thermal": "THERMAL STABILITY: ..."
562
  }}
563
  }}
564
  """)
@@ -578,14 +597,32 @@ async def get_ai_insights(
578
  )
579
  personnel_count = personnel_count_res.scalar() or 2 # Fallback to 2 per workspace minimum
580
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
581
  chain = prompt | llm
582
  try:
583
  # We use a try-except to catch LLM timeouts or provider 5xx (Cloudflare 524)
584
  response = await chain.ainvoke({
585
  "total": stats["total_tickets"],
586
- "breached": any(t.get("priority") == "P0" for t in queue) if isinstance(queue[0], dict) else any(t.priority == "P0" for t in queue),
 
 
587
  "status_dist": stats["by_status"],
588
- "agents": personnel_count,
 
589
  "ticket_sample": sample
590
  })
591
 
 
94
  except Exception as e:
95
  logger.error(f"Hydration Escalations Error: {e}")
96
  return {"rules": [], "breaches": [], "audit": []}
97
+ async def run_insights():
98
+ try:
99
+ # During hydration, we only wait 10s for AI to prevent blocking the entire dashboard.
100
+ # If it takes longer, we'll serve the background cache or a processing fallback.
101
+ return await asyncio.wait_for(
102
+ get_ai_insights(request, workspace_id, refresh, current_user, db),
103
+ timeout=10.0
104
+ )
105
+ except asyncio.TimeoutError:
106
+ logger.warning(f"Hydration AI Timeout: Serving background cache for {workspace_id}")
107
+ from core.cache import get_cached_search
108
+ ws_id = workspace_id or str(current_user.workspace_id)
109
+ return await get_cached_search(f"dashboard:insights:{ws_id}:system")
110
+ except Exception as e:
111
+ logger.error(f"Hydration AI Insights Error: {e}")
112
+ return None
113
 
114
 
115
  # return_exceptions=False (default) is fine here because we catch them inside the helpers
116
+ stats, reports, queue, escalations, insights = await asyncio.gather(
117
  run_stats(),
118
  run_reports(),
119
  run_queue(),
120
+ run_escalations(),
121
+ run_insights()
122
  )
123
 
124
  return {
 
126
  "reports": reports,
127
  "queue": queue,
128
  "escalations": escalations,
129
+ "insights": insights,
130
  "workspace_id": stats.get("workspace_id") if isinstance(stats, dict) else None
131
  }
132
 
133
  @router.get("/stats/")
134
  async def get_dashboard_stats(
135
+ request: Optional[Request] = None,
136
  workspace_id: str = None,
137
  refresh: bool = False,
138
  current_user: User = Depends(get_current_user),
 
142
 
143
  # 0. Role Class Normalization
144
  role_class = SemanticCacheManager._normalize_role_class(str(current_user.role))
145
+ portal = request.headers.get("X-Nexus-Portal", "unknown") if request else "system"
146
 
147
  # Cache lookup
148
  target_ws = workspace_id or str(current_user.workspace_id)
 
437
  raise HTTPException(status_code=403, detail="Operational Access: Staff privilege required")
438
 
439
  role_class = SemanticCacheManager._normalize_role_class(str(current_user.role))
440
+ portal = request.headers.get("X-Nexus-Portal", "unknown") if request else "system"
441
 
442
  # 0. Cache lookup (Context-Aware)
443
  target_ws = workspace_id or str(current_user.workspace_id)
 
543
  from api.v1.tickets import list_tickets
544
  queue = await list_tickets(limit=5, current_user=current_user, db=db)
545
 
546
+ # Prepare Prompt with strategic operational depth
547
+ llm = get_llm(timeout=35)
548
  prompt = ChatPromptTemplate.from_template("""
549
+ You are the Nexus Workspace Strategy Engine.
550
+ Analyze the following workspace telemetry and provide a high-fidelity operational directive.
551
 
552
  CONTEXT:
553
+ - "OPEN" tokens are handled by AI. Do not worry about them.
554
+ - Focus on bottleneck detection and quality pulse.
 
 
555
 
556
+ TELEMETRY:
557
+ - Active Tickets: {total}
558
+ - SLA Breached: {breached_count}
559
+ - Compliance Rate: {compliance}
560
+ - User CSAT: {csat}/5.0
561
+ - Distribution: {status_dist}
562
+ - Top Pressure Point (Category): {top_category}
563
+ - Personnel Load (Staff names + their ticket counts): {personnel_load}
564
 
565
  TICKET SAMPLE:
566
  {ticket_sample}
567
 
568
  GOALS:
569
+ 1. "summary": Exactly 2 sentences. One on current health, one on the primary bottleneck.
570
+ 2. "actions": Exactly 3 highly specific actions. If an agent is overloaded, suggest rebalancing. If a category is spiking, suggest a protocol review.
571
+ 3. "metric_insights": cards for intensity, velocity, and thermal stability.
572
 
573
  Respond strictly in JSON format:
574
  {{
575
  "summary": "...",
576
  "actions": ["...", "...", "..."],
577
  "metric_insights": {{
578
+ "intensity": "...",
579
+ "velocity": "...",
580
+ "thermal": "..."
581
  }}
582
  }}
583
  """)
 
597
  )
598
  personnel_count = personnel_count_res.scalar() or 2 # Fallback to 2 per workspace minimum
599
 
600
+ # Calculate high-fidelity metrics
601
+ performance = stats.get("performance", {})
602
+ top_cat = "None"
603
+ if stats.get("by_category"):
604
+ # Filter out 'GENERAL' and 'UNCATEGORIZED' to find real pressure points if possible
605
+ cats = stats["by_category"]
606
+ real_cats = {k: v for k, v in cats.items() if k not in ["GENERAL", "UNCATEGORIZED"]}
607
+ if real_cats:
608
+ top_cat = max(real_cats, key=real_cats.get)
609
+ elif cats:
610
+ top_cat = max(cats, key=cats.get)
611
+
612
+ p_load = stats.get("personnel_load", [])
613
+ load_str = ", ".join([f"{p['name']} ({p['count']})" for p in p_load[:5]])
614
+
615
  chain = prompt | llm
616
  try:
617
  # We use a try-except to catch LLM timeouts or provider 5xx (Cloudflare 524)
618
  response = await chain.ainvoke({
619
  "total": stats["total_tickets"],
620
+ "breached_count": performance.get("sla_breached_count", 0),
621
+ "compliance": f"{(stats.get('reports', {}).get('sla', {}).get('sla_compliance_rate', 0)*100):.1f}%",
622
+ "csat": performance.get("csat_score", 0),
623
  "status_dist": stats["by_status"],
624
+ "top_category": top_cat,
625
+ "personnel_load": load_str,
626
  "ticket_sample": sample
627
  })
628
 
frontend/apps/internal/src/components/AnalyticsDashboard.tsx CHANGED
@@ -53,7 +53,7 @@ export const AnalyticsDashboard: React.FC<AnalyticsDashboardProps> = ({ workspac
53
  const { stats, loading: statsLoading } = useDashboardStats(workspaceId);
54
  const { daily, sla, loading: reportsLoading } = useReports(workspaceId);
55
  const { loading: escLoading } = useEscalations(workspaceId);
56
- const { loading: aiLoading } = useAIInsights(workspaceId);
57
  const { narrative, loading: narrativeLoading } = useServiceNarrative(workspaceId);
58
 
59
  const [timeRange, setTimeRange] = useState(30);
@@ -61,7 +61,7 @@ export const AnalyticsDashboard: React.FC<AnalyticsDashboardProps> = ({ workspac
61
  const { metrics: userMetrics, loading: userMetricsLoading } = useUserMetrics(workspaceId, timeRange);
62
 
63
  const isLoading = statsLoading || reportsLoading || escLoading || aiLoading || narrativeLoading || slaLoading || userMetricsLoading;
64
- const hasData = stats && daily.length > 0;
65
 
66
  if (isLoading && !hasData) {
67
  return (
@@ -182,10 +182,10 @@ export const AnalyticsDashboard: React.FC<AnalyticsDashboardProps> = ({ workspac
182
  </div>
183
  <div className={styles.cardNeuralConclusion}>
184
  <Sparkles size={12} className={styles.neuralGlow} />
185
- {volumeTrendData.length >= 2 ? (
186
- <span>AI INSIGHT: Volume indicates {volumeTrendData[volumeTrendData.length-1].value > volumeTrendData[0].value ? 'an UPWARD' : 'a STABLE'} trajectory. Peak volume reached {Math.max(...volumeTrendData.map(v => v.value))} units.</span>
187
  ) : (
188
- <span>AI INSIGHT: Analyzing volume trajectory... initial data points are being synchronized.</span>
189
  )}
190
  </div>
191
  </div>
@@ -232,7 +232,11 @@ export const AnalyticsDashboard: React.FC<AnalyticsDashboardProps> = ({ workspac
232
  </div>
233
  <div className={styles.cardNeuralConclusion}>
234
  <TrendingUp size={12} className={styles.neuralGlow} />
235
- <span>CORE MIX: {categoryData[0]?.name || 'UNKNOWN'} Tier remains the primary operational load generator.</span>
 
 
 
 
236
  </div>
237
  </div>
238
 
@@ -260,10 +264,10 @@ export const AnalyticsDashboard: React.FC<AnalyticsDashboardProps> = ({ workspac
260
  </div>
261
  <div className={styles.cardNeuralConclusion}>
262
  <Shield size={12} className={styles.neuralGlow} />
263
- {slaTrend.length > 0 ? (
264
- <span>SLA INSIGHT: Current compliance is {Math.round(slaTrend[slaTrend.length-1].compliance * 100)}%. {slaTrend[slaTrend.length-1].compliance > 0.9 ? 'Operational targets are being met.' : 'Target thresholds require attention.'}</span>
265
  ) : (
266
- <span>SLA INSIGHT: Compliance levels are RECOVERING across all active workspaces.</span>
267
  )}
268
  </div>
269
  </div>
 
53
  const { stats, loading: statsLoading } = useDashboardStats(workspaceId);
54
  const { daily, sla, loading: reportsLoading } = useReports(workspaceId);
55
  const { loading: escLoading } = useEscalations(workspaceId);
56
+ const { insights, loading: aiLoading } = useAIInsights(workspaceId);
57
  const { narrative, loading: narrativeLoading } = useServiceNarrative(workspaceId);
58
 
59
  const [timeRange, setTimeRange] = useState(30);
 
61
  const { metrics: userMetrics, loading: userMetricsLoading } = useUserMetrics(workspaceId, timeRange);
62
 
63
  const isLoading = statsLoading || reportsLoading || escLoading || aiLoading || narrativeLoading || slaLoading || userMetricsLoading;
64
+ const hasData = (stats && daily.length > 0) || insights;
65
 
66
  if (isLoading && !hasData) {
67
  return (
 
182
  </div>
183
  <div className={styles.cardNeuralConclusion}>
184
  <Sparkles size={12} className={styles.neuralGlow} />
185
+ {insights?.metric_insights?.intensity ? (
186
+ <span>AI INTENSITY SCAN: {insights.metric_insights.intensity}</span>
187
  ) : (
188
+ <span>AI INSIGHT: Volume indicates {volumeTrendData[volumeTrendData.length-1]?.value > volumeTrendData[0]?.value ? 'an UPWARD' : 'a STABLE'} trajectory.</span>
189
  )}
190
  </div>
191
  </div>
 
232
  </div>
233
  <div className={styles.cardNeuralConclusion}>
234
  <TrendingUp size={12} className={styles.neuralGlow} />
235
+ {insights?.metric_insights?.velocity ? (
236
+ <span>AI VELOCITY PULSE: {insights.metric_insights.velocity}</span>
237
+ ) : (
238
+ <span>CORE MIX: {categoryData[0]?.name || 'UNKNOWN'} Tier remains the primary operational load generator.</span>
239
+ )}
240
  </div>
241
  </div>
242
 
 
264
  </div>
265
  <div className={styles.cardNeuralConclusion}>
266
  <Shield size={12} className={styles.neuralGlow} />
267
+ {insights?.metric_insights?.thermal ? (
268
+ <span>AI THERMAL STABILITY: {insights.metric_insights.thermal}</span>
269
  ) : (
270
+ <span>SLA INSIGHT: {slaTrend.length > 0 ? `Current compliance is ${Math.round(slaTrend[slaTrend.length-1].compliance * 100)}%.` : 'Compliance levels are RECOVERING.'}</span>
271
  )}
272
  </div>
273
  </div>
frontend/apps/internal/src/components/DashboardOverview.tsx CHANGED
@@ -54,8 +54,11 @@ export const DashboardOverview: React.FC<DashboardOverviewProps> = ({ workspaceI
54
  const isSyncing = hydrationLoading;
55
 
56
  const handleFullRefresh = async () => {
57
- // Only refresh live telemetry data together
58
- await refreshHydration();
 
 
 
59
  };
60
 
61
  const getGreeting = () => {
 
54
  const isSyncing = hydrationLoading;
55
 
56
  const handleFullRefresh = async () => {
57
+ // Synchronize all tactical and strategic layers
58
+ await Promise.all([
59
+ refreshHydration(),
60
+ refreshInsights()
61
+ ]);
62
  };
63
 
64
  const getGreeting = () => {
frontend/apps/internal/src/components/TicketDetails.tsx CHANGED
@@ -964,8 +964,8 @@ export const TicketDetails: React.FC<TicketDetailsProps> = ({ initialTicket, onB
964
  <div className={styles.sidebarSection}>
965
  <div className={styles.propertyLabel}>SEMANTIC PROXIMITY</div>
966
  <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 12 }}>
967
- {ticket.ai_metadata?.similar_tickets && ticket.ai_metadata.similar_tickets.length > 0 ? (
968
- ticket.ai_metadata.similar_tickets.map((sim: { id: string; title: string; similarity: number; status: string }, i: number) => (
969
  <div key={i} className={styles.propertyValue} style={{ cursor: 'pointer', padding: '8px 12px' }} onClick={() => window.location.href = `?ticket_id=${sim.id}`}>
970
  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
971
  <span style={{ fontSize: 8, fontWeight: 900, color: 'var(--primary)', letterSpacing: '0.05em' }}>{(sim.similarity * 100).toFixed(0)}% MATCH</span>
 
964
  <div className={styles.sidebarSection}>
965
  <div className={styles.propertyLabel}>SEMANTIC PROXIMITY</div>
966
  <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 12 }}>
967
+ {ticket.similar_tickets && ticket.similar_tickets.length > 0 ? (
968
+ ticket.similar_tickets.map((sim: { id: string; title: string; similarity: number; status: string }, i: number) => (
969
  <div key={i} className={styles.propertyValue} style={{ cursor: 'pointer', padding: '8px 12px' }} onClick={() => window.location.href = `?ticket_id=${sim.id}`}>
970
  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
971
  <span style={{ fontSize: 8, fontWeight: 900, color: 'var(--primary)', letterSpacing: '0.05em' }}>{(sim.similarity * 100).toFixed(0)}% MATCH</span>
frontend/packages/shared/src/hooks/useDashboard.ts CHANGED
@@ -431,7 +431,8 @@ let globalHydration = {
431
  stats: null as any,
432
  reports: null as any,
433
  escalations: null as any,
434
- queue: [] as any[]
 
435
  };
436
  let globalHydrationLoading = false;
437
  let globalHydrationError: string | null = null;
@@ -465,7 +466,7 @@ export const useDashboardHydration = (workspaceId?: string) => {
465
 
466
  // Strict 30s timeout to prevent infinite loading
467
  const timeoutPromise = new Promise((_, reject) =>
468
- setTimeout(() => reject(new Error('Dashboard hydration timed out after 30s')), 30000)
469
  );
470
 
471
  const fetchPromise = api.get(force ? `${url}${url.includes('?') ? '&' : '?'}refresh=true` : url);
@@ -478,6 +479,18 @@ export const useDashboardHydration = (workspaceId?: string) => {
478
  globalReports = response.data.reports;
479
  globalEscalations = response.data.escalations || globalEscalations;
480
 
 
 
 
 
 
 
 
 
 
 
 
 
481
  // Patch: Sync Narrative so useServiceNarrative doesn't fire a redundant fetch
482
  if (globalReports?.insights) {
483
  globalNarrative = globalReports.insights;
 
431
  stats: null as any,
432
  reports: null as any,
433
  escalations: null as any,
434
+ queue: [] as any[],
435
+ insights: null as AIInsights | null
436
  };
437
  let globalHydrationLoading = false;
438
  let globalHydrationError: string | null = null;
 
466
 
467
  // Strict 30s timeout to prevent infinite loading
468
  const timeoutPromise = new Promise((_, reject) =>
469
+ setTimeout(() => reject(new Error('Dashboard hydration timed out after 45s')), 45000)
470
  );
471
 
472
  const fetchPromise = api.get(force ? `${url}${url.includes('?') ? '&' : '?'}refresh=true` : url);
 
479
  globalReports = response.data.reports;
480
  globalEscalations = response.data.escalations || globalEscalations;
481
 
482
+ // Patch: Sync AI Insights to prevent redundant fetch
483
+ if (response.data.insights) {
484
+ globalAIInsights = response.data.insights;
485
+ try {
486
+ sessionStorage.setItem(AI_INSIGHTS_CACHE_KEY, JSON.stringify({
487
+ data: globalAIInsights,
488
+ timestamp: Date.now()
489
+ }));
490
+ } catch { }
491
+ notifyAIInsights();
492
+ }
493
+
494
  // Patch: Sync Narrative so useServiceNarrative doesn't fire a redundant fetch
495
  if (globalReports?.insights) {
496
  globalNarrative = globalReports.insights;
nexus_worker.py CHANGED
@@ -27,6 +27,7 @@ from core.tasks import (
27
  send_triple_notification,
28
  purge_stale_semantic_cache,
29
  generate_workspace_insights,
 
30
  recover_nexus_history,
31
  harvest_expertise_task,
32
  record_workflow_step_task,
@@ -263,6 +264,7 @@ class HeavyWorkerSettings:
263
  # Distributed Cron (Strategic Insight only needs to run on Heavy)
264
  cron_jobs = [
265
  cron(generate_global_insight, hour=3, minute=0),
 
266
  cron(generate_nightly_personnel_analytics, hour=0, minute=0)
267
  ]
268
  queue_name = "arq:heavy"
 
27
  send_triple_notification,
28
  purge_stale_semantic_cache,
29
  generate_workspace_insights,
30
+ refresh_active_workspace_insights,
31
  recover_nexus_history,
32
  harvest_expertise_task,
33
  record_workflow_step_task,
 
264
  # Distributed Cron (Strategic Insight only needs to run on Heavy)
265
  cron_jobs = [
266
  cron(generate_global_insight, hour=3, minute=0),
267
+ cron(refresh_active_workspace_insights, hour=0, minute=0),
268
  cron(generate_nightly_personnel_analytics, hour=0, minute=0)
269
  ]
270
  queue_name = "arq:heavy"
services/ticket_service.py CHANGED
@@ -79,6 +79,21 @@ class TicketService:
79
  setattr(ticket, "rating", ticket.feedback.rating if ticket.feedback else None)
80
  setattr(ticket, "feedback_comment", ticket.feedback.comment if ticket.feedback else None)
81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  if is_staff:
83
  return TicketInternalResponse.model_validate(ticket).model_dump(mode='json')
84
  return TicketResponse.model_validate(ticket).model_dump(mode='json')
 
79
  setattr(ticket, "rating", ticket.feedback.rating if ticket.feedback else None)
80
  setattr(ticket, "feedback_comment", ticket.feedback.comment if ticket.feedback else None)
81
 
82
+ # Semantic Proximity & Knowledge Hookups
83
+ if ticket.ai_metadata:
84
+ # 1. Similar Tickets (Role-Gated)
85
+ if is_staff:
86
+ setattr(ticket, "similar_tickets", ticket.ai_metadata.get("similar_tickets", []))
87
+ else:
88
+ setattr(ticket, "similar_tickets", ticket.ai_metadata.get("customer_proximity", []))
89
+
90
+ # 2. Similar Articles (Knowledge Base)
91
+ # Use the high-fidelity extracts for clickable links
92
+ setattr(ticket, "similar_articles", ticket.ai_metadata.get("kb_extracts", []))
93
+ else:
94
+ setattr(ticket, "similar_tickets", [])
95
+ setattr(ticket, "similar_articles", [])
96
+
97
  if is_staff:
98
  return TicketInternalResponse.model_validate(ticket).model_dump(mode='json')
99
  return TicketResponse.model_validate(ticket).model_dump(mode='json')
tasks/ai.py CHANGED
@@ -171,12 +171,26 @@ async def index_kb_article(ctx, article_id: UUID, **kwargs):
171
  chunk_vec = await text_model.aembed_query(f"{article.title}: {text_content}")
172
  db.add(KBArticleChunk(article_id=article.id, content=text_content, chunk_index=i, embedding=chunk_vec))
173
 
174
- # Summarization
 
175
  resp = await llm.ainvoke([
176
- SystemMessage(content="Summarize this technical article in 2-3 sentences."),
177
- HumanMessage(content=truncate_content(article.content, 12000))
 
 
 
178
  ])
179
- article.summary = str(resp.content)
 
 
 
 
 
 
 
 
 
 
180
 
181
  await db.commit()
182
  except Exception as e:
@@ -241,6 +255,24 @@ async def generate_global_insight(ctx, *args, **kwargs):
241
  await db.commit()
242
  except: pass
243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
244
  async def generate_workspace_insights(ctx, workspace_id: str, **kwargs):
245
  """Generate background AI insights for a workspace."""
246
  from api.v1.dashboard import get_dashboard_stats
@@ -249,20 +281,67 @@ async def generate_workspace_insights(ctx, workspace_id: str, **kwargs):
249
 
250
  async with async_session_factory() as db:
251
  try:
252
- user_stmt = select(User).where(or_(User.global_role == UserRole.SUPERADMIN, User._legacy_role == UserRole.SC_ADMIN), User.is_active).limit(1)
 
 
 
 
253
  system_user = (await db.execute(user_stmt)).scalar_one_or_none()
254
- if not system_user: return
 
 
255
 
256
- stats = await get_dashboard_stats(workspace_id, current_user=system_user, db=db)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
 
258
- llm = get_llm(timeout=120)
259
- prompt = f"Analyze workspace data and provide JSON summary, actions, and metric_insights: {json.dumps(stats)}"
260
  resp = await llm.ainvoke(prompt)
261
- insights = json.loads(str(resp.content).strip().replace("```json", "").replace("```", ""))
 
 
 
 
 
262
 
263
- await set_cached_search(f"dashboard:insights:{workspace_id}:system", insights, ttl=1800)
264
  except Exception as e:
265
- logger.error(f"Workspace insights failed: {e}")
266
 
267
  async def process_kb_import_task(ctx, workspace_id: UUID, author_id: UUID, file_content: str, original_filename: str, **kwargs):
268
  """Convert raw text into a structured KB Article."""
@@ -272,7 +351,7 @@ async def process_kb_import_task(ctx, workspace_id: UUID, author_id: UUID, file_
272
  ai_content = str(resp.content).strip()
273
 
274
  async with async_session_factory() as db:
275
- new_article = KBArticle(workspace_id=workspace_id, author_id=author_id, title=f"Import: {original_filename}", content=ai_content, category="General", is_published=False)
276
  db.add(new_article)
277
  await db.commit()
278
  await enqueue_task("index_kb_article", new_article.id)
 
171
  chunk_vec = await text_model.aembed_query(f"{article.title}: {text_content}")
172
  db.add(KBArticleChunk(article_id=article.id, content=text_content, chunk_index=i, embedding=chunk_vec))
173
 
174
+ # Summarization & Categorization
175
+ # We use a combined prompt to save LLM calls
176
  resp = await llm.ainvoke([
177
+ SystemMessage(content="""You are a KB Librarian. Analyze the article and provide:
178
+ 1. A 2-3 sentence technical summary.
179
+ 2. A single authoritative category from this list: ENGINEERING, FINANCE, SUCCESS, ACCOUNT, SECURITY, COMPLIANCE, PRODUCT, GENERAL.
180
+ Return as JSON: {"summary": "...", "category": "..."}"""),
181
+ HumanMessage(content=truncate_content(article.content, 10000))
182
  ])
183
+
184
+ try:
185
+ ai_data = json.loads(str(resp.content).strip().replace("```json", "").replace("```", ""))
186
+ article.summary = ai_data.get("summary", article.summary)
187
+
188
+ # Only overwrite if it's a generic placeholder
189
+ if article.category in [None, "Imported", "General", "Uncategorized"]:
190
+ article.category = ai_data.get("category", "GENERAL").upper()
191
+ except:
192
+ # Fallback to simple summary if JSON fails
193
+ article.summary = str(resp.content)
194
 
195
  await db.commit()
196
  except Exception as e:
 
255
  await db.commit()
256
  except: pass
257
 
258
+ async def refresh_active_workspace_insights(ctx, **kwargs):
259
+ """Cron task to preemptively refresh insights for active workspaces."""
260
+ from models.workspace import Workspace
261
+ from tasks.system import enqueue_task
262
+
263
+ async with async_session_factory() as db:
264
+ # Find workspaces with tickets created/updated in the last 24h
265
+ day_ago = datetime.utcnow() - timedelta(days=1)
266
+ stmt = select(Ticket.workspace_id).where(
267
+ or_(Ticket.created_at >= day_ago, Ticket.updated_at >= day_ago)
268
+ ).distinct()
269
+ res = await db.execute(stmt)
270
+ active_ws_ids = res.scalars().all()
271
+
272
+ logger.info(f"Insight Refresh: Found {len(active_ws_ids)} active workspaces to analyze.")
273
+ for ws_id in active_ws_ids:
274
+ await enqueue_task(ctx.get("redis") if isinstance(ctx, dict) else None, "generate_workspace_insights", str(ws_id))
275
+
276
  async def generate_workspace_insights(ctx, workspace_id: str, **kwargs):
277
  """Generate background AI insights for a workspace."""
278
  from api.v1.dashboard import get_dashboard_stats
 
281
 
282
  async with async_session_factory() as db:
283
  try:
284
+ # 1. Get a system user context for stats fetching
285
+ user_stmt = select(User).where(
286
+ or_(User.global_role == UserRole.SC_ADMIN, User._legacy_role == UserRole.SC_ADMIN),
287
+ User.is_active
288
+ ).limit(1)
289
  system_user = (await db.execute(user_stmt)).scalar_one_or_none()
290
+ if not system_user:
291
+ logger.error("Workspace Insights: No SC_ADMIN found for context.")
292
+ return
293
 
294
+ # 2. Fetch stats (Headless)
295
+ stats = await get_dashboard_stats(None, workspace_id, current_user=system_user, db=db)
296
+
297
+ # 3. Generate Analysis via LLM (Long timeout for background task)
298
+ llm = get_llm(timeout=300)
299
+
300
+ # Build context similar to the live endpoint
301
+ from api.v1.tickets import list_tickets
302
+ queue = await list_tickets(limit=10, current_user=system_user, db=db)
303
+ sample = "\n".join([f"- {t.title} ({t.priority}, {t.status})" for t in queue])
304
+
305
+ performance = stats.get("performance", {})
306
+ p_load = stats.get("personnel_load", [])
307
+ load_str = ", ".join([f"{p['name']} ({p['count']})" for p in p_load[:5]])
308
+
309
+ prompt = f"""
310
+ You are the Nexus Workspace Strategy Engine.
311
+ Analyze the following workspace telemetry and provide a high-fidelity operational directive.
312
+
313
+ TELEMETRY:
314
+ - Active Tickets: {stats["total_tickets"]}
315
+ - SLA Breached: {performance.get("sla_breached_count", 0)}
316
+ - Compliance Rate: {(stats.get('reports', {}).get('sla', {}).get('sla_compliance_rate', 0)*100):.1f}%
317
+ - User CSAT: {performance.get("csat_score", 0)}/5.0
318
+ - Personnel Load: {load_str}
319
+
320
+ TICKET SAMPLE:
321
+ {sample}
322
+
323
+ Respond strictly in JSON format:
324
+ {{
325
+ "summary": "2 sentences. One on health, one on bottleneck.",
326
+ "actions": ["Specific Action 1", "Specific Action 2", "Specific Action 3"],
327
+ "metric_insights": {{
328
+ "intensity": "...",
329
+ "velocity": "...",
330
+ "thermal": "..."
331
+ }}
332
+ }}
333
+ """
334
 
 
 
335
  resp = await llm.ainvoke(prompt)
336
+ json_str = str(resp.content).strip().replace("```json", "").replace("```", "")
337
+ insights = json.loads(json_str)
338
+
339
+ # Cache for 12 hours (Persistent system-level cache)
340
+ await set_cached_search(f"dashboard:insights:{workspace_id}:system", insights, ttl=43200)
341
+ logger.info(f"✅ Background insights generated for workspace: {workspace_id}")
342
 
 
343
  except Exception as e:
344
+ logger.error(f"Workspace insights failed for {workspace_id}: {e}")
345
 
346
  async def process_kb_import_task(ctx, workspace_id: UUID, author_id: UUID, file_content: str, original_filename: str, **kwargs):
347
  """Convert raw text into a structured KB Article."""
 
351
  ai_content = str(resp.content).strip()
352
 
353
  async with async_session_factory() as db:
354
+ new_article = KBArticle(workspace_id=workspace_id, author_id=author_id, title=f"Import: {original_filename}", content=ai_content, category="Imported", is_published=False)
355
  db.add(new_article)
356
  await db.commit()
357
  await enqueue_task("index_kb_article", new_article.id)
templates/landing.html CHANGED
@@ -10,8 +10,8 @@
10
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Outfit:wght@700;800;900&display=swap" rel="stylesheet">
11
  <style>
12
  :root {
13
- --primary: #dc2626;
14
- --primary-light: #fef2f2;
15
  --text-main: #0f172a;
16
  --text-muted: #64748b;
17
  --bg-page: #ffffff;
@@ -250,7 +250,7 @@
250
  <div class="container">
251
  <nav>
252
  <div class="logo-mark">
253
- <div style="width: 32px; height: 32px; background: var(--primary); color: white; border-radius: 8px; display: flex; alignItems: center; justifyContent: center; font-size: 18px; font-weight: 900;">N</div>
254
  NEXUS
255
  </div>
256
  </nav>
 
10
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Outfit:wght@700;800;900&display=swap" rel="stylesheet">
11
  <style>
12
  :root {
13
+ --primary: #7C3AED;
14
+ --primary-light: #F5F3FF;
15
  --text-main: #0f172a;
16
  --text-muted: #64748b;
17
  --bg-page: #ffffff;
 
250
  <div class="container">
251
  <nav>
252
  <div class="logo-mark">
253
+ <div style="width: 32px; height: 32px; background: var(--primary); color: white; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 18px; font-weight: 900;">N</div>
254
  NEXUS
255
  </div>
256
  </nav>