github-actions commited on
Commit
6793beb
·
0 Parent(s):

Initial sync to Hugging Face

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .env.example +24 -0
  2. .github/workflows/sync-to-hub.yml +28 -0
  3. .gitignore +55 -0
  4. ARCHITECTURE.md +77 -0
  5. Dockerfile +41 -0
  6. README.md +127 -0
  7. frontend/index.html +12 -0
  8. frontend/package-lock.json +0 -0
  9. frontend/package.json +41 -0
  10. frontend/postcss.config.js +6 -0
  11. frontend/src/App.tsx +31 -0
  12. frontend/src/components/dashboard/RecentActivityTable.tsx +68 -0
  13. frontend/src/components/dashboard/WorkflowMonitor.tsx +68 -0
  14. frontend/src/components/layout/Sidebar.tsx +72 -0
  15. frontend/src/components/layout/ThemeToggle.tsx +22 -0
  16. frontend/src/components/shared/KpiCard.tsx +65 -0
  17. frontend/src/index.css +18 -0
  18. frontend/src/main.tsx +15 -0
  19. frontend/src/pages/Compose.tsx +139 -0
  20. frontend/src/pages/Dashboard.tsx +174 -0
  21. frontend/src/pages/DetailedView.tsx +191 -0
  22. frontend/src/pages/Inbox.tsx +161 -0
  23. frontend/src/pages/ReviewQueue.tsx +130 -0
  24. frontend/src/pages/Settings.tsx +134 -0
  25. frontend/src/store.ts +72 -0
  26. frontend/src/vite-env.d.ts +1 -0
  27. frontend/tailwind.config.js +30 -0
  28. frontend/tsconfig.json +26 -0
  29. frontend/tsconfig.node.json +10 -0
  30. frontend/vercel.json +8 -0
  31. frontend/vite.config.ts +16 -0
  32. knowledge_base/README.md +11 -0
  33. knowledge_base/account.md +42 -0
  34. knowledge_base/billing.md +47 -0
  35. knowledge_base/faiss_index/index.pkl +0 -0
  36. knowledge_base/general.md +51 -0
  37. knowledge_base/technical.md +32 -0
  38. requirements.txt +35 -0
  39. src/__init__.py +1 -0
  40. src/api/__init__.py +1 -0
  41. src/api/dependencies.py +10 -0
  42. src/api/routes.py +420 -0
  43. src/core/__init__.py +1 -0
  44. src/core/config.py +56 -0
  45. src/core/logging.py +20 -0
  46. src/graph/__init__.py +1 -0
  47. src/graph/workflow.py +78 -0
  48. src/main.py +57 -0
  49. src/nodes/__init__.py +1 -0
  50. src/nodes/classifier.py +55 -0
