feat(ai-session): add Phase 2 PSA integration, escalation handoff, and session management

Phase 2 of the FlowPilot-First Pivot connecting AI sessions to ConnectWise PSA:

Slice 1 — PSA Ticket Intake:
- FlowPilotEngine accepts psa_ticket intake with graceful CW API fallback
- Ticket picker on intake screen (refactored TicketPickerModal for dual-mode)
- Ticket context card in session sidebar

Slice 2 — Auto Documentation Push:
- PSA documentation service with resolution/escalation note formatting
- Time entry creation via new ConnectWise provider method
- Automatic retry scheduler (APScheduler, 5min interval, 3 retries)
- PSA push status indicators in frontend with manual retry button
- Member mapping warning when CW member not mapped

Slice 3 — Session Pause/Resume & Escalation Handoff:
- Pause/resume endpoints for same-engineer session bookmarking
- Escalation flow: requesting_escalation status, self-escalation blocked
- Enhanced escalation package with LLM-generated hypotheses/suggestions
- Pickup endpoint with continue/fresh resume modes and briefing step
- Escalation queue (sidebar nav + dedicated page)
- SessionBriefing component with continue/fresh choice UI
- EscalateModal with PSA-aware button text

Slice 4 — Mid-Session Ticket Linking:
- Link ticket retroactively with context injection into system prompt
- Link Ticket button in session sidebar

Slice 5 — FlowPilot PSA Settings:
- Settings tab on IntegrationsPage with 7 configurable options
- Stored as flowpilot_settings JSONB on PsaConnection

Database: 2 migrations (flowpilot_settings, psa_post_log changes, status constraint)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-19 01:30:05 +00:00
parent 2063a799b0
commit bbe590bfec
37 changed files with 3698 additions and 121 deletions

View File

@@ -11,6 +11,7 @@ from .types import (
PSACompany,
PSAMember,
PSAConfiguration,
PSATimeEntry,
)
@@ -66,3 +67,14 @@ class PSAProvider(ABC):
@abstractmethod
async def get_ticket_configurations(self, ticket_id: str) -> list[PSAConfiguration]:
...
@abstractmethod
async def create_time_entry(
self,
ticket_id: str,
member_id: str,
hours: float,
notes: str | None = None,
work_type: str | None = None,
) -> PSATimeEntry:
...

View File

@@ -15,6 +15,7 @@ from app.services.psa.types import (
PSACompany,
PSAMember,
PSAConfiguration,
PSATimeEntry,
)
from .client import ConnectWiseClient
@@ -514,6 +515,37 @@ class ConnectWiseProvider(PSAProvider):
psa_cache.set(cache_key, ctx, ttl_seconds=300)
return ctx
async def create_time_entry(
self,
ticket_id: str,
member_id: str,
hours: float,
notes: str | None = None,
work_type: str | None = None,
) -> PSATimeEntry:
"""Create a time entry on a CW ticket via POST /time/entries."""
payload: dict = {
"chargeToId": int(ticket_id),
"chargeToType": "ServiceTicket",
"member": {"id": int(member_id)},
"timeStart": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"actualHours": hours,
}
if notes:
payload["notes"] = notes[:2000] # CW limit
if work_type:
payload["workType"] = {"name": work_type}
data = await self._client.post("/time/entries", payload)
return PSATimeEntry(
id=str(data["id"]),
ticket_id=ticket_id,
member_id=member_id,
hours=data.get("actualHours", hours),
notes=data.get("notes"),
created_at=data.get("timeStart"),
)
# ── Private helpers ───────────────────────────────────────────────
@staticmethod

View File

@@ -31,6 +31,32 @@ async def get_provider_for_account(
provider="unknown",
)
return _instantiate_provider(connection)
async def get_provider_for_connection(
connection_id: UUID, db: AsyncSession
) -> PSAProvider:
"""Look up a specific PSA connection by ID, decrypt credentials, instantiate provider."""
result = await db.execute(
select(PsaConnection).where(
PsaConnection.id == connection_id,
PsaConnection.is_active.is_(True),
)
)
connection = result.scalar_one_or_none()
if not connection:
raise PSAConnectionError(
"PSA connection not found or inactive.",
provider="unknown",
)
return _instantiate_provider(connection)
def _instantiate_provider(connection: PsaConnection) -> PSAProvider:
"""Create the appropriate provider instance from a connection record."""
if connection.provider == "connectwise":
from app.services.psa.connectwise.client import ConnectWiseClient
from app.services.psa.connectwise.provider import ConnectWiseProvider

View File

@@ -57,6 +57,16 @@ class PSAConfiguration(BaseModel):
company_name: str | None = None
class PSATimeEntry(BaseModel):
id: str
ticket_id: str
member_id: str | None = None
hours: float
notes: str | None = None
work_type: str | None = None
created_at: str | None = None
class NoteType:
INTERNAL_ANALYSIS = "internal_analysis"
RESOLUTION = "resolution"