Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit ·
e9a2d53
1
Parent(s): b7980f7
backend stabilization
Browse files- agents/nexus_checkpoint.py +21 -1
- agents/nexus_customer.py +2 -2
- agents/nexus_master.py +3 -2
- agents/tools/nexus_tools.py +12 -2
- alembic/versions/1536118577ca_add_nexus_checkpoint_writes.py +40 -0
- api/v1/dashboard.py +10 -7
- api/v1/tickets.py +6 -2
- core/observability.py +12 -3
- core/tasks.py +2 -2
- frontend/apps/customer/src/App.tsx +0 -1
- frontend/apps/customer/src/components/Dashboard.tsx +3 -2
- frontend/apps/customer/src/components/ThreadView.tsx +1 -1
- frontend/apps/customer/src/components/TicketList.tsx +2 -3
- frontend/packages/shared/src/contexts/AuthContext.tsx +13 -6
- models/__init__.py +3 -1
- models/nexus_checkpoint.py +15 -1
- schemas/ticket.py +2 -0
- tmp_get_token.py +30 -0
agents/nexus_checkpoint.py
CHANGED
|
@@ -11,7 +11,7 @@ from langgraph.checkpoint.base import (
|
|
| 11 |
from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
|
| 12 |
from sqlalchemy import select, update, insert
|
| 13 |
from core.database import async_session_factory
|
| 14 |
-
from models.nexus_checkpoint import NexusCheckpoint
|
| 15 |
|
| 16 |
class SQLAlchemySaver(BaseCheckpointSaver):
|
| 17 |
"""
|
|
@@ -83,6 +83,26 @@ class SQLAlchemySaver(BaseCheckpointSaver):
|
|
| 83 |
await session.commit()
|
| 84 |
|
| 85 |
return {"configurable": {"thread_id": thread_id, "checkpoint_id": checkpoint_id}}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
# Sync methods are required by the interface but we'll focus on async
|
| 88 |
def get_tuple(self, config: Dict[str, Any]) -> Optional[CheckpointTuple]:
|
|
|
|
| 11 |
from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
|
| 12 |
from sqlalchemy import select, update, insert
|
| 13 |
from core.database import async_session_factory
|
| 14 |
+
from models.nexus_checkpoint import NexusCheckpoint, NexusCheckpointWrite
|
| 15 |
|
| 16 |
class SQLAlchemySaver(BaseCheckpointSaver):
|
| 17 |
"""
|
|
|
|
| 83 |
await session.commit()
|
| 84 |
|
| 85 |
return {"configurable": {"thread_id": thread_id, "checkpoint_id": checkpoint_id}}
|
| 86 |
+
|
| 87 |
+
async def aput_writes(self, config: Dict[str, Any], writes: List[tuple[str, Any]], task_id: str) -> None:
|
| 88 |
+
"""
|
| 89 |
+
Persists intermediate task writes to support modern LangGraph async cycles.
|
| 90 |
+
"""
|
| 91 |
+
thread_id = config["configurable"]["thread_id"]
|
| 92 |
+
checkpoint_id = config["configurable"]["checkpoint_id"]
|
| 93 |
+
|
| 94 |
+
async with async_session_factory() as session:
|
| 95 |
+
for idx, (channel, value) in enumerate(writes):
|
| 96 |
+
stmt = insert(NexusCheckpointWrite).values(
|
| 97 |
+
thread_id=str(thread_id),
|
| 98 |
+
checkpoint_id=str(checkpoint_id),
|
| 99 |
+
task_id=str(task_id),
|
| 100 |
+
idx=idx,
|
| 101 |
+
channel=channel,
|
| 102 |
+
value=self.serde.dumps(value)
|
| 103 |
+
)
|
| 104 |
+
await session.execute(stmt)
|
| 105 |
+
await session.commit()
|
| 106 |
|
| 107 |
# Sync methods are required by the interface but we'll focus on async
|
| 108 |
def get_tuple(self, config: Dict[str, Any]) -> Optional[CheckpointTuple]:
|
agents/nexus_customer.py
CHANGED
|
@@ -111,14 +111,14 @@ async def nexus_customer_executor(state: NexusState) -> Dict[str, Any]:
|
|
| 111 |
priority=params.get("priority", "MEDIUM")
|
| 112 |
)))
|
| 113 |
|
| 114 |
-
# NEW: Conversational Ticket Discussion/Updates
|
| 115 |
elif tool_name == "UPDATE_TICKET":
|
| 116 |
task_calls.append((call_id, update_ticket_tool(
|
| 117 |
ticket_id=params.get("ticket_id"),
|
| 118 |
comment=params.get("comment"),
|
| 119 |
workspace_id=ws_id,
|
| 120 |
user_id=state.get("user_id"),
|
| 121 |
-
status=params.get("status")
|
|
|
|
| 122 |
)))
|
| 123 |
|
| 124 |
else:
|
|
|
|
| 111 |
priority=params.get("priority", "MEDIUM")
|
| 112 |
)))
|
| 113 |
|
|
|
|
| 114 |
elif tool_name == "UPDATE_TICKET":
|
| 115 |
task_calls.append((call_id, update_ticket_tool(
|
| 116 |
ticket_id=params.get("ticket_id"),
|
| 117 |
comment=params.get("comment"),
|
| 118 |
workspace_id=ws_id,
|
| 119 |
user_id=state.get("user_id"),
|
| 120 |
+
status=params.get("status"),
|
| 121 |
+
role=role
|
| 122 |
)))
|
| 123 |
|
| 124 |
else:
|
agents/nexus_master.py
CHANGED
|
@@ -218,7 +218,7 @@ async def nexus_tool_executor(state: NexusState) -> Dict[str, Any]:
|
|
| 218 |
if action["tool"] == "ASSIGN_TICKET":
|
| 219 |
write_tasks.append(assign_ticket_tool(state.get("ticket_id"), state.get("target_user_id"), ws_id))
|
| 220 |
elif action["tool"] == "UPDATE_STATUS":
|
| 221 |
-
write_tasks.append(update_ticket_status_tool(state.get("ticket_id"), state.get("target_status"), ws_id))
|
| 222 |
elif action["tool"] == "REMEDIATE":
|
| 223 |
rem = action.get("params") or {}
|
| 224 |
write_tasks.append(dynamic_remediation_tool(action["action"], rem, ws_id))
|
|
@@ -257,7 +257,8 @@ async def nexus_tool_executor(state: NexusState) -> Dict[str, Any]:
|
|
| 257 |
comment=params.get("comment"),
|
| 258 |
workspace_id=ws_id,
|
| 259 |
user_id=state.get("user_id"),
|
| 260 |
-
status=params.get("status")
|
|
|
|
| 261 |
)))
|
| 262 |
elif tool_name == "ANALYTICS":
|
| 263 |
task_calls.append((call_id, nexus_analytics_tool(ws_id, role=role)))
|
|
|
|
| 218 |
if action["tool"] == "ASSIGN_TICKET":
|
| 219 |
write_tasks.append(assign_ticket_tool(state.get("ticket_id"), state.get("target_user_id"), ws_id))
|
| 220 |
elif action["tool"] == "UPDATE_STATUS":
|
| 221 |
+
write_tasks.append(update_ticket_status_tool(state.get("ticket_id"), state.get("target_status"), ws_id, role=state.get("user_role")))
|
| 222 |
elif action["tool"] == "REMEDIATE":
|
| 223 |
rem = action.get("params") or {}
|
| 224 |
write_tasks.append(dynamic_remediation_tool(action["action"], rem, ws_id))
|
|
|
|
| 257 |
comment=params.get("comment"),
|
| 258 |
workspace_id=ws_id,
|
| 259 |
user_id=state.get("user_id"),
|
| 260 |
+
status=params.get("status"),
|
| 261 |
+
role=role
|
| 262 |
)))
|
| 263 |
elif tool_name == "ANALYTICS":
|
| 264 |
task_calls.append((call_id, nexus_analytics_tool(ws_id, role=role)))
|
agents/tools/nexus_tools.py
CHANGED
|
@@ -108,7 +108,7 @@ async def create_ticket_tool(title: str, description: str, workspace_id: UUID, u
|
|
| 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 |
|
| 111 |
-
async def update_ticket_tool(ticket_id: str, comment: str, workspace_id: UUID, user_id: UUID, status: Optional[str] = None) -> str:
|
| 112 |
"""
|
| 113 |
Update a ticket by adding a comment or changing its status.
|
| 114 |
"""
|
|
@@ -146,6 +146,11 @@ async def update_ticket_tool(ticket_id: str, comment: str, workspace_id: UUID, u
|
|
| 146 |
elif "OPEN" in s_norm: target_status = TicketStatus.OPEN
|
| 147 |
elif "ACKNOWLEDGED" in s_norm: target_status = TicketStatus.ACKNOWLEDGED
|
| 148 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
if target_status:
|
| 150 |
ticket.status = target_status
|
| 151 |
|
|
@@ -511,7 +516,7 @@ async def assign_ticket_tool(ticket_id: UUID, user_id: UUID, workspace_id: UUID)
|
|
| 511 |
await db.commit()
|
| 512 |
return f"Ticket {ticket_id} successfully assigned to user {user_id}."
|
| 513 |
|
| 514 |
-
async def update_ticket_status_tool(ticket_id: UUID, new_status: str, workspace_id: UUID) -> str:
|
| 515 |
"""
|
| 516 |
Update a ticket's status (e.g. to RESOLVED).
|
| 517 |
"""
|
|
@@ -535,6 +540,11 @@ async def update_ticket_status_tool(ticket_id: UUID, new_status: str, workspace_
|
|
| 535 |
elif "IN_PROGRESS" in s_norm: target_status = TicketStatus.IN_PROGRESS
|
| 536 |
elif "ACKNOWLEDGED" in s_norm: target_status = TicketStatus.ACKNOWLEDGED
|
| 537 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 538 |
if not target_status:
|
| 539 |
raise ValueError(f"Unknown status: {new_status}")
|
| 540 |
|
|
|
|
| 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 |
|
| 111 |
+
async def update_ticket_tool(ticket_id: str, comment: str, workspace_id: UUID, user_id: UUID, status: Optional[str] = None, role: str = "customer_user") -> str:
|
| 112 |
"""
|
| 113 |
Update a ticket by adding a comment or changing its status.
|
| 114 |
"""
|
|
|
|
| 146 |
elif "OPEN" in s_norm: target_status = TicketStatus.OPEN
|
| 147 |
elif "ACKNOWLEDGED" in s_norm: target_status = TicketStatus.ACKNOWLEDGED
|
| 148 |
|
| 149 |
+
# POLICY ENFORCEMENT: Only staff can RESOLVE or CLOSE
|
| 150 |
+
is_staff = "3sc" in role.lower()
|
| 151 |
+
if (target_status in [TicketStatus.RESOLVED, TicketStatus.CLOSED]) and not is_staff:
|
| 152 |
+
return f"Permission Denied: Only 3SC Support Staff can mark a ticket as {target_status.value.upper()}. Your comment has been added, but the status remains {old_status.value.upper()}."
|
| 153 |
+
|
| 154 |
if target_status:
|
| 155 |
ticket.status = target_status
|
| 156 |
|
|
|
|
| 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:
|
| 520 |
"""
|
| 521 |
Update a ticket's status (e.g. to RESOLVED).
|
| 522 |
"""
|
|
|
|
| 540 |
elif "IN_PROGRESS" in s_norm: target_status = TicketStatus.IN_PROGRESS
|
| 541 |
elif "ACKNOWLEDGED" in s_norm: target_status = TicketStatus.ACKNOWLEDGED
|
| 542 |
|
| 543 |
+
# POLICY ENFORCEMENT: Only staff can RESOLVE or CLOSE
|
| 544 |
+
is_staff = "3sc" in role.lower()
|
| 545 |
+
if (target_status in [TicketStatus.RESOLVED, TicketStatus.CLOSED]) and not is_staff:
|
| 546 |
+
return f"Permission Denied: Only 3SC Support Staff can mark a ticket as {target_status.value.upper()}. Transition refused."
|
| 547 |
+
|
| 548 |
if not target_status:
|
| 549 |
raise ValueError(f"Unknown status: {new_status}")
|
| 550 |
|
alembic/versions/1536118577ca_add_nexus_checkpoint_writes.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""add_nexus_checkpoint_writes
|
| 2 |
+
|
| 3 |
+
Revision ID: 1536118577ca
|
| 4 |
+
Revises: a1f8e2c3d4b5
|
| 5 |
+
Create Date: 2026-04-05 17:31:48.954591
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
from typing import Sequence, Union
|
| 9 |
+
|
| 10 |
+
from alembic import op
|
| 11 |
+
import sqlalchemy as sa
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# revision identifiers, used by Alembic.
|
| 15 |
+
revision: str = '1536118577ca'
|
| 16 |
+
down_revision: Union[str, None] = 'a1f8e2c3d4b5'
|
| 17 |
+
branch_labels: Union[str, Sequence[str], None] = None
|
| 18 |
+
depends_on: Union[str, Sequence[str], None] = None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def upgrade() -> None:
|
| 22 |
+
# ### commands auto generated by Alembic - please adjust! ###
|
| 23 |
+
op.create_table('nexus_checkpoint_writes',
|
| 24 |
+
sa.Column('thread_id', sa.String(), nullable=False),
|
| 25 |
+
sa.Column('checkpoint_id', sa.String(), nullable=False),
|
| 26 |
+
sa.Column('task_id', sa.String(), nullable=False),
|
| 27 |
+
sa.Column('idx', sa.Integer(), nullable=False),
|
| 28 |
+
sa.Column('channel', sa.String(), nullable=False),
|
| 29 |
+
sa.Column('value', sa.LargeBinary(), nullable=False),
|
| 30 |
+
sa.PrimaryKeyConstraint('thread_id', 'checkpoint_id', 'task_id', 'idx')
|
| 31 |
+
)
|
| 32 |
+
op.drop_index('ix_users_email_lower', table_name='users')
|
| 33 |
+
# ### end Alembic commands ###
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def downgrade() -> None:
|
| 37 |
+
# ### commands auto generated by Alembic - please adjust! ###
|
| 38 |
+
op.create_index('ix_users_email_lower', 'users', [sa.text('lower(email::text)')], unique=True)
|
| 39 |
+
op.drop_table('nexus_checkpoint_writes')
|
| 40 |
+
# ### end Alembic commands ###
|
api/v1/dashboard.py
CHANGED
|
@@ -66,6 +66,7 @@ async def get_dashboard_stats(
|
|
| 66 |
metrics_stmt = select(
|
| 67 |
func.avg(func.extract('epoch', Ticket.resolved_at - Ticket.created_at) / 3600).label("avg_res"),
|
| 68 |
func.avg(func.cast(Ticket.ai_metadata['rating'].astext, Float)).label("avg_csat"),
|
|
|
|
| 69 |
func.count(Ticket.id).filter(
|
| 70 |
(Ticket.status.notin_([TicketStatus.RESOLVED, TicketStatus.CLOSED])) &
|
| 71 |
(Ticket.sla_deadline < now)
|
|
@@ -82,6 +83,7 @@ async def get_dashboard_stats(
|
|
| 82 |
|
| 83 |
avg_res = m_row.avg_res or 0.0
|
| 84 |
avg_csat = m_row.avg_csat or 0.0
|
|
|
|
| 85 |
breach_count = m_row.breached_count or 0
|
| 86 |
|
| 87 |
# 3. Personalized Open Count
|
|
@@ -119,18 +121,19 @@ async def get_dashboard_stats(
|
|
| 119 |
"total_tickets": total,
|
| 120 |
"by_status": counts,
|
| 121 |
"workspace_id": target_ws,
|
| 122 |
-
"my_open_count": my_open_count
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
}
|
| 124 |
|
| 125 |
if is_staff:
|
| 126 |
# Staff get the full forensic payload
|
| 127 |
response.update({
|
| 128 |
-
"personnel_load": personnel_load
|
| 129 |
-
"performance": {
|
| 130 |
-
"avg_resolution_hours": round(avg_res, 1),
|
| 131 |
-
"csat_score": round(avg_csat, 1),
|
| 132 |
-
"sla_breached_count": breach_count
|
| 133 |
-
}
|
| 134 |
})
|
| 135 |
|
| 136 |
return response
|
|
|
|
| 66 |
metrics_stmt = select(
|
| 67 |
func.avg(func.extract('epoch', Ticket.resolved_at - Ticket.created_at) / 3600).label("avg_res"),
|
| 68 |
func.avg(func.cast(Ticket.ai_metadata['rating'].astext, Float)).label("avg_csat"),
|
| 69 |
+
func.count(Ticket.id).filter(Ticket.ai_metadata['rating'].isnot(None)).label("rated_count"),
|
| 70 |
func.count(Ticket.id).filter(
|
| 71 |
(Ticket.status.notin_([TicketStatus.RESOLVED, TicketStatus.CLOSED])) &
|
| 72 |
(Ticket.sla_deadline < now)
|
|
|
|
| 83 |
|
| 84 |
avg_res = m_row.avg_res or 0.0
|
| 85 |
avg_csat = m_row.avg_csat or 0.0
|
| 86 |
+
rated_count = m_row.rated_count or 0
|
| 87 |
breach_count = m_row.breached_count or 0
|
| 88 |
|
| 89 |
# 3. Personalized Open Count
|
|
|
|
| 121 |
"total_tickets": total,
|
| 122 |
"by_status": counts,
|
| 123 |
"workspace_id": target_ws,
|
| 124 |
+
"my_open_count": my_open_count,
|
| 125 |
+
"performance": {
|
| 126 |
+
"avg_resolution_hours": round(avg_res, 1),
|
| 127 |
+
"csat_score": round(avg_csat, 1),
|
| 128 |
+
"rated_count": rated_count,
|
| 129 |
+
"sla_breached_count": breach_count
|
| 130 |
+
}
|
| 131 |
}
|
| 132 |
|
| 133 |
if is_staff:
|
| 134 |
# Staff get the full forensic payload
|
| 135 |
response.update({
|
| 136 |
+
"personnel_load": personnel_load
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
})
|
| 138 |
|
| 139 |
return response
|
api/v1/tickets.py
CHANGED
|
@@ -111,7 +111,10 @@ async def sanitize_ticket_response(
|
|
| 111 |
dup_res = await db.execute(dup_stmt)
|
| 112 |
setattr(ticket, "duplicate_of_title", dup_res.scalar_one_or_none())
|
| 113 |
|
| 114 |
-
# 7.
|
|
|
|
|
|
|
|
|
|
| 115 |
creator_role = ticket.creator.role if ticket.creator else None
|
| 116 |
is_internal = creator_role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]
|
| 117 |
setattr(ticket, "creator_name", ticket.creator.full_name if ticket.creator else "System")
|
|
@@ -432,7 +435,8 @@ async def search_tickets(
|
|
| 432 |
creator_name=t_obj.creator.full_name if t_obj.creator else "System",
|
| 433 |
assigned_name=t_obj.assignee.full_name if t_obj.assignee else None,
|
| 434 |
is_escalated=t_obj.is_escalated,
|
| 435 |
-
score=round(norm_score, 1) # Display as e.g. 98.5
|
|
|
|
| 436 |
)
|
| 437 |
final_results.append(result_item)
|
| 438 |
|
|
|
|
| 111 |
dup_res = await db.execute(dup_stmt)
|
| 112 |
setattr(ticket, "duplicate_of_title", dup_res.scalar_one_or_none())
|
| 113 |
|
| 114 |
+
# 7. Ownership Identity (Frontend Sync)
|
| 115 |
+
setattr(ticket, "is_mine", ticket.created_by == user.id)
|
| 116 |
+
|
| 117 |
+
# 8. Metadata Sanitization & Internal Flag Injection
|
| 118 |
creator_role = ticket.creator.role if ticket.creator else None
|
| 119 |
is_internal = creator_role in [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]
|
| 120 |
setattr(ticket, "creator_name", ticket.creator.full_name if ticket.creator else "System")
|
|
|
|
| 435 |
creator_name=t_obj.creator.full_name if t_obj.creator else "System",
|
| 436 |
assigned_name=t_obj.assignee.full_name if t_obj.assignee else None,
|
| 437 |
is_escalated=t_obj.is_escalated,
|
| 438 |
+
score=round(norm_score, 1), # Display as e.g. 98.5
|
| 439 |
+
is_mine=t_obj.created_by == current_user.id
|
| 440 |
)
|
| 441 |
final_results.append(result_item)
|
| 442 |
|
core/observability.py
CHANGED
|
@@ -87,9 +87,18 @@ def setup_telemetry(app) -> None:
|
|
| 87 |
from opentelemetry.sdk.trace import TracerProvider
|
| 88 |
from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter
|
| 89 |
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
|
|
|
|
|
|
| 90 |
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
# Use Console Exporting for local development
|
| 95 |
# In production, this would be an OTLP exporter to Jaeger/Datadog/NewRelic
|
|
@@ -99,4 +108,4 @@ def setup_telemetry(app) -> None:
|
|
| 99 |
|
| 100 |
# Auto-instrument FastAPI routes
|
| 101 |
FastAPIInstrumentor.instrument_app(app)
|
| 102 |
-
logger.info("OpenTelemetry
|
|
|
|
| 87 |
from opentelemetry.sdk.trace import TracerProvider
|
| 88 |
from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter
|
| 89 |
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
| 90 |
+
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
|
| 91 |
+
from core.config import get_settings
|
| 92 |
|
| 93 |
+
settings = get_settings()
|
| 94 |
+
|
| 95 |
+
# Define the Resource (Service Name)
|
| 96 |
+
resource = Resource(attributes={
|
| 97 |
+
SERVICE_NAME: settings.APP_NAME
|
| 98 |
+
})
|
| 99 |
+
|
| 100 |
+
# Set global TracerProvider with the Resource
|
| 101 |
+
provider = TracerProvider(resource=resource)
|
| 102 |
|
| 103 |
# Use Console Exporting for local development
|
| 104 |
# In production, this would be an OTLP exporter to Jaeger/Datadog/NewRelic
|
|
|
|
| 108 |
|
| 109 |
# Auto-instrument FastAPI routes
|
| 110 |
FastAPIInstrumentor.instrument_app(app)
|
| 111 |
+
logger.info(f"OpenTelemetry Trace Provider configured for service: {settings.APP_NAME}")
|
core/tasks.py
CHANGED
|
@@ -626,8 +626,8 @@ async def nexus_pulse_check(ctx):
|
|
| 626 |
select(func.count(Ticket.id))
|
| 627 |
.where(
|
| 628 |
Ticket.workspace_id == w_id,
|
| 629 |
-
Ticket.priority ==
|
| 630 |
-
Ticket.status !=
|
| 631 |
Ticket.updated_at >= fifteen_mins_ago
|
| 632 |
)
|
| 633 |
)
|
|
|
|
| 626 |
select(func.count(Ticket.id))
|
| 627 |
.where(
|
| 628 |
Ticket.workspace_id == w_id,
|
| 629 |
+
Ticket.priority == TicketPriority.P0,
|
| 630 |
+
Ticket.status != TicketStatus.CLOSED,
|
| 631 |
Ticket.updated_at >= fifteen_mins_ago
|
| 632 |
)
|
| 633 |
)
|
frontend/apps/customer/src/App.tsx
CHANGED
|
@@ -103,7 +103,6 @@ export default function App() {
|
|
| 103 |
setSelectedTicket={setSelectedTicket}
|
| 104 |
tickets={tickets}
|
| 105 |
loading={ticketsLoading}
|
| 106 |
-
user={user}
|
| 107 |
/>
|
| 108 |
)}
|
| 109 |
{active === "thread" && selectedTicket && (
|
|
|
|
| 103 |
setSelectedTicket={setSelectedTicket}
|
| 104 |
tickets={tickets}
|
| 105 |
loading={ticketsLoading}
|
|
|
|
| 106 |
/>
|
| 107 |
)}
|
| 108 |
{active === "thread" && selectedTicket && (
|
frontend/apps/customer/src/components/Dashboard.tsx
CHANGED
|
@@ -31,9 +31,10 @@ export const Dashboard: React.FC<DashboardProps> = ({ setActive, setSelectedTick
|
|
| 31 |
const [kbLoading, setKbLoading] = useState(false);
|
| 32 |
const [stats, setStats] = useState<any>(null);
|
| 33 |
|
| 34 |
-
const
|
|
|
|
| 35 |
const activeTickets = userTickets
|
| 36 |
-
.filter(t => t.status.toLowerCase() === "open" || t.status.toLowerCase() === "in_progress")
|
| 37 |
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
|
| 38 |
|
| 39 |
useEffect(() => {
|
|
|
|
| 31 |
const [kbLoading, setKbLoading] = useState(false);
|
| 32 |
const [stats, setStats] = useState<any>(null);
|
| 33 |
|
| 34 |
+
const isAdmin = user?.role?.toLowerCase().includes('admin');
|
| 35 |
+
const userTickets = user ? (isAdmin ? tickets : tickets.filter(t => t.is_mine)) : [];
|
| 36 |
const activeTickets = userTickets
|
| 37 |
+
.filter(t => t.status.toLowerCase() === "open" || t.status.toLowerCase() === "in_progress" || t.status.toLowerCase() === "acknowledged")
|
| 38 |
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
|
| 39 |
|
| 40 |
useEffect(() => {
|
frontend/apps/customer/src/components/ThreadView.tsx
CHANGED
|
@@ -198,7 +198,7 @@ export const ThreadView: React.FC<ThreadViewProps> = ({ ticket: initialTicket, o
|
|
| 198 |
headers: { 'Content-Type': 'multipart/form-data' }
|
| 199 |
});
|
| 200 |
|
| 201 |
-
const downloadUrl = `/api/v1/
|
| 202 |
const markdownImage = `\n\n`;
|
| 203 |
|
| 204 |
if (isMainDesc) setDescDraft((curr: string) => curr.replace(placeholder, markdownImage));
|
|
|
|
| 198 |
headers: { 'Content-Type': 'multipart/form-data' }
|
| 199 |
});
|
| 200 |
|
| 201 |
+
const downloadUrl = `/api/v1/tickets/attachments/${resp.data.id}/download`;
|
| 202 |
const markdownImage = `\n\n`;
|
| 203 |
|
| 204 |
if (isMainDesc) setDescDraft((curr: string) => curr.replace(placeholder, markdownImage));
|
frontend/apps/customer/src/components/TicketList.tsx
CHANGED
|
@@ -20,13 +20,12 @@ interface TicketListProps {
|
|
| 20 |
setSelectedTicket: (ticket: any) => void;
|
| 21 |
tickets: any[];
|
| 22 |
loading: boolean;
|
| 23 |
-
user: any;
|
| 24 |
}
|
| 25 |
|
| 26 |
const STATUSES = ["OPEN", "ACKNOWLEDGED", "IN_PROGRESS", "RESOLVED", "CLOSED"];
|
| 27 |
const PRIORITIES = ["P0", "P1", "P2", "P3"];
|
| 28 |
|
| 29 |
-
export const TicketList: React.FC<TicketListProps> = ({ setActive, setSelectedTicket, tickets, loading
|
| 30 |
const [viewMode, setViewMode] = useState<"ALL" | "MINE">("ALL");
|
| 31 |
const [searchQuery, setSearchQuery] = useState("");
|
| 32 |
const [creatorFilter, setCreatorFilter] = useState("");
|
|
@@ -51,7 +50,7 @@ export const TicketList: React.FC<TicketListProps> = ({ setActive, setSelectedTi
|
|
| 51 |
|
| 52 |
const filtered = tickets.filter(t => {
|
| 53 |
// 1. View Mode (All vs Mine)
|
| 54 |
-
if (viewMode === "MINE" && t.
|
| 55 |
|
| 56 |
// 2. Status
|
| 57 |
if (statusFilter !== "ALL" && t.status.toUpperCase() !== statusFilter) return false;
|
|
|
|
| 20 |
setSelectedTicket: (ticket: any) => void;
|
| 21 |
tickets: any[];
|
| 22 |
loading: boolean;
|
|
|
|
| 23 |
}
|
| 24 |
|
| 25 |
const STATUSES = ["OPEN", "ACKNOWLEDGED", "IN_PROGRESS", "RESOLVED", "CLOSED"];
|
| 26 |
const PRIORITIES = ["P0", "P1", "P2", "P3"];
|
| 27 |
|
| 28 |
+
export const TicketList: React.FC<TicketListProps> = ({ setActive, setSelectedTicket, tickets, loading }) => {
|
| 29 |
const [viewMode, setViewMode] = useState<"ALL" | "MINE">("ALL");
|
| 30 |
const [searchQuery, setSearchQuery] = useState("");
|
| 31 |
const [creatorFilter, setCreatorFilter] = useState("");
|
|
|
|
| 50 |
|
| 51 |
const filtered = tickets.filter(t => {
|
| 52 |
// 1. View Mode (All vs Mine)
|
| 53 |
+
if (viewMode === "MINE" && !t.is_mine) return false;
|
| 54 |
|
| 55 |
// 2. Status
|
| 56 |
if (statusFilter !== "ALL" && t.status.toUpperCase() !== statusFilter) return false;
|
frontend/packages/shared/src/contexts/AuthContext.tsx
CHANGED
|
@@ -27,11 +27,15 @@ interface AuthContextType extends AuthState {
|
|
| 27 |
export const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
| 28 |
|
| 29 |
export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
|
| 30 |
-
const [auth, setAuth] = useState<AuthState>({
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
});
|
| 36 |
|
| 37 |
const hasRole = useCallback((roles: string | string[]) => {
|
|
@@ -43,7 +47,9 @@ export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
|
|
| 43 |
const fetchProfile = useCallback(async () => {
|
| 44 |
try {
|
| 45 |
const resp = await api.get('auth/me');
|
| 46 |
-
|
|
|
|
|
|
|
| 47 |
} catch (err: any) {
|
| 48 |
if (err.response?.status === 401) {
|
| 49 |
localStorage.removeItem('token');
|
|
@@ -103,6 +109,7 @@ export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
|
|
| 103 |
} finally {
|
| 104 |
localStorage.removeItem('token');
|
| 105 |
localStorage.removeItem('refresh_token');
|
|
|
|
| 106 |
setAuth({ user: null, token: null, loading: false, error: null });
|
| 107 |
window.location.href = '/';
|
| 108 |
}
|
|
|
|
| 27 |
export const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
| 28 |
|
| 29 |
export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
|
| 30 |
+
const [auth, setAuth] = useState<AuthState>(() => {
|
| 31 |
+
const savedToken = localStorage.getItem('token');
|
| 32 |
+
const savedUser = localStorage.getItem('user');
|
| 33 |
+
return {
|
| 34 |
+
user: savedUser ? JSON.parse(savedUser) : null,
|
| 35 |
+
token: savedToken,
|
| 36 |
+
loading: false,
|
| 37 |
+
error: null,
|
| 38 |
+
};
|
| 39 |
});
|
| 40 |
|
| 41 |
const hasRole = useCallback((roles: string | string[]) => {
|
|
|
|
| 47 |
const fetchProfile = useCallback(async () => {
|
| 48 |
try {
|
| 49 |
const resp = await api.get('auth/me');
|
| 50 |
+
const userData = resp.data;
|
| 51 |
+
localStorage.setItem('user', JSON.stringify(userData));
|
| 52 |
+
setAuth(prev => ({ ...prev, user: userData, loading: false }));
|
| 53 |
} catch (err: any) {
|
| 54 |
if (err.response?.status === 401) {
|
| 55 |
localStorage.removeItem('token');
|
|
|
|
| 109 |
} finally {
|
| 110 |
localStorage.removeItem('token');
|
| 111 |
localStorage.removeItem('refresh_token');
|
| 112 |
+
localStorage.removeItem('user');
|
| 113 |
setAuth({ user: null, token: null, loading: false, error: null });
|
| 114 |
window.location.href = '/';
|
| 115 |
}
|
models/__init__.py
CHANGED
|
@@ -23,6 +23,7 @@ from models.knowledge_insight import KnowledgeInsight, InsightType, InsightStatu
|
|
| 23 |
from models.knowledge_insight_ticket import KnowledgeInsightTicket
|
| 24 |
from models.meta_infra_health import MetaInfraHealth
|
| 25 |
from models.nexus_semantic_cache import NexusSemanticCache
|
|
|
|
| 26 |
|
| 27 |
__all__ = [
|
| 28 |
"Workspace",
|
|
@@ -42,5 +43,6 @@ __all__ = [
|
|
| 42 |
"RemediationHook", "RemediationActionType",
|
| 43 |
"MetaInfraHealth",
|
| 44 |
"KnowledgeInsight", "InsightType", "InsightStatus", "KnowledgeInsightTicket",
|
| 45 |
-
"NexusSemanticCache"
|
|
|
|
| 46 |
]
|
|
|
|
| 23 |
from models.knowledge_insight_ticket import KnowledgeInsightTicket
|
| 24 |
from models.meta_infra_health import MetaInfraHealth
|
| 25 |
from models.nexus_semantic_cache import NexusSemanticCache
|
| 26 |
+
from models.nexus_checkpoint import NexusCheckpoint, NexusCheckpointWrite
|
| 27 |
|
| 28 |
__all__ = [
|
| 29 |
"Workspace",
|
|
|
|
| 43 |
"RemediationHook", "RemediationActionType",
|
| 44 |
"MetaInfraHealth",
|
| 45 |
"KnowledgeInsight", "InsightType", "InsightStatus", "KnowledgeInsightTicket",
|
| 46 |
+
"NexusSemanticCache",
|
| 47 |
+
"NexusCheckpoint", "NexusCheckpointWrite"
|
| 48 |
]
|
models/nexus_checkpoint.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
from sqlalchemy import Column, String, LargeBinary
|
| 2 |
from sqlalchemy.dialects.postgresql import UUID
|
| 3 |
from core.database import Base
|
| 4 |
|
|
@@ -17,3 +17,17 @@ class NexusCheckpoint(Base):
|
|
| 17 |
# Serialized state
|
| 18 |
checkpoint_data = Column(LargeBinary, nullable=False)
|
| 19 |
metadata_data = Column(LargeBinary, nullable=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlalchemy import Column, String, LargeBinary, Integer
|
| 2 |
from sqlalchemy.dialects.postgresql import UUID
|
| 3 |
from core.database import Base
|
| 4 |
|
|
|
|
| 17 |
# Serialized state
|
| 18 |
checkpoint_data = Column(LargeBinary, nullable=False)
|
| 19 |
metadata_data = Column(LargeBinary, nullable=True)
|
| 20 |
+
|
| 21 |
+
class NexusCheckpointWrite(Base):
|
| 22 |
+
"""
|
| 23 |
+
Stores intermediate task writes for LangGraph async execution.
|
| 24 |
+
"""
|
| 25 |
+
__tablename__ = "nexus_checkpoint_writes"
|
| 26 |
+
|
| 27 |
+
thread_id = Column(String, primary_key=True)
|
| 28 |
+
checkpoint_id = Column(String, primary_key=True)
|
| 29 |
+
task_id = Column(String, primary_key=True)
|
| 30 |
+
idx = Column(Integer, primary_key=True)
|
| 31 |
+
|
| 32 |
+
channel = Column(String, nullable=False)
|
| 33 |
+
value = Column(LargeBinary, nullable=False)
|
schemas/ticket.py
CHANGED
|
@@ -51,6 +51,7 @@ class TicketResponse(TicketBase):
|
|
| 51 |
rating: Optional[int] = None
|
| 52 |
created_at: datetime
|
| 53 |
updated_at: datetime
|
|
|
|
| 54 |
|
| 55 |
model_config = ConfigDict(from_attributes=True)
|
| 56 |
|
|
@@ -80,6 +81,7 @@ class TicketSearchResult(BaseModel):
|
|
| 80 |
assigned_name: Optional[str] = None
|
| 81 |
is_escalated: Optional[datetime] = None
|
| 82 |
score: float
|
|
|
|
| 83 |
|
| 84 |
class TicketSearchResponse(BaseModel):
|
| 85 |
results: List[TicketSearchResult]
|
|
|
|
| 51 |
rating: Optional[int] = None
|
| 52 |
created_at: datetime
|
| 53 |
updated_at: datetime
|
| 54 |
+
is_mine: bool = False
|
| 55 |
|
| 56 |
model_config = ConfigDict(from_attributes=True)
|
| 57 |
|
|
|
|
| 81 |
assigned_name: Optional[str] = None
|
| 82 |
is_escalated: Optional[datetime] = None
|
| 83 |
score: float
|
| 84 |
+
is_mine: bool = False
|
| 85 |
|
| 86 |
class TicketSearchResponse(BaseModel):
|
| 87 |
results: List[TicketSearchResult]
|
tmp_get_token.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import asyncio
|
| 3 |
+
from core.security import create_access_token
|
| 4 |
+
from core.database import async_session_factory
|
| 5 |
+
from sqlalchemy import select
|
| 6 |
+
from models.user import User, UserRole
|
| 7 |
+
from models.user_workspace import UserWorkspace
|
| 8 |
+
|
| 9 |
+
async def get_token():
|
| 10 |
+
async with async_session_factory() as db:
|
| 11 |
+
# Fetch ANSELL ADMIN
|
| 12 |
+
u_res = await db.execute(select(User).where(User.email == "admin@ansell.com"))
|
| 13 |
+
user = u_res.scalar_one_or_none()
|
| 14 |
+
if not user:
|
| 15 |
+
print("User not found")
|
| 16 |
+
return
|
| 17 |
+
|
| 18 |
+
# Fetch association
|
| 19 |
+
assoc_res = await db.execute(select(UserWorkspace).where(UserWorkspace.user_id == user.id))
|
| 20 |
+
assoc = assoc_res.scalar_one_or_none()
|
| 21 |
+
|
| 22 |
+
token = create_access_token(
|
| 23 |
+
subject=str(user.id),
|
| 24 |
+
workspace_id=str(assoc.workspace_id),
|
| 25 |
+
role=assoc.role
|
| 26 |
+
)
|
| 27 |
+
print(f"TOKEN: {token}")
|
| 28 |
+
|
| 29 |
+
if __name__ == "__main__":
|
| 30 |
+
asyncio.run(get_token())
|