.env.example ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OpenAI inference (backend only)
2
+ OPENAI_API_KEY=your_openai_api_key_here
3
+ LLM_BASE_URL=https://api.openai.com/v1
4
+ LLM_MODEL=gpt-6-luna
5
+ EMBEDDING_MODEL=text-embedding-3-small
6
+
7
+ # Email / IMAP
8
+ EMAIL_HOST=imap.gmail.com
9
+ EMAIL_PORT=993
10
+ SMTP_HOST=smtp.gmail.com
11
+ SMTP_PORT=587
12
+ EMAIL_USERNAME=
13
+ EMAIL_PASSWORD=
14
+
15
+ # Persistence (Supabase)
16
+ SUPABASE_URL=
17
+ SUPABASE_KEY=
18
+
19
+ # Backend authentication: set a strong secret before deployment
20
+ API_TOKEN=
21
+
22
+ # Application
23
+ APP_ENV=development
24
+ LOG_LEVEL=DEBUG
.github/workflows/sync-to-hub.yml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Sync to Hugging Face Hub
2
+ on:
3
+ push:
4
+ branches: [main]
5
+ # Allow manual trigger from the Actions tab
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ sync:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ with:
14
+ fetch-depth: 0
15
+ lfs: true
16
+ - name: Push to hub
17
+ env:
18
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
19
+ run: |
20
+ rm -rf .git
21
+ git init
22
+ git branch -M main
23
+ git config user.name "github-actions"
24
+ git config user.email "github-actions@github.com"
25
+ git add .
26
+ git commit -m "Initial sync to Hugging Face"
27
+ git remote add origin "https://mrmayankmathurorg:$HF_TOKEN@huggingface.co/spaces/mrmayankmathurorg/Customer-EMAIL-Agent"
28
+ git push --force origin main
.gitignore ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Environment
2
+ .env
3
+ .env.*
4
+ !.env.example
5
+
6
+ # Python
7
+ __pycache__/
8
+ *.py[cod]
9
+ *$py.class
10
+ *.egg-info/
11
+ dist/
12
+ build/
13
+ .eggs/
14
+
15
+ # Virtual environments
16
+ venv/
17
+ .venv/
18
+ env/
19
+
20
+ # IDE
21
+ .idea/
22
+ .vscode/
23
+ *.swp
24
+ *.swo
25
+ *~
26
+
27
+ # OS
28
+ .DS_Store
29
+ Thumbs.db
30
+
31
+ # Logs
32
+ *.log
33
+ logs/
34
+
35
+ # Testing
36
+ .pytest_cache/
37
+ .coverage
38
+ htmlcov/
39
+
40
+ # Node / Frontend
41
+ node_modules/
42
+ frontend/dist/
43
+ frontend/dist-ssr/
44
+ npm-debug.log*
45
+ yarn-debug.log*
46
+ yarn-error.log*
47
+ pnpm-debug.log*
48
+ *.local
49
+
50
+ # Data / State
51
+ data_store.json
52
+ *.sqlite3
53
+ *.db
54
+ *.faiss
55
+
ARCHITECTURE.md ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # System Architecture
2
+
3
+ ## Architecture Flow Diagram
4
+
5
+ Below is the architectural flow diagram representing the Customer Support Email Agent system, mapping how the Frontend, Backend, AI Pipeline, and External Services interact.
6
+
7
+ ```mermaid
8
+ graph TD
9
+ %% Subsystems definition
10
+ subgraph Frontend ["Frontend (React / Vite) - Hosted on Vercel"]
11
+ UI_Compose["Compose UI (Compose.tsx)"]
12
+ UI_Dash["Dashboard UI (Dashboard.tsx)"]
13
+ UI_Ticket["Detailed View (DetailedView.tsx)"]
14
+ State["Zustand Global Store"]
15
+ end
16
+
17
+ subgraph Backend ["Backend (FastAPI) - Hosted on Hugging Face Spaces"]
18
+ API["FastAPI Routing (/api/v1)"]
19
+
20
+ subgraph Pipeline ["LangGraph Agent Pipeline (SupportPipeline)"]
21
+ Node1["1. classify_email"]
22
+ Node2["2. retrieve_context"]
23
+ Node3["3. generate_response"]
24
+ Node4["4. check_escalation"]
25
+ Node5["5. send_email_reply"]
26
+ Node6["6. check_follow_up"]
27
+ end
28
+
29
+ FAISS[("FAISS Vector Store\n(docs/knowledge base)")]
30
+ end
31
+
32
+ subgraph Services ["External Services"]
33
+ LLM["OpenAI Inference"]
34
+ Database[("Supabase (PostgreSQL)")]
35
+ SMTP["SMTP Server (Gmail/Resend)"]
36
+ end
37
+
38
+ %% --- Core Frontend to Backend APIs ---
39
+ UI_Compose -- "POST /process-email\n(X-API-Token)" --> API
40
+ UI_Dash -- "GET /kpis\nGET /emails/recent" --> API
41
+ UI_Ticket -- "GET /emails/{ticket_id}" --> API
42
+
43
+ %% --- Backend Database Operations ---
44
+ API -- "Write/Read Tickets Data\n(supabase-py)" --> Database
45
+
46
+ %% --- Pipeline Execution Flow ---
47
+ API -- "initiates workflow" --> Node1
48
+ Node1 --> Node2
49
+ Node2 --> Node3
50
+ Node3 --> Node4
51
+
52
+ Node4 -- "if Confidence < 0.7 or Sensitive\n(Escalated)" --> PipelineEnd((End Pipeline))
53
+ Node4 -- "if Confident\n(Auto-reply)" --> Node5
54
+
55
+ Node5 --> Node6
56
+ Node6 --> PipelineEnd
57
+
58
+ PipelineEnd -. "return result to API router" .-> API
59
+
60
+ %% --- LLM and Service Interactions ---
61
+ Node1 -. "LLM Prompt (JSON)" .-> LLM
62
+ Node2 -. "fetch similar docs" .-> FAISS
63
+ Node2 -. "embed query" .-> LLM
64
+ Node3 -. "draft reasoning" .-> LLM
65
+ Node4 -. "evaluate draft" .-> LLM
66
+ Node5 -. "dispatch SMTP" .-> SMTP
67
+ Node6 -. "LLM Prompt" .-> LLM
68
+ ```
69
+
70
+ ## Key Components
71
+
72
+ 1. **Frontend**: A React SPA built with Vite. It interacts with the backend strictly through REST APIs and manages state via `zustand`. It leverages `recharts` for the dashboard and `reactflow` for pipeline visualization.
73
+ 2. **Backend**: A FastAPI Python backend acting as the orchestrator. It manages the authentication (`X-API-Token`) and database persistence (`supabase-py`).
74
+ 3. **LangGraph Pipeline**: The core AI logic resides here as a Directed Acyclic Graph (DAG) state machine. It handles classification, context retrieval (RAG via FAISS), response generation, autonomous escalation scoring, and conditionally dispatching outbound SMTP emails.
75
+ 4. **External Services**:
76
+ - **OpenAI**: Provides the embedding (`text-embedding-3-small`) and LLM text generation capabilities for the intelligent nodes.
77
+ - **Supabase**: Serves as the primary operational database, storing tickets, statuses, extracted categorization, and execution metadata.
Dockerfile ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use an official Python runtime as a parent image
2
+ FROM python:3.11-slim
3
+
4
+ # Set environment variables
5
+ ENV PYTHONDONTWRITEBYTECODE 1
6
+ ENV PYTHONUNBUFFERED 1
7
+ ENV PORT 7860
8
+
9
+ # Set the working directory in the container
10
+ WORKDIR /app
11
+
12
+ # Install system dependencies
13
+ RUN apt-get update && apt-get install -y \
14
+ build-essential \
15
+ curl \
16
+ git \
17
+ && rm -rf /var/lib/apt/lists/*
18
+
19
+ # Copy the requirements file into the container
20
+ COPY requirements.txt .
21
+
22
+ # Install any needed packages specified in requirements.txt
23
+ RUN pip install --no-cache-dir -r requirements.txt
24
+
25
+ # Copy the rest of the application code into the container
26
+ COPY . .
27
+
28
+ # Create a non-root user and switch to it for better security on HF
29
+ RUN useradd -m -u 1000 user
30
+ USER user
31
+ ENV HOME=/home/user \
32
+ PATH=/home/user/.local/bin:$PATH
33
+
34
+ # Make sure the static directory exists
35
+ RUN mkdir -p /app/static
36
+
37
+ # Expose the port the app runs on
38
+ EXPOSE 7860
39
+
40
+ # Run the application
41
+ CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "7860"]
README.md ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Customer EMAIL Agent
3
+ emoji: 📧
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: docker
7
+ pinned: false
8
+ ---
9
+
10
+ # 📧 Customer Support Email Agent
11
+
12
+ An AI-powered customer support email agent built with **LangGraph**, **LangChain**, and **FastAPI**.
13
+
14
+ The agent automatically classifies incoming support emails, retrieves relevant knowledge, drafts responses, and optionally escalates complex issues — all orchestrated as a stateful LangGraph workflow.
15
+
16
+ ## Architecture
17
+
18
+ ```
19
+ Incoming Email
20
+ │
21
+ ▼
22
+ ┌─────────────┐
23
+ │ Classifier │ ← Categorizes intent (billing, technical, general, etc.)
24
+ └──────┬──────┘
25
+ │
26
+ ▼
27
+ ┌─────────────┐
28
+ │ Retriever │ ← Fetches relevant knowledge base articles
29
+ └──────┬──────┘
30
+ │
31
+ ▼
32
+ ┌─────────────┐
33
+ │ Responder │ ← Drafts a reply using context + LLM
34
+ └──────┬──────┘
35
+ │
36
+ ▼
37
+ ┌─────────────┐
38
+ │ Escalation │ ← Routes to human agent if confidence is low
39
+ └─────────────┘
40
+ ```
41
+
42
+ ## Project Structure
43
+
44
+ ```
45
+ cust_support_system/
46
+ ├── src/
47
+ │ ├── main.py # FastAPI application entry point
48
+ │ ├── api/ # API routes & dependencies
49
+ │ ├── core/ # Config, logging, constants
50
+ │ ├── graph/ # LangGraph workflow definition
51
+ │ ├── nodes/ # Individual graph nodes
52
+ │ ├── schemas/ # Pydantic models
53
+ │ ├── services/ # Email & LLM services
54
+ │ ├── prompts/ # Prompt templates
55
+ │ └── utils/ # Helper utilities
56
+ ├── knowledge_base/ # Support articles & FAQ docs
57
+ ├── tests/ # Pytest test suite
58
+ ├── requirements.txt
59
+ ├── .env.example # Credential-free configuration template
60
+ └── README.md
61
+ ```
62
+
63
+ ## Setup
64
+
65
+ ```bash
66
+ # 1. Create & activate a virtual environment (Python 3.12)
67
+ python3.12 -m venv venv
68
+ source venv/bin/activate
69
+
70
+ # 2. Install dependencies
71
+ pip install -r requirements.txt
72
+
73
+ # 3. Configure environment variables
74
+ cp .env.example .env # then fill in your keys
75
+
76
+ # 4. Run the server
77
+ uvicorn src.main:app --reload
78
+ ```
79
+
80
+ ### OpenAI inference configuration
81
+
82
+ Chat and knowledge-base embeddings use the backend-only `OPENAI_API_KEY`:
83
+
84
+ ```dotenv
85
+ OPENAI_API_KEY=your-openai-api-key
86
+ LLM_BASE_URL=https://api.openai.com/v1
87
+ LLM_MODEL=gpt-6-luna
88
+ EMBEDDING_MODEL=text-embedding-3-small
89
+ ```
90
+
91
+ The chat model ID `gpt-6-luna` is passed through exactly as configured.
92
+ Its availability and API compatibility have not been verified; it must be
93
+ accessible on your OpenAI account. The application no longer uses `GITHUB_TOKEN`
94
+ for inference. Do not use a GitHub token as an OpenAI key or expose provider keys
95
+ in frontend `VITE_*` variables.
96
+
97
+ For an existing installation, update the provider entries in `.env` rather than
98
+ replacing the file and losing unrelated credentials. Environment variables take
99
+ precedence over `.env`, which takes precedence over the code defaults. On your
100
+ backend host (for example, Hugging Face Spaces), set `OPENAI_API_KEY` as a secret
101
+ and update or remove stale `LLM_BASE_URL`, `LLM_MODEL`, and `EMBEDDING_MODEL`
102
+ overrides. Restart the backend after configuration changes. `/config` reports
103
+ the effective chat model; it does not modify inference settings.
104
+
105
+ Embeddings remain on the `text-embedding-3-small` model family with default
106
+ dimensions. The migration does not rebuild the FAISS index. If the old index used
107
+ a different embedding model or dimensions, rebuild it explicitly with
108
+ `python -m src.services.kb_service` after setting a valid key; that command makes
109
+ billable embedding requests.
110
+
111
+ ### Backend API authentication
112
+
113
+ Set `API_TOKEN` in the backend environment to a long random value. Production
114
+ startup fails when `APP_ENV=production` and the token is missing. For local
115
+ development, the frontend sends the same value from `frontend/.env` as
116
+ `VITE_API_TOKEN`; this value is visible to browser users and should not be
117
+ treated as a production-grade user authentication secret.
118
+
119
+ ## Tech Stack
120
+
121
+ | Layer | Technology |
122
+ | ------------- | --------------------- |
123
+ | LLM | OpenAI (`gpt-6-luna`) |
124
+ | Orchestration | LangGraph + LangChain |
125
+ | API | FastAPI |
126
+ | Validation | Pydantic v2 |
127
+ | Language | Python 3.12 |
frontend/index.html ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en" class="dark">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>Customer Support System Dashboard</title>
7
+ </head>
8
+ <body>
9
+ <div id="root"></div>
10
+ <script type="module" src="/src/main.tsx"></script>
11
+ </body>
12
+ </html>
frontend/package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
frontend/package.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "support-agent-frontend",
3
+ "private": true,
4
+ "version": "0.1.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "vite",
8
+ "build": "tsc -b && vite build",
9
+ "lint": "eslint .",
10
+ "preview": "vite preview"
11
+ },
12
+ "dependencies": {
13
+ "@supabase/supabase-js": "^2.104.0",
14
+ "axios": "^1.7.7",
15
+ "clsx": "^2.1.1",
16
+ "lucide-react": "^0.453.0",
17
+ "react": "^18.3.1",
18
+ "react-dom": "^18.3.1",
19
+ "react-router-dom": "^6.27.0",
20
+ "reactflow": "^11.11.4",
21
+ "recharts": "^2.13.0",
22
+ "tailwind-merge": "^2.5.4",
23
+ "zustand": "^5.0.0"
24
+ },
25
+ "devDependencies": {
26
+ "@eslint/js": "^9.13.0",
27
+ "@types/react": "^18.3.11",
28
+ "@types/react-dom": "^18.3.1",
29
+ "@vitejs/plugin-react": "^4.3.3",
30
+ "autoprefixer": "^10.4.20",
31
+ "eslint": "^9.13.0",
32
+ "eslint-plugin-react-hooks": "^5.0.0",
33
+ "eslint-plugin-react-refresh": "^0.4.13",
34
+ "globals": "^15.11.0",
35
+ "postcss": "^8.4.47",
36
+ "tailwindcss": "^3.4.14",
37
+ "typescript": "~5.6.2",
38
+ "typescript-eslint": "^8.10.0",
39
+ "vite": "^5.4.9"
40
+ }
41
+ }
frontend/postcss.config.js ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ export default {
2
+ plugins: {
3
+ tailwindcss: {},
4
+ autoprefixer: {},
5
+ },
6
+ }
frontend/src/App.tsx ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
2
+ import Sidebar from './components/layout/Sidebar';
3
+ import Dashboard from './pages/Dashboard';
4
+ import DetailedView from './pages/DetailedView';
5
+ import Settings from './pages/Settings';
6
+ import Compose from './pages/Compose';
7
+ import Inbox from './pages/Inbox';
8
+ import ReviewQueue from './pages/ReviewQueue';
9
+
10
+ function App() {
11
+ return (
12
+ <BrowserRouter>
13
+ <div className="flex h-screen w-screen overflow-hidden bg-lightBg dark:bg-darkBg text-lightText dark:text-darkText transition-colors duration-200">
14
+ <Sidebar />
15
+ <main className="flex-1 overflow-y-auto p-6 lg:p-10 relative">
16
+ <Routes>
17
+ <Route path="/" element={<Navigate to="/dashboard" replace />} />
18
+ <Route path="/dashboard" element={<Dashboard />} />
19
+ <Route path="/compose" element={<Compose />} />
20
+ <Route path="/inbox" element={<Inbox />} />
21
+ <Route path="/review" element={<ReviewQueue />} />
22
+ <Route path="/ticket/:id" element={<DetailedView />} />
23
+ <Route path="/settings" element={<Settings />} />
24
+ </Routes>
25
+ </main>
26
+ </div>
27
+ </BrowserRouter>
28
+ );
29
+ }
30
+
31
+ export default App;
frontend/src/components/dashboard/RecentActivityTable.tsx ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Link } from 'react-router-dom';
2
+ import { Ticket } from '../../store';
3
+
4
+ interface Props {
5
+ tickets: Ticket[];
6
+ }
7
+
8
+ export default function RecentActivityTable({ tickets }: Props) {
9
+ return (
10
+ <div className="bg-lightBg dark:bg-darkCard border border-borderLight dark:border-borderDark rounded-2xl shadow-sm overflow-hidden flex-1">
11
+ <div className="px-6 py-4 border-b border-borderLight dark:border-borderDark">
12
+ <h3 className="font-semibold dark:text-darkText">Recent Activity</h3>
13
+ </div>
14
+ <div className="overflow-x-auto">
15
+ <table className="w-full text-sm text-left">
16
+ <thead className="bg-gray-50 dark:bg-gray-800 text-gray-500 dark:text-gray-400">
17
+ <tr>
18
+ <th className="px-6 py-3 font-medium">Ticket ID</th>
19
+ <th className="px-6 py-3 font-medium">Sender</th>
20
+ <th className="px-6 py-3 font-medium">Subject</th>
21
+ <th className="px-6 py-3 font-medium">Category</th>
22
+ <th className="px-6 py-3 font-medium">Status</th>
23
+ </tr>
24
+ </thead>
25
+ <tbody>
26
+ {tickets.map((t) => (
27
+ <tr
28
+ key={t.ticket_id}
29
+ className="border-b border-borderLight dark:border-borderDark hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors"
30
+ >
31
+ <td className="px-6 py-4 font-mono text-accentCyan">
32
+ <Link
33
+ to={`/ticket/${t.ticket_id}`}
34
+ className="hover:underline focus:outline-none focus:ring-2 focus:ring-accentCyan rounded"
35
+ aria-label={`View ticket ${t.ticket_id}`}
36
+ >
37
+ #{t.ticket_id}
38
+ </Link>
39
+ </td>
40
+ <td className="px-6 py-4 font-medium dark:text-gray-200">{t.sender || 'Unknown'}</td>
41
+ <td className="px-6 py-4 text-gray-500 dark:text-gray-400 max-w-[200px] truncate">{t.subject || '(no subject)'}</td>
42
+ <td className="px-6 py-4">
43
+ <span className="px-2 py-1 rounded bg-gray-100 dark:bg-gray-700 text-xs font-medium uppercase text-gray-600 dark:text-gray-300">
44
+ {t.category}
45
+ </span>
46
+ </td>
47
+ <td className="px-6 py-4">
48
+ <span className={`px-2 py-1 rounded text-xs font-semibold ${
49
+ t.needs_escalation ? 'bg-accentRed/10 text-accentRed' : 'bg-accentGreen/10 text-accentGreen'
50
+ }`}>
51
+ {t.needs_escalation ? 'ESCALATED' : t.status.toUpperCase()}
52
+ </span>
53
+ </td>
54
+ </tr>
55
+ ))}
56
+ {tickets.length === 0 && (
57
+ <tr>
58
+ <td colSpan={5} className="px-6 py-8 text-center text-gray-500 dark:text-gray-400">
59
+ No recent activity found.
60
+ </td>
61
+ </tr>
62
+ )}
63
+ </tbody>
64
+ </table>
65
+ </div>
66
+ </div>
67
+ );
68
+ }
frontend/src/components/dashboard/WorkflowMonitor.tsx ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useState } from 'react';
2
+ import ReactFlow, { Background, Controls, Node, Edge } from 'reactflow';
3
+ import 'reactflow/dist/style.css';
4
+
5
+ const initialNodes: Node[] = [
6
+ { id: 'start', position: { x: 50, y: 150 }, data: { label: '📧 Incoming Email' }, type: 'input' },
7
+ { id: 'classifier', position: { x: 250, y: 150 }, data: { label: '🧠 Classifier' } },
8
+ { id: 'retriever', position: { x: 450, y: 150 }, data: { label: '🔍 Retriever' } },
9
+ { id: 'responder', position: { x: 650, y: 150 }, data: { label: '✍️ Responder' } },
10
+ { id: 'escalation', position: { x: 450, y: 250 }, data: { label: '⚠️ Escalation' }, type: 'output' },
11
+ ];
12
+
13
+ const initialEdges: Edge[] = [
14
+ { id: 'e1', source: 'start', target: 'classifier', animated: true },
15
+ { id: 'e2', source: 'classifier', target: 'retriever', animated: true },
16
+ { id: 'e3', source: 'retriever', target: 'responder', animated: true },
17
+ { id: 'e4', source: 'classifier', target: 'escalation', animated: false, style: { stroke: '#EF4444' } },
18
+ ];
19
+
20
+ export default function WorkflowMonitor() {
21
+ const [nodes, setNodes] = useState<Node[]>(initialNodes);
22
+ const [edges] = useState<Edge[]>(initialEdges);
23
+
24
+ // Simulate active node pulsing
25
+ useEffect(() => {
26
+ const interval = setInterval(() => {
27
+ setNodes((nds) =>
28
+ nds.map((n) => {
29
+ if (n.id === 'retriever' || n.id === 'responder') {
30
+ // Fake active pulse
31
+ return {
32
+ ...n,
33
+ style: {
34
+ background: '#212936',
35
+ color: '#D1D5DB',
36
+ border: '2px solid #06B6D4',
37
+ boxShadow: '0 0 15px rgba(6, 182, 212, 0.4)',
38
+ borderRadius: '12px',
39
+ padding: '12px',
40
+ }
41
+ };
42
+ }
43
+ if (n.id === 'escalation') {
44
+ return {
45
+ ...n,
46
+ style: { background: '#212936', color: '#D1D5DB', border: '2px solid #EF4444', borderRadius: '12px', padding: '12px' }
47
+ };
48
+ }
49
+ return {
50
+ ...n,
51
+ style: { background: '#212936', color: '#D1D5DB', border: '1px solid #374151', borderRadius: '12px', padding: '12px' }
52
+ };
53
+ })
54
+ );
55
+ }, 2000);
56
+ return () => clearInterval(interval);
57
+ }, []);
58
+
59
+ return (
60
+ <div className="h-64 w-full bg-lightBg dark:bg-darkBg border border-borderLight dark:border-borderDark rounded-2xl overflow-hidden shadow-sm relative">
61
+ <div className="absolute top-4 left-4 z-10 text-sm font-semibold tracking-wider text-gray-500 uppercase">Agentic Workflow Monitor</div>
62
+ <ReactFlow nodes={nodes} edges={edges} fitView>
63
+ <Background gap={16} size={1} color="#64748b" />
64
+ <Controls showInteractive={false} />
65
+ </ReactFlow>
66
+ </div>
67
+ );
68
+ }
frontend/src/components/layout/Sidebar.tsx ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NavLink } from "react-router-dom";
2
+ import {
3
+ LayoutDashboard,
4
+ Inbox,
5
+ MailOpen,
6
+ ListChecks,
7
+ Settings,
8
+ Bot,
9
+ } from "lucide-react";
10
+ import ThemeToggle from "./ThemeToggle";
11
+
12
+ export default function Sidebar() {
13
+ const routes = [
14
+ { name: "Workflow Monitor", path: "/dashboard", icon: LayoutDashboard },
15
+ { name: "Compose Email", path: "/compose", icon: MailOpen },
16
+ { name: "Email Inbox", path: "/inbox", icon: Inbox },
17
+ { name: "Review Queue", path: "/review", icon: ListChecks },
18
+ { name: "Configuration", path: "/settings", icon: Settings },
19
+ ];
20
+
21
+ return (
22
+ <aside className="w-64 min-w-64 flex flex-col justify-between border-r border-borderLight dark:border-borderDark bg-lightSidebar dark:bg-darkBg">
23
+ <div>
24
+ {/* Logo */}
25
+ <div className="flex items-center gap-3 px-6 py-8">
26
+ <div className="w-10 h-10 bg-accentCyan/20 rounded-xl flex items-center justify-center text-accentCyan shadow-glow-cyan border border-accentCyan/50">
27
+ <Bot size={24} />
28
+ </div>
29
+ <div>
30
+ <h1 className="font-bold text-lg leading-tight dark:text-darkText">
31
+ Support Agent
32
+ </h1>
33
+ <span className="text-xs text-gray-500 dark:text-gray-400">
34
+ AI-Powered Email
35
+ </span>
36
+ </div>
37
+ </div>
38
+
39
+ {/* Navigation */}
40
+ <nav className="px-4 flex flex-col gap-2 mt-4">
41
+ {routes.map((route) => (
42
+ <NavLink
43
+ key={route.path}
44
+ to={route.path}
45
+ className={({ isActive }: { isActive: boolean }) =>
46
+ `flex items-center gap-3 px-4 py-3 rounded-xl transition-all duration-200 border ${
47
+ isActive
48
+ ? "bg-accentCyan/10 text-accentCyan border-accentCyan/30 shadow-glow-cyan"
49
+ : "text-gray-600 dark:text-gray-400 border-transparent hover:bg-white dark:hover:bg-darkCard hover:text-gray-900 dark:hover:text-gray-200"
50
+ }`
51
+ }
52
+ >
53
+ <route.icon size={20} />
54
+ <span className="font-medium">{route.name}</span>
55
+ </NavLink>
56
+ ))}
57
+ </nav>
58
+ </div>
59
+
60
+ <div className="p-6 border-t border-borderLight dark:border-borderDark flex items-center justify-between">
61
+ <div className="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
62
+ <span className="relative flex h-3 w-3">
63
+ <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-accentGreen opacity-75"></span>
64
+ <span className="relative inline-flex rounded-full h-3 w-3 bg-accentGreen"></span>
65
+ </span>
66
+ System Online
67
+ </div>
68
+ <ThemeToggle />
69
+ </div>
70
+ </aside>
71
+ );
72
+ }
frontend/src/components/layout/ThemeToggle.tsx ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useThemeStore } from '../../store';
2
+ import { Moon, Sun } from 'lucide-react';
3
+
4
+ export default function ThemeToggle() {
5
+ const { theme, toggleTheme } = useThemeStore();
6
+
7
+ return (
8
+ <button
9
+ onClick={toggleTheme}
10
+ className="p-2 rounded-lg hover:bg-lightSidebar dark:hover:bg-darkCard transition-colors border border-borderLight dark:border-borderDark"
11
+ title="Toggle Theme"
12
+ aria-label="Toggle theme"
13
+ aria-pressed={theme === 'dark'}
14
+ >
15
+ {theme === 'dark' ? (
16
+ <Sun className="w-5 h-5 text-accentCyan" />
17
+ ) : (
18
+ <Moon className="w-5 h-5 text-accentCyan" />
19
+ )}
20
+ </button>
21
+ );
22
+ }
frontend/src/components/shared/KpiCard.tsx ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useMemo } from 'react';
2
+ import { LineChart, Line, ResponsiveContainer } from 'recharts';
3
+
4
+ interface KpiCardProps {
5
+ title: string;
6
+ value: string | number;
7
+ change: string;
8
+ trend: 'up' | 'down';
9
+ type: 'line' | 'progress' | 'gauge';
10
+ rawData?: number;
11
+ }
12
+
13
+ export default function KpiCard({ title, value, change, trend, type, rawData }: KpiCardProps) {
14
+ // Memoize sparkline data so it doesn't regenerate on every render
15
+ const sparklineData = useMemo(
16
+ () => Array.from({ length: 15 }, () => ({ val: Math.floor(Math.random() * 50) + 10 })),
17
+ []
18
+ );
19
+
20
+ const trendColor = trend === 'up' ? 'text-accentCyan' : 'text-accentRed';
21
+
22
+ return (
23
+ <div className="bg-lightBg dark:bg-darkCard border border-borderLight dark:border-borderDark rounded-2xl p-5 shadow-sm">
24
+ <div className="flex justify-between items-start mb-4">
25
+ <h3 className="text-gray-500 dark:text-gray-400 text-sm font-medium uppercase tracking-wider">{title}</h3>
26
+ <span className={`text-xs font-bold px-2 py-1 rounded bg-opacity-10 dark:bg-opacity-20 ${trendColor} ${
27
+ trend === 'up' ? 'bg-accentCyan' : 'bg-accentRed'
28
+ }`}>
29
+ {change}
30
+ </span>
31
+ </div>
32
+
33
+ <div className="flex items-end justify-between">
34
+ <div className="text-3xl font-bold dark:text-darkText">{value}</div>
35
+
36
+ <div className="h-12 w-24">
37
+ {type === 'line' && (
38
+ <ResponsiveContainer width="100%" height="100%">
39
+ <LineChart data={sparklineData}>
40
+ <Line type="monotone" dataKey="val" stroke="#06B6D4" strokeWidth={2} dot={false} />
41
+ </LineChart>
42
+ </ResponsiveContainer>
43
+ )}
44
+
45
+ {type === 'progress' && rawData !== undefined && (
46
+ <div className="flex items-center h-full">
47
+ <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2 overflow-hidden">
48
+ <div className="bg-accentCyan h-2 rounded-full shadow-glow-cyan" style={{ width: `${rawData}%` }}></div>
49
+ </div>
50
+ </div>
51
+ )}
52
+
53
+ {type === 'gauge' && rawData !== undefined && (
54
+ <div className="flex items-center justify-end h-full">
55
+ <div className="w-10 h-10 rounded-full border-4 border-gray-200 dark:border-gray-700 flex items-center justify-center relative">
56
+ <div className="absolute inset-0 rounded-full border-4 border-t-accentRed border-r-accentRed shadow-glow-red rotate-45"></div>
57
+ <span className="text-[10px] font-bold text-accentRed">{rawData}</span>
58
+ </div>
59
+ </div>
60
+ )}
61
+ </div>
62
+ </div>
63
+ </div>
64
+ );
65
+ }
frontend/src/index.css ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @tailwind base;
2
+ @tailwind components;
3
+ @tailwind utilities;
4
+
5
+ @layer base {
6
+ body {
7
+ @apply antialiased transition-colors duration-200;
8
+ }
9
+ }
10
+
11
+ /* React Flow custom node styles */
12
+ .react-flow__node {
13
+ @apply rounded-xl border transition-all;
14
+ }
15
+
16
+ .react-flow__handle {
17
+ @apply w-2 h-2 rounded-full border-none;
18
+ }
frontend/src/main.tsx ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { StrictMode } from 'react';
2
+ import { createRoot } from 'react-dom/client';
3
+ import axios from 'axios';
4
+ import App from './App.tsx';
5
+ import './index.css';
6
+
7
+ // Global API configuration
8
+ axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL || '';
9
+ axios.defaults.headers.common['X-API-Token'] = import.meta.env.VITE_API_TOKEN || '';
10
+
11
+ createRoot(document.getElementById('root')!).render(
12
+ <StrictMode>
13
+ <App />
14
+ </StrictMode>,
15
+ );
frontend/src/pages/Compose.tsx ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from 'react';
2
+ import { useNavigate } from 'react-router-dom';
3
+ import axios from 'axios';
4
+ import { Rocket, ClipboardList } from 'lucide-react';
5
+
6
+ const SAMPLES = [
7
+ {
8
+ sender: 'jane.smith@company.com',
9
+ subject: 'Double charge on my subscription',
10
+ body: 'Hi,\n\nI just checked my bank statement and it looks like I was charged twice for my Pro subscription this month — once on April 1st and again on April 3rd.\n\nThe amounts are $29.99 each. Can you please look into this and process a refund for the duplicate charge?\n\nThank you,\nJane'
11
+ },
12
+ {
13
+ sender: 'dev.team@startup.io',
14
+ subject: 'API returning 401 errors after key rotation',
15
+ body: 'Hello support,\n\nWe rotated our API keys yesterday following your documentation, but all our requests are now returning 401 Unauthorized errors.\n\nWe\'ve confirmed the new key is being sent in the Authorization header correctly. Our integration was working fine before the rotation.\n\nCan you help us debug this? It\'s blocking our production deployment.\n\nBest,\nMike from DevOps'
16
+ },
17
+ {
18
+ sender: 'alex.johnson@email.com',
19
+ subject: 'Cannot reset my password',
20
+ body: 'Hi there,\n\nI\'ve been trying to reset my password for the past hour but I never receive the reset email. I\'ve checked my spam folder and everything.\n\nMy account email is alex.johnson@email.com. I need to access my account urgently for a deadline.\n\nPlease help!\nAlex'
21
+ },
22
+ ];
23
+
24
+ export default function Compose() {
25
+ const navigate = useNavigate();
26
+ const [sampleIndex, setSampleIndex] = useState(0);
27
+ const [loading, setLoading] = useState(false);
28
+
29
+ const [formData, setFormData] = useState({
30
+ sender: '',
31
+ subject: '',
32
+ body: ''
33
+ });
34
+
35
+ const handleLoadSample = () => {
36
+ const sample = SAMPLES[sampleIndex % SAMPLES.length];
37
+ setFormData(sample);
38
+ setSampleIndex(prev => prev + 1);
39
+ };
40
+
41
+ const handleSubmit = async (e: React.FormEvent) => {
42
+ e.preventDefault();
43
+ if (!formData.sender || !formData.subject || !formData.body) return;
44
+
45
+ setLoading(true);
46
+ try {
47
+ const response = await axios.post('/api/v1/process-email', formData);
48
+ // Navigate to DetailedView to watch the nodes
49
+ navigate(`/ticket/${response.data.ticket_id}`);
50
+ } catch (err) {
51
+ console.error(err);
52
+ alert('Failed to process email. Check console.');
53
+ setLoading(false);
54
+ }
55
+ };
56
+
57
+ return (
58
+ <div className="h-full flex flex-col max-w-4xl mx-auto pb-8">
59
+ <header className="mb-6">
60
+ <h1 className="text-2xl font-bold dark:text-darkText">Test / Compose Mock Email</h1>
61
+ <p className="text-gray-500 dark:text-gray-400">Send a test email through the AI support pipeline and monitor the agent output in real-time.</p>
62
+ </header>
63
+
64
+ <div className="bg-lightBg dark:bg-darkCard border border-borderLight dark:border-borderDark rounded-2xl flex flex-col overflow-hidden shadow-sm">
65
+ <div className="p-5 border-b border-borderLight dark:border-borderDark bg-gray-50 dark:bg-[#1a212e]">
66
+ <h2 className="text-sm font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-widest flex items-center gap-2">
67
+ <span>📧</span> New Test Email
68
+ </h2>
69
+ </div>
70
+
71
+ <form onSubmit={handleSubmit} className="p-6 flex flex-col gap-6">
72
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
73
+ <div className="flex flex-col gap-2">
74
+ <label className="text-xs font-bold uppercase tracking-wider text-gray-500">From (Sender)</label>
75
+ <input
76
+ type="email"
77
+ required
78
+ placeholder="customer@example.com"
79
+ value={formData.sender}
80
+ onChange={e => setFormData({...formData, sender: e.target.value})}
81
+ className="w-full bg-[#F8FAFC] dark:bg-[#0D1117] text-gray-800 dark:text-[#A5D6FF] border border-borderLight dark:border-[#30363D] rounded-xl p-3 text-sm focus:outline-none focus:border-accentCyan transition-colors"
82
+ />
83
+ </div>
84
+ <div className="flex flex-col gap-2">
85
+ <label className="text-xs font-bold uppercase tracking-wider text-gray-500">Subject</label>
86
+ <input
87
+ type="text"
88
+ required
89
+ placeholder="e.g. Issue with my billing"
90
+ value={formData.subject}
91
+ onChange={e => setFormData({...formData, subject: e.target.value})}
92
+ className="w-full bg-[#F8FAFC] dark:bg-[#0D1117] text-gray-800 dark:text-[#A5D6FF] border border-borderLight dark:border-[#30363D] rounded-xl p-3 text-sm focus:outline-none focus:border-accentCyan transition-colors"
93
+ />
94
+ </div>
95
+ </div>
96
+
97
+ <div className="flex flex-col gap-2">
98
+ <label className="text-xs font-bold uppercase tracking-wider text-gray-500">Email Body</label>
99
+ <textarea
100
+ required
101
+ placeholder="Write the customer's email body here..."
102
+ value={formData.body}
103
+ onChange={e => setFormData({...formData, body: e.target.value})}
104
+ className="w-full h-48 bg-[#F8FAFC] dark:bg-[#0D1117] text-gray-800 dark:text-[#A5D6FF] border border-borderLight dark:border-[#30363D] rounded-xl p-4 text-sm leading-relaxed focus:outline-none focus:border-accentCyan transition-colors resize-none"
105
+ />
106
+ </div>
107
+
108
+ <div className="flex items-center gap-4 pt-4 border-t border-borderLight dark:border-borderDark">
109
+ <button
110
+ type="submit"
111
+ disabled={loading}
112
+ className="flex items-center gap-2 bg-accentCyan text-white px-6 py-2.5 rounded-lg font-bold shadow-glow-cyan hover:-translate-y-0.5 transition-transform disabled:opacity-50 disabled:cursor-not-allowed"
113
+ >
114
+ {loading ? (
115
+ <>
116
+ <span className="w-5 h-5 border-2 border-white/20 border-t-white rounded-full animate-spin" />
117
+ Processing...
118
+ </>
119
+ ) : (
120
+ <>
121
+ <Rocket size={18} /> Process Email
122
+ </>
123
+ )}
124
+ </button>
125
+
126
+ <button
127
+ type="button"
128
+ disabled={loading}
129
+ onClick={handleLoadSample}
130
+ className="flex items-center gap-2 bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 px-6 py-2.5 rounded-lg shadow-sm hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors disabled:opacity-50"
131
+ >
132
+ <ClipboardList size={18} /> Load Sample
133
+ </button>
134
+ </div>
135
+ </form>
136
+ </div>
137
+ </div>
138
+ );
139
+ }
frontend/src/pages/Dashboard.tsx ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect } from "react";
2
+ import axios from "axios";
3
+ import { RefreshCw } from "lucide-react";
4
+ import { useAppStore } from "../store";
5
+ import KpiCard from "../components/shared/KpiCard";
6
+ import WorkflowMonitor from "../components/dashboard/WorkflowMonitor";
7
+ import RecentActivityTable from "../components/dashboard/RecentActivityTable";
8
+
9
+ export default function Dashboard() {
10
+ const { kpis, setKpis, recentTickets, setRecentTickets } = useAppStore();
11
+
12
+ useEffect(() => {
13
+ // Fetch dashboard data
14
+ const fetchData = async () => {
15
+ try {
16
+ const [kpiRes, ticketsRes] = await Promise.all([
17
+ axios.get("/api/v1/kpis"),
18
+ axios.get("/api/v1/emails/recent?limit=8"),
19
+ ]);
20
+ setKpis(kpiRes.data);
21
+ setRecentTickets(ticketsRes.data?.tickets ?? []);
22
+ } catch (error) {
23
+ console.error("Failed to fetch dashboard data:", error);
24
+ }
25
+ };
26
+ fetchData();
27
+ const interval = setInterval(fetchData, 3000);
28
+ return () => clearInterval(interval);
29
+ }, [setKpis, setRecentTickets]);
30
+
31
+ const handleManualRefresh = () => {
32
+ axios
33
+ .get("/api/v1/kpis")
34
+ .then((res) => setKpis(res.data))
35
+ .catch((error) => console.error("Failed to refresh KPIs:", error));
36
+ axios
37
+ .get("/api/v1/emails/recent?limit=8")
38
+ .then((res) => setRecentTickets(res.data?.tickets ?? []))
39
+ .catch((error) => console.error("Failed to refresh tickets:", error));
40
+ };
41
+
42
+ return (
43
+ <div className="flex flex-col gap-6 max-w-7xl mx-auto h-full">
44
+ <header className="mb-2 flex justify-between items-end">
45
+ <div>
46
+ <h1 className="text-2xl font-bold dark:text-darkText">
47
+ Operations Dashboard
48
+ </h1>
49
+ <p className="text-gray-500 dark:text-gray-400">
50
+ Real-time overview of your support agent pipelines.
51
+ </p>
52
+ </div>
53
+ <button
54
+ onClick={handleManualRefresh}
55
+ className="p-2 border border-borderLight dark:border-borderDark rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
56
+ title="Refresh Data"
57
+ >
58
+ <RefreshCw size={18} className="text-gray-500 dark:text-gray-400" />
59
+ </button>
60
+ </header>
61
+
62
+ {/* KPI Cards */}
63
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
64
+ <KpiCard
65
+ title="Total Processed"
66
+ value={kpis?.kpis?.total_emails?.value ?? "0"}
67
+ change={kpis?.kpis?.total_emails?.change ?? "0%"}
68
+ trend={kpis?.kpis?.total_emails?.trend ?? "up"}
69
+ type="line"
70
+ />
71
+ <KpiCard
72
+ title="Avg. Resolution"
73
+ value={kpis?.kpis?.avg_resolution_time?.value ?? "0m"}
74
+ change={kpis?.kpis?.avg_resolution_time?.change ?? "0%"}
75
+ trend={kpis?.kpis?.avg_resolution_time?.trend ?? "down"}
76
+ type="line"
77
+ />
78
+ <KpiCard
79
+ title="Auto-Draft Success"
80
+ value={kpis?.kpis?.auto_draft_success?.value ?? "0%"}
81
+ change={kpis?.kpis?.auto_draft_success?.change ?? "0%"}
82
+ trend={kpis?.kpis?.auto_draft_success?.trend ?? "up"}
83
+ rawData={kpis?.kpis?.auto_draft_success?.raw_value ?? 0}
84
+ type="progress"
85
+ />
86
+ <KpiCard
87
+ title="Manual Escalations"
88
+ value={kpis?.kpis?.manual_escalations?.value ?? "0"}
89
+ change={kpis?.kpis?.manual_escalations?.change ?? "0%"}
90
+ trend={kpis?.kpis?.manual_escalations?.trend ?? "down"}
91
+ rawData={
92
+ kpis?.health?.classifier_confidence ?? 0
93
+ } /* mock visual for gauge */
94
+ type="gauge"
95
+ />
96
+ </div>
97
+
98
+ <div className="flex flex-col xl:flex-row gap-6 mt-4 flex-1 overflow-hidden">
99
+ {/* Left Column: Flow & System Health */}
100
+ <div className="xl:w-1/3 flex flex-col gap-6">
101
+ <WorkflowMonitor />
102
+ {/* System Health Component Inline */}
103
+ <div className="bg-lightBg dark:bg-darkCard border border-borderLight dark:border-borderDark rounded-2xl p-6 shadow-sm flex-1">
104
+ <h3 className="font-semibold dark:text-darkText mb-6">
105
+ Agent Quality Health
106
+ </h3>
107
+
108
+ <div className="space-y-6">
109
+ <div>
110
+ <div className="flex justify-between text-sm mb-2">
111
+ <span className="text-gray-500 dark:text-gray-400">
112
+ Classifier Confidence
113
+ </span>
114
+ <span className="font-mono text-accentCyan">
115
+ {kpis?.health?.classifier_confidence || "0"}%
116
+ </span>
117
+ </div>
118
+ <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-1.5 overflow-hidden">
119
+ <div
120
+ className="bg-accentCyan h-1.5 rounded-full"
121
+ style={{
122
+ width: `${kpis?.health?.classifier_confidence || 0}%`,
123
+ }}
124
+ ></div>
125
+ </div>
126
+ </div>
127
+
128
+ <div>
129
+ <div className="flex justify-between text-sm mb-2">
130
+ <span className="text-gray-500 dark:text-gray-400">
131
+ Retriever Precision
132
+ </span>
133
+ <span className="font-mono text-accentCyan">
134
+ {kpis?.health?.retriever_precision || "0"}%
135
+ </span>
136
+ </div>
137
+ <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-1.5 overflow-hidden">
138
+ <div
139
+ className="bg-accentCyan h-1.5 rounded-full"
140
+ style={{
141
+ width: `${kpis?.health?.retriever_precision || 0}%`,
142
+ }}
143
+ ></div>
144
+ </div>
145
+ </div>
146
+
147
+ <div>
148
+ <div className="flex justify-between text-sm mb-2">
149
+ <span className="text-gray-500 dark:text-gray-400">
150
+ Responder Quality
151
+ </span>
152
+ <span className="font-mono text-accentCyan">
153
+ {kpis?.health?.responder_quality || "0"}%
154
+ </span>
155
+ </div>
156
+ <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-1.5 overflow-hidden">
157
+ <div
158
+ className="bg-accentCyan h-1.5 rounded-full"
159
+ style={{
160
+ width: `${kpis?.health?.responder_quality || 0}%`,
161
+ }}
162
+ ></div>
163
+ </div>
164
+ </div>
165
+ </div>
166
+ </div>
167
+ </div>
168
+
169
+ {/* Right Column: Table */}
170
+ <RecentActivityTable tickets={recentTickets} />
171
+ </div>
172
+ </div>
173
+ );
174
+ }
frontend/src/pages/DetailedView.tsx ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useEffect } from 'react';
2
+ import { useParams, useNavigate } from 'react-router-dom';
3
+ import axios from 'axios';
4
+ import { Check, X, ArrowLeft, RefreshCw, Send, AlertTriangle } from 'lucide-react';
5
+
6
+ export default function DetailedView() {
7
+ const { id } = useParams();
8
+ const navigate = useNavigate();
9
+ const [ticket, setTicket] = useState<any>(null);
10
+ const [loading, setLoading] = useState(true);
11
+
12
+ // Fallback to latest pending ticket if no ID provided in the route (e.g., clicking on sidebar specific "review queue" equivalent)
13
+ const isRecentPath = id === 'recent';
14
+
15
+ useEffect(() => {
16
+ const fetchTicket = async () => {
17
+ setLoading(true);
18
+ try {
19
+ if (isRecentPath) {
20
+ const res = await axios.get('/api/v1/emails/recent?limit=1');
21
+ if (res.data.tickets.length > 0) setTicket(res.data.tickets[0]);
22
+ } else {
23
+ const res = await axios.get(`/api/v1/emails/${id}`);
24
+ setTicket(res.data);
25
+ }
26
+ } catch (e) {
27
+ console.error(e);
28
+ } finally {
29
+ setLoading(false);
30
+ }
31
+ };
32
+ fetchTicket();
33
+ }, [id, isRecentPath]);
34
+
35
+ if (loading) {
36
+ return <div className="flex h-full items-center justify-center"><RefreshCw className="animate-spin text-accentCyan" /></div>;
37
+ }
38
+
39
+ if (!ticket) {
40
+ return <div className="text-center p-12 text-gray-500">No ticket found or review queue empty.</div>;
41
+ }
42
+
43
+ const handleAction = async (action: 'approve' | 'reject') => {
44
+ try {
45
+ await axios.post(`/api/v1/review/${ticket.ticket_id}?action=${action}`);
46
+ navigate('/dashboard');
47
+ } catch (e) {
48
+ alert("Failed to process action. Ticket might not be pending review.");
49
+ }
50
+ };
51
+
52
+ return (
53
+ <div className="h-full flex flex-col max-w-[1600px] mx-auto pb-8">
54
+ <div className="flex items-center gap-4 mb-6">
55
+ <button onClick={() => navigate('/dashboard')} className="p-2 bg-lightBg dark:bg-darkCard rounded-xl hover:bg-gray-100 dark:hover:bg-gray-800 transition">
56
+ <ArrowLeft size={20} />
57
+ </button>
58
+ <div>
59
+ <h1 className="text-xl font-bold dark:text-darkText">Ticket Analysis #{ticket.ticket_id}</h1>
60
+ </div>
61
+ </div>
62
+
63
+ <div className="flex flex-col lg:flex-row gap-6 flex-1 overflow-hidden">
64
+ {/* Left Pane: Email Input */}
65
+ <div className="w-full lg:w-1/3 bg-lightBg dark:bg-darkCard border border-borderLight dark:border-borderDark rounded-2xl flex flex-col overflow-hidden">
66
+ <div className="p-4 border-b border-borderLight dark:border-borderDark bg-gray-50 dark:bg-[#1a212e]">
67
+ <h3 className="text-sm font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-widest">Input Email</h3>
68
+ </div>
69
+ <div className="p-6 flex-1 overflow-y-auto space-y-4">
70
+ <div>
71
+ <p className="text-xs text-gray-400 uppercase mb-1">From</p>
72
+ <p className="font-medium dark:text-darkText">{ticket.sender || 'Unknown'}</p>
73
+ </div>
74
+ <div>
75
+ <p className="text-xs text-gray-400 uppercase mb-1">Subject</p>
76
+ <p className="font-semibold text-lg dark:text-white">{ticket.subject || 'No Subject'}</p>
77
+ </div>
78
+ <div>
79
+ <p className="text-xs text-gray-400 uppercase mb-2">Body</p>
80
+ <div className="text-gray-600 dark:text-gray-300 whitespace-pre-wrap font-mono text-sm bg-gray-50 dark:bg-black/20 p-4 rounded-xl border border-gray-100 dark:border-gray-800">
81
+ {ticket.body || ''}
82
+ </div>
83
+ </div>
84
+ </div>
85
+ </div>
86
+
87
+ {/* Center Pane: AI Processing Log (Vertical Flow) */}
88
+ <div className="w-full lg:w-1/3 bg-lightBg dark:bg-darkCard border border-borderLight dark:border-borderDark rounded-2xl flex flex-col overflow-hidden relative">
89
+ <div className="p-4 border-b border-borderLight dark:border-borderDark bg-gray-50 dark:bg-[#1a212e]">
90
+ <h3 className="text-sm font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-widest">AI Processing Log</h3>
91
+ </div>
92
+ <div className="p-6 flex-1 overflow-y-auto">
93
+
94
+ {/* Flow Timeline */}
95
+ <div className="relative pl-6 space-y-8 before:absolute before:inset-0 before:ml-[11px] before:w-0.5 before:bg-gray-200 dark:before:bg-gray-800">
96
+
97
+ <div className="relative">
98
+ <div className="absolute -left-[30px] w-4 h-4 rounded-full bg-accentCyan ring-4 ring-lightBg dark:ring-darkCard shadow-glow-cyan z-10"></div>
99
+ <h4 className="font-semibold text-sm dark:text-darkText">Classifier</h4>
100
+ <div className="mt-2 bg-gray-50 dark:bg-black/20 p-3 rounded-lg border border-gray-100 dark:border-gray-800">
101
+ <div className="flex justify-between items-center mb-1 text-xs">
102
+ <span className="text-gray-500">Predicted Category</span>
103
+ <span className="text-accentCyan font-mono uppercase bg-accentCyan/10 px-2 rounded">{ticket.category}</span>
104
+ </div>
105
+ <div className="flex justify-between items-center text-xs">
106
+ <span className="text-gray-500">Confidence</span>
107
+ <span className="text-accentCyan font-mono text-xs">{ticket.confidence * 100}%</span>
108
+ </div>
109
+ </div>
110
+ </div>
111
+
112
+ <div className="relative">
113
+ <div className="absolute -left-[30px] w-4 h-4 rounded-full bg-accentCyan ring-4 ring-lightBg dark:ring-darkCard z-10"></div>
114
+ <h4 className="font-semibold text-sm dark:text-darkText">Retriever</h4>
115
+ <div className="mt-2 bg-gray-50 dark:bg-black/20 p-3 rounded-lg border border-gray-100 dark:border-gray-800">
116
+ <p className="text-xs text-gray-500 mb-2">Knowledge Base Chunks Retrieved:</p>
117
+ <ul className="text-xs space-y-2 dark:text-gray-300 list-disc pl-3">
118
+ {ticket.context?.map((chunk: string, i: number) => (
119
+ <li key={i} className="truncate" title={chunk}>{chunk.substring(0, 60)}...</li>
120
+ ))}
121
+ {(!ticket.context || ticket.context.length === 0) && <li>No specific context fetched.</li>}
122
+ </ul>
123
+ </div>
124
+ </div>
125
+
126
+ <div className="relative">
127
+ <div className={`absolute -left-[30px] w-4 h-4 rounded-full ${ticket.needs_escalation ? 'bg-accentRed shadow-glow-red' : 'bg-accentGreen'} ring-4 ring-lightBg dark:ring-darkCard z-10`}></div>
128
+ <h4 className="font-semibold text-sm dark:text-darkText">Escalation Evaluation</h4>
129
+ <div className="mt-2 bg-gray-50 dark:bg-black/20 p-3 rounded-lg border border-gray-100 dark:border-gray-800">
130
+ {ticket.needs_escalation ? (
131
+ <div className="text-accentRed text-xs font-medium space-y-1">
132
+ <p className="flex items-center gap-1"><AlertTriangle size={14}/> Escalation Triggered</p>
133
+ <p className="opacity-80 mt-1 italic">{ticket.escalation_reason}</p>
134
+ </div>
135
+ ) : (
136
+ <div className="text-accentGreen text-xs font-medium flex items-center gap-1">
137
+ <Check size={14} /> Auto-draft Approved by Guards
138
+ </div>
139
+ )}
140
+ </div>
141
+ </div>
142
+
143
+ </div>
144
+ </div>
145
+ </div>
146
+
147
+ {/* Right Pane: AI Draft & Action (Escalation Focus) */}
148
+ <div className="w-full lg:w-1/3 flex flex-col gap-6">
149
+ <div className="bg-lightBg dark:bg-darkCard border border-borderLight dark:border-borderDark rounded-2xl flex flex-col flex-1 overflow-hidden">
150
+ <div className="p-4 border-b border-borderLight dark:border-borderDark bg-gray-50 dark:bg-[#1a212e] flex justify-between items-center">
151
+ <h3 className="text-sm font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-widest">Draft Review & Action</h3>
152
+ <span className={`text-[10px] px-2 py-1 rounded-full uppercase font-bold tracking-wider ${ticket.status === 'pending_review' ? 'bg-accentRed/20 text-accentRed shadow-glow-red animate-pulse' : 'bg-gray-200 text-gray-500 dark:bg-gray-800'}`}>
153
+ {ticket.status.replace('_', ' ')}
154
+ </span>
155
+ </div>
156
+
157
+ <div className="p-6 flex-1 overflow-y-auto">
158
+ <div className="text-gray-800 dark:text-gray-200 whitespace-pre-wrap text-sm leading-relaxed font-sans">
159
+ {ticket.draft_response || ticket.final_response || <span className="italic opacity-50">No draft available.</span>}
160
+ </div>
161
+ </div>
162
+
163
+ <div className="p-4 border-t border-borderLight dark:border-borderDark bg-gray-50 dark:bg-[#1a212e]">
164
+ {ticket.status === 'pending_review' ? (
165
+ <div className="flex gap-3">
166
+ <button
167
+ onClick={() => handleAction('approve')}
168
+ className="flex-1 flex items-center justify-center gap-2 bg-accentGreen text-darkBg py-3 rounded-lg font-bold hover:bg-opacity-90 transition"
169
+ >
170
+ <Send size={18} /> Send Draft (Auto)
171
+ </button>
172
+ <button
173
+ onClick={() => handleAction('reject')}
174
+ className="flex-1 flex items-center justify-center gap-2 border border-accentRed text-accentRed py-3 rounded-lg font-bold hover:bg-accentRed/10 transition"
175
+ >
176
+ <X size={18} /> Reject
177
+ </button>
178
+ </div>
179
+ ) : (
180
+ <div className="text-center text-sm font-medium text-gray-500 py-2">
181
+ Action already taken on this ticket.
182
+ </div>
183
+ )}
184
+ </div>
185
+ </div>
186
+ </div>
187
+
188
+ </div>
189
+ </div>
190
+ );
191
+ }
frontend/src/pages/Inbox.tsx ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useEffect } from 'react';
2
+ import { useNavigate } from 'react-router-dom';
3
+ import axios from 'axios';
4
+ import { Search, Inbox as InboxIcon, RefreshCw } from 'lucide-react';
5
+ import { Ticket } from '../store';
6
+
7
+ // Helper to format badges based on the theme definitions
8
+ const getCategoryBadgeColor = (cat: string) => {
9
+ const category = cat.toLowerCase();
10
+ if (category === 'billing') return 'bg-amber-500/10 text-amber-500 border-amber-500/20';
11
+ if (category === 'technical') return 'bg-blue-500/10 text-blue-500 border-blue-500/20';
12
+ if (category === 'account') return 'bg-purple-500/10 text-purple-500 border-purple-500/20';
13
+ return 'bg-gray-500/10 text-gray-500 border-gray-500/20';
14
+ };
15
+
16
+ const getStatusBadgeColor = (status: string, needsEscalation: boolean) => {
17
+ if (needsEscalation && status === 'pending_review') return 'bg-accentRed/10 text-accentRed border-accentRed/20 shadow-glow-red';
18
+ if (status === 'rejected') return 'bg-accentRed/10 text-accentRed border-accentRed/20';
19
+ if (status === 'sent' || status === 'approved') return 'bg-accentGreen/10 text-accentGreen border-accentGreen/20';
20
+ return 'bg-gray-500/10 text-gray-500 border-gray-500/20';
21
+ };
22
+
23
+ function formatTime(isoString: string) {
24
+ if (!isoString) return '';
25
+ const date = new Date(isoString);
26
+ const now = new Date();
27
+ const diffMs = now.getTime() - date.getTime();
28
+ const diffMins = Math.floor(diffMs / 60000);
29
+
30
+ if (diffMins < 1) return 'Just now';
31
+ if (diffMins < 60) return `${diffMins}m ago`;
32
+
33
+ const diffHours = Math.floor(diffMins / 60);
34
+ if (diffHours < 24) return `${diffHours}h ago`;
35
+
36
+ return date.toLocaleDateString();
37
+ }
38
+
39
+ export default function Inbox() {
40
+ const navigate = useNavigate();
41
+ const [tickets, setTickets] = useState<Ticket[]>([]);
42
+ const [filteredTickets, setFilteredTickets] = useState<Ticket[]>([]);
43
+ const [loading, setLoading] = useState(true);
44
+ const [search, setSearch] = useState('');
45
+
46
+ const fetchEmails = async () => {
47
+ setLoading(true);
48
+ try {
49
+ const res = await axios.get('/api/v1/emails');
50
+ setTickets(res.data.tickets || []);
51
+ setFilteredTickets(res.data.tickets || []);
52
+ } catch (err) {
53
+ console.error('Failed to fetch emails', err);
54
+ } finally {
55
+ setLoading(false);
56
+ }
57
+ };
58
+
59
+ useEffect(() => {
60
+ fetchEmails();
61
+ }, []);
62
+
63
+ useEffect(() => {
64
+ const q = search.toLowerCase();
65
+ setFilteredTickets(
66
+ tickets.filter(t =>
67
+ t.sender?.toLowerCase().includes(q) ||
68
+ t.subject?.toLowerCase().includes(q) ||
69
+ t.category.toLowerCase().includes(q)
70
+ )
71
+ );
72
+ }, [search, tickets]);
73
+
74
+ return (
75
+ <div className="h-full flex flex-col max-w-6xl mx-auto pb-8">
76
+ <header className="mb-6 flex justify-between items-end">
77
+ <div>
78
+ <h1 className="text-2xl font-bold dark:text-darkText">Email Inbox</h1>
79
+ <p className="text-gray-500 dark:text-gray-400">Complete log of all processed support tickets.</p>
80
+ </div>
81
+ <div className="flex gap-4">
82
+ <div className="relative">
83
+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={16} />
84
+ <input
85
+ type="text"
86
+ placeholder="Search sender, subject, category..."
87
+ value={search}
88
+ onChange={(e) => setSearch(e.target.value)}
89
+ className="pl-10 pr-4 py-2 bg-lightBg dark:bg-darkCard border border-borderLight dark:border-borderDark rounded-lg text-sm w-80 focus:outline-none focus:border-accentCyan transition-colors dark:text-darkText"
90
+ />
91
+ </div>
92
+ <button
93
+ onClick={fetchEmails}
94
+ className="p-2 border border-borderLight dark:border-borderDark rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
95
+ title="Refresh"
96
+ >
97
+ <RefreshCw size={18} className="text-gray-500 dark:text-gray-400" />
98
+ </button>
99
+ </div>
100
+ </header>
101
+
102
+ <div className="bg-lightBg dark:bg-darkCard border border-borderLight dark:border-borderDark rounded-2xl flex flex-col overflow-hidden shadow-sm flex-1">
103
+ {loading ? (
104
+ <div className="flex-1 flex justify-center items-center">
105
+ <span className="w-8 h-8 border-4 border-gray-200 border-t-accentCyan rounded-full animate-spin" />
106
+ </div>
107
+ ) : filteredTickets.length === 0 ? (
108
+ <div className="flex-1 flex flex-col justify-center items-center text-gray-500 p-12">
109
+ <InboxIcon size={48} className="opacity-20 mb-4" />
110
+ <h3 className="text-lg font-semibold">No emails found</h3>
111
+ <p className="text-sm">We couldn't find any tickets matching your search.</p>
112
+ </div>
113
+ ) : (
114
+ <div className="flex-1 overflow-auto">
115
+ <table className="w-full text-sm text-left">
116
+ <thead className="bg-gray-50 dark:bg-[#1a212e] text-gray-500 dark:text-gray-400 sticky top-0 z-10 border-b border-borderLight dark:border-borderDark">
117
+ <tr>
118
+ <th className="px-6 py-4 font-medium uppercase tracking-wider text-xs">Sender</th>
119
+ <th className="px-6 py-4 font-medium uppercase tracking-wider text-xs">Subject</th>
120
+ <th className="px-6 py-4 font-medium uppercase tracking-wider text-xs">Category</th>
121
+ <th className="px-6 py-4 font-medium uppercase tracking-wider text-xs">Status</th>
122
+ <th className="px-6 py-4 font-medium uppercase tracking-wider text-xs text-right">Time</th>
123
+ </tr>
124
+ </thead>
125
+ <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
126
+ {filteredTickets.map((t) => (
127
+ <tr
128
+ key={t.ticket_id}
129
+ onClick={() => navigate(`/ticket/${t.ticket_id}`)}
130
+ className="hover:bg-gray-50 dark:hover:bg-[#374151] cursor-pointer transition-colors group"
131
+ >
132
+ <td className="px-6 py-4">
133
+ <div className="font-semibold dark:text-gray-200">{t.sender || 'Unknown'}</div>
134
+ <div className="font-mono text-[10px] text-gray-400 mt-1 uppercase tracking-wider">#{t.ticket_id}</div>
135
+ </td>
136
+ <td className="px-6 py-4 text-gray-600 dark:text-gray-300 max-w-sm truncate">
137
+ {t.subject || '(no subject)'}
138
+ </td>
139
+ <td className="px-6 py-4">
140
+ <span className={`px-2.5 py-1 rounded border text-[10px] font-bold uppercase tracking-wider ${getCategoryBadgeColor(t.category)}`}>
141
+ {t.category}
142
+ </span>
143
+ </td>
144
+ <td className="px-6 py-4">
145
+ <span className={`px-2.5 py-1 rounded border text-[10px] font-bold uppercase tracking-wider ${getStatusBadgeColor(t.status, t.needs_escalation)}`}>
146
+ {t.needs_escalation && t.status === 'pending_review' ? 'ESCALATED' : t.status.replace('_', ' ')}
147
+ </span>
148
+ </td>
149
+ <td className="px-6 py-4 text-right text-gray-400 text-xs">
150
+ {formatTime(t.created_at)}
151
+ </td>
152
+ </tr>
153
+ ))}
154
+ </tbody>
155
+ </table>
156
+ </div>
157
+ )}
158
+ </div>
159
+ </div>
160
+ );
161
+ }
frontend/src/pages/ReviewQueue.tsx ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useEffect } from 'react';
2
+ import { useNavigate } from 'react-router-dom';
3
+ import axios from 'axios';
4
+ import { ShieldCheck, AlertTriangle, Send, X } from 'lucide-react';
5
+
6
+ interface ReviewItem {
7
+ ticket_id: string;
8
+ category: string;
9
+ status: string;
10
+ escalation_reason: string;
11
+ draft_response: string;
12
+ sender?: string;
13
+ subject?: string;
14
+ body?: string;
15
+ created_at: string;
16
+ }
17
+
18
+ export default function ReviewQueue() {
19
+ const navigate = useNavigate();
20
+ const [tickets, setTickets] = useState<ReviewItem[]>([]);
21
+ const [loading, setLoading] = useState(true);
22
+
23
+ const fetchReviewQueue = async () => {
24
+ setLoading(true);
25
+ try {
26
+ const res = await axios.get('/api/v1/review');
27
+ setTickets(res.data.tickets || []);
28
+ } catch (err) {
29
+ console.error('Failed to fetch review queue', err);
30
+ } finally {
31
+ setLoading(false);
32
+ }
33
+ };
34
+
35
+ useEffect(() => {
36
+ fetchReviewQueue();
37
+ }, []);
38
+
39
+ const handleAction = async (ticketId: string, action: 'approve' | 'reject') => {
40
+ try {
41
+ await axios.post(`/api/v1/review/${ticketId}?action=${action}`);
42
+ // Refetch queue to remove the processed ticket
43
+ fetchReviewQueue();
44
+ } catch (e) {
45
+ alert("Failed to process action.");
46
+ }
47
+ };
48
+
49
+ return (
50
+ <div className="h-full flex flex-col max-w-5xl mx-auto pb-8">
51
+ <header className="mb-6 flex justify-between items-end">
52
+ <div>
53
+ <h1 className="text-2xl font-bold dark:text-darkText">Escalation Review Queue</h1>
54
+ <p className="text-gray-500 dark:text-gray-400">Emails flagged for manual intervention before sending.</p>
55
+ </div>
56
+ </header>
57
+
58
+ {loading ? (
59
+ <div className="flex-1 flex justify-center items-center">
60
+ <span className="w-8 h-8 border-4 border-gray-200 border-t-accentCyan rounded-full animate-spin" />
61
+ </div>
62
+ ) : tickets.length === 0 ? (
63
+ <div className="flex-1 flex flex-col justify-center items-center text-gray-500 p-12 bg-lightBg dark:bg-darkCard border border-borderLight dark:border-borderDark rounded-2xl shadow-sm">
64
+ <div className="w-20 h-20 rounded-full bg-accentGreen/10 flex items-center justify-center mb-6 shadow-glow-cyan border border-accentGreen/20">
65
+ <ShieldCheck size={40} className="text-accentGreen" />
66
+ </div>
67
+ <h3 className="text-xl font-bold dark:text-darkText mb-2">All clear!</h3>
68
+ <p className="text-center max-w-sm">No emails pending human review right now. The AI is handling everything perfectly.</p>
69
+ </div>
70
+ ) : (
71
+ <div className="flex flex-col gap-6 overflow-y-auto">
72
+ {tickets.map((t) => (
73
+ <div key={t.ticket_id} className="bg-lightBg dark:bg-darkCard border border-borderLight dark:border-borderDark rounded-2xl flex flex-col overflow-hidden shadow-sm hover:shadow-glow-cyan transition-shadow animation-fade-in">
74
+ <div className="p-5 border-b border-borderLight dark:border-borderDark bg-gray-50 dark:bg-[#1a212e] flex justify-between items-center">
75
+ <div className="flex items-center gap-3">
76
+ <h3 className="text-sm font-semibold dark:text-white uppercase tracking-wider">{t.subject || 'No Subject'}</h3>
77
+ <span className="px-2 py-0.5 rounded border border-gray-600 bg-gray-800 text-[10px] font-mono text-gray-300">#{t.ticket_id}</span>
78
+ </div>
79
+ <button onClick={() => navigate(`/ticket/${t.ticket_id}`)} className="text-xs font-bold text-accentCyan hover:underline uppercase tracking-wider">
80
+ Full Details
81
+ </button>
82
+ </div>
83
+
84
+ <div className="p-6 flex flex-col md:flex-row gap-8">
85
+ {/* Left: Esc info */}
86
+ <div className="w-full md:w-1/3 space-y-4">
87
+ <div>
88
+ <p className="text-xs text-gray-400 uppercase mb-1">From</p>
89
+ <p className="font-medium dark:text-darkText">{t.sender || 'Unknown'}</p>
90
+ </div>
91
+ <div>
92
+ <p className="text-xs text-accentRed uppercase font-bold mb-1 flex items-center gap-1">
93
+ <AlertTriangle size={14}/> Escalation Reason
94
+ </p>
95
+ <div className="text-sm bg-accentRed/5 border border-accentRed/20 p-3 rounded-lg dark:text-gray-300 leading-relaxed">
96
+ {t.escalation_reason}
97
+ </div>
98
+ </div>
99
+ </div>
100
+
101
+ {/* Right: Draft & Actions */}
102
+ <div className="w-full md:w-2/3 flex flex-col relative">
103
+ <p className="text-xs text-gray-500 uppercase tracking-widest font-bold mb-2">AI Draft Response</p>
104
+ <div className="flex-1 bg-[#F8FAFC] dark:bg-[#0D1117] border border-borderLight dark:border-[#30363D] rounded-xl p-4 text-sm leading-relaxed text-gray-800 dark:text-gray-300 whitespace-pre-wrap max-h-60 overflow-y-auto mb-4">
105
+ {t.draft_response || <span className="italic text-gray-500">No draft available.</span>}
106
+ </div>
107
+
108
+ <div className="flex items-center gap-4">
109
+ <button
110
+ onClick={() => handleAction(t.ticket_id, 'approve')}
111
+ className="flex-1 flex items-center justify-center gap-2 bg-accentGreen text-darkBg py-3 rounded-xl font-bold hover:bg-opacity-90 transition shadow-sm"
112
+ >
113
+ <Send size={18} /> Approve AI Draft
114
+ </button>
115
+ <button
116
+ onClick={() => handleAction(t.ticket_id, 'reject')}
117
+ className="flex items-center justify-center gap-2 border border-accentRed/50 hover:bg-accentRed/10 text-accentRed px-6 py-3 rounded-xl font-bold transition"
118
+ >
119
+ <X size={18} /> Reject
120
+ </button>
121
+ </div>
122
+ </div>
123
+ </div>
124
+ </div>
125
+ ))}
126
+ </div>
127
+ )}
128
+ </div>
129
+ );
130
+ }
frontend/src/pages/Settings.tsx ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState, useEffect } from 'react';
2
+ import axios from 'axios';
3
+ import { Database, FileText, Settings as SettingsIcon, Save } from 'lucide-react';
4
+
5
+ export default function Settings() {
6
+ const [config, setConfig] = useState<any>(null);
7
+
8
+ useEffect(() => {
9
+ const fetchConfig = async () => {
10
+ try {
11
+ const res = await axios.get('/api/v1/config');
12
+ setConfig(res.data);
13
+ } catch (e) {
14
+ console.error(e);
15
+ }
16
+ };
17
+ fetchConfig();
18
+ }, []);
19
+
20
+ if (!config) return <div className="p-10">Loading configuration...</div>;
21
+
22
+ return (
23
+ <div className="max-w-7xl mx-auto flex flex-col h-full gap-6 pb-8">
24
+ <header className="mb-2 flex justify-between items-end">
25
+ <div>
26
+ <h1 className="text-2xl font-bold dark:text-darkText">System Configuration</h1>
27
+ <p className="text-gray-500 dark:text-gray-400">Manage knowledge base and LLM prompt templates.</p>
28
+ </div>
29
+ <button className="flex items-center gap-2 bg-accentCyan text-white px-6 py-2.5 rounded-lg font-semibold shadow-glow-cyan hover:-translate-y-0.5 transition-transform">
30
+ <Save size={18} /> Save & Deploy
31
+ </button>
32
+ </header>
33
+
34
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 flex-1 min-h-0">
35
+ {/* Knowledge Base Config */}
36
+ <div className="bg-lightBg dark:bg-darkCard border border-borderLight dark:border-borderDark rounded-2xl flex flex-col overflow-hidden">
37
+ <div className="p-5 border-b border-borderLight dark:border-borderDark flex items-center gap-3">
38
+ <Database className="text-accentCyan" size={20} />
39
+ <h2 className="font-bold dark:text-darkText">Knowledge Base Visualizer</h2>
40
+ </div>
41
+
42
+ <div className="p-6">
43
+ <h3 className="text-sm font-semibold text-gray-500 mb-4 px-2">Data Sources</h3>
44
+ <div className="border border-borderLight dark:border-gray-700 rounded-xl overflow-hidden">
45
+ <table className="w-full text-sm text-left">
46
+ <thead className="bg-gray-50 dark:bg-gray-800 text-gray-500">
47
+ <tr>
48
+ <th className="px-4 py-3 font-medium">ID</th>
49
+ <th className="px-4 py-3 font-medium">Title</th>
50
+ <th className="px-4 py-3 font-medium">Last Updated</th>
51
+ </tr>
52
+ </thead>
53
+ <tbody>
54
+ {config.knowledge_base.map((kb: any) => (
55
+ <tr key={kb.id} className="border-t border-gray-100 dark:border-gray-700">
56
+ <td className="px-4 py-3 font-mono text-xs">{kb.id}</td>
57
+ <td className="px-4 py-3 font-medium dark:text-gray-200 flex items-center gap-2">
58
+ <FileText size={14} className="text-gray-400"/> {kb.title}
59
+ </td>
60
+ <td className="px-4 py-3 text-gray-500">{kb.updated}</td>
61
+ </tr>
62
+ ))}
63
+ </tbody>
64
+ </table>
65
+ </div>
66
+
67
+ <h3 className="text-sm font-semibold text-gray-500 mt-8 mb-4 px-2">Retriever Settings</h3>
68
+ <div className="space-y-6 px-2">
69
+ <div>
70
+ <div className="flex justify-between mb-2">
71
+ <span className="text-sm dark:text-gray-300">Top K Results</span>
72
+ <span className="text-sm font-mono text-accentCyan">{config.settings.top_k_results}</span>
73
+ </div>
74
+ <input type="range" min="1" max="10" defaultValue={config.settings.top_k_results} className="w-full accent-accentCyan"/>
75
+ </div>
76
+ <div>
77
+ <div className="flex justify-between mb-2">
78
+ <span className="text-sm dark:text-gray-300">Confidence Threshold</span>
79
+ <span className="text-sm font-mono text-accentCyan">{config.settings.confidence_threshold}</span>
80
+ </div>
81
+ <input type="range" min="0" max="1" step="0.05" defaultValue={config.settings.confidence_threshold} className="w-full accent-accentCyan"/>
82
+ </div>
83
+ </div>
84
+ </div>
85
+ </div>
86
+
87
+ {/* Prompt Management */}
88
+ <div className="bg-lightBg dark:bg-darkCard border border-borderLight dark:border-darkCard rounded-2xl flex flex-col overflow-hidden">
89
+ <div className="p-5 border-b border-borderLight dark:border-borderDark flex items-center justify-between">
90
+ <div className="flex items-center gap-3">
91
+ <SettingsIcon className="text-accentCyan" size={20} />
92
+ <h2 className="font-bold dark:text-darkText">LLM Prompt Management</h2>
93
+ </div>
94
+ <div className="text-xs px-2 py-1 bg-gray-100 dark:bg-gray-800 text-gray-500 rounded font-mono">Model: {config.settings.model_selection}</div>
95
+ </div>
96
+
97
+ <div className="flex-1 overflow-y-auto p-6 space-y-6">
98
+
99
+ <div className="space-y-2">
100
+ <label className="text-xs font-bold uppercase tracking-wider text-gray-500 flex justify-between">
101
+ <span>Classifier Prompt</span>
102
+ <span className="text-[10px] text-accentCyan bg-accentCyan/10 px-1 rounded">JSON Structuring</span>
103
+ </label>
104
+ <textarea
105
+ className="w-full h-32 bg-[#F8FAFC] dark:bg-[#0D1117] text-gray-800 dark:text-[#A5D6FF] border border-borderLight dark:border-[#30363D] rounded-xl p-4 font-mono text-xs leading-relaxed focus:outline-none focus:border-accentCyan transition-colors resize-none"
106
+ defaultValue={config.prompts.classifier}
107
+ />
108
+ </div>
109
+
110
+ <div className="space-y-2">
111
+ <label className="text-xs font-bold uppercase tracking-wider text-gray-500">Retriever Prompt</label>
112
+ <textarea
113
+ className="w-full h-32 bg-[#F8FAFC] dark:bg-[#0D1117] text-gray-800 dark:text-[#A5D6FF] border border-borderLight dark:border-[#30363D] rounded-xl p-4 font-mono text-xs leading-relaxed focus:outline-none focus:border-accentCyan transition-colors resize-none"
114
+ defaultValue={config.prompts.retriever}
115
+ />
116
+ </div>
117
+
118
+ <div className="space-y-2">
119
+ <label className="text-xs font-bold uppercase tracking-wider text-gray-500 flex justify-between">
120
+ <span>Responder Prompt</span>
121
+ <span className="text-[10px] text-accentGreen bg-accentGreen/10 px-1 rounded">Final Output Gen</span>
122
+ </label>
123
+ <textarea
124
+ className="w-full h-32 bg-[#F8FAFC] dark:bg-[#0D1117] text-gray-800 dark:text-[#A5D6FF] border border-borderLight dark:border-[#30363D] rounded-xl p-4 font-mono text-xs leading-relaxed focus:outline-none focus:border-accentCyan transition-colors resize-none"
125
+ defaultValue={config.prompts.responder}
126
+ />
127
+ </div>
128
+
129
+ </div>
130
+ </div>
131
+ </div>
132
+ </div>
133
+ );
134
+ }
frontend/src/store.ts ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { create } from 'zustand';
2
+
3
+ interface ThemeState {
4
+ theme: 'dark' | 'light';
5
+ toggleTheme: () => void;
6
+ }
7
+
8
+ export const useThemeStore = create<ThemeState>((set) => ({
9
+ theme: 'dark', // default theme
10
+ toggleTheme: () =>
11
+ set((state) => {
12
+ const newTheme = state.theme === 'dark' ? 'light' : 'dark';
13
+ // update html class for tailwind dark mode
14
+ if (newTheme === 'dark') {
15
+ document.documentElement.classList.add('dark');
16
+ } else {
17
+ document.documentElement.classList.remove('dark');
18
+ }
19
+ return { theme: newTheme };
20
+ }),
21
+ }));
22
+
23
+ // Basic types for the application data
24
+ export interface Ticket {
25
+ ticket_id: string;
26
+ category: string;
27
+ confidence: number;
28
+ status: string;
29
+ needs_escalation: boolean;
30
+ sender?: string;
31
+ subject?: string;
32
+ body?: string;
33
+ created_at: string;
34
+ }
35
+
36
+ type Trend = 'up' | 'down';
37
+
38
+ interface KpiMetric {
39
+ value: string | number;
40
+ change: string;
41
+ trend: Trend;
42
+ raw_value?: number;
43
+ }
44
+
45
+ export interface KpiResponse {
46
+ kpis?: {
47
+ total_emails?: KpiMetric;
48
+ avg_resolution_time?: KpiMetric;
49
+ auto_draft_success?: KpiMetric;
50
+ manual_escalations?: KpiMetric;
51
+ };
52
+ health?: {
53
+ classifier_confidence?: number;
54
+ retriever_precision?: number;
55
+ responder_quality?: number;
56
+ };
57
+ error?: string;
58
+ }
59
+
60
+ interface AppState {
61
+ recentTickets: Ticket[];
62
+ kpis: KpiResponse | null;
63
+ setRecentTickets: (tickets: Ticket[]) => void;
64
+ setKpis: (kpis: KpiResponse | null) => void;
65
+ }
66
+
67
+ export const useAppStore = create<AppState>((set) => ({
68
+ recentTickets: [],
69
+ kpis: null,
70
+ setRecentTickets: (tickets) => set({ recentTickets: tickets }),
71
+ setKpis: (kpis) => set({ kpis }),
72
+ }));
frontend/src/vite-env.d.ts ADDED
@@ -0,0 +1 @@
 
 
1
+ /// <reference types="vite/client" />
frontend/tailwind.config.js ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** @type {import('tailwindcss').Config} */
2
+ export default {
3
+ content: [
4
+ "./index.html",
5
+ "./src/**/*.{js,ts,jsx,tsx}",
6
+ ],
7
+ darkMode: 'class',
8
+ theme: {
9
+ extend: {
10
+ colors: {
11
+ darkBg: '#15191C',
12
+ darkCard: '#212936',
13
+ darkText: '#D1D5DB',
14
+ lightBg: '#FFFFFF',
15
+ lightSidebar: '#F3F4F6',
16
+ lightText: '#1F2937',
17
+ accentCyan: '#06B6D4',
18
+ accentGreen: '#4ADE80',
19
+ accentRed: '#EF4444',
20
+ borderDark: '#374151',
21
+ borderLight: '#E5E7EB',
22
+ },
23
+ boxShadow: {
24
+ 'glow-cyan': '0 0 15px rgba(6, 182, 212, 0.5)',
25
+ 'glow-red': '0 0 15px rgba(239, 68, 68, 0.5)',
26
+ }
27
+ },
28
+ },
29
+ plugins: [],
30
+ }
frontend/tsconfig.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "useDefineForClassFields": true,
5
+ "lib": ["ES2020", "DOM", "DOM.Iterable"],
6
+ "module": "ESNext",
7
+ "skipLibCheck": true,
8
+ "moduleResolution": "bundler",
9
+ "allowImportingTsExtensions": true,
10
+ "resolveJsonModule": true,
11
+ "isolatedModules": true,
12
+ "noEmit": true,
13
+ "jsx": "react-jsx",
14
+ "types": ["vite/client"],
15
+ "strict": true,
16
+ "noUnusedLocals": true,
17
+ "noUnusedParameters": true,
18
+ "noFallthroughCasesInSwitch": true,
19
+ "baseUrl": ".",
20
+ "paths": {
21
+ "@/*": ["./src/*"]
22
+ }
23
+ },
24
+ "include": ["src"],
25
+ "references": [{ "path": "./tsconfig.node.json" }]
26
+ }
frontend/tsconfig.node.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "composite": true,
4
+ "skipLibCheck": true,
5
+ "module": "ESNext",
6
+ "moduleResolution": "bundler",
7
+ "allowSyntheticDefaultImports": true
8
+ },
9
+ "include": ["vite.config.ts"]
10
+ }
frontend/vercel.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "rewrites": [
3
+ {
4
+ "source": "/(.*)",
5
+ "destination": "/index.html"
6
+ }
7
+ ]
8
+ }
frontend/vite.config.ts ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { defineConfig } from "vite";
2
+ import react from "@vitejs/plugin-react";
3
+
4
+ // https://vite.dev/config/
5
+ export default defineConfig({
6
+ plugins: [react()],
7
+ server: {
8
+ port: 5173,
9
+ proxy: {
10
+ "/api": {
11
+ target: "http://[IP_ADDRESS]",
12
+ changeOrigin: true,
13
+ },
14
+ },
15
+ },
16
+ });
knowledge_base/README.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Knowledge Base
2
+ #
3
+ # Place support articles, FAQ documents, and product documentation here.
4
+ # These files will be used by the retriever node to provide context for responses.
5
+ #
6
+ # Suggested structure:
7
+ # knowledge_base/
8
+ # ├── billing/
9
+ # ├── technical/
10
+ # ├── account/
11
+ # └── general/
knowledge_base/account.md ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Account Management — Knowledge Base
2
+
3
+ ## Password Reset
4
+
5
+ - Customers can reset their password at any time via **Forgot Password** on the login page.
6
+ - A password reset link is sent to the registered email and expires after **1 hour**.
7
+ - Passwords must be at least **12 characters** and include uppercase, lowercase, a number, and a special character.
8
+ - After a password reset, all active sessions are terminated and the customer must log in again.
9
+
10
+ ## Profile Updates
11
+
12
+ - Profile information (name, phone, timezone) can be updated at **Settings → Profile**.
13
+ - Email address changes require verification of the new address via a confirmation link.
14
+ - Changing the primary email does **not** affect the login email for SSO users — that is managed by the organisation's identity provider.
15
+
16
+ ## Account Deletion
17
+
18
+ - Customers can request account deletion from **Settings → Account → Delete Account**.
19
+ - Account deletion requires password confirmation and an optional feedback survey.
20
+ - Upon deletion, all data is **permanently removed within 30 days**. This action is irreversible.
21
+ - Organisation admins must transfer ownership before deleting their account if they are the sole admin.
22
+ - A **data export** is recommended before deletion: **Settings → Data → Export All**.
23
+
24
+ ## Two-Factor Authentication (2FA)
25
+
26
+ - 2FA can be enabled at **Settings → Security → Two-Factor Authentication**.
27
+ - Supported methods: **Authenticator app** (Google Authenticator, Authy) and **SMS** (Pro and Enterprise plans only).
28
+ - During setup, customers receive **10 one-time backup codes**. These should be stored securely.
29
+ - If a customer loses their 2FA device and backup codes, support can disable 2FA after identity verification (government-issued photo ID + verification of billing email).
30
+
31
+ ## Team & Organisation Management
32
+
33
+ - Organisation admins can invite team members at **Settings → Team → Invite Members**.
34
+ - Roles available: **Admin**, **Editor**, **Viewer**.
35
+ - Admins can manage team member permissions, transfer ownership, and remove members.
36
+ - Removed members lose access immediately but their created content is retained.
37
+
38
+ ## Data Export
39
+
40
+ - Full data exports are available in **JSON** or **CSV** format.
41
+ - Exports can be requested at **Settings → Data → Export** and typically complete within **1-24 hours** depending on data volume.
42
+ - Export download links expire after **7 days**.
knowledge_base/billing.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Billing & Payments — Knowledge Base
2
+
3
+ ## Refund Policy
4
+
5
+ - Customers can request a full refund within **30 days** of purchase.
6
+ - After 30 days, refunds are handled on a case-by-case basis and require manager approval.
7
+ - Refunds are processed back to the original payment method within **5-10 business days**.
8
+ - Partial refunds are available for annual plans if less than 3 months have been used.
9
+
10
+ ## Double-Charge / Duplicate Billing
11
+
12
+ - If a customer reports being charged twice, verify the transaction in the billing dashboard.
13
+ - Confirm whether one charge is a pre-authorisation hold (these drop off within 3-5 business days).
14
+ - If a genuine duplicate charge is confirmed, issue an immediate refund for the extra charge.
15
+ - Provide the customer with a refund confirmation number.
16
+
17
+ ## Subscription Plans
18
+
19
+ | Plan | Monthly Price | Annual Price | Features |
20
+ |------------|---------------|--------------|---------------------------------------|
21
+ | Starter | $9/mo | $89/yr | 1 user, 5 GB storage, email support |
22
+ | Pro | $29/mo | $279/yr | 5 users, 50 GB storage, priority support |
23
+ | Enterprise | Custom | Custom | Unlimited users, unlimited storage, dedicated account manager |
24
+
25
+ - Plan upgrades take effect immediately; the prorated difference is charged.
26
+ - Plan downgrades take effect at the next billing cycle.
27
+ - Customers can switch plans at any time from **Settings → Billing → Change Plan**.
28
+
29
+ ## Invoices & Receipts
30
+
31
+ - Invoices are emailed automatically after each payment.
32
+ - Past invoices can be downloaded from **Settings → Billing → Invoice History**.
33
+ - If a customer needs a corrected invoice (e.g., updated company name or VAT number), they can update their billing details and regenerate the invoice.
34
+
35
+ ## Payment Methods
36
+
37
+ - Accepted methods: Visa, Mastercard, American Express, PayPal, and bank transfer (Enterprise only).
38
+ - To update a payment method: **Settings → Billing → Payment Methods → Update**.
39
+ - If a payment fails, the system retries up to 3 times over 7 days before suspending the account.
40
+ - A grace period of **14 days** is given after suspension before data deletion.
41
+
42
+ ## Cancellation
43
+
44
+ - Accounts can be cancelled at any time from **Settings → Billing → Cancel Subscription**.
45
+ - Cancellation is effective at the end of the current billing period — the customer retains access until then.
46
+ - A **data export** option is available before cancellation under **Settings → Data → Export**.
47
+ - After cancellation, data is retained for **90 days** before permanent deletion.
knowledge_base/faiss_index/index.pkl ADDED
Binary file (14.6 kB). View file
 
knowledge_base/general.md ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # General Information — Knowledge Base
2
+
3
+ ## Business Hours & Support Availability
4
+
5
+ - **Email support**: Available 24/7. Response times:
6
+ - Starter plan: within **24 hours**
7
+ - Pro plan: within **4 hours**
8
+ - Enterprise plan: within **1 hour** (with dedicated account manager)
9
+ - **Live chat**: Monday–Friday, 9 AM–6 PM EST.
10
+ - **Phone support**: Available for Enterprise plan customers only. Contact your account manager for the direct line.
11
+
12
+ ## Contact Channels
13
+
14
+ - **Email**: support@example.com
15
+ - **Help Centre**: https://help.example.com
16
+ - **Community Forum**: https://community.example.com
17
+ - **Twitter / X**: @ExampleSupport (for non-sensitive enquiries only)
18
+ - **Status Page**: https://status.example.com (for real-time system status and incident updates)
19
+
20
+ ## Service Level Agreements (SLA)
21
+
22
+ | Severity | Description | Target Response | Target Resolution |
23
+ |------------|----------------------------------------------|-----------------|-------------------|
24
+ | Critical | Service completely down, all users affected | 15 minutes | 4 hours |
25
+ | High | Major feature broken, many users affected | 1 hour | 8 hours |
26
+ | Medium | Feature degraded, workaround available | 4 hours | 24 hours |
27
+ | Low | Minor issue, cosmetic, or feature request | 24 hours | Best effort |
28
+
29
+ - SLA clock runs during **business hours only** for Starter and Pro plans.
30
+ - Enterprise SLA runs **24/7**.
31
+
32
+ ## Feature Requests
33
+
34
+ - Customers can submit feature requests at **Help Centre → Feature Requests**.
35
+ - Feature requests are reviewed by the product team on a monthly basis.
36
+ - Popular requests (50+ votes) are fast-tracked for consideration.
37
+ - We do **not** provide ETAs for feature requests but customers are notified when a requested feature ships.
38
+
39
+ ## Privacy & Compliance
40
+
41
+ - We are **SOC 2 Type II** certified and **GDPR** compliant.
42
+ - Data is encrypted at rest (AES-256) and in transit (TLS 1.3).
43
+ - Customer data is hosted in **AWS US-East-1** (US customers) and **AWS EU-West-1** (EU customers).
44
+ - Data Processing Agreements (DPA) are available for Enterprise customers.
45
+ - For data subject access requests (DSAR), contact privacy@example.com.
46
+
47
+ ## System Requirements
48
+
49
+ - **Browsers**: Chrome 90+, Firefox 88+, Safari 15+, Edge 90+.
50
+ - **Mobile**: iOS 15+ (Safari), Android 12+ (Chrome).
51
+ - **API**: REST API with JSON payloads. SDKs available for Python, Node.js, Ruby, and Go.
knowledge_base/technical.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Technical Support — Knowledge Base
2
+
3
+ ## Login & Authentication Issues
4
+
5
+ - **"Invalid credentials" error**: Verify the email address and reset password via **Forgot Password** on the login page.
6
+ - **Account locked**: After 5 failed login attempts, the account is locked for 30 minutes. The customer can unlock it immediately via the email link sent automatically.
7
+ - **Two-factor authentication (2FA) issues**: If the customer has lost their 2FA device, they can use one of the **backup recovery codes** generated during 2FA setup. If all codes are lost, identity verification through support is required (government ID + billing email).
8
+ - **SSO login failures**: Ensure the organisation's SSO provider (Okta, Azure AD, Google Workspace) has the correct callback URL: `https://app.example.com/auth/sso/callback`.
9
+
10
+ ## API Errors
11
+
12
+ - **401 Unauthorised**: The API key is missing or invalid. Customers can regenerate keys at **Settings → API → Keys**.
13
+ - **403 Forbidden**: The API key does not have the required scope. Scopes can be updated in **Settings → API → Key Permissions**.
14
+ - **429 Too Many Requests**: Rate limit exceeded. Default limits: Starter = 100 req/min, Pro = 1000 req/min, Enterprise = 10,000 req/min.
15
+ - **500 Internal Server Error**: This indicates a server-side issue. Ask the customer to check our status page at `https://status.example.com` and retry after a few minutes. If persistent, escalate to the engineering team.
16
+
17
+ ## Performance Issues
18
+
19
+ - **Slow dashboard loading**: Ask the customer to clear their browser cache and try an incognito window. Supported browsers: Chrome 90+, Firefox 88+, Safari 15+, Edge 90+.
20
+ - **File upload timeouts**: Maximum file size is **100 MB** for Pro and **500 MB** for Enterprise. Starter plan has a **25 MB** limit. Large files should be uploaded via the API using multipart upload.
21
+ - **Data sync delays**: Real-time sync may experience delays of up to 5 minutes during peak hours. If delays exceed 15 minutes, escalate to the engineering team.
22
+
23
+ ## Integration Setup
24
+
25
+ - **Slack integration**: Install from **Settings → Integrations → Slack** and authorise the bot. Requires Slack workspace admin permissions.
26
+ - **Webhook configuration**: Webhooks can be configured at **Settings → Integrations → Webhooks**. Supported events: `ticket.created`, `ticket.updated`, `ticket.resolved`. Payloads are signed with HMAC-SHA256.
27
+ - **Zapier / Make (Integromat)**: Pre-built templates are available at `https://zapier.com/apps/example` and `https://make.com/en/integrations/example`.
28
+
29
+ ## Known Issues
30
+
31
+ - **Safari clipboard bug**: Copy-paste may not work correctly in Safari 16.x. Workaround: use keyboard shortcuts (Cmd+C/Cmd+V) instead of right-click context menu.
32
+ - **Dark mode rendering**: Some chart colours may have low contrast in dark mode. Fix scheduled for v2.5 release.
requirements.txt ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ===== Core AI / LLM =====
2
+ langchain>=0.3.0
3
+ langchain-openai>=0.3.0
4
+ langchain-community>=0.3.0
5
+ langchain-text-splitters>=0.3.0
6
+ langgraph>=0.4.0
7
+ openai>=1.60.0
8
+ faiss-cpu>=1.9.0
9
+
10
+ # ===== Web Framework =====
11
+ fastapi>=0.115.0
12
+ uvicorn[standard]>=0.34.0
13
+
14
+ # ===== Data Validation =====
15
+ pydantic>=2.10.0
16
+ pydantic-settings>=2.7.0
17
+
18
+ # ===== Database =====
19
+ supabase>=2.12.0
20
+ python-multipart>=0.0.12
21
+
22
+ # ===== Email Handling =====
23
+ imapclient>=3.0.1
24
+ aiosmtplib>=3.0.0
25
+
26
+ # ===== Environment & Config =====
27
+ python-dotenv>=1.1.0
28
+
29
+ # ===== Logging =====
30
+ loguru>=0.7.3
31
+
32
+ # ===== Testing =====
33
+ pytest>=8.3.0
34
+ pytest-asyncio>=0.25.0
35
+ httpx>=0.28.0
src/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # src package
src/api/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # api package
src/api/dependencies.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FastAPI dependency injection helpers.
3
+ """
4
+
5
+ from src.core.config import Settings, settings
6
+
7
+
8
+ def get_settings() -> Settings:
9
+ """FastAPI dependency that returns the app settings singleton."""
10
+ return settings
src/api/routes.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FastAPI routes for the Customer Support Email Agent.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import asyncio
8
+ import json
9
+ import os
10
+ import tempfile
11
+ import threading
12
+ import uuid
13
+ from datetime import datetime, timezone
14
+ from typing import Optional
15
+
16
+ from fastapi import APIRouter, HTTPException, Depends, Header
17
+ from loguru import logger
18
+
19
+ from src.core.config import settings
20
+ from src.graph.workflow import workflow
21
+ from src.schemas.email import IncomingEmail, OutgoingEmail
22
+ from src.schemas.state import SupportState, TicketStatus
23
+ from src.services.email_service import fetch_new_emails, send_reply
24
+ from src.utils.supabase_client import supabase
25
+
26
+ router = APIRouter(tags=["support"])
27
+
28
+
29
+ async def verify_token(x_api_token: str = Header(...)):
30
+ """Backend security middleware for private deployments."""
31
+ if x_api_token != settings.API_TOKEN:
32
+ raise HTTPException(status_code=403, detail="Invalid API Token")
33
+
34
+
35
+ def _redact_email(email_addr: str) -> str:
36
+ """Redact an email address for logging (e.g. j***@company.com)."""
37
+ if "@" not in email_addr:
38
+ return "***"
39
+ local, domain = email_addr.split("@", 1)
40
+ return f"{local[0]}***@{domain}" if local else f"***@{domain}"
41
+
42
+
43
+ def _generate_ticket_id() -> str:
44
+ """Generate a collision-resistant ticket ID (full UUID hex)."""
45
+ return uuid.uuid4().hex
46
+
47
+
48
+ def _redact_email(email_addr: str) -> str:
49
+ """Redact an email address for logging (e.g. j***@company.com)."""
50
+ if "@" not in email_addr:
51
+ return "***"
52
+ local, domain = email_addr.split("@", 1)
53
+ return f"{local[0]}***@{domain}" if local else f"***@{domain}"
54
+
55
+
56
+ async def _persist_ticket(email: IncomingEmail, result: dict) -> dict:
57
+ """Persist ticket data to Supabase."""
58
+ ticket_id = _generate_ticket_id()
59
+
60
+ # Map pydantic/dict result to DB schema
61
+ ticket_data = {
62
+ "ticket_id": ticket_id,
63
+ "sender": email.sender,
64
+ "subject": email.subject,
65
+ "body": email.body,
66
+ "message_id": email.message_id,
67
+ "received_at": email.received_at.isoformat(),
68
+ "category": result.get("category", "unknown"),
69
+ "confidence": result.get("confidence", 0.0),
70
+ "draft_response": result.get("draft_response", ""),
71
+ "final_response": result.get("final_response", ""),
72
+ "needs_escalation": result.get("needs_escalation", False),
73
+ "escalation_reason": result.get("escalation_reason", ""),
74
+ "follow_up_scheduled": result.get("follow_up_scheduled", False),
75
+ "status": result.get("status", "processing"),
76
+ "context": result.get("context", []),
77
+ "metadata": result.get("metadata", {}),
78
+ "created_at": datetime.now(timezone.utc).isoformat(),
79
+ }
80
+
81
+ try:
82
+ response = supabase.table("tickets").insert(ticket_data).execute()
83
+ return ticket_data
84
+ except Exception as e:
85
+ logger.error("Supabase insertion failed: {}", e)
86
+ # Raise HTTP exception so the frontend doesn't redirect to a missing ticket
87
+ raise HTTPException(status_code=500, detail=f"Database save failed: {str(e)}")
88
+
89
+
90
+
91
+ @router.post("/process-email", dependencies=[Depends(verify_token)])
92
+ async def process_email(email: IncomingEmail) -> dict:
93
+ """
94
+ Accept an incoming email and run it through the support agent graph.
95
+ Returns the agent's response and metadata.
96
+ """
97
+ logger.info("Processing email — ticket pipeline initiated")
98
+
99
+ initial_state = SupportState(email=email)
100
+ result = await workflow.ainvoke(initial_state)
101
+
102
+ ticket_record = await _persist_ticket(email, result)
103
+ return ticket_record
104
+
105
+
106
+ @router.get("/emails", dependencies=[Depends(verify_token)])
107
+ async def list_all_emails() -> dict:
108
+ """List all processed emails from Supabase."""
109
+ try:
110
+ response = (
111
+ supabase.table("tickets")
112
+ .select("*")
113
+ .order("created_at", desc=True)
114
+ .execute()
115
+ )
116
+ tickets = response.data
117
+ return {"total": len(tickets), "tickets": tickets}
118
+ except Exception as e:
119
+ logger.error("Supabase fetch failed: {}", e)
120
+ return {"total": 0, "tickets": [], "error": str(e)}
121
+
122
+
123
+ @router.get("/emails/recent", dependencies=[Depends(verify_token)])
124
+ async def get_recent_emails(limit: int = 10) -> dict:
125
+ """Get the N most recent emails for the recent activity table."""
126
+ try:
127
+ response = (
128
+ supabase.table("tickets")
129
+ .select("*")
130
+ .order("created_at", desc=True)
131
+ .limit(limit)
132
+ .execute()
133
+ )
134
+ tickets = response.data
135
+ return {"total": len(tickets), "tickets": tickets}
136
+ except Exception as e:
137
+ logger.error("Supabase fetch failed: {}", e)
138
+ return {"total": 0, "tickets": []}
139
+
140
+
141
+ @router.get("/emails/{ticket_id}", dependencies=[Depends(verify_token)])
142
+ async def get_email_details(ticket_id: str) -> dict:
143
+ """Get full details of a specific processed email."""
144
+ try:
145
+ response = (
146
+ supabase.table("tickets")
147
+ .select("*")
148
+ .eq("ticket_id", ticket_id)
149
+ .single()
150
+ .execute()
151
+ )
152
+ if not response.data:
153
+ raise HTTPException(
154
+ status_code=404, detail=f"Ticket '{ticket_id}' not found"
155
+ )
156
+ return response.data
157
+ except Exception:
158
+ raise HTTPException(status_code=404, detail=f"Ticket '{ticket_id}' not found")
159
+
160
+
161
+ @router.get("/kpis", dependencies=[Depends(verify_token)])
162
+ async def get_kpis() -> dict:
163
+ """Calculate and return system KPIs using Supabase analytics."""
164
+ try:
165
+ # Fetch all for simple calculation (HF Spaces CPU is fast enough for low volume)
166
+ response = (
167
+ supabase.table("tickets").select("needs_escalation, status").execute()
168
+ )
169
+ tickets = response.data
170
+ total_emails = len(tickets)
171
+
172
+ escalated = sum(1 for t in tickets if t.get("needs_escalation"))
173
+ sent_auto = sum(
174
+ 1
175
+ for t in tickets
176
+ if not t.get("needs_escalation")
177
+ and t.get("status") in ("sent", "processing")
178
+ )
179
+
180
+ auto_draft_success_rate = (
181
+ (sent_auto / total_emails * 100) if total_emails > 0 else 0
182
+ )
183
+
184
+ return {
185
+ "kpis": {
186
+ "total_emails": {
187
+ "value": total_emails,
188
+ "change": "+12%",
189
+ "trend": "up",
190
+ },
191
+ "avg_resolution_time": {
192
+ "value": "1.2m",
193
+ "change": "-15%",
194
+ "trend": "down",
195
+ },
196
+ "auto_draft_success": {
197
+ "value": f"{auto_draft_success_rate:.1f}%",
198
+ "raw_value": auto_draft_success_rate,
199
+ "change": "+2.4%",
200
+ "trend": "up",
201
+ },
202
+ "manual_escalations": {
203
+ "value": escalated,
204
+ "change": "-5%",
205
+ "trend": "down",
206
+ },
207
+ },
208
+ "health": {
209
+ "classifier_confidence": 92.5,
210
+ "retriever_precision": 88.0,
211
+ "responder_quality": 95.2,
212
+ },
213
+ }
214
+ except Exception as e:
215
+ logger.error("KPI calculation failed: {}", e)
216
+ return {
217
+ "error": "Failed to load dynamic KPIs",
218
+ "kpis": {
219
+ "total_emails": {"value": 0, "change": "0%", "trend": "up"},
220
+ "avg_resolution_time": {
221
+ "value": "0m",
222
+ "change": "0%",
223
+ "trend": "down",
224
+ },
225
+ "auto_draft_success": {
226
+ "value": "0%",
227
+ "raw_value": 0,
228
+ "change": "0%",
229
+ "trend": "up",
230
+ },
231
+ "manual_escalations": {
232
+ "value": 0,
233
+ "change": "0%",
234
+ "trend": "down",
235
+ },
236
+ },
237
+ "health": {
238
+ "classifier_confidence": 0,
239
+ "retriever_precision": 0,
240
+ "responder_quality": 0,
241
+ },
242
+ }
243
+
244
+
245
+ @router.get("/config", dependencies=[Depends(verify_token)])
246
+ async def get_system_config() -> dict:
247
+ """Return mock system configurations for the UI."""
248
+ return {
249
+ "knowledge_base": [
250
+ {
251
+ "id": "KB-001",
252
+ "title": "Billing Policies",
253
+ "updated": "2026-04-10",
254
+ "type": "Markdown",
255
+ },
256
+ {
257
+ "id": "KB-002",
258
+ "title": "API Documentation",
259
+ "updated": "2026-04-12",
260
+ "type": "Markdown",
261
+ },
262
+ {
263
+ "id": "KB-003",
264
+ "title": "Account Management",
265
+ "updated": "2026-04-05",
266
+ "type": "Markdown",
267
+ },
268
+ ],
269
+ "prompts": {
270
+ "classifier": "You are a senior support routing agent. Output ONLY JSON...",
271
+ "retriever": "Using the following context chunks, extract the relevance...",
272
+ "responder": "Draft a professional response to the user based on the context.",
273
+ },
274
+ "settings": {
275
+ "top_k_results": 3,
276
+ "confidence_threshold": 0.85,
277
+ "model_selection": settings.LLM_MODEL,
278
+ },
279
+ }
280
+
281
+
282
+ @router.post("/process-email-batch", dependencies=[Depends(verify_token)])
283
+ async def process_email_batch() -> dict:
284
+ """
285
+ Fetch unread emails from the IMAP mailbox and process each.
286
+ """
287
+ logger.info("Starting batch email processing")
288
+
289
+ emails = await fetch_new_emails()
290
+ if not emails:
291
+ return {"processed": 0, "message": "No new emails found"}
292
+
293
+ results = []
294
+ for email in emails:
295
+ try:
296
+ initial_state = SupportState(email=email)
297
+ result = await workflow.ainvoke(initial_state)
298
+ ticket_record = await _persist_ticket(email, result)
299
+ results.append(
300
+ {
301
+ "ticket_id": ticket_record["ticket_id"],
302
+ "status": ticket_record["status"],
303
+ "category": ticket_record["category"],
304
+ "needs_escalation": ticket_record["needs_escalation"],
305
+ }
306
+ )
307
+ except Exception as e:
308
+ logger.error("Failed to process batch email: {}", e)
309
+ results.append({"status": "error", "error": str(e)})
310
+
311
+ return {"processed": len(results), "results": results}
312
+
313
+
314
+ @router.get("/review", dependencies=[Depends(verify_token)])
315
+ async def list_escalated_tickets() -> dict:
316
+ """List all tickets pending human review from Supabase."""
317
+ try:
318
+ response = (
319
+ supabase.table("tickets")
320
+ .select("*")
321
+ .eq("needs_escalation", True)
322
+ .eq("status", "pending_review")
323
+ .execute()
324
+ )
325
+ return {"pending_count": len(response.data), "tickets": response.data}
326
+ except Exception as e:
327
+ logger.error("Escalation fetch failed: {}", e)
328
+ return {"pending_count": 0, "tickets": []}
329
+
330
+
331
+ @router.post("/review/{ticket_id}", dependencies=[Depends(verify_token)])
332
+ async def review_ticket(
333
+ ticket_id: str, action: str, revised_response: Optional[str] = None
334
+ ) -> dict:
335
+ """
336
+ Human review endpoint for escalated tickets.
337
+ """
338
+ try:
339
+ response = (
340
+ supabase.table("tickets")
341
+ .select("*")
342
+ .eq("ticket_id", ticket_id)
343
+ .single()
344
+ .execute()
345
+ )
346
+ ticket = response.data
347
+ except Exception:
348
+ raise HTTPException(status_code=404, detail=f"Ticket '{ticket_id}' not found")
349
+
350
+ if not ticket:
351
+ raise HTTPException(status_code=404, detail=f"Ticket '{ticket_id}' not found")
352
+
353
+ if ticket["status"] != "pending_review":
354
+ raise HTTPException(status_code=400, detail=f"Already {ticket['status']}")
355
+
356
+ if action not in ("approve", "reject"):
357
+ raise HTTPException(
358
+ status_code=400, detail="Action must be 'approve' or 'reject'"
359
+ )
360
+
361
+ # In Supabase, the email body/sender are top-level or in 'metadata' if we changed it.
362
+ # Given my _persist_ticket, they are top-level.
363
+
364
+ if action == "approve":
365
+ response_text = revised_response or ticket["draft_response"]
366
+ else:
367
+ if not revised_response:
368
+ supabase.table("tickets").update({"status": "rejected"}).eq(
369
+ "ticket_id", ticket_id
370
+ ).execute()
371
+ return {
372
+ "ticket_id": ticket_id,
373
+ "status": "rejected",
374
+ "message": "Ticket rejected",
375
+ }
376
+ response_text = revised_response
377
+
378
+ outgoing = OutgoingEmail(
379
+ to=ticket["sender"],
380
+ subject=f"Re: {ticket['subject']}",
381
+ body=response_text,
382
+ in_reply_to=ticket.get("message_id"),
383
+ )
384
+
385
+ try:
386
+ sent = await send_reply(outgoing)
387
+ new_status = "sent" if sent else "approved"
388
+
389
+ supabase.table("tickets").update(
390
+ {
391
+ "status": new_status,
392
+ "final_response": response_text,
393
+ "reviewed_at": datetime.now(timezone.utc).isoformat(),
394
+ }
395
+ ).eq("ticket_id", ticket_id).execute()
396
+
397
+ return {
398
+ "ticket_id": ticket_id,
399
+ "status": new_status,
400
+ "message": f"Response {'sent' if sent else 'approved'}",
401
+ }
402
+ except Exception as e:
403
+ logger.error("Failed to send reviewed reply: {}", e)
404
+ raise HTTPException(status_code=500, detail="Failed to send email")
405
+
406
+
407
+ @router.get("/follow-ups", dependencies=[Depends(verify_token)])
408
+ async def list_follow_ups() -> dict:
409
+ """List all scheduled follow-ups from Supabase."""
410
+ try:
411
+ response = (
412
+ supabase.table("tickets")
413
+ .select("*")
414
+ .eq("follow_up_scheduled", True)
415
+ .execute()
416
+ )
417
+ return {"pending_count": len(response.data), "follow_ups": response.data}
418
+ except Exception as e:
419
+ logger.error("Follow-up fetch failed: {}", e)
420
+ return {"pending_count": 0, "follow_ups": []}
src/core/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # core package
src/core/config.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Application configuration loaded from environment variables.
3
+ """
4
+
5
+ from pydantic import model_validator
6
+ from pydantic_settings import BaseSettings, SettingsConfigDict
7
+
8
+
9
+ class Settings(BaseSettings):
10
+ """Central application settings — loaded from .env file."""
11
+
12
+ model_config = SettingsConfigDict(
13
+ env_file=".env",
14
+ env_file_encoding="utf-8",
15
+ extra="ignore",
16
+ )
17
+
18
+ # --- LLM (OpenAI) ---
19
+ OPENAI_API_KEY: str = ""
20
+ LLM_BASE_URL: str = "https://api.openai.com/v1"
21
+ LLM_MODEL: str = "gpt-6-luna"
22
+ EMBEDDING_MODEL: str = "text-embedding-3-small"
23
+
24
+ # --- Email / IMAP ---
25
+ EMAIL_HOST: str = "imap.gmail.com"
26
+ EMAIL_PORT: int = 993
27
+ SMTP_HOST: str = "smtp.gmail.com"
28
+ SMTP_PORT: int = 587
29
+ EMAIL_USERNAME: str = ""
30
+ EMAIL_PASSWORD: str = ""
31
+
32
+ # --- Persistence (Supabase) ---
33
+ SUPABASE_URL: str = ""
34
+ SUPABASE_KEY: str = ""
35
+
36
+ # --- Security ---
37
+ # Secret token to protect the backend on public platforms (HF Spaces)
38
+ API_TOKEN: str = ""
39
+
40
+ # --- App ---
41
+ APP_ENV: str = "development"
42
+ LOG_LEVEL: str = "DEBUG"
43
+
44
+ @property
45
+ def DEBUG(self) -> bool:
46
+ return self.APP_ENV == "development"
47
+
48
+ @model_validator(mode="after")
49
+ def require_production_api_token(self) -> "Settings":
50
+ """Never start a production backend without an API token."""
51
+ if self.APP_ENV.lower() == "production" and not self.API_TOKEN.strip():
52
+ raise ValueError("API_TOKEN must be configured when APP_ENV=production")
53
+ return self
54
+
55
+
56
+ settings = Settings()
src/core/logging.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Logging configuration using loguru.
3
+ """
4
+
5
+ import sys
6
+
7
+ from loguru import logger
8
+
9
+ from src.core.config import settings
10
+
11
+
12
+ def setup_logging() -> None:
13
+ """Configure loguru logger for the application."""
14
+ logger.remove() # Remove default handler
15
+ logger.add(
16
+ sys.stderr,
17
+ level=settings.LOG_LEVEL,
18
+ format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level:<8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan> - <level>{message}</level>",
19
+ )
20
+ logger.info("Logging initialised (level={})", settings.LOG_LEVEL)
src/graph/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # graph package
src/graph/workflow.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LangGraph workflow definition for the Customer Support Email Agent.
3
+
4
+ Flow:
5
+ classify → retrieve → respond → check_escalation
6
+ │
7
+ ┌──────────┴──────────┐
8
+ escalate send_reply
9
+ (→ END) │
10
+ check_follow_up
11
+ │
12
+ END
13
+ """
14
+
15
+ from langgraph.graph import END, StateGraph
16
+
17
+ from src.nodes.classifier import classify_email
18
+ from src.nodes.escalation import check_escalation
19
+ from src.nodes.follow_up import check_follow_up
20
+ from src.nodes.responder import generate_response
21
+ from src.nodes.retriever import retrieve_context
22
+ from src.nodes.send_reply import send_email_reply
23
+ from src.schemas.state import SupportState
24
+
25
+
26
+ def should_escalate(state: SupportState) -> str:
27
+ """Conditional edge: route to escalation (human review) or auto-send."""
28
+ return "escalate" if state.needs_escalation else "send_reply"
29
+
30
+
31
+ def build_graph() -> StateGraph:
32
+ """
33
+ Construct and compile the support agent graph.
34
+
35
+ The graph implements the full pipeline:
36
+ 1. Classify the email intent
37
+ 2. Retrieve relevant knowledge base context
38
+ 3. Generate a draft response
39
+ 4. Check if human review is needed
40
+ - If yes: end (awaits human approval via API)
41
+ - If no: send the reply automatically
42
+ 5. Check if a follow-up should be scheduled
43
+ """
44
+ graph = StateGraph(SupportState)
45
+
46
+ # -- Add nodes --
47
+ graph.add_node("classify", classify_email)
48
+ graph.add_node("retrieve", retrieve_context)
49
+ graph.add_node("respond", generate_response)
50
+ graph.add_node("check_escalation", check_escalation)
51
+ graph.add_node("send_reply", send_email_reply)
52
+ graph.add_node("check_follow_up", check_follow_up)
53
+
54
+ # -- Define edges --
55
+ graph.set_entry_point("classify")
56
+ graph.add_edge("classify", "retrieve")
57
+ graph.add_edge("retrieve", "respond")
58
+ graph.add_edge("respond", "check_escalation")
59
+
60
+ # Conditional: escalate → END (human review), or auto-send
61
+ graph.add_conditional_edges(
62
+ "check_escalation",
63
+ should_escalate,
64
+ {
65
+ "escalate": END, # Stops here; human reviews via API
66
+ "send_reply": "send_reply",
67
+ },
68
+ )
69
+
70
+ # After sending, check for follow-up
71
+ graph.add_edge("send_reply", "check_follow_up")
72
+ graph.add_edge("check_follow_up", END)
73
+
74
+ return graph.compile()
75
+
76
+
77
+ # Pre-built compiled graph instance
78
+ workflow = build_graph()
src/main.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Customer Support Email Agent — FastAPI Application Entry Point
3
+ """
4
+
5
+ from pathlib import Path
6
+
7
+ from fastapi import FastAPI
8
+ from fastapi.staticfiles import StaticFiles
9
+ from fastapi.responses import FileResponse
10
+
11
+ from src.api.routes import router
12
+ from src.core.config import settings
13
+ from src.core.logging import setup_logging
14
+
15
+ # Resolve static directory
16
+ _STATIC_DIR = Path(__file__).resolve().parent.parent / "static"
17
+
18
+
19
+ def create_app() -> FastAPI:
20
+ """Application factory."""
21
+ setup_logging()
22
+
23
+ app = FastAPI(
24
+ title="Customer Support Email Agent",
25
+ description="AI-powered email support agent using LangGraph",
26
+ version="0.1.0",
27
+ debug=settings.DEBUG,
28
+ )
29
+
30
+ from fastapi.middleware.cors import CORSMiddleware
31
+ app.add_middleware(
32
+ CORSMiddleware,
33
+ allow_origins=["*"], # For production, we can refine this to the Vercel URL
34
+ allow_credentials=True,
35
+ allow_methods=["*"],
36
+ allow_headers=["*"],
37
+ )
38
+
39
+ app.include_router(router, prefix="/api/v1")
40
+
41
+ # Serve static files (CSS, JS, images)
42
+ if _STATIC_DIR.exists():
43
+ app.mount("/static", StaticFiles(directory=str(_STATIC_DIR)), name="static")
44
+
45
+ @app.get("/health")
46
+ async def health_check():
47
+ return {"status": "ok"}
48
+
49
+ @app.get("/")
50
+ async def serve_dashboard():
51
+ """Serve the main dashboard UI."""
52
+ return FileResponse(str(_STATIC_DIR / "index.html"))
53
+
54
+ return app
55
+
56
+
57
+ app = create_app()
src/nodes/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # nodes package
src/nodes/classifier.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Classifier node — categorises the incoming email using the LLM.
3
+ """
4
+
5
+ from loguru import logger
6
+
7
+ from src.prompts.templates import CLASSIFIER_PROMPT
8
+ from src.schemas.state import EmailCategory, SupportState
9
+ from src.services.llm_service import invoke_llm_json
10
+ from src.utils.security import sanitize_input
11
+
12
+
13
+ # Mapping of raw category strings to the EmailCategory enum
14
+ _CATEGORY_MAP = {
15
+ "billing": EmailCategory.BILLING,
16
+ "technical": EmailCategory.TECHNICAL,
17
+ "account": EmailCategory.ACCOUNT,
18
+ "general": EmailCategory.GENERAL,
19
+ }
20
+
21
+
22
+ async def classify_email(state: SupportState) -> dict:
23
+ """
24
+ Classify the incoming email into a support category.
25
+
26
+ Uses the LLM to determine the intent of the customer email,
27
+ returning the category, confidence score, and reasoning.
28
+ """
29
+ logger.info("Classifying email: {}", state.email.subject)
30
+
31
+ prompt = CLASSIFIER_PROMPT.format(
32
+ subject=sanitize_input(state.email.subject),
33
+ body=sanitize_input(state.email.body),
34
+ )
35
+
36
+ result = await invoke_llm_json(prompt)
37
+
38
+ # Extract and map category
39
+ raw_category = result.get("category", "general").lower().strip()
40
+ category = _CATEGORY_MAP.get(raw_category, EmailCategory.UNKNOWN)
41
+ confidence = float(result.get("confidence", 0.5))
42
+ reasoning = result.get("reasoning", "")
43
+
44
+ logger.info(
45
+ "Classified as '{}' (confidence={:.2f}): {}",
46
+ category.value,
47
+ confidence,
48
+ reasoning,
49
+ )
50
+
51
+ return {
52
+ "category": category,
53
+ "confidence": confidence,
54
+ "metadata": {**state.metadata, "classification_reasoning": reasoning},
55
+ }