Files
resolutionflow/backend/tests/test_handoff_manager.py
Michael Chihlas 07d0db9579 feat(handoff): email engineer-or-admin teammates on escalation
First half of the Escalation Mode notification dual-path. WebSocket/SSE
push is the second half (next commit) — email handles offline seniors,
push handles online ones for the magic-moment demo.

HandoffManager.dispatch_escalation_notifications:
- Pulls active engineer/admin/owner-role users in the same account_id
  (excludes the escalator + viewers + soft-deleted)
- Sends via existing EmailService.send_notification_email, concurrent
  via asyncio.gather; per-message failures don't block the rest
- Wrapped in try/except: any exception is logged + swallowed. Handoff
  creation is authoritative; notification is advisory. This is the
  graceful-degradation regression both eng + codex reviews flagged as
  critical (handoff must succeed even if SMTP is down).

Endpoint wiring (POST /ai-sessions/{id}/handoff):
- Dispatch fires AFTER db.commit() — never email about a rolled-back
  handoff. Trust-erosion bug if we got that wrong.
- Only fires for intent=escalate. Park is private to the escalator.

Tests (4 new):
- emails-engineer-recipients-in-account: viewer excluded, escalator
  excluded, only the engineer/admin teammates get the message
- skipped-for-park-intent: park doesn't fan out
- graceful-degradation-when-email-raises: RuntimeError from the email
  service does NOT bubble out of dispatch
- endpoint-dispatches-on-escalate: end-to-end wiring through POST

Per-channel delivery records (replacing the dead `notification_sent`
boolean per Codex correction) is a v1.x story — for now application
logs are the audit trail. See
docs/plans/2026-04-27-escalation-mode-wedge-design.md.

20 tests green across handoff_manager + session_handoffs_api +
flowpilot_analytics_escalations. No regressions.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-27 15:58:05 -04:00

324 lines
10 KiB
Python

