Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit ·
1818cda
1
Parent(s): d96521a
backend stabilization
Browse filesFiles changed (8)
- api/v1/messages.py+22-2
- api/v1/tickets.py+55-14
- frontend/apps/customer/src/components/TopBar.tsx+9-14
- frontend/apps/internal/src/components/TopBar.module.css+42
- frontend/apps/internal/src/components/TopBar.tsx+66-6
- frontend/packages/shared/src/index.ts+1-1
- frontend/packages/shared/src/utils/api.ts+17
- nexus_worker.py+4-2
1 unmodified line234567891055 unmodified lines6667686970717266 unmodified lines1391401411421431441 unmodified lineMessage endpoints: threaded messaging for tickets with BOLA protection."""from typing import Any, List, Dictfrom uuid import UUIDfrom fastapi import APIRouter, Depends, HTTPException, status, Responsefrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy import select55 unmodified linespayload: MessageCreate,current_user: User = Depends(get_current_user),db: AsyncSession = Depends(get_db),arq_pool: Any = Depends(get_arq_pool)) -> Any:"""Send a message on a ticket. Enforces BOLA protection for customers."""is_staff = current_user.role in ALL_SC_ROLES66 unmodified lines# --- 3. Refresh Summarization Context ---await arq_pool.enqueue_job("auto_summarize_ticket", ticket_id)return await sanitize_message_response(new_message, db)1 unmodified line234567891011121355 unmodified lines697071727374757666 unmodified lines1431441451461471481491501511521531541551561571581591601611621631641 unmodified lineMessage endpoints: threaded messaging for tickets with BOLA protection."""import logginglogger = logging.getLogger(__name__)from typing import Any, List, Dictfrom uuid import UUIDfrom fastapi import APIRouter, Depends, HTTPException, status, Response, BackgroundTasksfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy import select55 unmodified linespayload: MessageCreate,current_user: User = Depends(get_current_user),db: AsyncSession = Depends(get_db),arq_pool: Any = Depends(get_arq_pool),background_tasks: BackgroundTasks = None) -> Any:"""Send a message on a ticket. Enforces BOLA protection for customers."""is_staff = current_user.role in ALL_SC_ROLES66 unmodified lines# --- 3. Refresh Summarization Context ---await arq_pool.enqueue_job("auto_summarize_ticket", ticket_id)# --- 4. Notify Customer of Expert Response ---# Only if sender is staff and message is publicif is_staff and not payload.is_internal and ticket.created_by != current_user.id:from core.tasks import send_triple_notification# Use arq to avoid blocking, or background_tasks if availabletry:# Correct arq call: do NOT pass ctx/None explicitlyawait arq_pool.enqueue_job("send_triple_notification",str(ticket.created_by),str(ticket.workspace_id),"💬 Expert Response",f"An expert has replied to your ticket: '{ticket.title}'")except Exception as e:logger.error(f"Failed to queue customer response notification: {e}")return await sanitize_message_response(new_message, db)
263 unmodified lines264265266267268269136 unmodified lines4064074084094104114124131 unmodified line4154164174184194204214224238 unmodified lines432433434435436437438439440257 unmodified lines69869970070170270322 unmodified lines726727728729730731732733734735736737738739234 unmodified lines974975976977978979263 unmodified lines{"event": "ticket_created", "ticket_id": str(new_ticket.id), "title": new_ticket.title})logger.info(f"Ticket created: {new_ticket.id} by user {current_user.id} in workspace {current_user.workspace_id}")return await sanitize_ticket_response(new_ticket, current_user, db)136 unmodified linesfor rank, row in enumerate(list_hits):ticket = row[0]score = float(getattr(row, score_attr) or 0.0)# RRF formula with weightsrrf_score = weight * (1.0 / (60 + rank + 1))if ticket.id not in ticket_scores:ticket_scores[ticket.id] = {"obj": ticket, "score": rrf_score, "types": {score_attr}}1 unmodified lineticket_scores[ticket.id]["score"] += rrf_scoreticket_scores[ticket.id]["types"].add(score_attr)apply_fusion(hits, 0.5, "sim_score")apply_fusion(kw_hits, 0.3, "kw_score")apply_fusion(v_hits, 0.2, "vis_score")# 5. Final Thresholding & SortingTHRESHOLD = 0.001 # RRF scores are smaller by design (1/60 basis)8 unmodified linesif "kw_score" in data["types"]: match_types.append("keyword")if "vis_score" in data["types"]: match_types.append("visual")# Normalize RRF to 100% (Theoretical max = 1.0/61 = 0.01639344)# We use a gentle boost to make top hits feel "Confident" (>80%)norm_score = min(((score / 0.01639344) * 100), 100.0)result_item = TicketSearchResult(id=t_obj.id,257 unmodified linesticket.resolved_by = current_user.idif not update_data.get("resolution_text"):ticket.resolution_text = "This issue has been resolved. Thanks!"if "priority" in update_data and update_data["priority"] != ticket.priority:# Recalculate SLA22 unmodified lines# Notify if assignee changedif "assigned_to" in update_data and str(old_assignee) != str(update_data["assigned_to"]):background_tasks.add_task(send_triple_notification,None,update_data["assigned_to"],ticket.workspace_id,"Ticket Reassigned",f"Ticket '{ticket.title}' has been reassigned to you by {current_user.id}.")audit = AuditLog(workspace_id=current_user.workspace_id,234 unmodified linestitle="🚨 Manual Escalation Alert",message=f"Ticket '{ticket.title}' has been manually escalated by {current_user.full_name}. Priority: P0.")logger.info(f"Ticket {ticket.id} manually escalated by {current_user.id}")263 unmodified lines264265266267268269270271272273274275276277278136 unmodified lines4154164174184194204214224234244254261 unmodified line4284294304314324334344354368 unmodified lines445446447448449450451452453257 unmodified lines71171271371471571671771871972072172272372472572622 unmodified lines749750751752753754755756757758759760761762763764765766767768769770771234 unmodified lines100610071008100910101011101210131014101510161017101810191020263 unmodified lines{"event": "ticket_created", "ticket_id": str(new_ticket.id), "title": new_ticket.title})# 5. Notify Creator: Ticket Successfully Loggedawait arq_pool.enqueue_job("send_triple_notification",str(new_ticket.created_by),str(new_ticket.workspace_id),"🎟️ Ticket Created",f"We've received your request: '{new_ticket.title}'. Our team has been notified.")logger.info(f"Ticket created: {new_ticket.id} by user {current_user.id} in workspace {current_user.workspace_id}")return await sanitize_ticket_response(new_ticket, current_user, db)136 unmodified linesfor rank, row in enumerate(list_hits):ticket = row[0]score = float(getattr(row, score_attr) or 0.0)# Reciprocal Rank Fusion (RRF) with sharper k=10 for better top-k discriminationrrf_score = weight * (1.0 / (10 + rank + 1))# Boost exact title matches (intuitive relevance)if q.lower() in ticket.title.lower():rrf_score *= 2.0if ticket.id not in ticket_scores:ticket_scores[ticket.id] = {"obj": ticket, "score": rrf_score, "types": {score_attr}}1 unmodified lineticket_scores[ticket.id]["score"] += rrf_scoreticket_scores[ticket.id]["types"].add(score_attr)apply_fusion(hits, 0.4, "sim_score") # Semantic (balanced with keyword)apply_fusion(kw_hits, 0.4, "kw_score") # Keyword (elevated)apply_fusion(v_hits, 0.2, "vis_score") # Visual# 5. Final Thresholding & SortingTHRESHOLD = 0.001 # RRF scores are smaller by design (1/60 basis)8 unmodified linesif "kw_score" in data["types"]: match_types.append("keyword")if "vis_score" in data["types"]: match_types.append("visual")# Normalize RRF to 100% (Theoretical max with boost = 1.0 / 11 * 2 = 0.1818)# We use a base divisor of 0.0909 (rank 1 match across all branches)norm_score = min(((score / 0.0909) * 100), 100.0)result_item = TicketSearchResult(id=t_obj.id,257 unmodified linesticket.resolved_by = current_user.idif not update_data.get("resolution_text"):ticket.resolution_text = "This issue has been resolved. Thanks!"# Notify Creator of Resolutionbackground_tasks.add_task(send_triple_notification,None,ticket.created_by,ticket.workspace_id,"✅ Ticket Resolved",f"Great news! Your ticket '{ticket.title}' has been marked as {new_status}.")if "priority" in update_data and update_data["priority"] != ticket.priority:# Recalculate SLA22 unmodified lines# Notify if assignee changedif "assigned_to" in update_data and str(old_assignee) != str(update_data["assigned_to"]):# A) Notify Staff (Assignee)await arq_pool.enqueue_job("send_triple_notification",str(update_data["assigned_to"]),str(ticket.workspace_id),"Ticket Reassigned",f"Ticket '{ticket.title}' has been reassigned to you by {current_user.full_name or 'Admin'}.")# B) Notify Customer (Creator) if not self-assigning by customerif ticket.created_by != update_data["assigned_to"]:await arq_pool.enqueue_job("send_triple_notification",str(ticket.created_by),str(ticket.workspace_id),"👷 Expert Assigned",f"An expert has been assigned to your ticket '{ticket.title}' and is reviewing it now.")audit = AuditLog(workspace_id=current_user.workspace_id,234 unmodified linestitle="🚨 Manual Escalation Alert",message=f"Ticket '{ticket.title}' has been manually escalated by {current_user.full_name}. Priority: P0.")# Notify Creator: We're on it!await arq_pool.enqueue_job("send_triple_notification",str(ticket.created_by),str(ticket.workspace_id),"⚡ Priority Boosted",f"Your ticket '{ticket.title}' has been prioritized for immediate leadership review.")logger.info(f"Ticket {ticket.id} manually escalated by {current_user.id}")
1234540 unmodified lines4647484950515218 unmodified lines71727374757677787980818283848586878854 unmodified lines143144145146147148import React, { useState, useEffect, useRef } from 'react';import { api } from '@nexus/shared';import { StatusBadge } from './Badges';const COLORS = {40 unmodified linesconst token = localStorage.getItem('token');const user = JSON.parse(localStorage.getItem('user') || '{}');if (token && user.workspace_id) {const ws = new WebSocket(`ws://localhost:8000/ws/${user.workspace_id}?token=${token}`);ws.onmessage = (event) => {const data = JSON.parse(event.data);if (data.type === 'notification' || data.event === 'ticket_updated') {18 unmodified linesreturn () => document.removeEventListener("mousedown", handleClickOutside);}, []);useEffect(() => {const delayDebounceFn = setTimeout(() => {if (searchQuery.trim().length > 2) {handleSearch();} else {setSearchResults([]);setShowSearchDropdown(false);}}, 400);return () => clearTimeout(delayDebounceFn);}, [searchQuery]);const handleSearch = async () => {setIsSearching(true);54 unmodified linesplaceholder="Search tickets..."value={searchQuery}onChange={(e) => setSearchQuery(e.target.value)}onFocus={() => searchQuery.length > 0 && setShowSearchDropdown(true)}style={{padding: "7px 12px 7px 34px",1234540 unmodified lines4647484950515218 unmodified lines71727374757677787980818254 unmodified lines137138139140141142143import React, { useState, useEffect, useRef } from 'react';import { api, getWsUrl } from '@nexus/shared';import { StatusBadge } from './Badges';const COLORS = {40 unmodified linesconst token = localStorage.getItem('token');const user = JSON.parse(localStorage.getItem('user') || '{}');if (token && user.workspace_id) {const ws = new WebSocket(getWsUrl(`ws/${user.workspace_id}?token=${token}`));ws.onmessage = (event) => {const data = JSON.parse(event.data);if (data.type === 'notification' || data.event === 'ticket_updated') {18 unmodified linesreturn () => document.removeEventListener("mousedown", handleClickOutside);}, []);// Trigger search on Enter keyconst handleKeyDown = (e: React.KeyboardEvent) => {if (e.key === "Enter" && searchQuery.trim().length > 0) {handleSearch();}};const handleSearch = async () => {setIsSearching(true);54 unmodified linesplaceholder="Search tickets..."value={searchQuery}onChange={(e) => setSearchQuery(e.target.value)}onKeyDown={handleKeyDown}onFocus={() => searchQuery.length > 0 && setShowSearchDropdown(true)}style={{padding: "7px 12px 7px 34px",
298 unmodified lines299300301302303304298 unmodified linesfont-style: italic;}/* Logout Confirmation */.logoutWrapper {position: relative;298 unmodified lines299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346298 unmodified linesfont-style: italic;}.notifList {display: flex;flex-direction: column;gap: 8px;max-height: 400px;overflow-y: auto;padding-top: 10px;}.notifItem {padding: 12px;border-radius: 12px;background: var(--bg2);border-left: 3px solid transparent;transition: all 0.2s;}.notifItem[data-read="false"] {background: rgba(59, 130, 246, 0.05);border-left-color: #3b82f6;}.notifTitle {font-size: 13px;font-weight: 700;color: var(--text1);margin-bottom: 2px;}.notifMsg {font-size: 12px;color: var(--text2);line-height: 1.4;margin-bottom: 4px;}.notifTime {font-size: 10px;color: var(--text3);font-weight: 600;}/* Logout Confirmation */.logoutWrapper {position: relative;
1234510 unmodified lines1617181920212284 unmodified lines107108109110111112113114115116117118119import React, { useState, useEffect } from 'react';import { useAuth, api } from '@nexus/shared';import styles from './TopBar.module.css';interface TopBarProps {10 unmodified linesconst [showLogoutConfirm, setShowLogoutConfirm] = useState(false);const [showNotifications, setShowNotifications] = useState(false);const searchRef = React.useRef<HTMLFormElement>(null);const { logout } = useAuth();useEffect(() => {const handleClickOutside = (event: MouseEvent) => {84 unmodified lines</div><div className={styles.notificationWrapper}><button className={styles.iconButton} onClick={() => setShowNotifications(!showNotifications)}>🔔</button><span className={styles.notificationBadge} />{showNotifications && (<div className={styles.notifDropdown}><div className={styles.notifHeader}>Notifications</div><div className={styles.notifEmpty}>No new system alerts</div></div>)}</div>1234510 unmodified lines16171819202122232425262728293031323334353637383940414243444546474849505152535455565758596084 unmodified lines145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179import React, { useState, useEffect } from 'react';import { useAuth, api, getWsUrl } from '@nexus/shared';import styles from './TopBar.module.css';interface TopBarProps {10 unmodified linesconst [showLogoutConfirm, setShowLogoutConfirm] = useState(false);const [showNotifications, setShowNotifications] = useState(false);const searchRef = React.useRef<HTMLFormElement>(null);const { logout, user } = useAuth();const [notifications, setNotifications] = useState<any[]>([]);const [hasUnread, setHasUnread] = useState(false);const fetchNotifications = async () => {try {const res = await api.get('notifications/');setNotifications(res.data);setHasUnread(res.data.some((n: any) => !n.is_read));} catch (err) {console.error("Failed to fetch notifications:", err);}};const markAllAsRead = async () => {try {await api.patch('notifications/mark-read/');setHasUnread(false);fetchNotifications();} catch (err) {console.error("Failed to mark notifications read:", err);}};useEffect(() => {fetchNotifications();const token = localStorage.getItem('token');if (token && user?.workspace_id) {const ws = new WebSocket(getWsUrl(`ws/${user.workspace_id}?token=${token}`));ws.onmessage = (event) => {const data = JSON.parse(event.data);if (data.type === 'notification' || data.event === 'ticket_updated') {setHasUnread(true);fetchNotifications();}};return () => ws.close();}}, [user?.workspace_id]);useEffect(() => {const handleClickOutside = (event: MouseEvent) => {84 unmodified lines</div><div className={styles.notificationWrapper}><button className={styles.iconButton} onClick={() => {setShowNotifications(!showNotifications);if (!showNotifications) markAllAsRead();}}>🔔</button>{hasUnread && <span className={styles.notificationBadge} />}{showNotifications && (<div className={styles.notifDropdown}><div className={styles.notifHeader}>Notifications{notifications.length > 0 && (<span style={{ fontSize: '10px', marginLeft: '8px', opacity: 0.6 }}>{notifications.length} total</span>)}</div><div className={styles.notifList}>{notifications.length === 0 ? (<div className={styles.notifEmpty}>No new system alerts</div>) : (notifications.map(n => (<div key={n.id} className={styles.notifItem} data-read={n.is_read}><div className={styles.notifTitle}>{n.title}</div><div className={styles.notifMsg}>{n.message}</div><div className={styles.notifTime}>{new Date(n.created_at).toLocaleString()}</div></div>)))}</div></div>)}</div>
13 unmodified lines14151617181913 unmodified linesexport type { EscalationRule } from './hooks/useDashboard';export * from './hooks/useUsers';export * from './hooks/useWorkspaces';export { api, setPortalType } from './utils/api';import apiDefault from './utils/api';export default apiDefault;13 unmodified lines14151617181913 unmodified linesexport type { EscalationRule } from './hooks/useDashboard';export * from './hooks/useUsers';export * from './hooks/useWorkspaces';export { api, setPortalType, getWsUrl } from './utils/api';import apiDefault from './utils/api';export default apiDefault;
24 unmodified lines25262728293024 unmodified linesbaseURL: BASE_URL,});let portalType: 'customer' | 'internal' | null = null;export const setPortalType = (type: 'customer' | 'internal') => {24 unmodified lines252627282930313233343536373839404142434445464724 unmodified linesbaseURL: BASE_URL,});/*** Generates a WebSocket URL based on the current environment and API settings.* Handles HTTP/S protocol switching and domain resolution for production tunnels.*/export const getWsUrl = (path: string) => {// Use the API's base URL as the source of truth for the domainconst apiBase = new URL(BASE_URL);const protocol = apiBase.protocol === 'https:' ? 'wss:' : 'ws:';// WebSockets are served from the root of the API server (no /api/v1 prefix)const host = apiBase.host;// Clean forward slash concatenationconst cleanPath = path.startsWith('/') ? path : `/${path}`;return `${protocol}//${host}${cleanPath}`;};let portalType: 'customer' | 'internal' | null = null;export const setPortalType = (type: 'customer' | 'internal') => {
18 unmodified lines1920212223242545 unmodified lines7172737475767718 unmodified linesvectorize_nexus_interaction,generate_global_insight,crystallize_memory,nexus_pulse_check)from agents.workflow import run_ai_workflow45 unmodified linesvectorize_nexus_interaction,generate_global_insight,crystallize_memory,nexus_pulse_check]# Concurrency / Performance18 unmodified lines192021222324252645 unmodified lines727374757677787918 unmodified linesvectorize_nexus_interaction,generate_global_insight,crystallize_memory,nexus_pulse_check,send_triple_notification)from agents.workflow import run_ai_workflow45 unmodified linesvectorize_nexus_interaction,generate_global_insight,crystallize_memory,nexus_pulse_check,send_triple_notification]# Concurrency / Performance
api/v1/messages.py+22-2
api/v1/tickets.py+55-14
frontend/apps/customer/src/components/TopBar.tsx+9-14
frontend/apps/internal/src/components/TopBar.module.css+42
frontend/apps/internal/src/components/TopBar.tsx+66-6
frontend/packages/shared/src/index.ts+1-1
frontend/packages/shared/src/utils/api.ts+17
nexus_worker.py+4-2