# AI Project Context & Repository State Document

**Document Type:** AI Coding Agent Context & Source of Truth  
**Target Audience:** Future AI Assistant Trajectories (GPT, Claude, Gemini, Antigravity)  
**Last Updated:** Phase 1 Demo Goal (Active Users + Single Agent Ringing + Live Human Chat)

---

## 1. PROJECT OVERVIEW

The **Universal Chatbot Widget** is an embeddable, framework-agnostic chat solution designed to drop into any host website (Shopify, WordPress, React, Next.js, plain HTML) via a single script tag (`<script src=".../widget.js" data-site-id="..."></script>`). The Phase 1 reprioritized roadmap focuses on:
1. **Milestone 1 (DONE):** Widget Shell + Tenant Registration + Session Init + Echo Message.
2. **Milestone 2 (DONE - Active Users & Operations Dashboard):** Real-Time Visitor Presence Tracking + Active Users + Admin Dashboard + Single Agent Ringing & Live Chat.
3. **Milestone 3 (Deferred / Future):** Multi-agent routing, agent authentication & claiming algorithms.
4. **Milestone 4 (Deferred):** Rule Engine + AI Engine + RAG.

The backend is built with FastAPI (Python) and MongoDB Atlas, using strict multi-tenancy isolated by `siteId`. The client widget is built with Vanilla JavaScript inside a Shadow DOM container, compiled via `esbuild` into a single self-executing IIFE bundle.

---

## 2. CURRENT PROJECT STRUCTURE

```text
universal-chatbot-widget/
├── Docs/
│   ├── AI-PROJECT-CONTEXT.md                  <-- AI Source of Truth (This file)
│   └── updates-files/
│       ├── Universal-Chatbot-Widget-Documentation.md  <-- Master Spec (Updated)
│       └── Phase-1-Deep-Dive.md               <-- Phase 1 Implementation Plan (Updated Roadmap)
├── backend/
│   ├── app/
│   │   ├── main.py                            <-- FastAPI app, routers, GET /admin endpoint
│   │   ├── config.py                          <-- BaseSettings (.env loading & ALLOWED_ORIGINS)
│   │   ├── database.py                        <-- AsyncMongoClient with in-memory test fallback
│   │   ├── models/
│   │   │   ├── tenant.py                      <-- TenantCreate & TenantResponse schemas
│   │   │   ├── session.py                     <-- SessionInitRequest, VisitorUser & SessionInitResponse schemas
│   │   │   ├── conversation.py                <-- ConversationBase & ConversationResponse schemas
│   │   │   └── message.py                     <-- MessageRequest, MessageResponse & MessageInDB schemas
│   │   ├── repositories/
│   │   │   ├── tenant_repository.py          <-- MongoDB tenant queries & demo auto-seed
│   │   │   ├── session_repository.py         <-- MongoDB session queries (create_session & update_session_status)
│   │   │   ├── conversation_repository.py    <-- MongoDB conversation queries (get_or_create_conversation)
│   │   │   └── message_repository.py         <-- MongoDB message queries (create_message, get_messages)
│   │   ├── services/
│   │   │   └── presence.py                    <-- In-memory active_sessions & agent_websockets feed manager
│   │   ├── routers/
│   │   │   ├── tenant.py                      <-- POST /api/v1/tenant/register endpoint
│   │   │   ├── session.py                     <-- POST /api/v1/session/init endpoint (with identity & IP)
│   │   │   ├── message.py                     <-- POST /api/v1/message endpoint (Echo & IN_CHAT routing)
│   │   │   ├── websocket.py                   <-- WS /ws/session/{sessionId} & WS /ws/agent endpoints
│   │   │   ├── admin.py                      <-- GET /api/v1/admin/active-sessions endpoint
│   │   │   └── handoff.py                    <-- POST /api/v1/handoff/accept, end, and message endpoints
│   │   └── utils/
│   │       ├── origin_validator.py            <-- Server-side HTTP Origin validation helper
│   │       ├── ip_extractor.py                <-- Client IP extraction helper (X-Forwarded-For)
│   │       └── country_resolver.py            <-- IP-to-country resolver helper ("Local / Demo" vs "Unknown")
│   ├── tests/
│   │   ├── conftest.py                        <-- TestClient & in-memory test DB fixture
│   │   ├── test_tenant.py                     <-- Tenant registration unit tests
│   │   ├── test_cors.py                       <-- CORS middleware unit tests
│   │   ├── test_session.py                    <-- Session init, identity & IP capture unit tests
│   │   ├── test_message.py                    <-- Message echo & DB persistence unit tests
│   │   ├── test_websocket.py                  <-- Visitor WebSocket presence unit tests
│   │   └── test_demo_flow.py                  <-- Active users, single agent ringing & live human chat test
│   ├── docs/learning/                         <-- Beginner learning guides (M1.1 -> M2-4)
│   ├── .env & .env.example
│   └── requirements.txt
├── widget/
│   ├── src/
│   │   └── widget.js                          <-- Vanilla JS entry point (Shadow DOM + Chat Panel + WS + End Chat)
│   ├── dist/
│   │   └── widget.js                          <-- Generated IIFE output bundle (esbuild, 16.3kb)
│   ├── demo.html                              <-- Test harness with data-site-id="site_demo_123"
│   ├── admin.html                             <-- Single Agent Operations Dashboard UI
│   └── package.json                           <-- npm build tooling configuration
└── .gitignore
```

