diff --git a/backend/app/services/copilot_service.py b/backend/app/services/copilot_service.py index 4fc77a5c..175735ee 100644 --- a/backend/app/services/copilot_service.py +++ b/backend/app/services/copilot_service.py @@ -180,6 +180,40 @@ async def send_message( system_prompt += _build_flow_context(tree, conversation.current_node_id) system_prompt += build_rag_context(rag_results) + # Inject PSA ticket context if session has a linked ticket + if conversation.session_id: + try: + from app.models.session import Session as SessionModel + session_result = await db.execute( + select(SessionModel).where(SessionModel.id == conversation.session_id) + ) + session = session_result.scalar_one_or_none() + if session and session.psa_ticket_id: + try: + from app.services.psa.registry import get_provider_for_account + from app.services.psa.ticket_context import format_ticket_context_for_prompt + + provider = await get_provider_for_account(conversation.account_id, db) + connection_id = str(session.psa_connection_id) if session.psa_connection_id else None + ticket_ctx = await provider.get_ticket_context( + ticket_id=int(session.psa_ticket_id), + connection_id=connection_id, + ) + system_prompt += "\n\n" + format_ticket_context_for_prompt(ticket_ctx) + except Exception as psa_err: + logger.warning( + "Failed to fetch PSA ticket context for copilot (session=%s, ticket=%s): %s", + conversation.session_id, + session.psa_ticket_id, + psa_err, + ) + except Exception as session_err: + logger.warning( + "Failed to look up session for copilot PSA context (session_id=%s): %s", + conversation.session_id, + session_err, + ) + # Build messages for AI ai_messages = [] for msg in conversation.messages: