Spaces:
Paused
Paused
dushyantsingh0 commited on
Commit ·
9f4dea0
1
Parent(s): d06854c
backend stabilization
Browse files- .gitignore +1 -1
- BACKEND_DIAGRAMS.md → docs/BACKEND_DIAGRAMS.md +0 -0
- docs/agents.md +170 -0
- docs/api.md +459 -0
- docs/architecture.md +211 -0
- docs/backend_insights/01_nexus_architecture.md +44 -0
- docs/backend_insights/02_hybrid_search.md +62 -0
- docs/backend_insights/03_multimodal_pipeline.md +43 -0
- docs/backend_insights/04_semantic_caching.md +64 -0
- docs/backend_insights/05_multi_tenant_governance.md +72 -0
- docs/backend_insights/06_ai_observability.md +57 -0
- docs/backend_insights/07_kb_ingestion.md +62 -0
- docs/backend_insights/08_triple_notification.md +76 -0
- docs/backend_insights/09_sla_enforcement.md +52 -0
- docs/backend_insights/10_agentic_workflows.md +75 -0
- docs/backend_insights/11_db_schema_design.md +73 -0
- docs/backend_insights/12_scaling_arq_workers.md +69 -0
- docs/backend_insights/13_realtime_sync.md +67 -0
- docs/backend_insights/14_architecture_enrichment.md +47 -0
- docs/backend_insights/15_performance_tuning.md +67 -0
- docs/deployment.md +197 -0
- docs/development.md +223 -0
- frontend/docs/nexus-customer-portal.jsx +623 -0
- frontend/docs/nexus-internal-dashboard.jsx +758 -0
- main.py +68 -2
- requirements.txt +3 -0
- templates/docs.html +225 -0
- templates/landing.html +12 -0
.gitignore
CHANGED
|
@@ -69,7 +69,7 @@ _cache/
|
|
| 69 |
Thumbs.db
|
| 70 |
|
| 71 |
# Documentation & Misc
|
| 72 |
-
docs/
|
| 73 |
node_modules/
|
| 74 |
**/node_modules/
|
| 75 |
**/dist/
|
|
|
|
| 69 |
Thumbs.db
|
| 70 |
|
| 71 |
# Documentation & Misc
|
| 72 |
+
docs/archive/
|
| 73 |
node_modules/
|
| 74 |
**/node_modules/
|
| 75 |
**/dist/
|
BACKEND_DIAGRAMS.md → docs/BACKEND_DIAGRAMS.md
RENAMED
|
File without changes
|
docs/agents.md
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AI Agents
|
| 2 |
+
|
| 3 |
+
Nexus uses [LangGraph](https://github.com/langchain-ai/langgraph) to orchestrate a master agent graph that handles all natural-language workspace queries. The graph is defined in `agents/nexus_master.py` and is invoked via `POST /api/v1/nexus/query/` and the streaming `POST /api/v1/nexus/stream/`.
|
| 4 |
+
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
## Master agent graph
|
| 8 |
+
|
| 9 |
+
```
|
| 10 |
+
User query
|
| 11 |
+
│
|
| 12 |
+
▼
|
| 13 |
+
┌─────────────────────────────────────────────────────────┐
|
| 14 |
+
│ NexusMasterGraph │
|
| 15 |
+
│ │
|
| 16 |
+
│ [entry] ──▶ intent_router │
|
| 17 |
+
│ │ │
|
| 18 |
+
│ ┌────────────┼────────────┬─────────────┐ │
|
| 19 |
+
│ ▼ ▼ ▼ ▼ │
|
| 20 |
+
│ kb_search ticket_ops analytics remediation │
|
| 21 |
+
│ │ │ │ │ │
|
| 22 |
+
│ └────────────┴────────────┴─────────────┘ │
|
| 23 |
+
│ │ │
|
| 24 |
+
│ response_synthesizer │
|
| 25 |
+
│ │ │
|
| 26 |
+
│ [RBAC output masking] │
|
| 27 |
+
│ │ │
|
| 28 |
+
└────────────────────────┼────────────────────────────────┘
|
| 29 |
+
▼
|
| 30 |
+
Structured response
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
### Nodes
|
| 34 |
+
|
| 35 |
+
| Node | File | Description |
|
| 36 |
+
|---|---|---|
|
| 37 |
+
| `intent_router` | `agents/routing.py` | Classifies the query and selects which sub-nodes to invoke. Uses a small structured-output LLM call. |
|
| 38 |
+
| `kb_search` | `agents/kb_node.py` | Semantic + keyword search over KB articles. Returns ranked chunks with article metadata. |
|
| 39 |
+
| `ticket_ops` | `agents/nexus_master.py` | Create, update, or query tickets on behalf of the user via the `create_ticket` and `search_tickets` tools. |
|
| 40 |
+
| `analytics` | `agents/analytics.py` | Runs aggregation queries (SLA, sentiment, volume trends) and formats a narrative answer. |
|
| 41 |
+
| `remediation` | `agents/remediation.py` | Suggests resolution steps based on similar past tickets and KB articles. |
|
| 42 |
+
| `response_synthesizer` | `agents/nexus_master.py` | Merges outputs from all invoked nodes into a single coherent response. Appends source citations. |
|
| 43 |
+
|
| 44 |
+
### State
|
| 45 |
+
|
| 46 |
+
The graph carries a typed `NexusState` dict across nodes:
|
| 47 |
+
|
| 48 |
+
```python
|
| 49 |
+
class NexusState(TypedDict):
|
| 50 |
+
messages: list[BaseMessage]
|
| 51 |
+
workspace_id: str
|
| 52 |
+
user_role: str
|
| 53 |
+
intent: str | None
|
| 54 |
+
kb_results: list[KBResult]
|
| 55 |
+
ticket_results: list[TicketResult]
|
| 56 |
+
analytics_data: dict | None
|
| 57 |
+
final_answer: str | None
|
| 58 |
+
sources: list[Source]
|
| 59 |
+
tokens_used: int
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
### Persistence (checkpointing)
|
| 63 |
+
|
| 64 |
+
Every interaction is checkpointed to `NexusCheckpoint` rows in PostgreSQL via `agents/nexus_checkpoint.py`. This lets conversations resume across HTTP requests using the `thread_id`. LangGraph's `SqliteSaver` interface is adapted to use the async SQLAlchemy session.
|
| 65 |
+
|
| 66 |
+
---
|
| 67 |
+
|
| 68 |
+
## Tools
|
| 69 |
+
|
| 70 |
+
Tools are defined in `agents/tools/nexus_tools.py` and registered with the LangGraph `ToolNode`.
|
| 71 |
+
|
| 72 |
+
| Tool | Description |
|
| 73 |
+
|---|---|
|
| 74 |
+
| `search_kb` | Vector + keyword KB search with workspace scope |
|
| 75 |
+
| `search_tickets` | Hybrid search across workspace tickets |
|
| 76 |
+
| `create_ticket` | Create a ticket on behalf of the user (CUSTOMER_* roles only) |
|
| 77 |
+
| `get_ticket_details` | Fetch a single ticket's full thread |
|
| 78 |
+
| `get_workspace_analytics` | Pull aggregated metrics for a time window |
|
| 79 |
+
| `analyze_sentiment` | Score a block of text using the LLM |
|
| 80 |
+
| `suggest_resolution` | Match a problem description to past resolutions |
|
| 81 |
+
|
| 82 |
+
LangChain built-in tools (e.g. `DuckDuckGoSearchRun`) are available but disabled by default — see `agents/tools/langchain_tools.py`.
|
| 83 |
+
|
| 84 |
+
---
|
| 85 |
+
|
| 86 |
+
## LLM providers
|
| 87 |
+
|
| 88 |
+
The agent layer supports multiple providers configured via environment variables:
|
| 89 |
+
|
| 90 |
+
| Variable | Default | Role |
|
| 91 |
+
|---|---|---|
|
| 92 |
+
| `AI_PROVIDER` | `anthropic` | Primary text generation |
|
| 93 |
+
| `AI_TEXT_PROVIDER` | `anthropic` | Overrides text provider for agent nodes |
|
| 94 |
+
| `AI_TEXT_EMBEDDING_PROVIDER` | `ollama` | Embedding generation |
|
| 95 |
+
| `AI_MODEL` | `claude-3-haiku-20240307` | Model ID for primary provider |
|
| 96 |
+
|
| 97 |
+
Provider resolution is centralised in `core/llm.py`, which returns a `BaseChatModel` regardless of the backend. Supported backends: Anthropic Claude, Ollama, Google Gemini, Azure OpenAI.
|
| 98 |
+
|
| 99 |
+
Embeddings always go through Ollama (`nomic-embed-text`, 768 dimensions) by default. To use a cloud embedding API, set `AI_TEXT_EMBEDDING_PROVIDER=anthropic` or `openai`.
|
| 100 |
+
|
| 101 |
+
---
|
| 102 |
+
|
| 103 |
+
## RBAC output masking
|
| 104 |
+
|
| 105 |
+
`agents/security.py` intercepts the synthesized response before it is returned to the API. It applies role-based field stripping:
|
| 106 |
+
|
| 107 |
+
| Field | CUSTOMER_* | SC_AGENT | SC_LEAD+ |
|
| 108 |
+
|---|---|---|---|
|
| 109 |
+
| Internal notes | Hidden | Visible | Visible |
|
| 110 |
+
| Agent assignment details | Hidden | Visible | Visible |
|
| 111 |
+
| SLA breach reasons | Hidden | Hidden | Visible |
|
| 112 |
+
| Personnel analytics | Hidden | Hidden | Visible |
|
| 113 |
+
| Raw LLM reasoning trace | Hidden | Hidden | SUPERADMIN only |
|
| 114 |
+
|
| 115 |
+
The masking is additive — each role sees a strict subset of higher roles.
|
| 116 |
+
|
| 117 |
+
---
|
| 118 |
+
|
| 119 |
+
## Background AI jobs
|
| 120 |
+
|
| 121 |
+
The heavy ARQ worker runs several AI jobs that feed agent quality over time:
|
| 122 |
+
|
| 123 |
+
### `auto_summarize_ticket` (`tasks/ai.py`)
|
| 124 |
+
Triggered after a ticket is created or significantly updated. Generates two summaries using the primary LLM:
|
| 125 |
+
- **Customer summary** — plain-language, no internal context.
|
| 126 |
+
- **Internal summary** — full context including agent notes and SLA metadata.
|
| 127 |
+
|
| 128 |
+
Both are stored in `Ticket.ai_metadata` as structured JSON.
|
| 129 |
+
|
| 130 |
+
### `crystallize_memory` (`tasks/ai.py`)
|
| 131 |
+
When a `NexusThread` exceeds a message threshold, this job compresses the conversation history into a `NexusMemory` record using an LLM summarization prompt. Future interactions load the memory instead of the full history, keeping context windows bounded.
|
| 132 |
+
|
| 133 |
+
### `index_kb_article` (`tasks/ai.py`)
|
| 134 |
+
After a KB article is created or updated:
|
| 135 |
+
1. Split into overlapping chunks (configurable size/overlap).
|
| 136 |
+
2. Embed each chunk via Ollama.
|
| 137 |
+
3. Upsert vectors into the pgvector `kb_article_chunks` table.
|
| 138 |
+
4. Update the article's TSVECTOR column for full-text search.
|
| 139 |
+
|
| 140 |
+
### `generate_workspace_insights` (`tasks/analytics.py`)
|
| 141 |
+
Runs every 6 hours per workspace. Aggregates ticket metrics, feeds them into a prompt, and stores the resulting markdown narrative in `WorkspaceInsight` for the dashboard.
|
| 142 |
+
|
| 143 |
+
### `harvest_expertise_task` (`tasks/nexus_ai.py`)
|
| 144 |
+
After ticket resolution, extracts structured knowledge (problem pattern + resolution steps) and creates or updates a `KnowledgeInsight` linked to the relevant KB article.
|
| 145 |
+
|
| 146 |
+
---
|
| 147 |
+
|
| 148 |
+
## Prompts
|
| 149 |
+
|
| 150 |
+
All prompts live in `agents/prompts.py` as versioned string templates. Key prompts:
|
| 151 |
+
|
| 152 |
+
| Prompt | Purpose |
|
| 153 |
+
|---|---|
|
| 154 |
+
| `INTENT_CLASSIFICATION_PROMPT` | Map user message → intent label |
|
| 155 |
+
| `KB_SYNTHESIS_PROMPT` | Merge KB chunks into a coherent answer |
|
| 156 |
+
| `TICKET_SUMMARY_CUSTOMER_PROMPT` | Customer-facing ticket summary |
|
| 157 |
+
| `TICKET_SUMMARY_INTERNAL_PROMPT` | Internal ticket summary with full context |
|
| 158 |
+
| `WORKSPACE_INSIGHT_PROMPT` | Narrative insights from aggregated metrics |
|
| 159 |
+
| `MEMORY_CRYSTALLIZATION_PROMPT` | Compress long conversation history |
|
| 160 |
+
|
| 161 |
+
Prompts are injected with workspace context (name, active projects, role) to ground the LLM in the workspace's domain.
|
| 162 |
+
|
| 163 |
+
---
|
| 164 |
+
|
| 165 |
+
## Further reading
|
| 166 |
+
|
| 167 |
+
- [Agentic workflows deep-dive](backend_insights/10_agentic_workflows.md)
|
| 168 |
+
- [KB ingestion pipeline](backend_insights/07_kb_ingestion.md)
|
| 169 |
+
- [AI observability](backend_insights/06_ai_observability.md)
|
| 170 |
+
- [Multimodal pipeline](backend_insights/03_multimodal_pipeline.md)
|
docs/api.md
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# API Reference
|
| 2 |
+
|
| 3 |
+
Base URL (production): `https://3scerror404-nexus.hf.space`
|
| 4 |
+
Base URL (local dev): `http://localhost:8000`
|
| 5 |
+
Interactive docs: `{base}/docs` (Swagger UI), `{base}/redoc`
|
| 6 |
+
|
| 7 |
+
All endpoints require `Authorization: Bearer <access_token>` unless marked **public**.
|
| 8 |
+
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
## Authentication (`/api/v1/auth`)
|
| 12 |
+
|
| 13 |
+
### `POST /api/v1/auth/register/`
|
| 14 |
+
**Public.** Create a new user account. If the workspace does not exist, it is provisioned automatically along with a local admin account.
|
| 15 |
+
|
| 16 |
+
**Body**
|
| 17 |
+
```json
|
| 18 |
+
{
|
| 19 |
+
"email": "user@example.com",
|
| 20 |
+
"password": "string",
|
| 21 |
+
"full_name": "string",
|
| 22 |
+
"workspace_name": "Acme Corp"
|
| 23 |
+
}
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
**Response `201`**
|
| 27 |
+
```json
|
| 28 |
+
{
|
| 29 |
+
"id": "uuid",
|
| 30 |
+
"email": "user@example.com",
|
| 31 |
+
"full_name": "string",
|
| 32 |
+
"workspace_id": "uuid",
|
| 33 |
+
"role": "CUSTOMER_USER"
|
| 34 |
+
}
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
---
|
| 38 |
+
|
| 39 |
+
### `POST /api/v1/auth/login/`
|
| 40 |
+
**Public.** Exchange credentials for JWT token pair.
|
| 41 |
+
|
| 42 |
+
**Body** `application/x-www-form-urlencoded`
|
| 43 |
+
```
|
| 44 |
+
username=user@example.com&password=secret
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
**Response `200`**
|
| 48 |
+
```json
|
| 49 |
+
{
|
| 50 |
+
"access_token": "eyJ...",
|
| 51 |
+
"refresh_token": "eyJ...",
|
| 52 |
+
"token_type": "bearer"
|
| 53 |
+
}
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
---
|
| 57 |
+
|
| 58 |
+
### `POST /api/v1/auth/refresh/`
|
| 59 |
+
Exchange a valid refresh token for a new access token.
|
| 60 |
+
|
| 61 |
+
**Body**
|
| 62 |
+
```json
|
| 63 |
+
{ "refresh_token": "eyJ..." }
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
**Response `200`** — same shape as `/login/`.
|
| 67 |
+
|
| 68 |
+
---
|
| 69 |
+
|
| 70 |
+
### `POST /api/v1/auth/logout/`
|
| 71 |
+
Revoke the current access token (adds JTI to Redis blocklist).
|
| 72 |
+
|
| 73 |
+
**Response `204`** No content.
|
| 74 |
+
|
| 75 |
+
---
|
| 76 |
+
|
| 77 |
+
### `POST /api/v1/auth/forgot-password/`
|
| 78 |
+
**Public.** Send a password-reset email via Resend.
|
| 79 |
+
|
| 80 |
+
**Body** `{ "email": "user@example.com" }`
|
| 81 |
+
|
| 82 |
+
**Response `200`** `{ "message": "Reset email sent" }`
|
| 83 |
+
|
| 84 |
+
---
|
| 85 |
+
|
| 86 |
+
### `POST /api/v1/auth/reset-password/`
|
| 87 |
+
**Public.** Complete password reset with the token from email.
|
| 88 |
+
|
| 89 |
+
**Body** `{ "token": "string", "new_password": "string" }`
|
| 90 |
+
|
| 91 |
+
**Response `200`** `{ "message": "Password updated" }`
|
| 92 |
+
|
| 93 |
+
---
|
| 94 |
+
|
| 95 |
+
## Tickets (`/api/v1/tickets`)
|
| 96 |
+
|
| 97 |
+
### `GET /api/v1/tickets/`
|
| 98 |
+
List tickets visible to the current user in their workspace.
|
| 99 |
+
|
| 100 |
+
**Query params**
|
| 101 |
+
| Param | Type | Description |
|
| 102 |
+
|---|---|---|
|
| 103 |
+
| `status` | string | Filter by status enum value |
|
| 104 |
+
| `priority` | string | Filter by priority (P0–P3) |
|
| 105 |
+
| `category` | string | Filter by category |
|
| 106 |
+
| `assigned_to` | uuid | Filter by assignee |
|
| 107 |
+
| `search` | string | Full-text keyword search |
|
| 108 |
+
|
| 109 |
+
**Response `200`** — array of ticket objects.
|
| 110 |
+
|
| 111 |
+
---
|
| 112 |
+
|
| 113 |
+
### `GET /api/v1/tickets/paginated/`
|
| 114 |
+
Paginated ticket list with the same filters as above.
|
| 115 |
+
|
| 116 |
+
**Query params** — all filters above, plus:
|
| 117 |
+
| Param | Type | Default |
|
| 118 |
+
|---|---|---|
|
| 119 |
+
| `page` | int | 1 |
|
| 120 |
+
| `page_size` | int | 20 |
|
| 121 |
+
| `sort_by` | string | `created_at` |
|
| 122 |
+
| `sort_dir` | string | `desc` |
|
| 123 |
+
|
| 124 |
+
**Response `200`**
|
| 125 |
+
```json
|
| 126 |
+
{
|
| 127 |
+
"items": [...],
|
| 128 |
+
"total": 142,
|
| 129 |
+
"page": 1,
|
| 130 |
+
"page_size": 20,
|
| 131 |
+
"pages": 8
|
| 132 |
+
}
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
---
|
| 136 |
+
|
| 137 |
+
### `GET /api/v1/tickets/search/`
|
| 138 |
+
Hybrid semantic + keyword search (pgvector + TSVECTOR).
|
| 139 |
+
|
| 140 |
+
**Query params** `q` (required) — natural-language query string.
|
| 141 |
+
|
| 142 |
+
**Response `200`** — ranked array of ticket objects with a `score` field.
|
| 143 |
+
|
| 144 |
+
---
|
| 145 |
+
|
| 146 |
+
### `POST /api/v1/tickets/`
|
| 147 |
+
Create a new ticket. Triggers background AI summarization and embedding jobs.
|
| 148 |
+
|
| 149 |
+
**Body**
|
| 150 |
+
```json
|
| 151 |
+
{
|
| 152 |
+
"title": "string",
|
| 153 |
+
"description": "string",
|
| 154 |
+
"priority": "P1",
|
| 155 |
+
"category": "string",
|
| 156 |
+
"project_id": "uuid"
|
| 157 |
+
}
|
| 158 |
+
```
|
| 159 |
+
|
| 160 |
+
**Response `201`** — full ticket object.
|
| 161 |
+
|
| 162 |
+
---
|
| 163 |
+
|
| 164 |
+
### `GET /api/v1/tickets/{ticket_id}/`
|
| 165 |
+
Fetch a single ticket. Field set is role-sanitized (customers omit internal notes).
|
| 166 |
+
|
| 167 |
+
---
|
| 168 |
+
|
| 169 |
+
### `PUT /api/v1/tickets/{ticket_id}/`
|
| 170 |
+
Update ticket fields. Partial update — only supplied fields are changed.
|
| 171 |
+
|
| 172 |
+
**Body** — any subset of ticket fields.
|
| 173 |
+
|
| 174 |
+
---
|
| 175 |
+
|
| 176 |
+
### `PUT /api/v1/tickets/{ticket_id}/status/`
|
| 177 |
+
Transition ticket status. Enforces valid state machine transitions.
|
| 178 |
+
|
| 179 |
+
**Body** `{ "status": "IN_PROGRESS", "note": "optional string" }`
|
| 180 |
+
|
| 181 |
+
Valid transitions:
|
| 182 |
+
```
|
| 183 |
+
OPEN → ACKNOWLEDGED → IN_PROGRESS → RESOLVED → CLOSED
|
| 184 |
+
↑_____________________|
|
| 185 |
+
```
|
| 186 |
+
|
| 187 |
+
---
|
| 188 |
+
|
| 189 |
+
### `PUT /api/v1/tickets/{ticket_id}/assign/`
|
| 190 |
+
Assign ticket to a staff user in the same workspace.
|
| 191 |
+
|
| 192 |
+
**Body** `{ "user_id": "uuid" }`
|
| 193 |
+
|
| 194 |
+
---
|
| 195 |
+
|
| 196 |
+
### `GET /api/v1/tickets/statuses/`
|
| 197 |
+
Return all valid status enum values.
|
| 198 |
+
|
| 199 |
+
### `GET /api/v1/tickets/priorities/`
|
| 200 |
+
Return all valid priority enum values (P0–P3) with SLA targets.
|
| 201 |
+
|
| 202 |
+
---
|
| 203 |
+
|
| 204 |
+
## Messages (`/api/v1/tickets/{ticket_id}/messages`)
|
| 205 |
+
|
| 206 |
+
### `GET /api/v1/tickets/{ticket_id}/messages/`
|
| 207 |
+
Fetch the message thread for a ticket. Internal messages are filtered out for CUSTOMER_* roles.
|
| 208 |
+
|
| 209 |
+
**Response `200`** — array of message objects.
|
| 210 |
+
|
| 211 |
+
---
|
| 212 |
+
|
| 213 |
+
### `POST /api/v1/tickets/{ticket_id}/messages/`
|
| 214 |
+
Add a message to a ticket thread. Triggers mention notification jobs.
|
| 215 |
+
|
| 216 |
+
**Body**
|
| 217 |
+
```json
|
| 218 |
+
{
|
| 219 |
+
"content": "string",
|
| 220 |
+
"is_internal": false,
|
| 221 |
+
"mentions": ["uuid"]
|
| 222 |
+
}
|
| 223 |
+
```
|
| 224 |
+
|
| 225 |
+
**Response `201`** — message object.
|
| 226 |
+
|
| 227 |
+
---
|
| 228 |
+
|
| 229 |
+
## Knowledge Base (`/api/v1/kb`)
|
| 230 |
+
|
| 231 |
+
### `POST /api/v1/kb/`
|
| 232 |
+
Create a KB article. Triggers background chunking + embedding indexing.
|
| 233 |
+
|
| 234 |
+
**Body**
|
| 235 |
+
```json
|
| 236 |
+
{
|
| 237 |
+
"title": "string",
|
| 238 |
+
"content": "string (markdown)",
|
| 239 |
+
"project_id": "uuid",
|
| 240 |
+
"tags": ["string"]
|
| 241 |
+
}
|
| 242 |
+
```
|
| 243 |
+
|
| 244 |
+
---
|
| 245 |
+
|
| 246 |
+
### `GET /api/v1/kb/`
|
| 247 |
+
List KB articles for the current workspace. Supports `?project_id=`, `?tag=`, `?page=`.
|
| 248 |
+
|
| 249 |
+
---
|
| 250 |
+
|
| 251 |
+
### `GET /api/v1/kb/{article_id}/`
|
| 252 |
+
Fetch a single article including version history.
|
| 253 |
+
|
| 254 |
+
---
|
| 255 |
+
|
| 256 |
+
### `PUT /api/v1/kb/{article_id}/`
|
| 257 |
+
Update an article. Creates a new version snapshot before applying changes.
|
| 258 |
+
|
| 259 |
+
---
|
| 260 |
+
|
| 261 |
+
### `DELETE /api/v1/kb/{article_id}/`
|
| 262 |
+
Soft-delete an article (sets `deleted_at`). Removes its chunks from the vector index.
|
| 263 |
+
|
| 264 |
+
---
|
| 265 |
+
|
| 266 |
+
### `GET /api/v1/kb/search/`
|
| 267 |
+
Semantic + keyword search across KB chunks.
|
| 268 |
+
|
| 269 |
+
**Query params** `q` (required), `project_id` (optional), `limit` (default 10).
|
| 270 |
+
|
| 271 |
+
**Response `200`** — array of `{ article, chunk, score }` objects.
|
| 272 |
+
|
| 273 |
+
---
|
| 274 |
+
|
| 275 |
+
### `POST /api/v1/kb/bulk-sync/`
|
| 276 |
+
Batch import articles from external sources. Deduplicates by `content_hash`.
|
| 277 |
+
|
| 278 |
+
**Body** — array of article objects.
|
| 279 |
+
|
| 280 |
+
**Response `202`** — `{ "queued": N }` — each article is indexed asynchronously.
|
| 281 |
+
|
| 282 |
+
---
|
| 283 |
+
|
| 284 |
+
## Nexus Master Agent (`/api/v1/nexus`)
|
| 285 |
+
|
| 286 |
+
### `POST /api/v1/nexus/query/`
|
| 287 |
+
Submit a natural-language query to the Nexus agent. The agent resolves intent, routes to the appropriate sub-node (KB search, ticket ops, analytics, remediation), and returns a structured response.
|
| 288 |
+
|
| 289 |
+
**Body**
|
| 290 |
+
```json
|
| 291 |
+
{
|
| 292 |
+
"message": "What are the top recurring issues this month?",
|
| 293 |
+
"thread_id": "uuid (optional — omit to start new thread)"
|
| 294 |
+
}
|
| 295 |
+
```
|
| 296 |
+
|
| 297 |
+
**Response `200`**
|
| 298 |
+
```json
|
| 299 |
+
{
|
| 300 |
+
"answer": "string",
|
| 301 |
+
"sources": [{ "type": "ticket|kb", "id": "uuid", "title": "string" }],
|
| 302 |
+
"thread_id": "uuid",
|
| 303 |
+
"tokens_used": 420
|
| 304 |
+
}
|
| 305 |
+
```
|
| 306 |
+
|
| 307 |
+
Response fields are RBAC-masked — customers receive a narrower answer than staff.
|
| 308 |
+
|
| 309 |
+
---
|
| 310 |
+
|
| 311 |
+
### `POST /api/v1/nexus/stream/`
|
| 312 |
+
Streaming variant of `/query/`. Returns `text/event-stream` (SSE). Each chunk is a delta string; the final chunk contains `sources` and `thread_id` metadata.
|
| 313 |
+
|
| 314 |
+
**Body** — same as `/query/`.
|
| 315 |
+
|
| 316 |
+
---
|
| 317 |
+
|
| 318 |
+
### `GET /api/v1/nexus/threads/{thread_id}/history/`
|
| 319 |
+
Return the full conversation history for a Nexus thread.
|
| 320 |
+
|
| 321 |
+
**Response `200`** — array of `{ role, content, created_at }` objects.
|
| 322 |
+
|
| 323 |
+
---
|
| 324 |
+
|
| 325 |
+
## Dashboard (`/api/v1/dashboard`)
|
| 326 |
+
|
| 327 |
+
### `GET /api/v1/dashboard/telemetry/`
|
| 328 |
+
Workspace ticket counts broken down by status, priority, and category for the current period.
|
| 329 |
+
|
| 330 |
+
**Response `200`**
|
| 331 |
+
```json
|
| 332 |
+
{
|
| 333 |
+
"by_status": { "OPEN": 14, "IN_PROGRESS": 6, ... },
|
| 334 |
+
"by_priority": { "P0": 2, "P1": 8, ... },
|
| 335 |
+
"by_category": { "Billing": 9, ... },
|
| 336 |
+
"sla_breached": 3,
|
| 337 |
+
"avg_resolution_hours": 4.2
|
| 338 |
+
}
|
| 339 |
+
```
|
| 340 |
+
|
| 341 |
+
---
|
| 342 |
+
|
| 343 |
+
### `GET /api/v1/dashboard/insights/`
|
| 344 |
+
AI-generated narrative insights for the workspace (generated by the heavy worker every 6 hours).
|
| 345 |
+
|
| 346 |
+
**Response `200`** `{ "insights": "string (markdown)" }`
|
| 347 |
+
|
| 348 |
+
---
|
| 349 |
+
|
| 350 |
+
### `GET /api/v1/dashboard/trends/`
|
| 351 |
+
Historical ticket volume and resolution time over the past 30 days.
|
| 352 |
+
|
| 353 |
+
**Query params** `?days=30` (default), `?granularity=day|week`.
|
| 354 |
+
|
| 355 |
+
---
|
| 356 |
+
|
| 357 |
+
## Reports (`/api/v1/reports`)
|
| 358 |
+
|
| 359 |
+
### `GET /api/v1/reports/sla-audit/`
|
| 360 |
+
All SLA breaches in the workspace for a given period.
|
| 361 |
+
|
| 362 |
+
**Query params** `?from=ISO8601&to=ISO8601&priority=P0`
|
| 363 |
+
|
| 364 |
+
---
|
| 365 |
+
|
| 366 |
+
### `GET /api/v1/reports/personnel/`
|
| 367 |
+
Per-agent metrics: tickets handled, avg resolution time, customer satisfaction score.
|
| 368 |
+
|
| 369 |
+
**Roles required**: SC_LEAD, SC_ADMIN, SUPERADMIN.
|
| 370 |
+
|
| 371 |
+
---
|
| 372 |
+
|
| 373 |
+
### `GET /api/v1/reports/sentiment/`
|
| 374 |
+
Sentiment distribution across ticket messages (positive / neutral / negative).
|
| 375 |
+
|
| 376 |
+
---
|
| 377 |
+
|
| 378 |
+
## Notifications (`/api/v1/notifications`)
|
| 379 |
+
|
| 380 |
+
### `GET /api/v1/notifications/`
|
| 381 |
+
List unread notifications for the current user.
|
| 382 |
+
|
| 383 |
+
### `POST /api/v1/notifications/{id}/read/`
|
| 384 |
+
Mark a notification as read.
|
| 385 |
+
|
| 386 |
+
### `POST /api/v1/notifications/read-all/`
|
| 387 |
+
Mark all notifications as read.
|
| 388 |
+
|
| 389 |
+
---
|
| 390 |
+
|
| 391 |
+
## System & admin
|
| 392 |
+
|
| 393 |
+
### `GET /api/v1/system/health/`
|
| 394 |
+
**Public.** Infrastructure health check.
|
| 395 |
+
|
| 396 |
+
**Response `200`**
|
| 397 |
+
```json
|
| 398 |
+
{
|
| 399 |
+
"status": "ok",
|
| 400 |
+
"db": "connected",
|
| 401 |
+
"redis": "connected",
|
| 402 |
+
"arq": "connected",
|
| 403 |
+
"version": "string"
|
| 404 |
+
}
|
| 405 |
+
```
|
| 406 |
+
|
| 407 |
+
---
|
| 408 |
+
|
| 409 |
+
### `GET /api/v1/worker/jobs/`
|
| 410 |
+
List active ARQ job records. Requires SC_ADMIN or higher.
|
| 411 |
+
|
| 412 |
+
---
|
| 413 |
+
|
| 414 |
+
## WebSockets (`/ws`)
|
| 415 |
+
|
| 416 |
+
### `WS /ws/{workspace_id}?token=<access_token>`
|
| 417 |
+
Subscribe to workspace-level real-time events. The token is validated on connection; invalid or revoked tokens close the socket with code 4001.
|
| 418 |
+
|
| 419 |
+
**Events received** (JSON)
|
| 420 |
+
```json
|
| 421 |
+
{ "type": "ticket.status_changed", "payload": { "ticket_id": "uuid", "new_status": "..." } }
|
| 422 |
+
{ "type": "ticket.created", "payload": { ... } }
|
| 423 |
+
{ "type": "sla.breach", "payload": { "ticket_id": "uuid", "priority": "P0" } }
|
| 424 |
+
{ "type": "insight.ready", "payload": { "summary": "..." } }
|
| 425 |
+
```
|
| 426 |
+
|
| 427 |
+
---
|
| 428 |
+
|
| 429 |
+
### `WS /ws/tickets/{ticket_id}?token=<access_token>`
|
| 430 |
+
Subscribe to a single ticket's thread. Fires on new messages and status changes.
|
| 431 |
+
|
| 432 |
+
**Events received**
|
| 433 |
+
```json
|
| 434 |
+
{ "type": "message.created", "payload": { "message_id": "uuid", "content": "..." } }
|
| 435 |
+
{ "type": "ticket.assigned", "payload": { "assignee_id": "uuid" } }
|
| 436 |
+
```
|
| 437 |
+
|
| 438 |
+
---
|
| 439 |
+
|
| 440 |
+
## Error responses
|
| 441 |
+
|
| 442 |
+
All errors follow the RFC 7807 problem format:
|
| 443 |
+
|
| 444 |
+
```json
|
| 445 |
+
{
|
| 446 |
+
"detail": "human-readable message"
|
| 447 |
+
}
|
| 448 |
+
```
|
| 449 |
+
|
| 450 |
+
| HTTP code | Meaning |
|
| 451 |
+
|---|---|
|
| 452 |
+
| `400` | Validation error or invalid state transition |
|
| 453 |
+
| `401` | Missing or expired token |
|
| 454 |
+
| `403` | Role does not have permission |
|
| 455 |
+
| `404` | Resource not found (workspace-scoped) |
|
| 456 |
+
| `409` | Conflict (e.g. duplicate content hash) |
|
| 457 |
+
| `422` | Pydantic schema validation failure |
|
| 458 |
+
| `429` | Rate limit exceeded |
|
| 459 |
+
| `500` | Unhandled server error (check logs) |
|
docs/architecture.md
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# System Architecture
|
| 2 |
+
|
| 3 |
+
## Overview
|
| 4 |
+
|
| 5 |
+
Nexus is structured as a monolith-in-a-container: a single Docker image runs the FastAPI API server, two ARQ background worker processes, an embedded Redis instance (for pub/sub), and the compiled React frontend served as static files. This keeps deployment simple while maintaining clean internal separation between layers.
|
| 6 |
+
|
| 7 |
+
```
|
| 8 |
+
┌─────────────────────────────────────────────────────────────┐
|
| 9 |
+
│ Docker Container │
|
| 10 |
+
│ │
|
| 11 |
+
│ ┌──────────────┐ ┌────────────────┐ ┌────────────────┐ │
|
| 12 |
+
│ │ Gunicorn │ │ ARQ Regular │ │ ARQ Heavy │ │
|
| 13 |
+
│ │ (4 uvicorn │ │ Worker │ │ Worker │ │
|
| 14 |
+
│ │ workers) │ │ (SLA, notify) │ │ (AI, embed) │ │
|
| 15 |
+
│ └──────┬───────┘ └───────┬────────┘ └───────┬────────┘ │
|
| 16 |
+
│ │ │ │ │
|
| 17 |
+
│ ┌──────▼──────────────────▼────────────────────▼────────┐ │
|
| 18 |
+
│ │ Local Redis (pub/sub, ephemeral) │ │
|
| 19 |
+
│ └───────────────────────────────────────────────────────┘ │
|
| 20 |
+
└──────────────────────────────┬──────────────────────────────┘
|
| 21 |
+
│
|
| 22 |
+
┌─────────────────┼─────────────────┐
|
| 23 |
+
│ │ │
|
| 24 |
+
┌───────▼──────┐ ┌───────▼──────┐ ┌──────▼───────┐
|
| 25 |
+
│ PostgreSQL │ │ Redis │ │ Ollama │
|
| 26 |
+
│ (Supabase/ │ │ (Upstash, │ │ (local, │
|
| 27 |
+
│ Neon) │ │ cloud) │ │ embeddings)│
|
| 28 |
+
└──────────────┘ └──────────────┘ └──────────────┘
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
---
|
| 32 |
+
|
| 33 |
+
## Layer responsibilities
|
| 34 |
+
|
| 35 |
+
### API layer (`api/v1/`)
|
| 36 |
+
|
| 37 |
+
Twenty FastAPI router modules handle HTTP and WebSocket traffic. Each router depends on `core/deps.py` for JWT validation and workspace-context resolution. Business logic is delegated to the services layer or directly to SQLAlchemy queries for simple CRUD. Routers never import from one another.
|
| 38 |
+
|
| 39 |
+
Key routers:
|
| 40 |
+
|
| 41 |
+
| Router | Lines | Responsibility |
|
| 42 |
+
|---|---|---|
|
| 43 |
+
| `auth.py` | 554 | Registration, login, refresh, password reset, admin provisioning |
|
| 44 |
+
| `tickets.py` | 267 | Ticket CRUD, status transitions, assignment |
|
| 45 |
+
| `messages.py` | 352 | Thread messages, internal/public flagging |
|
| 46 |
+
| `kb.py` | 1,213 | KB article CRUD, versioning, semantic search, bulk sync |
|
| 47 |
+
| `nexus.py` | 607 | Master agent query interface (RBAC-isolated) |
|
| 48 |
+
| `nexus_stream.py` | 222 | Streaming SSE responses for long AI operations |
|
| 49 |
+
| `dashboard.py` | 487 | Workspace telemetry and AI-generated insights |
|
| 50 |
+
| `reports.py` | 657 | SLA audit, personnel analytics, sentiment reports |
|
| 51 |
+
| `websockets.py` | 85 | WebSocket upgrade and pub/sub subscription |
|
| 52 |
+
|
| 53 |
+
### Services layer (`services/`)
|
| 54 |
+
|
| 55 |
+
Stateless async classes that encapsulate workspace-aware business logic. The `TicketService` handles hybrid search, role-based field sanitization (customers see different fields than staff), and telemetry aggregation. Services receive a `db: AsyncSession` via dependency injection and are the only layer that issues complex queries.
|
| 56 |
+
|
| 57 |
+
### Core infrastructure (`core/`)
|
| 58 |
+
|
| 59 |
+
| Module | Purpose |
|
| 60 |
+
|---|---|
|
| 61 |
+
| `config.py` | Pydantic `BaseSettings`; all env var parsing with computed URL properties |
|
| 62 |
+
| `database.py` | Two SQLAlchemy engine configs: `AsyncAdaptedQueuePool` (API, max 70) and `NullPool` (workers) |
|
| 63 |
+
| `deps.py` | FastAPI dependencies — JWT decode, workspace-context resolution, role gate |
|
| 64 |
+
| `security.py` | Password hashing (bcrypt), token generation, JTI-based revocation |
|
| 65 |
+
| `cache.py` | L1 in-process LRU (2 048 entries) + L2 Redis + semantic vector cache |
|
| 66 |
+
| `websockets.py` | Redis pub/sub manager; fanout to workspace and ticket-scoped channels |
|
| 67 |
+
| `permissions.py` | Role-hierarchy helpers used by route guards and agent output masking |
|
| 68 |
+
| `audit.py` | Append-only compliance log for sensitive actions |
|
| 69 |
+
| `observability.py` | OpenTelemetry OTLP tracing instrumentation |
|
| 70 |
+
|
| 71 |
+
### Models (`models/`)
|
| 72 |
+
|
| 73 |
+
Thirty SQLAlchemy models. All use UUID primary keys, UTC timestamps (`created_at`, `updated_at`), and a `deleted_at` soft-delete column. Key entities:
|
| 74 |
+
|
| 75 |
+
```
|
| 76 |
+
Workspace ──< UserWorkspace >── User
|
| 77 |
+
│
|
| 78 |
+
┌─────┴──────┐
|
| 79 |
+
Ticket NexusThread
|
| 80 |
+
│ │
|
| 81 |
+
┌──────┼────────┐ NexusInteraction
|
| 82 |
+
Message Attachment Escalation
|
| 83 |
+
│
|
| 84 |
+
Feedback
|
| 85 |
+
|
| 86 |
+
Project ──< KBArticle ──< KBArticleChunk
|
| 87 |
+
└──< KBArticleVersion
|
| 88 |
+
└──< KnowledgeInsight
|
| 89 |
+
|
| 90 |
+
WorkerJob NexusMemory NexusCheckpoint Notification
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
Search optimization on `Ticket` and `KBArticle`:
|
| 94 |
+
- `TSVECTOR` computed column + GIN index for full-text search
|
| 95 |
+
- `pgvector` column + HNSW index (768-dim) for semantic similarity
|
| 96 |
+
- `content_hash` for deduplication
|
| 97 |
+
|
| 98 |
+
---
|
| 99 |
+
|
| 100 |
+
## Request lifecycle
|
| 101 |
+
|
| 102 |
+
```
|
| 103 |
+
Client
|
| 104 |
+
│
|
| 105 |
+
▼
|
| 106 |
+
Gunicorn/Uvicorn
|
| 107 |
+
│
|
| 108 |
+
▼
|
| 109 |
+
FastAPI middleware stack
|
| 110 |
+
├─ Security headers (HSTS, CSP, X-Frame-Options)
|
| 111 |
+
├─ CORS (workspace-domain aware)
|
| 112 |
+
├─ GZip compression
|
| 113 |
+
└─ Trusted proxy (RFC-1918 forwarded headers)
|
| 114 |
+
│
|
| 115 |
+
▼
|
| 116 |
+
Router (api/v1/*.py)
|
| 117 |
+
├─ JWT decode → resolve workspace + role (core/deps.py)
|
| 118 |
+
├─ RBAC gate (core/permissions.py)
|
| 119 |
+
│
|
| 120 |
+
├─ [cache hit] → return L1/L2 cached response
|
| 121 |
+
│
|
| 122 |
+
├─ Service / direct DB query (AsyncSession)
|
| 123 |
+
│
|
| 124 |
+
├─ [side effects] → enqueue ARQ job (core/tasks.py)
|
| 125 |
+
│
|
| 126 |
+
└─ Return Pydantic schema response
|
| 127 |
+
```
|
| 128 |
+
|
| 129 |
+
---
|
| 130 |
+
|
| 131 |
+
## Caching strategy
|
| 132 |
+
|
| 133 |
+
Three layers operate in order:
|
| 134 |
+
|
| 135 |
+
1. **L1 — in-process LRU** (`core/cache.py`): LRU dict with 2 048 slots. Zero-latency for hot read paths (workspace metadata, KB article headers). Invalidated on write within the same process; other Gunicorn workers invalidate on next L2 miss.
|
| 136 |
+
|
| 137 |
+
2. **L2 — Redis** (Upstash): Serialized JSON with configurable TTLs. Used for search results, dashboard telemetry, and KB chunk metadata.
|
| 138 |
+
|
| 139 |
+
3. **Semantic cache** (`core/cache.py`): Stores LLM response + embedding for recent queries. Incoming query is embedded and compared against cached embeddings via cosine similarity threshold (≥ 0.92). A cache hit bypasses the LLM entirely.
|
| 140 |
+
|
| 141 |
+
Cache invalidation is write-through: mutations call `cache.invalidate(key)` which deletes from both L1 and L2.
|
| 142 |
+
|
| 143 |
+
---
|
| 144 |
+
|
| 145 |
+
## Real-time events (WebSocket pub/sub)
|
| 146 |
+
|
| 147 |
+
```
|
| 148 |
+
API write (e.g. new message)
|
| 149 |
+
│
|
| 150 |
+
▼
|
| 151 |
+
core/websockets.py ──publish──▶ Local Redis channel
|
| 152 |
+
│
|
| 153 |
+
┌────────▼────────┐
|
| 154 |
+
│ Subscriber loop │ (one per uvicorn worker)
|
| 155 |
+
└────────┬────────┘
|
| 156 |
+
│
|
| 157 |
+
┌─────────────┼─────────────┐
|
| 158 |
+
▼ ▼ ▼
|
| 159 |
+
WS client 1 WS client 2 WS client N
|
| 160 |
+
```
|
| 161 |
+
|
| 162 |
+
Two channel namespaces:
|
| 163 |
+
- `workspace:{workspace_id}` — workspace-wide events (ticket status, SLA alerts, insight ready)
|
| 164 |
+
- `ticket:{ticket_id}` — thread-level events (new message, assignment change)
|
| 165 |
+
|
| 166 |
+
Local Redis (not Upstash) is used for pub/sub because it requires a persistent TCP connection. Upstash's HTTP-based Redis does not support `SUBSCRIBE`.
|
| 167 |
+
|
| 168 |
+
---
|
| 169 |
+
|
| 170 |
+
## Background workers (ARQ)
|
| 171 |
+
|
| 172 |
+
Two independent worker processes read from separate ARQ queues:
|
| 173 |
+
|
| 174 |
+
**Regular worker** — high concurrency, sub-second jobs:
|
| 175 |
+
- `monitor_sla_thresholds` (cron, every 5 min)
|
| 176 |
+
- `notify_mentions` (on-demand)
|
| 177 |
+
- `record_system_heartbeat` (cron, every 30 s)
|
| 178 |
+
- `send_triple_notification` (on-demand, batch)
|
| 179 |
+
|
| 180 |
+
**Heavy worker** — concurrency 1–2, 120 s timeout:
|
| 181 |
+
- `auto_summarize_ticket` — dual LLM summaries (customer-facing + internal)
|
| 182 |
+
- `index_kb_article` — chunk, embed, and HNSW-index a KB article
|
| 183 |
+
- `crystallize_memory` — LLM summarization of long agent conversation histories
|
| 184 |
+
- `generate_workspace_insights` — aggregate analytics → LLM narrative
|
| 185 |
+
- `harvest_expertise_task` — extract structured knowledge from resolved tickets
|
| 186 |
+
|
| 187 |
+
Job deduplication: a Redis-backed latch in `tasks/system.py` prevents the same job type from queuing twice for the same entity.
|
| 188 |
+
|
| 189 |
+
---
|
| 190 |
+
|
| 191 |
+
## Security model
|
| 192 |
+
|
| 193 |
+
- **Transport**: TLS terminated at the reverse proxy (HF Spaces / Railway ingress).
|
| 194 |
+
- **Auth**: JWT HS256 with access (60 min) + refresh (7 day) token pair. Logout stores the JTI in Redis with matching TTL (token blocklist).
|
| 195 |
+
- **RBAC**: Roles resolved per-workspace from `UserWorkspace.role`. Six roles in hierarchy: `SUPERADMIN > SC_ADMIN > SC_LEAD > SC_AGENT > CUSTOMER_ADMIN > CUSTOMER_USER`.
|
| 196 |
+
- **Workspace isolation**: All DB queries are scoped by `workspace_id` extracted from the JWT. Customers cannot read staff-internal fields (sanitized in `TicketService`).
|
| 197 |
+
- **Agent output masking**: `agents/security.py` strips sensitive fields from LLM responses based on the requesting user's role before the response is returned.
|
| 198 |
+
- **Input validation**: Pydantic schemas at every boundary; SQLAlchemy parameterized queries prevent SQL injection.
|
| 199 |
+
- **Audit log**: `core/audit.py` appends an immutable record for sensitive operations.
|
| 200 |
+
|
| 201 |
+
---
|
| 202 |
+
|
| 203 |
+
## Further reading
|
| 204 |
+
|
| 205 |
+
- [Hybrid search design](backend_insights/02_hybrid_search.md)
|
| 206 |
+
- [Semantic caching](backend_insights/04_semantic_caching.md)
|
| 207 |
+
- [Multi-tenant governance](backend_insights/05_multi_tenant_governance.md)
|
| 208 |
+
- [Real-time sync](backend_insights/13_realtime_sync.md)
|
| 209 |
+
- [DB schema design](backend_insights/11_db_schema_design.md)
|
| 210 |
+
- [ARQ worker scaling](backend_insights/12_scaling_arq_workers.md)
|
| 211 |
+
- [SLA enforcement](backend_insights/09_sla_enforcement.md)
|
docs/backend_insights/01_nexus_architecture.md
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Nexus Architecture: The Dual-Persona Backend
|
| 2 |
+
|
| 3 |
+
The Nexus Master Gateway is designed as a high-fidelity support platform that seamlessly handles both customer-facing interactions and internal staff operations through a unified, dual-persona architecture.
|
| 4 |
+
|
| 5 |
+
## Core Philosophical Alignment
|
| 6 |
+
|
| 7 |
+
Nexus isn't just a ticketing system; it's a **contextual gateway**. It sits between the user (customer or agent) and a suite of AI-driven tools. The architecture is built on three pillars:
|
| 8 |
+
1. **Isolated Personas**: Strict separation of internal metadata vs. customer-facing summaries.
|
| 9 |
+
2. **Agentic Orchestration**: Background AI workflows process tickets while keeping API responses fast.
|
| 10 |
+
3. **Multimodal Grounding**: LLM calls can include images from ticket attachments for richer context.
|
| 11 |
+
|
| 12 |
+
## The Service Layer Hierarchy
|
| 13 |
+
|
| 14 |
+
Nexus uses a layered FastAPI structure to ensure scalability and maintainability:
|
| 15 |
+
|
| 16 |
+
```mermaid
|
| 17 |
+
graph TD
|
| 18 |
+
UI[Frontend: Apps/Internal & Apps/Customer] --> API[FastAPI Gateway: api/v1/]
|
| 19 |
+
API --> Middleware[Governance Layer: Auth, RBAC, BOLA]
|
| 20 |
+
Middleware --> Services[Service Logic: Search, Tickets, KB]
|
| 21 |
+
Services --> Agents[AI Workflows: LangGraph & LLMs]
|
| 22 |
+
Services --> DB[(PostgreSQL: pgvector & FTS)]
|
| 23 |
+
Services --> Workers[Arq Background Workers: Redis]
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
### 1. The API Surface (`api/v1/`)
|
| 27 |
+
Our routers are partitioned by domain (e.g., `tickets.py`, `kb.py`, `messages.py`). Every endpoint is protected by a multi-layered dependency injection system defined in `core/deps.py`:
|
| 28 |
+
- `get_current_user`: Handles JWT validation and session hydration.
|
| 29 |
+
- `require_roles` / `require_staff` / `require_admin`: Enforce RBAC at the entry point.
|
| 30 |
+
- Workspace context is extracted from the JWT payload and threaded through every query — there is no separate `workspace_isolation` middleware dependency.
|
| 31 |
+
|
| 32 |
+
### 2. Dual-Persona Responses
|
| 33 |
+
A critical feature of Nexus is how we sanitize data. Staff members need technical metadata; customers need high-level summaries. This is handled at the **Response Model** level using separate Pydantic schemas (`TicketResponse` vs `TicketInternalResponse`) selected based on the resolved user role.
|
| 34 |
+
|
| 35 |
+
### 3. The Orchestration Layer
|
| 36 |
+
When a ticket is created or a message is sent, the backend writes core data and enqueues background jobs via `tasks/system.py::enqueue_task`. This keeps API response times fast while the AI works in the background. Key background jobs include `auto_summarize_ticket`, `generate_ticket_embedding`, `index_kb_article`, and `run_ai_workflow` (from `agents/workflow.py`).
|
| 37 |
+
|
| 38 |
+
## Key Technical Facts
|
| 39 |
+
|
| 40 |
+
- **Workflow Step Tracing**: Steps taken during AI processing are recorded via `core/observability.py::record_workflow_step`, which writes to a dedicated observability model. Job lifecycle (start/end/duration/status) is tracked in the `worker_jobs` table via `on_job_start` / `on_job_end` hooks in `nexus_worker.py`.
|
| 41 |
+
- **Triple-Redis Architecture**: Three Redis roles are used: (1) **ARQ queue** (`ARQ_REDIS_URL`, Upstash) for job orchestration, (2) **search cache** (`CACHE_REDIS_URL`, Upstash) for L2 caching, and (3) **local pub/sub** (`LOCAL_REDIS_URL`, persistent TCP) for WebSocket fan-out. The local Redis is a sidecar inside the container and cannot be replaced with Upstash's HTTP-based Redis because pub/sub requires a persistent connection.
|
| 42 |
+
- **Proactive SLA Monitoring**: The regular worker runs `monitor_sla_thresholds` (cron: `minute={0, 30}`), `nexus_pulse_check` (cron: `minute={15, 45}`), and `ai_dynamic_nudge_pulse` to detect and respond to SLA risks before they become breaches.
|
| 43 |
+
|
| 44 |
+
Next, we'll dive into how the **Search Engine** unifies these components into a single source of truth.
|
docs/backend_insights/02_hybrid_search.md
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hybrid Search Intelligence: Unifying Semantic and Keyword Retrieval
|
| 2 |
+
|
| 3 |
+
Nexus implements a two-branch Hybrid Search engine that solves the "fidelity gap" in technical support by combining vector similarity search with full-text keyword matching. The two approaches are complementary: semantics handles intent and paraphrasing, while keywords handle exact technical terms and error codes.
|
| 4 |
+
|
| 5 |
+
## The Retrieval Paradox
|
| 6 |
+
|
| 7 |
+
In a technical workspace, search queries are often messy:
|
| 8 |
+
- *"The login button is broken"* → best served by keyword matching on title/description.
|
| 9 |
+
- *"How do I fix the auth error on the portal?"* → best served by semantic similarity.
|
| 10 |
+
|
| 11 |
+
Nexus resolves this using **Parallel Two-Branch Retrieval** combined with **Reciprocal Rank Fusion (RRF)**.
|
| 12 |
+
|
| 13 |
+
## 1. The Two-Branch Retrieval Engine
|
| 14 |
+
|
| 15 |
+
Every search query triggers two simultaneous branches:
|
| 16 |
+
|
| 17 |
+
```mermaid
|
| 18 |
+
graph LR
|
| 19 |
+
Q[Query] --> Sem[Branch A: Semantic Vector]
|
| 20 |
+
Q --> Kw[Branch B: Keyword FTS]
|
| 21 |
+
|
| 22 |
+
Sem --> RRF[RRF Fusion]
|
| 23 |
+
Kw --> RRF
|
| 24 |
+
|
| 25 |
+
RRF --> Results[Ranked Results]
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
### Branch A: Semantic Vector Match
|
| 29 |
+
We use the `pgvector` extension to perform cosine distance calculations against 768-dimensional embeddings generated by the `nomic-embed-text` model via Ollama. This catches intent even when keywords don't match.
|
| 30 |
+
|
| 31 |
+
The semantic similarity threshold for KB chunk search is **0.2** (cosine distance), keeping results broadly relevant before re-ranking.
|
| 32 |
+
|
| 33 |
+
### Branch B: Full-Text Keyword Match
|
| 34 |
+
For technical terms (e.g., specific error codes like `ERR_AUTH_01`), keyword search is superior to semantic search. We use `websearch_to_tsquery` to support natural search operators like quotes and minus signs, matching against the precomputed `search_vector` TSVECTOR column.
|
| 35 |
+
|
| 36 |
+
## 2. Fusion Math: Reciprocal Rank Fusion (RRF)
|
| 37 |
+
|
| 38 |
+
How do you compare a Cosine Distance of `0.85` with a Keyword Rank of `0.42`? You don't. Instead, you use **Rank Position**.
|
| 39 |
+
|
| 40 |
+
RRF ensures that a result appearing at Rank 1 in *any* branch is prioritized, but a result appearing at high rank in *both* branches can outrank a Rank 1 result from only one branch.
|
| 41 |
+
|
| 42 |
+
**Formula:** `Score = Σ (Weight / (k + Rank + 1))`
|
| 43 |
+
*k=10 is used to reduce the reward gap between rank 1 and rank 2.*
|
| 44 |
+
|
| 45 |
+
## 3. High-Fidelity Normalization
|
| 46 |
+
|
| 47 |
+
Raw RRF scores are small by design. To make them intuitive in the UI, scores are normalized to a `0-100%` scale:
|
| 48 |
+
```python
|
| 49 |
+
MAX_RRF = 0.0909 # Theoretical max: Rank 1 in both branches
|
| 50 |
+
norm_score = min(((rrf_score / MAX_RRF) * 100), 100.0)
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
## Results Calibration
|
| 54 |
+
|
| 55 |
+
- **Semantic (Weight 0.4)**: The backbone of intent — catches synonyms and paraphrases.
|
| 56 |
+
- **Keyword (Weight 0.4)**: The anchor for precision — essential for exact technical terms.
|
| 57 |
+
|
| 58 |
+
Both branches are applied to the same corpus (tickets or KB articles). Each branch retrieves the top 10–20 candidates before the RRF fusion step, keeping the fusion matrix small and fast.
|
| 59 |
+
|
| 60 |
+
## What Hybrid Search Is Not
|
| 61 |
+
|
| 62 |
+
Attachments and images are **not** a separate search branch. Image content is passed to the LLM as multimodal context during AI-assisted responses (via `core/vision.py`), but there is no standalone attachment-text search index included in the hybrid retrieval pipeline.
|
docs/backend_insights/03_multimodal_pipeline.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Multimodal AI Pipeline: Images as LLM Context
|
| 2 |
+
|
| 3 |
+
Nexus uses images as first-class context in its AI workflows. When a ticket description or KB article contains image attachments, those images are resolved and passed directly to the LLM alongside the text, enabling multimodal reasoning over screenshots, diagrams, and error logs.
|
| 4 |
+
|
| 5 |
+
## The Problem: Images Are Invisible to Text-Only AI
|
| 6 |
+
|
| 7 |
+
When a customer attaches a screenshot of an error or a system diagram, a text-only LLM has no visibility into it. Nexus solves this by resolving image references and injecting them into LLM prompts as vision inputs.
|
| 8 |
+
|
| 9 |
+
## How It Works: `core/vision.py`
|
| 10 |
+
|
| 11 |
+
The `core/vision.py` module provides two key functions:
|
| 12 |
+
|
| 13 |
+
### `resolve_image(db, workspace_id, identifier)`
|
| 14 |
+
Resolves a Markdown image reference (a direct URL or a UUID pointing to an `Attachment` record) to a format the LLM can consume:
|
| 15 |
+
- **Direct URL** → returned as an `image_url` input.
|
| 16 |
+
- **UUID attachment reference** → looked up in the `attachments` table, then either fetched from S3 as a signed URL or read from local storage and base64-encoded as a `data:image/...` URI.
|
| 17 |
+
|
| 18 |
+
### `extract_visual_context(db, workspace_id, content, limit=2)`
|
| 19 |
+
Scans a piece of Markdown content (ticket description or article body) for embedded image references using a regex pattern, resolves up to `limit` images via `resolve_image`, and returns a list of vision-compatible content blocks.
|
| 20 |
+
|
| 21 |
+
## Where It Is Used
|
| 22 |
+
|
| 23 |
+
The multimodal pipeline is invoked inside background AI tasks:
|
| 24 |
+
|
| 25 |
+
### `auto_summarize_ticket` (`tasks/ai.py`)
|
| 26 |
+
After fetching the ticket and its messages, the task calls `extract_visual_context` on the ticket description to retrieve up to 2 images. These are appended to the LLM prompt alongside the text, so the summarization LLM can reason about any screenshots or diagrams attached to the ticket.
|
| 27 |
+
|
| 28 |
+
```python
|
| 29 |
+
all_imgs = await extract_visual_context(db, ticket.workspace_id, ticket.description, limit=2)
|
| 30 |
+
cust_prompt = [
|
| 31 |
+
SystemMessage(content="Summarize for a CUSTOMER..."),
|
| 32 |
+
HumanMessage(content=[{"type": "text", "text": "..."}, *all_imgs])
|
| 33 |
+
]
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
### `index_kb_article` (`tasks/ai.py`)
|
| 37 |
+
During KB article indexing, `sync_markdown_images` (`core/sync.py`) is called first to ensure all inline images are stored in the correct storage backend before the article is chunked and embedded. This keeps image references consistent between environments.
|
| 38 |
+
|
| 39 |
+
## What This Pipeline Is Not
|
| 40 |
+
|
| 41 |
+
There is no standalone OCR or diagram-classification job that runs when an attachment is uploaded. Images are not indexed into a separate searchable attachment corpus. The vision feature is strictly about enriching LLM prompts with visual context at inference time — not building a visual search index.
|
| 42 |
+
|
| 43 |
+
Mermaid diagrams in LLM output are handled separately by `sanitize_mermaid` in `agents/nexus_master.py`, which fixes common LLM hallucinations in generated diagram syntax before sending the response to the client.
|
docs/backend_insights/04_semantic_caching.md
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Semantic Caching: Three Layers from Zero to Sub-Millisecond
|
| 2 |
+
|
| 3 |
+
In a production AI system, speed is the ultimate feature. While LLMs are powerful, their high latency and token cost can degrade the user experience. Nexus solves this with a **Three-Layer Caching Architecture** implemented in `core/cache.py`.
|
| 4 |
+
|
| 5 |
+
## The Cost of Intelligence
|
| 6 |
+
|
| 7 |
+
Every time a user asks a question, a standard RAG pipeline typically:
|
| 8 |
+
1. Generates a Query Embedding (~100ms).
|
| 9 |
+
2. Performs Vector Search (~50ms).
|
| 10 |
+
3. Sends Context to LLM (~1–5s).
|
| 11 |
+
4. Streams the Response.
|
| 12 |
+
|
| 13 |
+
For a support team asking the same questions (e.g., *"What is the refund policy?"*), this is 99% redundant.
|
| 14 |
+
|
| 15 |
+
## Layer 0: In-Process LRU Cache (Zero Latency)
|
| 16 |
+
|
| 17 |
+
The fastest layer is a plain Python dictionary (`_l1_cache`) capped at **2,048 entries** with LRU eviction. It lives inside each Gunicorn worker process and requires no network I/O.
|
| 18 |
+
|
| 19 |
+
- **Access time**: sub-microsecond (dict lookup).
|
| 20 |
+
- **Scope**: single worker process — other Gunicorn workers have their own independent L0 cache.
|
| 21 |
+
- **Eviction**: when full, the oldest 10% of entries are evicted in one batch.
|
| 22 |
+
- **TTL**: every entry has a timestamp-based expiry checked on read.
|
| 23 |
+
|
| 24 |
+
```python
|
| 25 |
+
# core/cache.py
|
| 26 |
+
_l1_cache: dict[str, tuple[Any, float]] = {}
|
| 27 |
+
MAX_L1_SIZE = 2048
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
API endpoints opt into L0 via `use_l1=True` on `get_cached_object`.
|
| 31 |
+
|
| 32 |
+
## Layer 1: Redis Search Cache (<10ms)
|
| 33 |
+
|
| 34 |
+
The second layer is a **Redis-backed deterministic cache** for search results and API objects. It uses a hash of `workspace_id + query + filters` as the key, so the exact same search from any user in the same workspace returns instantly.
|
| 35 |
+
|
| 36 |
+
```python
|
| 37 |
+
def generate_cache_key(prefix, workspace_id, query, filters=None):
|
| 38 |
+
payload = f"{workspace_id}:{query}:{json.dumps(filters, sort_keys=True)}".lower()
|
| 39 |
+
query_hash = hashlib.sha256(payload.encode()).hexdigest()[:16]
|
| 40 |
+
return f"cache:search:{prefix}:{workspace_id}:{query_hash}"
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
Default TTL is 1 hour. The Resend → L1 path is: L0 miss → Redis GET → return if hit.
|
| 44 |
+
|
| 45 |
+
## Layer 2: Semantic Cache (pgvector, ~20ms)
|
| 46 |
+
|
| 47 |
+
Layer 1 fails when a user rephrases their query (e.g., *"How do I refund?"* vs *"What is the refund policy?"*). The **Semantic Cache** catches these near-duplicates.
|
| 48 |
+
|
| 49 |
+
### How it Works:
|
| 50 |
+
1. **Embedding**: Embed the incoming query using Ollama.
|
| 51 |
+
2. **Vector Similarity**: Query the `nexus_semantic_cache` table for stored queries in the same workspace using cosine distance.
|
| 52 |
+
3. **Threshold**: A match is returned only if cosine distance is **< 0.10** (≥ 90% similarity).
|
| 53 |
+
4. **Hit**: Return the cached `response_text` without touching the LLM.
|
| 54 |
+
|
| 55 |
+
### Workspace-Unified Knowledge
|
| 56 |
+
The semantic cache is scoped by `workspace_id`, not by user. If one user asks a complex question and gets a high-quality answer, every subsequent similar query from any user in the same workspace is served from cache.
|
| 57 |
+
|
| 58 |
+
## Cache Governance & Invalidation
|
| 59 |
+
|
| 60 |
+
- **Write invalidation**: when a KB article is updated, `invalidate_cache` deletes the matching Redis keys for that workspace.
|
| 61 |
+
- **Semantic cache pruning**: `purge_stale_semantic_cache` is a regular-worker cron job (every 6 hours at `hour={0, 6, 12, 18}`) that removes entries where `hit_count` is low and `last_hit_at` is old.
|
| 62 |
+
- **Fail-safe**: all cache reads are wrapped in try/except — if Redis is down, the system falls through to a fresh DB/LLM call with no user-visible impact.
|
| 63 |
+
|
| 64 |
+
By layering zero-latency in-process storage, fast Redis lookups, and vector-similarity matching, Nexus delivers sub-second responses for the long tail of repeated and rephrased support queries.
|
docs/backend_insights/05_multi_tenant_governance.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Multi-Tenant Governance: Hardening Support with BOLA Prevention
|
| 2 |
+
|
| 3 |
+
Nexus is built to serve thousands of independent support teams. In a multi-tenant environment, the "Security of Isolation" is paramount. A single leakage of a customer ticket between workspaces is a catastrophic failure. Nexus prevents this through a multi-layered **Governance Layer**.
|
| 4 |
+
|
| 5 |
+
## The Triple-Lock Security Model
|
| 6 |
+
|
| 7 |
+
Nexus enforces workspace boundaries at three distinct levels:
|
| 8 |
+
1. **Network Layer**: JWT-based session hydration.
|
| 9 |
+
2. **Access Control (RBAC)**: Role-based action validation.
|
| 10 |
+
3. **Data Layer (BOLA Prevention)**: Implicit row-level filtering.
|
| 11 |
+
|
| 12 |
+
## 1. Identity & Session Hydration
|
| 13 |
+
|
| 14 |
+
Every request to the Nexus API must carry a valid `Authorization: Bearer <token>`. The `get_current_user` dependency in `core/deps.py` verifies the JWT signature, decodes the payload, and resolves the user along with their workspace context. The `workspace_id` and `role` embedded in the token are trusted for all downstream filtering — there is no additional workspace lookup middleware.
|
| 15 |
+
|
| 16 |
+
```python
|
| 17 |
+
# core/deps.py — simplified
|
| 18 |
+
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
|
| 19 |
+
user = await db.get(User, payload["sub"])
|
| 20 |
+
# current_user.workspace_id is used in every subsequent query
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
Portal access is additionally constrained by the `portal` claim in the token: the customer portal produces tokens with `portal=customer`, which are rejected by any endpoint decorated with `require_staff`.
|
| 24 |
+
|
| 25 |
+
## 2. Breaking the BOLA Chain
|
| 26 |
+
|
| 27 |
+
BOLA (Broken Object Level Authorization) occurs when a user accesses a resource they don't own by guessing its ID (e.g., `/api/v1/tickets/<other_workspace_uuid>`).
|
| 28 |
+
|
| 29 |
+
Nexus eliminates this by **Implicit Partitioning** — the `workspace_id` check is baked into every database query, not applied as an afterthought:
|
| 30 |
+
|
| 31 |
+
```python
|
| 32 |
+
# api/v1/tickets.py
|
| 33 |
+
stmt = select(Ticket).where(
|
| 34 |
+
Ticket.id == ticket_id,
|
| 35 |
+
Ticket.workspace_id == current_user.workspace_id # hard boundary
|
| 36 |
+
)
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
Even if a user knows the UUID of a ticket from another workspace, the query returns zero rows, and the endpoint returns `404 Not Found`.
|
| 40 |
+
|
| 41 |
+
## 3. Six-Role RBAC
|
| 42 |
+
|
| 43 |
+
Nexus supports two personas (Customer, Staff) with six distinct roles defined as a `UserRole` enum in `models/user.py`:
|
| 44 |
+
|
| 45 |
+
| Role | Access |
|
| 46 |
+
|---|---|
|
| 47 |
+
| `SUPERADMIN` | Platform-wide oversight; linked to all workspaces |
|
| 48 |
+
| `SC_ADMIN` | Workspace staff admin; configure escalation rules, AI settings |
|
| 49 |
+
| `SC_LEAD` | Senior agent; access analytics, personnel reports, escalation |
|
| 50 |
+
| `SC_AGENT` | Support agent; manage tickets and messages in workspace |
|
| 51 |
+
| `CUSTOMER_ADMIN` | Workspace owner on customer side; manage workspace settings |
|
| 52 |
+
| `CUSTOMER_USER` | Regular customer; view/create own tickets and public KB |
|
| 53 |
+
|
| 54 |
+
Per-workspace role overrides are stored in the `UserWorkspace` join table, allowing the same user to be `SC_AGENT` in one workspace and `SC_LEAD` in another.
|
| 55 |
+
|
| 56 |
+
FastAPI dependencies enforce roles at the router entry point:
|
| 57 |
+
```python
|
| 58 |
+
@router.post("/kb/", dependencies=[Depends(require_staff)])
|
| 59 |
+
@router.get("/reports/personnel/", dependencies=[Depends(require_lead)])
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
## 4. SUPERADMIN Access
|
| 63 |
+
|
| 64 |
+
`SUPERADMIN` users are automatically linked to every workspace at the DB level. They bypass workspace-scoped filters only through explicit logic in the relevant service layer — not through a query-parameter override. All SUPERADMIN actions are recorded in the `audit_log` table.
|
| 65 |
+
|
| 66 |
+
## 5. Security at the Edge (CORS & Middleware)
|
| 67 |
+
|
| 68 |
+
CORS is configured dynamically in `main.py`. When running in Hugging Face Spaces (detected via the `SPACE_ID` env var), the allowed origins are computed from the Space URL. For other environments, `ALLOWED_ORIGINS` is read from settings. This prevents cross-origin access to internal portal endpoints from customer-facing domains.
|
| 69 |
+
|
| 70 |
+
Additional HTTP security headers (HSTS, CSP, X-Content-Type-Options, X-Frame-Options) are applied via middleware for every response.
|
| 71 |
+
|
| 72 |
+
By combining deterministic database filters with strict role-based guarding, Nexus provides an enterprise-ready environment where data privacy is enforced at the code's foundational level.
|
docs/backend_insights/06_ai_observability.md
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AI Workflow Observability: Tracking Every Thought
|
| 2 |
+
|
| 3 |
+
AI is often criticized for being a "black box." In Nexus, we've turned the black box into a glass box using two complementary observability mechanisms: **workflow step tracing** (domain-specific) and **OpenTelemetry** (infrastructure-level).
|
| 4 |
+
|
| 5 |
+
## The Challenge of Distributed AI
|
| 6 |
+
|
| 7 |
+
When a ticket is created, multiple async tasks fire independently across worker processes:
|
| 8 |
+
1. **Summarization**: `auto_summarize_ticket` generates dual LLM summaries.
|
| 9 |
+
2. **Embedding**: `generate_ticket_embedding` indexes the ticket for semantic search.
|
| 10 |
+
3. **AI workflow**: `run_ai_workflow` (from `agents/workflow.py`) may run triage or routing logic.
|
| 11 |
+
|
| 12 |
+
The challenge is capturing these independent events into a coherent, auditable trace.
|
| 13 |
+
|
| 14 |
+
## 1. Workflow Step Tracing (`core/observability.py`)
|
| 15 |
+
|
| 16 |
+
`core/observability.py` exposes a `record_workflow_step` function that persists discrete steps of an AI workflow to the database. It is called from `tasks/system.py::record_workflow_step_task`, which is enqueued as a fire-and-forget background job to avoid adding latency to the primary task.
|
| 17 |
+
|
| 18 |
+
Each recorded step contains:
|
| 19 |
+
- **`entity_id`** and **`workspace_id`**: The ticket or KB article being processed.
|
| 20 |
+
- **`workflow_type`**: The category of workflow (e.g., summarization, routing).
|
| 21 |
+
- **`step_name`**: The specific stage (e.g., `DOC_RETRIEVAL`, `SYNTHESIS`).
|
| 22 |
+
- **`input_data`** / **`output_data`**: The data in and out of the LLM call.
|
| 23 |
+
- **`current_stage`**: The lifecycle phase at the time of recording.
|
| 24 |
+
- **`duration_ms`**: Elapsed time for that step.
|
| 25 |
+
|
| 26 |
+
## 2. Worker Job Lifecycle Telemetry (`WorkerJob` model)
|
| 27 |
+
|
| 28 |
+
Every ARQ job is tracked in the `worker_jobs` table via lifecycle hooks in `nexus_worker.py`:
|
| 29 |
+
|
| 30 |
+
- **`on_job_start`**: Creates (or updates) a `WorkerJob` row with `status=RUNNING` and `started_at`.
|
| 31 |
+
- **`on_job_end`**: Updates the row with `finished_at`, `duration_ms`, and final status: `SUCCESS`, `FAILED`, or `INTERRUPTED` (worker shutdown mid-job).
|
| 32 |
+
|
| 33 |
+
Job IDs are deterministic (derived from the ARQ job ID via `get_deterministic_uuid`) so that cron job deduplication across replicas produces the same DB row.
|
| 34 |
+
|
| 35 |
+
```python
|
| 36 |
+
# nexus_worker.py on_job_end (simplified)
|
| 37 |
+
job.status = JobStatus.SUCCESS if not exception else JobStatus.FAILED
|
| 38 |
+
job.finished_at = datetime.utcnow()
|
| 39 |
+
job.duration_ms = (job.finished_at - job.started_at).total_seconds() * 1000
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
## 3. OpenTelemetry Integration
|
| 43 |
+
|
| 44 |
+
In addition to domain-specific tracing, `core/observability.py` instruments the FastAPI application with **OpenTelemetry**. Traces are exported via the OTLP exporter, capturing the full request path from the API gateway through database queries and into LLM calls (Ollama or Anthropic).
|
| 45 |
+
|
| 46 |
+
This allows developers to see:
|
| 47 |
+
- Which part of a request is slow (DB vs. LLM vs. Redis).
|
| 48 |
+
- How Gunicorn worker processes distribute load.
|
| 49 |
+
- Latency breakdowns for streaming responses.
|
| 50 |
+
|
| 51 |
+
## Why it Matters
|
| 52 |
+
|
| 53 |
+
1. **Debugging**: Developers can trace exactly why an AI gave a specific answer by reviewing the step output stored in the workflow trace.
|
| 54 |
+
2. **Reliability**: Failed jobs are immediately visible in the `worker_jobs` table with the raw exception message — no log scraping required.
|
| 55 |
+
3. **Cost/Performance**: `duration_ms` per step identifies which models or prompts are the bottleneck.
|
| 56 |
+
|
| 57 |
+
Observability isn't just about logs; it's about **AI Accountability**.
|
docs/backend_insights/07_kb_ingestion.md
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Knowledge Base Ingestion: From Raw Content to Vector Wisdom
|
| 2 |
+
|
| 3 |
+
The heart of Nexus's intelligence is its **Knowledge Base (KB) Ingestion Pipeline** (`tasks/ai.py::index_kb_article`). This isn't just a copy-paste ingestion; it's a transformation pipeline that turns static Markdown into high-fidelity, contextual vector chunks stored in the `kb_article_chunks` table.
|
| 4 |
+
|
| 5 |
+
## The Problem with "Big Docs"
|
| 6 |
+
|
| 7 |
+
Support articles can be long. If you embed a 2,000-word troubleshooting guide as a single vector, the "signal-to-noise" ratio drops significantly during retrieval. Nexus solves this using **Overlapping Paragraph-Aware Chunking**.
|
| 8 |
+
|
| 9 |
+
## 1. Stage 1: The Ingestion Trigger
|
| 10 |
+
|
| 11 |
+
When an article is created or updated in `api/v1/kb.py`, an `index_kb_article` job is enqueued to the **heavy ARQ queue**. This keeps the API response fast while the embedding computation happens in the background.
|
| 12 |
+
|
| 13 |
+
## 2. Stage 2: Deduplication Check
|
| 14 |
+
|
| 15 |
+
Before any computation, the pipeline checks for duplicate content:
|
| 16 |
+
1. A SHA-256 `content_hash` is computed from `title + content`.
|
| 17 |
+
2. The DB is queried for other articles in the same workspace with the same hash.
|
| 18 |
+
3. If a duplicate is found, the article is marked `is_published=False` and `duplicate_of_id` is set — no further processing occurs.
|
| 19 |
+
|
| 20 |
+
## 3. Stage 3: Image Sync
|
| 21 |
+
|
| 22 |
+
Before chunking, `sync_markdown_images` (`core/sync.py`) is called. This scans the article content for Markdown image references and ensures they are persisted to the correct storage backend (local or S3), keeping URLs stable across environments.
|
| 23 |
+
|
| 24 |
+
## 4. Stage 4: Chunking (`core/search.py::chunk_text`)
|
| 25 |
+
|
| 26 |
+
The article content is split using a paragraph-aware sliding window:
|
| 27 |
+
- **Chunk size**: **1,200 characters** (not words).
|
| 28 |
+
- **Overlap**: **200 characters** — the tail of chunk N is prepended to chunk N+1 to preserve context across split boundaries.
|
| 29 |
+
- **Split order**: paragraphs (`\n\n`) first, then lines (`\n`), then raw character limit as a last resort.
|
| 30 |
+
|
| 31 |
+
## 5. Stage 5: Parallel Embedding
|
| 32 |
+
|
| 33 |
+
All chunks are embedded concurrently using `asyncio.gather`:
|
| 34 |
+
|
| 35 |
+
```python
|
| 36 |
+
chunk_tasks = [_embed_and_add(i, txt) for i, txt in enumerate(raw_chunks)]
|
| 37 |
+
chunks = await asyncio.gather(*chunk_tasks)
|
| 38 |
+
db.add_all(chunks)
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
Each chunk becomes a `KBArticleChunk` row with a 768-dimensional `nomic-embed-text` vector and its `chunk_index`. The article-level embedding is computed separately from the full `title + content` (truncated to 8,000 characters).
|
| 42 |
+
|
| 43 |
+
The `kb_article_chunks` table uses an **HNSW** index (not IVFFlat) for approximate nearest-neighbor search.
|
| 44 |
+
|
| 45 |
+
## 6. Stage 6: Metadata Synthesis
|
| 46 |
+
|
| 47 |
+
After chunking, a single combined LLM call (saving tokens) generates:
|
| 48 |
+
- **Summary**: 2–3 sentence technical "TL;DR" stored in `article.summary`.
|
| 49 |
+
- **Category**: One authoritative label from: `ENGINEERING`, `FINANCE`, `SUCCESS`, `ACCOUNT`, `SECURITY`, `COMPLIANCE`, `PRODUCT`, `GENERAL`. The category is only overwritten if the current value is a generic placeholder (`None`, `"Imported"`, `"General"`, `"Uncategorized"`).
|
| 50 |
+
|
| 51 |
+
## The Re-Indexing Lifecycle
|
| 52 |
+
|
| 53 |
+
When an article is edited:
|
| 54 |
+
1. **Purge**: Old `kb_article_chunks` rows for that `article_id` are deleted.
|
| 55 |
+
2. **Re-Process**: The entire pipeline (stages 2–6) runs again.
|
| 56 |
+
3. **Cache Invalidation**: `invalidate_cache` removes the Redis keys for that workspace's search results.
|
| 57 |
+
|
| 58 |
+
## Job Deduplication
|
| 59 |
+
|
| 60 |
+
If the same article is updated 10 times in rapid succession, the job latch system (`check_job_latch`) ensures only the most recent enqueue actually runs, preventing redundant re-indexing.
|
| 61 |
+
|
| 62 |
+
By treating documentation as a structured dataset rather than a collection of files, Nexus ensures that the AI's retrieval layer is always synchronized with the latest knowledge.
|
docs/backend_insights/08_triple_notification.md
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# The Multi-Channel Notification Protocol: Universal Reach
|
| 2 |
+
|
| 3 |
+
In the fast-paced world of support, a missed notification is a missed opportunity to help. Nexus implements a multi-channel notification protocol in `tasks/notifications.py::send_triple_notification`, delivering every critical update through up to four channels in a single atomic background job.
|
| 4 |
+
|
| 5 |
+
## The Four Channels
|
| 6 |
+
|
| 7 |
+
1. **Persistent (In-App DB)**: Written to the `notifications` table — always present as a record.
|
| 8 |
+
2. **Real-Time (WebSocket)**: Sub-100ms UI update if the user is currently active.
|
| 9 |
+
3. **Out-of-Band (Email via Resend)**: Sent if the user has a delivery email on file.
|
| 10 |
+
4. **External Webhook (optional)**: Posted to a Discord or Slack webhook if `NOTIFICATION_WEBHOOK_URL` is set.
|
| 11 |
+
|
| 12 |
+
## 1. In-App Notification (Database)
|
| 13 |
+
|
| 14 |
+
A `Notification` row is written first, unconditionally:
|
| 15 |
+
|
| 16 |
+
```python
|
| 17 |
+
notification = Notification(
|
| 18 |
+
workspace_id=workspace_id, user_id=user_id,
|
| 19 |
+
title=title, message=message, link=link
|
| 20 |
+
)
|
| 21 |
+
db.add(notification)
|
| 22 |
+
await db.commit()
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
This ensures there is always a persistent, auditable record regardless of whether the user is online or has a delivery email.
|
| 26 |
+
|
| 27 |
+
## 2. WebSocket Delivery (User-Scoped)
|
| 28 |
+
|
| 29 |
+
After the DB write, the notification is pushed directly to the **specific user** (not the whole workspace) via `manager.send_to_user`:
|
| 30 |
+
|
| 31 |
+
```python
|
| 32 |
+
await manager.send_to_user(user_id, {
|
| 33 |
+
"type": "notification",
|
| 34 |
+
"id": str(notification.id),
|
| 35 |
+
"title": title,
|
| 36 |
+
"message": message,
|
| 37 |
+
"link": link,
|
| 38 |
+
"created_at": datetime.utcnow().isoformat()
|
| 39 |
+
})
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
If the user is not connected (or Redis pub/sub delivers to a worker process that doesn't hold their socket), the message is silently dropped — the in-app DB record serves as the fallback.
|
| 43 |
+
|
| 44 |
+
## 3. Email Delivery (Resend, not SMTP)
|
| 45 |
+
|
| 46 |
+
Nexus uses **Resend** (`core/email.py`) as its email provider — not SMTP or SendGrid. The delivery target is resolved from the `User` record: the `real_email` field (an optional personal email override) takes priority over the system-generated `email`.
|
| 47 |
+
|
| 48 |
+
```python
|
| 49 |
+
primary_email, real_email = u_res
|
| 50 |
+
delivery_target = real_email or primary_email
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
If a `delivery_target` is found, an HTML email is rendered from a template and dispatched via Resend. There is no retry queue at the ARQ level for email failures — the Resend SDK handles delivery retries internally.
|
| 54 |
+
|
| 55 |
+
## 4. Webhook (Discord / Slack)
|
| 56 |
+
|
| 57 |
+
If `settings.NOTIFICATION_WEBHOOK_URL` is configured, a final POST is sent. The payload key is auto-detected: `"content"` for Discord webhooks, `"text"` for Slack-style webhooks.
|
| 58 |
+
|
| 59 |
+
## Enqueuing (Asynchronous Backbone)
|
| 60 |
+
|
| 61 |
+
Sending notifications never blocks the API. Callers enqueue the job via `enqueue_task`:
|
| 62 |
+
|
| 63 |
+
```python
|
| 64 |
+
await enqueue_task("send_triple_notification",
|
| 65 |
+
user_id, workspace_id, title, message, link=link)
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
`send_triple_notification` is in the **regular worker queue** (`arq:regular`) because it is lightweight and latency-sensitive.
|
| 69 |
+
|
| 70 |
+
## Event Scenarios
|
| 71 |
+
|
| 72 |
+
- **SLA Warning / Breach**: The assignee and all leads/admins are notified (see `monitor_sla_thresholds` in `tasks/system.py`).
|
| 73 |
+
- **Mention**: Each mentioned user receives a separate triple-notification job via `notify_mentions`.
|
| 74 |
+
- **AI Nudge**: The `ai_dynamic_nudge_pulse` task posts an internal AI message to the ticket thread instead of sending a notification — there is no separate notification for nudges.
|
| 75 |
+
|
| 76 |
+
By unifying four channels into a single atomic background job, Nexus ensures the communication loop is never broken regardless of whether a user is actively in the portal.
|
docs/backend_insights/09_sla_enforcement.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Automated SLA Enforcement: Precision Guardrails
|
| 2 |
+
|
| 3 |
+
In an enterprise support environment, promises are made in the form of **SLA (Service Level Agreements)**. Nexus doesn't leave these to chance. The SLA system combines workspace-configurable escalation rules with a proactive background monitor that fires triple-notifications before a breach occurs.
|
| 4 |
+
|
| 5 |
+
## The SLA Model: `EscalationRule` per Workspace
|
| 6 |
+
|
| 7 |
+
There is no hardcoded SLA table. Each workspace configures its own `EscalationRule` rows — one per priority level (`P0`, `P1`, `P2`, `P3`) — via the `escalation_rules` table. Each rule has:
|
| 8 |
+
- `threshold_minutes`: The maximum time allowed for a ticket at that priority.
|
| 9 |
+
- `is_active`: Whether the rule is currently enforced.
|
| 10 |
+
|
| 11 |
+
The monitor computes a **risk score** dynamically:
|
| 12 |
+
|
| 13 |
+
```python
|
| 14 |
+
age_minutes = (now - ticket.created_at).total_seconds() / 60
|
| 15 |
+
raw_risk_score = (age_minutes / rule.threshold_minutes) * 100
|
| 16 |
+
```
|
| 17 |
+
|
| 18 |
+
There is no stored `sla_deadline` column computed at ticket creation. The deadline is calculated on the fly during each monitoring cycle.
|
| 19 |
+
|
| 20 |
+
## Three-Tier Alert System (`tasks/system.py::monitor_sla_thresholds`)
|
| 21 |
+
|
| 22 |
+
The monitor runs on a cron schedule (`minute={0, 30}` — every 30 minutes) on the **regular worker**. It scans up to 500 open tickets per run and applies three thresholds:
|
| 23 |
+
|
| 24 |
+
| Tier | Risk Score | Recipients | Action |
|
| 25 |
+
|---|---|---|---|
|
| 26 |
+
| **WARNING** | ≥ 60% | Assignee only | Triple-notification |
|
| 27 |
+
| **CRITICAL** | ≥ 85% | Assignee + all Leads/Admins | Triple-notification + AuditLog |
|
| 28 |
+
| **BREACHED** | ≥ 100% | Assignee + all Leads/Admins | Triple-notification + AuditLog + `is_escalated` set |
|
| 29 |
+
|
| 30 |
+
Each tier fires **once per ticket per day** — a Redis latch key (`notified_sla_warning:{ticket_id}`, `notified_sla_critical:{ticket_id}`, `notified_sla_breached:{ticket_id}`) with a 24-hour TTL prevents duplicate alerts. Latch keys are batch-fetched with `MGET` before the per-ticket loop to avoid N+1 Redis calls.
|
| 31 |
+
|
| 32 |
+
## AI Nudge Pulse (`tasks/ai.py::ai_dynamic_nudge_pulse`)
|
| 33 |
+
|
| 34 |
+
A separate cron task (`minute={15, 45}` — every 30 min, offset from the SLA monitor) fires when a ticket reaches **75% of its SLA window** and has not yet been nudged (`last_nudge_at` not set in `ai_metadata`). It:
|
| 35 |
+
1. Identifies up to 20 candidate tickets (safety cap).
|
| 36 |
+
2. Fires parallel LLM calls via `asyncio.gather` to generate brief resolution advice.
|
| 37 |
+
3. Posts an internal AI message to each ticket thread.
|
| 38 |
+
4. Stamps `last_nudge_at` in `ticket.ai_metadata` to prevent repeat nudges.
|
| 39 |
+
|
| 40 |
+
## Resolution Capture
|
| 41 |
+
|
| 42 |
+
When a ticket is transitioned to `RESOLVED` or `CLOSED`, the API records:
|
| 43 |
+
- `resolved_at`: Exact UTC timestamp.
|
| 44 |
+
- `resolved_by`: UUID of the resolving user.
|
| 45 |
+
|
| 46 |
+
SLA audit reports in `api/v1/reports.py` compare `resolved_at` vs the computed deadline (`created_at + rule.threshold_minutes`) to classify each ticket as MET or BREACHED.
|
| 47 |
+
|
| 48 |
+
## Auditability
|
| 49 |
+
|
| 50 |
+
Every SLA event (WARNING, CRITICAL_WARNING, SLA_ESCALATION) is written to the `audit_log` table within the same DB transaction as the ticket update. This ensures the log is always in sync with the ticket state.
|
| 51 |
+
|
| 52 |
+
By combining risk-score thresholds, Redis-latched deduplication, and parallel AI nudges, Nexus enforces SLAs proactively rather than reactively.
|
docs/backend_insights/10_agentic_workflows.md
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Agentic Support Flows: Two Distinct Workflows
|
| 2 |
+
|
| 3 |
+
Nexus uses LangGraph for two distinct agentic workflows with different entry points, purposes, and state models:
|
| 4 |
+
|
| 5 |
+
1. **Nexus Master Agent** (`agents/nexus_master.py`) — the interactive query/chat interface.
|
| 6 |
+
2. **Background AI Workflow** (`agents/workflow.py` → `run_ai_workflow` task) — the automated ticket processing pipeline.
|
| 7 |
+
|
| 8 |
+
---
|
| 9 |
+
|
| 10 |
+
## Workflow 1: Nexus Master Agent (Interactive)
|
| 11 |
+
|
| 12 |
+
The master agent handles natural-language queries from users via `POST /api/v1/nexus/query/` and the streaming `POST /api/v1/nexus/stream/`.
|
| 13 |
+
|
| 14 |
+
### State: `NexusState` TypedDict
|
| 15 |
+
|
| 16 |
+
The agent carries a typed state dict through the graph:
|
| 17 |
+
- `messages`: Conversation history with LangGraph message reducers.
|
| 18 |
+
- `workspace_id`, `user_role`: Scoping and RBAC context.
|
| 19 |
+
- `intent`: Classified intent from the router node.
|
| 20 |
+
- `kb_results`, `ticket_results`, `analytics_data`: Populated by sub-nodes.
|
| 21 |
+
- `final_answer`, `sources`: Output of the synthesizer node.
|
| 22 |
+
|
| 23 |
+
### FastTrack Rules
|
| 24 |
+
|
| 25 |
+
Before invoking the LLM for intent classification, the agent applies **regex-based FastTrack rules** that short-circuit common patterns (greetings, thanks, simple status checks) with instant responses. This avoids an LLM call for the majority of routine interactions.
|
| 26 |
+
|
| 27 |
+
### Graph Nodes
|
| 28 |
+
|
| 29 |
+
| Node | Responsibility |
|
| 30 |
+
|---|---|
|
| 31 |
+
| `nexus_initializer` | Loads user identity, memory, and checks for pending approvals |
|
| 32 |
+
| `intent_router` | Classifies query intent; chooses sub-nodes to invoke |
|
| 33 |
+
| `kb_search` (`agents/kb_node.py`) | Hybrid semantic + keyword KB search; gap detection |
|
| 34 |
+
| `ticket_ops` | Create/query tickets on behalf of the user |
|
| 35 |
+
| `analytics` (`agents/analytics.py`) | Aggregation queries; narrative answer |
|
| 36 |
+
| `remediation` (`agents/remediation.py`) | Suggests resolution steps from past tickets |
|
| 37 |
+
| `response_synthesizer` | Merges sub-node outputs into a single structured answer |
|
| 38 |
+
|
| 39 |
+
### Conversation Persistence (Checkpointing)
|
| 40 |
+
|
| 41 |
+
Every interaction is checkpointed to `NexusCheckpoint` rows via `agents/nexus_checkpoint.py`. The `thread_id` passed in the request body resumes an existing conversation. LangGraph's checkpointing is adapted to use the async SQLAlchemy session.
|
| 42 |
+
|
| 43 |
+
### RBAC Output Masking
|
| 44 |
+
|
| 45 |
+
`agents/security.py` post-processes the synthesized response, stripping fields the requesting user's role does not have access to (e.g., internal notes, SLA breach reasons, personnel metrics for CUSTOMER_* roles).
|
| 46 |
+
|
| 47 |
+
---
|
| 48 |
+
|
| 49 |
+
## Workflow 2: Background AI Workflow (`agents/workflow.py`)
|
| 50 |
+
|
| 51 |
+
`run_ai_workflow` is an ARQ heavy-queue task that runs automatically after a ticket is created or updated. It handles automated triage, routing, and context enrichment — not chat.
|
| 52 |
+
|
| 53 |
+
### What It Does
|
| 54 |
+
|
| 55 |
+
1. Runs the routing logic (`agents/routing.py`) to assign the ticket to the best available agent (load-balanced by open ticket count, with priority-based lead assignment for P0/P1).
|
| 56 |
+
2. Applies ticket metadata enrichment.
|
| 57 |
+
3. Writes results back to the ticket's `ai_metadata` JSONB column.
|
| 58 |
+
|
| 59 |
+
### Routing Intelligence (`agents/routing.py`)
|
| 60 |
+
|
| 61 |
+
- **Ownership lock**: If a human agent has already claimed the ticket, no re-routing occurs.
|
| 62 |
+
- **4-tier fallback**: specialists → team generalists → all workspace staff → lead fallback.
|
| 63 |
+
- **Load balancing**: assigns to the agent with the fewest open tickets.
|
| 64 |
+
|
| 65 |
+
---
|
| 66 |
+
|
| 67 |
+
## Reliability Hardening
|
| 68 |
+
|
| 69 |
+
Both workflows are hardened against LLM brittleness:
|
| 70 |
+
- **Recursion limit**: LangGraph's `recursion_limit` prevents infinite tool-calling loops.
|
| 71 |
+
- **Structured output**: Key LLM calls use `.with_structured_output(PydanticModel)` to enforce parseable JSON.
|
| 72 |
+
- **Exception isolation**: each node wraps its logic in try/except; a failed node logs the error and the graph continues or short-circuits gracefully.
|
| 73 |
+
- **Mermaid sanitization**: `sanitize_mermaid` in `nexus_master.py` fixes common LLM hallucinations in generated diagram syntax before the response is sent to the client.
|
| 74 |
+
|
| 75 |
+
Next, we'll explore the underlying **Database Schema** that makes this level of state management possible.
|
docs/backend_insights/11_db_schema_design.md
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# High-Fidelity DB Schema: Modeling Support Excellence
|
| 2 |
+
|
| 3 |
+
At the foundation of Nexus is a robust PostgreSQL schema designed for high-concurrency technical support. We move beyond simple "tables" to a **Relational Knowledge Graph** that captures the complex relationships between users, workspaces, tickets, and AI-generated insights.
|
| 4 |
+
|
| 5 |
+
## The Multi-Tenant Foundation
|
| 6 |
+
|
| 7 |
+
Every entity table — `tickets`, `kb_articles`, `messages`, `notifications`, `nexus_memories`, etc. — carries a `workspace_id` UUID column. Primary keys are UUIDs across all tables. A `deleted_at` column provides soft delete, meaning no data is ever permanently removed from the database.
|
| 8 |
+
|
| 9 |
+
## 1. The Ticket Lifecycle Schema
|
| 10 |
+
|
| 11 |
+
The `tickets` table is our most complex entity — a state container, not just a record.
|
| 12 |
+
|
| 13 |
+
- **Enumerated States**: `TicketStatus` and `TicketPriority` are Python enums (P0–P3) mapped to PostgreSQL string columns. Status transitions: `OPEN → ACKNOWLEDGED → IN_PROGRESS → RESOLVED → CLOSED`.
|
| 14 |
+
- **AI Metadata (JSONB)**: A single `ai_metadata` JSONB column stores summaries, nudge timestamps, and triage metadata. This avoids schema migrations when AI features evolve.
|
| 15 |
+
- **Vector Embeddings**: A `vector(768)` column (pgvector) holds the semantic embedding of the ticket's title + description.
|
| 16 |
+
- **Full-Text Search**: A computed `TSVECTOR` column with a GIN index enables fast keyword search alongside vector similarity.
|
| 17 |
+
- **Duplicate Detection**: `content_hash` (SHA-256 of title + description) and `duplicate_of_id` (FK to another ticket) allow the embedding job to detect and suppress duplicate tickets automatically.
|
| 18 |
+
- **SLA Fields**: `resolved_at`, `resolved_by`, `is_escalated` (timestamp set when a breach occurs), and `expected_resolution_at` for reporting.
|
| 19 |
+
|
| 20 |
+
## 2. The Knowledge Graph
|
| 21 |
+
|
| 22 |
+
```
|
| 23 |
+
Workspace ──< UserWorkspace >── User
|
| 24 |
+
│
|
| 25 |
+
┌─────┴──────┐
|
| 26 |
+
Ticket NexusThread
|
| 27 |
+
│ │
|
| 28 |
+
┌────────────┼─────────┐ NexusInteraction
|
| 29 |
+
Message Attachment Escalation │
|
| 30 |
+
│ NexusCheckpoint
|
| 31 |
+
Feedback
|
| 32 |
+
|
| 33 |
+
Project ──< KBArticle ──< KBArticleChunk
|
| 34 |
+
└──< KBArticleVersion
|
| 35 |
+
└──< KnowledgeInsight
|
| 36 |
+
|
| 37 |
+
WorkerJob NexusMemory PlatformInsight Notification
|
| 38 |
+
MetaInfraHealth AuditLog AIInteraction
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
## 3. Auditability: `audit_log` Table
|
| 42 |
+
|
| 43 |
+
The `AuditLog` model in `models/audit_log.py` records:
|
| 44 |
+
- `entity_type`, `entity_id`: What was changed.
|
| 45 |
+
- `action`: The event label (e.g., `SLA_ESCALATION`, `SLA_WARNING`, `ticket_status_update`).
|
| 46 |
+
- `old_value`, `new_value`: JSONB snapshots before and after.
|
| 47 |
+
- `user_id`: Who triggered the change (NULL for system-automated actions).
|
| 48 |
+
|
| 49 |
+
SLA monitor events, ticket status transitions, and SUPERADMIN actions all write to this table.
|
| 50 |
+
|
| 51 |
+
## 4. Index Strategy
|
| 52 |
+
|
| 53 |
+
| Index Type | Used For |
|
| 54 |
+
|---|---|
|
| 55 |
+
| B-Tree | UUID primary keys, foreign keys, `workspace_id`, timestamps |
|
| 56 |
+
| GIN | TSVECTOR full-text search columns, JSONB containment queries |
|
| 57 |
+
| **HNSW** (pgvector) | Vector similarity search on `tickets.embedding` and `kb_article_chunks.embedding` |
|
| 58 |
+
|
| 59 |
+
The vector index uses **HNSW** (Hierarchical Navigable Small World) — not IVFFlat. HNSW provides better query latency at the cost of higher index build time and memory, which is acceptable given the typical KB and ticket corpus size.
|
| 60 |
+
|
| 61 |
+
## 5. Connection Pooling
|
| 62 |
+
|
| 63 |
+
Two separate SQLAlchemy engine configurations are used:
|
| 64 |
+
- **API processes**: `AsyncAdaptedQueuePool` (up to 70 connections) — maintains persistent connections for low-latency request handling.
|
| 65 |
+
- **Worker processes**: `NullPool` — creates a fresh connection per job and releases it immediately. Workers are long-lived processes with infrequent DB access, so a pool would waste connections.
|
| 66 |
+
|
| 67 |
+
The engine selection is based on the `NEXUS_MODE` environment variable set at worker startup.
|
| 68 |
+
|
| 69 |
+
## 6. Schema Evolution with Alembic
|
| 70 |
+
|
| 71 |
+
All schema changes are managed via Alembic migrations in `alembic/versions/`. A distributed migration lock (Redis-backed, in `core/database.py`) prevents multiple container replicas from running migrations simultaneously at startup.
|
| 72 |
+
|
| 73 |
+
By treating the database as a "Strict Source of Truth," Nexus provides the reliability and performance required for enterprise-scale support operations.
|
docs/backend_insights/12_scaling_arq_workers.md
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Scaling with Arq & Redis: The Distributed Worker Engine
|
| 2 |
+
|
| 3 |
+
Technical support doesn't happen in a vacuum. It involves thousands of background tasks — indexing, triaging, notifying, and monitoring. Nexus handles this scale using **Arq**, a high-performance asynchronous task queue backed by **Redis**, with two specialized worker classes defined in `nexus_worker.py`.
|
| 4 |
+
|
| 5 |
+
## The Two-Queue Architecture
|
| 6 |
+
|
| 7 |
+
Nexus uses two named ARQ queues to prevent lightweight notification jobs from being blocked by heavy AI tasks:
|
| 8 |
+
|
| 9 |
+
| Queue | Class | `max_jobs` | `job_timeout` | Responsibilities |
|
| 10 |
+
|---|---|---|---|---|
|
| 11 |
+
| `arq:regular` | `RegularWorkerSettings` | 10 | 60s | SLA monitoring, notifications, heartbeat, cron management |
|
| 12 |
+
| `arq:heavy` | `HeavyWorkerSettings` | 30 | 1200s (20 min) | Embeddings, summaries, KB indexing, insights, streaming AI |
|
| 13 |
+
|
| 14 |
+
```mermaid
|
| 15 |
+
graph LR
|
| 16 |
+
API[FastAPI Gateway] -- enqueue_task() --> Redis[(arq:regular / arq:heavy)]
|
| 17 |
+
Redis -- Fetch --> RW[Regular Worker x N]
|
| 18 |
+
Redis -- Fetch --> HW[Heavy Worker x N]
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
`enqueue_task` in `tasks/system.py` automatically routes to the correct queue based on the task name:
|
| 22 |
+
|
| 23 |
+
```python
|
| 24 |
+
HEAVY_TASKS = [
|
| 25 |
+
"generate_ticket_embedding", "run_ai_workflow", "auto_summarize_ticket",
|
| 26 |
+
"index_kb_article", "crystallize_memory", "generate_workspace_insights",
|
| 27 |
+
"nexus_stream_task", ...
|
| 28 |
+
]
|
| 29 |
+
queue_name = "arq:heavy" if task_name in HEAVY_TASKS else "arq:regular"
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
## Deduplication: Job Latch (Latest-Only)
|
| 33 |
+
|
| 34 |
+
Nexus does NOT use ARQ's built-in `_job_id` deduplication. Instead, it implements a **latest-only latch** in Redis:
|
| 35 |
+
|
| 36 |
+
1. When a job is enqueued, a timestamp is stored at `job_latch:{task_name}:{entity_id}` (TTL 24h).
|
| 37 |
+
2. When the job starts, `check_job_latch` compares the job's `enqueue_time_ms` against the latch timestamp.
|
| 38 |
+
3. If a newer enqueue exists (the entity was updated again after this job was queued), the current job is **skipped**.
|
| 39 |
+
|
| 40 |
+
This means: if a KB article is edited 10 times in 1 minute, only the last enqueue runs. Earlier jobs self-terminate cheaply.
|
| 41 |
+
|
| 42 |
+
## Cron Deduplication: `check_cron_lock`
|
| 43 |
+
|
| 44 |
+
Cron jobs present a different problem: multiple container replicas will each trigger the cron at the same wall-clock time. Nexus uses a PostgreSQL-backed lock (`check_cron_lock` in `tasks/system.py`):
|
| 45 |
+
1. The raw cron job ID is rounded to the nearest 10 seconds (`normalize_job_id`) to generate a deterministic ID across replicas.
|
| 46 |
+
2. The DB is queried for a `WorkerJob` with that ID in `SUCCESS` or `RUNNING` state.
|
| 47 |
+
3. If found, the replica skips execution.
|
| 48 |
+
|
| 49 |
+
## Job Lifecycle Telemetry
|
| 50 |
+
|
| 51 |
+
Every job execution is tracked in the `worker_jobs` table via hooks:
|
| 52 |
+
- **`on_job_start`**: Creates a `WorkerJob` row with `status=RUNNING`, `started_at`.
|
| 53 |
+
- **`on_job_end`**: Updates `finished_at`, `duration_ms`, and status (`SUCCESS`, `FAILED`, or `INTERRUPTED`).
|
| 54 |
+
|
| 55 |
+
Memory usage is logged at job start via `psutil` (`log_memory_usage`) to help diagnose RSS spikes in the heavy worker.
|
| 56 |
+
|
| 57 |
+
## Cron Schedule
|
| 58 |
+
|
| 59 |
+
| Task | Queue | Schedule |
|
| 60 |
+
|---|---|---|
|
| 61 |
+
| `monitor_sla_thresholds` | Regular | Every 30 min (`minute={0, 30}`) |
|
| 62 |
+
| `nexus_pulse_check` | Regular | Every 30 min offset (`minute={15, 45}`) |
|
| 63 |
+
| `purge_stale_semantic_cache` | Regular | Every 6 hours |
|
| 64 |
+
| `record_system_heartbeat` | Regular | Twice daily |
|
| 65 |
+
| `generate_global_insight` | Heavy | Daily at 03:00 UTC |
|
| 66 |
+
| `refresh_active_workspace_insights` | Heavy | Daily at 00:00 UTC |
|
| 67 |
+
| `generate_nightly_personnel_analytics` | Heavy | Daily at 00:00 UTC |
|
| 68 |
+
|
| 69 |
+
By decoupling the AI engine from the API gateway with two purpose-tuned queues, Nexus ensures the platform remains responsive while LLM-heavy work scales horizontally in the background.
|
docs/backend_insights/13_realtime_sync.md
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Real-Time Synchronization: Event-Driven State Management
|
| 2 |
+
|
| 3 |
+
Nexus is a collaborative platform. When an agent reassigns a ticket, the lead needs to see it instantly. When a customer replies, the agent's dashboard must update without a refresh. We achieve this through a high-performance **Real-Time Synchronization Layer** using WebSockets and Redis Pub/Sub in `core/websockets.py`.
|
| 4 |
+
|
| 5 |
+
## The State Problem
|
| 6 |
+
|
| 7 |
+
In a distributed backend, keeping client state in sync across different server instances is difficult. If Agent A is connected to Gunicorn worker 1 and the state change occurs in worker 2, how does worker 1 know to notify Agent A?
|
| 8 |
+
|
| 9 |
+
## 1. Redis Pub/Sub: The Global Signal
|
| 10 |
+
|
| 11 |
+
Nexus uses a **Redis pub/sub fan-out** architecture. Each Gunicorn worker process runs a background subscriber task that listens on `nexus:ws:*` channels. When any worker publishes a message (via `broadcast_to_workspace`, `send_to_user`, etc.), every other worker's subscriber picks it up and delivers it to whatever WebSocket connections it holds locally.
|
| 12 |
+
|
| 13 |
+
```mermaid
|
| 14 |
+
graph TD
|
| 15 |
+
API2[Worker 2] -- publish --> Redis[(Local Redis Pub/Sub)]
|
| 16 |
+
Redis -- message --> Sub1[Worker 1 subscriber]
|
| 17 |
+
Redis -- message --> Sub3[Worker 3 subscriber]
|
| 18 |
+
Sub1 -- send --> ClientA[Client A's WebSocket]
|
| 19 |
+
Sub3 -- send --> ClientC[Client C's WebSocket]
|
| 20 |
+
```
|
| 21 |
+
|
| 22 |
+
**Important**: The pub/sub Redis must be a persistent TCP connection — `LOCAL_REDIS_URL` points to a local Redis instance (sidecar in the container or `localhost` in dev). Upstash's HTTP-only Redis cannot be used for pub/sub.
|
| 23 |
+
|
| 24 |
+
Fallback: if Redis is unavailable at broadcast time, the manager falls back to direct local delivery (only connections on the same worker process are reached). Single-process deployments are unaffected.
|
| 25 |
+
|
| 26 |
+
## 2. Four Channel Namespaces
|
| 27 |
+
|
| 28 |
+
The `ConnectionManager` maintains four in-process registries and publishes to four channel namespaces:
|
| 29 |
+
|
| 30 |
+
| Namespace | Key | Broadcast Method |
|
| 31 |
+
|---|---|---|
|
| 32 |
+
| `nexus:ws:workspace:{uuid}` | `workspace_id` | `broadcast_to_workspace` |
|
| 33 |
+
| `nexus:ws:user:{uuid}` | `user_id` | `send_to_user` |
|
| 34 |
+
| `nexus:ws:role:{workspace_uuid}:{role}` | `(workspace_id, role)` | `broadcast_to_role` |
|
| 35 |
+
| `nexus:ws:ticket:{uuid}` | `ticket_id` | `broadcast_to_ticket` |
|
| 36 |
+
|
| 37 |
+
All four methods publish to Redis first; the local subscriber loop then delivers the message to the correct registered WebSocket objects.
|
| 38 |
+
|
| 39 |
+
## 3. The Event Payload Standard
|
| 40 |
+
|
| 41 |
+
Every WebSocket message is serialized JSON. The `type` field is used by the frontend to route the event:
|
| 42 |
+
|
| 43 |
+
```json
|
| 44 |
+
{
|
| 45 |
+
"type": "notification",
|
| 46 |
+
"id": "uuid",
|
| 47 |
+
"title": "SLA WARNING",
|
| 48 |
+
"message": "Ticket X has used 60% of its SLA window.",
|
| 49 |
+
"link": "/dashboard?ticket=...",
|
| 50 |
+
"created_at": "2026-04-28T10:00:00"
|
| 51 |
+
}
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
Custom types (`ticket_updated`, `assignment_changed`, etc.) follow the same envelope. A `NexusJSONEncoder` handles serialization of `UUID`, `datetime`, and `Enum` objects that are not JSON-serializable by default.
|
| 55 |
+
|
| 56 |
+
## 4. Connection Lifecycle
|
| 57 |
+
|
| 58 |
+
- **Startup**: `manager.start_pubsub(redis_url)` is called once per worker process in the FastAPI lifespan (`main.py`). This launches the background subscriber coroutine.
|
| 59 |
+
- **Shutdown**: `manager.stop_pubsub()` cancels the subscriber and closes the publish client cleanly.
|
| 60 |
+
- **Connect**: the WebSocket endpoint validates the JWT from the `?token=` query parameter before upgrading the connection. Invalid or revoked tokens close the socket with code 4001.
|
| 61 |
+
- **Disconnect**: connection objects are removed from all four registries under an async lock to prevent race conditions.
|
| 62 |
+
|
| 63 |
+
## 5. Security: Socket Authentication
|
| 64 |
+
|
| 65 |
+
WebSocket connections are not anonymously open. The `?token=<access_token>` query parameter is validated against the same JWT logic used by HTTP endpoints. Revoked tokens (JTI in Redis blocklist) are rejected.
|
| 66 |
+
|
| 67 |
+
By combining in-process connection registries with Redis pub/sub fan-out, Nexus delivers sub-100ms real-time updates to every connected client regardless of which worker process they connected to.
|
docs/backend_insights/14_architecture_enrichment.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Architecture Enrichment: How Nexus Handles Diagrams and Visual Content
|
| 2 |
+
|
| 3 |
+
In technical support, diagrams and screenshots carry critical information. Nexus handles visual content through two complementary mechanisms: **LLM multimodal context injection** for images in ticket content, and **Mermaid diagram sanitization** for AI-generated diagrams in agent responses.
|
| 4 |
+
|
| 5 |
+
## 1. Multimodal Context Injection (`core/vision.py`)
|
| 6 |
+
|
| 7 |
+
When the AI processes a ticket or article that contains embedded images (referenced as Markdown `` syntax), `core/vision.py` resolves those references into LLM-compatible vision inputs.
|
| 8 |
+
|
| 9 |
+
The `extract_visual_context(db, workspace_id, content, limit=2)` function:
|
| 10 |
+
1. Scans the content with a regex for Markdown image patterns.
|
| 11 |
+
2. Resolves each reference via `resolve_image` — returning either a signed S3 URL or a base64-encoded data URI for local attachments.
|
| 12 |
+
3. Returns a list of `{"type": "image_url", ...}` content blocks that are appended to the LLM prompt's `HumanMessage`.
|
| 13 |
+
|
| 14 |
+
This is used in `auto_summarize_ticket` to give the summarization LLM visibility into any screenshots or diagrams attached to the ticket:
|
| 15 |
+
|
| 16 |
+
```python
|
| 17 |
+
# tasks/ai.py
|
| 18 |
+
all_imgs = await extract_visual_context(db, ticket.workspace_id, ticket.description, limit=2)
|
| 19 |
+
cust_prompt = [
|
| 20 |
+
SystemMessage(content="Summarize for a CUSTOMER..."),
|
| 21 |
+
HumanMessage(content=[{"type": "text", "text": context_str}, *all_imgs])
|
| 22 |
+
]
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
The LLM can then describe, reference, or reason about what is in the images when generating its summary. This is pure prompt enrichment — no separate indexing pipeline runs for attachments.
|
| 26 |
+
|
| 27 |
+
## 2. Mermaid Diagram Sanitization (`agents/nexus_master.py`)
|
| 28 |
+
|
| 29 |
+
The Nexus Master Agent frequently generates Mermaid diagram syntax in its responses (system architecture diagrams, workflow visualizations, etc.). LLMs commonly produce subtly malformed Mermaid — for example, using `graph` instead of `flowchart`, or including unsupported syntax that breaks the browser renderer.
|
| 30 |
+
|
| 31 |
+
`sanitize_mermaid(text: str) -> str` in `agents/nexus_master.py` post-processes every agent response before it is sent to the client. It applies a series of regex substitutions to:
|
| 32 |
+
- Fix node label quoting issues.
|
| 33 |
+
- Replace unsupported diagram types with valid equivalents.
|
| 34 |
+
- Remove syntax that is valid in Mermaid v9 but breaks common renderers.
|
| 35 |
+
|
| 36 |
+
This ensures that diagram-heavy responses from the Nexus Agent render correctly in the React frontend's Mermaid component.
|
| 37 |
+
|
| 38 |
+
## What Is Not Implemented
|
| 39 |
+
|
| 40 |
+
There is no standalone attachment classification pipeline that:
|
| 41 |
+
- Runs on every uploaded image to detect diagram types.
|
| 42 |
+
- Generates `[TEK_NAV]` navigational captions.
|
| 43 |
+
- Indexes attachment content into a separate searchable vector store.
|
| 44 |
+
|
| 45 |
+
Images contribute to AI reasoning only when they are embedded in ticket descriptions or article content that is actively being processed by an LLM task. Attachments that are not referenced in Markdown content are not automatically analyzed.
|
| 46 |
+
|
| 47 |
+
Next, we'll wrap up this series with a deep dive into **Backend Performance Tuning**.
|
docs/backend_insights/15_performance_tuning.md
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Backend Performance Tuning: Sub-Second AI Engineering
|
| 2 |
+
|
| 3 |
+
Nexus is a "Heavy Lift" platform. Between vector searches, LLM completions, and multimodal content, the backend is under constant computational pressure. The following strategies keep API overhead low while AI tasks scale in the background.
|
| 4 |
+
|
| 5 |
+
## The Performance Target: <200ms API Latency
|
| 6 |
+
|
| 7 |
+
The goal is for the API overhead (auth, DB queries, business logic) to stay under 200ms, leaving the LLM 800ms–2s for generation and streaming.
|
| 8 |
+
|
| 9 |
+
## 1. Pool-Per-Role: Async Database Connections
|
| 10 |
+
|
| 11 |
+
Two SQLAlchemy engine configurations are used — the choice is made automatically via the `NEXUS_MODE` env var set at startup:
|
| 12 |
+
|
| 13 |
+
- **API workers** (`AsyncAdaptedQueuePool`, up to 70 connections): Maintains a warm pool to avoid TCP handshake overhead on every request.
|
| 14 |
+
- **ARQ workers** (`NullPool`): Creates one connection per job and releases it immediately. Worker processes are long-lived but access the DB infrequently; a connection pool would idle-hold resources unnecessarily.
|
| 15 |
+
|
| 16 |
+
All DB access is async via `asyncpg` through SQLAlchemy 2.0's async session interface.
|
| 17 |
+
|
| 18 |
+
## 2. N+1 Prevention via Strategic Loading
|
| 19 |
+
|
| 20 |
+
Fetching a list of 100 tickets and then issuing 100 separate `SELECT` queries for each creator's name kills performance. Nexus uses SQLAlchemy's eager loading to collapse relationships into a minimal number of round-trips:
|
| 21 |
+
|
| 22 |
+
- **`joinedload`**: Used for to-one relationships (e.g., `Ticket.creator`, `Ticket.assignee`) — merged into the primary `SELECT` as a SQL `JOIN`.
|
| 23 |
+
- **`selectinload`**: Used for to-many relationships (e.g., `Ticket.messages`) — issued as a second optimized `IN` query.
|
| 24 |
+
|
| 25 |
+
## 3. Parallel LLM Calls in Background Tasks
|
| 26 |
+
|
| 27 |
+
`asyncio.gather` is used wherever multiple independent LLM calls or DB operations can run concurrently:
|
| 28 |
+
|
| 29 |
+
- **`auto_summarize_ticket`**: The customer summary and internal summary LLM calls run in parallel:
|
| 30 |
+
```python
|
| 31 |
+
cust_resp, intl_resp = await asyncio.gather(
|
| 32 |
+
llm.ainvoke(cust_prompt),
|
| 33 |
+
llm.ainvoke(intl_prompt)
|
| 34 |
+
)
|
| 35 |
+
```
|
| 36 |
+
- **`index_kb_article`**: All chunk embedding calls run concurrently:
|
| 37 |
+
```python
|
| 38 |
+
chunks = await asyncio.gather(*[_embed_and_add(i, txt) for i, txt in enumerate(raw_chunks)])
|
| 39 |
+
```
|
| 40 |
+
- **`ai_dynamic_nudge_pulse`**: Nudge LLM calls for all eligible tickets fire in parallel, with a safety cap of 20 tickets per run.
|
| 41 |
+
|
| 42 |
+
## 4. Trim-at-Source for Hybrid Search
|
| 43 |
+
|
| 44 |
+
When performing hybrid search, each branch (semantic, keyword) retrieves only the top 10–20 candidates before the RRF fusion step. The fusion math is then performed on a small, high-quality matrix — not the full table. This keeps the total search latency well under 100ms for typical corpus sizes.
|
| 45 |
+
|
| 46 |
+
## 5. Content Truncation to Prevent Overlong Prompts
|
| 47 |
+
|
| 48 |
+
The `truncate_content` helper in `tasks/ai.py` caps input text at 15,000 characters before sending it to the LLM. For KB article embedding, the article is truncated to 8,000 characters. This prevents runaway token usage on very long articles or ticket threads and keeps LLM latency predictable.
|
| 49 |
+
|
| 50 |
+
## 6. FTS: `websearch_to_tsquery`
|
| 51 |
+
|
| 52 |
+
For full-text search, Nexus uses `websearch_to_tsquery` instead of `plainto_tsquery`. It natively handles quoted phrases, minus exclusions, and OR operators, reducing pre-processing in Python and producing tighter, faster query plans.
|
| 53 |
+
|
| 54 |
+
## 7. Streaming for AI Responses (SSE)
|
| 55 |
+
|
| 56 |
+
AI responses from the Nexus Master Agent are streamed token-by-token via Server-Sent Events (`POST /api/v1/nexus/stream/`). The `nexus_stream_task` in the heavy worker handles the actual LLM call and pushes deltas to a Redis channel; the SSE endpoint reads from that channel and streams to the client. This means even a 3-second generation feels instantaneous because the first tokens appear in under 200ms.
|
| 57 |
+
|
| 58 |
+
## 8. Memory Monitoring in Workers
|
| 59 |
+
|
| 60 |
+
Each worker process logs RSS and VMS memory usage at job start via `psutil`. This makes it easy to detect memory leaks in long-lived workers before they trigger OOM kills.
|
| 61 |
+
|
| 62 |
+
## Engineering for Scale
|
| 63 |
+
|
| 64 |
+
Performance isn't a one-time fix; it's a foundation. By combining pool-per-role DB access, parallel async tasks, trim-at-source search, and token-streaming, Nexus ensures the user experience stays sub-second as the corpus grows.
|
| 65 |
+
|
| 66 |
+
---
|
| 67 |
+
*This concludes the Nexus Backend Insights series.*
|
docs/deployment.md
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Deployment Guide
|
| 2 |
+
|
| 3 |
+
Nexus uses a 3-tier deployment strategy: Hugging Face Spaces as primary, Railway as failover, and Docker Compose for local parity.
|
| 4 |
+
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
## Docker image
|
| 8 |
+
|
| 9 |
+
The `Dockerfile` is a four-stage build:
|
| 10 |
+
|
| 11 |
+
| Stage | Base | Output |
|
| 12 |
+
|---|---|---|
|
| 13 |
+
| `frontend-build` | `node:20-slim` | Compiled React assets (`dist/`) |
|
| 14 |
+
| `python-base` | `python:3.11-slim` | System deps + pip packages from `requirements.txt` |
|
| 15 |
+
| `ai-layer` | `python-base` | AI/ML packages from `requirements-ai.txt` |
|
| 16 |
+
| `production` | `ai-layer` | Final image: copied frontend assets, Gunicorn entry |
|
| 17 |
+
|
| 18 |
+
**Build the production image:**
|
| 19 |
+
```bash
|
| 20 |
+
docker build --target production -t nexus:latest .
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
**Run locally:**
|
| 24 |
+
```bash
|
| 25 |
+
docker run -p 8000:7860 \
|
| 26 |
+
--env-file .env \
|
| 27 |
+
nexus:latest
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
The container exposes port **7860** (Hugging Face Spaces convention). The `run_prod.sh` script handles internal service startup.
|
| 31 |
+
|
| 32 |
+
---
|
| 33 |
+
|
| 34 |
+
## Production startup (`scripts/run_prod.sh`)
|
| 35 |
+
|
| 36 |
+
The script runs inside the container as the entry point:
|
| 37 |
+
|
| 38 |
+
1. **Start local Redis** — `redis-server --maxmemory 256mb --maxmemory-policy allkeys-lru` (ephemeral, pub/sub only)
|
| 39 |
+
2. **Run Alembic migrations** — `alembic upgrade head` (guarded by a file lock so only one instance runs migrations)
|
| 40 |
+
3. **Start ARQ Regular Worker** — background process
|
| 41 |
+
4. **Start ARQ Heavy Worker** — background process
|
| 42 |
+
5. **Start Gunicorn** — 4 uvicorn workers, 120 s timeout, port 7860
|
| 43 |
+
6. **Monitor loop** — checks worker PIDs every 30 s, restarts crashed workers
|
| 44 |
+
|
| 45 |
+
---
|
| 46 |
+
|
| 47 |
+
## Tier 1 — Hugging Face Spaces
|
| 48 |
+
|
| 49 |
+
The primary production environment. HF Spaces reads the `README.md` frontmatter and builds the Docker image automatically on push.
|
| 50 |
+
|
| 51 |
+
**Frontmatter (do not remove from README.md):**
|
| 52 |
+
```yaml
|
| 53 |
+
---
|
| 54 |
+
title: Nexus
|
| 55 |
+
emoji: 🚀
|
| 56 |
+
colorFrom: blue
|
| 57 |
+
colorTo: indigo
|
| 58 |
+
sdk: docker
|
| 59 |
+
app_port: 7860
|
| 60 |
+
pinned: false
|
| 61 |
+
---
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
**Required Secrets** (set in Space Settings → Repository secrets):
|
| 65 |
+
|
| 66 |
+
| Secret | Value |
|
| 67 |
+
|---|---|
|
| 68 |
+
| `DATABASE_URL` | Supabase or Neon async connection string |
|
| 69 |
+
| `ARQ_REDIS_URL` | Upstash Redis URL |
|
| 70 |
+
| `CACHE_REDIS_URL` | Upstash Redis URL |
|
| 71 |
+
| `SECRET_KEY` | Random 32+ char string |
|
| 72 |
+
| `ANTHROPIC_API_KEY` | Anthropic API key |
|
| 73 |
+
|
| 74 |
+
`LOCAL_REDIS_URL` defaults to `redis://localhost:6379` — the container starts its own Redis, so no secret needed.
|
| 75 |
+
|
| 76 |
+
**Deployment steps:**
|
| 77 |
+
1. Push to `main` branch.
|
| 78 |
+
2. HF Spaces detects the push, runs `docker build --target production`.
|
| 79 |
+
3. The new container replaces the old one with zero-downtime (HF Spaces handles health checks).
|
| 80 |
+
|
| 81 |
+
**URLs:**
|
| 82 |
+
- Customer portal: `https://3scerror404-nexus.hf.space/`
|
| 83 |
+
- Internal portal: `https://3scerror404-nexus.hf.space/internal/`
|
| 84 |
+
- API docs: `https://3scerror404-nexus.hf.space/docs`
|
| 85 |
+
|
| 86 |
+
---
|
| 87 |
+
|
| 88 |
+
## Tier 2 — Railway (failover)
|
| 89 |
+
|
| 90 |
+
`railway.json` at the repo root configures auto-detection:
|
| 91 |
+
|
| 92 |
+
```json
|
| 93 |
+
{
|
| 94 |
+
"build": { "builder": "DOCKERFILE", "dockerfilePath": "Dockerfile", "target": "production" },
|
| 95 |
+
"deploy": { "startCommand": "bash scripts/run_prod.sh", "healthcheckPath": "/api/v1/system/health/" }
|
| 96 |
+
}
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
**Setup:**
|
| 100 |
+
1. Create a new Railway project and connect this GitHub repo.
|
| 101 |
+
2. Railway detects `railway.json` and builds automatically.
|
| 102 |
+
3. Set environment variables in the Railway dashboard (same set as HF Spaces secrets above).
|
| 103 |
+
4. Add a custom domain or use the `.railway.app` subdomain.
|
| 104 |
+
|
| 105 |
+
**Switching traffic:** Update your DNS CNAME or load-balancer origin to point at Railway when HF Spaces is unavailable.
|
| 106 |
+
|
| 107 |
+
---
|
| 108 |
+
|
| 109 |
+
## Tier 3 — Local Docker (development parity)
|
| 110 |
+
|
| 111 |
+
```bash
|
| 112 |
+
# Windows one-click
|
| 113 |
+
./scripts/start_local.bat
|
| 114 |
+
|
| 115 |
+
# Unix / WSL
|
| 116 |
+
docker compose -f compose.example.yml up --build
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
The compose file starts:
|
| 120 |
+
- `api` — the production Docker image with source mounted for hot reload
|
| 121 |
+
- `redis` — Redis 7 Alpine
|
| 122 |
+
- `ollama` — Ollama with `nomic-embed-text` pre-pulled
|
| 123 |
+
|
| 124 |
+
Ports:
|
| 125 |
+
| Service | Port |
|
| 126 |
+
|---|---|
|
| 127 |
+
| API | 8000 |
|
| 128 |
+
| Redis | 6379 |
|
| 129 |
+
| Ollama | 11434 |
|
| 130 |
+
|
| 131 |
+
---
|
| 132 |
+
|
| 133 |
+
## Frontend build
|
| 134 |
+
|
| 135 |
+
The frontend is compiled as static assets and served by FastAPI:
|
| 136 |
+
|
| 137 |
+
```bash
|
| 138 |
+
cd frontend
|
| 139 |
+
npm install
|
| 140 |
+
npm run build --workspaces # builds both customer and internal apps
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
Output directories:
|
| 144 |
+
- `frontend/apps/customer/dist/` → served at `/`
|
| 145 |
+
- `frontend/apps/internal/dist/` → served at `/internal/`
|
| 146 |
+
|
| 147 |
+
FastAPI mounts these with `StaticFiles`. In Docker, the `frontend-build` stage compiles the assets and the `production` stage copies them into place.
|
| 148 |
+
|
| 149 |
+
---
|
| 150 |
+
|
| 151 |
+
## Database (PostgreSQL + pgvector)
|
| 152 |
+
|
| 153 |
+
**Cloud options:**
|
| 154 |
+
- [Supabase](https://supabase.com) — free tier, pgvector enabled by default
|
| 155 |
+
- [Neon](https://neon.tech) — serverless Postgres, enable pgvector in the dashboard
|
| 156 |
+
- Self-hosted PostgreSQL 15+ with `CREATE EXTENSION vector;`
|
| 157 |
+
|
| 158 |
+
**Connection string format:**
|
| 159 |
+
```
|
| 160 |
+
postgresql+asyncpg://user:password@host:5432/dbname?ssl=require
|
| 161 |
+
```
|
| 162 |
+
|
| 163 |
+
Always run migrations before starting the app:
|
| 164 |
+
```bash
|
| 165 |
+
alembic upgrade head
|
| 166 |
+
```
|
| 167 |
+
|
| 168 |
+
---
|
| 169 |
+
|
| 170 |
+
## Redis
|
| 171 |
+
|
| 172 |
+
**Cloud options:**
|
| 173 |
+
- [Upstash](https://upstash.com) — HTTP-compatible Redis, use for `ARQ_REDIS_URL` and `CACHE_REDIS_URL`
|
| 174 |
+
- Self-hosted Redis 7+
|
| 175 |
+
|
| 176 |
+
Note: `LOCAL_REDIS_URL` (pub/sub) requires a real persistent TCP Redis, not Upstash's HTTP API. In production on HF Spaces and Railway, the container runs its own Redis for this role.
|
| 177 |
+
|
| 178 |
+
---
|
| 179 |
+
|
| 180 |
+
## Scaling considerations
|
| 181 |
+
|
| 182 |
+
- **Horizontal API scaling**: Gunicorn workers are stateless. Scale by adding more container replicas behind a load balancer. Session state is in PostgreSQL + Redis, not in-process.
|
| 183 |
+
- **Worker scaling**: Run additional `HeavyWorkerSettings` or `RegularWorkerSettings` instances — ARQ deduplicates jobs via the Redis latch in `tasks/system.py`.
|
| 184 |
+
- **Database connections**: The API pool is capped at 70 connections per instance (`AsyncAdaptedQueuePool`). If running multiple replicas, use PgBouncer in transaction mode to prevent connection exhaustion.
|
| 185 |
+
- **Vector index**: pgvector HNSW index is in-memory at query time. For large corpora (>1M vectors), increase `hnsw.ef_search` and consider dedicating a read replica for semantic search.
|
| 186 |
+
|
| 187 |
+
---
|
| 188 |
+
|
| 189 |
+
## Health check
|
| 190 |
+
|
| 191 |
+
`GET /api/v1/system/health/` returns HTTP 200 when the DB, Redis, and ARQ queue are reachable. Configure your load balancer or platform to use this endpoint with a 5 s timeout and 3-failure threshold before marking unhealthy.
|
| 192 |
+
|
| 193 |
+
---
|
| 194 |
+
|
| 195 |
+
## Render (alternate)
|
| 196 |
+
|
| 197 |
+
`render.yaml` is included for one-click Render.com deployment. It mirrors the Railway setup. Set the same environment variables in the Render dashboard.
|
docs/development.md
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Development Guide
|
| 2 |
+
|
| 3 |
+
## Prerequisites
|
| 4 |
+
|
| 5 |
+
| Tool | Version | Notes |
|
| 6 |
+
|---|---|---|
|
| 7 |
+
| Python | 3.11+ | Use `pyenv` or system package |
|
| 8 |
+
| Node.js | 20+ | LTS recommended |
|
| 9 |
+
| PostgreSQL | 15+ | With pgvector extension |
|
| 10 |
+
| Redis | 7+ | Local instance or Docker |
|
| 11 |
+
| Ollama | latest | For local embeddings |
|
| 12 |
+
| Docker | 24+ | Optional but recommended |
|
| 13 |
+
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
## Environment setup
|
| 17 |
+
|
| 18 |
+
Copy the example env file and fill in required values:
|
| 19 |
+
|
| 20 |
+
```bash
|
| 21 |
+
cp .env.example .env
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
### Required variables
|
| 25 |
+
|
| 26 |
+
| Variable | Description |
|
| 27 |
+
|---|---|
|
| 28 |
+
| `DATABASE_URL` | Async PostgreSQL URL: `postgresql+asyncpg://user:pass@host/db` |
|
| 29 |
+
| `SECRET_KEY` | 32+ char random string for JWT signing |
|
| 30 |
+
| `ANTHROPIC_API_KEY` | Anthropic API key for text generation |
|
| 31 |
+
| `OLLAMA_BASE_URL` | Ollama host (default `http://localhost:11434`) |
|
| 32 |
+
|
| 33 |
+
### Redis variables
|
| 34 |
+
|
| 35 |
+
Three Redis roles, all defaulting to `redis://localhost:6379`:
|
| 36 |
+
|
| 37 |
+
| Variable | Role |
|
| 38 |
+
|---|---|
|
| 39 |
+
| `ARQ_REDIS_URL` | ARQ job queue — can be Upstash or local |
|
| 40 |
+
| `CACHE_REDIS_URL` | L2 search cache — can be Upstash or local |
|
| 41 |
+
| `LOCAL_REDIS_URL` | WebSocket pub/sub — **must** be a real persistent Redis, not Upstash HTTP |
|
| 42 |
+
|
| 43 |
+
In local dev, a single Redis instance can serve all three by pointing all three variables to `redis://localhost:6379`.
|
| 44 |
+
|
| 45 |
+
### Optional variables
|
| 46 |
+
|
| 47 |
+
| Variable | Default | Description |
|
| 48 |
+
|---|---|---|
|
| 49 |
+
| `AI_PROVIDER` | `anthropic` | `anthropic`, `ollama`, `google`, `azure` |
|
| 50 |
+
| `AI_MODEL` | `claude-3-haiku-20240307` | Model ID for the chosen provider |
|
| 51 |
+
| `AI_TEXT_EMBEDDING_PROVIDER` | `ollama` | Embedding backend |
|
| 52 |
+
| `GOOGLE_API_KEY` | — | Required if `AI_PROVIDER=google` |
|
| 53 |
+
| `AZURE_OPENAI_API_KEY` | — | Required if `AI_PROVIDER=azure` |
|
| 54 |
+
| `RESEND_API_KEY` | — | Transactional email (password reset, mentions) |
|
| 55 |
+
| `RESEND_FROM_EMAIL` | — | Sender address for Resend |
|
| 56 |
+
| `UPLOAD_DIR` | `uploads` | Local file attachment storage |
|
| 57 |
+
| `S3_BUCKET` | — | S3-compatible bucket (overrides local storage) |
|
| 58 |
+
| `S3_ACCESS_KEY` | — | S3 credentials |
|
| 59 |
+
| `S3_SECRET_KEY` | — | S3 credentials |
|
| 60 |
+
| `S3_ENDPOINT_URL` | — | Custom endpoint for MinIO or similar |
|
| 61 |
+
| `ALLOWED_ORIGINS` | `["*"]` | CORS allowlist as JSON array |
|
| 62 |
+
| `DEBUG` | `false` | Enables detailed error pages |
|
| 63 |
+
| `SUPER_ADMIN_EMAIL` | `admin@3sc.com` | Auto-linked SUPERADMIN email |
|
| 64 |
+
| `ACCESS_TOKEN_EXPIRE_MINUTES` | `60` | JWT access token TTL |
|
| 65 |
+
| `REFRESH_TOKEN_EXPIRE_DAYS` | `7` | JWT refresh token TTL |
|
| 66 |
+
|
| 67 |
+
---
|
| 68 |
+
|
| 69 |
+
## Database setup
|
| 70 |
+
|
| 71 |
+
### Install pgvector
|
| 72 |
+
|
| 73 |
+
```bash
|
| 74 |
+
# macOS (Homebrew)
|
| 75 |
+
brew install pgvector
|
| 76 |
+
|
| 77 |
+
# Ubuntu/Debian
|
| 78 |
+
sudo apt install postgresql-15-pgvector
|
| 79 |
+
|
| 80 |
+
# Docker — use pgvector/pgvector image (see compose.example.yml)
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
### Run migrations
|
| 84 |
+
|
| 85 |
+
```bash
|
| 86 |
+
# Apply all pending migrations
|
| 87 |
+
alembic upgrade head
|
| 88 |
+
|
| 89 |
+
# Create a new migration after editing models/
|
| 90 |
+
alembic revision --autogenerate -m "describe your change"
|
| 91 |
+
|
| 92 |
+
# Roll back one migration
|
| 93 |
+
alembic downgrade -1
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
Migration files live in `alembic/versions/`. The `env.py` uses the async SQLAlchemy engine from `core/database.py`.
|
| 97 |
+
|
| 98 |
+
---
|
| 99 |
+
|
| 100 |
+
## Running locally (no Docker)
|
| 101 |
+
|
| 102 |
+
```bash
|
| 103 |
+
# 1. Install Python dependencies
|
| 104 |
+
pip install -r requirements.txt
|
| 105 |
+
pip install -r requirements-ai.txt # AI/ML packages (heavier)
|
| 106 |
+
|
| 107 |
+
# 2. Start services
|
| 108 |
+
redis-server &
|
| 109 |
+
ollama serve &
|
| 110 |
+
ollama pull nomic-embed-text # pull the embedding model
|
| 111 |
+
|
| 112 |
+
# 3. Run migrations
|
| 113 |
+
alembic upgrade head
|
| 114 |
+
|
| 115 |
+
# 4. Start the API (auto-reload on save)
|
| 116 |
+
uvicorn main:app --reload --port 8000
|
| 117 |
+
|
| 118 |
+
# 5. Start background workers (separate terminals)
|
| 119 |
+
arq nexus_worker.RegularWorkerSettings
|
| 120 |
+
arq nexus_worker.HeavyWorkerSettings
|
| 121 |
+
|
| 122 |
+
# 6. Start frontend dev servers
|
| 123 |
+
cd frontend
|
| 124 |
+
npm install
|
| 125 |
+
npm run dev -w apps/customer # http://localhost:5173
|
| 126 |
+
npm run dev -w apps/internal # http://localhost:5174
|
| 127 |
+
```
|
| 128 |
+
|
| 129 |
+
---
|
| 130 |
+
|
| 131 |
+
## Running with Docker
|
| 132 |
+
|
| 133 |
+
```bash
|
| 134 |
+
# Build and start everything (API + Redis + Ollama)
|
| 135 |
+
docker compose -f compose.example.yml up --build
|
| 136 |
+
|
| 137 |
+
# Or use the Windows one-click script
|
| 138 |
+
./scripts/start_local.bat
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
The compose file mounts the local source tree so code changes are picked up without a full rebuild (except for frontend assets).
|
| 142 |
+
|
| 143 |
+
---
|
| 144 |
+
|
| 145 |
+
## Project structure quick-reference
|
| 146 |
+
|
| 147 |
+
```
|
| 148 |
+
api/v1/ HTTP routers — one file per domain
|
| 149 |
+
agents/ LangGraph agent graph, nodes, prompts, tools
|
| 150 |
+
core/
|
| 151 |
+
config.py All settings (Pydantic BaseSettings)
|
| 152 |
+
database.py Async SQLAlchemy engine factory
|
| 153 |
+
deps.py FastAPI dependencies (auth, workspace context)
|
| 154 |
+
security.py JWT creation/validation, password hashing
|
| 155 |
+
cache.py L1 LRU + L2 Redis + semantic cache
|
| 156 |
+
websockets.py Redis pub/sub manager
|
| 157 |
+
permissions.py Role hierarchy helpers
|
| 158 |
+
audit.py Compliance audit log
|
| 159 |
+
models/ SQLAlchemy ORM models
|
| 160 |
+
schemas/ Pydantic request/response schemas
|
| 161 |
+
services/ Business logic (TicketService, etc.)
|
| 162 |
+
tasks/ ARQ background job functions
|
| 163 |
+
ai.py Summarization, embedding, memory
|
| 164 |
+
analytics.py Workspace insight generation
|
| 165 |
+
notifications.py Email/webhook dispatch
|
| 166 |
+
system.py Heartbeat, SLA monitor, job latch
|
| 167 |
+
alembic/ Database migrations
|
| 168 |
+
frontend/
|
| 169 |
+
apps/customer/ Customer portal (React + Vite)
|
| 170 |
+
apps/internal/ Internal console (React + Vite)
|
| 171 |
+
packages/shared/ Shared components and hooks
|
| 172 |
+
tests/ pytest test suite
|
| 173 |
+
scripts/ Dev and production helper scripts
|
| 174 |
+
```
|
| 175 |
+
|
| 176 |
+
---
|
| 177 |
+
|
| 178 |
+
## Testing
|
| 179 |
+
|
| 180 |
+
```bash
|
| 181 |
+
# Run the full test suite
|
| 182 |
+
pytest
|
| 183 |
+
|
| 184 |
+
# Run a specific module
|
| 185 |
+
pytest tests/test_tickets.py -v
|
| 186 |
+
|
| 187 |
+
# With coverage
|
| 188 |
+
pytest --cov=. --cov-report=term-missing
|
| 189 |
+
```
|
| 190 |
+
|
| 191 |
+
Test configuration is in `pytest.ini`. Tests use an in-memory SQLite database by default (see `tests/conftest.py`). Set `TEST_DATABASE_URL` in your env to point at a real PostgreSQL instance for integration tests.
|
| 192 |
+
|
| 193 |
+
---
|
| 194 |
+
|
| 195 |
+
## Code conventions
|
| 196 |
+
|
| 197 |
+
- **Async everywhere**: all route handlers, service methods, and DB calls are `async`. Never use synchronous DB calls inside an `async` context.
|
| 198 |
+
- **Pydantic schemas for I/O**: request bodies and responses use schemas from `schemas/`. Models are never returned directly.
|
| 199 |
+
- **Workspace scope on every query**: all DB queries must include a `workspace_id` filter. Use `get_current_workspace()` from `core/deps.py`.
|
| 200 |
+
- **Background work via ARQ**: do not do heavy work in a request handler. Enqueue a job with `core/tasks.enqueue(...)`.
|
| 201 |
+
- **No comments on obvious code**: only document non-obvious invariants or workarounds.
|
| 202 |
+
|
| 203 |
+
---
|
| 204 |
+
|
| 205 |
+
## Common issues
|
| 206 |
+
|
| 207 |
+
**`pgvector` extension not found**
|
| 208 |
+
```sql
|
| 209 |
+
CREATE EXTENSION IF NOT EXISTS vector;
|
| 210 |
+
```
|
| 211 |
+
Run this on your database once. Alembic migrations assume the extension exists.
|
| 212 |
+
|
| 213 |
+
**Ollama model not available**
|
| 214 |
+
```bash
|
| 215 |
+
ollama pull nomic-embed-text
|
| 216 |
+
```
|
| 217 |
+
Embedding jobs will fail silently if the model isn't pulled.
|
| 218 |
+
|
| 219 |
+
**ARQ worker not picking up jobs**
|
| 220 |
+
Check that `ARQ_REDIS_URL` points to the same Redis instance the API is using. If you see `ConnectionRefused`, Redis may not be running.
|
| 221 |
+
|
| 222 |
+
**WebSocket connections drop immediately**
|
| 223 |
+
`LOCAL_REDIS_URL` must point to a persistent Redis (not Upstash HTTP-only). Use `redis://localhost:6379` in local dev.
|
frontend/docs/nexus-customer-portal.jsx
ADDED
|
@@ -0,0 +1,623 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { useState, useEffect, useRef } from "react";
|
| 2 |
+
|
| 3 |
+
const COLORS = {
|
| 4 |
+
brand: "#1E40AF",
|
| 5 |
+
brandLight: "#EFF6FF",
|
| 6 |
+
brandMid: "#BFDBFE",
|
| 7 |
+
success: "#16A34A",
|
| 8 |
+
successLight: "#F0FDF4",
|
| 9 |
+
warning: "#D97706",
|
| 10 |
+
warningLight: "#FFFBEB",
|
| 11 |
+
danger: "#DC2626",
|
| 12 |
+
dangerLight: "#FEF2F2",
|
| 13 |
+
gray50: "#F9FAFB",
|
| 14 |
+
gray100: "#F3F4F6",
|
| 15 |
+
gray200: "#E5E7EB",
|
| 16 |
+
gray300: "#D1D5DB",
|
| 17 |
+
gray400: "#9CA3AF",
|
| 18 |
+
gray500: "#6B7280",
|
| 19 |
+
gray600: "#4B5563",
|
| 20 |
+
gray700: "#374151",
|
| 21 |
+
gray800: "#1F2937",
|
| 22 |
+
gray900: "#111827",
|
| 23 |
+
};
|
| 24 |
+
|
| 25 |
+
const MOCK_TICKETS = [
|
| 26 |
+
{ id: "TKT-1042", title: "Unable to access VPN after password reset", status: "IN_PROGRESS", priority: "HIGH", created: "2025-03-28", updated: "2 hours ago", category: "Network", sentiment: "Frustrated", aiSuggestion: "Reset your VPN credentials via the self-service portal at vpn.company.com/reset and restart the Cisco AnyConnect client.", messages: 3 },
|
| 27 |
+
{ id: "TKT-1039", title: "Excel crashes when opening files > 50MB", status: "OPEN", priority: "MEDIUM", created: "2025-03-27", updated: "1 day ago", category: "Software", sentiment: "Neutral", aiSuggestion: "Disable hardware graphics acceleration in Excel: File → Options → Advanced → Display → uncheck 'Disable hardware graphics acceleration'.", messages: 1 },
|
| 28 |
+
{ id: "TKT-1031", title: "New laptop setup - docking station not detected", status: "RESOLVED", priority: "LOW", created: "2025-03-22", updated: "5 days ago", category: "Hardware", sentiment: "Happy", aiSuggestion: "Update DisplayLink drivers and ensure the USB-C cable supports both power and data.", messages: 7 },
|
| 29 |
+
{ id: "TKT-1028", title: "Outlook not syncing calendar with mobile", status: "RESOLVED", priority: "LOW", created: "2025-03-20", updated: "7 days ago", category: "Email", sentiment: "Neutral", aiSuggestion: "Remove and re-add your Exchange account on the mobile device.", messages: 4 },
|
| 30 |
+
{ id: "TKT-1019", title: "2FA app lost after phone replacement", status: "CLOSED", priority: "URGENT", created: "2025-03-15", updated: "13 days ago", category: "Security", sentiment: "Frustrated", aiSuggestion: "Contact IT Security directly for emergency 2FA reset.", messages: 9 },
|
| 31 |
+
];
|
| 32 |
+
|
| 33 |
+
const MOCK_KB = [
|
| 34 |
+
{ id: "KB-001", title: "How to reset your VPN credentials", category: "Network", views: 1240, helpful: 94, excerpt: "Step-by-step guide to resetting your VPN password and reconfiguring client settings on Windows and Mac.", tags: ["vpn", "password", "network"] },
|
| 35 |
+
{ id: "KB-002", title: "Setting up Microsoft Authenticator on a new device", category: "Security", views: 892, helpful: 97, excerpt: "Transfer or reconfigure your 2FA app when switching devices without losing account access.", tags: ["2fa", "security", "mobile"] },
|
| 36 |
+
{ id: "KB-003", title: "Troubleshooting docking station display issues", category: "Hardware", views: 631, helpful: 88, excerpt: "Diagnose and fix common issues with external monitors and USB-C docking stations.", tags: ["hardware", "display", "docking"] },
|
| 37 |
+
{ id: "KB-004", title: "Outlook performance optimisation guide", category: "Email", views: 1055, helpful: 91, excerpt: "Reduce Outlook startup time and fix sync issues with Exchange on desktop and mobile clients.", tags: ["outlook", "email", "performance"] },
|
| 38 |
+
{ id: "KB-005", title: "Company software license portal walkthrough", category: "Software", views: 780, helpful: 86, excerpt: "How to request, activate, and manage your assigned software licenses through the IT self-service portal.", tags: ["software", "license", "portal"] },
|
| 39 |
+
{ id: "KB-006", title: "Remote desktop (RDP) setup guide", category: "Network", views: 543, helpful: 90, excerpt: "Connect to your office workstation from home using Remote Desktop Protocol on all platforms.", tags: ["rdp", "remote", "network"] },
|
| 40 |
+
];
|
| 41 |
+
|
| 42 |
+
const MOCK_STATS = {
|
| 43 |
+
open: 2, resolved: 8, avgResolution: "4.2h", csat: 4.6,
|
| 44 |
+
monthly: [
|
| 45 |
+
{ month: "Oct", open: 4, resolved: 6 },
|
| 46 |
+
{ month: "Nov", open: 3, resolved: 8 },
|
| 47 |
+
{ month: "Dec", open: 5, resolved: 4 },
|
| 48 |
+
{ month: "Jan", open: 2, resolved: 9 },
|
| 49 |
+
{ month: "Feb", open: 6, resolved: 7 },
|
| 50 |
+
{ month: "Mar", open: 3, resolved: 5 },
|
| 51 |
+
],
|
| 52 |
+
byCategory: [
|
| 53 |
+
{ name: "Network", count: 4, color: "#3B82F6" },
|
| 54 |
+
{ name: "Software", count: 3, color: "#8B5CF6" },
|
| 55 |
+
{ name: "Hardware", count: 2, color: "#10B981" },
|
| 56 |
+
{ name: "Security", count: 2, color: "#F59E0B" },
|
| 57 |
+
{ name: "Email", count: 1, color: "#EF4444" },
|
| 58 |
+
]
|
| 59 |
+
};
|
| 60 |
+
|
| 61 |
+
const THREAD_MESSAGES = [
|
| 62 |
+
{ id: 1, author: "You", role: "customer", time: "Mar 28, 10:14 AM", content: "Hi, after resetting my password yesterday I can no longer connect to the VPN. I get error code 0x0000007E. I've tried restarting but no luck." },
|
| 63 |
+
{ id: 2, author: "Nexus AI", role: "ai", time: "Mar 28, 10:14 AM", content: "Thanks for reaching out. Based on your description, this looks like a credential cache issue after a password reset. I've found 2 relevant KB articles and a similar resolved case. Here's what I'd suggest:\n\n1. Open Cisco AnyConnect → Preferences → clear saved passwords\n2. Reconnect using your new credentials\n3. If the issue persists, your IT profile may need a manual token refresh.\n\nWould you like me to escalate this to a network specialist, or does this help?" },
|
| 64 |
+
{ id: 3, author: "Priya Sharma", role: "agent", time: "Mar 28, 12:30 PM", content: "Hi there, I'm Priya from the network support team. I've reviewed your case and can see your VPN profile needs a server-side reset. I've triggered that now — please try connecting again in 5 minutes. Let me know if you still have issues!" },
|
| 65 |
+
];
|
| 66 |
+
|
| 67 |
+
const statusConfig = {
|
| 68 |
+
OPEN: { label: "Open", bg: "#EFF6FF", color: "#1E40AF", dot: "#3B82F6" },
|
| 69 |
+
IN_PROGRESS: { label: "In Progress", bg: "#FFFBEB", color: "#92400E", dot: "#F59E0B" },
|
| 70 |
+
RESOLVED: { label: "Resolved", bg: "#F0FDF4", color: "#14532D", dot: "#22C55E" },
|
| 71 |
+
CLOSED: { label: "Closed", bg: "#F9FAFB", color: "#4B5563", dot: "#9CA3AF" },
|
| 72 |
+
};
|
| 73 |
+
|
| 74 |
+
const priorityConfig = {
|
| 75 |
+
URGENT: { label: "Urgent", color: "#DC2626", bg: "#FEF2F2" },
|
| 76 |
+
HIGH: { label: "High", color: "#EA580C", bg: "#FFF7ED" },
|
| 77 |
+
MEDIUM: { label: "Medium", color: "#D97706", bg: "#FFFBEB" },
|
| 78 |
+
LOW: { label: "Low", color: "#65A30D", bg: "#F7FEE7" },
|
| 79 |
+
};
|
| 80 |
+
|
| 81 |
+
function StatusBadge({ status }) {
|
| 82 |
+
const c = statusConfig[status] || statusConfig.OPEN;
|
| 83 |
+
return (
|
| 84 |
+
<span style={{ display: "inline-flex", alignItems: "center", gap: 5, padding: "3px 10px", borderRadius: 20, fontSize: 12, fontWeight: 500, background: c.bg, color: c.color }}>
|
| 85 |
+
<span style={{ width: 6, height: 6, borderRadius: "50%", background: c.dot, flexShrink: 0 }} />
|
| 86 |
+
{c.label}
|
| 87 |
+
</span>
|
| 88 |
+
);
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
function PriorityBadge({ priority }) {
|
| 92 |
+
const c = priorityConfig[priority] || priorityConfig.MEDIUM;
|
| 93 |
+
return (
|
| 94 |
+
<span style={{ padding: "2px 8px", borderRadius: 4, fontSize: 11, fontWeight: 600, background: c.bg, color: c.color, letterSpacing: "0.03em" }}>
|
| 95 |
+
{c.label}
|
| 96 |
+
</span>
|
| 97 |
+
);
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
function Sidebar({ active, setActive, onNewTicket }) {
|
| 101 |
+
const nav = [
|
| 102 |
+
{ id: "dashboard", label: "Dashboard", icon: "⊞" },
|
| 103 |
+
{ id: "tickets", label: "My Tickets", icon: "◈" },
|
| 104 |
+
{ id: "kb", label: "Knowledge Base", icon: "◉" },
|
| 105 |
+
{ id: "analytics", label: "My Analytics", icon: "◫" },
|
| 106 |
+
];
|
| 107 |
+
return (
|
| 108 |
+
<aside style={{ width: 220, background: "#fff", borderRight: `1px solid ${COLORS.gray200}`, display: "flex", flexDirection: "column", flexShrink: 0, height: "100vh", position: "sticky", top: 0 }}>
|
| 109 |
+
<div style={{ padding: "20px 20px 16px", borderBottom: `1px solid ${COLORS.gray100}` }}>
|
| 110 |
+
<div style={{ display: "flex", alignItems: "center", gap: 10 }}>
|
| 111 |
+
<div style={{ width: 32, height: 32, borderRadius: 8, background: COLORS.brand, display: "flex", alignItems: "center", justifyContent: "center" }}>
|
| 112 |
+
<span style={{ color: "#fff", fontSize: 14, fontWeight: 700, fontFamily: "monospace" }}>N</span>
|
| 113 |
+
</div>
|
| 114 |
+
<div>
|
| 115 |
+
<div style={{ fontSize: 14, fontWeight: 600, color: COLORS.gray900 }}>Nexus</div>
|
| 116 |
+
<div style={{ fontSize: 11, color: COLORS.gray400 }}>Support Portal</div>
|
| 117 |
+
</div>
|
| 118 |
+
</div>
|
| 119 |
+
</div>
|
| 120 |
+
|
| 121 |
+
<div style={{ padding: "12px 12px 8px" }}>
|
| 122 |
+
<button onClick={onNewTicket} style={{ width: "100%", padding: "9px 14px", background: COLORS.brand, color: "#fff", border: "none", borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", gap: 6 }}>
|
| 123 |
+
<span style={{ fontSize: 16, lineHeight: 1 }}>+</span> New Ticket
|
| 124 |
+
</button>
|
| 125 |
+
</div>
|
| 126 |
+
|
| 127 |
+
<nav style={{ flex: 1, padding: "4px 12px" }}>
|
| 128 |
+
{nav.map(item => (
|
| 129 |
+
<button key={item.id} onClick={() => setActive(item.id)} style={{ width: "100%", display: "flex", alignItems: "center", gap: 10, padding: "9px 12px", borderRadius: 7, border: "none", cursor: "pointer", background: active === item.id ? COLORS.brandLight : "transparent", color: active === item.id ? COLORS.brand : COLORS.gray600, fontSize: 13, fontWeight: active === item.id ? 600 : 400, marginBottom: 2, textAlign: "left" }}>
|
| 130 |
+
<span style={{ fontSize: 14, opacity: 0.8 }}>{item.icon}</span>
|
| 131 |
+
{item.label}
|
| 132 |
+
{item.id === "tickets" && <span style={{ marginLeft: "auto", background: active === "tickets" ? COLORS.brandMid : COLORS.gray200, color: active === "tickets" ? COLORS.brand : COLORS.gray500, fontSize: 11, fontWeight: 600, borderRadius: 10, padding: "1px 7px" }}>2</span>}
|
| 133 |
+
</button>
|
| 134 |
+
))}
|
| 135 |
+
</nav>
|
| 136 |
+
|
| 137 |
+
<div style={{ padding: "12px 16px", borderTop: `1px solid ${COLORS.gray100}` }}>
|
| 138 |
+
<div style={{ display: "flex", alignItems: "center", gap: 10 }}>
|
| 139 |
+
<div style={{ width: 32, height: 32, borderRadius: "50%", background: "#EDE9FE", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 13, fontWeight: 600, color: "#6D28D9" }}>DS</div>
|
| 140 |
+
<div>
|
| 141 |
+
<div style={{ fontSize: 13, fontWeight: 500, color: COLORS.gray800 }}>Dushyant S.</div>
|
| 142 |
+
<div style={{ fontSize: 11, color: COLORS.gray400 }}>Customer</div>
|
| 143 |
+
</div>
|
| 144 |
+
</div>
|
| 145 |
+
</div>
|
| 146 |
+
</aside>
|
| 147 |
+
);
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
function TopBar({ title, subtitle }) {
|
| 151 |
+
return (
|
| 152 |
+
<div style={{ padding: "20px 32px 16px", borderBottom: `1px solid ${COLORS.gray100}`, background: "#fff", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
|
| 153 |
+
<div>
|
| 154 |
+
<h1 style={{ margin: 0, fontSize: 18, fontWeight: 600, color: COLORS.gray900 }}>{title}</h1>
|
| 155 |
+
{subtitle && <p style={{ margin: "2px 0 0", fontSize: 13, color: COLORS.gray500 }}>{subtitle}</p>}
|
| 156 |
+
</div>
|
| 157 |
+
<div style={{ display: "flex", alignItems: "center", gap: 12 }}>
|
| 158 |
+
<div style={{ position: "relative" }}>
|
| 159 |
+
<input placeholder="Search..." style={{ padding: "7px 12px 7px 34px", border: `1px solid ${COLORS.gray200}`, borderRadius: 8, fontSize: 13, color: COLORS.gray700, outline: "none", width: 200, background: COLORS.gray50 }} />
|
| 160 |
+
<span style={{ position: "absolute", left: 10, top: "50%", transform: "translateY(-50%)", color: COLORS.gray400, fontSize: 13 }}>⌕</span>
|
| 161 |
+
</div>
|
| 162 |
+
<button style={{ width: 34, height: 34, borderRadius: 8, border: `1px solid ${COLORS.gray200}`, background: "#fff", cursor: "pointer", fontSize: 14, display: "flex", alignItems: "center", justifyContent: "center", color: COLORS.gray500, position: "relative" }}>
|
| 163 |
+
🔔
|
| 164 |
+
<span style={{ position: "absolute", top: 5, right: 5, width: 7, height: 7, borderRadius: "50%", background: "#EF4444", border: "1.5px solid #fff" }} />
|
| 165 |
+
</button>
|
| 166 |
+
</div>
|
| 167 |
+
</div>
|
| 168 |
+
);
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
function Dashboard({ setActive, setSelectedTicket }) {
|
| 172 |
+
return (
|
| 173 |
+
<div style={{ padding: "24px 32px" }}>
|
| 174 |
+
<div style={{ background: `linear-gradient(135deg, ${COLORS.brand} 0%, #1D4ED8 100%)`, borderRadius: 12, padding: "24px 28px", marginBottom: 24, color: "#fff" }}>
|
| 175 |
+
<div style={{ fontSize: 13, opacity: 0.8, marginBottom: 4 }}>Good morning,</div>
|
| 176 |
+
<div style={{ fontSize: 22, fontWeight: 600, marginBottom: 8 }}>Dushyant</div>
|
| 177 |
+
<div style={{ fontSize: 13, opacity: 0.85 }}>You have <strong>2 open tickets</strong> and 1 awaiting your reply.</div>
|
| 178 |
+
<button onClick={() => setActive("tickets")} style={{ marginTop: 14, padding: "8px 16px", background: "rgba(255,255,255,0.2)", border: "1px solid rgba(255,255,255,0.3)", borderRadius: 7, color: "#fff", fontSize: 13, cursor: "pointer", fontWeight: 500 }}>View my tickets →</button>
|
| 179 |
+
</div>
|
| 180 |
+
|
| 181 |
+
<div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 24 }}>
|
| 182 |
+
{[
|
| 183 |
+
{ label: "Open tickets", value: "2", sub: "Active cases", color: COLORS.brand },
|
| 184 |
+
{ label: "Resolved (30d)", value: "8", sub: "+3 this week", color: COLORS.success },
|
| 185 |
+
{ label: "Avg. resolution", value: "4.2h", sub: "Last 30 days", color: "#7C3AED" },
|
| 186 |
+
{ label: "CSAT score", value: "4.6★", sub: "Based on 8 ratings", color: "#D97706" },
|
| 187 |
+
].map(s => (
|
| 188 |
+
<div key={s.label} style={{ background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 10, padding: "16px 18px" }}>
|
| 189 |
+
<div style={{ fontSize: 12, color: COLORS.gray500, marginBottom: 6, fontWeight: 500 }}>{s.label}</div>
|
| 190 |
+
<div style={{ fontSize: 24, fontWeight: 700, color: s.color, marginBottom: 2 }}>{s.value}</div>
|
| 191 |
+
<div style={{ fontSize: 11, color: COLORS.gray400 }}>{s.sub}</div>
|
| 192 |
+
</div>
|
| 193 |
+
))}
|
| 194 |
+
</div>
|
| 195 |
+
|
| 196 |
+
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
|
| 197 |
+
<div style={{ background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 10, padding: "20px" }}>
|
| 198 |
+
<div style={{ fontSize: 14, fontWeight: 600, color: COLORS.gray800, marginBottom: 16 }}>Active tickets</div>
|
| 199 |
+
{MOCK_TICKETS.filter(t => t.status === "OPEN" || t.status === "IN_PROGRESS").map(t => (
|
| 200 |
+
<div key={t.id} onClick={() => { setSelectedTicket(t); setActive("thread"); }} style={{ display: "flex", alignItems: "flex-start", gap: 12, padding: "12px 0", borderTop: `1px solid ${COLORS.gray100}`, cursor: "pointer" }}>
|
| 201 |
+
<div style={{ flex: 1, minWidth: 0 }}>
|
| 202 |
+
<div style={{ fontSize: 13, fontWeight: 500, color: COLORS.gray800, marginBottom: 4, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{t.title}</div>
|
| 203 |
+
<div style={{ display: "flex", gap: 6, alignItems: "center" }}>
|
| 204 |
+
<span style={{ fontSize: 11, color: COLORS.gray400 }}>{t.id}</span>
|
| 205 |
+
<span style={{ fontSize: 11, color: COLORS.gray300 }}>·</span>
|
| 206 |
+
<StatusBadge status={t.status} />
|
| 207 |
+
</div>
|
| 208 |
+
</div>
|
| 209 |
+
<div style={{ fontSize: 11, color: COLORS.gray400, flexShrink: 0, paddingTop: 2 }}>{t.updated}</div>
|
| 210 |
+
</div>
|
| 211 |
+
))}
|
| 212 |
+
</div>
|
| 213 |
+
|
| 214 |
+
<div style={{ background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 10, padding: "20px" }}>
|
| 215 |
+
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
|
| 216 |
+
<div style={{ fontSize: 14, fontWeight: 600, color: COLORS.gray800 }}>Suggested articles</div>
|
| 217 |
+
<button onClick={() => setActive("kb")} style={{ fontSize: 12, color: COLORS.brand, background: "none", border: "none", cursor: "pointer", fontWeight: 500 }}>View all →</button>
|
| 218 |
+
</div>
|
| 219 |
+
{MOCK_KB.slice(0, 4).map(a => (
|
| 220 |
+
<div key={a.id} style={{ padding: "10px 0", borderTop: `1px solid ${COLORS.gray100}` }}>
|
| 221 |
+
<div style={{ fontSize: 13, fontWeight: 500, color: COLORS.gray800, marginBottom: 3 }}>{a.title}</div>
|
| 222 |
+
<div style={{ display: "flex", gap: 8, alignItems: "center" }}>
|
| 223 |
+
<span style={{ fontSize: 11, padding: "2px 7px", background: COLORS.gray100, color: COLORS.gray500, borderRadius: 4 }}>{a.category}</span>
|
| 224 |
+
<span style={{ fontSize: 11, color: COLORS.gray400 }}>{a.helpful}% helpful</span>
|
| 225 |
+
</div>
|
| 226 |
+
</div>
|
| 227 |
+
))}
|
| 228 |
+
</div>
|
| 229 |
+
</div>
|
| 230 |
+
</div>
|
| 231 |
+
);
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
function TicketList({ setActive, setSelectedTicket }) {
|
| 235 |
+
const [filter, setFilter] = useState("ALL");
|
| 236 |
+
const filters = ["ALL", "OPEN", "IN_PROGRESS", "RESOLVED", "CLOSED"];
|
| 237 |
+
const filtered = filter === "ALL" ? MOCK_TICKETS : MOCK_TICKETS.filter(t => t.status === filter);
|
| 238 |
+
|
| 239 |
+
return (
|
| 240 |
+
<div style={{ padding: "24px 32px" }}>
|
| 241 |
+
<div style={{ display: "flex", gap: 8, marginBottom: 20, borderBottom: `1px solid ${COLORS.gray200}`, paddingBottom: 16 }}>
|
| 242 |
+
{filters.map(f => (
|
| 243 |
+
<button key={f} onClick={() => setFilter(f)} style={{ padding: "6px 14px", borderRadius: 20, border: "none", cursor: "pointer", fontSize: 12, fontWeight: 500, background: filter === f ? COLORS.brand : COLORS.gray100, color: filter === f ? "#fff" : COLORS.gray600 }}>
|
| 244 |
+
{f === "ALL" ? "All" : statusConfig[f]?.label}
|
| 245 |
+
{f === "ALL" && <span style={{ marginLeft: 6, background: filter === "ALL" ? "rgba(255,255,255,0.25)" : COLORS.gray200, borderRadius: 10, padding: "0 6px", fontSize: 11 }}>{MOCK_TICKETS.length}</span>}
|
| 246 |
+
</button>
|
| 247 |
+
))}
|
| 248 |
+
</div>
|
| 249 |
+
|
| 250 |
+
<div style={{ background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 10, overflow: "hidden" }}>
|
| 251 |
+
<table style={{ width: "100%", borderCollapse: "collapse" }}>
|
| 252 |
+
<thead>
|
| 253 |
+
<tr style={{ background: COLORS.gray50 }}>
|
| 254 |
+
{["Ticket ID", "Subject", "Category", "Priority", "Status", "Updated"].map(h => (
|
| 255 |
+
<th key={h} style={{ padding: "10px 16px", textAlign: "left", fontSize: 11, fontWeight: 600, color: COLORS.gray500, letterSpacing: "0.05em", textTransform: "uppercase", borderBottom: `1px solid ${COLORS.gray200}` }}>{h}</th>
|
| 256 |
+
))}
|
| 257 |
+
</tr>
|
| 258 |
+
</thead>
|
| 259 |
+
<tbody>
|
| 260 |
+
{filtered.map((t, i) => (
|
| 261 |
+
<tr key={t.id} onClick={() => { setSelectedTicket(t); setActive("thread"); }} style={{ borderBottom: i < filtered.length - 1 ? `1px solid ${COLORS.gray100}` : "none", cursor: "pointer", background: "#fff" }}
|
| 262 |
+
onMouseEnter={e => e.currentTarget.style.background = COLORS.gray50}
|
| 263 |
+
onMouseLeave={e => e.currentTarget.style.background = "#fff"}>
|
| 264 |
+
<td style={{ padding: "14px 16px", fontSize: 12, color: COLORS.brand, fontWeight: 600, fontFamily: "monospace" }}>{t.id}</td>
|
| 265 |
+
<td style={{ padding: "14px 16px" }}>
|
| 266 |
+
<div style={{ fontSize: 13, fontWeight: 500, color: COLORS.gray800 }}>{t.title}</div>
|
| 267 |
+
{t.messages > 1 && <div style={{ fontSize: 11, color: COLORS.gray400, marginTop: 2 }}>{t.messages} messages</div>}
|
| 268 |
+
</td>
|
| 269 |
+
<td style={{ padding: "14px 16px", fontSize: 12, color: COLORS.gray500 }}>{t.category}</td>
|
| 270 |
+
<td style={{ padding: "14px 16px" }}><PriorityBadge priority={t.priority} /></td>
|
| 271 |
+
<td style={{ padding: "14px 16px" }}><StatusBadge status={t.status} /></td>
|
| 272 |
+
<td style={{ padding: "14px 16px", fontSize: 12, color: COLORS.gray400 }}>{t.updated}</td>
|
| 273 |
+
</tr>
|
| 274 |
+
))}
|
| 275 |
+
</tbody>
|
| 276 |
+
</table>
|
| 277 |
+
</div>
|
| 278 |
+
</div>
|
| 279 |
+
);
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
function ThreadView({ ticket, onBack }) {
|
| 283 |
+
const [message, setMessage] = useState("");
|
| 284 |
+
const [sent, setSent] = useState(false);
|
| 285 |
+
const bottomRef = useRef(null);
|
| 286 |
+
|
| 287 |
+
const handleSend = () => {
|
| 288 |
+
if (message.trim()) { setSent(true); setMessage(""); }
|
| 289 |
+
};
|
| 290 |
+
|
| 291 |
+
return (
|
| 292 |
+
<div style={{ padding: "0", display: "flex", flexDirection: "column", height: "calc(100vh - 60px)" }}>
|
| 293 |
+
<div style={{ padding: "16px 32px", borderBottom: `1px solid ${COLORS.gray200}`, background: "#fff", display: "flex", alignItems: "center", gap: 14 }}>
|
| 294 |
+
<button onClick={onBack} style={{ background: "none", border: `1px solid ${COLORS.gray200}`, borderRadius: 7, padding: "5px 12px", fontSize: 12, cursor: "pointer", color: COLORS.gray600, display: "flex", alignItems: "center", gap: 4 }}>← Back</button>
|
| 295 |
+
<div style={{ flex: 1 }}>
|
| 296 |
+
<div style={{ fontSize: 15, fontWeight: 600, color: COLORS.gray900 }}>{ticket.title}</div>
|
| 297 |
+
<div style={{ display: "flex", gap: 8, alignItems: "center", marginTop: 3 }}>
|
| 298 |
+
<span style={{ fontSize: 12, color: COLORS.gray400, fontFamily: "monospace" }}>{ticket.id}</span>
|
| 299 |
+
<StatusBadge status={ticket.status} />
|
| 300 |
+
<PriorityBadge priority={ticket.priority} />
|
| 301 |
+
</div>
|
| 302 |
+
</div>
|
| 303 |
+
</div>
|
| 304 |
+
|
| 305 |
+
<div style={{ flex: 1, overflowY: "auto", padding: "24px 32px", background: COLORS.gray50, display: "flex", flexDirection: "column", gap: 16 }}>
|
| 306 |
+
{THREAD_MESSAGES.map(msg => (
|
| 307 |
+
<div key={msg.id} style={{ display: "flex", gap: 12, flexDirection: msg.role === "customer" ? "row-reverse" : "row" }}>
|
| 308 |
+
<div style={{ width: 34, height: 34, borderRadius: "50%", flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 600, background: msg.role === "customer" ? "#EDE9FE" : msg.role === "ai" ? COLORS.brandLight : "#FEF3C7", color: msg.role === "customer" ? "#6D28D9" : msg.role === "ai" ? COLORS.brand : "#92400E" }}>
|
| 309 |
+
{msg.role === "customer" ? "DS" : msg.role === "ai" ? "AI" : "PS"}
|
| 310 |
+
</div>
|
| 311 |
+
<div style={{ maxWidth: "70%" }}>
|
| 312 |
+
<div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 5, flexDirection: msg.role === "customer" ? "row-reverse" : "row" }}>
|
| 313 |
+
<span style={{ fontSize: 12, fontWeight: 600, color: COLORS.gray700 }}>{msg.author}</span>
|
| 314 |
+
{msg.role === "ai" && <span style={{ fontSize: 10, padding: "1px 7px", background: COLORS.brandLight, color: COLORS.brand, borderRadius: 10, fontWeight: 600 }}>AI Draft</span>}
|
| 315 |
+
<span style={{ fontSize: 11, color: COLORS.gray400 }}>{msg.time}</span>
|
| 316 |
+
</div>
|
| 317 |
+
<div style={{ background: msg.role === "customer" ? COLORS.brand : "#fff", color: msg.role === "customer" ? "#fff" : COLORS.gray700, borderRadius: msg.role === "customer" ? "12px 4px 12px 12px" : "4px 12px 12px 12px", padding: "12px 16px", fontSize: 13, lineHeight: 1.6, border: msg.role === "customer" ? "none" : `1px solid ${COLORS.gray200}`, whiteSpace: "pre-line" }}>
|
| 318 |
+
{msg.content}
|
| 319 |
+
</div>
|
| 320 |
+
</div>
|
| 321 |
+
</div>
|
| 322 |
+
))}
|
| 323 |
+
{sent && (
|
| 324 |
+
<div style={{ display: "flex", gap: 12, flexDirection: "row-reverse" }}>
|
| 325 |
+
<div style={{ width: 34, height: 34, borderRadius: "50%", background: "#EDE9FE", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 600, color: "#6D28D9" }}>DS</div>
|
| 326 |
+
<div style={{ maxWidth: "70%" }}>
|
| 327 |
+
<div style={{ display: "flex", justifyContent: "flex-end", marginBottom: 5 }}>
|
| 328 |
+
<span style={{ fontSize: 12, fontWeight: 600, color: COLORS.gray700 }}>You</span>
|
| 329 |
+
</div>
|
| 330 |
+
<div style={{ background: COLORS.brand, color: "#fff", borderRadius: "12px 4px 12px 12px", padding: "12px 16px", fontSize: 13, lineHeight: 1.6 }}>Your message has been sent.</div>
|
| 331 |
+
</div>
|
| 332 |
+
</div>
|
| 333 |
+
)}
|
| 334 |
+
<div ref={bottomRef} />
|
| 335 |
+
</div>
|
| 336 |
+
|
| 337 |
+
<div style={{ padding: "16px 32px", background: "#fff", borderTop: `1px solid ${COLORS.gray200}` }}>
|
| 338 |
+
<div style={{ border: `1px solid ${COLORS.gray200}`, borderRadius: 10, overflow: "hidden", background: "#fff" }}>
|
| 339 |
+
<textarea value={message} onChange={e => setMessage(e.target.value)} placeholder="Write a reply..." style={{ width: "100%", minHeight: 80, padding: "12px 16px", border: "none", resize: "none", fontSize: 13, color: COLORS.gray700, outline: "none", fontFamily: "inherit", boxSizing: "border-box" }} />
|
| 340 |
+
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "8px 12px", background: COLORS.gray50, borderTop: `1px solid ${COLORS.gray100}` }}>
|
| 341 |
+
<div style={{ display: "flex", gap: 8 }}>
|
| 342 |
+
{["📎", "🖼️"].map(icon => (
|
| 343 |
+
<button key={icon} style={{ background: "none", border: "none", cursor: "pointer", fontSize: 14, padding: "4px 6px", borderRadius: 5, color: COLORS.gray400 }}>{icon}</button>
|
| 344 |
+
))}
|
| 345 |
+
</div>
|
| 346 |
+
<button onClick={handleSend} disabled={!message.trim()} style={{ padding: "7px 18px", background: message.trim() ? COLORS.brand : COLORS.gray300, color: "#fff", border: "none", borderRadius: 7, fontSize: 13, fontWeight: 600, cursor: message.trim() ? "pointer" : "default", transition: "background 0.15s" }}>Send reply</button>
|
| 347 |
+
</div>
|
| 348 |
+
</div>
|
| 349 |
+
</div>
|
| 350 |
+
</div>
|
| 351 |
+
);
|
| 352 |
+
}
|
| 353 |
+
|
| 354 |
+
function NewTicketModal({ onClose, onCreate }) {
|
| 355 |
+
const [form, setForm] = useState({ title: "", category: "Network", priority: "MEDIUM", description: "" });
|
| 356 |
+
const [submitted, setSubmitted] = useState(false);
|
| 357 |
+
|
| 358 |
+
const handleSubmit = () => {
|
| 359 |
+
if (form.title && form.description) { setSubmitted(true); setTimeout(() => { onCreate(form); onClose(); }, 1500); }
|
| 360 |
+
};
|
| 361 |
+
|
| 362 |
+
return (
|
| 363 |
+
<div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.4)", zIndex: 100, display: "flex", alignItems: "center", justifyContent: "center" }}>
|
| 364 |
+
<div style={{ background: "#fff", borderRadius: 14, padding: "28px 32px", width: 540, maxWidth: "90vw", boxShadow: "0 20px 60px rgba(0,0,0,0.15)" }}>
|
| 365 |
+
{submitted ? (
|
| 366 |
+
<div style={{ textAlign: "center", padding: "20px 0" }}>
|
| 367 |
+
<div style={{ fontSize: 40, marginBottom: 12 }}>✓</div>
|
| 368 |
+
<div style={{ fontSize: 16, fontWeight: 600, color: COLORS.gray800, marginBottom: 6 }}>Ticket submitted!</div>
|
| 369 |
+
<div style={{ fontSize: 13, color: COLORS.gray500 }}>Our AI is triaging your request now...</div>
|
| 370 |
+
</div>
|
| 371 |
+
) : (
|
| 372 |
+
<>
|
| 373 |
+
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 24 }}>
|
| 374 |
+
<div style={{ fontSize: 16, fontWeight: 600, color: COLORS.gray900 }}>Create new ticket</div>
|
| 375 |
+
<button onClick={onClose} style={{ background: "none", border: "none", cursor: "pointer", fontSize: 18, color: COLORS.gray400, lineHeight: 1 }}>×</button>
|
| 376 |
+
</div>
|
| 377 |
+
<div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
|
| 378 |
+
<div>
|
| 379 |
+
<label style={{ display: "block", fontSize: 12, fontWeight: 600, color: COLORS.gray600, marginBottom: 6 }}>Subject *</label>
|
| 380 |
+
<input value={form.title} onChange={e => setForm(f => ({ ...f, title: e.target.value }))} placeholder="Briefly describe your issue" style={{ width: "100%", padding: "9px 12px", border: `1px solid ${COLORS.gray200}`, borderRadius: 8, fontSize: 13, outline: "none", boxSizing: "border-box" }} />
|
| 381 |
+
</div>
|
| 382 |
+
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
|
| 383 |
+
<div>
|
| 384 |
+
<label style={{ display: "block", fontSize: 12, fontWeight: 600, color: COLORS.gray600, marginBottom: 6 }}>Category</label>
|
| 385 |
+
<select value={form.category} onChange={e => setForm(f => ({ ...f, category: e.target.value }))} style={{ width: "100%", padding: "9px 12px", border: `1px solid ${COLORS.gray200}`, borderRadius: 8, fontSize: 13, outline: "none" }}>
|
| 386 |
+
{["Network", "Software", "Hardware", "Security", "Email", "Other"].map(c => <option key={c}>{c}</option>)}
|
| 387 |
+
</select>
|
| 388 |
+
</div>
|
| 389 |
+
<div>
|
| 390 |
+
<label style={{ display: "block", fontSize: 12, fontWeight: 600, color: COLORS.gray600, marginBottom: 6 }}>Priority</label>
|
| 391 |
+
<select value={form.priority} onChange={e => setForm(f => ({ ...f, priority: e.target.value }))} style={{ width: "100%", padding: "9px 12px", border: `1px solid ${COLORS.gray200}`, borderRadius: 8, fontSize: 13, outline: "none" }}>
|
| 392 |
+
{["LOW", "MEDIUM", "HIGH", "URGENT"].map(p => <option key={p}>{p}</option>)}
|
| 393 |
+
</select>
|
| 394 |
+
</div>
|
| 395 |
+
</div>
|
| 396 |
+
<div>
|
| 397 |
+
<label style={{ display: "block", fontSize: 12, fontWeight: 600, color: COLORS.gray600, marginBottom: 6 }}>Description *</label>
|
| 398 |
+
<textarea value={form.description} onChange={e => setForm(f => ({ ...f, description: e.target.value }))} placeholder="Provide as much detail as possible..." style={{ width: "100%", padding: "9px 12px", border: `1px solid ${COLORS.gray200}`, borderRadius: 8, fontSize: 13, outline: "none", minHeight: 100, resize: "vertical", fontFamily: "inherit", boxSizing: "border-box" }} />
|
| 399 |
+
</div>
|
| 400 |
+
<div style={{ background: COLORS.brandLight, borderRadius: 8, padding: "10px 14px", fontSize: 12, color: COLORS.brand, display: "flex", gap: 8 }}>
|
| 401 |
+
<span>✦</span> Our AI will automatically triage, categorise, and suggest solutions for your ticket.
|
| 402 |
+
</div>
|
| 403 |
+
<div style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}>
|
| 404 |
+
<button onClick={onClose} style={{ padding: "9px 18px", background: "none", border: `1px solid ${COLORS.gray200}`, borderRadius: 8, fontSize: 13, cursor: "pointer", color: COLORS.gray600 }}>Cancel</button>
|
| 405 |
+
<button onClick={handleSubmit} style={{ padding: "9px 20px", background: COLORS.brand, color: "#fff", border: "none", borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: "pointer" }}>Submit ticket</button>
|
| 406 |
+
</div>
|
| 407 |
+
</div>
|
| 408 |
+
</>
|
| 409 |
+
)}
|
| 410 |
+
</div>
|
| 411 |
+
</div>
|
| 412 |
+
);
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
function KnowledgeBase() {
|
| 416 |
+
const [search, setSearch] = useState("");
|
| 417 |
+
const [activeTag, setActiveTag] = useState(null);
|
| 418 |
+
const [expanded, setExpanded] = useState(null);
|
| 419 |
+
|
| 420 |
+
const allTags = [...new Set(MOCK_KB.flatMap(a => a.tags))];
|
| 421 |
+
const filtered = MOCK_KB.filter(a => {
|
| 422 |
+
const matchSearch = !search || a.title.toLowerCase().includes(search.toLowerCase()) || a.excerpt.toLowerCase().includes(search.toLowerCase());
|
| 423 |
+
const matchTag = !activeTag || a.tags.includes(activeTag);
|
| 424 |
+
return matchSearch && matchTag;
|
| 425 |
+
});
|
| 426 |
+
|
| 427 |
+
return (
|
| 428 |
+
<div style={{ padding: "24px 32px" }}>
|
| 429 |
+
<div style={{ background: COLORS.brand, borderRadius: 12, padding: "28px 32px", marginBottom: 24, color: "#fff" }}>
|
| 430 |
+
<div style={{ fontSize: 20, fontWeight: 700, marginBottom: 6 }}>Knowledge Base</div>
|
| 431 |
+
<div style={{ fontSize: 13, opacity: 0.85, marginBottom: 16 }}>Search for guides, troubleshooting steps, and how-to articles.</div>
|
| 432 |
+
<div style={{ position: "relative", maxWidth: 480 }}>
|
| 433 |
+
<input value={search} onChange={e => setSearch(e.target.value)} placeholder="e.g. VPN setup, Outlook not syncing, 2FA..." style={{ width: "100%", padding: "11px 16px 11px 40px", borderRadius: 8, border: "none", fontSize: 14, boxSizing: "border-box", outline: "none" }} />
|
| 434 |
+
<span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", fontSize: 16, opacity: 0.4 }}>⌕</span>
|
| 435 |
+
</div>
|
| 436 |
+
</div>
|
| 437 |
+
|
| 438 |
+
<div style={{ display: "flex", gap: 8, marginBottom: 20, flexWrap: "wrap" }}>
|
| 439 |
+
<button onClick={() => setActiveTag(null)} style={{ padding: "5px 12px", borderRadius: 16, border: "none", background: !activeTag ? COLORS.brand : COLORS.gray100, color: !activeTag ? "#fff" : COLORS.gray600, fontSize: 12, cursor: "pointer", fontWeight: 500 }}>All topics</button>
|
| 440 |
+
{allTags.map(tag => (
|
| 441 |
+
<button key={tag} onClick={() => setActiveTag(activeTag === tag ? null : tag)} style={{ padding: "5px 12px", borderRadius: 16, border: "none", background: activeTag === tag ? COLORS.brand : COLORS.gray100, color: activeTag === tag ? "#fff" : COLORS.gray600, fontSize: 12, cursor: "pointer" }}>{tag}</button>
|
| 442 |
+
))}
|
| 443 |
+
</div>
|
| 444 |
+
|
| 445 |
+
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
|
| 446 |
+
{filtered.map(article => (
|
| 447 |
+
<div key={article.id} style={{ background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 10, padding: "18px 20px", cursor: "pointer" }} onClick={() => setExpanded(expanded === article.id ? null : article.id)}>
|
| 448 |
+
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 8 }}>
|
| 449 |
+
<span style={{ fontSize: 11, padding: "2px 8px", background: COLORS.gray100, color: COLORS.gray500, borderRadius: 4, fontWeight: 500 }}>{article.category}</span>
|
| 450 |
+
<span style={{ fontSize: 11, color: COLORS.success, fontWeight: 600 }}>{article.helpful}% helpful</span>
|
| 451 |
+
</div>
|
| 452 |
+
<div style={{ fontSize: 14, fontWeight: 600, color: COLORS.gray800, marginBottom: 6, lineHeight: 1.4 }}>{article.title}</div>
|
| 453 |
+
<div style={{ fontSize: 12, color: COLORS.gray500, lineHeight: 1.5, marginBottom: 10 }}>{article.excerpt}</div>
|
| 454 |
+
{expanded === article.id && (
|
| 455 |
+
<div style={{ marginTop: 12, padding: "12px 14px", background: COLORS.gray50, borderRadius: 7, fontSize: 12, color: COLORS.gray600, lineHeight: 1.6, borderLeft: `3px solid ${COLORS.brand}` }}>
|
| 456 |
+
<strong>Step 1:</strong> Open Settings and navigate to the relevant section.<br />
|
| 457 |
+
<strong>Step 2:</strong> Follow the on-screen prompts to complete the configuration.<br />
|
| 458 |
+
<strong>Step 3:</strong> Restart the affected application or service.<br /><br />
|
| 459 |
+
Still having issues? <span style={{ color: COLORS.brand, fontWeight: 500 }}>Submit a ticket →</span>
|
| 460 |
+
</div>
|
| 461 |
+
)}
|
| 462 |
+
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 8 }}>
|
| 463 |
+
<div style={{ display: "flex", gap: 6 }}>
|
| 464 |
+
{article.tags.map(tag => <span key={tag} style={{ fontSize: 10, padding: "2px 6px", background: COLORS.brandLight, color: COLORS.brand, borderRadius: 4 }}>#{tag}</span>)}
|
| 465 |
+
</div>
|
| 466 |
+
<span style={{ fontSize: 11, color: COLORS.gray400 }}>{article.views.toLocaleString()} views</span>
|
| 467 |
+
</div>
|
| 468 |
+
</div>
|
| 469 |
+
))}
|
| 470 |
+
</div>
|
| 471 |
+
</div>
|
| 472 |
+
);
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
+
function Analytics() {
|
| 476 |
+
const maxVal = Math.max(...MOCK_STATS.monthly.flatMap(m => [m.open, m.resolved]));
|
| 477 |
+
const total = MOCK_STATS.byCategory.reduce((s, c) => s + c.count, 0);
|
| 478 |
+
let angle = -90;
|
| 479 |
+
|
| 480 |
+
return (
|
| 481 |
+
<div style={{ padding: "24px 32px" }}>
|
| 482 |
+
<div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 24 }}>
|
| 483 |
+
{[
|
| 484 |
+
{ label: "Total tickets", value: "12", change: "+2 this month" },
|
| 485 |
+
{ label: "Resolved", value: "8", change: "66% resolution rate" },
|
| 486 |
+
{ label: "Avg. response", value: "1.8h", change: "First response" },
|
| 487 |
+
{ label: "Satisfaction", value: "4.6 / 5", change: "8 ratings given" },
|
| 488 |
+
].map(s => (
|
| 489 |
+
<div key={s.label} style={{ background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 10, padding: "16px 18px" }}>
|
| 490 |
+
<div style={{ fontSize: 12, color: COLORS.gray500, marginBottom: 6, fontWeight: 500 }}>{s.label}</div>
|
| 491 |
+
<div style={{ fontSize: 22, fontWeight: 700, color: COLORS.gray900, marginBottom: 4 }}>{s.value}</div>
|
| 492 |
+
<div style={{ fontSize: 11, color: COLORS.gray400 }}>{s.change}</div>
|
| 493 |
+
</div>
|
| 494 |
+
))}
|
| 495 |
+
</div>
|
| 496 |
+
|
| 497 |
+
<div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 20, marginBottom: 20 }}>
|
| 498 |
+
<div style={{ background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 10, padding: "20px 24px" }}>
|
| 499 |
+
<div style={{ fontSize: 14, fontWeight: 600, color: COLORS.gray800, marginBottom: 20 }}>Ticket volume — last 6 months</div>
|
| 500 |
+
<div style={{ display: "flex", alignItems: "flex-end", gap: 10, height: 140 }}>
|
| 501 |
+
{MOCK_STATS.monthly.map(m => (
|
| 502 |
+
<div key={m.month} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
|
| 503 |
+
<div style={{ width: "100%", display: "flex", gap: 2, alignItems: "flex-end", height: 110 }}>
|
| 504 |
+
<div style={{ flex: 1, background: "#BFDBFE", borderRadius: "3px 3px 0 0", height: `${(m.open / maxVal) * 100}%`, minHeight: 4 }} title={`Open: ${m.open}`} />
|
| 505 |
+
<div style={{ flex: 1, background: COLORS.brand, borderRadius: "3px 3px 0 0", height: `${(m.resolved / maxVal) * 100}%`, minHeight: 4 }} title={`Resolved: ${m.resolved}`} />
|
| 506 |
+
</div>
|
| 507 |
+
<span style={{ fontSize: 11, color: COLORS.gray400 }}>{m.month}</span>
|
| 508 |
+
</div>
|
| 509 |
+
))}
|
| 510 |
+
</div>
|
| 511 |
+
<div style={{ display: "flex", gap: 16, marginTop: 12 }}>
|
| 512 |
+
<div style={{ display: "flex", alignItems: "center", gap: 6 }}><div style={{ width: 12, height: 12, background: "#BFDBFE", borderRadius: 2 }} /><span style={{ fontSize: 11, color: COLORS.gray500 }}>Open</span></div>
|
| 513 |
+
<div style={{ display: "flex", alignItems: "center", gap: 6 }}><div style={{ width: 12, height: 12, background: COLORS.brand, borderRadius: 2 }} /><span style={{ fontSize: 11, color: COLORS.gray500 }}>Resolved</span></div>
|
| 514 |
+
</div>
|
| 515 |
+
</div>
|
| 516 |
+
|
| 517 |
+
<div style={{ background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 10, padding: "20px 24px" }}>
|
| 518 |
+
<div style={{ fontSize: 14, fontWeight: 600, color: COLORS.gray800, marginBottom: 16 }}>By category</div>
|
| 519 |
+
<svg viewBox="0 0 120 120" style={{ width: "100%", maxWidth: 140, display: "block", margin: "0 auto 16px" }}>
|
| 520 |
+
{MOCK_STATS.byCategory.map(cat => {
|
| 521 |
+
const pct = cat.count / total;
|
| 522 |
+
const sweep = pct * 360;
|
| 523 |
+
const startAngle = angle;
|
| 524 |
+
angle += sweep;
|
| 525 |
+
const r = 50, cx = 60, cy = 60;
|
| 526 |
+
const toRad = deg => (deg * Math.PI) / 180;
|
| 527 |
+
const x1 = cx + r * Math.cos(toRad(startAngle));
|
| 528 |
+
const y1 = cy + r * Math.sin(toRad(startAngle));
|
| 529 |
+
const x2 = cx + r * Math.cos(toRad(startAngle + sweep));
|
| 530 |
+
const y2 = cy + r * Math.sin(toRad(startAngle + sweep));
|
| 531 |
+
const large = sweep > 180 ? 1 : 0;
|
| 532 |
+
return <path key={cat.name} d={`M ${cx} ${cy} L ${x1} ${y1} A ${r} ${r} 0 ${large} 1 ${x2} ${y2} Z`} fill={cat.color} stroke="#fff" strokeWidth={1.5} />;
|
| 533 |
+
})}
|
| 534 |
+
<circle cx="60" cy="60" r="28" fill="#fff" />
|
| 535 |
+
<text x="60" y="57" textAnchor="middle" style={{ fontSize: 14, fontWeight: 700, fill: COLORS.gray800 }}>{total}</text>
|
| 536 |
+
<text x="60" y="68" textAnchor="middle" style={{ fontSize: 7, fill: COLORS.gray400 }}>tickets</text>
|
| 537 |
+
</svg>
|
| 538 |
+
<div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
|
| 539 |
+
{MOCK_STATS.byCategory.map(cat => (
|
| 540 |
+
<div key={cat.name} style={{ display: "flex", alignItems: "center", gap: 8 }}>
|
| 541 |
+
<div style={{ width: 8, height: 8, borderRadius: "50%", background: cat.color, flexShrink: 0 }} />
|
| 542 |
+
<span style={{ fontSize: 12, color: COLORS.gray600, flex: 1 }}>{cat.name}</span>
|
| 543 |
+
<span style={{ fontSize: 12, fontWeight: 500, color: COLORS.gray800 }}>{cat.count}</span>
|
| 544 |
+
</div>
|
| 545 |
+
))}
|
| 546 |
+
</div>
|
| 547 |
+
</div>
|
| 548 |
+
</div>
|
| 549 |
+
|
| 550 |
+
<div style={{ background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 10, padding: "20px 24px" }}>
|
| 551 |
+
<div style={{ fontSize: 14, fontWeight: 600, color: COLORS.gray800, marginBottom: 16 }}>Recent ticket history</div>
|
| 552 |
+
<div style={{ overflowX: "auto" }}>
|
| 553 |
+
<table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
|
| 554 |
+
<thead>
|
| 555 |
+
<tr>
|
| 556 |
+
{["Ticket", "Subject", "Status", "Priority", "Resolution time", "Rating"].map(h => (
|
| 557 |
+
<th key={h} style={{ textAlign: "left", padding: "8px 12px", fontSize: 11, fontWeight: 600, color: COLORS.gray500, borderBottom: `1px solid ${COLORS.gray100}`, letterSpacing: "0.05em", textTransform: "uppercase" }}>{h}</th>
|
| 558 |
+
))}
|
| 559 |
+
</tr>
|
| 560 |
+
</thead>
|
| 561 |
+
<tbody>
|
| 562 |
+
{MOCK_TICKETS.map(t => (
|
| 563 |
+
<tr key={t.id} style={{ borderBottom: `1px solid ${COLORS.gray50}` }}>
|
| 564 |
+
<td style={{ padding: "10px 12px", fontSize: 12, fontFamily: "monospace", color: COLORS.brand, fontWeight: 600 }}>{t.id}</td>
|
| 565 |
+
<td style={{ padding: "10px 12px", maxWidth: 200, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", color: COLORS.gray700 }}>{t.title}</td>
|
| 566 |
+
<td style={{ padding: "10px 12px" }}><StatusBadge status={t.status} /></td>
|
| 567 |
+
<td style={{ padding: "10px 12px" }}><PriorityBadge priority={t.priority} /></td>
|
| 568 |
+
<td style={{ padding: "10px 12px", fontSize: 12, color: COLORS.gray500 }}>{t.status === "RESOLVED" || t.status === "CLOSED" ? `${Math.floor(Math.random() * 6 + 1)}h ${Math.floor(Math.random() * 50 + 5)}m` : "—"}</td>
|
| 569 |
+
<td style={{ padding: "10px 12px", fontSize: 13 }}>{t.status === "RESOLVED" || t.status === "CLOSED" ? "★★★★★" : "—"}</td>
|
| 570 |
+
</tr>
|
| 571 |
+
))}
|
| 572 |
+
</tbody>
|
| 573 |
+
</table>
|
| 574 |
+
</div>
|
| 575 |
+
</div>
|
| 576 |
+
</div>
|
| 577 |
+
);
|
| 578 |
+
}
|
| 579 |
+
|
| 580 |
+
export default function CustomerPortal() {
|
| 581 |
+
const [active, setActive] = useState("dashboard");
|
| 582 |
+
const [showNewTicket, setShowNewTicket] = useState(false);
|
| 583 |
+
const [selectedTicket, setSelectedTicket] = useState(null);
|
| 584 |
+
const [tickets, setTickets] = useState(MOCK_TICKETS);
|
| 585 |
+
|
| 586 |
+
const pageConfig = {
|
| 587 |
+
dashboard: { title: "Dashboard", subtitle: "Welcome back, Dushyant" },
|
| 588 |
+
tickets: { title: "My Tickets", subtitle: `${tickets.filter(t => t.status === "OPEN" || t.status === "IN_PROGRESS").length} active · ${tickets.length} total` },
|
| 589 |
+
kb: { title: "Knowledge Base", subtitle: "Browse self-service articles and guides" },
|
| 590 |
+
analytics: { title: "My Analytics", subtitle: "Your support history and trends" },
|
| 591 |
+
thread: { title: "Ticket Thread", subtitle: selectedTicket?.id },
|
| 592 |
+
};
|
| 593 |
+
|
| 594 |
+
const currentPage = pageConfig[active] || pageConfig.dashboard;
|
| 595 |
+
|
| 596 |
+
return (
|
| 597 |
+
<div style={{ display: "flex", background: COLORS.gray50, minHeight: "100vh", fontFamily: "'Inter', -apple-system, BlinkMacSystemFont, sans-serif" }}>
|
| 598 |
+
<Sidebar active={active} setActive={(v) => { setActive(v); setSelectedTicket(null); }} onNewTicket={() => setShowNewTicket(true)} />
|
| 599 |
+
|
| 600 |
+
<div style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0, overflow: "hidden" }}>
|
| 601 |
+
{active !== "thread" && <TopBar title={currentPage.title} subtitle={currentPage.subtitle} />}
|
| 602 |
+
|
| 603 |
+
<main style={{ flex: 1, overflowY: "auto" }}>
|
| 604 |
+
{active === "dashboard" && <Dashboard setActive={setActive} setSelectedTicket={setSelectedTicket} />}
|
| 605 |
+
{active === "tickets" && <TicketList setActive={setActive} setSelectedTicket={setSelectedTicket} />}
|
| 606 |
+
{active === "thread" && selectedTicket && <ThreadView ticket={selectedTicket} onBack={() => setActive("tickets")} />}
|
| 607 |
+
{active === "kb" && <KnowledgeBase />}
|
| 608 |
+
{active === "analytics" && <Analytics />}
|
| 609 |
+
</main>
|
| 610 |
+
</div>
|
| 611 |
+
|
| 612 |
+
{showNewTicket && (
|
| 613 |
+
<NewTicketModal
|
| 614 |
+
onClose={() => setShowNewTicket(false)}
|
| 615 |
+
onCreate={(form) => {
|
| 616 |
+
const newT = { id: `TKT-${1043 + tickets.length - 4}`, ...form, status: "OPEN", created: new Date().toISOString().slice(0, 10), updated: "just now", messages: 0, sentiment: "Neutral" };
|
| 617 |
+
setTickets(t => [newT, ...t]);
|
| 618 |
+
}}
|
| 619 |
+
/>
|
| 620 |
+
)}
|
| 621 |
+
</div>
|
| 622 |
+
);
|
| 623 |
+
}
|
frontend/docs/nexus-internal-dashboard.jsx
ADDED
|
@@ -0,0 +1,758 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { useState, useRef, useEffect } from "react";
|
| 2 |
+
|
| 3 |
+
// ─── Design Tokens ────────────────────────────────────────────────────────────
|
| 4 |
+
const T = {
|
| 5 |
+
bg0: "#0D0F14", // deepest bg
|
| 6 |
+
bg1: "#13161D", // sidebar
|
| 7 |
+
bg2: "#181C25", // panels
|
| 8 |
+
bg3: "#1F2433", // cards
|
| 9 |
+
bg4: "#252A3A", // hover / elevated
|
| 10 |
+
border: "#2A3147",
|
| 11 |
+
borderHi: "#3A4460",
|
| 12 |
+
text1: "#E8ECF4",
|
| 13 |
+
text2: "#9AA3B8",
|
| 14 |
+
text3: "#5C6580",
|
| 15 |
+
accent: "#4F8EF7", // blue
|
| 16 |
+
accentDim: "#1E3A6E",
|
| 17 |
+
green: "#34D399",
|
| 18 |
+
greenDim:"#0D3D2A",
|
| 19 |
+
amber: "#FBBF24",
|
| 20 |
+
amberDim:"#3D2D0A",
|
| 21 |
+
red: "#F87171",
|
| 22 |
+
redDim: "#3D1515",
|
| 23 |
+
purple: "#A78BFA",
|
| 24 |
+
purpleDim:"#2D1F5E",
|
| 25 |
+
teal: "#2DD4BF",
|
| 26 |
+
tealDim:"#0D3333",
|
| 27 |
+
};
|
| 28 |
+
|
| 29 |
+
const font = "'DM Sans', 'Segoe UI', system-ui, sans-serif";
|
| 30 |
+
const mono = "'JetBrains Mono', 'Fira Code', 'Consolas', monospace";
|
| 31 |
+
|
| 32 |
+
// ─── Mock Data ────────────────────────────────────────────────────────────────
|
| 33 |
+
const QUEUE_TICKETS = [
|
| 34 |
+
{ id:"TKT-1048", title:"Production DB latency spike — 8x degradation", customer:"Arjun Mehta", priority:"URGENT", status:"OPEN", category:"Database", age:"4m", sla:"22m", sentiment:"Angry", assignee:null, aiScore:97 },
|
| 35 |
+
{ id:"TKT-1047", title:"SSO login loop after tenant migration", customer:"Lisa Park", priority:"HIGH", status:"OPEN", category:"Auth", age:"18m", sla:"1h2m",sentiment:"Frustrated", assignee:"Priya Sharma", aiScore:84 },
|
| 36 |
+
{ id:"TKT-1046", title:"Webhook delivery failing — 503 responses", customer:"Dev Team B", priority:"HIGH", status:"IN_PROGRESS", category:"API", age:"35m", sla:"1h27m",sentiment:"Neutral", assignee:"You", aiScore:91 },
|
| 37 |
+
{ id:"TKT-1045", title:"Cannot export reports as PDF on Safari", customer:"Meera Joshi", priority:"MEDIUM", status:"IN_PROGRESS", category:"UI", age:"2h", sla:"3h", sentiment:"Frustrated", assignee:"You", aiScore:72 },
|
| 38 |
+
{ id:"TKT-1044", title:"Mobile app crash on Android 14 devices", customer:"Ravi Teja", priority:"HIGH", status:"OPEN", category:"Mobile", age:"1h", sla:"1h", sentiment:"Frustrated", assignee:null, aiScore:88 },
|
| 39 |
+
{ id:"TKT-1043", title:"Billing cycle shows incorrect proration", customer:"Finance Ops", priority:"MEDIUM", status:"OPEN", category:"Billing", age:"3h", sla:"5h", sentiment:"Neutral", assignee:null, aiScore:65 },
|
| 40 |
+
{ id:"TKT-1042", title:"VPN access lost after password reset", customer:"Dushyant S.", priority:"HIGH", status:"IN_PROGRESS", category:"Network",age:"4h",sla:"6h",sentiment:"Frustrated",assignee:"Priya Sharma", aiScore:82 },
|
| 41 |
+
];
|
| 42 |
+
|
| 43 |
+
const AGENTS = [
|
| 44 |
+
{ name:"Priya Sharma", role:"SC_AGENT", avatar:"PS", active:3, color:"#A78BFA" },
|
| 45 |
+
{ name:"You", role:"SC_AGENT", avatar:"ME", active:2, color:"#4F8EF7" },
|
| 46 |
+
{ name:"Rohan Das", role:"SC_LEAD", avatar:"RD", active:1, color:"#34D399" },
|
| 47 |
+
{ name:"Ananya Reddy", role:"SC_AGENT", avatar:"AR", active:4, color:"#FBBF24" },
|
| 48 |
+
];
|
| 49 |
+
|
| 50 |
+
const NEXUS_THREAD = [
|
| 51 |
+
{ role:"user", content:"I'm looking at TKT-1047. What's the root cause of the SSO loop and what's our fastest fix?" },
|
| 52 |
+
{ role:"ai", content:"Analysing TKT-1047 — SSO Login Loop after tenant migration.\n\n**Root Cause (confidence 91%):** The tenant's OAuth `redirect_uri` in the database still points to the old subdomain (`old.acme.corp`) instead of the migrated one (`acme.nexus.io`). When the IdP redirects post-auth, the callback fails validation, resetting the flow.\n\n**Recommended fix:**\n```sql\nUPDATE tenants\nSET oauth_redirect_uri = 'https://acme.nexus.io/auth/callback'\nWHERE tenant_id = 'acme-corp-t84';\n```\n\n**Risk:** Low — tenant-scoped change, no other tenants affected.\n\nShould I prepare the remediation action for your approval?", tools:["SQL Metadata Engine","Nexus Knowledge Base"], time:"10:42:05" },
|
| 53 |
+
{ role:"user", content:"Yes, prepare the fix." },
|
| 54 |
+
{ role:"approval", action:"PATCH_TENANT_CONFIG", params:{ tenant_id:"acme-corp-t84", field:"oauth_redirect_uri", value:"https://acme.nexus.io/auth/callback" }, description:"Update OAuth redirect URI for tenant acme-corp-t84 to resolve SSO login loop.", risk:"Low" },
|
| 55 |
+
];
|
| 56 |
+
|
| 57 |
+
const FORENSIC_STEPS = [
|
| 58 |
+
{ time:"10:42:01", node:"vision", label:"Vision", detail:"No attachments found. Skipped visual scan.", status:"skip" },
|
| 59 |
+
{ time:"10:42:02", node:"input_guard", label:"Input Guard", detail:"No injection patterns detected. Cleared.", status:"ok" },
|
| 60 |
+
{ time:"10:42:02", node:"router", label:"Intent Router", detail:"Intent: DIAGNOSE_TICKET. Tools selected: SQL + KB.", status:"ok" },
|
| 61 |
+
{ time:"10:42:03", node:"executor", label:"Tool Executor", detail:"Parallel: SQL query (12ms) + KB vector search (31ms).", status:"ok" },
|
| 62 |
+
{ time:"10:42:04", node:"responder", label:"Responder", detail:"Generated structured diagnosis with code block.", status:"ok" },
|
| 63 |
+
{ time:"10:42:05", node:"approval", label:"HITL Approval", detail:"Write action detected. Paused for staff approval.", status:"wait" },
|
| 64 |
+
];
|
| 65 |
+
|
| 66 |
+
const MEMORY = `TKT-1047: SSO loop for tenant acme-corp-t84 post-migration. Root cause identified as stale OAuth redirect_uri in DB. Remediation SQL prepared and awaiting approval. Customer: Lisa Park. Priority: HIGH. Agent: Priya Sharma assigned.`;
|
| 67 |
+
|
| 68 |
+
const STATS = {
|
| 69 |
+
openToday: 12, resolvedToday: 8, breached: 1, avgFRT: "14m",
|
| 70 |
+
hourly: [3,5,8,11,9,14,12,10,7,6,9,13,11,8,6,4,7,9,11,8,6,5,3,2],
|
| 71 |
+
};
|
| 72 |
+
|
| 73 |
+
// ─── Sub-components ───────────────────────────────────────────────────────────
|
| 74 |
+
const priorityCfg = {
|
| 75 |
+
URGENT: { label:"Urgent", color:T.red, bg:T.redDim },
|
| 76 |
+
HIGH: { label:"High", color:"#FB923C", bg:"#3D1F0A" },
|
| 77 |
+
MEDIUM: { label:"Medium", color:T.amber, bg:T.amberDim },
|
| 78 |
+
LOW: { label:"Low", color:T.green, bg:T.greenDim },
|
| 79 |
+
};
|
| 80 |
+
const statusCfg = {
|
| 81 |
+
OPEN: { label:"Open", dot:T.accent },
|
| 82 |
+
IN_PROGRESS: { label:"In Progress", dot:T.amber },
|
| 83 |
+
RESOLVED: { label:"Resolved", dot:T.green },
|
| 84 |
+
CLOSED: { label:"Closed", dot:T.text3 },
|
| 85 |
+
};
|
| 86 |
+
|
| 87 |
+
function Pill({ color, bg, label, mono: isMono }) {
|
| 88 |
+
return <span style={{ fontSize:11, fontWeight:600, padding:"2px 8px", borderRadius:4, background:bg, color, fontFamily: isMono ? mono : font, letterSpacing:"0.03em" }}>{label}</span>;
|
| 89 |
+
}
|
| 90 |
+
function StatusDot({ status }) {
|
| 91 |
+
const c = statusCfg[status] || statusCfg.OPEN;
|
| 92 |
+
return (
|
| 93 |
+
<span style={{ display:"inline-flex", alignItems:"center", gap:5, fontSize:12, color:T.text2 }}>
|
| 94 |
+
<span style={{ width:6, height:6, borderRadius:"50%", background:c.dot, flexShrink:0, boxShadow:`0 0 5px ${c.dot}88` }} />
|
| 95 |
+
{c.label}
|
| 96 |
+
</span>
|
| 97 |
+
);
|
| 98 |
+
}
|
| 99 |
+
function Avatar({ initials, color, size=28 }) {
|
| 100 |
+
return (
|
| 101 |
+
<div style={{ width:size, height:size, borderRadius:"50%", background: color+"22", border:`1px solid ${color}44`, display:"flex", alignItems:"center", justifyContent:"center", fontSize: size*0.36, fontWeight:700, color, flexShrink:0, fontFamily:mono }}>
|
| 102 |
+
{initials}
|
| 103 |
+
</div>
|
| 104 |
+
);
|
| 105 |
+
}
|
| 106 |
+
function SentimentIcon({ s }) {
|
| 107 |
+
if (s === "Angry") return <span style={{ fontSize:12, title:s }}>🔴</span>;
|
| 108 |
+
if (s === "Frustrated") return <span style={{ fontSize:12 }}>🟠</span>;
|
| 109 |
+
if (s === "Happy") return <span style={{ fontSize:12 }}>🟢</span>;
|
| 110 |
+
return <span style={{ fontSize:12 }}>⚪</span>;
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
// ─── Sidebar ──────────────────────────────────────────────────────────────────
|
| 114 |
+
function Sidebar({ active, setActive }) {
|
| 115 |
+
const nav = [
|
| 116 |
+
{ id:"overview", icon:"▦", label:"Overview" },
|
| 117 |
+
{ id:"queue", icon:"◈", label:"Agent Queue", badge:7 },
|
| 118 |
+
{ id:"nexus", icon:"✦", label:"Nexus AI" },
|
| 119 |
+
{ id:"forensics", icon:"◉", label:"Forensics" },
|
| 120 |
+
{ id:"escalation",icon:"⚑", label:"Escalation", badge:1 },
|
| 121 |
+
{ id:"analytics", icon:"◫", label:"Analytics" },
|
| 122 |
+
];
|
| 123 |
+
return (
|
| 124 |
+
<aside style={{ width:216, background:T.bg1, borderRight:`1px solid ${T.border}`, display:"flex", flexDirection:"column", flexShrink:0, height:"100vh", position:"sticky", top:0 }}>
|
| 125 |
+
<div style={{ padding:"18px 18px 14px", borderBottom:`1px solid ${T.border}` }}>
|
| 126 |
+
<div style={{ display:"flex", alignItems:"center", gap:10 }}>
|
| 127 |
+
<div style={{ width:32, height:32, borderRadius:8, background:"linear-gradient(135deg, #4F8EF7, #A78BFA)", display:"flex", alignItems:"center", justifyContent:"center" }}>
|
| 128 |
+
<span style={{ color:"#fff", fontSize:13, fontWeight:800, fontFamily:mono }}>N</span>
|
| 129 |
+
</div>
|
| 130 |
+
<div>
|
| 131 |
+
<div style={{ fontSize:13, fontWeight:700, color:T.text1, letterSpacing:"-0.01em" }}>Nexus</div>
|
| 132 |
+
<div style={{ fontSize:10, color:T.text3, letterSpacing:"0.08em", textTransform:"uppercase" }}>Staff Console</div>
|
| 133 |
+
</div>
|
| 134 |
+
</div>
|
| 135 |
+
</div>
|
| 136 |
+
|
| 137 |
+
<nav style={{ flex:1, padding:"10px 10px" }}>
|
| 138 |
+
{nav.map(item => {
|
| 139 |
+
const isActive = active === item.id;
|
| 140 |
+
return (
|
| 141 |
+
<button key={item.id} onClick={() => setActive(item.id)} style={{ width:"100%", display:"flex", alignItems:"center", gap:10, padding:"9px 12px", borderRadius:7, border:"none", cursor:"pointer", background: isActive ? T.accentDim : "transparent", color: isActive ? T.accent : T.text2, fontSize:13, fontWeight: isActive ? 600 : 400, marginBottom:2, textAlign:"left", transition:"all 0.12s" }}>
|
| 142 |
+
<span style={{ fontSize:13, width:16, textAlign:"center", flexShrink:0 }}>{item.icon}</span>
|
| 143 |
+
<span style={{ flex:1 }}>{item.label}</span>
|
| 144 |
+
{item.badge && <span style={{ background: isActive ? T.accent+"33" : T.bg4, color: isActive ? T.accent : T.text3, fontSize:10, fontWeight:700, borderRadius:10, padding:"1px 6px", fontFamily:mono }}>{item.badge}</span>}
|
| 145 |
+
</button>
|
| 146 |
+
);
|
| 147 |
+
})}
|
| 148 |
+
</nav>
|
| 149 |
+
|
| 150 |
+
<div style={{ padding:"10px 14px", borderTop:`1px solid ${T.border}` }}>
|
| 151 |
+
<div style={{ display:"flex", alignItems:"center", gap:10 }}>
|
| 152 |
+
<Avatar initials="ME" color={T.accent} size={30} />
|
| 153 |
+
<div style={{ flex:1, minWidth:0 }}>
|
| 154 |
+
<div style={{ fontSize:12, fontWeight:600, color:T.text1 }}>Rohan Das</div>
|
| 155 |
+
<div style={{ fontSize:10, color:T.green, display:"flex", alignItems:"center", gap:4 }}>
|
| 156 |
+
<span style={{ width:5, height:5, borderRadius:"50%", background:T.green, flexShrink:0 }} />SC_LEAD
|
| 157 |
+
</div>
|
| 158 |
+
</div>
|
| 159 |
+
</div>
|
| 160 |
+
</div>
|
| 161 |
+
</aside>
|
| 162 |
+
);
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
// ─── Topbar ───────────────────────────────────────────────────────────────────
|
| 166 |
+
function TopBar({ title, subtitle }) {
|
| 167 |
+
const [time, setTime] = useState(new Date());
|
| 168 |
+
useEffect(() => { const t = setInterval(() => setTime(new Date()), 1000); return () => clearInterval(t); }, []);
|
| 169 |
+
return (
|
| 170 |
+
<div style={{ padding:"14px 28px", borderBottom:`1px solid ${T.border}`, background:T.bg1, display:"flex", alignItems:"center", justifyContent:"space-between" }}>
|
| 171 |
+
<div>
|
| 172 |
+
<div style={{ fontSize:16, fontWeight:700, color:T.text1, letterSpacing:"-0.01em" }}>{title}</div>
|
| 173 |
+
{subtitle && <div style={{ fontSize:11, color:T.text3, marginTop:1 }}>{subtitle}</div>}
|
| 174 |
+
</div>
|
| 175 |
+
<div style={{ display:"flex", alignItems:"center", gap:14 }}>
|
| 176 |
+
<div style={{ display:"flex", alignItems:"center", gap:6, padding:"5px 12px", background:T.bg3, borderRadius:7, border:`1px solid ${T.border}` }}>
|
| 177 |
+
<span style={{ width:7, height:7, borderRadius:"50%", background:T.green, boxShadow:`0 0 6px ${T.green}` }} />
|
| 178 |
+
<span style={{ fontSize:11, color:T.text2, fontFamily:mono }}>LIVE</span>
|
| 179 |
+
<span style={{ fontSize:11, color:T.text3, fontFamily:mono }}>{time.toLocaleTimeString("en-GB")}</span>
|
| 180 |
+
</div>
|
| 181 |
+
<div style={{ position:"relative" }}>
|
| 182 |
+
<button style={{ width:32, height:32, borderRadius:7, border:`1px solid ${T.border}`, background:T.bg3, cursor:"pointer", fontSize:14, display:"flex", alignItems:"center", justifyContent:"center", color:T.text2 }}>🔔</button>
|
| 183 |
+
<span style={{ position:"absolute", top:4, right:4, width:8, height:8, borderRadius:"50%", background:T.red, border:`2px solid ${T.bg1}` }} />
|
| 184 |
+
</div>
|
| 185 |
+
</div>
|
| 186 |
+
</div>
|
| 187 |
+
);
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
// ─── Overview ─────────────────────────────────────────────────────────────────
|
| 191 |
+
function Overview({ setActive }) {
|
| 192 |
+
const maxH = Math.max(...STATS.hourly);
|
| 193 |
+
return (
|
| 194 |
+
<div style={{ padding:"24px 28px" }}>
|
| 195 |
+
<div style={{ display:"grid", gridTemplateColumns:"repeat(4,1fr)", gap:12, marginBottom:20 }}>
|
| 196 |
+
{[
|
| 197 |
+
{ label:"Open today", value:STATS.openToday, color:T.accent, sub:"↑2 vs yesterday" },
|
| 198 |
+
{ label:"Resolved today", value:STATS.resolvedToday,color:T.green, sub:"66% resolution rate" },
|
| 199 |
+
{ label:"SLA breaches", value:STATS.breached, color:T.red, sub:"1 critical ticket" },
|
| 200 |
+
{ label:"Avg first reply", value:STATS.avgFRT, color:T.purple, sub:"Target: 15m" },
|
| 201 |
+
].map(s => (
|
| 202 |
+
<div key={s.label} style={{ background:T.bg2, border:`1px solid ${T.border}`, borderRadius:10, padding:"16px 18px" }}>
|
| 203 |
+
<div style={{ fontSize:11, color:T.text3, marginBottom:6, fontWeight:500, letterSpacing:"0.04em", textTransform:"uppercase" }}>{s.label}</div>
|
| 204 |
+
<div style={{ fontSize:26, fontWeight:800, color:s.color, marginBottom:2, fontFamily:mono, letterSpacing:"-0.02em" }}>{s.value}</div>
|
| 205 |
+
<div style={{ fontSize:11, color:T.text3 }}>{s.sub}</div>
|
| 206 |
+
</div>
|
| 207 |
+
))}
|
| 208 |
+
</div>
|
| 209 |
+
|
| 210 |
+
<div style={{ display:"grid", gridTemplateColumns:"2fr 1fr", gap:16, marginBottom:16 }}>
|
| 211 |
+
<div style={{ background:T.bg2, border:`1px solid ${T.border}`, borderRadius:10, padding:"18px 20px" }}>
|
| 212 |
+
<div style={{ fontSize:13, fontWeight:600, color:T.text1, marginBottom:4 }}>Ticket volume — today (hourly)</div>
|
| 213 |
+
<div style={{ fontSize:11, color:T.text3, marginBottom:16 }}>12:00 AM → now</div>
|
| 214 |
+
<div style={{ display:"flex", alignItems:"flex-end", gap:3, height:80 }}>
|
| 215 |
+
{STATS.hourly.map((v, i) => (
|
| 216 |
+
<div key={i} style={{ flex:1, background: i >= 18 ? T.accent : T.accentDim, borderRadius:"2px 2px 0 0", height:`${Math.round((v/maxH)*100)}%`, minHeight:2, transition:"height 0.3s", opacity: i >= 18 ? 1 : 0.7 }} />
|
| 217 |
+
))}
|
| 218 |
+
</div>
|
| 219 |
+
<div style={{ display:"flex", justifyContent:"space-between", marginTop:6 }}>
|
| 220 |
+
<span style={{ fontSize:10, color:T.text3, fontFamily:mono }}>12am</span>
|
| 221 |
+
<span style={{ fontSize:10, color:T.text3, fontFamily:mono }}>6am</span>
|
| 222 |
+
<span style={{ fontSize:10, color:T.text3, fontFamily:mono }}>12pm</span>
|
| 223 |
+
<span style={{ fontSize:10, color:T.text3, fontFamily:mono }}>6pm</span>
|
| 224 |
+
<span style={{ fontSize:10, color:T.text3, fontFamily:mono }}>now</span>
|
| 225 |
+
</div>
|
| 226 |
+
</div>
|
| 227 |
+
|
| 228 |
+
<div style={{ background:T.bg2, border:`1px solid ${T.border}`, borderRadius:10, padding:"18px 20px" }}>
|
| 229 |
+
<div style={{ fontSize:13, fontWeight:600, color:T.text1, marginBottom:14 }}>Agent workload</div>
|
| 230 |
+
{AGENTS.map(a => (
|
| 231 |
+
<div key={a.name} style={{ display:"flex", alignItems:"center", gap:10, marginBottom:12 }}>
|
| 232 |
+
<Avatar initials={a.avatar} color={a.color} size={26} />
|
| 233 |
+
<div style={{ flex:1, minWidth:0 }}>
|
| 234 |
+
<div style={{ display:"flex", justifyContent:"space-between", marginBottom:4 }}>
|
| 235 |
+
<span style={{ fontSize:12, color:T.text1, fontWeight:500 }}>{a.name}</span>
|
| 236 |
+
<span style={{ fontSize:11, color:T.text3, fontFamily:mono }}>{a.active}</span>
|
| 237 |
+
</div>
|
| 238 |
+
<div style={{ height:4, background:T.bg4, borderRadius:4, overflow:"hidden" }}>
|
| 239 |
+
<div style={{ width:`${Math.min((a.active/5)*100,100)}%`, height:"100%", background:a.active>=4?T.red:a.active>=3?T.amber:T.green, borderRadius:4 }} />
|
| 240 |
+
</div>
|
| 241 |
+
</div>
|
| 242 |
+
</div>
|
| 243 |
+
))}
|
| 244 |
+
</div>
|
| 245 |
+
</div>
|
| 246 |
+
|
| 247 |
+
<div style={{ background:T.bg2, border:`1px solid ${T.border}`, borderRadius:10, padding:"18px 20px" }}>
|
| 248 |
+
<div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:14 }}>
|
| 249 |
+
<div style={{ fontSize:13, fontWeight:600, color:T.text1 }}>Priority queue — top 4</div>
|
| 250 |
+
<button onClick={() => setActive("queue")} style={{ fontSize:12, color:T.accent, background:"none", border:"none", cursor:"pointer", fontWeight:500 }}>View all →</button>
|
| 251 |
+
</div>
|
| 252 |
+
{QUEUE_TICKETS.slice(0,4).map(t => (
|
| 253 |
+
<div key={t.id} style={{ display:"flex", alignItems:"center", gap:12, padding:"10px 0", borderTop:`1px solid ${T.border}` }}>
|
| 254 |
+
<Pill color={priorityCfg[t.priority].color} bg={priorityCfg[t.priority].bg} label={priorityCfg[t.priority].label} />
|
| 255 |
+
<div style={{ flex:1, minWidth:0 }}>
|
| 256 |
+
<div style={{ fontSize:12, fontWeight:500, color:T.text1, whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis" }}>{t.title}</div>
|
| 257 |
+
<div style={{ fontSize:11, color:T.text3, marginTop:2 }}>{t.customer} · {t.category}</div>
|
| 258 |
+
</div>
|
| 259 |
+
<div style={{ textAlign:"right", flexShrink:0 }}>
|
| 260 |
+
<StatusDot status={t.status} />
|
| 261 |
+
<div style={{ fontSize:10, color: t.sla.includes("m") && parseInt(t.sla)<30 ? T.red : T.text3, marginTop:3, fontFamily:mono }}>SLA {t.sla}</div>
|
| 262 |
+
</div>
|
| 263 |
+
</div>
|
| 264 |
+
))}
|
| 265 |
+
</div>
|
| 266 |
+
</div>
|
| 267 |
+
);
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
// ─── Agent Queue ──────────────────────────────────────────────────────────────
|
| 271 |
+
function AgentQueue({ setSelectedTicket, setActive }) {
|
| 272 |
+
const [sort, setSort] = useState("priority");
|
| 273 |
+
const [hov, setHov] = useState(null);
|
| 274 |
+
|
| 275 |
+
const pOrder = { URGENT:0, HIGH:1, MEDIUM:2, LOW:3 };
|
| 276 |
+
const sorted = [...QUEUE_TICKETS].sort((a,b) => pOrder[a.priority]-pOrder[b.priority]);
|
| 277 |
+
|
| 278 |
+
return (
|
| 279 |
+
<div style={{ padding:"24px 28px" }}>
|
| 280 |
+
<div style={{ display:"flex", gap:8, marginBottom:16, alignItems:"center" }}>
|
| 281 |
+
<span style={{ fontSize:12, color:T.text3, marginRight:4 }}>Sort by:</span>
|
| 282 |
+
{["priority","sla","ai score"].map(s => (
|
| 283 |
+
<button key={s} onClick={() => setSort(s)} style={{ padding:"5px 12px", borderRadius:16, border:`1px solid ${sort===s?T.accent:T.border}`, background: sort===s?T.accentDim:"transparent", color: sort===s?T.accent:T.text2, fontSize:11, cursor:"pointer", fontWeight:500 }}>{s}</button>
|
| 284 |
+
))}
|
| 285 |
+
<div style={{ marginLeft:"auto", fontSize:12, color:T.text3 }}>{QUEUE_TICKETS.length} tickets</div>
|
| 286 |
+
</div>
|
| 287 |
+
|
| 288 |
+
<div style={{ background:T.bg2, border:`1px solid ${T.border}`, borderRadius:10, overflow:"hidden" }}>
|
| 289 |
+
<div style={{ display:"grid", gridTemplateColumns:"1fr 2.5fr 1fr 1fr 1fr 1fr 1fr", gap:0, padding:"10px 16px", borderBottom:`1px solid ${T.border}`, background:T.bg3 }}>
|
| 290 |
+
{["Ticket","Subject","Customer","Priority","Status","SLA","Assigned"].map(h => (
|
| 291 |
+
<span key={h} style={{ fontSize:10, fontWeight:700, color:T.text3, letterSpacing:"0.07em", textTransform:"uppercase" }}>{h}</span>
|
| 292 |
+
))}
|
| 293 |
+
</div>
|
| 294 |
+
{sorted.map((t,i) => {
|
| 295 |
+
const isHov = hov===t.id;
|
| 296 |
+
const slaUrgent = t.sla.endsWith("m") && parseInt(t.sla) < 30;
|
| 297 |
+
return (
|
| 298 |
+
<div key={t.id}
|
| 299 |
+
onMouseEnter={() => setHov(t.id)} onMouseLeave={() => setHov(null)}
|
| 300 |
+
onClick={() => { setSelectedTicket(t); setActive("nexus"); }}
|
| 301 |
+
style={{ display:"grid", gridTemplateColumns:"1fr 2.5fr 1fr 1fr 1fr 1fr 1fr", gap:0, padding:"12px 16px", borderTop: i>0?`1px solid ${T.border}`:"none", cursor:"pointer", background: isHov?T.bg3:T.bg2, transition:"background 0.1s" }}>
|
| 302 |
+
<span style={{ fontSize:11, color:T.accent, fontFamily:mono, fontWeight:700 }}>{t.id}</span>
|
| 303 |
+
<div>
|
| 304 |
+
<div style={{ fontSize:12, fontWeight:500, color:T.text1, marginBottom:2, paddingRight:12, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{t.title}</div>
|
| 305 |
+
<div style={{ display:"flex", alignItems:"center", gap:6 }}>
|
| 306 |
+
<span style={{ fontSize:10, color:T.text3 }}>{t.category}</span>
|
| 307 |
+
<span style={{ fontSize:10, background:T.bg4, color:T.text3, padding:"1px 5px", borderRadius:3, fontFamily:mono }}>AI {t.aiScore}%</span>
|
| 308 |
+
</div>
|
| 309 |
+
</div>
|
| 310 |
+
<div style={{ display:"flex", alignItems:"center", gap:6 }}>
|
| 311 |
+
<SentimentIcon s={t.sentiment} />
|
| 312 |
+
<span style={{ fontSize:11, color:T.text2 }}>{t.customer}</span>
|
| 313 |
+
</div>
|
| 314 |
+
<div><Pill color={priorityCfg[t.priority].color} bg={priorityCfg[t.priority].bg} label={priorityCfg[t.priority].label} /></div>
|
| 315 |
+
<div style={{ display:"flex", alignItems:"center" }}><StatusDot status={t.status} /></div>
|
| 316 |
+
<div style={{ display:"flex", alignItems:"center" }}>
|
| 317 |
+
<span style={{ fontSize:12, fontFamily:mono, color: slaUrgent?T.red:T.text2, fontWeight: slaUrgent?700:400 }}>
|
| 318 |
+
{slaUrgent && "⚠ "}{t.sla}
|
| 319 |
+
</span>
|
| 320 |
+
</div>
|
| 321 |
+
<div style={{ display:"flex", alignItems:"center" }}>
|
| 322 |
+
{t.assignee
|
| 323 |
+
? <span style={{ fontSize:11, color: t.assignee==="You"?T.accent:T.text2 }}>{t.assignee}</span>
|
| 324 |
+
: <span style={{ fontSize:11, color:T.text3, fontStyle:"italic" }}>Unassigned</span>}
|
| 325 |
+
</div>
|
| 326 |
+
</div>
|
| 327 |
+
);
|
| 328 |
+
})}
|
| 329 |
+
</div>
|
| 330 |
+
</div>
|
| 331 |
+
);
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
// ─── Nexus AI Panel ───────────────────────────────────────────────────────────
|
| 335 |
+
function NexusAI({ selectedTicket }) {
|
| 336 |
+
const [messages, setMessages] = useState(NEXUS_THREAD);
|
| 337 |
+
const [input, setInput] = useState("");
|
| 338 |
+
const [approvalState, setApprovalState] = useState("pending"); // pending | approved | rejected
|
| 339 |
+
const [thinking, setThinking] = useState(false);
|
| 340 |
+
const [showMemory, setShowMemory] = useState(false);
|
| 341 |
+
const bottomRef = useRef(null);
|
| 342 |
+
|
| 343 |
+
useEffect(() => { bottomRef.current?.scrollIntoView({ behavior:"smooth" }); }, [messages, thinking]);
|
| 344 |
+
|
| 345 |
+
const sendMessage = () => {
|
| 346 |
+
if (!input.trim()) return;
|
| 347 |
+
const userMsg = { role:"user", content:input };
|
| 348 |
+
setMessages(m => [...m, userMsg]);
|
| 349 |
+
setInput("");
|
| 350 |
+
setThinking(true);
|
| 351 |
+
setTimeout(() => {
|
| 352 |
+
setThinking(false);
|
| 353 |
+
setMessages(m => [...m, { role:"ai", content:"I've queued the remediation action. Once approved, the tenant OAuth config will update within ~30 seconds and Lisa can retry login. I'll monitor the auth logs for 5 minutes post-execution to confirm.", tools:["Execution Engine"], time:"10:44:22" }]);
|
| 354 |
+
}, 1800);
|
| 355 |
+
};
|
| 356 |
+
|
| 357 |
+
return (
|
| 358 |
+
<div style={{ display:"flex", height:"calc(100vh - 60px)", gap:0 }}>
|
| 359 |
+
{/* Chat column */}
|
| 360 |
+
<div style={{ flex:1, display:"flex", flexDirection:"column", borderRight:`1px solid ${T.border}`, minWidth:0 }}>
|
| 361 |
+
{/* Ticket context bar */}
|
| 362 |
+
{selectedTicket && (
|
| 363 |
+
<div style={{ padding:"10px 20px", background:T.bg3, borderBottom:`1px solid ${T.border}`, display:"flex", alignItems:"center", gap:12 }}>
|
| 364 |
+
<span style={{ fontSize:11, color:T.accent, fontFamily:mono, fontWeight:700 }}>{selectedTicket.id}</span>
|
| 365 |
+
<span style={{ fontSize:12, color:T.text1, fontWeight:500, flex:1, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{selectedTicket.title}</span>
|
| 366 |
+
<StatusDot status={selectedTicket.status} />
|
| 367 |
+
<Pill color={priorityCfg[selectedTicket.priority].color} bg={priorityCfg[selectedTicket.priority].bg} label={priorityCfg[selectedTicket.priority].label} />
|
| 368 |
+
</div>
|
| 369 |
+
)}
|
| 370 |
+
|
| 371 |
+
{/* Messages */}
|
| 372 |
+
<div style={{ flex:1, overflowY:"auto", padding:"20px", display:"flex", flexDirection:"column", gap:16, background:T.bg0 }}>
|
| 373 |
+
{messages.map((msg, i) => {
|
| 374 |
+
if (msg.role === "approval") {
|
| 375 |
+
return (
|
| 376 |
+
<div key={i} style={{ background:T.amberDim, border:`1px solid ${T.amber}44`, borderRadius:10, padding:"16px 18px" }}>
|
| 377 |
+
<div style={{ display:"flex", alignItems:"center", gap:8, marginBottom:10 }}>
|
| 378 |
+
<span style={{ fontSize:13, fontWeight:700, color:T.amber }}>⚑ Action requires approval</span>
|
| 379 |
+
<span style={{ fontSize:10, fontFamily:mono, color:T.amber, background:T.amber+"22", padding:"2px 7px", borderRadius:4, fontWeight:700 }}>HITL PAUSE</span>
|
| 380 |
+
</div>
|
| 381 |
+
<div style={{ background:T.bg0, borderRadius:7, padding:"12px 14px", marginBottom:12, fontSize:12, fontFamily:mono, color:T.text2, lineHeight:1.7 }}>
|
| 382 |
+
<div style={{ color:T.text3, fontSize:10, marginBottom:6, letterSpacing:"0.06em", textTransform:"uppercase" }}>Proposed action</div>
|
| 383 |
+
<div><span style={{ color:T.amber }}>ACTION</span> {msg.action}</div>
|
| 384 |
+
<div><span style={{ color:T.amber }}>TENANT</span> {msg.params.tenant_id}</div>
|
| 385 |
+
<div><span style={{ color:T.amber }}>FIELD</span> {msg.params.field}</div>
|
| 386 |
+
<div><span style={{ color:T.amber }}>VALUE</span> <span style={{ color:T.green }}>{msg.params.value}</span></div>
|
| 387 |
+
<div><span style={{ color:T.amber }}>RISK</span> <span style={{ color:T.green }}>{msg.risk}</span></div>
|
| 388 |
+
</div>
|
| 389 |
+
<div style={{ fontSize:12, color:T.text2, marginBottom:12 }}>{msg.description}</div>
|
| 390 |
+
{approvalState === "pending" ? (
|
| 391 |
+
<div style={{ display:"flex", gap:8 }}>
|
| 392 |
+
<button onClick={() => setApprovalState("approved")} style={{ padding:"7px 16px", background:T.greenDim, border:`1px solid ${T.green}44`, borderRadius:7, color:T.green, fontSize:12, fontWeight:700, cursor:"pointer" }}>✓ Approve</button>
|
| 393 |
+
<button onClick={() => setApprovalState("rejected")} style={{ padding:"7px 16px", background:T.redDim, border:`1px solid ${T.red}44`, borderRadius:7, color:T.red, fontSize:12, fontWeight:700, cursor:"pointer" }}>✕ Reject</button>
|
| 394 |
+
<button style={{ padding:"7px 16px", background:T.bg3, border:`1px solid ${T.border}`, borderRadius:7, color:T.text2, fontSize:12, cursor:"pointer" }}>✎ Modify</button>
|
| 395 |
+
</div>
|
| 396 |
+
) : (
|
| 397 |
+
<div style={{ display:"flex", alignItems:"center", gap:8, fontSize:12, color: approvalState==="approved"?T.green:T.red, fontWeight:600 }}>
|
| 398 |
+
{approvalState==="approved" ? "✓ Approved — executing remediation..." : "✕ Rejected — action cancelled."}
|
| 399 |
+
</div>
|
| 400 |
+
)}
|
| 401 |
+
</div>
|
| 402 |
+
);
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
if (msg.role === "user") {
|
| 406 |
+
return (
|
| 407 |
+
<div key={i} style={{ display:"flex", justifyContent:"flex-end" }}>
|
| 408 |
+
<div style={{ maxWidth:"72%", background:T.accentDim, border:`1px solid ${T.accent}33`, borderRadius:"10px 3px 10px 10px", padding:"10px 14px", fontSize:13, color:T.text1, lineHeight:1.6 }}>{msg.content}</div>
|
| 409 |
+
</div>
|
| 410 |
+
);
|
| 411 |
+
}
|
| 412 |
+
|
| 413 |
+
// AI message
|
| 414 |
+
const parts = msg.content.split(/(```[\s\S]*?```|\*\*[^*]+\*\*)/g);
|
| 415 |
+
return (
|
| 416 |
+
<div key={i} style={{ display:"flex", gap:10 }}>
|
| 417 |
+
<div style={{ width:28, height:28, borderRadius:7, background:"linear-gradient(135deg,#4F8EF7,#A78BFA)", display:"flex", alignItems:"center", justifyContent:"center", fontSize:11, fontWeight:800, color:"#fff", flexShrink:0, fontFamily:mono }}>N</div>
|
| 418 |
+
<div style={{ flex:1 }}>
|
| 419 |
+
<div style={{ display:"flex", alignItems:"center", gap:8, marginBottom:6 }}>
|
| 420 |
+
<span style={{ fontSize:12, fontWeight:700, color:T.text1 }}>Nexus</span>
|
| 421 |
+
{msg.tools?.map(t => <span key={t} style={{ fontSize:10, padding:"1px 7px", background:T.purpleDim, color:T.purple, borderRadius:10, fontWeight:600 }}>{t}</span>)}
|
| 422 |
+
{msg.time && <span style={{ fontSize:10, color:T.text3, fontFamily:mono, marginLeft:"auto" }}>{msg.time}</span>}
|
| 423 |
+
</div>
|
| 424 |
+
<div style={{ background:T.bg2, border:`1px solid ${T.border}`, borderRadius:"3px 10px 10px 10px", padding:"12px 16px", fontSize:13, color:T.text2, lineHeight:1.7 }}>
|
| 425 |
+
{parts.map((p,j) => {
|
| 426 |
+
if (p.startsWith("```")) {
|
| 427 |
+
const code = p.replace(/```\w*\n?/,"").replace(/```$/,"");
|
| 428 |
+
return <pre key={j} style={{ margin:"8px 0", padding:"10px 12px", background:T.bg0, borderRadius:6, fontSize:11, fontFamily:mono, color:T.green, overflowX:"auto", lineHeight:1.6, border:`1px solid ${T.border}` }}>{code}</pre>;
|
| 429 |
+
}
|
| 430 |
+
if (p.startsWith("**")) return <strong key={j} style={{ color:T.text1, fontWeight:600 }}>{p.replace(/\*\*/g,"")}</strong>;
|
| 431 |
+
return <span key={j}>{p}</span>;
|
| 432 |
+
})}
|
| 433 |
+
</div>
|
| 434 |
+
</div>
|
| 435 |
+
</div>
|
| 436 |
+
);
|
| 437 |
+
})}
|
| 438 |
+
|
| 439 |
+
{thinking && (
|
| 440 |
+
<div style={{ display:"flex", gap:10 }}>
|
| 441 |
+
<div style={{ width:28, height:28, borderRadius:7, background:"linear-gradient(135deg,#4F8EF7,#A78BFA)", display:"flex", alignItems:"center", justifyContent:"center", fontSize:11, fontWeight:800, color:"#fff", flexShrink:0 }}>N</div>
|
| 442 |
+
<div style={{ display:"flex", alignItems:"center", gap:4, padding:"10px 14px", background:T.bg2, border:`1px solid ${T.border}`, borderRadius:"3px 10px 10px 10px" }}>
|
| 443 |
+
{[0,1,2].map(d => <span key={d} style={{ width:6, height:6, borderRadius:"50%", background:T.accent, opacity:0.5, animation:`pulse 1.2s ${d*0.3}s infinite` }} />)}
|
| 444 |
+
</div>
|
| 445 |
+
</div>
|
| 446 |
+
)}
|
| 447 |
+
<div ref={bottomRef} />
|
| 448 |
+
</div>
|
| 449 |
+
|
| 450 |
+
{/* Input bar */}
|
| 451 |
+
<div style={{ padding:"12px 16px", background:T.bg1, borderTop:`1px solid ${T.border}` }}>
|
| 452 |
+
<div style={{ display:"flex", gap:8, alignItems:"flex-end" }}>
|
| 453 |
+
<textarea value={input} onChange={e => setInput(e.target.value)}
|
| 454 |
+
onKeyDown={e => { if(e.key==="Enter" && !e.shiftKey) { e.preventDefault(); sendMessage(); }}}
|
| 455 |
+
placeholder="Ask Nexus about any ticket, request a diagnosis, or trigger a remediation…"
|
| 456 |
+
style={{ flex:1, padding:"10px 14px", background:T.bg3, border:`1px solid ${T.border}`, borderRadius:9, fontSize:13, color:T.text1, resize:"none", outline:"none", fontFamily:font, lineHeight:1.5, minHeight:42, maxHeight:120 }} />
|
| 457 |
+
<button onClick={sendMessage} disabled={!input.trim()} style={{ padding:"10px 16px", background: input.trim()?T.accent:T.bg4, color: input.trim()?"#fff":T.text3, border:"none", borderRadius:9, cursor: input.trim()?"pointer":"default", fontSize:13, fontWeight:700, height:42, flexShrink:0 }}>Send</button>
|
| 458 |
+
</div>
|
| 459 |
+
<div style={{ fontSize:10, color:T.text3, marginTop:6 }}>Enter to send · Shift+Enter for newline · All actions require approval</div>
|
| 460 |
+
</div>
|
| 461 |
+
</div>
|
| 462 |
+
|
| 463 |
+
{/* Right panel — memory + forensic mini */}
|
| 464 |
+
<div style={{ width:280, display:"flex", flexDirection:"column", background:T.bg1, flexShrink:0 }}>
|
| 465 |
+
<div style={{ padding:"14px 16px", borderBottom:`1px solid ${T.border}` }}>
|
| 466 |
+
<div style={{ fontSize:12, fontWeight:700, color:T.text1, marginBottom:2 }}>Case summary</div>
|
| 467 |
+
<div style={{ fontSize:10, color:T.text3 }}>Recursive memory · auto-updated</div>
|
| 468 |
+
</div>
|
| 469 |
+
<div style={{ padding:"14px 16px", borderBottom:`1px solid ${T.border}` }}>
|
| 470 |
+
<div style={{ fontSize:12, color:T.text2, lineHeight:1.7, background:T.bg3, borderRadius:7, padding:"10px 12px", border:`1px solid ${T.border}` }}>{MEMORY}</div>
|
| 471 |
+
</div>
|
| 472 |
+
|
| 473 |
+
<div style={{ padding:"14px 16px", borderBottom:`1px solid ${T.border}` }}>
|
| 474 |
+
<div style={{ fontSize:12, fontWeight:700, color:T.text1, marginBottom:12 }}>Graph trace</div>
|
| 475 |
+
{FORENSIC_STEPS.map((step,i) => (
|
| 476 |
+
<div key={i} style={{ display:"flex", gap:10, marginBottom: i<FORENSIC_STEPS.length-1?10:0, alignItems:"flex-start" }}>
|
| 477 |
+
<div style={{ display:"flex", flexDirection:"column", alignItems:"center", flexShrink:0 }}>
|
| 478 |
+
<div style={{ width:16, height:16, borderRadius:"50%", background: step.status==="ok"?T.greenDim:step.status==="wait"?T.amberDim:T.bg4, border:`1.5px solid ${step.status==="ok"?T.green:step.status==="wait"?T.amber:T.border}`, display:"flex", alignItems:"center", justifyContent:"center", fontSize:8, color: step.status==="ok"?T.green:step.status==="wait"?T.amber:T.text3 }}>
|
| 479 |
+
{step.status==="ok"?"✓":step.status==="wait"?"⏸":"–"}
|
| 480 |
+
</div>
|
| 481 |
+
{i < FORENSIC_STEPS.length-1 && <div style={{ width:1, height:16, background:T.border, margin:"2px 0" }} />}
|
| 482 |
+
</div>
|
| 483 |
+
<div style={{ flex:1 }}>
|
| 484 |
+
<div style={{ display:"flex", justifyContent:"space-between" }}>
|
| 485 |
+
<span style={{ fontSize:11, fontWeight:600, color: step.status==="wait"?T.amber:T.text1 }}>{step.label}</span>
|
| 486 |
+
<span style={{ fontSize:9, color:T.text3, fontFamily:mono }}>{step.time}</span>
|
| 487 |
+
</div>
|
| 488 |
+
<div style={{ fontSize:10, color:T.text3, lineHeight:1.5, marginTop:1 }}>{step.detail}</div>
|
| 489 |
+
</div>
|
| 490 |
+
</div>
|
| 491 |
+
))}
|
| 492 |
+
</div>
|
| 493 |
+
|
| 494 |
+
<div style={{ padding:"14px 16px", flex:1 }}>
|
| 495 |
+
<div style={{ fontSize:12, fontWeight:700, color:T.text1, marginBottom:10 }}>Tools used</div>
|
| 496 |
+
{["SQL Metadata Engine","Nexus Knowledge Base","Execution Engine"].map(tool => (
|
| 497 |
+
<div key={tool} style={{ display:"flex", alignItems:"center", gap:8, marginBottom:7 }}>
|
| 498 |
+
<span style={{ width:6, height:6, borderRadius:"50%", background:T.purple, flexShrink:0 }} />
|
| 499 |
+
<span style={{ fontSize:11, color:T.text2 }}>{tool}</span>
|
| 500 |
+
</div>
|
| 501 |
+
))}
|
| 502 |
+
</div>
|
| 503 |
+
</div>
|
| 504 |
+
|
| 505 |
+
<style>{`@keyframes pulse{0%,100%{opacity:0.3}50%{opacity:1}}`}</style>
|
| 506 |
+
</div>
|
| 507 |
+
);
|
| 508 |
+
}
|
| 509 |
+
|
| 510 |
+
// ─── Forensics ────────────────────────────────────────────────────────────────
|
| 511 |
+
function Forensics() {
|
| 512 |
+
const [selected, setSelected] = useState(QUEUE_TICKETS[1]);
|
| 513 |
+
return (
|
| 514 |
+
<div style={{ padding:"24px 28px", display:"grid", gridTemplateColumns:"1fr 1.4fr", gap:20, height:"calc(100vh-60px)" }}>
|
| 515 |
+
<div>
|
| 516 |
+
<div style={{ fontSize:13, fontWeight:600, color:T.text1, marginBottom:12 }}>Select ticket to inspect</div>
|
| 517 |
+
{QUEUE_TICKETS.map(t => (
|
| 518 |
+
<div key={t.id} onClick={() => setSelected(t)} style={{ padding:"12px 14px", background: selected?.id===t.id?T.bg3:T.bg2, border:`1px solid ${selected?.id===t.id?T.accent+"55":T.border}`, borderRadius:8, cursor:"pointer", marginBottom:8, transition:"all 0.1s" }}>
|
| 519 |
+
<div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:4 }}>
|
| 520 |
+
<span style={{ fontSize:11, color:T.accent, fontFamily:mono, fontWeight:700 }}>{t.id}</span>
|
| 521 |
+
<Pill color={priorityCfg[t.priority].color} bg={priorityCfg[t.priority].bg} label={priorityCfg[t.priority].label} />
|
| 522 |
+
</div>
|
| 523 |
+
<div style={{ fontSize:12, color:T.text1, fontWeight:500, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{t.title}</div>
|
| 524 |
+
<div style={{ fontSize:11, color:T.text3, marginTop:3 }}>{t.customer}</div>
|
| 525 |
+
</div>
|
| 526 |
+
))}
|
| 527 |
+
</div>
|
| 528 |
+
|
| 529 |
+
<div>
|
| 530 |
+
<div style={{ fontSize:13, fontWeight:600, color:T.text1, marginBottom:12 }}>Forensic timeline — {selected?.id}</div>
|
| 531 |
+
<div style={{ background:T.bg2, border:`1px solid ${T.border}`, borderRadius:10, padding:"16px 18px" }}>
|
| 532 |
+
{FORENSIC_STEPS.map((step, i) => (
|
| 533 |
+
<div key={i} style={{ display:"flex", gap:14, paddingBottom: i<FORENSIC_STEPS.length-1?16:0, position:"relative" }}>
|
| 534 |
+
{i < FORENSIC_STEPS.length-1 && <div style={{ position:"absolute", left:12, top:20, bottom:0, width:1, background:T.border }} />}
|
| 535 |
+
<div style={{ width:24, height:24, borderRadius:"50%", flexShrink:0, background: step.status==="ok"?T.greenDim:step.status==="wait"?T.amberDim:T.bg4, border:`2px solid ${step.status==="ok"?T.green:step.status==="wait"?T.amber:T.border}`, display:"flex", alignItems:"center", justifyContent:"center", fontSize:10, color: step.status==="ok"?T.green:step.status==="wait"?T.amber:T.text3, zIndex:1 }}>
|
| 536 |
+
{step.status==="ok"?"✓":step.status==="wait"?"⏸":"–"}
|
| 537 |
+
</div>
|
| 538 |
+
<div style={{ flex:1, paddingTop:2 }}>
|
| 539 |
+
<div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:4 }}>
|
| 540 |
+
<span style={{ fontSize:13, fontWeight:600, color: step.status==="wait"?T.amber:T.text1 }}>{step.label}</span>
|
| 541 |
+
<span style={{ fontSize:10, color:T.text3, fontFamily:mono }}>{step.time}</span>
|
| 542 |
+
</div>
|
| 543 |
+
<div style={{ fontSize:12, color:T.text2, background:T.bg3, borderRadius:6, padding:"8px 10px", border:`1px solid ${T.border}` }}>{step.detail}</div>
|
| 544 |
+
</div>
|
| 545 |
+
</div>
|
| 546 |
+
))}
|
| 547 |
+
</div>
|
| 548 |
+
|
| 549 |
+
<div style={{ background:T.bg2, border:`1px solid ${T.border}`, borderRadius:10, padding:"16px 18px", marginTop:14 }}>
|
| 550 |
+
<div style={{ fontSize:12, fontWeight:600, color:T.text1, marginBottom:10 }}>AI interaction record</div>
|
| 551 |
+
{[
|
| 552 |
+
{ label:"Confidence", value:"91%", color:T.green },
|
| 553 |
+
{ label:"Model", value:"kimi-k2.5:cloud", color:T.purple },
|
| 554 |
+
{ label:"Latency", value:"847ms", color:T.amber },
|
| 555 |
+
{ label:"Tools called", value:"2", color:T.accent },
|
| 556 |
+
{ label:"Tokens used", value:"1,204", color:T.text2 },
|
| 557 |
+
{ label:"Workspace", value:"acme-corp", color:T.text2 },
|
| 558 |
+
].map(r => (
|
| 559 |
+
<div key={r.label} style={{ display:"flex", justifyContent:"space-between", padding:"5px 0", borderBottom:`1px solid ${T.border}` }}>
|
| 560 |
+
<span style={{ fontSize:12, color:T.text3 }}>{r.label}</span>
|
| 561 |
+
<span style={{ fontSize:12, color:r.color, fontFamily:mono, fontWeight:600 }}>{r.value}</span>
|
| 562 |
+
</div>
|
| 563 |
+
))}
|
| 564 |
+
</div>
|
| 565 |
+
</div>
|
| 566 |
+
</div>
|
| 567 |
+
);
|
| 568 |
+
}
|
| 569 |
+
|
| 570 |
+
// ─── Escalation ───────────────────────────────────────────────────────────────
|
| 571 |
+
function Escalation() {
|
| 572 |
+
const [rules, setRules] = useState([
|
| 573 |
+
{ id:1, priority:"URGENT", threshold:"30m", action:"NOTIFY_LEAD", active:true },
|
| 574 |
+
{ id:2, priority:"HIGH", threshold:"2h", action:"REASSIGN", active:true },
|
| 575 |
+
{ id:3, priority:"MEDIUM", threshold:"8h", action:"NOTIFY_LEAD", active:false },
|
| 576 |
+
{ id:4, priority:"LOW", threshold:"24h", action:"MARK_ESCALATED",active:true },
|
| 577 |
+
]);
|
| 578 |
+
const breached = QUEUE_TICKETS.filter(t => t.priority==="URGENT" || (t.priority==="HIGH" && t.sla.endsWith("m")));
|
| 579 |
+
|
| 580 |
+
return (
|
| 581 |
+
<div style={{ padding:"24px 28px" }}>
|
| 582 |
+
<div style={{ background:T.redDim, border:`1px solid ${T.red}44`, borderRadius:10, padding:"16px 20px", marginBottom:20, display:"flex", alignItems:"center", gap:14 }}>
|
| 583 |
+
<span style={{ fontSize:20 }}>⚑</span>
|
| 584 |
+
<div>
|
| 585 |
+
<div style={{ fontSize:13, fontWeight:700, color:T.red, marginBottom:2 }}>{breached.length} SLA breach{breached.length!==1?"es":""} active</div>
|
| 586 |
+
<div style={{ fontSize:12, color:T.text2 }}>Immediate attention required on the following tickets.</div>
|
| 587 |
+
</div>
|
| 588 |
+
</div>
|
| 589 |
+
|
| 590 |
+
<div style={{ background:T.bg2, border:`1px solid ${T.border}`, borderRadius:10, overflow:"hidden", marginBottom:20 }}>
|
| 591 |
+
<div style={{ padding:"12px 18px", background:T.bg3, borderBottom:`1px solid ${T.border}`, fontSize:12, fontWeight:700, color:T.text1 }}>Breached tickets</div>
|
| 592 |
+
{breached.map((t,i) => (
|
| 593 |
+
<div key={t.id} style={{ display:"flex", alignItems:"center", gap:14, padding:"12px 18px", borderTop: i>0?`1px solid ${T.border}`:"none" }}>
|
| 594 |
+
<Pill color={priorityCfg[t.priority].color} bg={priorityCfg[t.priority].bg} label={priorityCfg[t.priority].label} />
|
| 595 |
+
<div style={{ flex:1 }}>
|
| 596 |
+
<div style={{ fontSize:13, fontWeight:500, color:T.text1 }}>{t.title}</div>
|
| 597 |
+
<div style={{ fontSize:11, color:T.text3, marginTop:2 }}>{t.customer} · {t.id}</div>
|
| 598 |
+
</div>
|
| 599 |
+
<div style={{ textAlign:"right" }}>
|
| 600 |
+
<div style={{ fontSize:12, color:T.red, fontWeight:700, fontFamily:mono }}>SLA: {t.sla}</div>
|
| 601 |
+
<div style={{ fontSize:11, color:T.text3, marginTop:2 }}>Age: {t.age}</div>
|
| 602 |
+
</div>
|
| 603 |
+
<button style={{ padding:"6px 12px", background:T.accentDim, border:`1px solid ${T.accent}44`, borderRadius:6, color:T.accent, fontSize:11, cursor:"pointer", fontWeight:600 }}>Assign →</button>
|
| 604 |
+
</div>
|
| 605 |
+
))}
|
| 606 |
+
</div>
|
| 607 |
+
|
| 608 |
+
<div style={{ background:T.bg2, border:`1px solid ${T.border}`, borderRadius:10, overflow:"hidden" }}>
|
| 609 |
+
<div style={{ padding:"12px 18px", background:T.bg3, borderBottom:`1px solid ${T.border}`, display:"flex", justifyContent:"space-between", alignItems:"center" }}>
|
| 610 |
+
<span style={{ fontSize:12, fontWeight:700, color:T.text1 }}>Escalation rules</span>
|
| 611 |
+
<button style={{ fontSize:11, color:T.accent, background:"none", border:`1px solid ${T.accent}44`, borderRadius:5, padding:"4px 10px", cursor:"pointer" }}>+ Add rule</button>
|
| 612 |
+
</div>
|
| 613 |
+
{rules.map((rule,i) => (
|
| 614 |
+
<div key={rule.id} style={{ display:"flex", alignItems:"center", gap:14, padding:"14px 18px", borderTop: i>0?`1px solid ${T.border}`:"none" }}>
|
| 615 |
+
<div style={{ width:36, height:20, borderRadius:10, background: rule.active?T.greenDim:T.bg4, border:`1px solid ${rule.active?T.green:T.border}`, cursor:"pointer", display:"flex", alignItems:"center", padding:"0 3px", transition:"all 0.2s" }} onClick={() => setRules(r => r.map(x => x.id===rule.id?{...x,active:!x.active}:x))}>
|
| 616 |
+
<div style={{ width:14, height:14, borderRadius:"50%", background: rule.active?T.green:T.text3, transition:"all 0.2s", marginLeft: rule.active?16:0 }} />
|
| 617 |
+
</div>
|
| 618 |
+
<Pill color={priorityCfg[rule.priority].color} bg={priorityCfg[rule.priority].bg} label={rule.priority} />
|
| 619 |
+
<div style={{ flex:1, fontSize:12, color:T.text2 }}>
|
| 620 |
+
If unresolved after <span style={{ color:T.amber, fontFamily:mono, fontWeight:700 }}>{rule.threshold}</span> → <span style={{ color:T.accent }}>{rule.action.replace(/_/g," ").toLowerCase()}</span>
|
| 621 |
+
</div>
|
| 622 |
+
<button style={{ fontSize:11, color:T.text3, background:"none", border:`1px solid ${T.border}`, borderRadius:5, padding:"4px 8px", cursor:"pointer" }}>Edit</button>
|
| 623 |
+
</div>
|
| 624 |
+
))}
|
| 625 |
+
</div>
|
| 626 |
+
</div>
|
| 627 |
+
);
|
| 628 |
+
}
|
| 629 |
+
|
| 630 |
+
// ─── Analytics ────────────────────────────────────────────────────────────────
|
| 631 |
+
function Analytics() {
|
| 632 |
+
const resData = [65,72,58,80,75,69,84,79,91,77,83,88];
|
| 633 |
+
const months = ["Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar"];
|
| 634 |
+
const maxR = Math.max(...resData);
|
| 635 |
+
|
| 636 |
+
return (
|
| 637 |
+
<div style={{ padding:"24px 28px" }}>
|
| 638 |
+
<div style={{ display:"grid", gridTemplateColumns:"repeat(4,1fr)", gap:12, marginBottom:20 }}>
|
| 639 |
+
{[
|
| 640 |
+
{ label:"Total tickets (30d)", value:"142", sub:"↑18% vs prev month", color:T.accent },
|
| 641 |
+
{ label:"Resolution rate", value:"84%", sub:"Target: 80%", color:T.green },
|
| 642 |
+
{ label:"Avg resolution", value:"3.4h", sub:"↓0.6h improvement", color:T.purple },
|
| 643 |
+
{ label:"Team CSAT", value:"4.7", sub:"Based on 98 ratings", color:T.amber },
|
| 644 |
+
].map(s => (
|
| 645 |
+
<div key={s.label} style={{ background:T.bg2, border:`1px solid ${T.border}`, borderRadius:10, padding:"16px 18px" }}>
|
| 646 |
+
<div style={{ fontSize:10, color:T.text3, marginBottom:6, fontWeight:600, letterSpacing:"0.05em", textTransform:"uppercase" }}>{s.label}</div>
|
| 647 |
+
<div style={{ fontSize:26, fontWeight:800, color:s.color, marginBottom:3, fontFamily:mono, letterSpacing:"-0.02em" }}>{s.value}</div>
|
| 648 |
+
<div style={{ fontSize:11, color:T.text3 }}>{s.sub}</div>
|
| 649 |
+
</div>
|
| 650 |
+
))}
|
| 651 |
+
</div>
|
| 652 |
+
|
| 653 |
+
<div style={{ display:"grid", gridTemplateColumns:"2fr 1fr", gap:16, marginBottom:16 }}>
|
| 654 |
+
<div style={{ background:T.bg2, border:`1px solid ${T.border}`, borderRadius:10, padding:"18px 22px" }}>
|
| 655 |
+
<div style={{ fontSize:13, fontWeight:600, color:T.text1, marginBottom:4 }}>Resolution rate trend — 12 months</div>
|
| 656 |
+
<div style={{ fontSize:11, color:T.text3, marginBottom:16 }}>Monthly % of tickets resolved within SLA</div>
|
| 657 |
+
<div style={{ display:"flex", alignItems:"flex-end", gap:6, height:100 }}>
|
| 658 |
+
{resData.map((v,i) => (
|
| 659 |
+
<div key={i} style={{ flex:1, display:"flex", flexDirection:"column", alignItems:"center", gap:4 }}>
|
| 660 |
+
<div style={{ width:"100%", background: v>=80?T.green:v>=65?T.amber:T.red, borderRadius:"3px 3px 0 0", height:`${Math.round((v/maxR)*100)}%`, minHeight:4, opacity: i===resData.length-1?1:0.65 }} />
|
| 661 |
+
<span style={{ fontSize:9, color:T.text3, fontFamily:mono }}>{months[i]}</span>
|
| 662 |
+
</div>
|
| 663 |
+
))}
|
| 664 |
+
</div>
|
| 665 |
+
</div>
|
| 666 |
+
|
| 667 |
+
<div style={{ background:T.bg2, border:`1px solid ${T.border}`, borderRadius:10, padding:"18px 22px" }}>
|
| 668 |
+
<div style={{ fontSize:13, fontWeight:600, color:T.text1, marginBottom:14 }}>By category (30d)</div>
|
| 669 |
+
{[
|
| 670 |
+
{ name:"Database", count:28, color:T.red },
|
| 671 |
+
{ name:"Auth/SSO", count:22, color:T.purple },
|
| 672 |
+
{ name:"API", count:19, color:T.accent },
|
| 673 |
+
{ name:"UI/Web", count:14, color:T.teal },
|
| 674 |
+
{ name:"Billing", count:11, color:T.amber },
|
| 675 |
+
{ name:"Other", count:8, color:T.text3 },
|
| 676 |
+
].map(c => (
|
| 677 |
+
<div key={c.name} style={{ display:"flex", alignItems:"center", gap:10, marginBottom:8 }}>
|
| 678 |
+
<span style={{ fontSize:11, color:T.text2, width:60, flexShrink:0 }}>{c.name}</span>
|
| 679 |
+
<div style={{ flex:1, height:6, background:T.bg4, borderRadius:3, overflow:"hidden" }}>
|
| 680 |
+
<div style={{ width:`${Math.round((c.count/28)*100)}%`, height:"100%", background:c.color, borderRadius:3 }} />
|
| 681 |
+
</div>
|
| 682 |
+
<span style={{ fontSize:11, fontFamily:mono, color:T.text3, width:24, textAlign:"right" }}>{c.count}</span>
|
| 683 |
+
</div>
|
| 684 |
+
))}
|
| 685 |
+
</div>
|
| 686 |
+
</div>
|
| 687 |
+
|
| 688 |
+
<div style={{ background:T.bg2, border:`1px solid ${T.border}`, borderRadius:10, padding:"18px 22px" }}>
|
| 689 |
+
<div style={{ fontSize:13, fontWeight:600, color:T.text1, marginBottom:14 }}>Agent performance (30d)</div>
|
| 690 |
+
<table style={{ width:"100%", borderCollapse:"collapse", fontSize:12 }}>
|
| 691 |
+
<thead>
|
| 692 |
+
<tr style={{ borderBottom:`1px solid ${T.border}` }}>
|
| 693 |
+
{["Agent","Role","Resolved","Avg time","CSAT","Breaches"].map(h => (
|
| 694 |
+
<th key={h} style={{ padding:"6px 12px 10px", textAlign:"left", fontSize:10, color:T.text3, fontWeight:700, letterSpacing:"0.06em", textTransform:"uppercase" }}>{h}</th>
|
| 695 |
+
))}
|
| 696 |
+
</tr>
|
| 697 |
+
</thead>
|
| 698 |
+
<tbody>
|
| 699 |
+
{[
|
| 700 |
+
{ name:"Priya Sharma", role:"SC_AGENT", resolved:38, avgTime:"2.9h", csat:"4.8", breaches:0 },
|
| 701 |
+
{ name:"You", role:"SC_AGENT", resolved:29, avgTime:"3.6h", csat:"4.5", breaches:1 },
|
| 702 |
+
{ name:"Rohan Das", role:"SC_LEAD", resolved:22, avgTime:"4.1h", csat:"4.9", breaches:0 },
|
| 703 |
+
{ name:"Ananya Reddy", role:"SC_AGENT", resolved:41, avgTime:"2.7h", csat:"4.7", breaches:2 },
|
| 704 |
+
].map((a,i) => (
|
| 705 |
+
<tr key={a.name} style={{ borderTop:`1px solid ${T.border}` }}>
|
| 706 |
+
<td style={{ padding:"10px 12px" }}>
|
| 707 |
+
<div style={{ display:"flex", alignItems:"center", gap:8 }}>
|
| 708 |
+
<Avatar initials={a.name.split(" ").map(w=>w[0]).join("")} color={AGENTS.find(ag=>ag.name===a.name)?.color||T.accent} size={24} />
|
| 709 |
+
<span style={{ fontSize:12, color:T.text1, fontWeight:500 }}>{a.name}</span>
|
| 710 |
+
</div>
|
| 711 |
+
</td>
|
| 712 |
+
<td style={{ padding:"10px 12px" }}><span style={{ fontSize:10, color:T.purple, background:T.purpleDim, padding:"2px 7px", borderRadius:4, fontWeight:600 }}>{a.role}</span></td>
|
| 713 |
+
<td style={{ padding:"10px 12px", fontSize:12, color:T.green, fontFamily:mono, fontWeight:700 }}>{a.resolved}</td>
|
| 714 |
+
<td style={{ padding:"10px 12px", fontSize:12, color:T.text2, fontFamily:mono }}>{a.avgTime}</td>
|
| 715 |
+
<td style={{ padding:"10px 12px", fontSize:12, color:T.amber, fontFamily:mono, fontWeight:700 }}>{a.csat}</td>
|
| 716 |
+
<td style={{ padding:"10px 12px", fontSize:12, fontFamily:mono, color: a.breaches>0?T.red:T.green, fontWeight:700 }}>{a.breaches}</td>
|
| 717 |
+
</tr>
|
| 718 |
+
))}
|
| 719 |
+
</tbody>
|
| 720 |
+
</table>
|
| 721 |
+
</div>
|
| 722 |
+
</div>
|
| 723 |
+
);
|
| 724 |
+
}
|
| 725 |
+
|
| 726 |
+
// ─── Root ─────────────────────────────────────────────────────────────────────
|
| 727 |
+
export default function InternalDashboard() {
|
| 728 |
+
const [active, setActive] = useState("overview");
|
| 729 |
+
const [selectedTicket, setSelectedTicket] = useState(null);
|
| 730 |
+
|
| 731 |
+
const pages = {
|
| 732 |
+
overview: { title:"Operations Overview", subtitle:"Workspace: Snowball · 12 open · 1 SLA breach" },
|
| 733 |
+
queue: { title:"Agent Queue", subtitle:"All active tickets · sorted by priority" },
|
| 734 |
+
nexus: { title:"Nexus AI", subtitle: selectedTicket ? `${selectedTicket.id} — ${selectedTicket.title}` : "Agentic support assistant" },
|
| 735 |
+
forensics: { title:"Forensic Inspector", subtitle:"AI interaction traces & graph logs" },
|
| 736 |
+
escalation: { title:"Escalation Centre", subtitle:"SLA monitoring & escalation rules" },
|
| 737 |
+
analytics: { title:"Team Analytics", subtitle:"Performance metrics — last 30 days" },
|
| 738 |
+
};
|
| 739 |
+
|
| 740 |
+
const pg = pages[active] || pages.overview;
|
| 741 |
+
|
| 742 |
+
return (
|
| 743 |
+
<div style={{ display:"flex", background:T.bg0, minHeight:"100vh", fontFamily:font, color:T.text1 }}>
|
| 744 |
+
<Sidebar active={active} setActive={v => { setActive(v); }} />
|
| 745 |
+
<div style={{ flex:1, display:"flex", flexDirection:"column", minWidth:0, overflow:"hidden" }}>
|
| 746 |
+
<TopBar title={pg.title} subtitle={pg.subtitle} />
|
| 747 |
+
<main style={{ flex:1, overflowY: active==="nexus"?"hidden":"auto" }}>
|
| 748 |
+
{active==="overview" && <Overview setActive={setActive} />}
|
| 749 |
+
{active==="queue" && <AgentQueue setSelectedTicket={setSelectedTicket} setActive={setActive} />}
|
| 750 |
+
{active==="nexus" && <NexusAI selectedTicket={selectedTicket} />}
|
| 751 |
+
{active==="forensics" && <Forensics />}
|
| 752 |
+
{active==="escalation" && <Escalation />}
|
| 753 |
+
{active==="analytics" && <Analytics />}
|
| 754 |
+
</main>
|
| 755 |
+
</div>
|
| 756 |
+
</div>
|
| 757 |
+
);
|
| 758 |
+
}
|
main.py
CHANGED
|
@@ -21,6 +21,9 @@ from core.observability import setup_telemetry
|
|
| 21 |
# Initialize global logging
|
| 22 |
setup_logging()
|
| 23 |
from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
|
|
|
|
|
|
|
|
|
|
| 24 |
logger = get_logger(__name__)
|
| 25 |
|
| 26 |
settings = get_settings()
|
|
@@ -80,8 +83,9 @@ app = FastAPI(
|
|
| 80 |
title=settings.APP_NAME,
|
| 81 |
version=settings.APP_VERSION,
|
| 82 |
lifespan=lifespan,
|
| 83 |
-
docs_url="/docs",
|
| 84 |
-
redoc_url="/redoc",
|
|
|
|
| 85 |
strict_slashes=False,
|
| 86 |
)
|
| 87 |
|
|
@@ -265,3 +269,65 @@ app.mount("/customer", StaticFiles(directory=FRONTEND_CUSTOMER_PATH, html=True),
|
|
| 265 |
async def root_landing(request: Request):
|
| 266 |
return templates.TemplateResponse("landing.html", {"request": request})
|
| 267 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
# Initialize global logging
|
| 22 |
setup_logging()
|
| 23 |
from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
|
| 24 |
+
import markdown
|
| 25 |
+
from markdown.extensions.codehilite import CodeHiliteExtension
|
| 26 |
+
from markdown.extensions.fenced_code import FencedCodeExtension
|
| 27 |
logger = get_logger(__name__)
|
| 28 |
|
| 29 |
settings = get_settings()
|
|
|
|
| 83 |
title=settings.APP_NAME,
|
| 84 |
version=settings.APP_VERSION,
|
| 85 |
lifespan=lifespan,
|
| 86 |
+
docs_url="/api/docs",
|
| 87 |
+
redoc_url="/api/redoc",
|
| 88 |
+
openapi_url="/api/openapi.json",
|
| 89 |
strict_slashes=False,
|
| 90 |
)
|
| 91 |
|
|
|
|
| 269 |
async def root_landing(request: Request):
|
| 270 |
return templates.TemplateResponse("landing.html", {"request": request})
|
| 271 |
|
| 272 |
+
# --- DOCUMENTATION HOSTING ---
|
| 273 |
+
DOCS_DIR = os.path.join(BASE_DIR, "docs")
|
| 274 |
+
|
| 275 |
+
def get_docs_list():
|
| 276 |
+
docs = []
|
| 277 |
+
if not os.path.exists(DOCS_DIR):
|
| 278 |
+
return docs
|
| 279 |
+
for f in os.listdir(DOCS_DIR):
|
| 280 |
+
if f.endswith(".md") and f.lower() != "readme.md":
|
| 281 |
+
doc_id = f[:-3]
|
| 282 |
+
title = doc_id.replace("_", " ").title()
|
| 283 |
+
docs.append({"id": doc_id, "title": title})
|
| 284 |
+
return sorted(docs, key=lambda x: x["title"])
|
| 285 |
+
|
| 286 |
+
@app.get("/docs")
|
| 287 |
+
@app.get("/docs/")
|
| 288 |
+
async def list_docs(request: Request):
|
| 289 |
+
docs = get_docs_list()
|
| 290 |
+
if not docs:
|
| 291 |
+
return templates.TemplateResponse("docs.html", {"request": request, "title": "No Docs", "content": "<h1>No documentation found.</h1>", "docs": [], "current_doc": None})
|
| 292 |
+
|
| 293 |
+
# Redirect to first doc or show index
|
| 294 |
+
first_doc = docs[0]["id"]
|
| 295 |
+
return await show_doc(request, first_doc)
|
| 296 |
+
|
| 297 |
+
@app.get("/docs/{doc_id}")
|
| 298 |
+
async def show_doc(request: Request, doc_id: str):
|
| 299 |
+
docs = get_docs_list()
|
| 300 |
+
file_path = os.path.join(DOCS_DIR, f"{doc_id}.md")
|
| 301 |
+
|
| 302 |
+
if not os.path.exists(file_path):
|
| 303 |
+
return templates.TemplateResponse("docs.html", {
|
| 304 |
+
"request": request,
|
| 305 |
+
"title": "404 Not Found",
|
| 306 |
+
"content": "<h1>Document Not Found</h1><p>The requested documentation page does not exist.</p>",
|
| 307 |
+
"docs": docs,
|
| 308 |
+
"current_doc": doc_id
|
| 309 |
+
})
|
| 310 |
+
|
| 311 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
| 312 |
+
md_content = f.read()
|
| 313 |
+
|
| 314 |
+
html_content = markdown.markdown(
|
| 315 |
+
md_content,
|
| 316 |
+
extensions=[
|
| 317 |
+
'fenced_code',
|
| 318 |
+
'codehilite',
|
| 319 |
+
'tables',
|
| 320 |
+
'toc'
|
| 321 |
+
]
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
title = doc_id.replace("_", " ").title()
|
| 325 |
+
|
| 326 |
+
return templates.TemplateResponse("docs.html", {
|
| 327 |
+
"request": request,
|
| 328 |
+
"title": title,
|
| 329 |
+
"content": html_content,
|
| 330 |
+
"docs": docs,
|
| 331 |
+
"current_doc": doc_id
|
| 332 |
+
})
|
| 333 |
+
|
requirements.txt
CHANGED
|
@@ -38,3 +38,6 @@ opentelemetry-api
|
|
| 38 |
opentelemetry-sdk
|
| 39 |
opentelemetry-instrumentation-fastapi
|
| 40 |
opentelemetry-exporter-otlp
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
opentelemetry-sdk
|
| 39 |
opentelemetry-instrumentation-fastapi
|
| 40 |
opentelemetry-exporter-otlp
|
| 41 |
+
markdown==3.7
|
| 42 |
+
pygments==2.18.0
|
| 43 |
+
|
templates/docs.html
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>{{ title }} | Nexus Docs</title>
|
| 7 |
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
| 8 |
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
| 9 |
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Outfit:wght@700;800&family=Fira+Code:wght@400;500&display=swap" rel="stylesheet">
|
| 10 |
+
<style>
|
| 11 |
+
:root {
|
| 12 |
+
--primary: #7C3AED;
|
| 13 |
+
--primary-light: #F5F3FF;
|
| 14 |
+
--text-main: #0f172a;
|
| 15 |
+
--text-muted: #64748b;
|
| 16 |
+
--bg-page: #ffffff;
|
| 17 |
+
--bg-sidebar: #f8fafc;
|
| 18 |
+
--border: #e2e8f0;
|
| 19 |
+
--code-bg: #f1f5f9;
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
* { margin: 0; padding: 0; box-sizing: border-box; }
|
| 23 |
+
|
| 24 |
+
body {
|
| 25 |
+
background-color: var(--bg-page);
|
| 26 |
+
color: var(--text-main);
|
| 27 |
+
font-family: 'Inter', sans-serif;
|
| 28 |
+
line-height: 1.6;
|
| 29 |
+
display: flex;
|
| 30 |
+
min-height: 100vh;
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
/* --- SIDEBAR --- */
|
| 34 |
+
.sidebar {
|
| 35 |
+
width: 300px;
|
| 36 |
+
background: var(--bg-sidebar);
|
| 37 |
+
border-right: 1px solid var(--border);
|
| 38 |
+
padding: 40px 24px;
|
| 39 |
+
position: sticky;
|
| 40 |
+
top: 0;
|
| 41 |
+
height: 100vh;
|
| 42 |
+
overflow-y: auto;
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
.logo {
|
| 46 |
+
font-family: 'Outfit', sans-serif;
|
| 47 |
+
font-size: 20px;
|
| 48 |
+
font-weight: 800;
|
| 49 |
+
color: var(--primary);
|
| 50 |
+
text-decoration: none;
|
| 51 |
+
display: flex;
|
| 52 |
+
align-items: center;
|
| 53 |
+
gap: 10px;
|
| 54 |
+
margin-bottom: 40px;
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
.nav-group {
|
| 58 |
+
margin-bottom: 32px;
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
.nav-label {
|
| 62 |
+
font-size: 12px;
|
| 63 |
+
font-weight: 700;
|
| 64 |
+
text-transform: uppercase;
|
| 65 |
+
letter-spacing: 0.05em;
|
| 66 |
+
color: var(--text-muted);
|
| 67 |
+
margin-bottom: 12px;
|
| 68 |
+
display: block;
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
.nav-item {
|
| 72 |
+
display: block;
|
| 73 |
+
padding: 8px 12px;
|
| 74 |
+
border-radius: 8px;
|
| 75 |
+
text-decoration: none;
|
| 76 |
+
color: var(--text-main);
|
| 77 |
+
font-size: 14px;
|
| 78 |
+
font-weight: 500;
|
| 79 |
+
margin-bottom: 4px;
|
| 80 |
+
transition: all 0.2s;
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
.nav-item:hover {
|
| 84 |
+
background: var(--primary-light);
|
| 85 |
+
color: var(--primary);
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
.nav-item.active {
|
| 89 |
+
background: var(--primary);
|
| 90 |
+
color: white;
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
/* --- CONTENT --- */
|
| 94 |
+
main {
|
| 95 |
+
flex: 1;
|
| 96 |
+
padding: 60px 80px;
|
| 97 |
+
max-width: 900px;
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
.markdown-body h1 {
|
| 101 |
+
font-family: 'Outfit', sans-serif;
|
| 102 |
+
font-size: 42px;
|
| 103 |
+
font-weight: 800;
|
| 104 |
+
margin-bottom: 24px;
|
| 105 |
+
letter-spacing: -1px;
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
.markdown-body h2 {
|
| 109 |
+
font-family: 'Outfit', sans-serif;
|
| 110 |
+
font-size: 28px;
|
| 111 |
+
font-weight: 700;
|
| 112 |
+
margin-top: 48px;
|
| 113 |
+
margin-bottom: 16px;
|
| 114 |
+
border-bottom: 1px solid var(--border);
|
| 115 |
+
padding-bottom: 8px;
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
.markdown-body h3 {
|
| 119 |
+
font-size: 20px;
|
| 120 |
+
font-weight: 700;
|
| 121 |
+
margin-top: 32px;
|
| 122 |
+
margin-bottom: 12px;
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
.markdown-body p {
|
| 126 |
+
margin-bottom: 16px;
|
| 127 |
+
color: #334155;
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
.markdown-body code {
|
| 131 |
+
font-family: 'Fira Code', monospace;
|
| 132 |
+
background: var(--code-bg);
|
| 133 |
+
padding: 2px 6px;
|
| 134 |
+
border-radius: 4px;
|
| 135 |
+
font-size: 0.9em;
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
.markdown-body pre {
|
| 139 |
+
background: #1e293b;
|
| 140 |
+
color: #f8fafc;
|
| 141 |
+
padding: 24px;
|
| 142 |
+
border-radius: 12px;
|
| 143 |
+
overflow-x: auto;
|
| 144 |
+
margin: 24px 0;
|
| 145 |
+
font-family: 'Fira Code', monospace;
|
| 146 |
+
font-size: 14px;
|
| 147 |
+
line-height: 1.5;
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
.markdown-body pre code {
|
| 151 |
+
background: transparent;
|
| 152 |
+
padding: 0;
|
| 153 |
+
color: inherit;
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
.markdown-body ul, .markdown-body ol {
|
| 157 |
+
margin-bottom: 16px;
|
| 158 |
+
padding-left: 24px;
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
.markdown-body li {
|
| 162 |
+
margin-bottom: 8px;
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
.markdown-body img {
|
| 166 |
+
max-width: 100%;
|
| 167 |
+
border-radius: 12px;
|
| 168 |
+
border: 1px solid var(--border);
|
| 169 |
+
margin: 24px 0;
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
.markdown-body blockquote {
|
| 173 |
+
border-left: 4px solid var(--primary);
|
| 174 |
+
padding: 16px 24px;
|
| 175 |
+
background: var(--primary-light);
|
| 176 |
+
border-radius: 0 12px 12px 0;
|
| 177 |
+
margin: 24px 0;
|
| 178 |
+
color: var(--text-main);
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
/* Syntax Highlighting overrides if needed */
|
| 182 |
+
.codehilite .k { color: #f472b6; } /* keyword */
|
| 183 |
+
.codehilite .s { color: #34d399; } /* string */
|
| 184 |
+
.codehilite .nf { color: #60a5fa; } /* function */
|
| 185 |
+
.codehilite .c1 { color: #94a3b8; } /* comment */
|
| 186 |
+
|
| 187 |
+
@media (max-width: 1024px) {
|
| 188 |
+
main { padding: 40px; }
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
@media (max-width: 768px) {
|
| 192 |
+
body { flex-direction: column; }
|
| 193 |
+
.sidebar { width: 100%; height: auto; position: relative; }
|
| 194 |
+
main { padding: 32px 24px; }
|
| 195 |
+
}
|
| 196 |
+
</style>
|
| 197 |
+
</head>
|
| 198 |
+
<body>
|
| 199 |
+
<aside class="sidebar">
|
| 200 |
+
<a href="/" class="logo">
|
| 201 |
+
<div style="width: 28px; height: 28px; background: var(--primary); color: white; border-radius: 6px; display: flex; align-items: center; justify-content: center; font-size: 16px; font-weight: 900;">N</div>
|
| 202 |
+
NEXUS <span style="color: var(--text-muted); font-weight: 500; font-size: 14px;">DOCS</span>
|
| 203 |
+
</a>
|
| 204 |
+
|
| 205 |
+
<div class="nav-group">
|
| 206 |
+
<span class="nav-label">Documentation</span>
|
| 207 |
+
{% for doc in docs %}
|
| 208 |
+
<a href="/docs/{{ doc.id }}" class="nav-item {% if current_doc == doc.id %}active{% endif %}">
|
| 209 |
+
{{ doc.title }}
|
| 210 |
+
</a>
|
| 211 |
+
{% endfor %}
|
| 212 |
+
</div>
|
| 213 |
+
|
| 214 |
+
<div class="nav-group" style="margin-top: auto; padding-top: 40px;">
|
| 215 |
+
<a href="/" class="nav-item" style="color: var(--text-muted);">← Back to Hub</a>
|
| 216 |
+
</div>
|
| 217 |
+
</aside>
|
| 218 |
+
|
| 219 |
+
<main>
|
| 220 |
+
<article class="markdown-body">
|
| 221 |
+
{{ content | safe }}
|
| 222 |
+
</article>
|
| 223 |
+
</main>
|
| 224 |
+
</body>
|
| 225 |
+
</html>
|
templates/landing.html
CHANGED
|
@@ -253,6 +253,10 @@
|
|
| 253 |
<div style="width: 32px; height: 32px; background: var(--primary); color: white; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 18px; font-weight: 900;">N</div>
|
| 254 |
NEXUS
|
| 255 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
</nav>
|
| 257 |
|
| 258 |
<section class="hero">
|
|
@@ -276,6 +280,14 @@
|
|
| 276 |
</div>
|
| 277 |
<span class="portal-btn">Launch Console</span>
|
| 278 |
</a>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
</section>
|
| 280 |
</section>
|
| 281 |
</div>
|
|
|
|
| 253 |
<div style="width: 32px; height: 32px; background: var(--primary); color: white; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 18px; font-weight: 900;">N</div>
|
| 254 |
NEXUS
|
| 255 |
</div>
|
| 256 |
+
<div style="display: flex; gap: 24px; align-items: center;">
|
| 257 |
+
<a href="/docs" style="text-decoration: none; color: var(--text-muted); font-weight: 600; font-size: 14px; transition: color 0.2s;" onmouseover="this.style.color='var(--primary)'" onmouseout="this.style.color='var(--text-muted)'">Documentation</a>
|
| 258 |
+
<a href="/customer/" style="text-decoration: none; background: var(--primary-light); color: var(--primary); padding: 8px 16px; border-radius: 8px; font-weight: 700; font-size: 14px; transition: all 0.2s;" onmouseover="this.style.transform='scale(1.05)'" onmouseout="this.style.transform='scale(1)'">Sign In</a>
|
| 259 |
+
</div>
|
| 260 |
</nav>
|
| 261 |
|
| 262 |
<section class="hero">
|
|
|
|
| 280 |
</div>
|
| 281 |
<span class="portal-btn">Launch Console</span>
|
| 282 |
</a>
|
| 283 |
+
|
| 284 |
+
<a href="/docs" class="portal-card">
|
| 285 |
+
<div>
|
| 286 |
+
<h3>Technical Docs</h3>
|
| 287 |
+
<p>Deep dive into the architecture, agentic workflows, and API specifications of the Nexus engine.</p>
|
| 288 |
+
</div>
|
| 289 |
+
<span class="portal-btn">Browse Docs</span>
|
| 290 |
+
</a>
|
| 291 |
</section>
|
| 292 |
</section>
|
| 293 |
</div>
|