"""Integration tests for HandoffManager service."""
from unittest.mock import AsyncMock, patch
import pytest
from httpx import AsyncClient
from app.models.ai_session import AISession
from app.models.user import User
from app.services.handoff_manager import HandoffManager
@pytest.mark.asyncio
async def test_create_park_handoff(client: AsyncClient, test_user, auth_headers, test_db):
"""Parking a session creates a handoff with snapshot."""
session = AISession(
user_id=test_user["user_data"]["id"],
account_id=test_user["user_data"]["account_id"],
session_type="guided",
intake_type="free_text",
intake_content={"text": "test"},
status="active",
confidence_tier="discovery",
conversation_messages=[{"role": "user", "content": "help me"}],
)
test_db.add(session)
await test_db.flush()
from app.services.handoff_manager import HandoffManager
manager = HandoffManager(test_db)
handoff = await manager.create_handoff(
session_id=session.id,
intent="park",
engineer_notes="Waiting for client to provide logs",
user_id=test_user["user_data"]["id"],
)
assert handoff is not None
assert handoff.intent == "park"
assert handoff.engineer_notes == "Waiting for client to provide logs"
assert handoff.snapshot is not None
# Session should be paused
await test_db.refresh(session)
assert session.status == "paused"
assert session.handoff_count == 1
@pytest.mark.asyncio
async def test_create_escalate_handoff(client: AsyncClient, test_user, auth_headers, test_db):
"""Escalating creates handoff + dual-writes to escalation_package."""
session = AISession(
user_id=test_user["user_data"]["id"],
account_id=test_user["user_data"]["account_id"],
session_type="guided",
intake_type="free_text",
intake_content={"text": "test"},
status="active",
confidence_tier="discovery",
conversation_messages=[],
)
test_db.add(session)
await test_db.flush()
from app.services.handoff_manager import HandoffManager
manager = HandoffManager(test_db)
handoff = await manager.create_handoff(
session_id=session.id,
intent="escalate",
engineer_notes="Need senior help",
user_id=test_user["user_data"]["id"],
)
assert handoff.intent == "escalate"
# Dual-write check
await test_db.refresh(session)
assert session.status == "escalated"
assert session.escalation_package is not None
assert "branch_map" in session.escalation_package or "snapshot" in session.escalation_package
@pytest.mark.asyncio
async def test_claim_session(client: AsyncClient, test_user, test_admin, auth_headers, test_db):
"""Claiming a handoff sets claimed_by and reactivates session."""
session = AISession(
user_id=test_user["user_data"]["id"],
account_id=test_user["user_data"]["account_id"],
session_type="guided",
intake_type="free_text",
intake_content={"text": "test"},
status="active",
confidence_tier="discovery",
conversation_messages=[],
)
test_db.add(session)
await test_db.flush()
from app.services.handoff_manager import HandoffManager
manager = HandoffManager(test_db)
handoff = await manager.create_handoff(
session_id=session.id,
intent="escalate",
engineer_notes="Need help",
user_id=test_user["user_data"]["id"],
)
claimed = await manager.claim_session(
handoff_id=handoff.id,
claiming_user_id=test_admin["user_data"]["id"],
)
assert claimed.claimed_by == test_admin["user_data"]["id"]
assert claimed.claimed_at is not None
await test_db.refresh(session)
assert session.status == "active"
# ─── Notification dispatch ────────────────────────────────────────────────────
@pytest.mark.asyncio
async def test_dispatch_emails_engineer_recipients_in_account(
client: AsyncClient, test_user, auth_headers, test_db
):
"""dispatch_escalation_notifications emails every engineer/admin in the
account except the escalator."""
# Add a second user (engineer role) in the same account.
teammate = User(
email="teammate@example.com",
password_hash="x",
name="Teammate",
role="engineer",
account_id=test_user["user_data"]["account_id"],
account_role="engineer",
)
test_db.add(teammate)
await test_db.flush()
# Add a viewer-role user — must NOT receive a notification.
viewer = User(
email="viewer@example.com",
password_hash="x",
name="Viewer",
role="engineer",
account_id=test_user["user_data"]["account_id"],
account_role="viewer",
)
test_db.add(viewer)
await test_db.flush()
session = AISession(
user_id=test_user["user_data"]["id"],
account_id=test_user["user_data"]["account_id"],
session_type="guided",
intake_type="free_text",
intake_content={"text": "vpn down"},
problem_summary="VPN won't connect after Win update",
status="active",
confidence_tier="discovery",
conversation_messages=[],
)
test_db.add(session)
await test_db.commit()
manager = HandoffManager(test_db)
handoff = await manager.create_handoff(
session_id=session.id,
intent="escalate",
engineer_notes="Stuck on auth handshake",
user_id=test_user["user_data"]["id"],
)
await test_db.commit()
with patch(
"app.services.handoff_manager.EmailService.send_notification_email",
new=AsyncMock(return_value=True),
) as send:
sent = await manager.dispatch_escalation_notifications(handoff)
assert sent == 1 # only the engineer-role teammate
recipients = {call.kwargs["to_email"] for call in send.call_args_list}
assert recipients == {"teammate@example.com"}
assert viewer.email not in recipients
assert test_user["email"] not in recipients # not self-notified
title = send.call_args_list[0].kwargs["title"]
assert "VPN won't connect after Win update" in title
@pytest.mark.asyncio
async def test_dispatch_skipped_for_park_intent(
client: AsyncClient, test_user, auth_headers, test_db
):
"""park-intent handoffs are private (waiting for client logs etc) — no
team-wide email."""
session = AISession(
user_id=test_user["user_data"]["id"],
account_id=test_user["user_data"]["account_id"],
session_type="guided",
intake_type="free_text",
intake_content={"text": "x"},
status="active",
confidence_tier="discovery",
conversation_messages=[],
)
test_db.add(session)
await test_db.commit()
manager = HandoffManager(test_db)
handoff = await manager.create_handoff(
session_id=session.id,
intent="park",
engineer_notes="waiting on customer",
user_id=test_user["user_data"]["id"],
)
await test_db.commit()
with patch(
"app.services.handoff_manager.EmailService.send_notification_email",
new=AsyncMock(return_value=True),
) as send:
sent = await manager.dispatch_escalation_notifications(handoff)
assert sent == 0
assert send.call_count == 0
@pytest.mark.asyncio
async def test_dispatch_graceful_degradation_when_email_raises(
client: AsyncClient, test_user, auth_headers, test_db
):
"""If the email service raises (auth misconfig, network, etc.), dispatch
must NOT raise. Handoff creation has already committed; emailing is
best-effort. Codex-flagged regression."""
teammate = User(
email="t@example.com",
password_hash="x",
name="T",
role="engineer",
account_id=test_user["user_data"]["account_id"],
account_role="engineer",
)
test_db.add(teammate)
await test_db.flush()
session = AISession(
user_id=test_user["user_data"]["id"],
account_id=test_user["user_data"]["account_id"],
session_type="guided",
intake_type="free_text",
intake_content={"text": "x"},
status="active",
confidence_tier="discovery",
conversation_messages=[],
)
test_db.add(session)
await test_db.commit()
manager = HandoffManager(test_db)
handoff = await manager.create_handoff(
session_id=session.id,
intent="escalate",
engineer_notes="help",
user_id=test_user["user_data"]["id"],
)
await test_db.commit()
with patch(
"app.services.handoff_manager.EmailService.send_notification_email",
new=AsyncMock(side_effect=RuntimeError("SMTP down")),
):
# Must not raise.
sent = await manager.dispatch_escalation_notifications(handoff)
assert sent == 0
@pytest.mark.asyncio
async def test_create_handoff_endpoint_dispatches_on_escalate(
client: AsyncClient, test_user, auth_headers, test_db
):
"""End-to-end: POST /handoff with intent=escalate triggers
dispatch_escalation_notifications after commit. Verifies the wiring in
the endpoint, not just the manager method."""
teammate = User(
email="t2@example.com",
password_hash="x",
name="T2",
role="engineer",
account_id=test_user["user_data"]["account_id"],
account_role="engineer",
)
test_db.add(teammate)
await test_db.commit()
session = AISession(
user_id=test_user["user_data"]["id"],
account_id=test_user["user_data"]["account_id"],
session_type="guided",
intake_type="free_text",
intake_content={"text": "x"},
status="active",
confidence_tier="discovery",
conversation_messages=[],
)
test_db.add(session)
await test_db.commit()
with patch(
"app.services.handoff_manager.EmailService.send_notification_email",
new=AsyncMock(return_value=True),
) as send:
resp = await client.post(
f"/api/v1/ai-sessions/{session.id}/handoff",
headers=auth_headers,
json={"intent": "escalate", "engineer_notes": "Need help"},
)
assert resp.status_code == 201
assert send.call_count == 1
assert send.call_args.kwargs["to_email"] == "t2@example.com"