Update src/api/admin.py
Browse files- src/api/admin.py +531 -27
src/api/admin.py
CHANGED
|
@@ -1,8 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import secrets
|
| 2 |
import time
|
| 3 |
-
|
|
|
|
|
|
|
| 4 |
|
| 5 |
from fastapi import APIRouter, HTTPException, Request, Response
|
|
|
|
| 6 |
from pydantic import BaseModel
|
| 7 |
|
| 8 |
from src.config import get_settings
|
|
@@ -11,27 +29,85 @@ from src.services.runtime_store import JsonRuntimeStore
|
|
| 11 |
router = APIRouter()
|
| 12 |
admin_sessions: Dict[str, float] = {}
|
| 13 |
|
|
|
|
| 14 |
|
| 15 |
-
|
| 16 |
-
password: str
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
class ConfigUpdate(BaseModel):
|
| 20 |
-
key: str
|
| 21 |
-
value: str
|
| 22 |
|
|
|
|
| 23 |
|
| 24 |
def _cleanup_sessions() -> None:
|
| 25 |
now = time.time()
|
| 26 |
-
expired = [
|
| 27 |
-
for
|
| 28 |
-
admin_sessions.pop(
|
| 29 |
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
def _config_store() -> JsonRuntimeStore:
|
| 32 |
settings = get_settings()
|
| 33 |
-
return JsonRuntimeStore(settings.config_path, default=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
@router.post("/auth")
|
| 37 |
async def admin_auth(req: LoginRequest):
|
|
@@ -46,7 +122,7 @@ async def admin_auth(req: LoginRequest):
|
|
| 46 |
|
| 47 |
|
| 48 |
@router.post("/logout")
|
| 49 |
-
async def
|
| 50 |
token = request.cookies.get("admin_session")
|
| 51 |
if token:
|
| 52 |
admin_sessions.pop(token, None)
|
|
@@ -55,45 +131,473 @@ async def admin_logout(request: Request):
|
|
| 55 |
return resp
|
| 56 |
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
token = request.cookies.get("admin_session")
|
| 61 |
-
if
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
@router.get("/config")
|
| 66 |
async def get_config(request: Request):
|
| 67 |
_require_session(request)
|
| 68 |
-
return
|
| 69 |
|
| 70 |
|
| 71 |
@router.post("/config")
|
| 72 |
async def update_config(req: ConfigUpdate, request: Request):
|
| 73 |
_require_session(request)
|
| 74 |
-
allowed = {"max_results", "maintenance_mode"
|
|
|
|
| 75 |
if req.key not in allowed:
|
| 76 |
-
raise HTTPException(status_code=400,
|
| 77 |
-
|
| 78 |
-
if req.key == "max_results":
|
| 79 |
-
value = int(value)
|
| 80 |
-
if req.key == "maintenance_mode":
|
| 81 |
-
value = str(value).lower() in {"1", "true", "yes", "on"}
|
| 82 |
data = _config_store().load()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
data[req.key] = value
|
| 84 |
_config_store().save(data)
|
| 85 |
return {"status": "ok", "updated": req.key, "value": value}
|
| 86 |
|
| 87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
@router.get("/rag-status")
|
| 89 |
async def rag_status(request: Request):
|
| 90 |
_require_session(request)
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
|
| 95 |
@router.get("/metrics")
|
| 96 |
async def metrics(request: Request):
|
| 97 |
_require_session(request)
|
| 98 |
-
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
admin.py β LibBee v3.2
|
| 3 |
+
|
| 4 |
+
Changes over v3.1:
|
| 5 |
+
1. Full HTML admin dashboard at GET /admin (login β dashboard)
|
| 6 |
+
2. GET /admin/login β login page (redirects to /admin if already authed)
|
| 7 |
+
3. GET /admin/logout β clears session, redirects to /admin/login
|
| 8 |
+
4. GET /status β system health: RAG chunks, memory, uptime, API key status
|
| 9 |
+
5. POST /admin/rebuild β rebuild RAG index (calls rag_service.initialize)
|
| 10 |
+
6. All existing endpoints preserved: /auth, /logout, /config GET+POST,
|
| 11 |
+
/rag-status, /metrics
|
| 12 |
+
7. Circular import fix: uses get_rag_service() / get_metrics_service() accessors
|
| 13 |
+
8. Config now supports more keys: max_results, maintenance_mode,
|
| 14 |
+
welcome_message, custom_instructions, announcement
|
| 15 |
+
"""
|
| 16 |
import secrets
|
| 17 |
import time
|
| 18 |
+
import glob
|
| 19 |
+
import os
|
| 20 |
+
from typing import Any, Dict
|
| 21 |
|
| 22 |
from fastapi import APIRouter, HTTPException, Request, Response
|
| 23 |
+
from fastapi.responses import HTMLResponse, RedirectResponse
|
| 24 |
from pydantic import BaseModel
|
| 25 |
|
| 26 |
from src.config import get_settings
|
|
|
|
| 29 |
router = APIRouter()
|
| 30 |
admin_sessions: Dict[str, float] = {}
|
| 31 |
|
| 32 |
+
_START_TIME = time.time()
|
| 33 |
|
| 34 |
+
# ββ Config defaults ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 35 |
|
| 36 |
+
_CONFIG_DEFAULTS: Dict[str, Any] = {
|
| 37 |
+
"max_results": 5,
|
| 38 |
+
"maintenance_mode": False,
|
| 39 |
+
"welcome_message": "Hi! I'm LibBee, the Khalifa University Library AI Assistant.",
|
| 40 |
+
"custom_instructions": "",
|
| 41 |
+
"announcement": "",
|
| 42 |
+
}
|
| 43 |
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
+
# ββ Session helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 46 |
|
| 47 |
def _cleanup_sessions() -> None:
|
| 48 |
now = time.time()
|
| 49 |
+
expired = [t for t, exp in admin_sessions.items() if exp <= now]
|
| 50 |
+
for t in expired:
|
| 51 |
+
admin_sessions.pop(t, None)
|
| 52 |
|
| 53 |
|
| 54 |
+
def _require_session(request: Request) -> None:
|
| 55 |
+
_cleanup_sessions()
|
| 56 |
+
token = request.cookies.get("admin_session")
|
| 57 |
+
if not token or token not in admin_sessions:
|
| 58 |
+
raise HTTPException(status_code=401, detail="Not authenticated")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _has_session(request: Request) -> bool:
|
| 62 |
+
_cleanup_sessions()
|
| 63 |
+
token = request.cookies.get("admin_session")
|
| 64 |
+
return bool(token and token in admin_sessions)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# ββ Config store βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 68 |
+
|
| 69 |
def _config_store() -> JsonRuntimeStore:
|
| 70 |
settings = get_settings()
|
| 71 |
+
return JsonRuntimeStore(settings.config_path, default=_CONFIG_DEFAULTS)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _load_config() -> Dict[str, Any]:
|
| 75 |
+
data = _config_store().load()
|
| 76 |
+
# Ensure all defaults exist
|
| 77 |
+
for k, v in _CONFIG_DEFAULTS.items():
|
| 78 |
+
if k not in data:
|
| 79 |
+
data[k] = v
|
| 80 |
+
return data
|
| 81 |
+
|
| 82 |
|
| 83 |
+
# ββ HTML helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 84 |
+
|
| 85 |
+
def _esc(s: Any) -> str:
|
| 86 |
+
return (
|
| 87 |
+
str(s or "")
|
| 88 |
+
.replace("&", "&")
|
| 89 |
+
.replace("<", "<")
|
| 90 |
+
.replace(">", ">")
|
| 91 |
+
.replace('"', """)
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# ββ Pydantic models ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 96 |
+
|
| 97 |
+
class LoginRequest(BaseModel):
|
| 98 |
+
password: str
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class ConfigUpdate(BaseModel):
|
| 102 |
+
key: str
|
| 103 |
+
value: str
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class ConfigBulkUpdate(BaseModel):
|
| 107 |
+
settings: Dict[str, Any]
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# ββ Auth endpoints βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 111 |
|
| 112 |
@router.post("/auth")
|
| 113 |
async def admin_auth(req: LoginRequest):
|
|
|
|
| 122 |
|
| 123 |
|
| 124 |
@router.post("/logout")
|
| 125 |
+
async def admin_logout_post(request: Request):
|
| 126 |
token = request.cookies.get("admin_session")
|
| 127 |
if token:
|
| 128 |
admin_sessions.pop(token, None)
|
|
|
|
| 131 |
return resp
|
| 132 |
|
| 133 |
|
| 134 |
+
@router.get("/logout")
|
| 135 |
+
async def admin_logout_get(request: Request):
|
| 136 |
token = request.cookies.get("admin_session")
|
| 137 |
+
if token:
|
| 138 |
+
admin_sessions.pop(token, None)
|
| 139 |
+
resp = RedirectResponse(url="/admin/login")
|
| 140 |
+
resp.delete_cookie("admin_session")
|
| 141 |
+
return resp
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# ββ Login page βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 145 |
+
|
| 146 |
+
@router.get("/login", response_class=HTMLResponse)
|
| 147 |
+
async def admin_login_page(request: Request):
|
| 148 |
+
if _has_session(request):
|
| 149 |
+
return RedirectResponse(url="/admin")
|
| 150 |
+
return HTMLResponse("""<!DOCTYPE html>
|
| 151 |
+
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
| 152 |
+
<title>LibBee Admin β Login</title>
|
| 153 |
+
<style>
|
| 154 |
+
*{box-sizing:border-box;margin:0;padding:0}
|
| 155 |
+
body{font-family:'Segoe UI',system-ui,sans-serif;background:#f0f4f8;display:flex;
|
| 156 |
+
justify-content:center;align-items:center;min-height:100vh}
|
| 157 |
+
.box{background:#fff;border-radius:16px;padding:40px;width:360px;
|
| 158 |
+
box-shadow:0 4px 24px rgba(0,0,0,.1);text-align:center}
|
| 159 |
+
h1{color:#003366;font-size:1.3rem;margin-bottom:6px}
|
| 160 |
+
.sub{color:#6b7280;font-size:.84rem;margin-bottom:24px}
|
| 161 |
+
input{width:100%;padding:12px 14px;border:1.5px solid #d1d5db;border-radius:10px;
|
| 162 |
+
font-size:.92rem;margin-bottom:14px;outline:none}
|
| 163 |
+
input:focus{border-color:#003366}
|
| 164 |
+
.btn{width:100%;padding:12px;background:#003366;color:#fff;border:none;border-radius:10px;
|
| 165 |
+
font-weight:700;font-size:.92rem;cursor:pointer}
|
| 166 |
+
.btn:hover{background:#004488}
|
| 167 |
+
.err{color:#dc2626;font-size:.82rem;margin-bottom:10px;display:none}
|
| 168 |
+
</style></head><body>
|
| 169 |
+
<div class="box">
|
| 170 |
+
<h1>π LibBee Admin</h1>
|
| 171 |
+
<div class="sub">Khalifa University Library AI Dashboard</div>
|
| 172 |
+
<div class="err" id="err">Incorrect password.</div>
|
| 173 |
+
<form onsubmit="return login(event)">
|
| 174 |
+
<input type="password" id="pw" placeholder="Admin password" autofocus>
|
| 175 |
+
<button type="submit" class="btn">Login β</button>
|
| 176 |
+
</form>
|
| 177 |
+
</div>
|
| 178 |
+
<script>
|
| 179 |
+
async function login(e){
|
| 180 |
+
e.preventDefault();
|
| 181 |
+
const r=await fetch('/admin/auth',{method:'POST',
|
| 182 |
+
headers:{'Content-Type':'application/json'},
|
| 183 |
+
body:JSON.stringify({password:document.getElementById('pw').value})});
|
| 184 |
+
if(r.ok){location.href='/admin';}
|
| 185 |
+
else{document.getElementById('err').style.display='block';
|
| 186 |
+
document.getElementById('pw').value='';
|
| 187 |
+
document.getElementById('pw').focus();}
|
| 188 |
+
return false;
|
| 189 |
+
}
|
| 190 |
+
</script></body></html>""")
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
# ββ Main dashboard βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 194 |
+
|
| 195 |
+
@router.get("", response_class=HTMLResponse)
|
| 196 |
+
async def admin_dashboard(request: Request):
|
| 197 |
+
if not _has_session(request):
|
| 198 |
+
return RedirectResponse(url="/admin/login")
|
| 199 |
+
|
| 200 |
+
cfg = _load_config()
|
| 201 |
+
mm_selected_on = "selected" if cfg.get("maintenance_mode") else ""
|
| 202 |
+
mm_selected_off = "" if cfg.get("maintenance_mode") else "selected"
|
| 203 |
+
|
| 204 |
+
return HTMLResponse(f"""<!DOCTYPE html>
|
| 205 |
+
<html><head><meta charset="utf-8"><title>LibBee Admin</title>
|
| 206 |
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
| 207 |
+
<style>
|
| 208 |
+
*{{box-sizing:border-box;margin:0;padding:0}}
|
| 209 |
+
body{{font-family:'Segoe UI',system-ui,sans-serif;background:#f0f4f8;color:#1a1a2e}}
|
| 210 |
+
.topbar{{background:#003366;color:#fff;padding:12px 20px;display:flex;
|
| 211 |
+
align-items:center;justify-content:space-between}}
|
| 212 |
+
.topbar h1{{font-size:1.05rem;font-weight:700}}
|
| 213 |
+
.topbar a{{color:#C8A951;font-size:.8rem;text-decoration:none;padding:5px 12px;
|
| 214 |
+
border:1px solid #C8A951;border-radius:8px}}
|
| 215 |
+
.main{{max-width:960px;margin:24px auto;padding:0 16px;display:flex;
|
| 216 |
+
flex-direction:column;gap:18px}}
|
| 217 |
+
.card{{background:#fff;border-radius:14px;padding:20px;
|
| 218 |
+
box-shadow:0 2px 12px rgba(0,0,0,.07)}}
|
| 219 |
+
.card h2{{font-size:.95rem;font-weight:700;color:#003366;margin-bottom:14px}}
|
| 220 |
+
.stat-grid{{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:10px}}
|
| 221 |
+
.stat{{background:#f8fafc;border-radius:10px;padding:12px;text-align:center;
|
| 222 |
+
border:1px solid #e5e7eb}}
|
| 223 |
+
.stat .val{{font-size:1.5rem;font-weight:800;color:#003366}}
|
| 224 |
+
.stat .lbl{{font-size:.72rem;color:#6b7280;margin-top:2px}}
|
| 225 |
+
.ok{{color:#16a34a}}.warn{{color:#d97706}}.err{{color:#dc2626}}
|
| 226 |
+
label{{display:block;font-size:.8rem;font-weight:600;color:#374151;
|
| 227 |
+
margin-bottom:3px;margin-top:10px}}
|
| 228 |
+
input[type=text],textarea,select{{width:100%;padding:9px 12px;
|
| 229 |
+
border:1.5px solid #d1d5db;border-radius:8px;font-size:.86rem;font-family:inherit}}
|
| 230 |
+
textarea{{min-height:70px;resize:vertical}}
|
| 231 |
+
.btn{{padding:9px 20px;background:#003366;color:#fff;border:none;border-radius:8px;
|
| 232 |
+
font-weight:700;cursor:pointer;font-size:.85rem;margin-top:12px}}
|
| 233 |
+
.btn:hover{{background:#004488}}
|
| 234 |
+
.btn-green{{background:#16a34a}}.btn-green:hover{{background:#15803d}}
|
| 235 |
+
.btn-amber{{background:#d97706}}.btn-amber:hover{{background:#b45309}}
|
| 236 |
+
.btn-red{{background:#dc2626}}.btn-red:hover{{background:#b91c1c}}
|
| 237 |
+
.saved{{font-size:.8rem;color:#16a34a;margin-top:8px;display:none}}
|
| 238 |
+
table{{width:100%;border-collapse:collapse;font-size:.8rem}}
|
| 239 |
+
th{{background:#f1f5f9;padding:7px 10px;text-align:left;font-weight:700;color:#374151}}
|
| 240 |
+
td{{padding:6px 10px;border-bottom:1px solid #f1f5f9;word-break:break-word}}
|
| 241 |
+
tr:last-child td{{border-bottom:none}}
|
| 242 |
+
.tabs{{display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap}}
|
| 243 |
+
.tab{{padding:6px 14px;border-radius:20px;font-size:.8rem;font-weight:600;
|
| 244 |
+
cursor:pointer;border:1.5px solid #d1d5db;background:#fff;color:#6b7280}}
|
| 245 |
+
.tab.active{{background:#003366;color:#fff;border-color:#003366}}
|
| 246 |
+
.section{{display:none}}.section.active{{display:block}}
|
| 247 |
+
</style></head>
|
| 248 |
+
<body>
|
| 249 |
+
<div class="topbar">
|
| 250 |
+
<h1>π LibBee β Admin Dashboard</h1>
|
| 251 |
+
<a href="/admin/logout">Logout</a>
|
| 252 |
+
</div>
|
| 253 |
+
<div class="main">
|
| 254 |
+
|
| 255 |
+
<!-- TABS -->
|
| 256 |
+
<div class="tabs">
|
| 257 |
+
<div class="tab active" onclick="switchTab('status')">π Status</div>
|
| 258 |
+
<div class="tab" onclick="switchTab('config')">βοΈ Config</div>
|
| 259 |
+
<div class="tab" onclick="switchTab('rag')">π§ RAG</div>
|
| 260 |
+
<div class="tab" onclick="switchTab('metrics')">π Metrics</div>
|
| 261 |
+
</div>
|
| 262 |
+
|
| 263 |
+
<!-- STATUS TAB -->
|
| 264 |
+
<div class="section active card" id="tab-status">
|
| 265 |
+
<h2>π System Status</h2>
|
| 266 |
+
<div class="stat-grid" id="statusGrid">
|
| 267 |
+
<div style="color:#6b7280;font-size:.84rem">Loadingβ¦</div>
|
| 268 |
+
</div>
|
| 269 |
+
<div style="margin-top:14px;font-size:.74rem;color:#6b7280" id="statusTime"></div>
|
| 270 |
+
</div>
|
| 271 |
+
|
| 272 |
+
<!-- CONFIG TAB -->
|
| 273 |
+
<div class="section card" id="tab-config">
|
| 274 |
+
<h2>βοΈ Configuration</h2>
|
| 275 |
+
<label>Welcome Message</label>
|
| 276 |
+
<input type="text" id="cfg_welcome_message" value="{_esc(cfg.get('welcome_message',''))}">
|
| 277 |
+
<label>Custom Instructions (appended to system prompt)</label>
|
| 278 |
+
<textarea id="cfg_custom_instructions">{_esc(cfg.get('custom_instructions',''))}</textarea>
|
| 279 |
+
<label>Announcement Banner (leave blank to hide)</label>
|
| 280 |
+
<input type="text" id="cfg_announcement" value="{_esc(cfg.get('announcement',''))}">
|
| 281 |
+
<label>Max Search Results per Query</label>
|
| 282 |
+
<input type="text" id="cfg_max_results" value="{_esc(cfg.get('max_results', 5))}" style="width:80px">
|
| 283 |
+
<label>Maintenance Mode</label>
|
| 284 |
+
<select id="cfg_maintenance_mode">
|
| 285 |
+
<option value="false" {mm_selected_off}>Off β normal operation</option>
|
| 286 |
+
<option value="true" {mm_selected_on}>On β show maintenance message</option>
|
| 287 |
+
</select>
|
| 288 |
+
<button class="btn" onclick="saveConfig()">πΎ Save Configuration</button>
|
| 289 |
+
<div class="saved" id="saveMsg">β
Saved successfully.</div>
|
| 290 |
+
</div>
|
| 291 |
+
|
| 292 |
+
<!-- RAG TAB -->
|
| 293 |
+
<div class="section card" id="tab-rag">
|
| 294 |
+
<h2>π§ RAG Index</h2>
|
| 295 |
+
<div id="ragStats" style="font-size:.84rem;color:#6b7280;margin-bottom:12px">Loadingβ¦</div>
|
| 296 |
+
<button class="btn btn-green" onclick="rebuildRAG()">π Rebuild Index</button>
|
| 297 |
+
<div id="rebuildMsg" style="margin-top:10px;font-size:.84rem"></div>
|
| 298 |
+
</div>
|
| 299 |
+
|
| 300 |
+
<!-- METRICS TAB -->
|
| 301 |
+
<div class="section card" id="tab-metrics">
|
| 302 |
+
<h2>π Request Metrics</h2>
|
| 303 |
+
<div id="metricsContent" style="font-size:.84rem;color:#6b7280">Loadingβ¦</div>
|
| 304 |
+
</div>
|
| 305 |
+
|
| 306 |
+
</div><!-- /main -->
|
| 307 |
+
|
| 308 |
+
<script>
|
| 309 |
+
// ββ Tab switching ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 310 |
+
function switchTab(name){{
|
| 311 |
+
document.querySelectorAll('.tab').forEach(t=>t.classList.remove('active'));
|
| 312 |
+
document.querySelectorAll('.section').forEach(s=>s.classList.remove('active'));
|
| 313 |
+
document.querySelectorAll('.tab').forEach(t=>{{
|
| 314 |
+
if(t.textContent.toLowerCase().includes(name.substring(0,3)))t.classList.add('active');
|
| 315 |
+
}});
|
| 316 |
+
const sec=document.getElementById('tab-'+name);
|
| 317 |
+
if(sec)sec.classList.add('active');
|
| 318 |
+
if(name==='metrics')loadMetrics();
|
| 319 |
+
if(name==='rag')loadRAG();
|
| 320 |
+
}}
|
| 321 |
+
|
| 322 |
+
// ββ Status βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 323 |
+
async function loadStatus(){{
|
| 324 |
+
try{{
|
| 325 |
+
const r=await fetch('/admin/status');
|
| 326 |
+
if(!r.ok)throw new Error(r.status);
|
| 327 |
+
const d=await r.json();
|
| 328 |
+
const rag=d.rag_ready;
|
| 329 |
+
document.getElementById('statusGrid').innerHTML=`
|
| 330 |
+
<div class="stat"><div class="val ${{rag?'ok':'warn'}}">${{rag?'β
':'β οΈ'}}</div>
|
| 331 |
+
<div class="lbl">RAG (${{d.rag_chunks||0}} chunks)</div></div>
|
| 332 |
+
<div class="stat"><div class="val ${{d.openai?'ok':'err'}}">${{d.openai?'β
':'β'}}</div>
|
| 333 |
+
<div class="lbl">OpenAI API</div></div>
|
| 334 |
+
<div class="stat"><div class="val ${{d.anthropic?'ok':'warn'}}">${{d.anthropic?'β
':'β'}}</div>
|
| 335 |
+
<div class="lbl">Anthropic API</div></div>
|
| 336 |
+
<div class="stat"><div class="val ${{d.primo?'ok':'err'}}">${{d.primo?'β
':'β'}}</div>
|
| 337 |
+
<div class="lbl">PRIMO API</div></div>
|
| 338 |
+
<div class="stat"><div class="val">${{d.kb_files||0}}</div>
|
| 339 |
+
<div class="lbl">KB Files</div></div>
|
| 340 |
+
<div class="stat"><div class="val">${{Math.floor((d.uptime_secs||0)/60)}}m</div>
|
| 341 |
+
<div class="lbl">Uptime</div></div>
|
| 342 |
+
<div class="stat"><div class="val">${{d.mem_used_mb||0}}MB</div>
|
| 343 |
+
<div class="lbl">Memory (${{d.mem_pct||0}}%)</div></div>
|
| 344 |
+
<div class="stat"><div class="val ${{d.maintenance?'warn':'ok'}}">${{d.maintenance?'ON':'OFF'}}</div>
|
| 345 |
+
<div class="lbl">Maintenance</div></div>
|
| 346 |
+
`;
|
| 347 |
+
document.getElementById('statusTime').textContent=
|
| 348 |
+
'Last refreshed: '+new Date().toLocaleTimeString();
|
| 349 |
+
}}catch(e){{
|
| 350 |
+
document.getElementById('statusGrid').innerHTML=
|
| 351 |
+
'<span class="err">β Cannot reach server: '+e.message+'</span>';
|
| 352 |
+
}}
|
| 353 |
+
}}
|
| 354 |
+
|
| 355 |
+
// ββ Config βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 356 |
+
async function saveConfig(){{
|
| 357 |
+
const keys=['welcome_message','custom_instructions','announcement','max_results','maintenance_mode'];
|
| 358 |
+
const settings={{}};
|
| 359 |
+
keys.forEach(k=>{{
|
| 360 |
+
const el=document.getElementById('cfg_'+k);
|
| 361 |
+
if(el)settings[k]=el.value;
|
| 362 |
+
}});
|
| 363 |
+
const r=await fetch('/admin/config-bulk',{{
|
| 364 |
+
method:'POST',
|
| 365 |
+
headers:{{'Content-Type':'application/json'}},
|
| 366 |
+
body:JSON.stringify({{settings}})
|
| 367 |
+
}});
|
| 368 |
+
if(r.ok){{
|
| 369 |
+
const m=document.getElementById('saveMsg');
|
| 370 |
+
m.style.display='block';
|
| 371 |
+
setTimeout(()=>m.style.display='none',3000);
|
| 372 |
+
}}
|
| 373 |
+
}}
|
| 374 |
+
|
| 375 |
+
// ββ RAG ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 376 |
+
async function loadRAG(){{
|
| 377 |
+
try{{
|
| 378 |
+
const r=await fetch('/admin/rag-status');
|
| 379 |
+
const d=await r.json();
|
| 380 |
+
document.getElementById('ragStats').innerHTML=
|
| 381 |
+
'<strong>Ready:</strong> '+d.ready+
|
| 382 |
+
' | <strong>Chunks:</strong> '+d.chunk_count+
|
| 383 |
+
' | <strong>KB Dir:</strong> '+d.knowledge_dir+
|
| 384 |
+
' | <strong>Hash:</strong> '+d.kb_hash.substring(0,12)+'β¦';
|
| 385 |
+
}}catch(e){{
|
| 386 |
+
document.getElementById('ragStats').textContent='Could not load RAG stats.';
|
| 387 |
+
}}
|
| 388 |
+
}}
|
| 389 |
+
|
| 390 |
+
async function rebuildRAG(){{
|
| 391 |
+
const el=document.getElementById('rebuildMsg');
|
| 392 |
+
el.innerHTML='<span style="color:#d97706">β³ Rebuilding β this may take 30β60 secondsβ¦</span>';
|
| 393 |
+
try{{
|
| 394 |
+
const r=await fetch('/admin/rebuild',{{method:'POST'}});
|
| 395 |
+
const d=await r.json();
|
| 396 |
+
if(d.status==='ok')
|
| 397 |
+
el.innerHTML='<span style="color:#16a34a">β
Done β '+d.chunks+' chunks rebuilt.</span>';
|
| 398 |
+
else
|
| 399 |
+
el.innerHTML='<span class="err">β '+d.error+'</span>';
|
| 400 |
+
loadRAG();
|
| 401 |
+
}}catch(e){{
|
| 402 |
+
el.innerHTML='<span class="err">β '+e.message+'</span>';
|
| 403 |
+
}}
|
| 404 |
+
}}
|
| 405 |
+
|
| 406 |
+
// ββ Metrics ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 407 |
+
async function loadMetrics(){{
|
| 408 |
+
try{{
|
| 409 |
+
const r=await fetch('/admin/metrics');
|
| 410 |
+
const d=await r.json();
|
| 411 |
+
const fmt=v=>JSON.stringify(v,null,2);
|
| 412 |
+
let html='<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">';
|
| 413 |
+
|
| 414 |
+
// Top-level counters
|
| 415 |
+
const counters=[
|
| 416 |
+
['agent_requests','Agent Requests'],
|
| 417 |
+
['search_requests','Search Requests'],
|
| 418 |
+
['feedback_total','Feedback Total'],
|
| 419 |
+
['follow_up_hits','Follow-up Hits'],
|
| 420 |
+
['search_handoffs','Search Handoffs'],
|
| 421 |
+
['summary_fallbacks','Summary Fallbacks'],
|
| 422 |
+
];
|
| 423 |
+
html+='<div><h3 style="font-size:.82rem;font-weight:700;color:#003366;margin-bottom:8px">Counters</h3>';
|
| 424 |
+
html+='<table><tbody>';
|
| 425 |
+
counters.forEach(([k,l])=>{{
|
| 426 |
+
html+=`<tr><td style="font-weight:600">${{l}}</td><td>${{d[k]||0}}</td></tr>`;
|
| 427 |
+
}});
|
| 428 |
+
html+='</tbody></table></div>';
|
| 429 |
+
|
| 430 |
+
// Intent breakdown
|
| 431 |
+
const intents=d.intents||{{}};
|
| 432 |
+
html+='<div><h3 style="font-size:.82rem;font-weight:700;color:#003366;margin-bottom:8px">Intent Breakdown</h3>';
|
| 433 |
+
html+='<table><tbody>';
|
| 434 |
+
Object.entries(intents).sort((a,b)=>b[1]-a[1]).forEach(([k,v])=>{{
|
| 435 |
+
html+=`<tr><td style="font-weight:600">${{k}}</td><td>${{v}}</td></tr>`;
|
| 436 |
+
}});
|
| 437 |
+
if(!Object.keys(intents).length)html+='<tr><td colspan=2 style="color:#6b7280">No data yet</td></tr>';
|
| 438 |
+
html+='</tbody></table></div>';
|
| 439 |
|
| 440 |
+
// Errors
|
| 441 |
+
const errors=d.errors||{{}};
|
| 442 |
+
html+='<div><h3 style="font-size:.82rem;font-weight:700;color:#003366;margin-bottom:8px">Errors</h3>';
|
| 443 |
+
html+='<table><tbody>';
|
| 444 |
+
Object.entries(errors).sort((a,b)=>b[1]-a[1]).forEach(([k,v])=>{{
|
| 445 |
+
html+=`<tr><td style="font-weight:600;color:#dc2626">${{k}}</td><td>${{v}}</td></tr>`;
|
| 446 |
+
}});
|
| 447 |
+
if(!Object.keys(errors).length)html+='<tr><td colspan=2 style="color:#16a34a">No errors π</td></tr>';
|
| 448 |
+
html+='</tbody></table></div>';
|
| 449 |
+
|
| 450 |
+
html+='<div style="font-size:.72rem;color:#6b7280">Last updated: '+(d.last_updated?new Date(d.last_updated*1000).toLocaleString():'-')+'</div>';
|
| 451 |
+
html+='</div>';
|
| 452 |
+
document.getElementById('metricsContent').innerHTML=html;
|
| 453 |
+
}}catch(e){{
|
| 454 |
+
document.getElementById('metricsContent').innerHTML=
|
| 455 |
+
'<span class="err">β Could not load metrics: '+e.message+'</span>';
|
| 456 |
+
}}
|
| 457 |
+
}}
|
| 458 |
+
|
| 459 |
+
// Init
|
| 460 |
+
loadStatus();
|
| 461 |
+
setInterval(loadStatus,30000);
|
| 462 |
+
</script>
|
| 463 |
+
</body></html>""")
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
# ββ API endpoints (existing + new) ββββββββββββββββββββββββββββββββββββββββββββ
|
| 467 |
|
| 468 |
@router.get("/config")
|
| 469 |
async def get_config(request: Request):
|
| 470 |
_require_session(request)
|
| 471 |
+
return _load_config()
|
| 472 |
|
| 473 |
|
| 474 |
@router.post("/config")
|
| 475 |
async def update_config(req: ConfigUpdate, request: Request):
|
| 476 |
_require_session(request)
|
| 477 |
+
allowed = {"max_results", "maintenance_mode", "welcome_message",
|
| 478 |
+
"custom_instructions", "announcement"}
|
| 479 |
if req.key not in allowed:
|
| 480 |
+
raise HTTPException(status_code=400,
|
| 481 |
+
detail=f"Unsupported key. Allowed: {sorted(allowed)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 482 |
data = _config_store().load()
|
| 483 |
+
value: Any = req.value
|
| 484 |
+
if req.key == "max_results":
|
| 485 |
+
value = int(req.value)
|
| 486 |
+
elif req.key == "maintenance_mode":
|
| 487 |
+
value = str(req.value).lower() in {"1", "true", "yes", "on"}
|
| 488 |
data[req.key] = value
|
| 489 |
_config_store().save(data)
|
| 490 |
return {"status": "ok", "updated": req.key, "value": value}
|
| 491 |
|
| 492 |
|
| 493 |
+
@router.post("/config-bulk")
|
| 494 |
+
async def update_config_bulk(req: ConfigBulkUpdate, request: Request):
|
| 495 |
+
_require_session(request)
|
| 496 |
+
data = _config_store().load()
|
| 497 |
+
for key, value in req.settings.items():
|
| 498 |
+
if key == "max_results":
|
| 499 |
+
try:
|
| 500 |
+
data[key] = int(value)
|
| 501 |
+
except (ValueError, TypeError):
|
| 502 |
+
pass
|
| 503 |
+
elif key == "maintenance_mode":
|
| 504 |
+
data[key] = str(value).lower() in {"1", "true", "yes", "on", "true"}
|
| 505 |
+
else:
|
| 506 |
+
data[key] = str(value)
|
| 507 |
+
_config_store().save(data)
|
| 508 |
+
return {"status": "ok", "updated": list(req.settings.keys())}
|
| 509 |
+
|
| 510 |
+
|
| 511 |
@router.get("/rag-status")
|
| 512 |
async def rag_status(request: Request):
|
| 513 |
_require_session(request)
|
| 514 |
+
try:
|
| 515 |
+
from app import get_rag_service
|
| 516 |
+
return get_rag_service().get_stats()
|
| 517 |
+
except Exception as e:
|
| 518 |
+
return {"error": str(e), "ready": False}
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
@router.post("/rebuild")
|
| 522 |
+
async def rebuild_rag(request: Request):
|
| 523 |
+
_require_session(request)
|
| 524 |
+
try:
|
| 525 |
+
from app import get_rag_service
|
| 526 |
+
svc = get_rag_service()
|
| 527 |
+
settings = get_settings()
|
| 528 |
+
if not settings.openai_api_key:
|
| 529 |
+
return {"status": "error", "error": "OPENAI_API_KEY not set"}
|
| 530 |
+
# Force a fresh build by clearing the cache hash
|
| 531 |
+
svc._kb_hash = ""
|
| 532 |
+
await svc.initialize(openai_api_key=settings.openai_api_key)
|
| 533 |
+
return {"status": "ok", "chunks": len(svc.bm25_corpus), "ready": svc.is_ready()}
|
| 534 |
+
except Exception as e:
|
| 535 |
+
return {"status": "error", "error": str(e)}
|
| 536 |
|
| 537 |
|
| 538 |
@router.get("/metrics")
|
| 539 |
async def metrics(request: Request):
|
| 540 |
_require_session(request)
|
| 541 |
+
try:
|
| 542 |
+
from app import get_metrics_service
|
| 543 |
+
return get_metrics_service().snapshot()
|
| 544 |
+
except Exception as e:
|
| 545 |
+
return {"error": str(e)}
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
@router.get("/status")
|
| 549 |
+
async def system_status(request: Request):
|
| 550 |
+
_require_session(request)
|
| 551 |
+
settings = get_settings()
|
| 552 |
+
|
| 553 |
+
# Memory
|
| 554 |
+
mem_used_mb = mem_pct = 0
|
| 555 |
+
try:
|
| 556 |
+
with open("/sys/fs/cgroup/memory.current") as f:
|
| 557 |
+
used = int(f.read().strip())
|
| 558 |
+
with open("/sys/fs/cgroup/memory.max") as f:
|
| 559 |
+
val = f.read().strip()
|
| 560 |
+
total = int(val) if val != "max" else 16 * 1024 ** 3
|
| 561 |
+
mem_used_mb = round(used / 1024 / 1024)
|
| 562 |
+
mem_pct = round(used / total * 100)
|
| 563 |
+
except Exception:
|
| 564 |
+
try:
|
| 565 |
+
with open("/sys/fs/cgroup/memory/memory.usage_in_bytes") as f:
|
| 566 |
+
used = int(f.read().strip())
|
| 567 |
+
with open("/sys/fs/cgroup/memory/memory.limit_in_bytes") as f:
|
| 568 |
+
total = int(f.read().strip())
|
| 569 |
+
mem_used_mb = round(used / 1024 / 1024)
|
| 570 |
+
mem_pct = round(used / total * 100)
|
| 571 |
+
except Exception:
|
| 572 |
+
pass
|
| 573 |
+
|
| 574 |
+
# RAG stats
|
| 575 |
+
rag_ready = False
|
| 576 |
+
rag_chunks = 0
|
| 577 |
+
kb_files = 0
|
| 578 |
+
try:
|
| 579 |
+
from app import get_rag_service
|
| 580 |
+
svc = get_rag_service()
|
| 581 |
+
rag_ready = svc.is_ready()
|
| 582 |
+
rag_chunks = len(svc.bm25_corpus)
|
| 583 |
+
kb_dir = settings.kb_dir
|
| 584 |
+
kb_files = len(list(kb_dir.glob("*.txt"))) if kb_dir.exists() else 0
|
| 585 |
+
except Exception:
|
| 586 |
+
pass
|
| 587 |
+
|
| 588 |
+
cfg = _load_config()
|
| 589 |
+
|
| 590 |
+
return {
|
| 591 |
+
"status": "ok",
|
| 592 |
+
"rag_ready": rag_ready,
|
| 593 |
+
"rag_chunks": rag_chunks,
|
| 594 |
+
"kb_files": kb_files,
|
| 595 |
+
"openai": bool(settings.openai_api_key),
|
| 596 |
+
"anthropic": bool(settings.anthropic_api_key),
|
| 597 |
+
"primo": bool(settings.primo_api_key),
|
| 598 |
+
"mem_used_mb": mem_used_mb,
|
| 599 |
+
"mem_pct": mem_pct,
|
| 600 |
+
"uptime_secs": round(time.time() - _START_TIME),
|
| 601 |
+
"maintenance": bool(cfg.get("maintenance_mode")),
|
| 602 |
+
"version": "3.2.0",
|
| 603 |
+
}
|