---

## 3. MILESTONE STATUS TRACKER

- M1.1 → DONE (Tenant Registration `POST /api/v1/tenant/register`)
- M1.2 → DONE (CORS Middleware & Domain Whitelisting)
- M1.3 → DONE (Widget Build Tooling with esbuild)
- M1.4 → DONE (Shadow DOM Container & CSS Isolation)
- M1.5 → DONE (Chat Bubble UI & Panel Shell)
- M1.6 → DONE (`data-site-id` Script Configuration)
- M1.7 → DONE (Session Initialization Endpoint `POST /api/v1/session/init`)
- M1.8 → DONE (Session Persistence using `localStorage`)
- M1.9 → DONE (Message API `POST /api/v1/message` + Echo Response)
- M1.10 → DONE (Final M1 Verification & End-to-End Audit)
- M2.1 → DONE (Visitor WebSocket Presence Foundation `WS /ws/session/{sessionId}`)
- M2.2 → DONE (Conversation & Message Database Persistence)
- M2.3 → DONE (Visitor Identity & IP Address Capture)
- M2 Demo → DONE (Active Users + Country Resolution + Single Agent Ringing Chime + Accept Handshake + Real-time Live Chat + End Chat)

---

## 4. AI HANDOFF SECTION

### Completed
- **Phase 1 Demo Complete:** Active Users + Single Agent Ringing + Live Human Chat.
- **Active Visitors Feed:** `GET /api/v1/admin/active-sessions` and `WS /ws/agent`.
- **IP & Country Resolution:** `resolve_country` in `app/utils/country_resolver.py` returning `"Local / Demo"` for local/private IPs.
- **Single Agent Ringing:** Dashboard audio ring chime loop (Web Audio API tone + toggle) and visual pulse when visitor is in `RINGING` state.
- **Accept Action:** `POST /api/v1/handoff/accept` transitions status from `RINGING` to `IN_CHAT`, stops ring tone, and connects live chat.
- **Live Human Chat:** Visitor messages delivered to agent dashboard in `IN_CHAT` mode without echo. Agent replies via `POST /api/v1/handoff/message` persisted with `role="agent"` in MongoDB.
- **End Chat:** Visitor widget includes End Chat button calling `POST /api/v1/handoff/end` which updates status to `ENDED` and closes chat.
- **Admin Dashboard:** `widget/admin.html` served at `GET /admin`.

### Verified
- Automated backend pytest suite: **20/20 passed** in 0.37 seconds.
- Client widget bundle: `dist/widget.js` (16.3kb compiled via `esbuild`).

### Architecture
- **Backend:** FastAPI + PyMongo `AsyncMongoClient` + Starlette WebSockets + Pydantic + MongoDB Atlas.
- **Client Widget:** Vanilla JS in Shadow DOM compiled via `esbuild` (`dist/widget.js`).
- **Dashboard:** HTML5 / CSS3 / ES6 Javascript with Web Audio API sound generator.
