# Milestone 2 — Active Users, Single Agent Ringing & Live Human Chat

## Overview

This directory documents the complete end-to-end architecture, API contracts, WebSocket feeds, confirmation dialogs, role tracking, and widget UI capabilities for **Milestone 2: Active Users + Single Agent Ring + Live Human Chat**.

---

## 1. Complete System Architecture & Flow

```text
Visitor Widget                              FastAPI Backend                                  Agent Dashboard
  [Shadow DOM]                                [App Server]                                    [admin.html]
       │                                           │                                               │
       ├──── POST /api/v1/session/init ───────────►│ (Creates Session: status="RINGING")           │
       ├──── WS /ws/session/{sessionId} ──────────►│ (Broadcasts visitor_connected) ──────────────►│ (Chime sound + Ringing card)
       │                                           │                                               │
       │ ─── POST /api/v1/message (RINGING) ─────►│ (Persists msg, suppresses echo) ─────────────►│ (Appends visitor message)
       │     └─► "Please wait while we connect..." │                                               │
       │                                           │                                               │
       │                                           │◄─── POST /api/v1/handoff/accept ──────────────┤ (Click ACCEPT)
       │◄─── WS {"type":"status_changed"} ─────────┤ (Status -> "IN_CHAT", stops chime) ──────────►│ (Card -> IN_CHAT)
       │                                           │                                               │
       │ ─── POST /api/v1/message (IN_CHAT) ──────►│ (Persists user msg, broadcasts) ─────────────►│ (Appends visitor message)
       │     └─► "Message delivered to agent."     │                                               │
       │                                           │                                               │
       │◄─── WS {"type":"agent_message"} ──────────┼─── POST /api/v1/handoff/message ──────────────┤ (Agent sends reply)
       │                                           │ (Persists agent msg in DB)                    │
       │                                           │                                               │
       ├──── POST /api/v1/handoff/end ────────────►│ (Status -> "ENDED", endedBy="visitor") ───────►│ (Card -> ENDED)
       │                                           │                                               │
       │◄─── WS {"type":"status_changed"} ─────────┼─── POST /api/v1/handoff/end (agent) ──────────┤ (Agent clicks End Chat)
       │     (endedBy="agent")                     │ (Status -> "ENDED", endedBy="agent")          │
```

---

## 2. API & Real-Time Specifications

### REST Endpoints

- `GET /api/v1/admin/active-sessions?siteId={siteId}`: Returns active visitor snapshot including `sessionId`, `siteId`, `status`, `endedBy`, `user`, `ipAddress`, `country`, `connectedAt`.
- `POST /api/v1/handoff/accept`: Transitions session state from `RINGING` to `IN_CHAT`.
- `POST /api/v1/handoff/end`: Accepts `{ "sessionId": "sess_123", "endedBy": "visitor" | "agent" }`. Transitions session status to `ENDED` and updates DB/memory.
- `POST /api/v1/handoff/message`: Agent reply endpoint. Rejects if session is `ENDED` (`HTTP 400 Bad Request`).
- `POST /api/v1/message`: Visitor message endpoint.
  - `RINGING`: Returns `"Please wait while we connect you to an agent."`
  - `IN_CHAT`: Returns `"Message delivered to agent."`
  - `ENDED`: Rejects with `HTTP 400 Bad Request`.
- `GET /admin`: Serves the Single Agent Operations Dashboard (`widget/admin.html`).

### WebSocket Feeds

- `WS /ws/session/{sessionId}`: Visitor WebSocket connection. Listens for `status_changed` (`IN_CHAT`, `ENDED`) and live `agent_message` events.
- `WS /ws/agent`: Agent Dashboard WebSocket connection. Receives real-time events (`visitor_connected`, `visitor_disconnected`, `visitor_accepted`, `user_message`, `agent_message`, `chat_ended`).

---

## 3. End-Chat Confirmation & Role Tracking (`endedBy`)

### Confirmation Dialogs
- **Visitor Side:** Clicking "End Chat" displays a confirmation modal overlay (`"Are you sure you want to end this chat?"`).
  - **Cancel:** Closes modal and keeps chat active.
  - **Confirm:** Triggers `POST /api/v1/handoff/end` with `{ "endedBy": "visitor" }`.
- **Agent Side:** Clicking "End Chat" displays an agent confirmation modal overlay (`"Are you sure you want to end this chat?"`).
  - **Cancel:** Closes modal and keeps chat active.
  - **Confirm:** Triggers `POST /api/v1/handoff/end` with `{ "endedBy": "agent" }`.

### Role-Based Messaging
- **Visitor Ends Chat:**
  - Visitor sees: `"You have ended the chat session."`
  - Agent sees: `"Visitor ended the chat session."`
- **Agent Ends Chat:**
  - Agent sees: `"You have ended the chat session."`
  - Visitor sees: `"The agent has ended the chat session."`

---

## 4. Visitor Widget Features

- **Shadow DOM Isolation:** Completely encapsulates CSS and DOM to prevent host page style bleeding.
- **Fullscreen Toggle:** Added header toggle button. Expands widget to viewport bounds (`100vw` x `100vh` at `z-index: 9999999`) and restores to normal bounds (`360px` x `500px`).
- **Build Tooling:** esbuild compiles `src/widget.js` into IIFE production bundle `dist/widget.js`.

---

## 5. Verification & Test Suite

The full backend pytest test suite validates all CORS, Tenant, Session, WebSocket, Message Routing, Handoff, and End-Chat flows:

```bash
cd backend
.\venv\Scripts\python.exe -m pytest
```

Result:
```text
======================= 22 passed, 4 warnings in 0.42s ========================
```
