nikeshn commited on
Commit
cc41a34
Β·
verified Β·
1 Parent(s): f99f29c

Create Admin.py

Browse files
Files changed (1) hide show
  1. Admin.py +545 -0
Admin.py ADDED
@@ -0,0 +1,545 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ admin.py β€” ResearchBee admin dashboard
3
+
4
+ Ported from LibBee v3.8's admin module so the two dashboards behave
5
+ identically: same cookie-session login, same 5-attempt IP lockout, same
6
+ server-rendered single page, same visual language. Someone who
7
+ administers LibBee should not have to learn a second interface.
8
+
9
+ What is deliberately different
10
+ ------------------------------
11
+ LibBee's dashboard shows recent questions. This one cannot, because
12
+ ResearchBee never stores question text β€” see usage.py. The equivalent
13
+ panels here answer "how much of each tool is being used" and "how often
14
+ could we not answer", both from counters.
15
+
16
+ Mount with:
17
+ from admin import router as admin_router
18
+ app.include_router(admin_router, prefix="/admin")
19
+
20
+ Environment:
21
+ RESEARCHBEE_ADMIN_PASSWORD required β€” the dashboard is unreachable without it
22
+ CLOUDFLARE_WORKER_URL the LibBee Worker (shared)
23
+ CLOUDFLARE_WORKER_TOKEN must equal the Worker's ANALYTICS_TOKEN
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import json
29
+ import os
30
+ import secrets
31
+ import time
32
+ from typing import Any, Dict, Optional
33
+
34
+ from fastapi import APIRouter, HTTPException, Request, Response
35
+ from fastapi.responses import HTMLResponse, RedirectResponse
36
+ from pydantic import BaseModel
37
+
38
+ router = APIRouter()
39
+
40
+ _START_TIME = time.time()
41
+
42
+ ADMIN_PASSWORD = (os.environ.get("RESEARCHBEE_ADMIN_PASSWORD") or "").strip()
43
+ WORKER_URL = (os.environ.get("CLOUDFLARE_WORKER_URL") or "").strip().strip('"').strip("'").rstrip("/")
44
+ WORKER_TOKEN = (os.environ.get("CLOUDFLARE_WORKER_TOKEN") or "").strip()
45
+
46
+ _SESSIONS_FILE = "/tmp/researchbee_admin_sessions.json"
47
+
48
+ admin_sessions: Dict[str, float] = {}
49
+
50
+ # Failed logins per IP. Five misses inside the window locks that IP out
51
+ # for fifteen minutes β€” enough to make guessing a shared password
52
+ # impractical without locking out a librarian who fat-fingers it twice.
53
+ _login_attempts: Dict[str, list] = {}
54
+ _MAX_LOGIN_ATTEMPTS = 5
55
+ _LOCKOUT_WINDOW = 300
56
+ _LOCKOUT_DURATION = 900
57
+
58
+
59
+ # ── Sessions ──────────────────────────────────────────────────────────
60
+
61
+ def _load_sessions() -> None:
62
+ try:
63
+ with open(_SESSIONS_FILE, "r", encoding="utf-8") as f:
64
+ data = json.load(f)
65
+ now = time.time()
66
+ admin_sessions.update({
67
+ t: exp for t, exp in data.items()
68
+ if isinstance(exp, (int, float)) and exp > now
69
+ })
70
+ except Exception:
71
+ pass
72
+
73
+
74
+ def _save_sessions() -> None:
75
+ try:
76
+ now = time.time()
77
+ with open(_SESSIONS_FILE, "w", encoding="utf-8") as f:
78
+ json.dump({t: e for t, e in admin_sessions.items() if e > now}, f)
79
+ except Exception:
80
+ pass
81
+
82
+
83
+ def _cleanup_sessions() -> None:
84
+ now = time.time()
85
+ for t in [t for t, exp in admin_sessions.items() if exp <= now]:
86
+ admin_sessions.pop(t, None)
87
+ _load_sessions()
88
+
89
+
90
+ def _has_session(request: Request) -> bool:
91
+ _cleanup_sessions()
92
+ token = request.cookies.get("rb_admin_session")
93
+ return bool(token and token in admin_sessions)
94
+
95
+
96
+ def _require_session(request: Request) -> None:
97
+ if not _has_session(request):
98
+ raise HTTPException(status_code=401, detail="Not authenticated")
99
+
100
+
101
+ class LoginRequest(BaseModel):
102
+ password: str
103
+
104
+
105
+ # ── Auth ──────────────────────────────────────────────────────────────
106
+
107
+ @router.post("/auth")
108
+ async def admin_auth(req: LoginRequest, request: Request):
109
+ client_ip = request.client.host if request.client else "unknown"
110
+ now = time.time()
111
+
112
+ attempts = [t for t in _login_attempts.get(client_ip, []) if now - t < _LOCKOUT_WINDOW]
113
+ if len(attempts) >= _MAX_LOGIN_ATTEMPTS:
114
+ wait = int(_LOCKOUT_DURATION - (now - attempts[0]))
115
+ raise HTTPException(429, f"Too many failed attempts. Try again in {wait} seconds.")
116
+
117
+ if not ADMIN_PASSWORD or not secrets.compare_digest(
118
+ req.password.encode(), ADMIN_PASSWORD.encode()
119
+ ):
120
+ attempts.append(now)
121
+ _login_attempts[client_ip] = attempts
122
+ remaining = _MAX_LOGIN_ATTEMPTS - len(attempts)
123
+ if not ADMIN_PASSWORD:
124
+ detail = "No admin password is set on this Space. Add RESEARCHBEE_ADMIN_PASSWORD to the Space secrets."
125
+ elif remaining <= 0:
126
+ detail = f"Too many failed attempts. Try again in {_LOCKOUT_DURATION // 60} minutes."
127
+ else:
128
+ detail = f"Incorrect password. {remaining} attempt{'s' if remaining != 1 else ''} left before lockout."
129
+ raise HTTPException(401, detail)
130
+
131
+ _login_attempts.pop(client_ip, None)
132
+ token = secrets.token_hex(32)
133
+ admin_sessions[token] = now + 86400
134
+ _save_sessions()
135
+ resp = Response(content='{"status":"ok"}', media_type="application/json")
136
+ resp.set_cookie("rb_admin_session", token, httponly=True,
137
+ max_age=86400, samesite="lax", secure=True)
138
+ return resp
139
+
140
+
141
+ @router.get("/logout")
142
+ async def admin_logout(request: Request):
143
+ token = request.cookies.get("rb_admin_session")
144
+ if token:
145
+ admin_sessions.pop(token, None)
146
+ _save_sessions()
147
+ resp = RedirectResponse(url="/admin/login")
148
+ resp.delete_cookie("rb_admin_session")
149
+ return resp
150
+
151
+
152
+ # ── Worker proxies ────────────────────────────────────────────────────
153
+ # The Worker URL and token stay server-side. The browser only ever talks
154
+ # to this Space, so neither secret reaches the page.
155
+
156
+ async def _worker_get(path: str, params: Optional[dict] = None):
157
+ if not WORKER_URL:
158
+ raise HTTPException(503, "CLOUDFLARE_WORKER_URL is not set on this Space")
159
+ import httpx
160
+ headers = {"Authorization": f"Bearer {WORKER_TOKEN}"} if WORKER_TOKEN else {}
161
+ try:
162
+ async with httpx.AsyncClient(timeout=15) as client:
163
+ r = await client.get(f"{WORKER_URL}{path}", params=params or {}, headers=headers)
164
+ return r.json()
165
+ except HTTPException:
166
+ raise
167
+ except Exception as exc:
168
+ raise HTTPException(502, f"Worker unreachable: {type(exc).__name__}: {exc}")
169
+
170
+
171
+ @router.get("/usage")
172
+ async def admin_usage(request: Request, days: int = 30):
173
+ _require_session(request)
174
+ return await _worker_get("/rb/usage", {"days": max(0, min(days, 3650))})
175
+
176
+
177
+ @router.get("/canary-status")
178
+ async def admin_canary_status(request: Request):
179
+ _require_session(request)
180
+ return await _worker_get("/rb/canary/status")
181
+
182
+
183
+ @router.get("/local-usage")
184
+ async def admin_local_usage(request: Request):
185
+ """Counts held in this container since it last started. Useful when
186
+ the Worker is unreachable, and as a cross-check that counting is
187
+ actually happening before blaming the Worker."""
188
+ _require_session(request)
189
+ from usage import usage
190
+ return usage.snapshot()
191
+
192
+
193
+ @router.get("/status")
194
+ async def admin_status(request: Request):
195
+ _require_session(request)
196
+ import app as rb_app
197
+
198
+ out: Dict[str, Any] = {
199
+ "uptime_seconds": int(time.time() - _START_TIME),
200
+ "worker_url_configured": bool(WORKER_URL),
201
+ "worker_token_configured": bool(WORKER_TOKEN),
202
+ "admin_password_set": bool(ADMIN_PASSWORD),
203
+ "openai_key_set": bool(os.environ.get("OPENAI_API_KEY")),
204
+ }
205
+ try:
206
+ out["health"] = await rb_app.health()
207
+ except Exception as exc:
208
+ out["health"] = {"error": f"{type(exc).__name__}: {exc}"}
209
+ return out
210
+
211
+
212
+ @router.post("/reload-khazna")
213
+ async def admin_reload_khazna(request: Request):
214
+ """Session-protected wrapper around the existing reload endpoint, so
215
+ the button on this page works without exposing an unauthenticated
216
+ admin path."""
217
+ _require_session(request)
218
+ import asyncio
219
+ from app import khazna_index
220
+ ok = await asyncio.to_thread(khazna_index.reload)
221
+ return {"reloaded": ok, "khazna": khazna_index.status}
222
+
223
+
224
+ # ── Login page ────────────────────────────────────────────────────────
225
+
226
+ @router.get("/login", response_class=HTMLResponse)
227
+ async def admin_login_page(request: Request):
228
+ if _has_session(request):
229
+ return RedirectResponse(url="/admin")
230
+ return HTMLResponse("""<!DOCTYPE html>
231
+ <html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
232
+ <title>ResearchBee β€” Admin</title>
233
+ <style>
234
+ *{box-sizing:border-box;margin:0;padding:0}
235
+ body{font-family:'Segoe UI',system-ui,sans-serif;background:#f0f4f8;display:flex;justify-content:center;align-items:center;min-height:100vh}
236
+ .box{background:#fff;border-radius:16px;padding:40px;width:360px;box-shadow:0 4px 24px rgba(0,0,0,.1);text-align:center}
237
+ h1{color:#003366;font-size:1.3rem;margin-bottom:6px}
238
+ .sub{color:#6b7280;font-size:.84rem;margin-bottom:24px}
239
+ input{width:100%;padding:12px 14px;border:1.5px solid #d1d5db;border-radius:10px;font-size:.92rem;margin-bottom:14px}
240
+ input:focus{outline:none;border-color:#003366}
241
+ .btn{width:100%;padding:12px;background:#003366;color:#fff;border:none;border-radius:10px;font-weight:700;font-size:.92rem;cursor:pointer}
242
+ .btn:hover{background:#004488}
243
+ .err{color:#dc2626;font-size:.82rem;margin-bottom:10px;display:none}
244
+ </style></head><body>
245
+ <div class="box">
246
+ <h1>🐝 ResearchBee Admin</h1>
247
+ <div class="sub">KU Library publishing assistant</div>
248
+ <div class="err" id="err"></div>
249
+ <form onsubmit="return go(event)">
250
+ <input type="password" id="pw" placeholder="Admin password" autofocus>
251
+ <button type="submit" class="btn">Sign in</button>
252
+ </form>
253
+ </div>
254
+ <script>
255
+ async function go(e){
256
+ e.preventDefault();
257
+ const r=await fetch('/admin/auth',{method:'POST',headers:{'Content-Type':'application/json'},
258
+ body:JSON.stringify({password:document.getElementById('pw').value})});
259
+ if(r.ok){window.location.href='/admin';return false;}
260
+ const d=await r.json().catch(()=>({}));
261
+ const el=document.getElementById('err');
262
+ el.textContent=d.detail||'Incorrect password.';el.style.display='block';
263
+ document.getElementById('pw').value='';document.getElementById('pw').focus();
264
+ return false;
265
+ }
266
+ </script></body></html>""")
267
+
268
+
269
+ # ── Dashboard ─────────────────────────────────────────────────────────
270
+
271
+ SURFACE_LABELS = {
272
+ "journal_subject": "Find a journal β€” browse by subject",
273
+ "journal_manuscript": "Find a journal β€” analyse manuscript",
274
+ "licence_deposit": "Share your article (deposit rights)",
275
+ "data_repository": "Deposit your data (repository finder)",
276
+ "cover_letter": "Cover letter generator",
277
+ "chat": "Chat assistant",
278
+ }
279
+
280
+ GAP_LABELS = {
281
+ "scimago_miss": "Subject not found in the journal index",
282
+ "oaworks_404": "No permissions record for that article",
283
+ "oaworks_unconfirmed": "Permissions record found but policy not confirmed",
284
+ "doi_unparseable": "Could not read a DOI from what was entered",
285
+ "khazna_no_doi": "No DOI supplied, so Khazna could not be checked",
286
+ "khazna_unavailable": "Khazna index not loaded",
287
+ "no_apc_agreement": "No KU APC agreement for that publisher",
288
+ "no_repository_match": "No repository matched the dataset",
289
+ }
290
+
291
+
292
+ @router.get("", response_class=HTMLResponse)
293
+ async def admin_dashboard(request: Request):
294
+ if not _has_session(request):
295
+ return RedirectResponse(url="/admin/login")
296
+
297
+ return HTMLResponse("""<!DOCTYPE html>
298
+ <html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
299
+ <title>ResearchBee β€” Admin</title>
300
+ <style>
301
+ *{box-sizing:border-box;margin:0;padding:0}
302
+ body{font-family:'Segoe UI',system-ui,sans-serif;background:#f0f4f8;color:#1a1a2e}
303
+ .topbar{background:#003366;color:#fff;padding:12px 20px;display:flex;align-items:center;justify-content:space-between}
304
+ .topbar h1{font-size:1.1rem;font-weight:700}
305
+ .topbar a{color:#C8A951;font-size:.82rem;text-decoration:none;padding:5px 12px;border:1px solid #C8A951;border-radius:8px}
306
+ .main{max-width:900px;margin:24px auto;padding:0 16px;display:flex;flex-direction:column;gap:20px}
307
+ .card{background:#fff;border-radius:14px;padding:20px;box-shadow:0 2px 12px rgba(0,0,0,.07)}
308
+ .card h2{font-size:1rem;font-weight:700;color:#003366;margin-bottom:6px}
309
+ .card .hint{font-size:.78rem;color:#6b7280;margin-bottom:14px;line-height:1.5}
310
+ .btn{padding:9px 20px;background:#003366;color:#fff;border:none;border-radius:8px;font-weight:700;cursor:pointer;font-size:.88rem}
311
+ .btn:hover{background:#004488}
312
+ .btn-ghost{background:#fff;color:#003366;border:1.5px solid #d1d5db}
313
+ .btn-ghost:hover{background:#f8fafc}
314
+ .stat-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:12px}
315
+ .stat{background:#f8fafc;border-radius:10px;padding:14px;text-align:center;border:1px solid #e5e7eb}
316
+ .stat .val{font-size:1.6rem;font-weight:800;color:#003366}
317
+ .stat .lbl{font-size:.74rem;color:#6b7280;margin-top:2px}
318
+ table{width:100%;border-collapse:collapse;font-size:.84rem}
319
+ th{text-align:left;font-size:.72rem;text-transform:uppercase;letter-spacing:.05em;color:#6b7280;border-bottom:1px solid #e5e7eb;padding:7px 8px}
320
+ td{padding:7px 8px;border-bottom:1px solid #f1f5f9}
321
+ tr:last-child td{border-bottom:none}
322
+ .bar{height:8px;background:#e5e7eb;border-radius:4px;overflow:hidden;min-width:60px}
323
+ .bar span{display:block;height:100%;background:#003366}
324
+ .pill{display:inline-block;padding:2px 9px;border-radius:20px;font-size:.72rem;font-weight:700}
325
+ .pill-ok{background:#dcfce7;color:#15803d}
326
+ .pill-bad{background:#fee2e2;color:#b91c1c}
327
+ .pill-warn{background:#fef3c7;color:#92400e}
328
+ .range{display:flex;gap:6px;margin-bottom:12px;flex-wrap:wrap}
329
+ .range button{padding:4px 12px;border:1.5px solid #d1d5db;background:#fff;border-radius:20px;font-size:.78rem;cursor:pointer;color:#6b7280}
330
+ .range button.on{border-color:#003366;background:#003366;color:#fff;font-weight:700}
331
+ .msg{font-size:.82rem;color:#6b7280;padding:8px 0}
332
+ .err{font-size:.82rem;color:#b91c1c;padding:8px 0}
333
+ .mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.76rem}
334
+ </style></head><body>
335
+ <div class="topbar">
336
+ <h1>🐝 ResearchBee β€” Admin</h1>
337
+ <a href="/admin/logout">Sign out</a>
338
+ </div>
339
+ <div class="main">
340
+
341
+ <div class="card">
342
+ <h2>Tool usage</h2>
343
+ <div class="hint">How many times each tool was used. Counts only β€” ResearchBee never
344
+ stores what anyone typed, so there is no question log here by design.
345
+ Keep-alive traffic is excluded.</div>
346
+ <div class="range">
347
+ <button data-days="7">7 days</button>
348
+ <button data-days="30" class="on">30 days</button>
349
+ <button data-days="90">90 days</button>
350
+ <button data-days="0">All time</button>
351
+ </div>
352
+ <div id="usage"><div class="msg">Loading…</div></div>
353
+ </div>
354
+
355
+ <div class="card">
356
+ <h2>Questions we could not answer</h2>
357
+ <div class="hint">Requests that completed but found nothing to answer with β€” a subject
358
+ missing from the journal index, an article with no permissions record. Each one is a
359
+ candidate for improving a data source.</div>
360
+ <div id="gaps"><div class="msg">Loading…</div></div>
361
+ </div>
362
+
363
+ <div class="card">
364
+ <h2>Health checks</h2>
365
+ <div class="hint">Every six hours the Worker asks ResearchBee a real question, rotating
366
+ through the four tools. This keeps the Space awake and proves a different pipeline
367
+ still works each time.</div>
368
+ <div id="canary"><div class="msg">Loading…</div></div>
369
+ </div>
370
+
371
+ <div class="card">
372
+ <h2>Service status</h2>
373
+ <div class="hint">Data sources this Space is currently using, and its connection to the
374
+ analytics Worker.</div>
375
+ <div id="status"><div class="msg">Loading…</div></div>
376
+ <div style="margin-top:14px;display:flex;gap:8px;flex-wrap:wrap">
377
+ <button class="btn" id="reload-khazna">Reload the Khazna index</button>
378
+ <button class="btn btn-ghost" id="show-local">Show counts held in this container</button>
379
+ </div>
380
+ <div id="action-out"></div>
381
+ </div>
382
+
383
+ </div>
384
+ <script>
385
+ const SURFACE = """ + json.dumps(SURFACE_LABELS) + """;
386
+ const GAP = """ + json.dumps(GAP_LABELS) + """;
387
+ const esc = s => String(s??'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
388
+ const num = n => Number(n||0).toLocaleString();
389
+
390
+ async function get(path){
391
+ const r = await fetch(path);
392
+ if(r.status===401){window.location.href='/admin/login';throw new Error('unauthenticated');}
393
+ const d = await r.json().catch(()=>({}));
394
+ if(!r.ok) throw new Error(d.detail || ('HTTP '+r.status));
395
+ return d;
396
+ }
397
+
398
+ // ── Usage ──────────────────────────────────────────────────────
399
+ let days = 30;
400
+
401
+ async function loadUsage(){
402
+ const el = document.getElementById('usage');
403
+ const gapEl = document.getElementById('gaps');
404
+ el.innerHTML = '<div class="msg">Loading…</div>';
405
+ try {
406
+ const d = await get('/admin/usage?days='+days);
407
+ const t = d.totals || {};
408
+ const rows = (d.by_surface || []);
409
+ const max = Math.max(1, ...rows.map(r => r.total || 0));
410
+
411
+ el.innerHTML =
412
+ `<div class="stat-grid" style="margin-bottom:16px">
413
+ <div class="stat"><div class="val">${num(t.total)}</div><div class="lbl">Times used</div></div>
414
+ <div class="stat"><div class="val">${num(t.today)}</div><div class="lbl">Today</div></div>
415
+ <div class="stat"><div class="val">${num(t.miss)}</div><div class="lbl">Unanswered</div></div>
416
+ <div class="stat"><div class="val">${num(t.errors)}</div><div class="lbl">Errors</div></div>
417
+ </div>` +
418
+ (rows.length
419
+ ? `<table><thead><tr><th>Tool</th><th>Times used</th><th style="width:35%"></th><th>Unanswered</th><th>Errors</th></tr></thead><tbody>` +
420
+ rows.map(r => `<tr>
421
+ <td>${esc(SURFACE[r.surface] || r.surface)}</td>
422
+ <td><strong>${num(r.total)}</strong></td>
423
+ <td><div class="bar"><span style="width:${Math.round((r.total/max)*100)}%"></span></div></td>
424
+ <td>${num(r.miss)}</td>
425
+ <td>${num(r.errors)}</td>
426
+ </tr>`).join('') +
427
+ `</tbody></table>`
428
+ : `<div class="msg">Nothing recorded in this period yet. Use one of the tools, wait a minute for the next flush, then reload.</div>`);
429
+
430
+ const gaps = d.gaps || [];
431
+ gapEl.innerHTML = gaps.length
432
+ ? `<table><thead><tr><th>What was missing</th><th>Tool</th><th>Times</th></tr></thead><tbody>` +
433
+ gaps.map(g => `<tr>
434
+ <td>${esc(GAP[g.gap_code] || g.gap_code)}</td>
435
+ <td>${esc(SURFACE[g.surface] || g.surface)}</td>
436
+ <td><strong>${num(g.c)}</strong></td>
437
+ </tr>`).join('') + `</tbody></table>`
438
+ : `<div class="msg">Nothing flagged in this period.</div>`;
439
+
440
+ } catch(e) {
441
+ el.innerHTML = '<div class="err">Could not load usage: '+esc(e.message)+'</div>';
442
+ gapEl.innerHTML = '';
443
+ }
444
+ }
445
+
446
+ document.querySelectorAll('.range button').forEach(b => {
447
+ b.addEventListener('click', () => {
448
+ document.querySelectorAll('.range button').forEach(x => x.classList.remove('on'));
449
+ b.classList.add('on');
450
+ days = parseInt(b.dataset.days, 10);
451
+ loadUsage();
452
+ });
453
+ });
454
+
455
+ // ── Canary ─────────────────────────────────────────────────────
456
+ async function loadCanary(){
457
+ const el = document.getElementById('canary');
458
+ try {
459
+ const d = await get('/admin/canary-status');
460
+ const runs = d.runs || [];
461
+ el.innerHTML =
462
+ `<div class="msg" style="padding-top:0">${esc(d.summary||'')}</div>` +
463
+ (runs.length
464
+ ? `<table><thead><tr><th>When (UTC)</th><th>Tool checked</th><th>Result</th><th>Took</th><th>Detail</th></tr></thead><tbody>` +
465
+ runs.map(r => `<tr>
466
+ <td class="mono">${esc(r.run_at)}</td>
467
+ <td>${esc(r.slot||'')}</td>
468
+ <td><span class="pill ${r.ok?'pill-ok':'pill-bad'}">${r.ok?'Passed':'Failed'}</span></td>
469
+ <td>${r.latency_ms!=null?(r.latency_ms/1000).toFixed(1)+'s':''}</td>
470
+ <td class="mono">${esc(r.error || r.detail || '')}</td>
471
+ </tr>`).join('') + `</tbody></table>`
472
+ : '');
473
+ } catch(e) {
474
+ el.innerHTML = '<div class="err">Could not load health checks: '+esc(e.message)+'</div>';
475
+ }
476
+ }
477
+
478
+ // ── Status ─────────────────────────────────────────────────────
479
+ function yesNo(v){ return `<span class="pill ${v?'pill-ok':'pill-warn'}">${v?'Yes':'No'}</span>`; }
480
+
481
+ async function loadStatus(){
482
+ const el = document.getElementById('status');
483
+ try {
484
+ const d = await get('/admin/status');
485
+ const h = d.health || {};
486
+ const src = h.sources || {};
487
+ const k = src.khazna || {};
488
+ const hrs = Math.floor((d.uptime_seconds||0)/3600);
489
+ const mins = Math.floor(((d.uptime_seconds||0)%3600)/60);
490
+ el.innerHTML = `<table><tbody>
491
+ <tr><td>Version</td><td>${esc(h.version||'unknown')}</td></tr>
492
+ <tr><td>Running for</td><td>${hrs}h ${mins}m</td></tr>
493
+ <tr><td>Khazna index loaded</td><td>${yesNo(k.available)}${k.records?' &middot; '+num(k.records)+' records':''}</td></tr>
494
+ <tr><td>KU institution ID set for permissions</td><td>${yesNo(src.oaworks && src.oaworks.ku_ror_set)}</td></tr>
495
+ <tr><td>Repository registry</td><td>${num((src.repository_registry||{}).entries)} entries</td></tr>
496
+ <tr><td>Analytics Worker configured</td><td>${yesNo(d.worker_url_configured)}</td></tr>
497
+ <tr><td>Worker token configured</td><td>${yesNo(d.worker_token_configured)}</td></tr>
498
+ <tr><td>Language model key set</td><td>${yesNo(d.openai_key_set)}</td></tr>
499
+ </tbody></table>`;
500
+ } catch(e) {
501
+ el.innerHTML = '<div class="err">Could not load status: '+esc(e.message)+'</div>';
502
+ }
503
+ }
504
+
505
+ // ── Actions ────────────────────────────────────────────────────
506
+ document.getElementById('reload-khazna').addEventListener('click', async (ev) => {
507
+ const out = document.getElementById('action-out');
508
+ ev.target.disabled = true;
509
+ out.innerHTML = '<div class="msg">Reloading…</div>';
510
+ try {
511
+ const r = await fetch('/admin/reload-khazna', {method:'POST'});
512
+ const d = await r.json();
513
+ out.innerHTML = d.reloaded
514
+ ? `<div class="msg">Reloaded. ${num((d.khazna||{}).records)} records now in the index.</div>`
515
+ : `<div class="err">Reload failed. Check the Space logs for the line beginning "Khazna index download failed".</div>`;
516
+ loadStatus();
517
+ } catch(e) {
518
+ out.innerHTML = '<div class="err">Reload failed: '+esc(e.message)+'</div>';
519
+ }
520
+ ev.target.disabled = false;
521
+ });
522
+
523
+ document.getElementById('show-local').addEventListener('click', async () => {
524
+ const out = document.getElementById('action-out');
525
+ try {
526
+ const d = await get('/admin/local-usage');
527
+ const rows = Object.entries(d.by_surface||{});
528
+ out.innerHTML =
529
+ `<div class="msg">${esc(d.note)} Counting since ${esc(d.since)}. `+
530
+ `${d.pending_deltas} delta(s) waiting to be sent.</div>` +
531
+ (rows.length
532
+ ? `<table><thead><tr><th>Tool</th><th>Used</th><th>Unanswered</th><th>Errors</th></tr></thead><tbody>` +
533
+ rows.map(([k,v]) => `<tr><td>${esc(SURFACE[k]||k)}</td><td>${num(v.total)}</td><td>${num(v.miss)}</td><td>${num(v.error)}</td></tr>`).join('') +
534
+ `</tbody></table>`
535
+ : '<div class="msg">Nothing counted since this container started.</div>') +
536
+ ((d.recent_flushes||[]).length
537
+ ? `<div class="hint" style="margin-top:10px">Last send to the Worker: <span class="mono">${esc(d.recent_flushes[0].outcome)} β€” ${esc(d.recent_flushes[0].detail)}</span></div>`
538
+ : '');
539
+ } catch(e) {
540
+ out.innerHTML = '<div class="err">'+esc(e.message)+'</div>';
541
+ }
542
+ });
543
+
544
+ loadUsage(); loadCanary(); loadStatus();
545
+ </script></body></html>""")