Admin pages: one shared specification, builders, fragments, caps and live refresh
Adds admin_sections registry, shared admin partials, WorkspaceList, admin CLAUDE.md spec, capped node/flag listings, and api/unit tests enforcing the spec. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AdminSection:
|
||||
key: str
|
||||
label: str
|
||||
href: str
|
||||
icon: str
|
||||
|
||||
|
||||
ADMIN_SECTIONS: tuple[AdminSection, ...] = (
|
||||
AdminSection("users", "Users", "/admin/users", "\U0001f465"),
|
||||
AdminSection("news", "News", "/admin/news", "\U0001f4f0"),
|
||||
AdminSection("media", "Media", "/admin/media", "\U0001f5bc️"),
|
||||
AdminSection("moderation", "Moderation", "/admin/moderation", "\U0001f6a9"),
|
||||
AdminSection("trash", "Trash", "/admin/trash", "\U0001f5d1️"),
|
||||
AdminSection("services", "Services", "/admin/services", "⚙️"),
|
||||
AdminSection("gateway", "Gateway", "/admin/gateway", "\U0001f500"),
|
||||
AdminSection("containers", "Containers", "/admin/containers", "\U0001f4e6"),
|
||||
AdminSection("workspaces", "Workspaces", "/admin/workspaces", "\U0001f4bb"),
|
||||
AdminSection("devii-tasks", "Devii tasks", "/admin/devii-tasks", "⏰"),
|
||||
AdminSection("communities", "Communities", "/admin/communities", "\U0001f310"),
|
||||
AdminSection("nodes", "Community nodes", "/admin/nodes", "\U0001f4e1"),
|
||||
AdminSection("bots", "Bot Monitor", "/admin/bots", "\U0001f916"),
|
||||
AdminSection("game", "Code Farm", "/admin/game", "\U0001f69c"),
|
||||
AdminSection("ai-usage", "AI usage", "/admin/ai-usage", "\U0001f4ca"),
|
||||
AdminSection("statistics", "Statistics", "/admin/statistics", "\U0001f4c8"),
|
||||
AdminSection("audit-log", "Audit Log", "/admin/audit-log", "\U0001f4cb"),
|
||||
AdminSection("backups", "Backups", "/admin/backups", "\U0001f4be"),
|
||||
AdminSection("issues", "Ticket Planning", "/admin/issues/planning", "\U0001f5c2️"),
|
||||
AdminSection("notifications", "Notifications", "/admin/notifications", "\U0001f514"),
|
||||
AdminSection("settings", "Settings", "/admin/settings", "\U0001f527"),
|
||||
)
|
||||
|
||||
ADMIN_SECTION_KEYS: frozenset[str] = frozenset(section.key for section in ADMIN_SECTIONS)
|
||||
@@ -592,14 +592,23 @@ def raise_flag(kind: str, *, device_uid: str = "", user_uid: str = "", detail: s
|
||||
return table.find_one(uid=uid)
|
||||
|
||||
|
||||
def list_flags(status: str = FLAG_OPEN) -> list[dict]:
|
||||
def list_flags(status: str = FLAG_OPEN, limit: int | None = None) -> list[dict]:
|
||||
window = {} if limit is None else {"_limit": limit}
|
||||
return list(
|
||||
get_table("node_flags").find(
|
||||
status=status, deleted_at=None, order_by=["-created_at"]
|
||||
status=status, deleted_at=None, order_by=["-created_at"], **window
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def count_flags(status: str = FLAG_OPEN) -> int:
|
||||
return get_table("node_flags").count(status=status, deleted_at=None)
|
||||
|
||||
|
||||
def count_all_devices() -> int:
|
||||
return get_table("node_devices").count(deleted_at=None)
|
||||
|
||||
|
||||
def resolve_flag(flag_uid: str, actor_uid: str) -> bool:
|
||||
return (
|
||||
_execute(
|
||||
|
||||
+11
-2
@@ -19,7 +19,14 @@ def wants_json(request: Request) -> bool:
|
||||
return "application/json" in accept and "text/html" not in accept
|
||||
|
||||
|
||||
def respond(request: Request, template: str, context: dict, *, model: type[BaseModel]):
|
||||
def respond(
|
||||
request: Request,
|
||||
template: str,
|
||||
context: dict,
|
||||
*,
|
||||
model: type[BaseModel],
|
||||
status_code: int = 200,
|
||||
):
|
||||
if wants_json(request):
|
||||
try:
|
||||
payload = model.model_validate(context).model_dump(mode="json")
|
||||
@@ -29,7 +36,9 @@ def respond(request: Request, template: str, context: dict, *, model: type[BaseM
|
||||
return JSONResponse(payload)
|
||||
from devplacepy.templating import templates
|
||||
|
||||
return templates.TemplateResponse(request, template, context)
|
||||
return templates.TemplateResponse(
|
||||
request, template, context, status_code=status_code
|
||||
)
|
||||
|
||||
|
||||
def action_result(
|
||||
|
||||
@@ -179,6 +179,10 @@ All dates displayed to users use European DD/MM/YYYY format. Implemented via:
|
||||
- **`time_ago()`** returns `DD/MM/YYYY` for items older than 30 days (instead of `"Xmo ago"`)
|
||||
- Services page has a JS `formatDate()` function for live polling updates
|
||||
|
||||
### Admin page specification
|
||||
|
||||
Every admin route and template conforms to `devplacepy/routers/admin/CLAUDE.md` (A1-A11). Read it before adding or changing anything under `/admin`; it is enforced by `tests/unit/admin_spec.py`.
|
||||
|
||||
### Admin pagination
|
||||
|
||||
Both `/admin/users` and `/admin/news` use offset-based pagination via a reusable component:
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
# CLAUDE.md
|
||||
|
||||
The specification every `/admin` page follows. Claude Code loads it whenever a file under `routers/admin/` is touched; the root, `routers/`, `templates/`, `static/js/` and `static/css/` `CLAUDE.md` files point here. A page that breaks a rule below is a defect, not a style choice. `tests/unit/admin_spec.py` enforces the mechanical rules (A1, A2, A5, A6, A7, A9, A10) against the real templates and routers, so a violation fails the suite.
|
||||
|
||||
Code references: the section registry is `devplacepy/admin_sections.py`; the caps and floors are `ADMIN_LIST_CAP` and `ADMIN_POLL_FLOOR_SECONDS` in `routers/admin/_shared.py`; the cap note is `templates/_admin_cap_note.html`.
|
||||
|
||||
## A1. Backend rendered, always
|
||||
|
||||
A GET of an admin page returns the complete content in the HTML: every table, card, key figure, tab label and empty state is rendered by Jinja from data the handler computed. A placeholder such as "Loading..." in a template is forbidden. The page must be readable and correct with JavaScript off.
|
||||
|
||||
JavaScript only enhances: live refresh, charts drawn on a `<canvas>`, sorting, modals. The numbers and tables around a chart are server rendered; the chart is drawn from JSON embedded in the page.
|
||||
|
||||
The only permitted live-first surface is a page whose whole purpose is a live channel (WebSocket) such as the Bot Monitor and the container terminal, and even those render their initial frame on the server.
|
||||
|
||||
## A2. One handler, one builder, one model
|
||||
|
||||
- The HTML route calls `respond(request, "<template>.html", ctx, model=XOut)` with `base_seo_context(..., robots="noindex,nofollow")` and a breadcrumb trail `Home > Admin > <Page>`. Never `templates.TemplateResponse` directly: that drops the JSON face and the `*Out` schema.
|
||||
- The data the page shows is produced by ONE builder function. The HTML route and the refresh endpoint (`GET /admin/<page>/data`, `require_admin`, `JSONResponse`) both call it. The two must never compute the same figures twice with different code.
|
||||
- Context keys never collide with a Jinja global (root rule: `viewer_is_admin`, not `is_admin`).
|
||||
- Every admin page sets `"admin_section": "<key>"` where the key exists in `ADMIN_SECTIONS`.
|
||||
|
||||
## A3. Page anatomy
|
||||
|
||||
Every page extends `admin_base.html` and, in this order, renders:
|
||||
|
||||
1. `<div class="admin-toolbar">` holding the page title as `<h2>` (never `<h1>`; the layout owns the document heading), then `admin-count` spans, filters and the primary action.
|
||||
2. Optional `<nav class="admin-tabs" data-overflow-tabs>` for page tabs. A tab is a real link (`?tab=`), rendered on the server.
|
||||
3. The content: `admin-table-wrap > table.admin-table`, or cards, or a form `admin-settings-form`.
|
||||
4. The empty state: `<p class="admin-empty">`, never `empty-state`, never an empty table.
|
||||
5. Pagination via `_pagination.html` when the list is paged (A6).
|
||||
|
||||
Tables carry `<caption class="sr-only">`, every `<th>` has `scope="col"`, every icon-only or repeated row button has an `aria-label`. Page CSS goes in `{% block extra_head %}` after `{{ super() }}` (never re-link `admin.css` or `sidebar.css`; `admin_base.html` already loads them). No inline `<style>`, no `style=` attributes, no inline event handlers.
|
||||
|
||||
## A4. Class vocabulary
|
||||
|
||||
Buttons are `admin-btn` with `admin-btn-primary`, `admin-btn-danger`, `admin-btn-sm`. Fields are `admin-field`, selects `admin-select`, forms `admin-settings-form` or `admin-inline-form`, hints `admin-hint`. Status chips reuse the page family badge (`service-status`, `cm-badge`, `workspace-badge`). The public-site classes `btn`, `btn-primary`, `btn-danger`, `hint-text`, `empty-state`, `admin-header` are forbidden in admin templates. A missing admin class is added to `admin.css`, never worked around with a public class. Destructive buttons carry `data-confirm` (and `data-confirm-danger` for role/quota style changes).
|
||||
|
||||
## A5. Time
|
||||
|
||||
Every instant shown to a viewer is `local_dt(iso, mode)` or `dt_ago(iso)`; never `format_date`/`time_ago` for an instant (those stay for JSON and non-timestamp date fields). When client JS re-renders a row it emits the same `<time data-dt="...">` markup, and `LocalTime` localizes it through its MutationObserver; JS never formats an instant itself with `toLocaleString`/`toLocaleTimeString`.
|
||||
|
||||
## A6. Everything is capped
|
||||
|
||||
No list is unbounded.
|
||||
|
||||
- A list that can grow with users or content is paginated: `build_pagination(page, total)` plus `_limit/_offset` in the query and `_pagination.html`. Sorting is in SQL (`order_by`), never `rows.sort()` over the whole table.
|
||||
- A list that is naturally small (services, gateway providers) still reads with `_limit=ADMIN_LIST_CAP` and renders `_admin_cap_note.html` (`_shown`, `_total`) so truncation is visible, never silent.
|
||||
- Per-row work (queries, `await`s, service calls) is done for the visible page only, in batch (`get_users_by_uids` and friends), never per row of the whole table.
|
||||
- Query parameters that size a computation (`hours`, `top_n`, `limit`) are clamped on the server to a declared constant.
|
||||
|
||||
## A7. Heavy and remote work
|
||||
|
||||
A GET handler must not wait on a remote service. Gitea, providers and any network call go through a cache with a fixed TTL and a hard item cap; the handler renders the cached value at once and keeps the page's explicit error state (`*_error`) when the source is down. A computation costing more than one page of plain queries (statistics, usage analytics) is computed once per request: the HTML route embeds its result, and a tab or window change either navigates (server render) or fetches `/data`, never both.
|
||||
|
||||
## A8. Live refresh
|
||||
|
||||
- The shared `Poller` only: `new Poller(fn, ms, { pauseHidden: true, immediate: false })`. `immediate: false` because the first paint is already on the page (A1). Raw `setInterval` is forbidden.
|
||||
- Interval floor is `ADMIN_POLL_FLOOR_SECONDS` (15 s); a page that needs faster is a live channel.
|
||||
- Fetch through `Http.getJson`; never a bare `fetch`.
|
||||
- The refresh response is the `/data` JSON of A2, or, for a page made of server-rendered sections, HTML fetched with `Http.getHtml` (the page itself, or a `/fragment` route returning the same partial) and swapped into the `[data-live]` regions (Backups, Community pages, AI usage, Gateway stats). The markup then lives only in Jinja and the one builder feeds the page, the fragment and `/data`. The client re-renders only the regions that changed and preserves open modals, focus, scroll position and input values.
|
||||
- Initial data for charts is embedded as `<script type="application/json" id="<root>-initial">{{ initial | tojson }}</script>` and read synchronously; the client does not issue a second request to learn what the server already knew.
|
||||
|
||||
## A9. Assets
|
||||
|
||||
- One copy of each vendored library. Chart.js is `/static/vendor/chartjs/chart.umd.min.js`, loaded with `defer` through `static_url(...)` from `{% block extra_js %}` only on pages that draw charts.
|
||||
- Page JS is one ES6 module per class in `static/js/`, started from a three-line module block in `extra_js`. No page logic inline.
|
||||
|
||||
## A10. Navigation is one registry
|
||||
|
||||
The admin sections are declared once in `devplacepy/admin_sections.py` (`ADMIN_SECTIONS`, exposed as the `admin_sections` Jinja global). `admin_base.html` (desktop sidebar) and the admin block of `base.html` (the phone menu, because the sidebar is hidden at 1024 px and below) both loop over it. A new admin page adds one registry entry and nothing else; hand-writing a nav link in either template is forbidden. Every `admin_section` value passed by a route must exist in the registry.
|
||||
|
||||
## A11. Responsive
|
||||
|
||||
Everything works at 360 px. Tables sit in `admin-table-wrap` (horizontal scroll inside the wrap, never the page). A toolbar with more than three controls wraps; a button group of more than three becomes a `<select>` or a `dp-action-menu`. Touch targets are at least 44 px (`admin.css` already enforces it for `admin-btn`/`admin-select`).
|
||||
|
||||
## Checklist for a new or changed admin page
|
||||
|
||||
1. Registry entry in `ADMIN_SECTIONS`, `admin_section` matches.
|
||||
2. Builder function, `respond(... model=XOut)`, `/data` endpoint if it refreshes, audit event for every mutation.
|
||||
3. Template follows A3, A4, A5; no placeholder text; caps and pagination per A6.
|
||||
4. JS (only if needed) per A8 and A9.
|
||||
5. `tests/api/admin/...` asserts the first response already contains the data (not "Loading"), and `tests/unit/admin_spec.py` still passes.
|
||||
@@ -8,6 +8,10 @@ from devplacepy.responses import action_result
|
||||
from devplacepy.services.audit import record as audit
|
||||
|
||||
|
||||
ADMIN_LIST_CAP = 200
|
||||
ADMIN_POLL_FLOOR_SECONDS = 15
|
||||
|
||||
|
||||
def seniority_key(user: dict) -> tuple[str, int]:
|
||||
return (user.get("created_at") or "", user.get("id") or 0)
|
||||
|
||||
|
||||
@@ -8,16 +8,46 @@ from devplacepy.seo import base_seo_context, site_url, website_schema
|
||||
from devplacepy.responses import respond
|
||||
from devplacepy.schemas import GatewayUsageOut
|
||||
from devplacepy.services.manager import service_manager
|
||||
from devplacepy.services.openai_gateway.analytics import build_analytics
|
||||
from devplacepy.services.openai_gateway.analytics import MAX_WINDOW_HOURS, build_analytics
|
||||
from devplacepy.services.openai_gateway.usage import pricing_from_cfg
|
||||
from devplacepy.templating import templates
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
|
||||
DEFAULT_WINDOW_HOURS = 48
|
||||
MAX_TOP_N = 50
|
||||
WINDOW_CHOICES = (
|
||||
(1, "1 hour"),
|
||||
(24, "24 hours"),
|
||||
(48, "48 hours"),
|
||||
(168, "7 days"),
|
||||
(0, "All time"),
|
||||
)
|
||||
|
||||
|
||||
def _clamp_hours(hours: int) -> int:
|
||||
if hours <= 0:
|
||||
return 0
|
||||
return min(hours, MAX_WINDOW_HOURS)
|
||||
|
||||
|
||||
def _clamp_top_n(top_n: int) -> int:
|
||||
return max(1, min(top_n, MAX_TOP_N))
|
||||
|
||||
|
||||
def build_usage(hours: int, top_n: int) -> dict:
|
||||
service = service_manager.get_service("openai")
|
||||
pricing = pricing_from_cfg(service.get_config()) if service is not None else None
|
||||
return build_analytics(_clamp_hours(hours), top_n=_clamp_top_n(top_n), pricing=pricing)
|
||||
|
||||
|
||||
@router.get("/ai-usage", response_class=HTMLResponse)
|
||||
async def admin_ai_usage(request: Request):
|
||||
async def admin_ai_usage(
|
||||
request: Request, hours: int = DEFAULT_WINDOW_HOURS, top_n: int = 10
|
||||
):
|
||||
admin = require_admin(request)
|
||||
usage = build_usage(hours, top_n)
|
||||
base = site_url(request)
|
||||
seo_ctx = base_seo_context(
|
||||
request,
|
||||
@@ -39,14 +69,28 @@ async def admin_ai_usage(request: Request):
|
||||
"request": request,
|
||||
"user": admin,
|
||||
"admin_section": "ai-usage",
|
||||
"usage": usage,
|
||||
"window_choices": WINDOW_CHOICES,
|
||||
"window_hours": usage["window_hours"],
|
||||
**usage,
|
||||
},
|
||||
model=GatewayUsageOut,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/ai-usage/data")
|
||||
async def admin_ai_usage_json(request: Request, hours: int = 48, top_n: int = 10):
|
||||
async def admin_ai_usage_json(
|
||||
request: Request, hours: int = DEFAULT_WINDOW_HOURS, top_n: int = 10
|
||||
):
|
||||
require_admin(request)
|
||||
service = service_manager.get_service("openai")
|
||||
pricing = pricing_from_cfg(service.get_config()) if service is not None else None
|
||||
return JSONResponse(build_analytics(hours, top_n=top_n, pricing=pricing))
|
||||
return JSONResponse(build_usage(hours, top_n))
|
||||
|
||||
|
||||
@router.get("/ai-usage/fragment", response_class=HTMLResponse)
|
||||
async def admin_ai_usage_fragment(
|
||||
request: Request, hours: int = DEFAULT_WINDOW_HOURS, top_n: int = 10
|
||||
):
|
||||
require_admin(request)
|
||||
usage = build_usage(hours, top_n)
|
||||
html = templates.get_template("_ai_usage_report.html").render(usage=usage)
|
||||
return HTMLResponse(html)
|
||||
|
||||
@@ -20,6 +20,8 @@ from devplacepy.services.jobs import queue
|
||||
from devplacepy.utils import is_primary_admin, not_found, require_admin
|
||||
from fastapi import Depends, HTTPException
|
||||
from devplacepy.dependencies import json_or_form
|
||||
from devplacepy.database import db, get_table
|
||||
from devplacepy.routers.admin._shared import ADMIN_LIST_CAP
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
@@ -63,12 +65,16 @@ def _targets() -> list[dict]:
|
||||
]
|
||||
|
||||
async def _dashboard(can_download: bool) -> dict:
|
||||
backups = [_backup_payload(row, can_download) for row in store.list_backups()]
|
||||
backups = [
|
||||
_backup_payload(row, can_download)
|
||||
for row in store.list_backups(limit=ADMIN_LIST_CAP)
|
||||
]
|
||||
schedules = store.list_schedules()
|
||||
storage = await asyncio.to_thread(store.compute_storage_stats)
|
||||
return {
|
||||
"storage": storage,
|
||||
"backups": backups,
|
||||
"backups_total": get_table("backups").count() if "backups" in db.tables else 0,
|
||||
"schedules": schedules,
|
||||
"targets": _targets(),
|
||||
"metrics": _metrics(backups),
|
||||
|
||||
@@ -10,7 +10,7 @@ from urllib.parse import urlencode
|
||||
from fastapi import APIRouter, Form, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
|
||||
from devplacepy.database import get_setting, get_table, get_users_by_uids, resolve_object_url
|
||||
from devplacepy.database import build_pagination, get_setting, get_table, get_users_by_uids, resolve_object_url
|
||||
from devplacepy.database.sync import count_links, identity_map
|
||||
from devplacepy.responses import action_result, json_error, respond
|
||||
from devplacepy.schemas import AdminCommunitiesOut, AdminCommunityLedgerOut, AdminCommunityOut, AdminCommunitySchemaOut
|
||||
@@ -174,8 +174,10 @@ def feed_summary(feed: dict) -> dict:
|
||||
|
||||
|
||||
@router.get("/communities", response_class=HTMLResponse)
|
||||
async def admin_communities(request: Request):
|
||||
async def admin_communities(request: Request, page: int = 1):
|
||||
admin = require_admin(request)
|
||||
pagination = build_pagination(page, store.count())
|
||||
offset = (pagination["page"] - 1) * pagination["per_page"]
|
||||
return respond(
|
||||
request,
|
||||
"admin_communities.html",
|
||||
@@ -183,7 +185,8 @@ async def admin_communities(request: Request):
|
||||
**seo(request, "Communities", LIST_URL, "Communities"),
|
||||
"request": request,
|
||||
"user": admin,
|
||||
"items": [public(row) for row in store.list()],
|
||||
"items": [public(row) for row in store.list(pagination["per_page"], offset)],
|
||||
"pagination": pagination,
|
||||
"sync_enabled": sync_enabled(),
|
||||
**service_flags(),
|
||||
"admin_section": "communities",
|
||||
|
||||
@@ -6,6 +6,7 @@ from fastapi import Depends, APIRouter, Request
|
||||
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
|
||||
|
||||
from devplacepy.database import (
|
||||
build_pagination,
|
||||
db,
|
||||
get_table,
|
||||
get_users_by_uids,
|
||||
@@ -111,10 +112,20 @@ def _audit_admin(request: Request, admin: dict, event_key: str, inst: dict, summ
|
||||
result=result,
|
||||
)
|
||||
|
||||
def _containers_payload(admin: dict, page: int) -> dict:
|
||||
visible = _decorate(store.all_instances(), admin)
|
||||
pagination = build_pagination(page, len(visible))
|
||||
start = (pagination["page"] - 1) * pagination["per_page"]
|
||||
return {
|
||||
"instances": visible[start : start + pagination["per_page"]],
|
||||
"pagination": pagination,
|
||||
}
|
||||
|
||||
|
||||
@router.get("", response_class=HTMLResponse)
|
||||
async def containers_index(request: Request):
|
||||
async def containers_index(request: Request, page: int = 1):
|
||||
admin = require_admin(request)
|
||||
instances = _decorate(store.all_instances(), admin)
|
||||
payload = _containers_payload(admin, page)
|
||||
base = site_url(request)
|
||||
seo_ctx = base_seo_context(
|
||||
request,
|
||||
@@ -136,7 +147,7 @@ async def containers_index(request: Request):
|
||||
**seo_ctx,
|
||||
"request": request,
|
||||
"user": admin,
|
||||
"instances": instances,
|
||||
**payload,
|
||||
"boot_languages": BOOT_LANGUAGES,
|
||||
"restart_policies": RESTART_POLICIES,
|
||||
"admin_section": "containers",
|
||||
@@ -145,9 +156,9 @@ async def containers_index(request: Request):
|
||||
)
|
||||
|
||||
@router.get("/data")
|
||||
async def containers_index_json(request: Request):
|
||||
async def containers_index_json(request: Request, page: int = 1):
|
||||
admin = require_admin(request)
|
||||
return JSONResponse({"instances": _decorate(store.all_instances(), admin)})
|
||||
return JSONResponse(_containers_payload(admin, page))
|
||||
|
||||
@router.get("/projects/search")
|
||||
async def project_search(request: Request, q: str = ""):
|
||||
|
||||
@@ -5,7 +5,13 @@ import logging
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
|
||||
from devplacepy.database import db, get_admin_uids, get_int_setting, get_users_by_uids
|
||||
from devplacepy.database import (
|
||||
build_pagination,
|
||||
db,
|
||||
get_admin_uids,
|
||||
get_int_setting,
|
||||
get_users_by_uids,
|
||||
)
|
||||
from devplacepy.responses import action_result, respond
|
||||
from devplacepy.schemas import AdminDeviiTasksOut
|
||||
from devplacepy.seo import base_seo_context, site_url, website_schema
|
||||
@@ -32,17 +38,26 @@ def _schedule_text(row: dict) -> str:
|
||||
return f"once {row.get('run_at') or ''}".strip()
|
||||
|
||||
|
||||
def _rows(state: str) -> list[dict]:
|
||||
def _page(state: str, page: int) -> tuple[list[dict], dict]:
|
||||
if TABLE not in db.tables:
|
||||
return []
|
||||
return [], build_pagination(page, 0)
|
||||
criteria: dict = {"deleted_at": None}
|
||||
if state == "active":
|
||||
criteria["enabled"] = True
|
||||
elif state == "inactive":
|
||||
criteria["enabled"] = False
|
||||
rows = list(db[TABLE].find(**criteria))
|
||||
rows.sort(key=lambda row: int(row.get("run_count") or 0), reverse=True)
|
||||
return rows
|
||||
table = db[TABLE]
|
||||
pagination = build_pagination(page, table.count(**criteria))
|
||||
offset = (pagination["page"] - 1) * pagination["per_page"]
|
||||
rows = list(
|
||||
table.find(
|
||||
order_by=["-run_count", "-created_at"],
|
||||
_limit=pagination["per_page"],
|
||||
_offset=offset,
|
||||
**criteria,
|
||||
)
|
||||
)
|
||||
return rows, pagination
|
||||
|
||||
|
||||
def _quotas(owner_uids: set[str]) -> dict[str, dict]:
|
||||
@@ -98,11 +113,11 @@ def _require_task(uid: str) -> dict:
|
||||
|
||||
|
||||
@router.get("/devii-tasks", response_class=HTMLResponse)
|
||||
async def admin_devii_tasks(request: Request, state: str = "active"):
|
||||
async def admin_devii_tasks(request: Request, state: str = "active", page: int = 1):
|
||||
admin = require_admin(request)
|
||||
if state not in STATES:
|
||||
state = "active"
|
||||
rows = _rows(state)
|
||||
rows, pagination = _page(state, page)
|
||||
items = _items(rows)
|
||||
bounds = {
|
||||
"max_concurrent": get_int_setting(
|
||||
@@ -149,6 +164,7 @@ async def admin_devii_tasks(request: Request, state: str = "active"):
|
||||
"request": request,
|
||||
"user": admin,
|
||||
"items": items,
|
||||
"pagination": pagination,
|
||||
"state": state,
|
||||
"tabs": tabs,
|
||||
"limits": bounds,
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi import APIRouter, Query, Request
|
||||
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
|
||||
from pydantic import ValidationError
|
||||
|
||||
@@ -16,6 +17,7 @@ from devplacepy.schemas import (
|
||||
AdminGatewayQuotaFormOut,
|
||||
)
|
||||
from devplacepy.seo import base_seo_context, site_url, website_schema
|
||||
from devplacepy.routers.admin._shared import ADMIN_LIST_CAP
|
||||
from devplacepy.services.audit import record as audit
|
||||
from devplacepy.services.manager import service_manager
|
||||
from devplacepy.services.openai_gateway import (
|
||||
@@ -38,6 +40,7 @@ router = APIRouter()
|
||||
|
||||
INDEX_URL = "/admin/gateway"
|
||||
TABS = ("models", "providers", "quota", "stats")
|
||||
DEFAULT_STATS_RANGE = "24h"
|
||||
|
||||
|
||||
def _default_provider_summary() -> dict:
|
||||
@@ -149,16 +152,17 @@ def _error_response(
|
||||
):
|
||||
if wants_json(request):
|
||||
return json_error(status_code, message)
|
||||
return templates.TemplateResponse(
|
||||
return respond(
|
||||
request,
|
||||
template,
|
||||
{**context, "request": request, "error": message},
|
||||
model=AdminGatewayOut,
|
||||
status_code=status_code,
|
||||
)
|
||||
|
||||
|
||||
def _models_with_learned() -> list[dict]:
|
||||
models = routing.model_store.list()
|
||||
def _models_with_learned(limit: int = ADMIN_LIST_CAP) -> list[dict]:
|
||||
models = routing.model_store.list()[:limit]
|
||||
for model in models:
|
||||
method = learned_store.get(
|
||||
model["provider"] or DEFAULT_PROVIDER, model["target_model"]
|
||||
@@ -192,18 +196,25 @@ def _reset_learned(request: Request, admin: dict, payload: LearnedResetIn) -> bo
|
||||
|
||||
@router.get("/gateway", response_class=HTMLResponse)
|
||||
async def gateway_config_page(
|
||||
request: Request, tab: str = "models", tested: str = "", test_image: str = ""
|
||||
request: Request,
|
||||
tab: str = "models",
|
||||
tested: str = "",
|
||||
test_image: str = "",
|
||||
stats_range: str = Query(DEFAULT_STATS_RANGE, alias="range"),
|
||||
):
|
||||
admin = require_admin(request)
|
||||
if tab not in TABS:
|
||||
tab = "models"
|
||||
if not test_image.startswith("http"):
|
||||
test_image = ""
|
||||
quota_rules = quota.quota_rule_store.list()
|
||||
all_quota_rules = quota.quota_rule_store.list()
|
||||
quota_rules = all_quota_rules[:ADMIN_LIST_CAP]
|
||||
for rule in quota_rules:
|
||||
rule["spent_24h_usd"] = round(
|
||||
quota.spent_24h(rule["owner_kind"], rule["owner_id"], rule["app_reference"]), 6
|
||||
)
|
||||
all_providers = routing.provider_store.list()
|
||||
stats_context = _stats_context(stats_range) if tab == "stats" else {}
|
||||
return respond(
|
||||
request,
|
||||
"admin_gateway.html",
|
||||
@@ -212,9 +223,13 @@ async def gateway_config_page(
|
||||
"user": admin,
|
||||
"admin_section": "gateway",
|
||||
"tab": tab,
|
||||
"providers": routing.provider_store.list(),
|
||||
"providers": all_providers[:ADMIN_LIST_CAP],
|
||||
"providers_total": len(all_providers),
|
||||
"models": _models_with_learned(),
|
||||
"models_total": routing.model_store.count(),
|
||||
"quota_rules": quota_rules,
|
||||
"quota_rules_total": len(all_quota_rules),
|
||||
**stats_context,
|
||||
"default_provider": _default_provider_summary(),
|
||||
"quota_defaults": _quota_defaults_summary(),
|
||||
"stats_ranges": list(model_stats_query.RANGE_SECONDS.keys()),
|
||||
@@ -1111,8 +1126,28 @@ async def reset_quota_rule_page(request: Request, uid: str):
|
||||
# --- Stats: JSON API for the Stats tab's charts ------------------------------
|
||||
|
||||
|
||||
def _stats_context(range_key: str) -> dict:
|
||||
if range_key not in model_stats_query.RANGE_SECONDS:
|
||||
range_key = DEFAULT_STATS_RANGE
|
||||
summary = model_stats_query.compute_summary(range_key)
|
||||
return _stats_view(summary, range_key)
|
||||
|
||||
|
||||
def _stats_view(summary: dict, range_key: str) -> dict:
|
||||
per_model = summary["per_model"]
|
||||
generated = datetime.fromtimestamp(summary["generated_at"], tz=timezone.utc)
|
||||
return {
|
||||
"stats": summary,
|
||||
"stats_range": range_key,
|
||||
"stats_generated_iso": generated.isoformat(),
|
||||
"stats_models": model_stats_query.list_known_models()[:ADMIN_LIST_CAP],
|
||||
"stats_table_models": per_model[:ADMIN_LIST_CAP],
|
||||
"stats_table_models_total": len(per_model),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/gateway/stats/data")
|
||||
async def gateway_stats_data(request: Request, range: str = "24h"):
|
||||
async def gateway_stats_data(request: Request, range: str = DEFAULT_STATS_RANGE):
|
||||
require_admin(request)
|
||||
try:
|
||||
return JSONResponse(model_stats_query.compute_summary(range))
|
||||
@@ -1120,6 +1155,17 @@ async def gateway_stats_data(request: Request, range: str = "24h"):
|
||||
return json_error(400, f"Unknown range: {range!r}")
|
||||
|
||||
|
||||
@router.get("/gateway/stats/fragment", response_class=HTMLResponse)
|
||||
async def gateway_stats_fragment(request: Request, range: str = DEFAULT_STATS_RANGE):
|
||||
require_admin(request)
|
||||
if range not in model_stats_query.RANGE_SECONDS:
|
||||
return json_error(400, f"Unknown range: {range!r}")
|
||||
context = _stats_context(range)
|
||||
return HTMLResponse(
|
||||
templates.get_template("_gateway_stats_fragment.html").render(**context)
|
||||
)
|
||||
|
||||
|
||||
@router.get("/gateway/stats/models")
|
||||
async def gateway_stats_models(request: Request):
|
||||
require_admin(request)
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
|
||||
from devplacepy.cache import TTLCache
|
||||
from devplacepy.responses import respond
|
||||
from devplacepy.schemas import AdminIssuesPlanningOut
|
||||
from devplacepy.seo import base_seo_context
|
||||
@@ -16,10 +18,20 @@ from devplacepy.utils import require_admin
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
|
||||
TICKETS_CACHE_SECONDS = 60
|
||||
TICKETS_CACHE_KEY = "open"
|
||||
TICKETS_FETCH_TIMEOUT_SECONDS = 8
|
||||
_tickets_cache = TTLCache(TICKETS_CACHE_SECONDS, max_size=1)
|
||||
|
||||
|
||||
async def _open_tickets() -> tuple[list[dict], bool]:
|
||||
cached = _tickets_cache.get(TICKETS_CACHE_KEY)
|
||||
if cached is not None:
|
||||
return cached, False
|
||||
try:
|
||||
issues = await collect_open_issues(runtime.get_client())
|
||||
issues = await asyncio.wait_for(
|
||||
collect_open_issues(runtime.get_client()), TICKETS_FETCH_TIMEOUT_SECONDS
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning("Could not load open tickets for planning: %s", exc)
|
||||
return [], True
|
||||
@@ -35,6 +47,7 @@ async def _open_tickets() -> tuple[list[dict], bool]:
|
||||
}
|
||||
for issue in issues
|
||||
]
|
||||
_tickets_cache.set(TICKETS_CACHE_KEY, tickets)
|
||||
return tickets, False
|
||||
|
||||
|
||||
@@ -49,7 +62,7 @@ async def admin_issues_planning(request: Request):
|
||||
breadcrumbs=[
|
||||
{"name": "Home", "url": "/feed"},
|
||||
{"name": "Admin", "url": "/admin"},
|
||||
{"name": "Issues", "url": "/issues"},
|
||||
{"name": "Ticket Planning", "url": "/admin/issues/planning"},
|
||||
],
|
||||
)
|
||||
configured = gitea_config().is_configured
|
||||
|
||||
@@ -15,6 +15,8 @@ from devplacepy.database.nodes import (
|
||||
DEVICE_BREAKDOWN_COLUMNS,
|
||||
LIMITS,
|
||||
add_event,
|
||||
count_all_devices,
|
||||
count_flags,
|
||||
count_open_requests,
|
||||
device_breakdown,
|
||||
cache_stats,
|
||||
@@ -234,7 +236,7 @@ def overview() -> dict:
|
||||
lifetime = lifetime_counters()
|
||||
outcomes = {name: value for name, value in lifetime.items() if name.startswith(OUTCOME_PREFIX)}
|
||||
devices = recent_devices(ADMIN_LIST_LIMIT)
|
||||
flags = list_flags()[:ADMIN_LIST_LIMIT]
|
||||
flags = list_flags(limit=ADMIN_LIST_LIMIT)
|
||||
device_by_uid = {row["uid"]: row for row in devices}
|
||||
missing = [row["device_uid"] for row in flags if row.get("device_uid") and row["device_uid"] not in device_by_uid]
|
||||
for uid in missing:
|
||||
@@ -251,7 +253,9 @@ def overview() -> dict:
|
||||
**breakdowns,
|
||||
"usage_today": usage_day_totals(),
|
||||
"flags": flag_views(flags, owners, device_by_uid),
|
||||
"flags_total": count_flags(),
|
||||
"devices": device_views(devices, owners),
|
||||
"devices_total": count_all_devices(),
|
||||
"settings": settings_view(),
|
||||
"limits": LIMITS.describe(),
|
||||
"circuits": circuit_views(),
|
||||
|
||||
@@ -4,7 +4,9 @@ import logging
|
||||
from typing import Any
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import HTMLResponse, JSONResponse
|
||||
from devplacepy.templating import templates
|
||||
from devplacepy.responses import respond
|
||||
from devplacepy.routers.admin._shared import ADMIN_LIST_CAP
|
||||
from devplacepy.schemas import ServiceDetailOut, ServicesOut
|
||||
from devplacepy.utils import require_admin, not_found
|
||||
from devplacepy.services.manager import service_manager
|
||||
from devplacepy.seo import base_seo_context, site_url, website_schema
|
||||
@@ -15,10 +17,24 @@ logger = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _services_payload() -> dict:
|
||||
services = service_manager.describe_all()
|
||||
return {
|
||||
"services": services[:ADMIN_LIST_CAP],
|
||||
"services_total": len(services),
|
||||
}
|
||||
|
||||
|
||||
def _service_payload(name: str) -> dict | None:
|
||||
svc = service_manager.get_service(name)
|
||||
if svc is None:
|
||||
return None
|
||||
return {"service": svc.describe()}
|
||||
|
||||
|
||||
@router.get("", response_class=HTMLResponse)
|
||||
async def services_page(request: Request):
|
||||
admin = require_admin(request)
|
||||
services = service_manager.describe_all()
|
||||
base = site_url(request)
|
||||
seo_ctx = base_seo_context(
|
||||
request,
|
||||
@@ -32,32 +48,33 @@ async def services_page(request: Request):
|
||||
],
|
||||
schemas=[website_schema(base)],
|
||||
)
|
||||
return templates.TemplateResponse(
|
||||
return respond(
|
||||
request,
|
||||
"services.html",
|
||||
{
|
||||
**seo_ctx,
|
||||
"request": request,
|
||||
"user": admin,
|
||||
"services": services,
|
||||
**_services_payload(),
|
||||
"admin_section": "services",
|
||||
},
|
||||
model=ServicesOut,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/data")
|
||||
async def services_json(request: Request):
|
||||
require_admin(request)
|
||||
return JSONResponse({"services": service_manager.describe_all()})
|
||||
return JSONResponse({"services": _services_payload()["services"]})
|
||||
|
||||
|
||||
@router.get("/{name}", response_class=HTMLResponse)
|
||||
async def service_detail(request: Request, name: str):
|
||||
admin = require_admin(request)
|
||||
svc = service_manager.get_service(name)
|
||||
if svc is None:
|
||||
payload = _service_payload(name)
|
||||
if payload is None:
|
||||
raise not_found("Service not found")
|
||||
info = svc.describe()
|
||||
info = payload["service"]
|
||||
base = site_url(request)
|
||||
seo_ctx = base_seo_context(
|
||||
request,
|
||||
@@ -73,27 +90,28 @@ async def service_detail(request: Request, name: str):
|
||||
schemas=[website_schema(base)],
|
||||
)
|
||||
tool_groups = tool_prefs.group_overview() if name == "devii" else None
|
||||
return templates.TemplateResponse(
|
||||
return respond(
|
||||
request,
|
||||
"service_detail.html",
|
||||
{
|
||||
**seo_ctx,
|
||||
"request": request,
|
||||
"user": admin,
|
||||
"service": info,
|
||||
**payload,
|
||||
"tool_groups": tool_groups,
|
||||
"admin_section": "services",
|
||||
},
|
||||
model=ServiceDetailOut,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{name}/data")
|
||||
async def service_detail_json(request: Request, name: str):
|
||||
require_admin(request)
|
||||
svc = service_manager.get_service(name)
|
||||
if svc is None:
|
||||
payload = _service_payload(name)
|
||||
if payload is None:
|
||||
return JSONResponse({"error": "unknown service"}, status_code=404)
|
||||
return JSONResponse({"service": svc.describe()})
|
||||
return JSONResponse(payload)
|
||||
|
||||
|
||||
def _audit_service(request: Request, admin: dict, name: str, event_key: str, summary: str, **kwargs: Any) -> None:
|
||||
|
||||
@@ -7,7 +7,7 @@ from devplacepy.responses import respond
|
||||
from devplacepy.schemas.statistics import StatisticsOut
|
||||
from devplacepy.seo import base_seo_context, site_url, website_schema
|
||||
from devplacepy.services.statistics.build import build_statistics_tab
|
||||
from devplacepy.services.statistics.common import VALID_TABS
|
||||
from devplacepy.services.statistics.common import MAX_WINDOW_HOURS, VALID_TABS
|
||||
from devplacepy.utils import require_admin
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -32,10 +32,45 @@ TAB_LABELS = (
|
||||
)
|
||||
|
||||
|
||||
@router.get("/statistics", response_class=HTMLResponse)
|
||||
async def admin_statistics(request: Request, tab: str = "overview", hours: int = 168):
|
||||
admin = require_admin(request)
|
||||
STATISTICS_DEFAULT_HOURS = 168
|
||||
STATISTICS_DEFAULT_TOP_N = 10
|
||||
STATISTICS_MAX_TOP_N = 50
|
||||
STATISTICS_WINDOWS = (
|
||||
(24, "Last 24 hours"),
|
||||
(168, "Last 7 days"),
|
||||
(720, "Last 30 days"),
|
||||
(2160, "Last 90 days"),
|
||||
(0, "All time"),
|
||||
)
|
||||
|
||||
|
||||
def clamp_hours(hours: int) -> int:
|
||||
if hours <= 0:
|
||||
return 0
|
||||
return min(hours, MAX_WINDOW_HOURS)
|
||||
|
||||
|
||||
def statistics_view(tab: str, hours: int, compare: int, top_n: int) -> dict:
|
||||
active = tab if tab in VALID_TABS else "overview"
|
||||
bounded_top = max(1, min(top_n, STATISTICS_MAX_TOP_N))
|
||||
return build_statistics_tab(
|
||||
active,
|
||||
clamp_hours(hours),
|
||||
compare=bool(compare),
|
||||
top_n=bounded_top,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/statistics", response_class=HTMLResponse)
|
||||
async def admin_statistics(
|
||||
request: Request,
|
||||
tab: str = "overview",
|
||||
hours: int = STATISTICS_DEFAULT_HOURS,
|
||||
compare: int = 1,
|
||||
):
|
||||
admin = require_admin(request)
|
||||
initial = statistics_view(tab, hours, compare, STATISTICS_DEFAULT_TOP_N)
|
||||
active = initial["tab"]
|
||||
base = site_url(request)
|
||||
seo_ctx = base_seo_context(
|
||||
request,
|
||||
@@ -49,7 +84,6 @@ async def admin_statistics(request: Request, tab: str = "overview", hours: int =
|
||||
],
|
||||
schemas=[website_schema(base)],
|
||||
)
|
||||
initial = build_statistics_tab(active, hours, compare=True, top_n=10)
|
||||
tabs = [
|
||||
{"key": key, "label": label, "icon": icon, "active": key == active}
|
||||
for key, label, icon in TAB_LABELS
|
||||
@@ -64,7 +98,9 @@ async def admin_statistics(request: Request, tab: str = "overview", hours: int =
|
||||
"admin_section": "statistics",
|
||||
"tabs": tabs,
|
||||
"active_tab": active,
|
||||
"window_hours": hours,
|
||||
"window_hours": initial["window_hours"],
|
||||
"compare": initial["compare"],
|
||||
"windows": STATISTICS_WINDOWS,
|
||||
"initial": initial,
|
||||
},
|
||||
model=StatisticsOut,
|
||||
@@ -75,16 +111,9 @@ async def admin_statistics(request: Request, tab: str = "overview", hours: int =
|
||||
async def admin_statistics_data(
|
||||
request: Request,
|
||||
tab: str = "overview",
|
||||
hours: int = 168,
|
||||
hours: int = STATISTICS_DEFAULT_HOURS,
|
||||
compare: int = 1,
|
||||
top_n: int = 10,
|
||||
top_n: int = STATISTICS_DEFAULT_TOP_N,
|
||||
):
|
||||
require_admin(request)
|
||||
return JSONResponse(
|
||||
build_statistics_tab(
|
||||
tab,
|
||||
hours,
|
||||
compare=bool(compare),
|
||||
top_n=top_n,
|
||||
)
|
||||
)
|
||||
return JSONResponse(statistics_view(tab, hours, compare, top_n))
|
||||
|
||||
@@ -6,7 +6,12 @@ from typing import Annotated
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from devplacepy.database import get_projects_by_uids, get_table, get_users_by_uids
|
||||
from devplacepy.database import (
|
||||
build_pagination,
|
||||
get_projects_by_uids,
|
||||
get_table,
|
||||
get_users_by_uids,
|
||||
)
|
||||
from devplacepy.dependencies import json_or_form
|
||||
from devplacepy.models import (
|
||||
EditorPrefsForm,
|
||||
@@ -15,7 +20,7 @@ from devplacepy.models import (
|
||||
WorkspaceSuspendForm,
|
||||
)
|
||||
from devplacepy.responses import action_result, json_error, respond
|
||||
from devplacepy.routers.admin._shared import deny_senior, is_senior_admin
|
||||
from devplacepy.routers.admin._shared import ADMIN_LIST_CAP, deny_senior, is_senior_admin
|
||||
from devplacepy.schemas import AdminWorkspacesOut
|
||||
from devplacepy.seo import base_seo_context
|
||||
from devplacepy.services.audit import record as audit
|
||||
@@ -49,8 +54,32 @@ async def _decorate(rows: list[dict]) -> list[dict]:
|
||||
return decorated
|
||||
|
||||
|
||||
def _all_workspaces() -> list[dict]:
|
||||
return list(get_table("instances").find(is_workspace=1, deleted_at=None))
|
||||
def _workspace_page(page: int) -> tuple[list[dict], dict]:
|
||||
table = get_table("instances")
|
||||
total = table.count(is_workspace=1, deleted_at=None)
|
||||
pagination = build_pagination(page, total)
|
||||
offset = (pagination["page"] - 1) * pagination["per_page"]
|
||||
rows = list(
|
||||
table.find(
|
||||
is_workspace=1,
|
||||
deleted_at=None,
|
||||
order_by=["-created_at"],
|
||||
_limit=pagination["per_page"],
|
||||
_offset=offset,
|
||||
)
|
||||
)
|
||||
return rows, pagination
|
||||
|
||||
|
||||
async def _workspaces_payload(page: int) -> dict:
|
||||
rows, pagination = _workspace_page(page)
|
||||
open_flags = flags.list_flags()
|
||||
return {
|
||||
"workspaces": await _decorate(rows),
|
||||
"flags": open_flags[:ADMIN_LIST_CAP],
|
||||
"flags_total": len(open_flags),
|
||||
"pagination": pagination,
|
||||
}
|
||||
|
||||
|
||||
def _instance_or_404(uid: str) -> dict:
|
||||
@@ -75,13 +104,12 @@ def _audit(request: Request, admin: dict, event_key: str, instance: dict, **extr
|
||||
|
||||
|
||||
@router.get("/workspaces")
|
||||
async def admin_workspaces(request: Request):
|
||||
async def admin_workspaces(request: Request, page: int = 1):
|
||||
admin = require_admin(request)
|
||||
if not isinstance(admin, dict):
|
||||
return admin
|
||||
context = {
|
||||
"workspaces": await _decorate(_all_workspaces()),
|
||||
"flags": flags.list_flags(),
|
||||
**await _workspaces_payload(page),
|
||||
"admin_section": "workspaces",
|
||||
"user": admin,
|
||||
**base_seo_context(
|
||||
@@ -100,13 +128,11 @@ async def admin_workspaces(request: Request):
|
||||
|
||||
|
||||
@router.get("/workspaces/data")
|
||||
async def admin_workspaces_data(request: Request):
|
||||
async def admin_workspaces_data(request: Request, page: int = 1):
|
||||
admin = require_admin(request)
|
||||
if not isinstance(admin, dict):
|
||||
return admin
|
||||
return JSONResponse(
|
||||
{"workspaces": await _decorate(_all_workspaces()), "flags": flags.list_flags()}
|
||||
)
|
||||
return JSONResponse(await _workspaces_payload(page))
|
||||
|
||||
|
||||
@router.post("/workspaces/{uid}/suspend")
|
||||
|
||||
@@ -135,6 +135,9 @@ from devplacepy.schemas.admin import (
|
||||
AdminNewsOut,
|
||||
AdminNotificationsOut,
|
||||
AdminSettingsOut,
|
||||
ServiceDetailOut,
|
||||
ServiceOut,
|
||||
ServicesOut,
|
||||
AdminTrashOut,
|
||||
AdminUserOut,
|
||||
AdminUsersOut,
|
||||
|
||||
@@ -94,12 +94,43 @@ class AdminDeviiTaskItemOut(_Out):
|
||||
|
||||
class AdminDeviiTasksOut(_Out):
|
||||
items: list[AdminDeviiTaskItemOut] = []
|
||||
pagination: Optional[Any] = None
|
||||
state: str = "active"
|
||||
tabs: list[dict] = []
|
||||
limits: dict = {}
|
||||
admin_section: Optional[str] = None
|
||||
|
||||
|
||||
class ServiceOut(_Out):
|
||||
name: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
details: Optional[str] = None
|
||||
enabled: bool = False
|
||||
status: Optional[str] = None
|
||||
interval_seconds: Optional[int] = None
|
||||
last_run: Optional[str] = None
|
||||
next_run: Optional[str] = None
|
||||
heartbeat: Optional[str] = None
|
||||
uptime: Optional[str] = None
|
||||
log_buffer: list[str] = []
|
||||
metrics: dict = {}
|
||||
fields: list[Any] = []
|
||||
field_groups: list[Any] = []
|
||||
|
||||
|
||||
class ServicesOut(_Out):
|
||||
services: list[ServiceOut] = []
|
||||
services_total: Optional[int] = None
|
||||
admin_section: Optional[str] = None
|
||||
|
||||
|
||||
class ServiceDetailOut(_Out):
|
||||
service: ServiceOut
|
||||
tool_groups: Optional[list[Any]] = None
|
||||
admin_section: Optional[str] = None
|
||||
|
||||
|
||||
class AdminGameOut(_Out):
|
||||
era_active: bool = False
|
||||
era_name: str = ""
|
||||
@@ -139,6 +170,7 @@ class AdminCommunityItemOut(_Out):
|
||||
|
||||
class AdminCommunitiesOut(_Out):
|
||||
items: list[AdminCommunityItemOut] = []
|
||||
pagination: Optional[Any] = None
|
||||
sync_enabled: bool = False
|
||||
service_enabled: bool = False
|
||||
service_dry_run: bool = True
|
||||
@@ -316,7 +348,9 @@ class AdminNodesOut(_Out):
|
||||
devices_by_country: dict[str, int] = {}
|
||||
usage_today: dict[str, int] = {}
|
||||
flags: list[AdminNodeFlagOut] = []
|
||||
flags_total: int = 0
|
||||
devices: list[AdminNodeDeviceOut] = []
|
||||
devices_total: int = 0
|
||||
settings: list[AdminNodeSettingOut] = []
|
||||
limits: dict[str, int] = {}
|
||||
circuits: list[AdminNodeCircuitOut] = []
|
||||
|
||||
@@ -72,6 +72,7 @@ class BackupScheduleOut(_Out):
|
||||
class BackupDashboardOut(_Out):
|
||||
storage: dict = {}
|
||||
backups: list[BackupOut] = []
|
||||
backups_total: int = 0
|
||||
schedules: list[BackupScheduleOut] = []
|
||||
targets: list[dict] = []
|
||||
metrics: dict = {}
|
||||
|
||||
@@ -48,6 +48,7 @@ class ContainersOut(_Out):
|
||||
|
||||
class AdminContainersOut(_Out):
|
||||
instances: list = []
|
||||
pagination: Optional[Any] = None
|
||||
projects: list = []
|
||||
boot_languages: list = []
|
||||
restart_policies: list = []
|
||||
@@ -199,5 +200,7 @@ class WorkspaceOut(_Out):
|
||||
class AdminWorkspacesOut(_Out):
|
||||
workspaces: list[WorkspaceViewOut] = []
|
||||
flags: list[WorkspaceFlagOut] = []
|
||||
flags_total: int = 0
|
||||
pagination: Optional[Any] = None
|
||||
admin_section: Optional[str] = None
|
||||
user: Optional[Any] = None
|
||||
|
||||
@@ -14,6 +14,9 @@ class StatisticsMetricOut(BaseModel):
|
||||
format: str = "int"
|
||||
delta: Optional[float] = None
|
||||
direction: Optional[str] = None
|
||||
display: Optional[str] = None
|
||||
arrow: Optional[str] = None
|
||||
delta_display: Optional[str] = None
|
||||
|
||||
|
||||
class StatisticsPointOut(BaseModel):
|
||||
@@ -32,6 +35,9 @@ class StatisticsTableOut(BaseModel):
|
||||
title: str
|
||||
columns: list[str]
|
||||
rows: list[list[Any]]
|
||||
column_classes: list[str] = []
|
||||
display_rows: list[list[str]] = []
|
||||
row_count: Optional[str] = None
|
||||
|
||||
|
||||
class StatisticsHighlightOut(BaseModel):
|
||||
|
||||
@@ -88,10 +88,14 @@ class CommunityStore:
|
||||
row = table.find_one(slug=ref, deleted_at=None) or table.find_one(uid=ref, deleted_at=None)
|
||||
return decode(row, JSON_COLUMNS)
|
||||
|
||||
def list(self) -> list[dict]:
|
||||
rows = get_table("communities").find(deleted_at=None, order_by=["name"])
|
||||
def list(self, limit: int | None = None, offset: int = 0) -> list[dict]:
|
||||
window = {} if limit is None else {"_limit": limit, "_offset": offset}
|
||||
rows = get_table("communities").find(deleted_at=None, order_by=["name"], **window)
|
||||
return [decode(row, JSON_COLUMNS) for row in rows]
|
||||
|
||||
def count(self) -> int:
|
||||
return get_table("communities").count(deleted_at=None)
|
||||
|
||||
def pending(self, limit: int) -> list[dict]:
|
||||
horizon = iso(now() - timedelta(seconds=LIMITS.run_timeout_seconds))
|
||||
table = get_table("communities")
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from devplacepy.services.statistics.common import (
|
||||
VALID_TABS,
|
||||
cache_get,
|
||||
@@ -28,6 +30,18 @@ from devplacepy.services.statistics.tabs_data import (
|
||||
build_visitors,
|
||||
)
|
||||
|
||||
NUMERIC_HEADER_TOKENS = (
|
||||
"count", "events", "views", "gists", "posts", "votes", "actions", "stars",
|
||||
"turns", "requests", "cost", "coins", "level", "restarts", "followers",
|
||||
"upvotes", "downvotes", "members", "guests", "tokens", "errors",
|
||||
)
|
||||
NAME_HEADERS = ("user", "name")
|
||||
NAME_HEADER_TOKENS = ("username", "instance")
|
||||
NUMERIC_SAMPLE_ROWS = 12
|
||||
ARROWS = {"up": "\u2191", "down": "\u2193", "flat": "\u2192"}
|
||||
MONEY_SMALL_LIMIT = 1
|
||||
CELL_DIGITS = 2
|
||||
DECIMAL_DIGITS = 1
|
||||
TAB_BUILDERS = {
|
||||
"overview": build_overview,
|
||||
"visitors": build_visitors,
|
||||
@@ -47,6 +61,73 @@ TAB_BUILDERS = {
|
||||
}
|
||||
|
||||
|
||||
NUMERIC_TEXT = re.compile(r"^-?\d+(\.\d+)?$")
|
||||
|
||||
|
||||
def is_numeric_text(value) -> bool:
|
||||
if isinstance(value, bool):
|
||||
return False
|
||||
if isinstance(value, (int, float)):
|
||||
return True
|
||||
return bool(NUMERIC_TEXT.match(str(value if value is not None else "").strip().replace(",", "")))
|
||||
|
||||
|
||||
def format_number_text(value, digits: int) -> str:
|
||||
number = float(str(value).strip().replace(",", ""))
|
||||
if number == int(number):
|
||||
return f"{int(number):,}"
|
||||
return f"{round(number, digits):,}"
|
||||
|
||||
|
||||
def column_class(index: int, columns: list, rows: list) -> str:
|
||||
header = str(columns[index] if index < len(columns) else "").lower()
|
||||
if index == 0:
|
||||
if any(token in header for token in NAME_HEADER_TOKENS) or header in NAME_HEADERS:
|
||||
return "statistics-col-name"
|
||||
return "statistics-col-key"
|
||||
if any(token in header for token in NUMERIC_HEADER_TOKENS):
|
||||
return "statistics-col-num"
|
||||
sample = rows[:NUMERIC_SAMPLE_ROWS]
|
||||
if not sample:
|
||||
return "statistics-col-num"
|
||||
if all(is_numeric_text(row[index] if index < len(row) else None) for row in sample):
|
||||
return "statistics-col-num"
|
||||
return "statistics-col-text"
|
||||
|
||||
|
||||
def present_card(card: dict) -> dict:
|
||||
kind = card.get("format") or "int"
|
||||
value = float(card.get("value") or 0)
|
||||
if kind == "money":
|
||||
display = f"${value:.4f}" if value < MONEY_SMALL_LIMIT else f"${value:.2f}"
|
||||
elif kind == "decimal":
|
||||
display = format_number_text(value, DECIMAL_DIGITS)
|
||||
else:
|
||||
display = f"{int(value):,}"
|
||||
out = {**card, "display": display}
|
||||
delta = card.get("delta")
|
||||
if delta is not None:
|
||||
direction = card.get("direction") or "flat"
|
||||
out["direction"] = direction
|
||||
out["arrow"] = ARROWS.get(direction, ARROWS["flat"])
|
||||
out["delta_display"] = f"{format_number_text(abs(float(delta)), DECIMAL_DIGITS)}%"
|
||||
return out
|
||||
|
||||
|
||||
def present_table(table: dict) -> dict:
|
||||
columns = list(table.get("columns") or [])
|
||||
rows = list(table.get("rows") or [])
|
||||
classes = [column_class(index, columns, rows) for index in range(len(columns))]
|
||||
display_rows = [
|
||||
[
|
||||
format_number_text(row[index], CELL_DIGITS) if classes[index] == "statistics-col-num" and is_numeric_text(row[index]) else str(row[index] if row[index] is not None else "")
|
||||
for index in range(len(columns))
|
||||
]
|
||||
for row in rows
|
||||
]
|
||||
return {**table, "column_classes": classes, "display_rows": display_rows, "row_count": f"{len(rows):,}"}
|
||||
|
||||
|
||||
def build_statistics_tab(
|
||||
tab: str,
|
||||
hours: int = 168,
|
||||
@@ -73,5 +154,7 @@ def build_statistics_tab(
|
||||
"compare": bool(compare),
|
||||
**body,
|
||||
}
|
||||
payload["cards"] = [present_card(card) for card in payload.get("cards") or []]
|
||||
payload["tables"] = [present_table(table) for table in payload.get("tables") or []]
|
||||
cache_set(cache_key, payload)
|
||||
return payload
|
||||
@@ -466,7 +466,7 @@ def build_members(hours: int, compare: bool, top_n: int) -> dict:
|
||||
if window["start"]:
|
||||
series.append(series_payload("signups", "Signups", _series_table("users", window), window))
|
||||
tables = []
|
||||
if _table_exists("users") and window["start"]:
|
||||
if all(_table_exists(name) for name in ("users", "posts", "comments", "gists", "projects")) and window["start"]:
|
||||
active_rows = db.query(
|
||||
"SELECT u.username, COUNT(*) AS c FROM ("
|
||||
"SELECT user_uid, created_at FROM posts WHERE deleted_at IS NULL "
|
||||
@@ -1262,7 +1262,7 @@ def _highlights() -> list[dict]:
|
||||
)
|
||||
if row:
|
||||
items.append({"label": "Peak posting hour (UTC)", "value": f"{row[0]['hour']}:00"})
|
||||
if _table_exists("instances"):
|
||||
if _has_column("instances", "restart_count"):
|
||||
row = list(
|
||||
db.query(
|
||||
"SELECT name, slug, uid, restart_count FROM instances "
|
||||
|
||||
@@ -41,3 +41,5 @@ One global rule at the end of `base.css` collapses every animation/transition to
|
||||
- `!important` is allowed only for: the `.hidden`/`[hidden]` display utilities, the global reduced-motion rule, and the devii-avatar third-party-beating override. Anything else is a specificity problem to be fixed structurally.
|
||||
- Page-specific CSS lives in its own `static/css/*.css` loaded via `{% block extra_head %}`, never an inline `<style>` block; shared component styles live once (`components.css`, `feed.css` vote buttons) and are never redefined per page.
|
||||
- **Never give a sticky column its own CSS `max-height`/`overflow-y`.** A column shorter than the tallest column on the page renders a dead gap below it once capped (see root `CLAUDE.md`, commit `b475e7d6`, reverting exactly that). Independent scroll on a sticky column taller than the viewport is JS-driven: `static/js/StickyScrollPane.js` measures each managed element's real content height against the viewport space actually available and only then toggles `.sticky-scroll-active` (`overflow-y: auto`, defined once in `components.css`) plus a computed inline `max-height`. Add a new sticky column to its selector list in `Application.js` instead of writing CSS for it.
|
||||
|
||||
Admin pages use only the `admin-*` vocabulary in `admin.css` (`admin-btn*`, `admin-empty`, `admin-hint`, `admin-cap-note`, `admin-field`, ...); a missing class is added to `admin.css`, never replaced by a public-site class. See `devplacepy/routers/admin/CLAUDE.md` (A4).
|
||||
|
||||
@@ -199,6 +199,11 @@
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.admin-btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.admin-btn-sm {
|
||||
font-size: 0.6875rem;
|
||||
padding: 0.25rem 0.375rem;
|
||||
@@ -227,6 +232,14 @@
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.admin-btn.is-loading {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.admin-btn.is-loading .btn-spinner {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.admin-select {
|
||||
font-size: 0.75rem;
|
||||
padding: 0.25rem 0.375rem;
|
||||
@@ -329,6 +342,16 @@
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.admin-hint,
|
||||
.admin-cap-note {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.admin-cap-note {
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
.admin-toggle-switch {
|
||||
position: relative;
|
||||
width: 40px;
|
||||
|
||||
@@ -238,6 +238,10 @@
|
||||
|
||||
/* --- Stats tab ----------------------------------------------------------- */
|
||||
|
||||
.gw-section-hint-flush {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.gw-stats-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -4,10 +4,6 @@
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.planning-header h1 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.planning-subtitle {
|
||||
margin: 0.35rem 0 0;
|
||||
color: var(--text-secondary);
|
||||
|
||||
@@ -69,26 +69,6 @@
|
||||
margin-bottom: var(--space-md);
|
||||
}
|
||||
|
||||
.service-btn {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 500;
|
||||
padding: 0.25rem var(--space-md);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
background: var(--bg-card);
|
||||
color: var(--text-primary);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.service-btn:hover:not(:disabled) {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.service-btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.service-config {
|
||||
border-top: 1px solid var(--border);
|
||||
margin-bottom: var(--space-md);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
|
||||
import { Http } from "./Http.js";
|
||||
import { Poller } from "./Poller.js";
|
||||
|
||||
const REFRESH_MS = 3000;
|
||||
@@ -13,9 +14,7 @@ class AdminCommunity {
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
const response = await fetch(window.location.href, { headers: { "Accept": "text/html" }, credentials: "same-origin" });
|
||||
if (!response.ok) return;
|
||||
const fresh = new DOMParser().parseFromString(await response.text(), "text/html");
|
||||
const fresh = new DOMParser().parseFromString(await Http.getHtml(window.location.href), "text/html");
|
||||
const next = fresh.querySelector("[data-community-root]");
|
||||
if (!next) return;
|
||||
this.root.querySelectorAll("[data-live]").forEach((section) => {
|
||||
|
||||
@@ -23,9 +23,7 @@ class AdminNodes {
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
const response = await fetch(PAGE_URL, { headers: { "Accept": "text/html" } });
|
||||
if (!response.ok) return;
|
||||
const fresh = new DOMParser().parseFromString(await response.text(), "text/html");
|
||||
const fresh = new DOMParser().parseFromString(await Http.getHtml(PAGE_URL), "text/html");
|
||||
this.root.querySelectorAll("[data-live]").forEach((section) => {
|
||||
const next = fresh.querySelector(`[data-live="${section.dataset.live}"]`);
|
||||
if (next) section.innerHTML = next.innerHTML;
|
||||
|
||||
@@ -2,266 +2,28 @@
|
||||
|
||||
import { Http } from "./Http.js";
|
||||
import { Poller } from "./Poller.js";
|
||||
import { DateFormat } from "./DateFormat.js";
|
||||
|
||||
const POLL_MS = 60000;
|
||||
|
||||
class AiUsageMonitor {
|
||||
constructor() {
|
||||
this.root = document.getElementById("ai-usage-root");
|
||||
this.windowSelect = document.getElementById("ai-usage-window");
|
||||
this.dividedToggle = document.getElementById("ai-usage-divided");
|
||||
this.generated = document.querySelector("[data-meta='generated']");
|
||||
this.pollMs = 15000;
|
||||
this.hours = 48;
|
||||
}
|
||||
|
||||
start() {
|
||||
if (!this.root) return;
|
||||
if (this.windowSelect) {
|
||||
this.windowSelect.addEventListener("change", () => {
|
||||
const parsed = parseInt(this.windowSelect.value, 10);
|
||||
this.hours = Number.isNaN(parsed) ? 48 : parsed;
|
||||
this.subscribe();
|
||||
this.poll();
|
||||
});
|
||||
}
|
||||
if (this.dividedToggle) {
|
||||
this.dividedToggle.addEventListener("change", () => {
|
||||
this.root.classList.toggle("show-divided", this.dividedToggle.checked);
|
||||
});
|
||||
}
|
||||
this.subscribe();
|
||||
this.poller = new Poller(() => this.poll(), 60000, { pauseHidden: true });
|
||||
this.poller = new Poller(() => this.refresh(), POLL_MS, { pauseHidden: true, immediate: false });
|
||||
}
|
||||
|
||||
subscribe() {
|
||||
const pubsub = window.app && window.app.pubsub;
|
||||
if (!pubsub) return;
|
||||
if (this.unsubscribe) this.unsubscribe();
|
||||
this.unsubscribe = pubsub.subscribe(`admin.ai-usage.${this.hours}`, (data) => this.render(data));
|
||||
}
|
||||
|
||||
async poll() {
|
||||
try {
|
||||
const data = await Http.getJson(`/admin/ai-usage/data?hours=${this.hours}`);
|
||||
this.render(data);
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
|
||||
el(tag, className, text) {
|
||||
const node = document.createElement(tag);
|
||||
if (className) node.className = className;
|
||||
if (text !== undefined) node.textContent = String(text);
|
||||
return node;
|
||||
}
|
||||
|
||||
money(value) {
|
||||
const number = Number(value || 0);
|
||||
return number < 1 ? `$${number.toFixed(6)}` : `$${number.toFixed(2)}`;
|
||||
}
|
||||
|
||||
integer(value) {
|
||||
return Number(value || 0).toLocaleString("en-GB");
|
||||
}
|
||||
|
||||
cards(items) {
|
||||
const grid = this.el("div", "metric-cards");
|
||||
for (const item of items) {
|
||||
const card = this.el("div", "metric-card");
|
||||
card.appendChild(this.el("span", "metric-value", item.value));
|
||||
card.appendChild(this.el("span", "metric-label", item.label));
|
||||
grid.appendChild(card);
|
||||
}
|
||||
return grid;
|
||||
}
|
||||
|
||||
table(columns, rows, className) {
|
||||
const node = this.el("table", className || "metric-table");
|
||||
const thead = this.el("thead");
|
||||
const headRow = this.el("tr");
|
||||
for (const col of columns) headRow.appendChild(this.el("th", null, col));
|
||||
thead.appendChild(headRow);
|
||||
node.appendChild(thead);
|
||||
const tbody = this.el("tbody");
|
||||
for (const row of rows) {
|
||||
const tr = this.el("tr");
|
||||
for (const cell of row) tr.appendChild(this.el("td", null, cell));
|
||||
tbody.appendChild(tr);
|
||||
}
|
||||
node.appendChild(tbody);
|
||||
return node;
|
||||
}
|
||||
|
||||
section(title, ...nodes) {
|
||||
const wrap = this.el("div", "ai-usage-section");
|
||||
wrap.appendChild(this.el("h3", null, title));
|
||||
for (const node of nodes) if (node) wrap.appendChild(node);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
psetTable(title, pset) {
|
||||
const rows = [
|
||||
["avg", this.integer(pset.avg)],
|
||||
["p50", this.integer(pset.p50)],
|
||||
["p90", this.integer(pset.p90)],
|
||||
["p95", this.integer(pset.p95)],
|
||||
["p99", this.integer(pset.p99)],
|
||||
["max", this.integer(pset.max)],
|
||||
];
|
||||
const node = this.table([title, "value"], rows, "metric-table pset-table");
|
||||
return node;
|
||||
}
|
||||
|
||||
psetGrid(title, sets) {
|
||||
const grid = this.el("div", "ai-usage-grid");
|
||||
for (const [label, pset] of sets) {
|
||||
const block = this.el("div");
|
||||
block.appendChild(this.el("h3", null, label));
|
||||
block.appendChild(this.psetTable("stat", pset));
|
||||
grid.appendChild(block);
|
||||
}
|
||||
return this.section(title, grid);
|
||||
}
|
||||
|
||||
groupRows(items) {
|
||||
return (items || []).map((item) => [
|
||||
item.key, this.integer(item.requests), this.integer(item.total_tokens), this.money(item.cost_usd),
|
||||
]);
|
||||
}
|
||||
|
||||
render(data) {
|
||||
this.root.textContent = "";
|
||||
if (this.generated && data.generated_at) {
|
||||
const windowLabel = data.window_hours ? `${data.window_hours}h` : "all time";
|
||||
this.generated.textContent = `Window: ${windowLabel} - updated ${DateFormat.format(data.generated_at, true)}`;
|
||||
}
|
||||
if (!data.requests) {
|
||||
this.root.appendChild(this.el("p", "admin-empty", "No AI gateway traffic recorded in this window yet."));
|
||||
return;
|
||||
}
|
||||
const v = data.volume || {};
|
||||
const t = data.tokens || {};
|
||||
const l = data.latency || {};
|
||||
const e = data.errors || {};
|
||||
const c = data.cost || {};
|
||||
const b = data.behavior || {};
|
||||
const conc = v.concurrency || {};
|
||||
|
||||
this.root.appendChild(this.section("Overview", this.cards([
|
||||
{ label: "Requests", value: this.integer(v.requests) },
|
||||
{ label: "Success", value: `${v.requests ? (100 * v.success / v.requests).toFixed(1) : 0}%` },
|
||||
{ label: "Error rate", value: `${e.error_rate_pct}%` },
|
||||
{ label: "Requests / hour", value: this.integer(v.requests_per_hour) },
|
||||
{ label: "Peak req / min", value: this.integer(v.peak_requests_per_minute) },
|
||||
{ label: "Cost (window)", value: this.money(c.total_usd) },
|
||||
{ label: "Cost this hour", value: this.money(c.this_hour_usd) },
|
||||
{ label: "Cost 24h", value: this.money(c.last_24h_usd) },
|
||||
{ label: "Projected / month", value: this.money(c.projected_monthly_usd) },
|
||||
{ label: "Tokens total", value: this.integer(t.total) },
|
||||
{ label: "Upstream avail.", value: `${l.upstream_availability_pct}%` },
|
||||
{ label: "Concurrency peak", value: this.integer(conc.peak) },
|
||||
])));
|
||||
|
||||
this.root.appendChild(this.section("Tokens", this.cards([
|
||||
{ label: "Prompt total", value: this.integer(t.prompt_total) },
|
||||
{ label: "Completion total", value: this.integer(t.completion_total) },
|
||||
{ label: "Total", value: this.integer(t.total) },
|
||||
{ label: "Cache hit rate", value: `${((t.cache_hit_rate || 0) * 100).toFixed(1)}%` },
|
||||
{ label: "Input:output", value: t.input_output_ratio },
|
||||
{ label: "Cache hit tokens", value: this.integer(t.cache_hit_total) },
|
||||
{ label: "Cache miss tokens", value: this.integer(t.cache_miss_total) },
|
||||
{ label: "Reasoning tokens", value: this.integer(t.reasoning_total) },
|
||||
{ label: "Tokens / hour", value: this.integer(t.tokens_per_hour) },
|
||||
{ label: "Context util avg", value: t.context_utilization_avg === null || t.context_utilization_avg === undefined ? "n/a" : `${(t.context_utilization_avg * 100).toFixed(1)}%` },
|
||||
])));
|
||||
this.root.appendChild(this.psetGrid("Token distribution per request", [
|
||||
["Prompt tokens", t.prompt || {}],
|
||||
["Completion tokens", t.completion || {}],
|
||||
["Total tokens", t.total_per_request || {}],
|
||||
]));
|
||||
|
||||
this.root.appendChild(this.section("Latency and throughput", this.cards([
|
||||
{ label: "Upstream availability", value: `${l.upstream_availability_pct}%` },
|
||||
{ label: "Gateway overhead share", value: `${((l.gateway_overhead_share || 0) * 100).toFixed(1)}%` },
|
||||
{ label: "TTFT", value: "n/a (non-streaming)" },
|
||||
{ label: "Inter-token", value: "n/a (non-streaming)" },
|
||||
])));
|
||||
this.root.appendChild(this.psetGrid("Latency percentiles (ms)", [
|
||||
["Upstream round-trip", l.upstream_ms || {}],
|
||||
["Gateway overhead", l.gateway_overhead_ms || {}],
|
||||
["Queue wait", l.queue_wait_ms || {}],
|
||||
["Connection establish", l.connect_ms || {}],
|
||||
["Total", l.total_ms || {}],
|
||||
["Tokens / second", l.tokens_per_second || {}],
|
||||
]));
|
||||
|
||||
this.root.appendChild(this.section("Errors and reliability", this.cards([
|
||||
{ label: "Total errors", value: this.integer(e.total) },
|
||||
{ label: "Error rate", value: `${e.error_rate_pct}%` },
|
||||
{ label: "4xx", value: this.integer(e.count_4xx) },
|
||||
{ label: "5xx", value: this.integer(e.count_5xx) },
|
||||
{ label: "Timeouts", value: this.integer(e.timeouts) },
|
||||
{ label: "Retries attempted", value: this.integer(e.retries_attempted) },
|
||||
{ label: "Retries succeeded", value: this.integer(e.retries_succeeded) },
|
||||
{ label: "Circuit opens", value: this.integer(e.circuit_open_events) },
|
||||
]), this.table(["Error category", "Count"],
|
||||
Object.entries(e.by_category || {}).map(([k, n]) => [k, this.integer(n)]))));
|
||||
|
||||
this.root.appendChild(this.section("Cost", this.cards([
|
||||
{ label: "Total", value: this.money(c.total_usd) },
|
||||
{ label: "Input cost", value: this.money(c.input_usd) },
|
||||
{ label: "Output cost", value: this.money(c.output_usd) },
|
||||
{ label: "Per 1k tokens", value: this.money(c.effective_per_1k_tokens_usd) },
|
||||
{ label: "Caching savings", value: this.money(c.caching_savings_usd) },
|
||||
{ label: "This hour", value: this.money(c.this_hour_usd) },
|
||||
{ label: "Last 24h", value: this.money(c.last_24h_usd) },
|
||||
{ label: "Projected / month", value: this.money(c.projected_monthly_usd) },
|
||||
])));
|
||||
|
||||
this.root.appendChild(this.section("Behavior", this.cards([
|
||||
{ label: "Unique callers", value: this.integer(b.unique_callers) },
|
||||
{ label: "Req / caller avg", value: this.integer((b.requests_per_caller || {}).avg) },
|
||||
{ label: "Req / caller p95", value: this.integer((b.requests_per_caller || {}).p95) },
|
||||
{ label: "Heaviest caller", value: this.integer((b.requests_per_caller || {}).max) },
|
||||
{ label: "Avg temperature", value: b.avg_temperature === null || b.avg_temperature === undefined ? "n/a" : b.avg_temperature },
|
||||
{ label: "Avg top_p", value: b.avg_top_p === null || b.avg_top_p === undefined ? "n/a" : b.avg_top_p },
|
||||
{ label: "Tool calls", value: this.integer(b.tool_call_requests) },
|
||||
{ label: "Streaming", value: this.integer(b.streaming_requests) },
|
||||
{ label: "Non-streaming", value: this.integer(b.non_streaming_requests) },
|
||||
])));
|
||||
|
||||
const divided = this.el("div", "ai-divided");
|
||||
divided.appendChild(this.section("By model",
|
||||
this.table(["Model", "Requests", "Tokens", "Cost"], this.groupRows(v.by_model))));
|
||||
divided.appendChild(this.section("By endpoint",
|
||||
this.table(["Endpoint", "Requests", "Tokens", "Cost"], this.groupRows(v.by_endpoint))));
|
||||
divided.appendChild(this.section("By backend",
|
||||
this.table(["Backend", "Requests", "Tokens", "Cost"], this.groupRows(v.by_backend))));
|
||||
divided.appendChild(this.section("By caller",
|
||||
this.table(["Caller", "Requests", "Tokens", "Cost"], this.groupRows(v.by_caller))));
|
||||
divided.appendChild(this.section("User agents",
|
||||
this.table(["User agent", "Requests"],
|
||||
(b.user_agents || []).map((item) => [item.key, this.integer(item.requests)]))));
|
||||
this.root.appendChild(divided);
|
||||
|
||||
const hourlyRows = (data.hourly || []).map((h) => {
|
||||
const [day, hour] = String(h.hour).split("T");
|
||||
return [
|
||||
`${DateFormat.format(day)} ${(hour || "00").padStart(2, "0")}:00`,
|
||||
this.integer(h.requests),
|
||||
this.integer(h.success),
|
||||
this.integer(h.failed),
|
||||
this.integer(h.prompt_tokens),
|
||||
this.integer(h.completion_tokens),
|
||||
this.integer(h.total_tokens),
|
||||
this.money(h.cost_usd),
|
||||
this.integer(h.avg_latency_ms),
|
||||
this.integer(h.active_owners),
|
||||
this.integer(h.new_owners),
|
||||
];
|
||||
});
|
||||
this.root.appendChild(this.section("Hourly breakdown",
|
||||
this.table(["Hour", "Requests", "OK", "Failed", "Prompt", "Completion", "Total", "Cost", "Avg ms", "Callers", "New"], hourlyRows)));
|
||||
async refresh() {
|
||||
const url = `${this.root.dataset.fragment}?hours=${encodeURIComponent(this.root.dataset.hours)}`;
|
||||
this.root.innerHTML = await Http.getHtml(url);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,20 +3,19 @@
|
||||
import { Http } from "./Http.js";
|
||||
import { Poller } from "./Poller.js";
|
||||
import { JobPoller } from "./JobPoller.js";
|
||||
import { DateFormat } from "./DateFormat.js";
|
||||
|
||||
class BackupMonitor {
|
||||
const REFRESH_MS = 30000;
|
||||
const LIVE_SELECTOR = "[data-live]";
|
||||
|
||||
export class BackupMonitor {
|
||||
constructor() {
|
||||
this.root = document.getElementById("backups-root");
|
||||
this.generated = document.querySelector("[data-meta='generated']");
|
||||
this.generated = document.querySelector(".backup-generated");
|
||||
this.runForm = document.getElementById("backup-run-form");
|
||||
this.scheduleForm = document.getElementById("backup-schedule-form");
|
||||
this.scheduleModal = document.getElementById("backup-schedule-modal");
|
||||
this.scheduleKind = document.getElementById("backup-schedule-kind");
|
||||
this.scheduleTitle = document.getElementById("backup-schedule-title");
|
||||
this.pollMs = 30000;
|
||||
this.targets = [];
|
||||
this.canDownload = false;
|
||||
}
|
||||
|
||||
start() {
|
||||
@@ -25,29 +24,32 @@ class BackupMonitor {
|
||||
this.bindScheduleForm();
|
||||
this.bindActions();
|
||||
this.subscribe();
|
||||
this.poller = new Poller(() => this.poll(), this.pollMs, { pauseHidden: true });
|
||||
this.poller = new Poller(() => this.refresh(), REFRESH_MS, { pauseHidden: true, immediate: false });
|
||||
}
|
||||
|
||||
subscribe() {
|
||||
const pubsub = window.app && window.app.pubsub;
|
||||
if (!pubsub) return;
|
||||
if (this.unsubscribe) this.unsubscribe();
|
||||
this.unsubscribe = pubsub.subscribe("admin.backups", (data) => this.applyPush(data));
|
||||
this.unsubscribe = pubsub.subscribe("admin.backups", () => this.refresh());
|
||||
}
|
||||
|
||||
applyPush(data) {
|
||||
this.targets = data.targets || this.targets;
|
||||
this.render(data);
|
||||
}
|
||||
|
||||
async poll() {
|
||||
async refresh() {
|
||||
let html;
|
||||
try {
|
||||
const data = await Http.getJson("/admin/backups/data");
|
||||
this.canDownload = !!data.can_download_backups;
|
||||
this.targets = data.targets || [];
|
||||
this.render(data);
|
||||
html = await Http.getHtml(window.location.pathname);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const fresh = new DOMParser().parseFromString(html, "text/html");
|
||||
const next = fresh.getElementById("backups-root");
|
||||
if (!next) return;
|
||||
this.root.querySelectorAll(LIVE_SELECTOR).forEach((section) => {
|
||||
const replacement = next.querySelector(`[data-live="${section.dataset.live}"]`);
|
||||
if (replacement) section.innerHTML = replacement.innerHTML;
|
||||
});
|
||||
const stamp = fresh.querySelector(".backup-generated");
|
||||
if (this.generated && stamp) this.generated.innerHTML = stamp.innerHTML;
|
||||
}
|
||||
|
||||
bindRunForm() {
|
||||
@@ -70,15 +72,15 @@ class BackupMonitor {
|
||||
|
||||
followJob(statusUrl) {
|
||||
if (!statusUrl) return;
|
||||
this.poll();
|
||||
this.refresh();
|
||||
JobPoller.run(statusUrl, {
|
||||
onDone: () => {
|
||||
window.app.toast.show("Backup completed", { type: "success" });
|
||||
this.poll();
|
||||
this.refresh();
|
||||
},
|
||||
onFailed: (status) => {
|
||||
Http.notifyError((status && status.error) || "Backup failed");
|
||||
this.poll();
|
||||
this.refresh();
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -99,7 +101,7 @@ class BackupMonitor {
|
||||
await Http.send(this.scheduleForm.action, params);
|
||||
this.scheduleModal.classList.remove("visible");
|
||||
window.app.toast.show("Schedule saved", { type: "success" });
|
||||
this.poll();
|
||||
this.refresh();
|
||||
} catch {
|
||||
}
|
||||
});
|
||||
@@ -140,7 +142,7 @@ class BackupMonitor {
|
||||
const action = button.dataset.action;
|
||||
const uid = button.dataset.uid;
|
||||
if (action === "edit-schedule") {
|
||||
const schedule = this.schedulesByUid[uid];
|
||||
const schedule = JSON.parse(button.dataset.schedule || "null");
|
||||
if (schedule) this.openScheduleEdit(schedule);
|
||||
return;
|
||||
}
|
||||
@@ -163,191 +165,9 @@ class BackupMonitor {
|
||||
};
|
||||
try {
|
||||
await Http.send(urls[action], {});
|
||||
this.poll();
|
||||
this.refresh();
|
||||
} catch {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
el(tag, className, text) {
|
||||
const node = document.createElement(tag);
|
||||
if (className) node.className = className;
|
||||
if (text !== undefined) node.textContent = String(text);
|
||||
return node;
|
||||
}
|
||||
|
||||
cards(items) {
|
||||
const grid = this.el("div", "metric-cards");
|
||||
for (const item of items) {
|
||||
const card = this.el("div", "metric-card");
|
||||
card.appendChild(this.el("span", "metric-value", item.value));
|
||||
card.appendChild(this.el("span", "metric-label", item.label));
|
||||
grid.appendChild(card);
|
||||
}
|
||||
return grid;
|
||||
}
|
||||
|
||||
section(title, ...nodes) {
|
||||
const wrap = this.el("div", "backups-section");
|
||||
wrap.appendChild(this.el("h3", null, title));
|
||||
for (const node of nodes) if (node) wrap.appendChild(node);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
storageSection(storage) {
|
||||
const disk = storage.disk || {};
|
||||
const totals = storage.backups_total || {};
|
||||
const data = storage.data_dir || {};
|
||||
const overview = this.cards([
|
||||
{ label: "Disk used", value: `${disk.used_human || "0"} / ${disk.total_human || "0"}` },
|
||||
{ label: "Disk free", value: disk.free_human || "0" },
|
||||
{ label: "Disk usage", value: `${disk.used_percent || 0}%` },
|
||||
{ label: "Data directory", value: data.size_human || "0" },
|
||||
{ label: "Backups stored", value: totals.count || 0 },
|
||||
{ label: "Backups size", value: totals.size_human || "0" },
|
||||
]);
|
||||
const table = this.el("table", "metric-table");
|
||||
const head = this.el("thead");
|
||||
const headRow = this.el("tr");
|
||||
for (const col of ["Path", "Size", "Files", "Location"]) headRow.appendChild(this.el("th", null, col));
|
||||
head.appendChild(headRow);
|
||||
table.appendChild(head);
|
||||
const body = this.el("tbody");
|
||||
for (const path of storage.paths || []) {
|
||||
const tr = this.el("tr");
|
||||
tr.appendChild(this.el("td", null, path.label));
|
||||
tr.appendChild(this.el("td", null, path.size_human));
|
||||
tr.appendChild(this.el("td", null, path.file_count));
|
||||
const location = this.el("td", "backups-path", path.path);
|
||||
if (!path.exists) location.classList.add("backups-missing");
|
||||
tr.appendChild(location);
|
||||
body.appendChild(tr);
|
||||
}
|
||||
table.appendChild(body);
|
||||
return this.section("Storage", overview, table);
|
||||
}
|
||||
|
||||
backupsSection(backups, metrics) {
|
||||
const overview = this.cards([
|
||||
{ label: "Total", value: metrics.total || 0 },
|
||||
{ label: "Done", value: metrics.done || 0 },
|
||||
{ label: "Running", value: metrics.running || 0 },
|
||||
{ label: "Pending", value: metrics.pending || 0 },
|
||||
{ label: "Failed", value: metrics.failed || 0 },
|
||||
{ label: "Archive size", value: metrics.size_human || "0" },
|
||||
]);
|
||||
if (!backups.length) {
|
||||
return this.section("Backups", overview, this.el("p", "admin-empty", "No backups yet."));
|
||||
}
|
||||
const table = this.el("table", "metric-table backups-table");
|
||||
const head = this.el("thead");
|
||||
const headRow = this.el("tr");
|
||||
for (const col of ["Created", "Target", "Status", "Size", "Files", "Checksum", "Actions"]) {
|
||||
headRow.appendChild(this.el("th", null, col));
|
||||
}
|
||||
head.appendChild(headRow);
|
||||
table.appendChild(head);
|
||||
const body = this.el("tbody");
|
||||
for (const backup of backups) {
|
||||
const tr = this.el("tr");
|
||||
tr.appendChild(this.el("td", null, DateFormat.format(backup.created_at, true)));
|
||||
tr.appendChild(this.el("td", null, backup.label || backup.target));
|
||||
const status = this.el("td");
|
||||
status.appendChild(this.el("span", `backups-status backups-status-${backup.status}`, backup.status));
|
||||
tr.appendChild(status);
|
||||
tr.appendChild(this.el("td", null, backup.size_human || "-"));
|
||||
tr.appendChild(this.el("td", null, backup.file_count || 0));
|
||||
tr.appendChild(this.el("td", "backups-sha", backup.sha256 ? backup.sha256.slice(0, 12) : "-"));
|
||||
tr.appendChild(this.backupActions(backup));
|
||||
body.appendChild(tr);
|
||||
}
|
||||
table.appendChild(body);
|
||||
return this.section("Backups", overview, table);
|
||||
}
|
||||
|
||||
backupActions(backup) {
|
||||
const cell = this.el("td", "backups-actions");
|
||||
if (backup.status === "done") {
|
||||
if (this.canDownload) {
|
||||
const link = this.el("a", "admin-btn admin-btn-sm", "Download");
|
||||
link.href = `/admin/backups/${backup.uid}/download`;
|
||||
cell.appendChild(link);
|
||||
} else {
|
||||
const blocked = this.el("button", "admin-btn admin-btn-sm", "Download");
|
||||
blocked.disabled = true;
|
||||
blocked.setAttribute("aria-disabled", "true");
|
||||
blocked.title = "Not available";
|
||||
cell.appendChild(blocked);
|
||||
}
|
||||
}
|
||||
const remove = this.el("button", "admin-btn admin-btn-sm admin-btn-danger", "Delete");
|
||||
remove.dataset.action = "delete-backup";
|
||||
remove.dataset.uid = backup.uid;
|
||||
cell.appendChild(remove);
|
||||
return cell;
|
||||
}
|
||||
|
||||
schedulesSection(schedules) {
|
||||
this.schedulesByUid = {};
|
||||
for (const schedule of schedules) this.schedulesByUid[schedule.uid] = schedule;
|
||||
if (!schedules.length) {
|
||||
return this.section("Schedules", this.el("p", "admin-empty", "No backup schedules configured."));
|
||||
}
|
||||
const table = this.el("table", "metric-table backups-schedules");
|
||||
const head = this.el("thead");
|
||||
const headRow = this.el("tr");
|
||||
for (const col of ["Name", "Target", "Trigger", "Keep", "Next run", "Last run", "Runs", "State", "Actions"]) {
|
||||
headRow.appendChild(this.el("th", null, col));
|
||||
}
|
||||
head.appendChild(headRow);
|
||||
table.appendChild(head);
|
||||
const body = this.el("tbody");
|
||||
for (const schedule of schedules) {
|
||||
const tr = this.el("tr");
|
||||
tr.appendChild(this.el("td", null, schedule.name));
|
||||
tr.appendChild(this.el("td", null, schedule.target));
|
||||
const trigger = schedule.kind === "cron" ? `cron ${schedule.cron}` : `every ${schedule.every_seconds}s`;
|
||||
tr.appendChild(this.el("td", null, trigger));
|
||||
tr.appendChild(this.el("td", null, schedule.keep_last || "all"));
|
||||
tr.appendChild(this.el("td", null, schedule.next_run_at ? DateFormat.format(schedule.next_run_at, true) : "-"));
|
||||
tr.appendChild(this.el("td", null, schedule.last_run_at ? DateFormat.format(schedule.last_run_at, true) : "-"));
|
||||
tr.appendChild(this.el("td", null, schedule.run_count || 0));
|
||||
const state = this.el("td");
|
||||
state.appendChild(this.el("span", `backups-status backups-status-${schedule.enabled ? "done" : "failed"}`, schedule.enabled ? "enabled" : "disabled"));
|
||||
tr.appendChild(state);
|
||||
tr.appendChild(this.scheduleActions(schedule));
|
||||
body.appendChild(tr);
|
||||
}
|
||||
table.appendChild(body);
|
||||
return this.section("Schedules", table);
|
||||
}
|
||||
|
||||
scheduleActions(schedule) {
|
||||
const cell = this.el("td", "backups-actions");
|
||||
const definitions = [
|
||||
["run-schedule", "Run", ""],
|
||||
["edit-schedule", "Edit", ""],
|
||||
["toggle-schedule", schedule.enabled ? "Disable" : "Enable", ""],
|
||||
["delete-schedule", "Delete", "admin-btn-danger"],
|
||||
];
|
||||
for (const [action, label, extra] of definitions) {
|
||||
const button = this.el("button", `admin-btn admin-btn-sm ${extra}`.trim(), label);
|
||||
button.dataset.action = action;
|
||||
button.dataset.uid = schedule.uid;
|
||||
cell.appendChild(button);
|
||||
}
|
||||
return cell;
|
||||
}
|
||||
|
||||
render(data) {
|
||||
if (this.generated && data.generated_at) {
|
||||
this.generated.textContent = `Updated ${DateFormat.format(data.generated_at, true)}`;
|
||||
}
|
||||
this.root.textContent = "";
|
||||
this.root.appendChild(this.storageSection(data.storage || {}));
|
||||
this.root.appendChild(this.backupsSection(data.backups || [], data.metrics || {}));
|
||||
this.root.appendChild(this.schedulesSection(data.schedules || []));
|
||||
}
|
||||
}
|
||||
|
||||
window.BackupMonitor = BackupMonitor;
|
||||
|
||||
@@ -44,6 +44,8 @@ A small set of plain ES6 modules under `static/js/` own the cross-cutting patter
|
||||
|
||||
Detail on each utility:
|
||||
|
||||
- **Admin page scripts follow `devplacepy/routers/admin/CLAUDE.md` (A8, A9).** The first paint is server-rendered, so an admin monitor starts with `new Poller(fn, ms, { pauseHidden: true, immediate: false })` (floor 15 s, never `setInterval`), reads its initial data from the embedded `<script type="application/json" id="...-initial">` island instead of fetching it, refreshes through `Http.getJson` on the page's `/data` endpoint, re-emits `<time data-dt>` for instants (never `toLocaleString`), and draws charts with the single vendored `/static/vendor/chartjs/chart.umd.min.js`.
|
||||
|
||||
- **`Http` (`static/js/Http.js`, global `window.Http`).** The single HTTP helper. `getJson(url)` (GET -> JSON, throws on non-2xx); `sendForm(url, params)` (POST form-encoded, follows the `/auth/login` redirect via `Http.toLogin()`, throws a bare status on failure, returns JSON); `send(url, params)` (POST form-encoded that throws `data.error.message` on `!ok` **or** a 200 body with `ok:false` - the manager-style error the container/admin UIs surface in a toast); `postJson`/`postForm`/`toLogin`. Container files (`ContainerManager`, `ContainerList`, `ContainerInstance`, `ContainerTerminal`), `ServiceMonitor`, and `ProjectFiles` all route through it - none re-implement `fetch`.
|
||||
`Http.suspend()` is the named "we are resolving this elsewhere, do not let the caller render an error" idiom (a promise that never settles). It replaced three inline `new Promise(() => {})` copies and is what `toLogin()` and the terms gate both return.
|
||||
- **`TermsGate` (`static/js/TermsGate.js`, `app.termsGate`).** The single client-side handler for the terms-acceptance refusal. `Http` calls `Http._gate(data, options, retry)` on **every** POST helper (`sendForm`, `send`, `postJson`); when the error payload carries `code: "terms_acceptance_required"` it hands off to `app.termsGate.intercept(error, retry)`, which shows one dialog (Accept and continue / Not now, with the Terms, Guidelines and Privacy links), POSTs `/auth/accept-terms` on accept, and then **re-runs the original request** so the click the user made actually happens. Declining returns `Http.suspend()`.
|
||||
|
||||
@@ -8,9 +8,17 @@ export class ContainerList {
|
||||
constructor(root) {
|
||||
this.root = root;
|
||||
this.endpoint = root.dataset.endpoint;
|
||||
this.page = root.dataset.page || "1";
|
||||
this.body = document.getElementById("cm-admin-rows");
|
||||
this.pollMs = 4000;
|
||||
this.instances = [];
|
||||
this.instances = Array.from(
|
||||
this.body ? this.body.querySelectorAll(".cm-row") : [],
|
||||
(row) => ({ uid: row.dataset.uid }),
|
||||
);
|
||||
}
|
||||
|
||||
onPage(instances) {
|
||||
const known = new Set(this.instances.map((inst) => inst.uid));
|
||||
return instances.filter((inst) => known.has(inst.uid));
|
||||
}
|
||||
|
||||
init() {
|
||||
@@ -23,21 +31,11 @@ export class ContainerList {
|
||||
const pubsub = window.app && window.app.pubsub;
|
||||
if (pubsub) {
|
||||
pubsub.subscribe("container.list", (data) => {
|
||||
if (data.partial) this.merge(data.instances || []);
|
||||
else this.render(data.instances || []);
|
||||
if (this.onPage(data.instances || []).length) this.refresh();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
merge(updates) {
|
||||
const byUid = new Map(this.instances.map((inst) => [inst.uid, inst]));
|
||||
for (const update of updates) {
|
||||
const current = byUid.get(update.uid);
|
||||
byUid.set(update.uid, current ? { ...update, can_manage: current.can_manage } : update);
|
||||
}
|
||||
this.render([...byUid.values()]);
|
||||
}
|
||||
|
||||
toast(message, type) {
|
||||
if (window.app && window.app.toast) window.app.toast.show(message, { type: type || "info" });
|
||||
}
|
||||
@@ -126,7 +124,16 @@ export class ContainerList {
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
this.render((await Http.getJson(this.endpoint)).instances || []);
|
||||
if (this.refreshing) return;
|
||||
this.refreshing = true;
|
||||
try {
|
||||
const data = await Http.getJson(`${this.endpoint}?page=${encodeURIComponent(this.page)}`);
|
||||
this.render(data.instances || []);
|
||||
const count = document.getElementById("cm-admin-count");
|
||||
if (count && data.pagination) count.textContent = `${data.pagination.total} instances`;
|
||||
} finally {
|
||||
this.refreshing = false;
|
||||
}
|
||||
}
|
||||
|
||||
render(instances) {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
|
||||
import { Http } from "./Http.js";
|
||||
import { Poller } from "./Poller.js";
|
||||
import { GatewayChartManager } from "./GatewayChartManager.js";
|
||||
|
||||
const AUTO_REFRESH_MS = 30000;
|
||||
const REFRESH_MS = 30000;
|
||||
const SLOTS = ["tiles", "models", "failures", "note"];
|
||||
|
||||
function formatMs(value) {
|
||||
if (value === null || value === undefined) return "-";
|
||||
@@ -23,66 +25,42 @@ export class GatewayStats {
|
||||
this.modelSelect = root.querySelector("#gw-model-detail-select");
|
||||
this.modelEmptyState = root.querySelector("#gw-model-detail-empty-state");
|
||||
this.modelCharts = root.querySelector("#gw-model-detail-charts");
|
||||
this.timer = null;
|
||||
this.poller = null;
|
||||
}
|
||||
|
||||
start() {
|
||||
if (!this.rangeSelect) return;
|
||||
this.rangeSelect.addEventListener("change", () => this.refresh());
|
||||
if (this.modelSelect) {
|
||||
this.modelSelect.addEventListener("change", () => this.refreshModelDetail());
|
||||
}
|
||||
this.loadModelOptions();
|
||||
this.refresh();
|
||||
this.timer = window.setInterval(() => this.refresh(), AUTO_REFRESH_MS);
|
||||
this.renderCharts(this.readIsland(this.root));
|
||||
this.poller = new Poller(() => this.refresh(), REFRESH_MS, { pauseHidden: true, immediate: false });
|
||||
}
|
||||
|
||||
stop() {
|
||||
if (this.timer) window.clearInterval(this.timer);
|
||||
if (this.poller) this.poller.stop();
|
||||
}
|
||||
|
||||
readIsland(scope) {
|
||||
const island = scope.querySelector("#gw-stats-initial");
|
||||
return island ? JSON.parse(island.textContent) : {};
|
||||
}
|
||||
|
||||
get range() {
|
||||
return this.rangeSelect ? this.rangeSelect.value : "24h";
|
||||
}
|
||||
|
||||
async loadModelOptions() {
|
||||
let data;
|
||||
try {
|
||||
data = await Http.getJson("/admin/gateway/stats/models");
|
||||
} catch (err) {
|
||||
return;
|
||||
}
|
||||
if (!this.modelSelect) return;
|
||||
for (const entry of data.models || []) {
|
||||
const option = document.createElement("option");
|
||||
option.value = `${entry.provider}|${entry.model}`;
|
||||
option.textContent = `${entry.model} (${entry.provider})`;
|
||||
this.modelSelect.appendChild(option);
|
||||
}
|
||||
return this.root.dataset.range || "24h";
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
let data;
|
||||
try {
|
||||
data = await Http.getJson(`/admin/gateway/stats/data?range=${encodeURIComponent(this.range)}`);
|
||||
} catch (err) {
|
||||
return;
|
||||
const url = `${this.root.dataset.fragment}?range=${encodeURIComponent(this.range)}`;
|
||||
const html = await Http.getHtml(url);
|
||||
const incoming = document.createElement("div");
|
||||
incoming.innerHTML = html;
|
||||
for (const name of SLOTS) {
|
||||
const target = this.root.querySelector(`[data-slot="${name}"]`);
|
||||
const source = incoming.querySelector(`[data-slot="${name}"]`);
|
||||
if (target && source) target.innerHTML = source.innerHTML;
|
||||
}
|
||||
this.renderTiles(data);
|
||||
this.renderCharts(data);
|
||||
this.renderModelTable(data.per_model || []);
|
||||
this.renderFailuresTable(data.recent_failures || []);
|
||||
}
|
||||
|
||||
renderTiles(data) {
|
||||
const totalRequests = (data.totals.success || 0) + (data.totals.error || 0);
|
||||
this.setText("#gw-stat-total-requests", totalRequests);
|
||||
this.setText("#gw-stat-success-rate", formatPct(data.totals.success || 0, totalRequests));
|
||||
this.setText("#gw-stat-models-tracked", (data.per_model || []).length);
|
||||
this.setText(
|
||||
"#gw-stat-generated-at",
|
||||
data.generated_at ? new Date(data.generated_at * 1000).toLocaleTimeString() : "-"
|
||||
);
|
||||
this.renderCharts(this.readIsland(incoming));
|
||||
}
|
||||
|
||||
setText(selector, value) {
|
||||
@@ -158,56 +136,6 @@ export class GatewayStats {
|
||||
);
|
||||
}
|
||||
|
||||
renderModelTable(perModel) {
|
||||
const body = this.root.querySelector("#gw-stats-model-table-body");
|
||||
if (!body) return;
|
||||
if (!perModel.length) {
|
||||
body.innerHTML = '<tr><td colspan="10" class="admin-empty">No requests in this range.</td></tr>';
|
||||
return;
|
||||
}
|
||||
body.innerHTML = "";
|
||||
for (const row of perModel) {
|
||||
const health = row.health || {};
|
||||
const tr = document.createElement("tr");
|
||||
tr.innerHTML = `
|
||||
<td>${row.model}</td>
|
||||
<td>${row.provider}</td>
|
||||
<td>${row.total_requests}</td>
|
||||
<td>${formatPct(row.success_requests, row.total_requests)}</td>
|
||||
<td>${formatMs(row.avg_latency_ms)}</td>
|
||||
<td>${row.avg_tokens_per_second ?? "-"}</td>
|
||||
<td>${health.weight ?? "-"}</td>
|
||||
<td>${health.circuit_open ? "open" : "closed"}</td>
|
||||
<td>${row.prompt_tokens}</td>
|
||||
<td>${row.completion_tokens}</td>
|
||||
`;
|
||||
body.appendChild(tr);
|
||||
}
|
||||
}
|
||||
|
||||
renderFailuresTable(failures) {
|
||||
const body = this.root.querySelector("#gw-stats-failures-table-body");
|
||||
if (!body) return;
|
||||
if (!failures.length) {
|
||||
body.innerHTML = '<tr><td colspan="7" class="admin-empty">No failures in this range.</td></tr>';
|
||||
return;
|
||||
}
|
||||
body.innerHTML = "";
|
||||
for (const row of failures) {
|
||||
const tr = document.createElement("tr");
|
||||
tr.innerHTML = `
|
||||
<td>${row.created_at ? new Date(row.created_at).toLocaleString() : "-"}</td>
|
||||
<td>${row.model || "-"}</td>
|
||||
<td>${row.provider || "-"}</td>
|
||||
<td>${row.endpoint || "-"}</td>
|
||||
<td>${row.status_code ?? "-"}</td>
|
||||
<td>${row.reason || "-"}</td>
|
||||
<td>${row.fallback_used_route || "no fallback"}</td>
|
||||
`;
|
||||
body.appendChild(tr);
|
||||
}
|
||||
}
|
||||
|
||||
async refreshModelDetail() {
|
||||
const raw = this.modelSelect ? this.modelSelect.value : "";
|
||||
if (!raw) {
|
||||
|
||||
@@ -56,6 +56,17 @@ export class Http {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
static async getHtml(url, options = {}) {
|
||||
const response = await fetch(url, {
|
||||
headers: { "Accept": "text/html" },
|
||||
signal: options.signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw Http._error(`request failed with status ${response.status}`, response.status);
|
||||
}
|
||||
return response.text();
|
||||
}
|
||||
|
||||
static async sendForm(url, params = {}, options = {}) {
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
import { Http } from "./Http.js";
|
||||
import { Poller } from "./Poller.js";
|
||||
import { Toast } from "./Toast.js";
|
||||
import { DateFormat } from "./DateFormat.js";
|
||||
|
||||
class ServiceMonitor {
|
||||
constructor() {
|
||||
@@ -18,7 +17,7 @@ class ServiceMonitor {
|
||||
if (!container) return;
|
||||
this.bindActions(container);
|
||||
this.bindConfigForms(container);
|
||||
this.poller = new Poller(() => this.poll(), 20000, { pauseHidden: true });
|
||||
this.poller = new Poller(() => this.poll(), 20000, { pauseHidden: true, immediate: false });
|
||||
const pubsub = window.app && window.app.pubsub;
|
||||
if (pubsub) {
|
||||
const topic = this.detail ? `admin.services.${this.detailName}` : "admin.services";
|
||||
@@ -138,9 +137,9 @@ class ServiceMonitor {
|
||||
statusEl.className = "service-status " + svc.status;
|
||||
}
|
||||
this.setMeta(root, "uptime", svc.uptime || "-");
|
||||
this.setMeta(root, "last_run", svc.last_run ? DateFormat.format(svc.last_run, true) : "-");
|
||||
this.setMeta(root, "next_run", svc.next_run ? DateFormat.format(svc.next_run, true) : "-");
|
||||
this.setMeta(root, "heartbeat", svc.heartbeat ? DateFormat.format(svc.heartbeat, true) : "-");
|
||||
this.setInstant(root, "last_run", svc.last_run);
|
||||
this.setInstant(root, "next_run", svc.next_run);
|
||||
this.setInstant(root, "heartbeat", svc.heartbeat);
|
||||
this.setMeta(root, "interval", "every " + svc.interval_seconds + "s");
|
||||
|
||||
const logPre = root.querySelector(".log-output");
|
||||
@@ -176,6 +175,24 @@ class ServiceMonitor {
|
||||
if (el) el.textContent = value;
|
||||
}
|
||||
|
||||
setInstant(root, key, iso) {
|
||||
const el = root.querySelector(`[data-meta="${key}"]`);
|
||||
if (!el) return;
|
||||
if (!iso) {
|
||||
el.textContent = "-";
|
||||
return;
|
||||
}
|
||||
const current = el.querySelector("time[data-dt]");
|
||||
if (current && current.getAttribute("datetime") === iso) return;
|
||||
const time = document.createElement("time");
|
||||
time.setAttribute("datetime", iso);
|
||||
time.dataset.dt = "";
|
||||
time.dataset.dtMode = "datetime";
|
||||
time.textContent = iso;
|
||||
el.textContent = "";
|
||||
el.appendChild(time);
|
||||
}
|
||||
|
||||
renderMetrics(container, metrics) {
|
||||
container.textContent = "";
|
||||
if (!metrics || (!metrics.stats && !metrics.table)) return;
|
||||
|
||||
@@ -29,23 +29,9 @@ export class StatisticsCharts {
|
||||
render(container, seriesList) {
|
||||
this.destroy();
|
||||
if (!container || !window.Chart || !Array.isArray(seriesList)) return;
|
||||
const panels = [];
|
||||
for (const series of seriesList) {
|
||||
const panel = document.createElement("div");
|
||||
panel.className = "statistics-chart-panel";
|
||||
const title = document.createElement("h4");
|
||||
title.textContent = series.label || series.key || "Series";
|
||||
panel.appendChild(title);
|
||||
const wrap = document.createElement("div");
|
||||
wrap.className = "statistics-chart-wrap";
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.setAttribute("role", "img");
|
||||
canvas.setAttribute("aria-label", `${series.label || "Chart"} over time`);
|
||||
wrap.appendChild(canvas);
|
||||
panel.appendChild(wrap);
|
||||
container.appendChild(panel);
|
||||
panels.push({ canvas, series });
|
||||
}
|
||||
const panels = Array.from(container.querySelectorAll("canvas[data-series-index]"))
|
||||
.map((canvas) => ({ canvas, series: seriesList[Number(canvas.dataset.seriesIndex)] }))
|
||||
.filter((panel) => panel.series);
|
||||
for (let index = 0; index < panels.length; index += 1) {
|
||||
const { canvas, series } = panels[index];
|
||||
const labels = (series.points || []).map((point) => point.t);
|
||||
|
||||
@@ -1,327 +1,34 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
|
||||
import { Http } from "./Http.js";
|
||||
import { StatisticsCharts } from "./StatisticsCharts.js";
|
||||
|
||||
class StatisticsDashboard {
|
||||
constructor(options = {}) {
|
||||
this.root = document.getElementById(options.rootId || "statistics-root");
|
||||
this.initialNode = document.getElementById(options.initialId || "statistics-initial");
|
||||
this.windowSelect = document.getElementById("statistics-window");
|
||||
this.compareToggle = document.getElementById("statistics-compare");
|
||||
this.generated = document.querySelector("[data-meta='generated']");
|
||||
this.tabLinks = Array.from(document.querySelectorAll(".admin-tabs .admin-tab[data-tab]"));
|
||||
this.activeTab = options.activeTab || "overview";
|
||||
this.windowHours = Number(options.windowHours || 168);
|
||||
export class StatisticsDashboard {
|
||||
constructor(root, seriesNode) {
|
||||
this.root = root;
|
||||
this.seriesNode = seriesNode;
|
||||
this.charts = new StatisticsCharts();
|
||||
this.cache = new Map();
|
||||
this.loading = false;
|
||||
}
|
||||
|
||||
readSeries() {
|
||||
if (!this.seriesNode) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(this.seriesNode.textContent || "[]");
|
||||
return Array.isArray(parsed) ? parsed : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
start() {
|
||||
if (!this.root) return;
|
||||
if (this.windowSelect) {
|
||||
this.windowSelect.addEventListener("change", () => {
|
||||
const parsed = parseInt(this.windowSelect.value, 10);
|
||||
this.windowHours = Number.isNaN(parsed) ? 168 : parsed;
|
||||
this.cache.clear();
|
||||
this.loadTab(this.activeTab, true);
|
||||
});
|
||||
}
|
||||
if (this.compareToggle) {
|
||||
this.compareToggle.addEventListener("change", () => {
|
||||
this.cache.clear();
|
||||
this.loadTab(this.activeTab, true);
|
||||
});
|
||||
}
|
||||
for (const link of this.tabLinks) {
|
||||
link.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
const tab = link.dataset.tab;
|
||||
if (!tab || tab === this.activeTab) return;
|
||||
for (const node of this.tabLinks) {
|
||||
node.classList.toggle("active", node.dataset.tab === tab);
|
||||
}
|
||||
this.activeTab = tab;
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set("tab", tab);
|
||||
url.searchParams.set("hours", String(this.windowHours));
|
||||
window.history.replaceState({}, "", url);
|
||||
this.loadTab(tab, false);
|
||||
});
|
||||
}
|
||||
const initial = this.readInitial();
|
||||
if (initial) {
|
||||
this.cache.set(this.cacheKey(this.activeTab), initial);
|
||||
this.render(initial);
|
||||
const container = this.root.querySelector("[data-statistics-charts]");
|
||||
const series = this.readSeries();
|
||||
if (!container || !series.length) return;
|
||||
const draw = () => this.charts.render(container, series);
|
||||
if (window.Chart) {
|
||||
draw();
|
||||
} else {
|
||||
this.loadTab(this.activeTab, true);
|
||||
}
|
||||
}
|
||||
|
||||
readInitial() {
|
||||
if (!this.initialNode) return null;
|
||||
try {
|
||||
return JSON.parse(this.initialNode.textContent || "null");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
cacheKey(tab) {
|
||||
const compare = this.compareToggle && this.compareToggle.checked ? 1 : 0;
|
||||
return `${tab}:${this.windowHours}:${compare}`;
|
||||
}
|
||||
|
||||
async loadTab(tab, force) {
|
||||
const key = this.cacheKey(tab);
|
||||
if (!force && this.cache.has(key)) {
|
||||
this.render(this.cache.get(key));
|
||||
return;
|
||||
}
|
||||
if (this.loading) return;
|
||||
this.loading = true;
|
||||
this.root.innerHTML = '<p class="admin-empty">Loading statistics...</p>';
|
||||
try {
|
||||
const compare = this.compareToggle && this.compareToggle.checked ? 1 : 0;
|
||||
const data = await Http.getJson(
|
||||
`/admin/statistics/data?tab=${encodeURIComponent(tab)}&hours=${this.windowHours}&compare=${compare}`
|
||||
);
|
||||
this.cache.set(key, data);
|
||||
this.render(data);
|
||||
} catch {
|
||||
this.root.innerHTML = '<p class="admin-empty">Could not load statistics.</p>';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
formatValue(card) {
|
||||
const value = card.value;
|
||||
const kind = card.format || "int";
|
||||
if (kind === "money") {
|
||||
const number = Number(value || 0);
|
||||
return number < 1 ? `$${number.toFixed(4)}` : `$${number.toFixed(2)}`;
|
||||
}
|
||||
if (kind === "decimal") {
|
||||
return Number(value || 0).toLocaleString("en-GB", { maximumFractionDigits: 1 });
|
||||
}
|
||||
return Number(value || 0).toLocaleString("en-GB");
|
||||
}
|
||||
|
||||
deltaMarkup(card) {
|
||||
if (card.delta === undefined || card.delta === null) return null;
|
||||
const direction = card.direction || "flat";
|
||||
const arrow = direction === "up" ? "\u2191" : direction === "down" ? "\u2193" : "\u2192";
|
||||
const node = document.createElement("span");
|
||||
node.className = `statistics-delta ${direction}`;
|
||||
node.textContent = `${arrow} ${Math.abs(Number(card.delta || 0)).toLocaleString("en-GB")}%`;
|
||||
return node;
|
||||
}
|
||||
|
||||
isNumericValue(value) {
|
||||
if (typeof value === "number" && Number.isFinite(value)) return true;
|
||||
const text = String(value ?? "").trim().replace(/,/g, "");
|
||||
if (!text) return false;
|
||||
return /^-?\d+(\.\d+)?$/.test(text);
|
||||
}
|
||||
|
||||
columnIsNumeric(columnIndex, columns, rows) {
|
||||
const header = (columns[columnIndex] || "").toLowerCase();
|
||||
const numericHeaders = [
|
||||
"count", "events", "views", "gists", "posts", "votes", "actions", "stars",
|
||||
"turns", "requests", "cost", "coins", "level", "restarts", "followers",
|
||||
"upvotes", "downvotes", "members", "guests", "tokens", "errors",
|
||||
];
|
||||
if (numericHeaders.some((token) => header.includes(token))) return true;
|
||||
const sample = rows.slice(0, 12);
|
||||
if (!sample.length) return columnIndex > 0;
|
||||
return sample.every((row) => this.isNumericValue(row[columnIndex]));
|
||||
}
|
||||
|
||||
formatTableCell(value) {
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
if (Number.isInteger(value)) return value.toLocaleString("en-GB");
|
||||
return value.toLocaleString("en-GB", { maximumFractionDigits: 2 });
|
||||
}
|
||||
const text = String(value ?? "");
|
||||
const plain = text.trim().replace(/,/g, "");
|
||||
if (/^-?\d+(\.\d+)?$/.test(plain)) {
|
||||
const number = Number(plain);
|
||||
if (Number.isInteger(number)) return number.toLocaleString("en-GB");
|
||||
return number.toLocaleString("en-GB", { maximumFractionDigits: 2 });
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
columnClass(columnIndex, columns, rows) {
|
||||
const header = (columns[columnIndex] || "").toLowerCase();
|
||||
if (columnIndex === 0) {
|
||||
if (
|
||||
header.includes("username")
|
||||
|| header === "user"
|
||||
|| header.includes("instance")
|
||||
|| header === "name"
|
||||
) {
|
||||
return "statistics-col-name";
|
||||
}
|
||||
return "statistics-col-key";
|
||||
}
|
||||
if (this.columnIsNumeric(columnIndex, columns, rows)) return "statistics-col-num";
|
||||
return "statistics-col-text";
|
||||
}
|
||||
|
||||
renderBreakdownTable(table) {
|
||||
const columns = table.columns || [];
|
||||
const rows = table.rows || [];
|
||||
const panel = document.createElement("article");
|
||||
panel.className = "statistics-table-panel";
|
||||
if (columns.length > 2) panel.classList.add("is-wide");
|
||||
|
||||
const head = document.createElement("div");
|
||||
head.className = "statistics-table-panel-head";
|
||||
const title = document.createElement("h4");
|
||||
title.textContent = table.title || "";
|
||||
head.appendChild(title);
|
||||
const count = document.createElement("span");
|
||||
count.className = "statistics-table-panel-count";
|
||||
count.textContent = `${rows.length.toLocaleString("en-GB")} rows`;
|
||||
head.appendChild(count);
|
||||
panel.appendChild(head);
|
||||
|
||||
const wrap = document.createElement("div");
|
||||
wrap.className = "admin-table-wrap";
|
||||
|
||||
const node = document.createElement("table");
|
||||
node.className = "admin-table";
|
||||
|
||||
const thead = document.createElement("thead");
|
||||
const headRow = document.createElement("tr");
|
||||
for (let index = 0; index < columns.length; index += 1) {
|
||||
const th = document.createElement("th");
|
||||
th.className = this.columnClass(index, columns, rows);
|
||||
th.textContent = columns[index];
|
||||
headRow.appendChild(th);
|
||||
}
|
||||
thead.appendChild(headRow);
|
||||
node.appendChild(thead);
|
||||
|
||||
const tbody = document.createElement("tbody");
|
||||
for (const row of rows) {
|
||||
const tr = document.createElement("tr");
|
||||
for (let index = 0; index < columns.length; index += 1) {
|
||||
const td = document.createElement("td");
|
||||
const cellClass = this.columnClass(index, columns, rows);
|
||||
td.className = cellClass;
|
||||
const cell = row[index];
|
||||
td.textContent = cellClass === "statistics-col-num"
|
||||
? this.formatTableCell(cell)
|
||||
: String(cell ?? "");
|
||||
tr.appendChild(td);
|
||||
}
|
||||
tbody.appendChild(tr);
|
||||
}
|
||||
node.appendChild(tbody);
|
||||
wrap.appendChild(node);
|
||||
panel.appendChild(wrap);
|
||||
return panel;
|
||||
}
|
||||
|
||||
render(data) {
|
||||
if (!data) return;
|
||||
if (this.generated && data.generated_at) {
|
||||
this.generated.textContent = `Generated ${data.generated_at.replace("T", " ").slice(0, 19)} UTC`;
|
||||
}
|
||||
this.root.innerHTML = "";
|
||||
if (Array.isArray(data.highlights) && data.highlights.length) {
|
||||
const wrap = document.createElement("div");
|
||||
wrap.className = "metric-cards";
|
||||
for (const item of data.highlights) {
|
||||
const card = document.createElement("div");
|
||||
card.className = "metric-card";
|
||||
const value = document.createElement("span");
|
||||
value.className = "metric-value";
|
||||
value.textContent = String(item.value ?? "");
|
||||
const label = document.createElement("span");
|
||||
label.className = "metric-label";
|
||||
label.textContent = item.label || "";
|
||||
card.appendChild(value);
|
||||
card.appendChild(label);
|
||||
wrap.appendChild(card);
|
||||
}
|
||||
this.root.appendChild(wrap);
|
||||
}
|
||||
if (Array.isArray(data.cards) && data.cards.length) {
|
||||
const grid = document.createElement("div");
|
||||
grid.className = "metric-cards";
|
||||
for (const card of data.cards) {
|
||||
const node = document.createElement("div");
|
||||
node.className = "metric-card";
|
||||
const value = document.createElement("span");
|
||||
value.className = "metric-value";
|
||||
value.textContent = this.formatValue(card);
|
||||
const label = document.createElement("span");
|
||||
label.className = "metric-label";
|
||||
label.textContent = card.label || "";
|
||||
node.appendChild(value);
|
||||
node.appendChild(label);
|
||||
const delta = this.deltaMarkup(card);
|
||||
if (delta) node.appendChild(delta);
|
||||
grid.appendChild(node);
|
||||
}
|
||||
this.root.appendChild(grid);
|
||||
}
|
||||
if (Array.isArray(data.series) && data.series.length) {
|
||||
const section = document.createElement("div");
|
||||
section.className = "statistics-section";
|
||||
const heading = document.createElement("h3");
|
||||
heading.textContent = "Trends";
|
||||
section.appendChild(heading);
|
||||
const charts = document.createElement("div");
|
||||
charts.className = "statistics-charts";
|
||||
section.appendChild(charts);
|
||||
this.root.appendChild(section);
|
||||
const renderCharts = () => this.charts.render(charts, data.series);
|
||||
if (window.Chart) {
|
||||
renderCharts();
|
||||
} else {
|
||||
window.addEventListener("load", renderCharts, { once: true });
|
||||
}
|
||||
} else {
|
||||
this.charts.destroy();
|
||||
}
|
||||
if (Array.isArray(data.tables) && data.tables.length) {
|
||||
const section = document.createElement("div");
|
||||
section.className = "statistics-section statistics-breakdowns";
|
||||
const heading = document.createElement("h3");
|
||||
heading.textContent = "Breakdowns";
|
||||
section.appendChild(heading);
|
||||
const grid = document.createElement("div");
|
||||
grid.className = "statistics-breakdowns-grid";
|
||||
for (const table of data.tables) {
|
||||
grid.appendChild(this.renderBreakdownTable(table));
|
||||
}
|
||||
section.appendChild(grid);
|
||||
this.root.appendChild(section);
|
||||
}
|
||||
if (data.notes && data.notes.full_page) {
|
||||
const note = document.createElement("p");
|
||||
note.className = "statistics-note";
|
||||
const link = document.createElement("a");
|
||||
link.className = "statistics-link";
|
||||
link.href = data.notes.full_page;
|
||||
link.textContent = "Open full detail page";
|
||||
note.appendChild(link);
|
||||
this.root.appendChild(note);
|
||||
}
|
||||
if (data.notes && data.notes.retention_days) {
|
||||
const note = document.createElement("p");
|
||||
note.className = "statistics-note";
|
||||
note.textContent = `Visitor data retention: ${data.notes.retention_days} days.`;
|
||||
this.root.appendChild(note);
|
||||
window.addEventListener("load", draw, { once: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
window.StatisticsDashboard = StatisticsDashboard;
|
||||
export { StatisticsDashboard };
|
||||
@@ -0,0 +1,106 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
|
||||
import { Http } from "./Http.js";
|
||||
import { Poller } from "./Poller.js";
|
||||
import { escapeHtml } from "./ContainerFormControls.js";
|
||||
|
||||
const REFRESH_MS = 20000;
|
||||
const CELLS = ["status", "disk", "egress", "tunnels", "flags"];
|
||||
|
||||
export class WorkspaceList {
|
||||
constructor(root) {
|
||||
this.root = root;
|
||||
this.endpoint = root.dataset.endpoint;
|
||||
this.page = root.dataset.page || "1";
|
||||
this.body = document.getElementById("ws-admin-rows");
|
||||
}
|
||||
|
||||
init() {
|
||||
this.poller = new Poller(() => this.refresh(), REFRESH_MS, {
|
||||
immediate: false,
|
||||
pauseHidden: true,
|
||||
});
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
const data = await Http.getJson(`${this.endpoint}?page=${encodeURIComponent(this.page)}`);
|
||||
this.apply(data.workspaces || []);
|
||||
}
|
||||
|
||||
state(ws) {
|
||||
return ws.suspended ? "suspended" : ws.status;
|
||||
}
|
||||
|
||||
apply(workspaces) {
|
||||
if (!this.body) return;
|
||||
const rows = Array.from(this.body.querySelectorAll("tr[data-workspace-uid]"));
|
||||
const sameSet = rows.length === workspaces.length
|
||||
&& rows.every((row, index) => row.dataset.workspaceUid === workspaces[index].uid);
|
||||
if (!sameSet) {
|
||||
if (this.body.contains(document.activeElement)) return;
|
||||
this.body.innerHTML = workspaces.length
|
||||
? workspaces.map((ws) => this.row(ws)).join("")
|
||||
: `<tr><td colspan="11" class="admin-empty">No workspaces yet.</td></tr>`;
|
||||
return;
|
||||
}
|
||||
rows.forEach((row, index) => this.update(row, workspaces[index]));
|
||||
}
|
||||
|
||||
update(row, ws) {
|
||||
if (row.dataset.state !== this.state(ws)) {
|
||||
if (row.contains(document.activeElement)) return;
|
||||
row.outerHTML = this.row(ws);
|
||||
return;
|
||||
}
|
||||
const values = this.cells(ws);
|
||||
for (const name of CELLS) {
|
||||
const cell = row.querySelector(`[data-ws-cell="${name}"]`);
|
||||
if (cell && cell.innerHTML.trim() !== values[name]) cell.innerHTML = values[name];
|
||||
}
|
||||
}
|
||||
|
||||
cells(ws) {
|
||||
const status = ws.suspended
|
||||
? `<span class="workspace-badge workspace-badge-failed">suspended</span>`
|
||||
: `<span class="workspace-badge">${escapeHtml(ws.status)}</span>`;
|
||||
return {
|
||||
status,
|
||||
disk: `${escapeHtml(ws.disk_percent)}% of ${escapeHtml(ws.disk_quota_mb)} MB`,
|
||||
egress: `${escapeHtml(ws.egress_percent)}% of ${escapeHtml(ws.egress_quota_mb)} MB`,
|
||||
tunnels: String((ws.tunnels || []).length),
|
||||
flags: String((ws.flags || []).length),
|
||||
};
|
||||
}
|
||||
|
||||
actions(ws) {
|
||||
const uid = escapeHtml(ws.uid);
|
||||
const name = escapeHtml(ws.name);
|
||||
const power = ws.status === "running"
|
||||
? `<form method="post" action="/admin/workspaces/${uid}/stop"><button type="submit" class="admin-btn" aria-label="Stop ${name}">Stop</button></form>`
|
||||
: `<form method="post" action="/admin/workspaces/${uid}/start"><button type="submit" class="admin-btn" aria-label="Start ${name}">Start</button></form>`;
|
||||
const suspend = ws.suspended
|
||||
? `<form method="post" action="/admin/workspaces/${uid}/unsuspend"><button type="submit" class="admin-btn" aria-label="Unsuspend ${name}">Unsuspend</button></form>`
|
||||
: `<form method="post" action="/admin/workspaces/${uid}/suspend"><input type="text" name="reason" placeholder="Reason" maxlength="500" required aria-label="Suspend reason for ${name}"><button type="submit" class="admin-btn" aria-label="Suspend ${name}">Suspend</button></form>`;
|
||||
const flag = `<form method="post" action="/admin/workspaces/${uid}/flag"><input type="text" name="detail" placeholder="Flag detail" maxlength="500" aria-label="Flag detail for ${name}"><button type="submit" class="admin-btn" aria-label="Flag ${name}">Flag</button></form>`;
|
||||
const remove = `<form method="post" action="/admin/workspaces/${uid}/delete"><button type="submit" data-confirm="Delete this workspace?" data-confirm-danger class="admin-btn admin-btn-danger" aria-label="Delete ${name}">Delete</button></form>`;
|
||||
return power + suspend + flag + remove;
|
||||
}
|
||||
|
||||
row(ws) {
|
||||
const editor = ws.editor || {};
|
||||
const values = this.cells(ws);
|
||||
return `<tr data-workspace-uid="${escapeHtml(ws.uid)}" data-state="${escapeHtml(this.state(ws))}">
|
||||
<td>${escapeHtml(ws.name)}</td>
|
||||
<td>${escapeHtml(ws.owner_username || "")}</td>
|
||||
<td>${escapeHtml(ws.project_title || "")}</td>
|
||||
<td data-ws-cell="status">${values.status}</td>
|
||||
<td data-ws-cell="disk">${values.disk}</td>
|
||||
<td data-ws-cell="egress">${values.egress}</td>
|
||||
<td>${escapeHtml(editor.cpu_cores)} CPU / ${escapeHtml(editor.memory_mb)} MB</td>
|
||||
<td>${escapeHtml(editor.theme)} / ${escapeHtml(editor.layout)}</td>
|
||||
<td data-ws-cell="tunnels">${values.tunnels}</td>
|
||||
<td data-ws-cell="flags">${values.flags}</td>
|
||||
<td class="admin-actions">${this.actions(ws)}</td>
|
||||
</tr>`;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,10 @@ This file documents CDN libraries, the emoji picker, the modal system, and share
|
||||
- Templates extend `base.html`, add page CSS via `{% block extra_head %}`, page JS via `{% block extra_js %}`.
|
||||
- **Nav active state is the `nav_active` Jinja global**, never an inline path check. `nav_active(request, *prefixes, exact=False)` (`templating.py`) returns `"active"` (or `""`) when `request.url.path` equals a prefix or is a sub-path of it (`exact=True` matches only the exact path, e.g. the admin Dashboard root). Every topnav/sidebar link uses it (`class="topnav-link {{ nav_active(request, '/projects') }}"`); do NOT hand-write `{% if request.url.path == ... or request.url.path.startswith(...) %}active{% endif %}`.
|
||||
|
||||
## Admin templates
|
||||
|
||||
Admin templates extend `admin_base.html` and follow `devplacepy/routers/admin/CLAUDE.md`: server-rendered content (never a "Loading..." placeholder), `<h2>` inside `.admin-toolbar`, `admin-*` classes only (never `btn`, `empty-state`, `hint-text`, `<h1>`), `local_dt` for instants, `<caption class="sr-only">` and `scope="col"` on tables, the `_admin_cap_note.html` partial (`_shown`, `_total`) beside any capped list, and no hand-written nav links: the sidebar in `admin_base.html` and the phone menu in `base.html` both loop over the `admin_sections` global.
|
||||
|
||||
## CDN Libraries
|
||||
|
||||
Loaded via `<script>` tags in `base.html`. ALL must use `defer` to avoid blocking DOMContentLoaded:
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
<div class="backups-section" data-live="storage">
|
||||
<h3>Storage</h3>
|
||||
{% set disk = storage.get('disk') or {} %}
|
||||
{% set totals = storage.get('backups_total') or {} %}
|
||||
{% set datadir = storage.get('data_dir') or {} %}
|
||||
<div class="metric-cards">
|
||||
<div class="metric-card"><span class="metric-value">{{ disk.get('used_human') or '0' }} / {{ disk.get('total_human') or '0' }}</span><span class="metric-label">Disk used</span></div>
|
||||
<div class="metric-card"><span class="metric-value">{{ disk.get('free_human') or '0' }}</span><span class="metric-label">Disk free</span></div>
|
||||
<div class="metric-card"><span class="metric-value">{{ disk.get('used_percent') or 0 }}%</span><span class="metric-label">Disk usage</span></div>
|
||||
<div class="metric-card"><span class="metric-value">{{ datadir.get('size_human') or '0' }}</span><span class="metric-label">Data directory</span></div>
|
||||
<div class="metric-card"><span class="metric-value">{{ totals.get('count') or 0 }}</span><span class="metric-label">Backups stored</span></div>
|
||||
<div class="metric-card"><span class="metric-value">{{ totals.get('size_human') or '0' }}</span><span class="metric-label">Backups size</span></div>
|
||||
</div>
|
||||
<div class="admin-table-wrap">
|
||||
<table class="admin-table metric-table">
|
||||
<caption class="sr-only">Storage paths</caption>
|
||||
<thead><tr><th scope="col">Path</th><th scope="col">Size</th><th scope="col">Files</th><th scope="col">Location</th></tr></thead>
|
||||
<tbody>
|
||||
{% for path in storage.get('paths') or [] %}
|
||||
<tr>
|
||||
<td>{{ path.label }}</td>
|
||||
<td>{{ path.size_human }}</td>
|
||||
<td>{{ path.file_count }}</td>
|
||||
<td class="backups-path{% if not path.exists %} backups-missing{% endif %}">{{ path.path }}</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="4" class="admin-empty">No storage paths.</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="backups-section" data-live="backups">
|
||||
<h3>Backups</h3>
|
||||
<div class="metric-cards">
|
||||
<div class="metric-card"><span class="metric-value">{{ metrics.total or 0 }}</span><span class="metric-label">Total</span></div>
|
||||
<div class="metric-card"><span class="metric-value">{{ metrics.done or 0 }}</span><span class="metric-label">Done</span></div>
|
||||
<div class="metric-card"><span class="metric-value">{{ metrics.running or 0 }}</span><span class="metric-label">Running</span></div>
|
||||
<div class="metric-card"><span class="metric-value">{{ metrics.pending or 0 }}</span><span class="metric-label">Pending</span></div>
|
||||
<div class="metric-card"><span class="metric-value">{{ metrics.failed or 0 }}</span><span class="metric-label">Failed</span></div>
|
||||
<div class="metric-card"><span class="metric-value">{{ metrics.size_human or '0' }}</span><span class="metric-label">Archive size</span></div>
|
||||
</div>
|
||||
{% if backups %}
|
||||
<div class="admin-table-wrap">
|
||||
<table class="admin-table metric-table backups-table">
|
||||
<caption class="sr-only">Backup archives</caption>
|
||||
<thead><tr><th scope="col">Created</th><th scope="col">Target</th><th scope="col">Status</th><th scope="col">Size</th><th scope="col">Files</th><th scope="col">Checksum</th><th scope="col">Actions</th></tr></thead>
|
||||
<tbody>
|
||||
{% for backup in backups %}
|
||||
<tr>
|
||||
<td>{{ local_dt(backup.created_at) }}</td>
|
||||
<td>{{ backup.label or backup.target }}</td>
|
||||
<td><span class="backups-status backups-status-{{ backup.status }}">{{ backup.status }}</span></td>
|
||||
<td>{{ backup.size_human or '-' }}</td>
|
||||
<td>{{ backup.file_count or 0 }}</td>
|
||||
<td class="backups-sha">{{ backup.sha256[:12] if backup.sha256 else '-' }}</td>
|
||||
<td class="backups-actions">
|
||||
{% if backup.status == 'done' %}
|
||||
{% if can_download_backups %}
|
||||
<a class="admin-btn admin-btn-sm" href="/admin/backups/{{ backup.uid }}/download" aria-label="Download backup {{ backup.filename }}">Download</a>
|
||||
{% else %}
|
||||
<button type="button" class="admin-btn admin-btn-sm" disabled aria-disabled="true" title="Not available" aria-label="Download backup {{ backup.filename }} (not available)">Download</button>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
<button type="button" class="admin-btn admin-btn-sm admin-btn-danger" data-action="delete-backup" data-uid="{{ backup.uid }}" aria-label="Delete backup {{ backup.filename }}">Delete</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% set _shown = backups|length %}{% set _total = backups_total %}{% include "_admin_cap_note.html" %}
|
||||
{% else %}
|
||||
<p class="admin-empty">No backups yet.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="backups-section" data-live="schedules">
|
||||
<h3>Schedules</h3>
|
||||
{% if schedules %}
|
||||
<div class="admin-table-wrap">
|
||||
<table class="admin-table metric-table backups-schedules">
|
||||
<caption class="sr-only">Backup schedules</caption>
|
||||
<thead><tr><th scope="col">Name</th><th scope="col">Target</th><th scope="col">Trigger</th><th scope="col">Keep</th><th scope="col">Next run</th><th scope="col">Last run</th><th scope="col">Runs</th><th scope="col">State</th><th scope="col">Actions</th></tr></thead>
|
||||
<tbody>
|
||||
{% for schedule in schedules %}
|
||||
<tr>
|
||||
<td>{{ schedule.name }}</td>
|
||||
<td>{{ schedule.target }}</td>
|
||||
<td>{% if schedule.kind == 'cron' %}cron {{ schedule.cron }}{% else %}every {{ schedule.every_seconds }}s{% endif %}</td>
|
||||
<td>{{ schedule.keep_last or 'all' }}</td>
|
||||
<td>{% if schedule.next_run_at %}{{ local_dt(schedule.next_run_at) }}{% else %}-{% endif %}</td>
|
||||
<td>{% if schedule.last_run_at %}{{ local_dt(schedule.last_run_at) }}{% else %}-{% endif %}</td>
|
||||
<td>{{ schedule.run_count or 0 }}</td>
|
||||
<td><span class="backups-status backups-status-{{ 'done' if schedule.enabled else 'failed' }}">{{ 'enabled' if schedule.enabled else 'disabled' }}</span></td>
|
||||
<td class="backups-actions">
|
||||
<button type="button" class="admin-btn admin-btn-sm" data-action="run-schedule" data-uid="{{ schedule.uid }}" aria-label="Run schedule {{ schedule.name }}">Run</button>
|
||||
<button type="button" class="admin-btn admin-btn-sm" data-action="edit-schedule" data-uid="{{ schedule.uid }}" data-schedule="{{ {'uid': schedule.uid, 'name': schedule.name, 'target': schedule.target, 'kind': schedule.kind, 'every_seconds': schedule.every_seconds, 'cron': schedule.cron, 'keep_last': schedule.keep_last} | tojson | forceescape }}" aria-label="Edit schedule {{ schedule.name }}">Edit</button>
|
||||
<button type="button" class="admin-btn admin-btn-sm" data-action="toggle-schedule" data-uid="{{ schedule.uid }}" aria-label="{{ 'Disable' if schedule.enabled else 'Enable' }} schedule {{ schedule.name }}">{{ 'Disable' if schedule.enabled else 'Enable' }}</button>
|
||||
<button type="button" class="admin-btn admin-btn-sm admin-btn-danger" data-action="delete-schedule" data-uid="{{ schedule.uid }}" aria-label="Delete schedule {{ schedule.name }}">Delete</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="admin-empty">No backup schedules configured.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
@@ -0,0 +1 @@
|
||||
{% if _total > _shown %}<p class="admin-cap-note" role="status">Showing {{ _shown }} of {{ _total }}. Narrow the list to see the rest.</p>{% endif %}
|
||||
@@ -0,0 +1,181 @@
|
||||
{% macro integer(value) %}{{ "{:,}".format((value or 0) | int) }}{% endmacro %}
|
||||
{% macro money(value) %}{% set number = (value or 0) | float %}{% if number < 1 %}${{ "%.6f" | format(number) }}{% else %}${{ "%.2f" | format(number) }}{% endif %}{% endmacro %}
|
||||
{% macro percent(value, scale=1) %}{{ "%.1f" | format((value or 0) | float * scale) }}%{% endmacro %}
|
||||
{% macro optional(value) %}{% if value is none %}n/a{% else %}{{ value }}{% endif %}{% endmacro %}
|
||||
{% macro cards(items) %}
|
||||
<div class="metric-cards">
|
||||
{% for item in items %}
|
||||
<div class="metric-card"><span class="metric-value">{{ item[1] }}</span><span class="metric-label">{{ item[0] }}</span></div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endmacro %}
|
||||
{% macro group_table(title, label, items) %}
|
||||
<div class="ai-usage-section">
|
||||
<h3>{{ title }}</h3>
|
||||
<table class="metric-table">
|
||||
<caption class="sr-only">{{ title }}</caption>
|
||||
<thead><tr><th scope="col">{{ label }}</th><th scope="col">Requests</th><th scope="col">Tokens</th><th scope="col">Cost</th></tr></thead>
|
||||
<tbody>
|
||||
{% for item in items or [] %}
|
||||
<tr><td>{{ item.key }}</td><td>{{ integer(item.requests) }}</td><td>{{ integer(item.total_tokens) }}</td><td>{{ money(item.cost_usd) }}</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% endmacro %}
|
||||
{% macro pset_grid(title, sets) %}
|
||||
<div class="ai-usage-section">
|
||||
<h3>{{ title }}</h3>
|
||||
<div class="ai-usage-grid">
|
||||
{% for label, pset in sets %}
|
||||
<div>
|
||||
<h3>{{ label }}</h3>
|
||||
<table class="metric-table pset-table">
|
||||
<caption class="sr-only">{{ label }}</caption>
|
||||
<thead><tr><th scope="col">stat</th><th scope="col">value</th></tr></thead>
|
||||
<tbody>
|
||||
{% for stat in ["avg", "p50", "p90", "p95", "p99", "max"] %}
|
||||
<tr><td>{{ stat }}</td><td>{{ integer(pset[stat]) }}</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
{% endmacro %}
|
||||
<p class="ai-usage-generated" role="status">Window: {% if usage.window_hours %}{{ usage.window_hours }}h{% else %}all time{% endif %}, updated {{ local_dt(usage.generated_at) }}</p>
|
||||
{% if not usage.requests %}
|
||||
<p class="admin-empty">No AI gateway traffic recorded in this window yet.</p>
|
||||
{% else %}
|
||||
{% set v = usage.volume %}{% set t = usage.tokens %}{% set l = usage.latency %}{% set e = usage.errors %}{% set c = usage.cost %}{% set b = usage.behavior %}{% set conc = v.concurrency or {} %}{% set rpc = b.requests_per_caller or {} %}
|
||||
<div class="ai-usage-section">
|
||||
<h3>Overview</h3>
|
||||
{{ cards([
|
||||
("Requests", integer(v.requests)),
|
||||
("Success", percent(v.success / v.requests if v.requests else 0, 100)),
|
||||
("Error rate", e.error_rate_pct ~ "%"),
|
||||
("Requests / hour", integer(v.requests_per_hour)),
|
||||
("Peak req / min", integer(v.peak_requests_per_minute)),
|
||||
("Cost (window)", money(c.total_usd)),
|
||||
("Cost this hour", money(c.this_hour_usd)),
|
||||
("Cost 24h", money(c.last_24h_usd)),
|
||||
("Projected / month", money(c.projected_monthly_usd)),
|
||||
("Tokens total", integer(t.total)),
|
||||
("Upstream avail.", l.upstream_availability_pct ~ "%"),
|
||||
("Concurrency peak", integer(conc.peak)),
|
||||
]) }}
|
||||
</div>
|
||||
<div class="ai-usage-section">
|
||||
<h3>Tokens</h3>
|
||||
{{ cards([
|
||||
("Prompt total", integer(t.prompt_total)),
|
||||
("Completion total", integer(t.completion_total)),
|
||||
("Total", integer(t.total)),
|
||||
("Cache hit rate", percent(t.cache_hit_rate, 100)),
|
||||
("Input:output", t.input_output_ratio),
|
||||
("Cache hit tokens", integer(t.cache_hit_total)),
|
||||
("Cache miss tokens", integer(t.cache_miss_total)),
|
||||
("Reasoning tokens", integer(t.reasoning_total)),
|
||||
("Tokens / hour", integer(t.tokens_per_hour)),
|
||||
("Context util avg", "n/a" if t.context_utilization_avg is none else percent(t.context_utilization_avg, 100)),
|
||||
]) }}
|
||||
</div>
|
||||
{{ pset_grid("Token distribution per request", [("Prompt tokens", t.prompt or {}), ("Completion tokens", t.completion or {}), ("Total tokens", t.total_per_request or {})]) }}
|
||||
<div class="ai-usage-section">
|
||||
<h3>Latency and throughput</h3>
|
||||
{{ cards([
|
||||
("Upstream availability", l.upstream_availability_pct ~ "%"),
|
||||
("Gateway overhead share", percent(l.gateway_overhead_share, 100)),
|
||||
("TTFT", "n/a (non-streaming)"),
|
||||
("Inter-token", "n/a (non-streaming)"),
|
||||
]) }}
|
||||
</div>
|
||||
{{ pset_grid("Latency percentiles (ms)", [("Upstream round-trip", l.upstream_ms or {}), ("Gateway overhead", l.gateway_overhead_ms or {}), ("Queue wait", l.queue_wait_ms or {}), ("Connection establish", l.connect_ms or {}), ("Total", l.total_ms or {}), ("Tokens / second", l.tokens_per_second or {})]) }}
|
||||
<div class="ai-usage-section">
|
||||
<h3>Errors and reliability</h3>
|
||||
{{ cards([
|
||||
("Total errors", integer(e.total)),
|
||||
("Error rate", e.error_rate_pct ~ "%"),
|
||||
("4xx", integer(e.count_4xx)),
|
||||
("5xx", integer(e.count_5xx)),
|
||||
("Timeouts", integer(e.timeouts)),
|
||||
("Retries attempted", integer(e.retries_attempted)),
|
||||
("Retries succeeded", integer(e.retries_succeeded)),
|
||||
("Circuit opens", integer(e.circuit_open_events)),
|
||||
]) }}
|
||||
<table class="metric-table">
|
||||
<caption class="sr-only">Errors by category</caption>
|
||||
<thead><tr><th scope="col">Error category</th><th scope="col">Count</th></tr></thead>
|
||||
<tbody>
|
||||
{% for name, count in (e.by_category or {}).items() %}
|
||||
<tr><td>{{ name }}</td><td>{{ integer(count) }}</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="ai-usage-section">
|
||||
<h3>Cost</h3>
|
||||
{{ cards([
|
||||
("Total", money(c.total_usd)),
|
||||
("Input cost", money(c.input_usd)),
|
||||
("Output cost", money(c.output_usd)),
|
||||
("Per 1k tokens", money(c.effective_per_1k_tokens_usd)),
|
||||
("Caching savings", money(c.caching_savings_usd)),
|
||||
("This hour", money(c.this_hour_usd)),
|
||||
("Last 24h", money(c.last_24h_usd)),
|
||||
("Projected / month", money(c.projected_monthly_usd)),
|
||||
]) }}
|
||||
</div>
|
||||
<div class="ai-usage-section">
|
||||
<h3>Behavior</h3>
|
||||
{{ cards([
|
||||
("Unique callers", integer(b.unique_callers)),
|
||||
("Req / caller avg", integer(rpc.avg)),
|
||||
("Req / caller p95", integer(rpc.p95)),
|
||||
("Heaviest caller", integer(rpc.max)),
|
||||
("Avg temperature", optional(b.avg_temperature)),
|
||||
("Avg top_p", optional(b.avg_top_p)),
|
||||
("Tool calls", integer(b.tool_call_requests)),
|
||||
("Streaming", integer(b.streaming_requests)),
|
||||
("Non-streaming", integer(b.non_streaming_requests)),
|
||||
]) }}
|
||||
</div>
|
||||
<div class="ai-divided">
|
||||
{{ group_table("By model", "Model", v.by_model) }}
|
||||
{{ group_table("By endpoint", "Endpoint", v.by_endpoint) }}
|
||||
{{ group_table("By backend", "Backend", v.by_backend) }}
|
||||
{{ group_table("By caller", "Caller", v.by_caller) }}
|
||||
<div class="ai-usage-section">
|
||||
<h3>User agents</h3>
|
||||
<table class="metric-table">
|
||||
<caption class="sr-only">User agents</caption>
|
||||
<thead><tr><th scope="col">User agent</th><th scope="col">Requests</th></tr></thead>
|
||||
<tbody>
|
||||
{% for item in b.user_agents or [] %}
|
||||
<tr><td>{{ item.key }}</td><td>{{ integer(item.requests) }}</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div class="ai-usage-section">
|
||||
<h3>Hourly breakdown</h3>
|
||||
<div class="admin-table-wrap">
|
||||
<table class="metric-table">
|
||||
<caption class="sr-only">Hourly breakdown</caption>
|
||||
<thead><tr><th scope="col">Hour</th><th scope="col">Requests</th><th scope="col">OK</th><th scope="col">Failed</th><th scope="col">Prompt</th><th scope="col">Completion</th><th scope="col">Total</th><th scope="col">Cost</th><th scope="col">Avg ms</th><th scope="col">Callers</th><th scope="col">New</th></tr></thead>
|
||||
<tbody>
|
||||
{% for h in usage.hourly or [] %}
|
||||
<tr>
|
||||
<td>{{ local_dt(h.hour ~ ":00:00+00:00") }}</td>
|
||||
<td>{{ integer(h.requests) }}</td><td>{{ integer(h.success) }}</td><td>{{ integer(h.failed) }}</td>
|
||||
<td>{{ integer(h.prompt_tokens) }}</td><td>{{ integer(h.completion_tokens) }}</td><td>{{ integer(h.total_tokens) }}</td>
|
||||
<td>{{ money(h.cost_usd) }}</td><td>{{ integer(h.avg_latency_ms) }}</td><td>{{ integer(h.active_owners) }}</td><td>{{ integer(h.new_owners) }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
@@ -0,0 +1,6 @@
|
||||
{% from "_gateway_stats_summary.html" import tiles, model_rows, failure_rows with context %}
|
||||
<div data-slot="tiles">{{ tiles() }}</div>
|
||||
<table><tbody data-slot="models">{{ model_rows() }}</tbody></table>
|
||||
<table><tbody data-slot="failures">{{ failure_rows() }}</tbody></table>
|
||||
<div data-slot="note">{% set _shown = stats_table_models|length %}{% set _total = stats_table_models_total %}{% include "_admin_cap_note.html" %}</div>
|
||||
<script type="application/json" id="gw-stats-initial">{{ stats | tojson }}</script>
|
||||
@@ -0,0 +1,44 @@
|
||||
{% macro percent(success, total) %}{% if total %}{{ "%.1f" | format(success / total * 100) }}%{% else %}-{% endif %}{% endmacro %}
|
||||
{% macro ms(value) %}{% if value is none %}-{% else %}{{ value | round | int }}ms{% endif %}{% endmacro %}
|
||||
{% macro dash(value) %}{% if value is none or value == "" %}-{% else %}{{ value }}{% endif %}{% endmacro %}
|
||||
{% macro tiles() %}
|
||||
{% set total = (stats.totals.success or 0) + (stats.totals.error or 0) %}
|
||||
<div class="gw-tile"><div class="gw-tile-label">Total requests</div><div class="gw-tile-value" id="gw-stat-total-requests">{{ total }}</div></div>
|
||||
<div class="gw-tile"><div class="gw-tile-label">Success rate</div><div class="gw-tile-value" id="gw-stat-success-rate">{{ percent(stats.totals.success or 0, total) }}</div></div>
|
||||
<div class="gw-tile"><div class="gw-tile-label">Models tracked</div><div class="gw-tile-value" id="gw-stat-models-tracked">{{ stats_table_models_total }}</div></div>
|
||||
<div class="gw-tile"><div class="gw-tile-label">Last updated</div><div class="gw-tile-value" id="gw-stat-generated-at">{{ local_dt(stats_generated_iso, "ago") }}</div></div>
|
||||
{% endmacro %}
|
||||
{% macro model_rows() %}
|
||||
{% for row in stats_table_models %}
|
||||
{% set health = row.health or {} %}
|
||||
<tr>
|
||||
<td>{{ row.model }}</td>
|
||||
<td>{{ row.provider }}</td>
|
||||
<td>{{ row.total_requests }}</td>
|
||||
<td>{{ percent(row.success_requests, row.total_requests) }}</td>
|
||||
<td>{{ ms(row.avg_latency_ms) }}</td>
|
||||
<td>{{ dash(row.avg_tokens_per_second) }}</td>
|
||||
<td>{{ dash(health.weight) }}</td>
|
||||
<td>{% if health.circuit_open %}open{% else %}closed{% endif %}</td>
|
||||
<td>{{ row.prompt_tokens }}</td>
|
||||
<td>{{ row.completion_tokens }}</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="10" class="admin-empty">No requests in this range.</td></tr>
|
||||
{% endfor %}
|
||||
{% endmacro %}
|
||||
{% macro failure_rows() %}
|
||||
{% for row in stats.recent_failures %}
|
||||
<tr>
|
||||
<td>{{ local_dt(row.created_at) }}</td>
|
||||
<td>{{ dash(row.model) }}</td>
|
||||
<td>{{ dash(row.provider) }}</td>
|
||||
<td>{{ dash(row.endpoint) }}</td>
|
||||
<td>{{ dash(row.status_code) }}</td>
|
||||
<td>{{ dash(row.reason) }}</td>
|
||||
<td>{{ row.fallback_used_route or "no fallback" }}</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="7" class="admin-empty">No failures in this range.</td></tr>
|
||||
{% endfor %}
|
||||
{% endmacro %}
|
||||
@@ -0,0 +1,19 @@
|
||||
{% if _metrics %}
|
||||
{% if _metrics.stats %}
|
||||
<div class="metric-cards">
|
||||
{% for stat in _metrics.stats %}
|
||||
<div class="metric-card"><span class="metric-value">{{ stat.value }}</span><span class="metric-label">{{ stat.label }}</span></div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if _metrics.table and _metrics.table.rows %}
|
||||
<table class="metric-table">
|
||||
<thead><tr>{% for col in _metrics.table.columns or [] %}<th>{{ col }}</th>{% endfor %}</tr></thead>
|
||||
<tbody>
|
||||
{% for row in _metrics.table.rows %}
|
||||
<tr>{% for cell in row %}<td>{% if cell is mapping and cell.href %}<a class="metric-link" href="{{ cell.href }}">{% if cell.avatar %}<dp-avatar username="{{ cell.avatar }}" size="20"></dp-avatar>{% endif %}{{ cell.text }}</a>{% else %}{{ cell }}{% endif %}</td>{% endfor %}</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
@@ -91,7 +91,7 @@
|
||||
<tbody>
|
||||
{% for e in entries %}
|
||||
<tr>
|
||||
<td title="{{ format_date(e['created_at'], include_time=True) }}">{{ dt_ago(e.created_at) if e.created_at else e.get('time_ago', '') }}</td>
|
||||
<td>{{ dt_ago(e.created_at) if e.created_at else e.get('time_ago', '') }}</td>
|
||||
<td><span class="audit-badge">{{ e['event_key'] }}</span></td>
|
||||
<td>
|
||||
{% if e.get('actor_user') %}
|
||||
|
||||
@@ -19,12 +19,12 @@
|
||||
<button type="submit" class="admin-btn admin-btn-primary"><span class="icon">💾</span> Create backup</button>
|
||||
</form>
|
||||
<a href="#" class="admin-btn admin-btn-sm" data-modal="backup-schedule-modal" id="backup-schedule-new"><span class="icon">🕑</span> New schedule</a>
|
||||
<span class="backup-generated" data-meta="generated" role="status" aria-live="polite" aria-label="Last generated">-</span>
|
||||
<span class="backup-generated" role="status" aria-label="Last generated">Updated {{ local_dt(generated_at) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="backups-root" class="backups" role="region" aria-label="Backup status" aria-live="polite">
|
||||
<p class="admin-empty" data-empty>Loading backup status...</p>
|
||||
<div id="backups-root" class="backups" role="region" aria-label="Backup status">
|
||||
{% include "_admin_backups_body.html" %}
|
||||
</div>
|
||||
|
||||
<div id="backup-schedule-modal" class="modal-overlay">
|
||||
@@ -67,8 +67,8 @@
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
<script type="module" src="{{ static_url('/static/js/BackupMonitor.js') }}"></script>
|
||||
<script type="module">
|
||||
new window.BackupMonitor().start();
|
||||
import { BackupMonitor } from "{{ static_url('/static/js/BackupMonitor.js') }}";
|
||||
new BackupMonitor().start();
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -8,66 +8,11 @@
|
||||
<aside class="sidebar-card">
|
||||
<div class="sidebar-heading">Admin Panel</div>
|
||||
<nav class="sidebar-nav" aria-label="Admin">
|
||||
<a href="/admin/users" class="sidebar-link {% if admin_section == 'users' %}active{% endif %}">
|
||||
<span class="sidebar-icon">👥</span> Users
|
||||
</a>
|
||||
<a href="/admin/news" class="sidebar-link {% if admin_section == 'news' %}active{% endif %}">
|
||||
<span class="sidebar-icon">📰</span> News
|
||||
</a>
|
||||
<a href="/admin/media" class="sidebar-link {% if admin_section == 'media' %}active{% endif %}">
|
||||
<span class="sidebar-icon">🖼️</span> Media
|
||||
</a>
|
||||
<a href="/admin/moderation" class="sidebar-link {% if admin_section == 'moderation' %}active{% endif %}">
|
||||
<span class="sidebar-icon">🚩</span> Moderation
|
||||
</a>
|
||||
<a href="/admin/trash" class="sidebar-link {% if admin_section == 'trash' %}active{% endif %}">
|
||||
<span class="sidebar-icon">🗑️</span> Trash
|
||||
</a>
|
||||
<a href="/admin/services" class="sidebar-link {% if admin_section == 'services' %}active{% endif %}">
|
||||
<span class="sidebar-icon">⚙️</span> Services
|
||||
</a>
|
||||
<a href="/admin/gateway" class="sidebar-link {% if admin_section == 'gateway' %}active{% endif %}">
|
||||
<span class="sidebar-icon">🔀</span> Gateway
|
||||
</a>
|
||||
<a href="/admin/containers" class="sidebar-link {% if admin_section == 'containers' %}active{% endif %}">
|
||||
<span class="sidebar-icon">📦</span> Containers
|
||||
</a>
|
||||
<a href="/admin/workspaces" class="sidebar-link {% if admin_section == 'workspaces' %}active{% endif %}">
|
||||
<span class="sidebar-icon">💻</span> Workspaces
|
||||
</a>
|
||||
<a href="/admin/devii-tasks" class="sidebar-link {% if admin_section == 'devii-tasks' %}active{% endif %}">
|
||||
<span class="sidebar-icon">⏰</span> Devii tasks
|
||||
</a>
|
||||
<a href="/admin/communities" class="sidebar-link {% if admin_section == 'communities' %}active{% endif %}">
|
||||
<span class="sidebar-icon">🌐</span> Communities
|
||||
</a>
|
||||
<a href="/admin/nodes" class="sidebar-link {% if admin_section == 'nodes' %}active{% endif %}">
|
||||
<span class="sidebar-icon">📡</span> Community nodes
|
||||
</a>
|
||||
<a href="/admin/bots" class="sidebar-link {% if admin_section == 'bots' %}active{% endif %}">
|
||||
<span class="sidebar-icon">🤖</span> Bot Monitor
|
||||
</a>
|
||||
<a href="/admin/game" class="sidebar-link {% if admin_section == 'game' %}active{% endif %}">
|
||||
<span class="sidebar-icon">🚜</span> Code Farm
|
||||
</a>
|
||||
<a href="/admin/ai-usage" class="sidebar-link {% if admin_section == 'ai-usage' %}active{% endif %}">
|
||||
<span class="sidebar-icon">📊</span> AI usage
|
||||
</a>
|
||||
<a href="/admin/statistics" class="sidebar-link {% if admin_section == 'statistics' %}active{% endif %}">
|
||||
<span class="sidebar-icon">📈</span> Statistics
|
||||
</a>
|
||||
<a href="/admin/audit-log" class="sidebar-link {% if admin_section == 'audit-log' %}active{% endif %}">
|
||||
<span class="sidebar-icon">📋</span> Audit Log
|
||||
</a>
|
||||
<a href="/admin/backups" class="sidebar-link {% if admin_section == 'backups' %}active{% endif %}">
|
||||
<span class="sidebar-icon">💾</span> Backups
|
||||
</a>
|
||||
<a href="/admin/notifications" class="sidebar-link {% if admin_section == 'notifications' %}active{% endif %}">
|
||||
<span class="sidebar-icon">🔔</span> Notifications
|
||||
</a>
|
||||
<a href="/admin/settings" class="sidebar-link {% if admin_section == 'settings' %}active{% endif %}">
|
||||
<span class="sidebar-icon">🔧</span> Settings
|
||||
{% for section in admin_sections %}
|
||||
<a href="{{ section.href }}" class="sidebar-link {% if admin_section == section.key %}active{% endif %}"{% if admin_section == section.key %} aria-current="page"{% endif %}>
|
||||
<span class="sidebar-icon" aria-hidden="true">{{ section.icon }}</span> {{ section.label }}
|
||||
</a>
|
||||
{% endfor %}
|
||||
</nav>
|
||||
</aside>
|
||||
<main class="admin-content">
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
{% block admin_content %}
|
||||
<div class="admin-toolbar">
|
||||
<h2>Communities</h2>
|
||||
<span class="admin-count">{{ items|length }}</span>
|
||||
<span class="admin-count">{{ pagination.total }}</span>
|
||||
</div>
|
||||
|
||||
{% if not sync_enabled %}
|
||||
@@ -74,4 +74,5 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% include "_pagination.html" %}
|
||||
{% endblock %}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
{% block admin_content %}
|
||||
<div class="admin-toolbar">
|
||||
<h2>Devii tasks</h2>
|
||||
<span class="admin-count">{{ items|length }} {{ state }}</span>
|
||||
<span class="admin-count">{{ pagination.total }} {{ state }}</span>
|
||||
</div>
|
||||
|
||||
<p class="admin-text-muted">
|
||||
@@ -24,6 +24,7 @@
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="admin-table-wrap">
|
||||
<table class="admin-table">
|
||||
<caption class="sr-only">Scheduled Devii tasks with disable and delete actions</caption>
|
||||
<thead>
|
||||
@@ -79,9 +80,12 @@
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="7" class="empty-state">No tasks.</td>
|
||||
<td colspan="7" class="admin-empty">No tasks.</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% set pagination_query = 'state=' ~ state ~ '&' %}
|
||||
{% include "_pagination.html" %}
|
||||
{% endblock %}
|
||||
|
||||
@@ -4,18 +4,18 @@
|
||||
<h2>Code Farm - Eras</h2>
|
||||
</div>
|
||||
|
||||
<p class="hint-text admin-settings-intro">Starting an Era snapshots a fresh visible leaderboard (coins/harvests this Era) for every farm. Real coin balances, prestige, stars, and Legacy/Mastery upgrades are never touched or reset. Ending an Era ranks farms by Era score, awards Stars to the top 10, and records the results permanently.</p>
|
||||
<p class="admin-hint admin-settings-intro">Starting an Era snapshots a fresh visible leaderboard (coins/harvests this Era) for every farm. Real coin balances, prestige, stars, and Legacy/Mastery upgrades are never touched or reset. Ending an Era ranks farms by Era score, awards Stars to the top 10, and records the results permanently.</p>
|
||||
|
||||
{% if era_active %}
|
||||
<div class="admin-field">
|
||||
<p><strong>Era {{ era_number }}: {{ era_name }}</strong> is running.</p>
|
||||
<p class="hint-text">Started {{ format_date(era_started_at, true) }}, scheduled to end {{ format_date(era_ends_at, true) }}.</p>
|
||||
<p class="admin-hint">Started {{ local_dt(era_started_at) }}, scheduled to end {{ local_dt(era_ends_at) }}.</p>
|
||||
</div>
|
||||
<form method="POST" action="/admin/game/era/end">
|
||||
<button type="submit" class="btn btn-danger" data-confirm="End the current Era now? This ranks every farm, awards Stars to the top 10, and resets the visible Era leaderboard. Real balances are never affected.">End Era</button>
|
||||
<button type="submit" class="admin-btn admin-btn-danger" data-confirm="End the current Era now? This ranks every farm, awards Stars to the top 10, and resets the visible Era leaderboard. Real balances are never affected.">End Era</button>
|
||||
</form>
|
||||
{% else %}
|
||||
<p class="hint-text">No Era is currently running. The Era leaderboard board and Era-exclusive crops stay dormant until one is started.</p>
|
||||
<p class="admin-hint">No Era is currently running. The Era leaderboard board and Era-exclusive crops stay dormant until one is started.</p>
|
||||
<form method="POST" action="/admin/game/era/start" class="admin-settings-form">
|
||||
<div class="admin-field">
|
||||
<label for="era-name">Era name</label>
|
||||
@@ -25,7 +25,7 @@
|
||||
<label for="era-duration">Duration (days)</label>
|
||||
<input type="number" id="era-duration" name="duration_days" min="1" max="180" value="28">
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary" data-confirm="Start a new Code Farm Era? This resets every farm's visible Era coins/harvests counters to zero (real coins and prestige are untouched).">Start Era</button>
|
||||
<button type="submit" class="admin-btn admin-btn-primary" data-confirm="Start a new Code Farm Era? This resets every farm's visible Era coins/harvests counters to zero (real coins and prestige are untouched).">Start Era</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
@@ -6,14 +6,14 @@
|
||||
{% block admin_content %}
|
||||
<div class="admin-toolbar">
|
||||
<h2>Gateway routing</h2>
|
||||
<span class="admin-count">{{ providers|length }} providers, {{ models|length }} routes, {{ quota_rules|length }} quota rules</span>
|
||||
<span class="admin-count">{{ providers_total }} providers, {{ models_total }} routes, {{ quota_rules_total }} quota rules</span>
|
||||
</div>
|
||||
<p class="gw-intro">Map any requested model name onto a provider and target model, each with its own pricing economy and an optional vision model for image to text merging. Image routes use a flat per-image price. Unmapped requests fall through to the default upstream unchanged.</p>
|
||||
|
||||
<nav class="admin-tabs" aria-label="Gateway configuration">
|
||||
<a href="/admin/gateway?tab=models" class="admin-tab {% if tab == 'models' %}active{% endif %}">Models <span class="admin-tab-count">{{ models|length }}</span></a>
|
||||
<a href="/admin/gateway?tab=providers" class="admin-tab {% if tab == 'providers' %}active{% endif %}">Providers <span class="admin-tab-count">{{ providers|length }}</span></a>
|
||||
<a href="/admin/gateway?tab=quota" class="admin-tab {% if tab == 'quota' %}active{% endif %}">Quota rules <span class="admin-tab-count">{{ quota_rules|length }}</span></a>
|
||||
<a href="/admin/gateway?tab=models" class="admin-tab {% if tab == 'models' %}active{% endif %}">Models <span class="admin-tab-count">{{ models_total }}</span></a>
|
||||
<a href="/admin/gateway?tab=providers" class="admin-tab {% if tab == 'providers' %}active{% endif %}">Providers <span class="admin-tab-count">{{ providers_total }}</span></a>
|
||||
<a href="/admin/gateway?tab=quota" class="admin-tab {% if tab == 'quota' %}active{% endif %}">Quota rules <span class="admin-tab-count">{{ quota_rules_total }}</span></a>
|
||||
<a href="/admin/gateway?tab=stats" class="admin-tab {% if tab == 'stats' %}active{% endif %}">Stats</a>
|
||||
</nav>
|
||||
|
||||
@@ -90,6 +90,7 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% set _shown = models|length %}{% set _total = models_total %}{% include "_admin_cap_note.html" %}
|
||||
{% if test_image %}
|
||||
<div id="gw-test-image-modal" class="modal-overlay visible">
|
||||
<div class="modal">
|
||||
@@ -149,6 +150,7 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% set _shown = providers|length %}{% set _total = providers_total %}{% include "_admin_cap_note.html" %}
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
@@ -198,46 +200,52 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% set _shown = quota_rules|length %}{% set _total = quota_rules_total %}{% include "_admin_cap_note.html" %}
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
{% if tab == 'stats' %}
|
||||
<section class="gw-section" id="gw-stats-panel" data-stats-root>
|
||||
{% from "_gateway_stats_summary.html" import tiles, model_rows, failure_rows with context %}
|
||||
<section class="gw-section" id="gw-stats-panel" data-stats-root data-fragment="/admin/gateway/stats/fragment" data-range="{{ stats_range }}">
|
||||
<div class="gw-stats-head">
|
||||
<p class="gw-section-hint" style="margin:0;">Request volume, latency, and per-model reliability, computed from the gateway usage ledger you already record - no separate data collection.</p>
|
||||
<select id="gw-stats-range">
|
||||
{% for r in stats_ranges %}
|
||||
<option value="{{ r }}" {% if r == '24h' %}selected{% endif %}>{{ r }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
<p class="gw-section-hint gw-section-hint-flush">Request volume, latency, and per-model reliability, computed from the gateway usage ledger you already record - no separate data collection.</p>
|
||||
<form method="GET" action="/admin/gateway" class="admin-inline-form" aria-label="Stats range">
|
||||
<input type="hidden" name="tab" value="stats">
|
||||
<select id="gw-stats-range" name="range" class="admin-select" aria-label="Range" data-auto-submit>
|
||||
{% for r in stats_ranges %}
|
||||
<option value="{{ r }}" {% if r == stats_range %}selected{% endif %}>{{ r }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
<noscript><button type="submit" class="admin-btn admin-btn-sm">Apply</button></noscript>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="gw-tiles">
|
||||
<div class="gw-tile"><div class="gw-tile-label">Total requests</div><div class="gw-tile-value" id="gw-stat-total-requests">-</div></div>
|
||||
<div class="gw-tile"><div class="gw-tile-label">Success rate</div><div class="gw-tile-value" id="gw-stat-success-rate">-</div></div>
|
||||
<div class="gw-tile"><div class="gw-tile-label">Models tracked</div><div class="gw-tile-value" id="gw-stat-models-tracked">-</div></div>
|
||||
<div class="gw-tile"><div class="gw-tile-label">Last updated</div><div class="gw-tile-value" id="gw-stat-generated-at">-</div></div>
|
||||
</div>
|
||||
<div class="gw-tiles" data-slot="tiles">{{ tiles() }}</div>
|
||||
|
||||
<div class="gw-charts-grid">
|
||||
<div class="gw-panel gw-wide"><h4>Requests over time</h4><div class="gw-chart-box"><canvas id="gw-chart-timeseries"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Success / failure</h4><div class="gw-chart-box"><canvas id="gw-chart-totals"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Requests by model</h4><div class="gw-chart-box"><canvas id="gw-chart-per-model"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Requests by endpoint</h4><div class="gw-chart-box"><canvas id="gw-chart-endpoints"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>HTTP status codes</h4><div class="gw-chart-box"><canvas id="gw-chart-status-codes"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Streaming vs non-streaming</h4><div class="gw-chart-box"><canvas id="gw-chart-streaming"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Top failure reasons</h4><div class="gw-chart-box"><canvas id="gw-chart-failure-reasons"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Requests by hour of day (UTC)</h4><div class="gw-chart-box"><canvas id="gw-chart-hourly"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Latency distribution</h4><div class="gw-chart-box"><canvas id="gw-chart-latency-hist"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Tokens/sec distribution</h4><div class="gw-chart-box"><canvas id="gw-chart-tps-hist"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Model reliability weight</h4><div class="gw-chart-box"><canvas id="gw-chart-weight"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Prompt vs completion tokens</h4><div class="gw-chart-box"><canvas id="gw-chart-tokens"></canvas></div></div>
|
||||
<div class="gw-panel gw-wide"><h4>Requests over time</h4><div class="gw-chart-box"><canvas id="gw-chart-timeseries" role="img" aria-label="Requests over time"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Success / failure</h4><div class="gw-chart-box"><canvas id="gw-chart-totals" role="img" aria-label="Success and failure"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Requests by model</h4><div class="gw-chart-box"><canvas id="gw-chart-per-model" role="img" aria-label="Requests by model"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Requests by endpoint</h4><div class="gw-chart-box"><canvas id="gw-chart-endpoints" role="img" aria-label="Requests by endpoint"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>HTTP status codes</h4><div class="gw-chart-box"><canvas id="gw-chart-status-codes" role="img" aria-label="HTTP status codes"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Streaming vs non-streaming</h4><div class="gw-chart-box"><canvas id="gw-chart-streaming" role="img" aria-label="Streaming split"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Top failure reasons</h4><div class="gw-chart-box"><canvas id="gw-chart-failure-reasons" role="img" aria-label="Top failure reasons"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Requests by hour of day (UTC)</h4><div class="gw-chart-box"><canvas id="gw-chart-hourly" role="img" aria-label="Requests by hour"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Latency distribution</h4><div class="gw-chart-box"><canvas id="gw-chart-latency-hist" role="img" aria-label="Latency distribution"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Tokens/sec distribution</h4><div class="gw-chart-box"><canvas id="gw-chart-tps-hist" role="img" aria-label="Tokens per second distribution"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Model reliability weight</h4><div class="gw-chart-box"><canvas id="gw-chart-weight" role="img" aria-label="Model reliability weight"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Prompt vs completion tokens</h4><div class="gw-chart-box"><canvas id="gw-chart-tokens" role="img" aria-label="Prompt and completion tokens"></canvas></div></div>
|
||||
</div>
|
||||
|
||||
<section class="gw-section">
|
||||
<div class="gw-section-head">
|
||||
<h3>Per-model detail</h3>
|
||||
<select id="gw-model-detail-select"><option value="">Select a model...</option></select>
|
||||
<select id="gw-model-detail-select" class="admin-select" aria-label="Model">
|
||||
<option value="">Select a model...</option>
|
||||
{% for entry in stats_models %}
|
||||
<option value="{{ entry.provider }}|{{ entry.model }}">{{ entry.model }} ({{ entry.provider }})</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div id="gw-model-detail-empty-state" class="gw-section-hint">Pick a model above to see its own timeseries and latency distribution.</div>
|
||||
<div id="gw-model-detail-charts" hidden>
|
||||
@@ -248,8 +256,8 @@
|
||||
<div class="gw-tile"><div class="gw-tile-label">Avg tokens/sec</div><div class="gw-tile-value" id="gw-model-detail-tps">-</div></div>
|
||||
</div>
|
||||
<div class="gw-charts-grid">
|
||||
<div class="gw-panel gw-wide"><h4>Requests over time</h4><div class="gw-chart-box"><canvas id="gw-chart-model-timeseries"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Latency distribution</h4><div class="gw-chart-box"><canvas id="gw-chart-model-latency-hist"></canvas></div></div>
|
||||
<div class="gw-panel gw-wide"><h4>Requests over time</h4><div class="gw-chart-box"><canvas id="gw-chart-model-timeseries" role="img" aria-label="Model requests over time"></canvas></div></div>
|
||||
<div class="gw-panel"><h4>Latency distribution</h4><div class="gw-chart-box"><canvas id="gw-chart-model-latency-hist" role="img" aria-label="Model latency distribution"></canvas></div></div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -262,11 +270,10 @@
|
||||
<thead>
|
||||
<tr><th scope="col">Model</th><th scope="col">Provider</th><th scope="col">Requests</th><th scope="col">Success</th><th scope="col">Avg latency</th><th scope="col">Avg tok/s</th><th scope="col">Weight</th><th scope="col">Circuit</th><th scope="col">Prompt tok</th><th scope="col">Completion tok</th></tr>
|
||||
</thead>
|
||||
<tbody id="gw-stats-model-table-body">
|
||||
<tr><td colspan="10" class="admin-empty">Loading...</td></tr>
|
||||
</tbody>
|
||||
<tbody id="gw-stats-model-table-body" data-slot="models">{{ model_rows() }}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div data-slot="note">{% set _shown = stats_table_models|length %}{% set _total = stats_table_models_total %}{% include "_admin_cap_note.html" %}</div>
|
||||
</section>
|
||||
|
||||
<section class="gw-section">
|
||||
@@ -277,18 +284,17 @@
|
||||
<thead>
|
||||
<tr><th scope="col">When</th><th scope="col">Model</th><th scope="col">Provider</th><th scope="col">Endpoint</th><th scope="col">Status</th><th scope="col">Reason</th><th scope="col">Fell back to</th></tr>
|
||||
</thead>
|
||||
<tbody id="gw-stats-failures-table-body">
|
||||
<tr><td colspan="7" class="admin-empty">Loading...</td></tr>
|
||||
</tbody>
|
||||
<tbody id="gw-stats-failures-table-body" data-slot="failures">{{ failure_rows() }}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
<script type="application/json" id="gw-stats-initial">{{ stats | tojson }}</script>
|
||||
</section>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
{% if tab == 'stats' %}
|
||||
<script src="{{ static_url('/static/js/vendor/chart.js') }}"></script>
|
||||
<script src="{{ static_url('/static/vendor/chartjs/chart.umd.min.js') }}" defer></script>
|
||||
<script type="module">
|
||||
import { GatewayStats } from "{{ static_url('/static/js/GatewayStats.js') }}";
|
||||
const gatewayStats = new GatewayStats(document.querySelector("[data-stats-root]"));
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
{% extends "admin_base.html" %}
|
||||
{% block extra_head %}
|
||||
<link rel="stylesheet" href="{{ static_url('/static/css/admin.css') }}">
|
||||
<link rel="stylesheet" href="{{ static_url('/static/css/sidebar.css') }}">
|
||||
{{ super() }}
|
||||
<link rel="stylesheet" href="{{ static_url('/static/css/planning.css') }}">
|
||||
{% endblock %}
|
||||
{% block admin_content %}
|
||||
<div class="admin-header planning-header">
|
||||
<h1>Ticket Planning</h1>
|
||||
<p class="planning-subtitle">Pick the open tickets to include, then generate a phased implementation document. Each selected ticket's full text is reproduced verbatim so the result can be handed straight to a coding agent.</p>
|
||||
<div class="admin-toolbar">
|
||||
<h2>Ticket Planning</h2>
|
||||
{% if tickets %}<span class="admin-count">{{ tickets|length }} open tickets</span>{% endif %}
|
||||
</div>
|
||||
<p class="planning-subtitle">Pick the open tickets to include, then generate a phased implementation document. Each selected ticket's full text is reproduced verbatim so the result can be handed straight to a coding agent.</p>
|
||||
|
||||
{% if not configured %}
|
||||
<div class="empty-state">The issue tracker is not configured yet. Configure Gitea in Services first.</div>
|
||||
<p class="admin-empty">The issue tracker is not configured yet. Configure Gitea in Services first.</p>
|
||||
{% elif tickets_error %}
|
||||
<div class="empty-state">Could not load the open tickets from the tracker. Try again shortly.</div>
|
||||
<p class="admin-empty">Could not load the open tickets from the tracker. Try again shortly.</p>
|
||||
{% elif not tickets %}
|
||||
<div class="empty-state">There are no open tickets to plan.</div>
|
||||
<p class="admin-empty">There are no open tickets to plan.</p>
|
||||
{% else %}
|
||||
<div class="planning-select" data-planning-select>
|
||||
<div class="planning-select-head">
|
||||
@@ -42,7 +42,7 @@
|
||||
{% endfor %}
|
||||
</ul>
|
||||
<div class="planning-select-foot">
|
||||
<button type="button" class="btn btn-primary" data-planning-generate data-action="/issues/planning">
|
||||
<button type="button" class="admin-btn admin-btn-primary" data-planning-generate data-action="/issues/planning">
|
||||
<span class="btn-spinner" aria-hidden="true"></span> Generate planning
|
||||
</button>
|
||||
<span class="planning-hint">A report covers only the tickets selected above.</span>
|
||||
@@ -50,9 +50,7 @@
|
||||
</div>
|
||||
|
||||
<div class="planning-output">
|
||||
<div class="empty-state" data-planning-empty>
|
||||
No planning generated yet. Select tickets and click "Generate planning".
|
||||
</div>
|
||||
<p class="admin-empty" data-planning-empty>No planning generated yet. Select tickets and click "Generate planning".</p>
|
||||
|
||||
<div class="planning-status" data-planning-status hidden role="status" aria-live="polite">
|
||||
<span class="planning-spinner" aria-hidden="true"></span>
|
||||
@@ -61,7 +59,7 @@
|
||||
|
||||
<div class="planning-result" data-planning-result hidden role="region" aria-label="Planning report">
|
||||
<div class="planning-actions">
|
||||
<a class="btn btn-secondary" data-planning-download href="#" download>Download markdown</a>
|
||||
<a class="admin-btn" data-planning-download href="#" download>Download markdown</a>
|
||||
<span class="planning-hint">Hover the report and use the Copy button to copy the markdown source.</span>
|
||||
</div>
|
||||
<dp-content class="planning-report" data-planning-report></dp-content>
|
||||
|
||||
@@ -35,7 +35,7 @@
|
||||
</div>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="empty-state">Trash is empty.</div>
|
||||
<div class="admin-empty">Trash is empty.</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
<button type="button" class="admin-tab overflow-tabs-more" aria-haspopup="menu" aria-label="More tabs" hidden><span class="icon">⋯</span> More</button>
|
||||
</nav>
|
||||
|
||||
<div class="admin-table-wrap">
|
||||
<table class="admin-table">
|
||||
<caption class="sr-only">Reported content awaiting a moderation decision</caption>
|
||||
<thead>
|
||||
@@ -51,11 +52,12 @@
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="7" class="empty-state">No reports in this state.</td>
|
||||
<td colspan="7" class="admin-empty">No reports in this state.</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{% set pagination_query = 'status=' ~ status ~ '&' %}{% include "_pagination.html" %}
|
||||
{% endblock %}
|
||||
|
||||
@@ -82,6 +82,7 @@
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% set _shown = flags|length %}{% set _total = flags_total %}{% include "_admin_cap_note.html" %}
|
||||
</div>
|
||||
|
||||
<h3 class="nodes-heading">Recent devices</h3>
|
||||
@@ -129,6 +130,7 @@
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% set _shown = devices|length %}{% set _total = devices_total %}{% include "_admin_cap_note.html" %}
|
||||
</div>
|
||||
|
||||
<h3 class="nodes-heading">Circuit breakers</h3>
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
<td>{{ local_dt(action['created_at']) }}</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
{% if empty %}<tr><td colspan="4" class="empty-state">{{ empty }}</td></tr>{% endif %}
|
||||
{% if empty %}<tr><td colspan="4" class="admin-empty">{{ empty }}</td></tr>{% endif %}
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -79,7 +79,7 @@
|
||||
<label for="decision-notes">Internal notes</label>
|
||||
<textarea id="decision-notes" name="notes" rows="3" maxlength="2000"></textarea>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary" data-confirm="Apply this moderation decision?">Apply decision</button>
|
||||
<button type="submit" class="admin-btn admin-btn-primary" data-confirm="Apply this moderation decision?">Apply decision</button>
|
||||
</form>
|
||||
<form method="POST" action="/admin/moderation/{{ report['uid'] }}/status" class="report-form-inline">
|
||||
<input type="hidden" name="status" value="acknowledged">
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<h2>Settings</h2>
|
||||
</div>
|
||||
|
||||
<p class="hint-text admin-settings-intro">Background service parameters (news fetching, intervals, AI grading) are configured per service on the <a href="/admin/services">Services</a> page.</p>
|
||||
<p class="admin-hint admin-settings-intro">Background service parameters (news fetching, intervals, AI grading) are configured per service on the <a href="/admin/services">Services</a> page.</p>
|
||||
|
||||
<form method="POST" action="/admin/settings" class="admin-settings-form">
|
||||
<h3 class="admin-settings-group-title">General</h3>
|
||||
@@ -43,19 +43,19 @@
|
||||
<div class="admin-field">
|
||||
<label for="max_upload_size_mb">Max Upload Size (MB)</label>
|
||||
<input type="number" id="max_upload_size_mb" name="max_upload_size_mb" value="{{ settings.get('max_upload_size_mb', '10') }}" min="1" max="500" class="admin-settings-num">
|
||||
<small class="hint-text">Maximum file size per upload in megabytes.</small>
|
||||
<small class="admin-hint">Maximum file size per upload in megabytes.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
<label for="allowed_file_types">Allowed File Types</label>
|
||||
<input type="text" id="allowed_file_types" name="allowed_file_types" value="{{ settings.get('allowed_file_types', '') }}" maxlength="1000" placeholder="e.g. .png,.jpg,.mp4,.webm (leave empty for default)">
|
||||
<small class="hint-text">Comma-separated list of allowed extensions. When set, this is the authoritative allowlist; any extension listed here is enabled and its type auto-detected. Leave empty to use the built-in defaults, which include common image and video formats (mp4, webm, ogv, mov, m4v).</small>
|
||||
<small class="admin-hint">Comma-separated list of allowed extensions. When set, this is the authoritative allowlist; any extension listed here is enabled and its type auto-detected. Leave empty to use the built-in defaults, which include common image and video formats (mp4, webm, ogv, mov, m4v).</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
<label for="max_attachments_per_resource">Max Attachments Per Resource</label>
|
||||
<input type="number" id="max_attachments_per_resource" name="max_attachments_per_resource" value="{{ settings.get('max_attachments_per_resource', '10') }}" min="1" max="50" class="admin-settings-num">
|
||||
<small class="hint-text">Maximum number of files that can be attached to a single post, comment, etc.</small>
|
||||
<small class="admin-hint">Maximum number of files that can be attached to a single post, comment, etc.</small>
|
||||
</div>
|
||||
|
||||
<hr class="admin-settings-divider">
|
||||
@@ -68,7 +68,7 @@
|
||||
<option value="agent" {% if settings.get('docs_search_mode', 'agent') == 'agent' %}selected{% endif %}>AI agent (conversational)</option>
|
||||
<option value="bm25" {% if settings.get('docs_search_mode', 'agent') == 'bm25' %}selected{% endif %}>Keyword (BM25)</option>
|
||||
</select>
|
||||
<small class="hint-text">AI agent renders the in-page Devii chat on the docs search page. Keyword uses the classic BM25 results list. Users who exceed their daily AI limit (or guests when Devii is disabled) fall back to keyword search automatically.</small>
|
||||
<small class="admin-hint">AI agent renders the in-page Devii chat on the docs search page. Keyword uses the classic BM25 results list. Users who exceed their daily AI limit (or guests when Devii is disabled) fall back to keyword search automatically.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
@@ -77,7 +77,7 @@
|
||||
<option value="1" {% if settings.get('registration_open', '1') == '1' %}selected{% endif %}>Open</option>
|
||||
<option value="0" {% if settings.get('registration_open', '1') != '1' %}selected{% endif %}>Closed</option>
|
||||
</select>
|
||||
<small class="hint-text">When closed, new account sign-ups are rejected.</small>
|
||||
<small class="admin-hint">When closed, new account sign-ups are rejected.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
@@ -86,13 +86,13 @@
|
||||
<option value="0" {% if settings.get('maintenance_mode', '0') != '1' %}selected{% endif %}>Disabled</option>
|
||||
<option value="1" {% if settings.get('maintenance_mode', '0') == '1' %}selected{% endif %}>Enabled</option>
|
||||
</select>
|
||||
<small class="hint-text">When enabled, non-admin visitors see the maintenance page. Admins retain full access.</small>
|
||||
<small class="admin-hint">When enabled, non-admin visitors see the maintenance page. Admins retain full access.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
<label for="maintenance_message">Maintenance Message</label>
|
||||
<input type="text" id="maintenance_message" name="maintenance_message" value="{{ settings.get('maintenance_message', 'DevPlace is undergoing scheduled maintenance. Please check back shortly.') }}" maxlength="300">
|
||||
<small class="hint-text">Shown to visitors while maintenance mode is enabled.</small>
|
||||
<small class="admin-hint">Shown to visitors while maintenance mode is enabled.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
@@ -101,7 +101,7 @@
|
||||
<option value="1" {% if settings.get('happy_404_enabled', '1') == '1' %}selected{% endif %}>Enabled</option>
|
||||
<option value="0" {% if settings.get('happy_404_enabled', '1') != '1' %}selected{% endif %}>Disabled</option>
|
||||
</select>
|
||||
<small class="hint-text">When enabled, a page that would otherwise 404 renders a random existing post instead. HTML requests only - JSON/API clients still get a real 404.</small>
|
||||
<small class="admin-hint">When enabled, a page that would otherwise 404 renders a random existing post instead. HTML requests only - JSON/API clients still get a real 404.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
@@ -110,43 +110,43 @@
|
||||
<option value="0" {% if settings.get('sync_enabled', '0') != '1' %}selected{% endif %}>Disabled</option>
|
||||
<option value="1" {% if settings.get('sync_enabled', '0') == '1' %}selected{% endif %}>Enabled</option>
|
||||
</select>
|
||||
<small class="hint-text">When enabled, administrators can copy users, posts and comments in from other communities through the <a href="/docs/sync.html">sync API</a>.</small>
|
||||
<small class="admin-hint">When enabled, administrators can copy users, posts and comments in from other communities through the <a href="/docs/sync.html">sync API</a>.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
<label for="sync_origins">Sync Origins</label>
|
||||
<input type="text" id="sync_origins" name="sync_origins" value="{{ settings.get('sync_origins', '') }}" maxlength="1000">
|
||||
<small class="hint-text">Comma separated origins allowed to sync, for example other.example.org. Leave empty to allow any origin.</small>
|
||||
<small class="admin-hint">Comma separated origins allowed to sync, for example other.example.org. Leave empty to allow any origin.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
<label for="rate_limit_per_minute">Rate Limit (requests)</label>
|
||||
<input type="number" id="rate_limit_per_minute" name="rate_limit_per_minute" value="{{ settings.get('rate_limit_per_minute', '60') }}" min="1" class="admin-settings-num">
|
||||
<small class="hint-text">Maximum mutating requests allowed per IP within the window below.</small>
|
||||
<small class="admin-hint">Maximum mutating requests allowed per IP within the window below.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
<label for="rate_limit_window_seconds">Rate Limit Window (seconds)</label>
|
||||
<input type="number" id="rate_limit_window_seconds" name="rate_limit_window_seconds" value="{{ settings.get('rate_limit_window_seconds', '60') }}" min="1" class="admin-settings-num">
|
||||
<small class="hint-text">Rolling window over which the request limit is counted.</small>
|
||||
<small class="admin-hint">Rolling window over which the request limit is counted.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
<label for="session_max_age_days">Session Length (days)</label>
|
||||
<input type="number" id="session_max_age_days" name="session_max_age_days" value="{{ settings.get('session_max_age_days', '7') }}" min="1" class="admin-settings-num">
|
||||
<small class="hint-text">Cookie lifetime for a standard sign-in.</small>
|
||||
<small class="admin-hint">Cookie lifetime for a standard sign-in.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
<label for="session_remember_days">Remember-Me Length (days)</label>
|
||||
<input type="number" id="session_remember_days" name="session_remember_days" value="{{ settings.get('session_remember_days', '30') }}" min="1" class="admin-settings-num">
|
||||
<small class="hint-text">Cookie lifetime when "remember me" is checked at login.</small>
|
||||
<small class="admin-hint">Cookie lifetime when "remember me" is checked at login.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
<label for="outbound_proxy_url">Outbound Proxy URL</label>
|
||||
<input type="text" id="outbound_proxy_url" name="outbound_proxy_url" value="{{ settings.get('outbound_proxy_url', '') }}" maxlength="500" placeholder="http://user:pass@host:port" class="admin-settings-select-wide">
|
||||
<small class="hint-text">Routes every outbound stealth-client request (Devii fetch, DeepSearch, news, attachments, and more) through this proxy. Leave empty to connect directly. Needed only when a destination blocks this server's own IP/network (not its browser fingerprint) - most sites never need this.</small>
|
||||
<small class="admin-hint">Routes every outbound stealth-client request (Devii fetch, DeepSearch, news, attachments, and more) through this proxy. Leave empty to connect directly. Needed only when a destination blocks this server's own IP/network (not its browser fingerprint) - most sites never need this.</small>
|
||||
</div>
|
||||
|
||||
<h3 class="admin-settings-group-title admin-settings-group-title-spaced">Moderation & Safety</h3>
|
||||
@@ -160,19 +160,19 @@
|
||||
<option value="review"{% if _mode == 'review' %} selected{% endif %}>review - publish and raise a report</option>
|
||||
<option value="block"{% if _mode == 'block' %} selected{% endif %}>block - refuse at creation</option>
|
||||
</select>
|
||||
<small class="hint-text">How the classifier acts on a match. <strong>review</strong> is the default: nothing legitimate is ever suppressed by a machine and a human sees every flag. Move to <strong>block</strong> only with evidence from the queue - on a developer platform a blanket block produces false positives on security research and error messages. The sexual and exploitative categories always block, whatever this setting says.</small>
|
||||
<small class="admin-hint">How the classifier acts on a match. <strong>review</strong> is the default: nothing legitimate is ever suppressed by a machine and a human sees every flag. Move to <strong>block</strong> only with evidence from the queue - on a developer platform a blanket block produces false positives on security research and error messages. The sexual and exploitative categories always block, whatever this setting says.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
<label for="moderation_sla_hours">Moderation Response Window (hours)</label>
|
||||
<input type="number" id="moderation_sla_hours" name="moderation_sla_hours" value="{{ settings.get('moderation_sla_hours', '24') }}" min="1" max="720" class="admin-settings-num">
|
||||
<small class="hint-text">The commitment published in the terms and shown on every report acknowledgement. The moderation queue badge turns red once the oldest open report is older than this.</small>
|
||||
<small class="admin-hint">The commitment published in the terms and shown on every report acknowledgement. The moderation queue badge turns red once the oldest open report is older than this.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
<label for="moderation_minimum_age">Minimum Age</label>
|
||||
<input type="number" id="moderation_minimum_age" name="moderation_minimum_age" value="{{ settings.get('moderation_minimum_age', '16') }}" min="13" max="21" class="admin-settings-num">
|
||||
<small class="hint-text">Signup is refused below this age. Only the derived age band is stored, never the date of birth.</small>
|
||||
<small class="admin-hint">Signup is refused below this age. Only the derived age band is stored, never the date of birth.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
@@ -181,19 +181,19 @@
|
||||
<option value="1"{% if settings.get('moderation_mature_default_hidden', '1') == '1' %} selected{% endif %}>Yes</option>
|
||||
<option value="0"{% if settings.get('moderation_mature_default_hidden', '1') == '0' %} selected{% endif %}>No</option>
|
||||
</select>
|
||||
<small class="hint-text">When on, mature-labelled content renders behind an interstitial until the viewer explicitly opts in. Minor age bands are never offered the reveal for restricted content.</small>
|
||||
<small class="admin-hint">When on, mature-labelled content renders behind an interstitial until the viewer explicitly opts in. Minor age bands are never offered the reveal for restricted content.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
<label for="account_deletion_grace_hours">Account Deletion Grace (hours)</label>
|
||||
<input type="number" id="account_deletion_grace_hours" name="account_deletion_grace_hours" value="{{ settings.get('account_deletion_grace_hours', '24') }}" min="0" max="720" class="admin-settings-num">
|
||||
<small class="hint-text">How long a deleted account stays restorable from the trash before it is permanently purged. The account is anonymised immediately either way; this only sets when the purge runs.</small>
|
||||
<small class="admin-hint">How long a deleted account stays restorable from the trash before it is permanently purged. The account is anonymised immediately either way; this only sets when the purge runs.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
<label for="ai_third_party_provider">Third-party AI Provider Name</label>
|
||||
<input type="text" id="ai_third_party_provider" name="ai_third_party_provider" value="{{ settings.get('ai_third_party_provider', '') }}" maxlength="120" placeholder="e.g. Acme Model Co.">
|
||||
<small class="hint-text">Named in the consent copy and the privacy policy, so the user knows who receives their content before they grant consent.</small>
|
||||
<small class="admin-hint">Named in the consent copy and the privacy policy, so the user knows who receives their content before they grant consent.</small>
|
||||
</div>
|
||||
|
||||
<h3 class="admin-settings-group-title admin-settings-group-title-spaced">AI Models</h3>
|
||||
@@ -201,19 +201,19 @@
|
||||
<div class="admin-field">
|
||||
<label for="correction_model">AI Content Correction Model</label>
|
||||
<input type="text" id="correction_model" name="correction_model" value="{{ settings.get('correction_model', '') }}" maxlength="120" placeholder="molodetz">
|
||||
<small class="hint-text">Model sent to the internal AI gateway for opt-in content correction. Blank uses the gateway default model.</small>
|
||||
<small class="admin-hint">Model sent to the internal AI gateway for opt-in content correction. Blank uses the gateway default model.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
<label for="modifier_model">AI Modifier Model</label>
|
||||
<input type="text" id="modifier_model" name="modifier_model" value="{{ settings.get('modifier_model', '') }}" maxlength="120" placeholder="molodetz">
|
||||
<small class="hint-text">Model sent to the internal AI gateway for inline @ai directives. Blank uses the gateway default model.</small>
|
||||
<small class="admin-hint">Model sent to the internal AI gateway for inline @ai directives. Blank uses the gateway default model.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
<label for="quiz_grading_model">Quiz AI Grading Model</label>
|
||||
<input type="text" id="quiz_grading_model" name="quiz_grading_model" value="{{ settings.get('quiz_grading_model', '') }}" maxlength="120" placeholder="molodetz">
|
||||
<small class="hint-text">Model sent to the internal AI gateway for free-text quiz answer grading. Blank uses the gateway default model.</small>
|
||||
<small class="admin-hint">Model sent to the internal AI gateway for free-text quiz answer grading. Blank uses the gateway default model.</small>
|
||||
</div>
|
||||
|
||||
<h3 class="admin-settings-group-title admin-settings-group-title-spaced">Policy Versions</h3>
|
||||
@@ -221,7 +221,7 @@
|
||||
<div class="admin-field">
|
||||
<label for="terms_version">Terms Version</label>
|
||||
<input type="text" id="terms_version" name="terms_version" value="{{ settings.get('terms_version', '1') }}" maxlength="20" class="admin-settings-num">
|
||||
<small class="hint-text">Bumping this forces every member to accept the terms again before their next write. Reading and account deletion are never blocked.</small>
|
||||
<small class="admin-hint">Bumping this forces every member to accept the terms again before their next write. Reading and account deletion are never blocked.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
@@ -239,7 +239,7 @@
|
||||
<div class="admin-field">
|
||||
<label for="contact_email">Contact Email</label>
|
||||
<input type="text" id="contact_email" name="contact_email" value="{{ settings.get('contact_email', '') }}" maxlength="200" placeholder="support@example.com">
|
||||
<small class="hint-text">Rendered on /docs/contact.html. Keep it identical to the trader email declared in every app store that carries a DevPlace client.</small>
|
||||
<small class="admin-hint">Rendered on /docs/contact.html. Keep it identical to the trader email declared in every app store that carries a DevPlace client.</small>
|
||||
</div>
|
||||
|
||||
<div class="admin-field">
|
||||
@@ -257,9 +257,9 @@
|
||||
<div class="admin-field">
|
||||
<label for="extra_head">Extra Head</label>
|
||||
<textarea id="extra_head" name="extra_head" rows="10" spellcheck="false" class="admin-settings-code">{{ settings.get('extra_head', '') }}</textarea>
|
||||
<small class="hint-text">Raw HTML injected into the page <head> on every page. Put anything here: a <style> block, <script>, <link>, meta tags, or an analytics snippet. Applies site-wide. Leave empty to remove.</small>
|
||||
<small class="admin-hint">Raw HTML injected into the page <head> on every page. Put anything here: a <style> block, <script>, <link>, meta tags, or an analytics snippet. Applies site-wide. Leave empty to remove.</small>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary"><span class="icon">💾</span>Save Settings</button>
|
||||
<button type="submit" class="admin-btn admin-btn-primary"><span class="icon">💾</span>Save Settings</button>
|
||||
</form>
|
||||
{% endblock %}
|
||||
|
||||
@@ -7,30 +7,32 @@
|
||||
{% block admin_content %}
|
||||
<div class="admin-toolbar statistics-toolbar">
|
||||
<h2>Statistics</h2>
|
||||
<div class="statistics-controls">
|
||||
<form method="get" action="/admin/statistics" class="statistics-controls" aria-label="Statistics window">
|
||||
<input type="hidden" name="tab" value="{{ active_tab }}">
|
||||
<div class="statistics-controls-primary">
|
||||
<label for="statistics-window">Window
|
||||
<select id="statistics-window">
|
||||
<option value="24" {% if window_hours == 24 %}selected{% endif %}>Last 24 hours</option>
|
||||
<option value="168" {% if window_hours == 168 %}selected{% endif %}>Last 7 days</option>
|
||||
<option value="720" {% if window_hours == 720 %}selected{% endif %}>Last 30 days</option>
|
||||
<option value="2160" {% if window_hours == 2160 %}selected{% endif %}>Last 90 days</option>
|
||||
<option value="0" {% if window_hours == 0 %}selected{% endif %}>All time</option>
|
||||
<select id="statistics-window" name="hours" class="admin-select" data-auto-submit>
|
||||
{% for hours, label in windows %}
|
||||
<option value="{{ hours }}" {% if window_hours == hours %}selected{% endif %}>{{ label }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<label class="statistics-compare-label">
|
||||
<input type="checkbox" id="statistics-compare" checked>
|
||||
<span>Compare previous period</span>
|
||||
<label for="statistics-compare">Compare
|
||||
<select id="statistics-compare" name="compare" class="admin-select" data-auto-submit>
|
||||
<option value="1" {% if compare %}selected{% endif %}>Previous period</option>
|
||||
<option value="0" {% if not compare %}selected{% endif %}>No comparison</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<span class="statistics-generated" data-meta="generated" role="status" aria-live="polite">-</span>
|
||||
</div>
|
||||
<noscript><button type="submit" class="admin-btn admin-btn-sm">Apply</button></noscript>
|
||||
<span class="statistics-generated" role="status">Generated {{ local_dt(initial.generated_at) }}</span>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<nav class="admin-tabs" data-overflow-tabs aria-label="Statistics categories">
|
||||
<div class="overflow-tabs-strip">
|
||||
{% for tab in tabs %}
|
||||
<a href="/admin/statistics?tab={{ tab['key'] }}&hours={{ window_hours }}" class="admin-tab {% if tab['active'] %}active{% endif %}" data-tab="{{ tab['key'] }}" data-menu-icon="{{ tab['icon'] }}" data-menu-label="{{ tab['label'] }}">
|
||||
<a href="/admin/statistics?tab={{ tab['key'] }}&hours={{ window_hours }}&compare={{ 1 if compare else 0 }}" class="admin-tab {% if tab['active'] %}active{% endif %}" data-menu-icon="{{ tab['icon'] }}" data-menu-label="{{ tab['label'] }}"{% if tab['active'] %} aria-current="page"{% endif %}>
|
||||
<span class="icon">{{ tab['icon'] }}</span> {{ tab['label'] }}
|
||||
</a>
|
||||
{% endfor %}
|
||||
@@ -38,21 +40,84 @@
|
||||
<button type="button" class="admin-tab overflow-tabs-more" aria-haspopup="menu" aria-label="More tabs" hidden><span class="icon">⋯</span> More</button>
|
||||
</nav>
|
||||
|
||||
<div id="statistics-root" class="statistics" role="region" aria-label="Platform statistics" aria-live="polite">
|
||||
<p class="admin-empty" data-empty>Loading statistics...</p>
|
||||
<div id="statistics-root" class="statistics" role="region" aria-label="Platform statistics">
|
||||
{% if initial.highlights %}
|
||||
<div class="metric-cards">
|
||||
{% for item in initial.highlights %}
|
||||
<div class="metric-card"><span class="metric-value">{{ item.value }}</span><span class="metric-label">{{ item.label }}</span></div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if initial.cards %}
|
||||
<div class="metric-cards">
|
||||
{% for card in initial.cards %}
|
||||
<div class="metric-card">
|
||||
<span class="metric-value">{{ card.display }}</span>
|
||||
<span class="metric-label">{{ card.label }}</span>
|
||||
{% if card.delta_display %}<span class="statistics-delta {{ card.direction }}">{{ card.arrow }} {{ card.delta_display }}</span>{% endif %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if initial.series %}
|
||||
<div class="statistics-section">
|
||||
<h3>Trends</h3>
|
||||
<div class="statistics-charts" data-statistics-charts>
|
||||
{% for series in initial.series %}
|
||||
<div class="statistics-chart-panel">
|
||||
<h4>{{ series.label or series.key }}</h4>
|
||||
<div class="statistics-chart-wrap"><canvas data-series-index="{{ loop.index0 }}" role="img" aria-label="{{ series.label or 'Chart' }} over time"></canvas></div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if initial.tables %}
|
||||
<div class="statistics-section statistics-breakdowns">
|
||||
<h3>Breakdowns</h3>
|
||||
<div class="statistics-breakdowns-grid">
|
||||
{% for table in initial.tables %}
|
||||
<article class="statistics-table-panel{% if table.columns|length > 2 %} is-wide{% endif %}">
|
||||
<div class="statistics-table-panel-head">
|
||||
<h4>{{ table.title }}</h4>
|
||||
<span class="statistics-table-panel-count">{{ table.row_count }} rows</span>
|
||||
</div>
|
||||
<div class="admin-table-wrap">
|
||||
<table class="admin-table">
|
||||
<caption class="sr-only">{{ table.title }}</caption>
|
||||
<thead>
|
||||
<tr>{% for column in table.columns %}<th scope="col" class="{{ table.column_classes[loop.index0] }}">{{ column }}</th>{% endfor %}</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for row in table.display_rows %}
|
||||
<tr>{% for cell in row %}<td class="{{ table.column_classes[loop.index0] }}">{{ cell }}</td>{% endfor %}</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</article>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if not initial.highlights and not initial.cards and not initial.series and not initial.tables %}
|
||||
<p class="admin-empty">No statistics for this tab in this window.</p>
|
||||
{% endif %}
|
||||
{% set page_notes = initial.notes or {} %}
|
||||
{% if page_notes.full_page %}
|
||||
<p class="statistics-note"><a class="statistics-link" href="{{ page_notes.full_page }}">Open full detail page</a></p>
|
||||
{% endif %}
|
||||
{% if page_notes.retention_days %}
|
||||
<p class="statistics-note">Visitor data retention: {{ page_notes.retention_days }} days.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<script type="application/json" id="statistics-initial">{{ initial | tojson }}</script>
|
||||
<script type="application/json" id="statistics-initial">{{ initial.series | tojson }}</script>
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
<script src="{{ static_url('/static/vendor/chartjs/chart.umd.min.js') }}" defer></script>
|
||||
<script type="module" src="{{ static_url('/static/js/StatisticsDashboard.js') }}"></script>
|
||||
<script type="module">
|
||||
new window.StatisticsDashboard({
|
||||
rootId: "statistics-root",
|
||||
initialId: "statistics-initial",
|
||||
activeTab: {{ active_tab | tojson }},
|
||||
windowHours: {{ window_hours }},
|
||||
}).start();
|
||||
import { StatisticsDashboard } from "{{ static_url('/static/js/StatisticsDashboard.js') }}";
|
||||
new StatisticsDashboard(document.getElementById("statistics-root"), document.getElementById("statistics-initial")).start();
|
||||
</script>
|
||||
{% endblock %}
|
||||
{% endblock %}
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
<button type="button" class="admin-tab overflow-tabs-more" aria-haspopup="menu" aria-label="More tabs" hidden><span class="icon">⋯</span> More</button>
|
||||
</nav>
|
||||
|
||||
<div class="admin-table-wrap">
|
||||
<table class="admin-table">
|
||||
<caption class="sr-only">Soft-deleted items with restore and purge actions</caption>
|
||||
<thead>
|
||||
@@ -49,11 +50,12 @@
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="4" class="empty-state">Trash is empty.</td>
|
||||
<td colspan="4" class="admin-empty">Trash is empty.</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{% include "_pagination.html" %}
|
||||
{% endblock %}
|
||||
|
||||
@@ -6,82 +6,83 @@
|
||||
{% block admin_content %}
|
||||
<div class="admin-toolbar">
|
||||
<h2>Workspaces</h2>
|
||||
<span class="admin-count">{{ workspaces|length }} workspaces</span>
|
||||
<span class="admin-count">{{ flags|length }} open flags</span>
|
||||
<span class="admin-count">{{ pagination.total }} workspaces</span>
|
||||
<span class="admin-count">{{ flags_total }} open flags</span>
|
||||
</div>
|
||||
|
||||
<div class="admin-table-wrap">
|
||||
<table class="admin-table" id="ws-admin-list" data-endpoint="/admin/workspaces/data">
|
||||
<table class="admin-table" id="ws-admin-list" data-endpoint="/admin/workspaces/data" data-page="{{ pagination.page }}">
|
||||
<caption class="sr-only">Dev workspaces</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Owner</th>
|
||||
<th>Project</th>
|
||||
<th>Status</th>
|
||||
<th>Disk</th>
|
||||
<th>Egress</th>
|
||||
<th>Size</th>
|
||||
<th>Editor</th>
|
||||
<th>Tunnels</th>
|
||||
<th>Flags</th>
|
||||
<th>Actions</th>
|
||||
<th scope="col">Name</th>
|
||||
<th scope="col">Owner</th>
|
||||
<th scope="col">Project</th>
|
||||
<th scope="col">Status</th>
|
||||
<th scope="col">Disk</th>
|
||||
<th scope="col">Egress</th>
|
||||
<th scope="col">Size</th>
|
||||
<th scope="col">Editor</th>
|
||||
<th scope="col">Tunnels</th>
|
||||
<th scope="col">Flags</th>
|
||||
<th scope="col">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tbody id="ws-admin-rows" aria-live="polite">
|
||||
{% for ws in workspaces %}
|
||||
<tr data-workspace-uid="{{ ws.uid }}">
|
||||
<tr data-workspace-uid="{{ ws.uid }}" data-state="{{ 'suspended' if ws.suspended else ws.status }}">
|
||||
<td>{{ ws.name }}</td>
|
||||
<td>{{ ws.owner_username }}</td>
|
||||
<td>{{ ws.project_title }}</td>
|
||||
<td>
|
||||
<td data-ws-cell="status">
|
||||
{% if ws.suspended %}
|
||||
<span class="workspace-badge workspace-badge-failed">suspended</span>
|
||||
{% else %}
|
||||
<span class="workspace-badge">{{ ws.status }}</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>{{ ws.disk_percent }}% of {{ ws.disk_quota_mb }} MB</td>
|
||||
<td>{{ ws.egress_percent }}% of {{ ws.egress_quota_mb }} MB</td>
|
||||
<td data-ws-cell="disk">{{ ws.disk_percent }}% of {{ ws.disk_quota_mb }} MB</td>
|
||||
<td data-ws-cell="egress">{{ ws.egress_percent }}% of {{ ws.egress_quota_mb }} MB</td>
|
||||
<td>{{ ws.editor.cpu_cores }} CPU / {{ ws.editor.memory_mb }} MB</td>
|
||||
<td>{{ ws.editor.theme }} / {{ ws.editor.layout }}</td>
|
||||
<td>{{ ws.tunnels|length }}</td>
|
||||
<td>{{ ws.flags|length }}</td>
|
||||
<td data-ws-cell="tunnels">{{ ws.tunnels|length }}</td>
|
||||
<td data-ws-cell="flags">{{ ws.flags|length }}</td>
|
||||
<td class="admin-actions">
|
||||
{% if ws.status == "running" %}
|
||||
<form method="post" action="/admin/workspaces/{{ ws.uid }}/stop">
|
||||
<button type="submit" class="admin-btn">Stop</button>
|
||||
<button type="submit" class="admin-btn" aria-label="Stop {{ ws.name }}">Stop</button>
|
||||
</form>
|
||||
{% else %}
|
||||
<form method="post" action="/admin/workspaces/{{ ws.uid }}/start">
|
||||
<button type="submit" class="admin-btn">Start</button>
|
||||
<button type="submit" class="admin-btn" aria-label="Start {{ ws.name }}">Start</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
{% if ws.suspended %}
|
||||
<form method="post" action="/admin/workspaces/{{ ws.uid }}/unsuspend">
|
||||
<button type="submit" class="admin-btn">Unsuspend</button>
|
||||
<button type="submit" class="admin-btn" aria-label="Unsuspend {{ ws.name }}">Unsuspend</button>
|
||||
</form>
|
||||
{% else %}
|
||||
<form method="post" action="/admin/workspaces/{{ ws.uid }}/suspend">
|
||||
<input type="text" name="reason" placeholder="Reason" maxlength="500" required>
|
||||
<button type="submit" class="admin-btn">Suspend</button>
|
||||
<input type="text" name="reason" placeholder="Reason" maxlength="500" required aria-label="Suspend reason for {{ ws.name }}">
|
||||
<button type="submit" class="admin-btn" aria-label="Suspend {{ ws.name }}">Suspend</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
<form method="post" action="/admin/workspaces/{{ ws.uid }}/flag">
|
||||
<input type="text" name="detail" placeholder="Flag detail" maxlength="500">
|
||||
<button type="submit" class="admin-btn">Flag</button>
|
||||
<input type="text" name="detail" placeholder="Flag detail" maxlength="500" aria-label="Flag detail for {{ ws.name }}">
|
||||
<button type="submit" class="admin-btn" aria-label="Flag {{ ws.name }}">Flag</button>
|
||||
</form>
|
||||
<form method="post" action="/admin/workspaces/{{ ws.uid }}/delete">
|
||||
<button type="submit" data-confirm="Delete this workspace?" data-confirm-danger class="admin-btn admin-btn-danger">Delete</button>
|
||||
<button type="submit" data-confirm="Delete this workspace?" data-confirm-danger class="admin-btn admin-btn-danger" aria-label="Delete {{ ws.name }}">Delete</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="11">No workspaces yet.</td></tr>
|
||||
<tr><td colspan="11" class="admin-empty">No workspaces yet.</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% include "_pagination.html" %}
|
||||
|
||||
<div class="admin-toolbar">
|
||||
<h2>Open flags</h2>
|
||||
@@ -90,7 +91,7 @@
|
||||
<table class="admin-table">
|
||||
<caption class="sr-only">Open workspace flags</caption>
|
||||
<thead>
|
||||
<tr><th>Kind</th><th>Severity</th><th>Detail</th><th>Value</th><th>Threshold</th><th>Actions</th></tr>
|
||||
<tr><th scope="col">Kind</th><th scope="col">Severity</th><th scope="col">Detail</th><th scope="col">Value</th><th scope="col">Threshold</th><th scope="col">Actions</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for flag in flags %}
|
||||
@@ -102,17 +103,27 @@
|
||||
<td>{{ flag.threshold }}</td>
|
||||
<td class="admin-actions">
|
||||
<form method="post" action="/admin/workspaces/flags/{{ flag.uid }}/resolve?status=resolved">
|
||||
<button type="submit" class="admin-btn">Resolve</button>
|
||||
<button type="submit" class="admin-btn" aria-label="Resolve {{ flag.kind }} flag">Resolve</button>
|
||||
</form>
|
||||
<form method="post" action="/admin/workspaces/flags/{{ flag.uid }}/resolve?status=dismissed">
|
||||
<button type="submit" class="admin-btn">Dismiss</button>
|
||||
<button type="submit" class="admin-btn" aria-label="Dismiss {{ flag.kind }} flag">Dismiss</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="6">No open flags.</td></tr>
|
||||
<tr><td colspan="6" class="admin-empty">No open flags.</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% set _shown = flags|length %}{% set _total = flags_total %}
|
||||
{% include "_admin_cap_note.html" %}
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
<script type="module">
|
||||
import { WorkspaceList } from "{{ static_url('/static/js/WorkspaceList.js') }}";
|
||||
const list = new WorkspaceList(document.getElementById("ws-admin-list"));
|
||||
list.init();
|
||||
window.app.workspaceList = list;
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -8,17 +8,17 @@
|
||||
<div class="admin-toolbar">
|
||||
<h2>AI usage</h2>
|
||||
<div class="ai-usage-controls">
|
||||
<label for="ai-usage-window">Window
|
||||
<select id="ai-usage-window">
|
||||
<option value="1">1 hour</option>
|
||||
<option value="24">24 hours</option>
|
||||
<option value="48" selected>48 hours</option>
|
||||
<option value="168">7 days</option>
|
||||
<option value="0">All time</option>
|
||||
</select>
|
||||
</label>
|
||||
<form method="GET" action="/admin/ai-usage" class="admin-inline-form" aria-label="Usage window">
|
||||
<label for="ai-usage-window">Window
|
||||
<select id="ai-usage-window" name="hours" class="admin-select" data-auto-submit>
|
||||
{% for value, label in window_choices %}
|
||||
<option value="{{ value }}" {% if window_hours == value %}selected{% endif %}>{{ label }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<noscript><button type="submit" class="admin-btn admin-btn-sm">Apply</button></noscript>
|
||||
</form>
|
||||
<label><input type="checkbox" id="ai-usage-divided"> Show breakdowns</label>
|
||||
<span class="ai-usage-generated" data-meta="generated" role="status" aria-live="polite" aria-label="Last generated">-</span>
|
||||
<form method="POST" action="/admin/ai-quota/reset-guests" class="admin-inline-form" aria-label="Reset guest quotas">
|
||||
<button type="submit" class="admin-btn admin-btn-sm" data-confirm-danger data-confirm="Reset guest AI quotas for all guests?"><span class="icon">🔄</span> Reset guest quotas</button>
|
||||
</form>
|
||||
@@ -27,8 +27,8 @@
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div id="ai-usage-root" class="ai-usage" role="region" aria-label="AI usage metrics" aria-live="polite">
|
||||
<p class="admin-empty" data-empty>Loading metrics...</p>
|
||||
<div id="ai-usage-root" class="ai-usage" data-fragment="/admin/ai-usage/fragment" data-hours="{{ window_hours }}" role="region" aria-label="AI usage metrics" aria-live="polite">
|
||||
{% include "_ai_usage_report.html" %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
|
||||
@@ -157,18 +157,9 @@
|
||||
{% if is_admin(user) %}
|
||||
<div class="topnav-mobile-divider"></div>
|
||||
<div class="topnav-mobile-section-label">Admin</div>
|
||||
<a href="/admin" class="topnav-mobile-link {{ nav_active(request, '/admin', exact=True) }}"><span class="icon">🛡️</span> Dashboard</a>
|
||||
<a href="/admin/users" class="topnav-mobile-link {{ nav_active(request, '/admin/users') }}"><span class="icon">👥</span> Users</a>
|
||||
<a href="/admin/news" class="topnav-mobile-link {{ nav_active(request, '/admin/news') }}"><span class="icon">📰</span> News</a>
|
||||
<a href="/admin/media" class="topnav-mobile-link {{ nav_active(request, '/admin/media') }}"><span class="icon">🖼️</span> Media</a>
|
||||
<a href="/admin/trash" class="topnav-mobile-link {{ nav_active(request, '/admin/trash') }}"><span class="icon">🗑️</span> Trash</a>
|
||||
<a href="/admin/services" class="topnav-mobile-link {{ nav_active(request, '/admin/services') }}"><span class="icon">⚙️</span> Services</a>
|
||||
<a href="/admin/containers" class="topnav-mobile-link {{ nav_active(request, '/admin/containers') }}"><span class="icon">📦</span> Containers</a>
|
||||
<a href="/admin/bots" class="topnav-mobile-link {{ nav_active(request, '/admin/bots') }}"><span class="icon">🤖</span> Bot Monitor</a>
|
||||
<a href="/admin/ai-usage" class="topnav-mobile-link {{ nav_active(request, '/admin/ai-usage') }}"><span class="icon">📊</span> AI usage</a>
|
||||
<a href="/admin/audit-log" class="topnav-mobile-link {{ nav_active(request, '/admin/audit-log') }}"><span class="icon">📋</span> Audit Log</a>
|
||||
<a href="/admin/notifications" class="topnav-mobile-link {{ nav_active(request, '/admin/notifications') }}"><span class="icon">🔔</span> Notifications</a>
|
||||
<a href="/admin/settings" class="topnav-mobile-link {{ nav_active(request, '/admin/settings') }}"><span class="icon">🔧</span> Settings</a>
|
||||
{% for section in admin_sections %}
|
||||
<a href="{{ section.href }}" class="topnav-mobile-link {{ nav_active(request, section.href) }}"><span class="icon">{{ section.icon }}</span> {{ section.label }}</a>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
<div class="topnav-mobile-divider"></div>
|
||||
<div class="topnav-mobile-user">
|
||||
|
||||
@@ -7,12 +7,12 @@
|
||||
{% block admin_content %}
|
||||
<div class="admin-toolbar">
|
||||
<h2>Containers</h2>
|
||||
<span class="admin-count">{{ instances|length }} instances</span>
|
||||
<span class="admin-count" id="cm-admin-count">{{ pagination.total }} instances</span>
|
||||
<a href="#" class="admin-btn admin-btn-primary" data-modal="cm-admin-create-modal">New instance</a>
|
||||
</div>
|
||||
|
||||
<div class="admin-table-wrap">
|
||||
<table class="admin-table" id="cm-admin-list" data-endpoint="/admin/containers/data">
|
||||
<table class="admin-table" id="cm-admin-list" data-endpoint="/admin/containers/data" data-page="{{ pagination.page }}">
|
||||
<caption class="sr-only">Container instances</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
@@ -63,6 +63,7 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% include "_pagination.html" %}
|
||||
|
||||
{% call modal('cm-admin-create-modal', 'New container instance', wide=true) %}
|
||||
<form id="cm-admin-create-form" class="cm-form">
|
||||
@@ -122,7 +123,7 @@
|
||||
<label class="cm-check"><input type="checkbox" name="start_on_boot"> Start on container service boot</label>
|
||||
<label class="cm-check"><input type="checkbox" name="autostart" checked> Start immediately</label>
|
||||
<div class="modal-footer">
|
||||
<button type="submit" class="btn btn-primary">Create instance</button>
|
||||
<button type="submit" class="admin-btn admin-btn-primary">Create instance</button>
|
||||
</div>
|
||||
</form>
|
||||
{% endcall %}
|
||||
|
||||
@@ -46,7 +46,7 @@
|
||||
</div>
|
||||
<label class="cm-check"><input type="checkbox" name="start_on_boot" {% if instance['start_on_boot'] %}checked{% endif %}> Start on container service boot</label>
|
||||
<div class="modal-footer">
|
||||
<button type="submit" class="btn btn-primary">Save changes</button>
|
||||
<button type="submit" class="admin-btn admin-btn-primary">Save changes</button>
|
||||
</div>
|
||||
</form>
|
||||
{% endblock %}
|
||||
|
||||
@@ -43,7 +43,7 @@ Every service exposes a `metrics` dictionary through `describe()`, surfaced live
|
||||
|
||||
| Service | Headline metrics it reports |
|
||||
|---------|------------------------------|
|
||||
| `openai` | requests, errors, in-flight and peak concurrency, vision calls, last status and latency, circuit state, plus rolled-up 24h cost, tokens, success rate, average latency and TPS, top model and caller. |
|
||||
| `openai` | requests, errors, in-flight and peak concurrency, vision calls, last status and latency, circuit state and open per-model breakers, plus rolled-up 24h cost, tokens, success rate, average latency and TPS, top model and caller. |
|
||||
| `devii` | active sessions, open connections, 24h spend, the user/guest/admin caps, whether guests are allowed, and the model name. |
|
||||
| `news` | AI usage cards (grading and formatting calls, tokens, cost, and averages) rolled up from `news_usage`, plus status, last and next run, and the log tail for run health. |
|
||||
| `bots` | bots running, fleet cost, cost rate, projected 24h cost, LLM calls, tokens in and out, posts, comments, votes, and a per-bot table. |
|
||||
|
||||
@@ -21,10 +21,10 @@
|
||||
</details>
|
||||
{% endif %}
|
||||
<div class="service-controls">
|
||||
<button type="button" class="service-btn" data-action="start" data-service="{{ svc.name }}" aria-label="Start {{ svc.title }}" {% if svc.enabled %}disabled{% endif %}>Start</button>
|
||||
<button type="button" class="service-btn" data-action="stop" data-service="{{ svc.name }}" aria-label="Stop {{ svc.title }}" data-confirm="Stop the {{ svc.title }} service?" {% if not svc.enabled %}disabled{% endif %}>Stop</button>
|
||||
<button type="button" class="service-btn" data-action="run" data-service="{{ svc.name }}" aria-label="Run {{ svc.title }} now">Run now</button>
|
||||
<button type="button" class="service-btn" data-action="clear-logs" data-service="{{ svc.name }}" aria-label="Clear logs for {{ svc.title }}" data-confirm="Clear the log buffer for {{ svc.title }}?">Clear logs</button>
|
||||
<button type="button" class="admin-btn" data-action="start" data-service="{{ svc.name }}" aria-label="Start {{ svc.title }}" {% if svc.enabled %}disabled{% endif %}>Start</button>
|
||||
<button type="button" class="admin-btn" data-action="stop" data-service="{{ svc.name }}" aria-label="Stop {{ svc.title }}" data-confirm="Stop the {{ svc.title }} service?" {% if not svc.enabled %}disabled{% endif %}>Stop</button>
|
||||
<button type="button" class="admin-btn" data-action="run" data-service="{{ svc.name }}" aria-label="Run {{ svc.title }} now">Run now</button>
|
||||
<button type="button" class="admin-btn" data-action="clear-logs" data-service="{{ svc.name }}" aria-label="Clear logs for {{ svc.title }}" data-confirm="Clear the log buffer for {{ svc.title }}?">Clear logs</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -41,12 +41,12 @@
|
||||
<section class="svc-tabpane" data-tab-pane="overview">
|
||||
<div class="svc-meta-grid">
|
||||
<div class="svc-meta-item"><span class="svc-meta-label">Uptime</span><span class="svc-meta-value" data-meta="uptime">{{ svc.uptime or "-" }}</span></div>
|
||||
<div class="svc-meta-item"><span class="svc-meta-label">Last run</span><span class="svc-meta-value" data-meta="last_run">{% if svc.last_run %}{{ format_date(svc.last_run, include_time=True) }}{% else %}-{% endif %}</span></div>
|
||||
<div class="svc-meta-item"><span class="svc-meta-label">Next run</span><span class="svc-meta-value" data-meta="next_run">{% if svc.next_run %}{{ format_date(svc.next_run, include_time=True) }}{% else %}-{% endif %}</span></div>
|
||||
<div class="svc-meta-item"><span class="svc-meta-label">Heartbeat</span><span class="svc-meta-value" data-meta="heartbeat">{% if svc.heartbeat %}{{ format_date(svc.heartbeat, include_time=True) }}{% else %}-{% endif %}</span></div>
|
||||
<div class="svc-meta-item"><span class="svc-meta-label">Last run</span><span class="svc-meta-value" data-meta="last_run">{% if svc.last_run %}{{ local_dt(svc.last_run) }}{% else %}-{% endif %}</span></div>
|
||||
<div class="svc-meta-item"><span class="svc-meta-label">Next run</span><span class="svc-meta-value" data-meta="next_run">{% if svc.next_run %}{{ local_dt(svc.next_run) }}{% else %}-{% endif %}</span></div>
|
||||
<div class="svc-meta-item"><span class="svc-meta-label">Heartbeat</span><span class="svc-meta-value" data-meta="heartbeat">{% if svc.heartbeat %}{{ local_dt(svc.heartbeat) }}{% else %}-{% endif %}</span></div>
|
||||
<div class="svc-meta-item"><span class="svc-meta-label">Interval</span><span class="svc-meta-value" data-meta="interval">every {{ svc.interval_seconds }}s</span></div>
|
||||
</div>
|
||||
<div class="service-metrics" data-metrics role="status" aria-live="polite" aria-label="Service metrics"></div>
|
||||
<div class="service-metrics" data-metrics role="status" aria-live="polite" aria-label="Service metrics">{% set _metrics = svc.metrics %}{% include "_service_metrics.html" %}</div>
|
||||
</section>
|
||||
|
||||
<section class="svc-tabpane" data-tab-pane="config">
|
||||
@@ -81,14 +81,14 @@
|
||||
{% else %}
|
||||
<input type="text" id="{{ svc.name }}_{{ field.key }}" name="{{ field.key }}" value="{{ field.value }}">
|
||||
{% endif %}
|
||||
{% if field.help %}<small class="hint-text">{{ field.help }}</small>{% endif %}
|
||||
{% if field.help %}<small class="admin-hint">{{ field.help }}</small>{% endif %}
|
||||
<small class="field-error" data-error="{{ field.key }}" role="alert" aria-live="assertive"></small>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</fieldset>
|
||||
{% endfor %}
|
||||
<div class="config-actions">
|
||||
<button type="submit" class="btn btn-primary">Save configuration</button>
|
||||
<button type="submit" class="admin-btn admin-btn-primary">Save configuration</button>
|
||||
<span class="config-status" data-config-status role="status" aria-live="polite"></span>
|
||||
</div>
|
||||
</form>
|
||||
@@ -96,7 +96,7 @@
|
||||
|
||||
{% if tool_groups is not none %}
|
||||
<section class="svc-tabpane" data-tab-pane="tools">
|
||||
<p class="hint-text devii-tools-intro">
|
||||
<p class="admin-hint devii-tools-intro">
|
||||
Every tool Devii can call costs tokens on every turn just by being listed - disable what a
|
||||
deployment does not need to spare context. Changes apply to every Devii session on the next turn.
|
||||
</p>
|
||||
@@ -127,7 +127,7 @@
|
||||
{% endfor %}
|
||||
</div>
|
||||
<div class="config-actions">
|
||||
<button type="submit" class="btn btn-primary">Save tool configuration</button>
|
||||
<button type="submit" class="admin-btn admin-btn-primary">Save tool configuration</button>
|
||||
<span class="config-status" data-tools-status role="status" aria-live="polite"></span>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
{% block admin_content %}
|
||||
<div class="admin-toolbar">
|
||||
<h2>Services</h2>
|
||||
<span class="admin-count">{{ services|length }} services</span>
|
||||
<span class="admin-count">{{ services_total }} services</span>
|
||||
</div>
|
||||
|
||||
<div class="admin-table-wrap">
|
||||
@@ -32,8 +32,8 @@
|
||||
</td>
|
||||
<td><span class="service-status {{ svc.status }}">{{ svc.status }}</span></td>
|
||||
<td data-meta="uptime">{{ svc.uptime or "-" }}</td>
|
||||
<td data-meta="last_run">{% if svc.last_run %}{{ format_date(svc.last_run, include_time=True) }}{% else %}-{% endif %}</td>
|
||||
<td data-meta="next_run">{% if svc.next_run %}{{ format_date(svc.next_run, include_time=True) }}{% else %}-{% endif %}</td>
|
||||
<td data-meta="last_run">{% if svc.last_run %}{{ local_dt(svc.last_run) }}{% else %}-{% endif %}</td>
|
||||
<td data-meta="next_run">{% if svc.next_run %}{{ local_dt(svc.next_run) }}{% else %}-{% endif %}</td>
|
||||
<td data-meta="interval">every {{ svc.interval_seconds }}s</td>
|
||||
<td><a class="admin-btn admin-btn-sm" href="/admin/services/{{ svc.name }}">Manage →</a></td>
|
||||
</tr>
|
||||
@@ -43,6 +43,7 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% set _shown = services|length %}{% set _total = services_total %}{% include "_admin_cap_note.html" %}
|
||||
{% endblock %}
|
||||
{% block extra_js %}
|
||||
<script type="module" src="{{ static_url('/static/js/ServiceMonitor.js') }}"></script>
|
||||
|
||||
@@ -5,6 +5,7 @@ from datetime import datetime, timezone
|
||||
import jinja2
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from markupsafe import Markup, escape
|
||||
from devplacepy.admin_sections import ADMIN_SECTIONS
|
||||
from devplacepy.cache import TTLCache
|
||||
from devplacepy.config import STATIC_VERSION, TEMPLATES_DIR, TEMPLATE_AUTO_RELOAD
|
||||
from devplacepy.constants import TOPICS, REACTION_EMOJI
|
||||
@@ -62,6 +63,7 @@ def static_url(path) -> str:
|
||||
|
||||
|
||||
templates.env.globals["static_url"] = static_url
|
||||
templates.env.globals["admin_sections"] = ADMIN_SECTIONS
|
||||
templates.env.globals["nodes_spec"] = NODES_SPEC.describe()
|
||||
templates.env.globals["static_version"] = STATIC_VERSION
|
||||
templates.env.globals["is_admin"] = is_admin
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "devplacepy"
|
||||
version = "1.1.25"
|
||||
version = "1.1.26"
|
||||
description = "DevPlace - The Developer Social Network"
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
|
||||
@@ -39,3 +39,34 @@ def test_admin_ai_usage_data_returns_json(app_server, seeded_db):
|
||||
assert r.status_code == 200
|
||||
data = r.json()
|
||||
assert isinstance(data, dict)
|
||||
|
||||
|
||||
def test_admin_ai_usage_first_response_is_rendered(app_server, seeded_db):
|
||||
admin = _admin_aiusage(seeded_db)
|
||||
r = admin.get(f"{BASE_URL}/admin/ai-usage")
|
||||
assert r.status_code == 200
|
||||
assert "Loading metrics" not in r.text
|
||||
assert 'id="ai-usage-root"' in r.text
|
||||
assert "Window:" in r.text
|
||||
|
||||
|
||||
def test_admin_ai_usage_window_param_is_honored_and_clamped(app_server, seeded_db):
|
||||
admin = _admin_aiusage(seeded_db)
|
||||
r = admin.get(f"{BASE_URL}/admin/ai-usage/data?hours=999999&top_n=999", headers=JSON_aiusage)
|
||||
assert r.status_code == 200
|
||||
assert r.json()["window_hours"] <= 168
|
||||
page = admin.get(f"{BASE_URL}/admin/ai-usage?hours=1")
|
||||
assert '<option value="1" selected>' in page.text
|
||||
|
||||
|
||||
def test_admin_ai_usage_fragment_is_html(app_server, seeded_db):
|
||||
admin = _admin_aiusage(seeded_db)
|
||||
r = admin.get(f"{BASE_URL}/admin/ai-usage/fragment?hours=24")
|
||||
assert r.status_code == 200
|
||||
assert "text/html" in r.headers["content-type"]
|
||||
assert "Window:" in r.text
|
||||
|
||||
|
||||
def test_admin_ai_usage_fragment_requires_admin(app_server):
|
||||
r = requests.get(f"{BASE_URL}/admin/ai-usage/fragment", allow_redirects=False)
|
||||
assert r.status_code in (302, 303, 401, 403)
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import requests
|
||||
from tests.conftest import BASE_URL
|
||||
from devplacepy.database import get_table, refresh_snapshot
|
||||
from devplacepy.services.backup import store
|
||||
|
||||
HTML = {"Accept": "text/html"}
|
||||
JSON = {"Accept": "application/json"}
|
||||
|
||||
|
||||
def _admin(seeded_db):
|
||||
refresh_snapshot()
|
||||
key = get_table("users").find_one(username="alice_test")["api_key"]
|
||||
session = requests.Session()
|
||||
session.headers.update({"X-API-KEY": key})
|
||||
return session
|
||||
|
||||
|
||||
def test_backups_page_is_server_rendered(seeded_db):
|
||||
admin = _admin(seeded_db)
|
||||
schedule_uid = store.create_schedule(
|
||||
name="Pages schedule",
|
||||
target="database",
|
||||
kind="interval",
|
||||
every_seconds=3600,
|
||||
cron="",
|
||||
keep_last=3,
|
||||
created_by="pages-test",
|
||||
next_run_at="",
|
||||
)
|
||||
backup_uid = store.create_backup(
|
||||
target="database", created_by="pages-test", job_uid="pagesjob"
|
||||
)
|
||||
refresh_snapshot()
|
||||
r = admin.get(f"{BASE_URL}/admin/backups", headers=HTML)
|
||||
assert r.status_code == 200
|
||||
assert "Loading" not in r.text
|
||||
assert 'data-live="storage"' in r.text
|
||||
assert 'data-live="backups"' in r.text
|
||||
assert 'data-live="schedules"' in r.text
|
||||
assert f'data-uid="{backup_uid}"' in r.text
|
||||
assert f'data-uid="{schedule_uid}"' in r.text
|
||||
assert "Pages schedule" in r.text
|
||||
assert "<time" in r.text
|
||||
|
||||
|
||||
def test_backups_data_matches_page_json(seeded_db):
|
||||
admin = _admin(seeded_db)
|
||||
page = admin.get(f"{BASE_URL}/admin/backups", headers=JSON).json()
|
||||
data = admin.get(f"{BASE_URL}/admin/backups/data", headers=JSON).json()
|
||||
assert {b["uid"] for b in page["backups"]} == {b["uid"] for b in data["backups"]}
|
||||
assert page["backups_total"] >= len(page["backups"])
|
||||
assert data["backups_total"] >= len(data["backups"])
|
||||
@@ -91,6 +91,7 @@ def test_add_learns_and_shows_detail(client, admin, fake_world):
|
||||
listing = client.get("/admin/communities", headers=admin["headers"])
|
||||
assert listing.status_code == 200
|
||||
assert listing.json()["items"][0]["slug"] == "forum-test"
|
||||
assert listing.json()["pagination"]["total"] >= 1
|
||||
detail = client.get("/admin/communities/forum-test", headers=admin["headers"])
|
||||
assert detail.status_code == 200
|
||||
body = detail.json()
|
||||
|
||||
@@ -16,3 +16,37 @@ def test_containers_admin_data_denied_for_non_admin(app_server, seeded_db):
|
||||
)
|
||||
r = s.get(f"{BASE_URL}/admin/containers/data", allow_redirects=False)
|
||||
assert r.status_code in (302, 303, 403)
|
||||
|
||||
|
||||
def test_containers_admin_data_is_paginated(app_server, seeded_db):
|
||||
from devplacepy.database import refresh_snapshot
|
||||
from devplacepy.services.containers import store
|
||||
|
||||
refresh_snapshot()
|
||||
admin = get_table("users").find_one(username=seeded_db["alice"]["username"])
|
||||
uids = []
|
||||
try:
|
||||
for index in range(27):
|
||||
row = store.create_instance(
|
||||
{
|
||||
"project_uid": "proj-admin-page",
|
||||
"name": f"cm-page-{index}",
|
||||
"status": "stopped",
|
||||
"desired_state": "stopped",
|
||||
}
|
||||
)
|
||||
uids.append(row["uid"])
|
||||
headers = {"Accept": "application/json", "X-API-KEY": admin["api_key"]}
|
||||
first = requests.get(f"{BASE_URL}/admin/containers/data", headers=headers).json()
|
||||
assert first["pagination"]["per_page"] == 25
|
||||
assert len(first["instances"]) <= 25
|
||||
second = requests.get(
|
||||
f"{BASE_URL}/admin/containers/data", headers=headers, params={"page": 2}
|
||||
).json()
|
||||
assert not {i["uid"] for i in first["instances"]} & {
|
||||
i["uid"] for i in second["instances"]
|
||||
}
|
||||
finally:
|
||||
table = get_table("instances")
|
||||
for uid in uids:
|
||||
table.delete(uid=uid)
|
||||
|
||||
@@ -182,3 +182,26 @@ def test_devii_tasks_shows_the_owner_24h_usage(seeded_db):
|
||||
assert entry["quota"]["runs_used"] >= 1
|
||||
assert entry["quota"]["runs_limit"] == 100
|
||||
assert entry["quota"]["creates_used"] >= 1
|
||||
|
||||
|
||||
def test_devii_tasks_list_is_paginated(seeded_db):
|
||||
owner = _admin_uid(seeded_db)
|
||||
uids = [_seed_task(owner) for _ in range(27)]
|
||||
admin = _admin_dt(seeded_db)
|
||||
first = admin.get(f"{BASE_URL}/admin/devii-tasks", headers=JSON_dt).json()
|
||||
assert first["pagination"]["per_page"] == 25
|
||||
assert first["pagination"]["total"] >= 27
|
||||
assert len(first["items"]) == 25
|
||||
second = admin.get(
|
||||
f"{BASE_URL}/admin/devii-tasks", headers=JSON_dt, params={"page": 2}
|
||||
).json()
|
||||
assert second["items"]
|
||||
assert not {i["uid"] for i in first["items"]} & {i["uid"] for i in second["items"]}
|
||||
assert uids
|
||||
|
||||
|
||||
def test_devii_tasks_page_is_server_rendered_with_admin_empty_classes(seeded_db):
|
||||
admin = _admin_dt(seeded_db)
|
||||
html = admin.get(f"{BASE_URL}/admin/devii-tasks").text
|
||||
assert "empty-state" not in html
|
||||
assert 'class="admin-table-wrap"' in html
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import re
|
||||
|
||||
import requests
|
||||
from tests.conftest import BASE_URL
|
||||
from devplacepy.database import get_table, refresh_snapshot
|
||||
|
||||
JSON = {"Accept": "application/json"}
|
||||
HTML = {"Accept": "text/html"}
|
||||
|
||||
|
||||
def _admin(seeded_db):
|
||||
refresh_snapshot()
|
||||
key = get_table("users").find_one(username="alice_test")["api_key"]
|
||||
session = requests.Session()
|
||||
session.headers.update({"X-API-KEY": key})
|
||||
return session
|
||||
|
||||
|
||||
def test_game_admin_json_face(seeded_db):
|
||||
r = _admin(seeded_db).get(f"{BASE_URL}/admin/game", headers=JSON)
|
||||
assert r.status_code == 200, r.text[:300]
|
||||
assert "era_active" in r.json()
|
||||
|
||||
|
||||
def test_game_admin_uses_the_admin_vocabulary(seeded_db):
|
||||
r = _admin(seeded_db).get(f"{BASE_URL}/admin/game", headers=HTML)
|
||||
assert r.status_code == 200
|
||||
assert "admin-btn" in r.text
|
||||
content = r.text.split('<main class="admin-content">', 1)[1].split("</main>", 1)[0]
|
||||
tokens = {name for value in re.findall(r'class="([^"]*)"', content) for name in value.split()}
|
||||
assert not tokens & {"btn", "btn-primary", "btn-danger", "hint-text"}
|
||||
@@ -0,0 +1,251 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import http.server
|
||||
import json
|
||||
import socket
|
||||
import socketserver
|
||||
import threading
|
||||
import time
|
||||
|
||||
import requests
|
||||
|
||||
from devplacepy.database import get_table, refresh_snapshot
|
||||
from devplacepy.database.settings import internal_gateway_key
|
||||
from tests.api.admin.gateway.index import (
|
||||
_unique_gateway,
|
||||
admin_session,
|
||||
)
|
||||
from tests.conftest import BASE_URL
|
||||
|
||||
CHAT_URL = f"{BASE_URL}/openai/v1/chat/completions"
|
||||
NOTICE_MARKER = "tripped its circuit breaker"
|
||||
SYNC_SECONDS = 1.5
|
||||
NOTICE_WAIT_SECONDS = 10
|
||||
OK_BODY = {
|
||||
"id": "x",
|
||||
"model": "m",
|
||||
"choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
|
||||
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
|
||||
}
|
||||
|
||||
|
||||
class _Upstream:
|
||||
def __init__(self, status, payload):
|
||||
self.calls = []
|
||||
calls = self.calls
|
||||
body = json.dumps(payload).encode()
|
||||
code = status
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
calls.append(json.loads(self.rfile.read(length) or b"{}"))
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
sock = socket.socket()
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
self.port = sock.getsockname()[1]
|
||||
sock.close()
|
||||
self.httpd = socketserver.ThreadingTCPServer(("127.0.0.1", self.port), Handler)
|
||||
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
|
||||
|
||||
@property
|
||||
def host(self):
|
||||
return f"127.0.0.1:{self.port}"
|
||||
|
||||
def close(self):
|
||||
self.httpd.shutdown()
|
||||
self.httpd.server_close()
|
||||
|
||||
|
||||
def _internal_headers():
|
||||
refresh_snapshot()
|
||||
return {"Authorization": f"Bearer {internal_gateway_key()}", "Content-Type": "application/json"}
|
||||
|
||||
|
||||
def _route(admin, upstream, prefix, target=None):
|
||||
provider = _unique_gateway(f"{prefix}p").lower()
|
||||
source = _unique_gateway(f"{prefix}m").lower()
|
||||
target = target or f"vendor/{prefix}"
|
||||
admin.post(
|
||||
f"{BASE_URL}/admin/gateway/providers",
|
||||
json={"name": provider, "base_url": f"http://{upstream.host}/v1/chat/completions", "api_key": "sk-test"},
|
||||
)
|
||||
created = admin.post(
|
||||
f"{BASE_URL}/admin/gateway/models",
|
||||
json={"source_model": source, "provider": provider, "target_model": target, "kind": "chat"},
|
||||
)
|
||||
assert created.status_code == 200, created.text[:300]
|
||||
return provider, source
|
||||
|
||||
|
||||
def _cleanup(admin, provider, source):
|
||||
admin.delete(f"{BASE_URL}/admin/gateway/models/{source}")
|
||||
admin.delete(f"{BASE_URL}/admin/gateway/providers/{provider}")
|
||||
|
||||
|
||||
def _chat(source):
|
||||
return requests.post(
|
||||
CHAT_URL,
|
||||
headers=_internal_headers(),
|
||||
json={"model": source, "messages": [{"role": "user", "content": "hi"}]},
|
||||
timeout=60,
|
||||
)
|
||||
|
||||
|
||||
def _admin_notices(host):
|
||||
refresh_snapshot()
|
||||
rows = get_table("notifications").find(type="system")
|
||||
return [r for r in rows if NOTICE_MARKER in (r.get("message") or "") and host in r["message"]]
|
||||
|
||||
|
||||
def _wait_for_notices(host):
|
||||
deadline = time.time() + NOTICE_WAIT_SECONDS
|
||||
while time.time() < deadline:
|
||||
found = _admin_notices(host)
|
||||
if found:
|
||||
return found
|
||||
time.sleep(0.5)
|
||||
return []
|
||||
|
||||
|
||||
def test_first_upstream_error_opens_the_target_and_the_second_call_never_leaves(seeded_db):
|
||||
admin = admin_session(seeded_db)
|
||||
upstream = _Upstream(500, {"error": {"message": "provider exploded"}})
|
||||
provider, source = _route(admin, upstream, "trip")
|
||||
try:
|
||||
first = _chat(source)
|
||||
assert first.status_code >= 500
|
||||
sent_after_first = len(upstream.calls)
|
||||
assert sent_after_first >= 1
|
||||
second = _chat(source)
|
||||
assert second.status_code == 503
|
||||
assert second.json()["error"]["type"] == "circuit_open"
|
||||
assert len(upstream.calls) == sent_after_first
|
||||
finally:
|
||||
_cleanup(admin, provider, source)
|
||||
upstream.close()
|
||||
|
||||
|
||||
def test_every_admin_gets_one_detailed_notification_per_incident(seeded_db):
|
||||
admin = admin_session(seeded_db)
|
||||
upstream = _Upstream(500, {"error": {"message": "provider exploded"}})
|
||||
provider, source = _route(admin, upstream, "notify")
|
||||
try:
|
||||
_chat(source)
|
||||
_chat(source)
|
||||
_chat(source)
|
||||
notices = _wait_for_notices(upstream.host)
|
||||
assert notices, "no system notification reached the admins"
|
||||
admins = {u["uid"] for u in get_table("users").find(role="Admin")}
|
||||
per_admin = {}
|
||||
for row in notices:
|
||||
per_admin[row["user_uid"]] = per_admin.get(row["user_uid"], 0) + 1
|
||||
assert set(per_admin) == admins
|
||||
assert set(per_admin.values()) == {1}
|
||||
message = notices[0]["message"]
|
||||
assert "vendor/notify" in message
|
||||
assert "Error class: upstream_error" in message
|
||||
assert "HTTP status: 500" in message
|
||||
assert "provider exploded" in message
|
||||
assert "sk-test" not in message
|
||||
assert notices[0]["target_url"] == "/admin/services/openai"
|
||||
finally:
|
||||
_cleanup(admin, provider, source)
|
||||
upstream.close()
|
||||
|
||||
|
||||
def test_a_failing_target_does_not_block_a_healthy_one(seeded_db):
|
||||
admin = admin_session(seeded_db)
|
||||
bad = _Upstream(500, {"error": {"message": "down"}})
|
||||
good = _Upstream(200, OK_BODY)
|
||||
bad_provider, bad_source = _route(admin, bad, "isobad")
|
||||
good_provider, good_source = _route(admin, good, "isogood")
|
||||
try:
|
||||
_chat(bad_source)
|
||||
assert _chat(bad_source).status_code == 503
|
||||
healthy = _chat(good_source)
|
||||
assert healthy.status_code == 200
|
||||
assert healthy.json()["choices"][0]["message"]["content"] == "ok"
|
||||
assert len(good.calls) == 1
|
||||
finally:
|
||||
_cleanup(admin, bad_provider, bad_source)
|
||||
_cleanup(admin, good_provider, good_source)
|
||||
bad.close()
|
||||
good.close()
|
||||
|
||||
|
||||
def test_a_malformed_request_trips_once_and_is_not_resent(seeded_db):
|
||||
admin = admin_session(seeded_db)
|
||||
upstream = _Upstream(400, {"error": {"message": "bad schema"}})
|
||||
provider, source = _route(admin, upstream, "badreq")
|
||||
try:
|
||||
first = _chat(source)
|
||||
assert first.status_code == 400
|
||||
sent = len(upstream.calls)
|
||||
assert sent == 1
|
||||
assert _chat(source).status_code == 503
|
||||
assert len(upstream.calls) == sent
|
||||
finally:
|
||||
_cleanup(admin, provider, source)
|
||||
upstream.close()
|
||||
|
||||
|
||||
def test_a_shape_fixable_400_does_not_open_the_target(seeded_db):
|
||||
admin = admin_session(seeded_db)
|
||||
upstream = _Upstream(
|
||||
400, {"issues": [{"code": "unrecognized_keys", "keys": ["thinking"]}]}
|
||||
)
|
||||
provider, source = _route(admin, upstream, "shape")
|
||||
try:
|
||||
_chat(source)
|
||||
sent = len(upstream.calls)
|
||||
assert sent >= 2
|
||||
again = _chat(source)
|
||||
assert again.status_code == 400
|
||||
assert len(upstream.calls) > sent
|
||||
finally:
|
||||
_cleanup(admin, provider, source)
|
||||
upstream.close()
|
||||
|
||||
|
||||
def test_the_breaker_is_per_model_not_per_upstream(seeded_db):
|
||||
admin = admin_session(seeded_db)
|
||||
first = _Upstream(500, {"error": {"message": "down"}})
|
||||
second = _Upstream(200, OK_BODY)
|
||||
model = _unique_gateway("vendor/shared").lower()
|
||||
first_provider, first_source = _route(admin, first, "permodela", target=model)
|
||||
second_provider, second_source = _route(admin, second, "permodelb", target=model)
|
||||
try:
|
||||
_chat(first_source)
|
||||
blocked = _chat(second_source)
|
||||
assert blocked.status_code == 503
|
||||
assert blocked.json()["error"]["type"] == "circuit_open"
|
||||
assert second.calls == []
|
||||
finally:
|
||||
_cleanup(admin, first_provider, first_source)
|
||||
_cleanup(admin, second_provider, second_source)
|
||||
first.close()
|
||||
second.close()
|
||||
|
||||
|
||||
def test_a_healthy_target_stays_closed_and_raises_no_notification(seeded_db):
|
||||
admin = admin_session(seeded_db)
|
||||
upstream = _Upstream(200, OK_BODY)
|
||||
provider, source = _route(admin, upstream, "calm")
|
||||
try:
|
||||
for _ in range(3):
|
||||
assert _chat(source).status_code == 200
|
||||
assert len(upstream.calls) == 3
|
||||
time.sleep(SYNC_SECONDS)
|
||||
assert _admin_notices(upstream.host) == []
|
||||
finally:
|
||||
_cleanup(admin, provider, source)
|
||||
upstream.close()
|
||||
@@ -80,3 +80,54 @@ def test_stats_model_detail_for_an_unknown_model(seeded_db):
|
||||
data = response.json()
|
||||
assert data["summary"]["total_requests"] == 0
|
||||
assert data["health"] is None
|
||||
|
||||
|
||||
def test_stats_tab_first_response_is_rendered(seeded_db):
|
||||
admin = admin_session(seeded_db)
|
||||
response = admin.get(
|
||||
f"{BASE_URL}/admin/gateway?tab=stats", headers={"Accept": "text/html"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert "Loading..." not in response.text
|
||||
assert 'id="gw-stats-initial"' in response.text
|
||||
assert 'data-slot="tiles"' in response.text
|
||||
assert "/vendor/chartjs/chart.umd.min.js" in response.text
|
||||
assert "js/vendor/chart.js" not in response.text
|
||||
|
||||
|
||||
def test_stats_tab_honors_range_param(seeded_db):
|
||||
admin = admin_session(seeded_db)
|
||||
response = admin.get(
|
||||
f"{BASE_URL}/admin/gateway?tab=stats&range=7d", headers={"Accept": "text/html"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert '<option value="7d" selected>' in response.text
|
||||
|
||||
|
||||
def test_stats_tab_falls_back_on_unknown_range(seeded_db):
|
||||
admin = admin_session(seeded_db)
|
||||
response = admin.get(
|
||||
f"{BASE_URL}/admin/gateway?tab=stats&range=nonsense", headers={"Accept": "text/html"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert '<option value="24h" selected>' in response.text
|
||||
|
||||
|
||||
def test_stats_fragment_renders_slots(seeded_db):
|
||||
admin = admin_session(seeded_db)
|
||||
response = admin.get(f"{BASE_URL}/admin/gateway/stats/fragment?range=24h")
|
||||
assert response.status_code == 200
|
||||
for slot in ("tiles", "models", "failures", "note"):
|
||||
assert f'data-slot="{slot}"' in response.text
|
||||
assert 'id="gw-stats-initial"' in response.text
|
||||
|
||||
|
||||
def test_stats_fragment_rejects_unknown_range(seeded_db):
|
||||
admin = admin_session(seeded_db)
|
||||
response = admin.get(f"{BASE_URL}/admin/gateway/stats/fragment?range=nonsense")
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_stats_fragment_requires_admin(seeded_db):
|
||||
response = requests.get(f"{BASE_URL}/admin/gateway/stats/fragment", allow_redirects=False)
|
||||
assert response.status_code in (302, 303, 401, 403)
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import requests
|
||||
from tests.conftest import BASE_URL
|
||||
from devplacepy.database import get_table, refresh_snapshot
|
||||
|
||||
JSON = {"Accept": "application/json"}
|
||||
HTML = {"Accept": "text/html"}
|
||||
|
||||
|
||||
def _admin(seeded_db):
|
||||
refresh_snapshot()
|
||||
key = get_table("users").find_one(username="alice_test")["api_key"]
|
||||
session = requests.Session()
|
||||
session.headers.update({"X-API-KEY": key})
|
||||
return session
|
||||
|
||||
|
||||
def test_planning_page_json_face(seeded_db):
|
||||
r = _admin(seeded_db).get(f"{BASE_URL}/admin/issues/planning", headers=JSON)
|
||||
assert r.status_code == 200, r.text[:300]
|
||||
body = r.json()
|
||||
assert "configured" in body
|
||||
assert isinstance(body["tickets"], list)
|
||||
|
||||
|
||||
def test_planning_page_uses_the_admin_vocabulary(seeded_db):
|
||||
r = _admin(seeded_db).get(f"{BASE_URL}/admin/issues/planning", headers=HTML)
|
||||
assert r.status_code == 200
|
||||
assert "<h1" not in r.text.split('class="admin-content"', 1)[1]
|
||||
assert "empty-state" not in r.text
|
||||
assert "admin-header" not in r.text
|
||||
assert 'aria-current="page"' in r.text
|
||||
@@ -34,6 +34,8 @@ def test_admin_overview_shape(client, admin):
|
||||
listed = {row["uid"]: row for row in body["devices"]}
|
||||
assert listed[device["uid"]]["owner_username"] == owner["username"]
|
||||
assert len(body["devices"]) <= 100
|
||||
assert body["devices_total"] >= len(body["devices"])
|
||||
assert body["flags_total"] >= len(body["flags"])
|
||||
assert "secret_hash" not in listed[device["uid"]]
|
||||
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ def _all_tool_names():
|
||||
|
||||
def test_devii_service_page_has_tools_tab(seeded_db):
|
||||
admin = _admin(seeded_db)
|
||||
r = admin.get(f"{BASE_URL}/admin/services/devii")
|
||||
r = admin.get(f"{BASE_URL}/admin/services/devii", headers={"Accept": "text/html"})
|
||||
assert r.status_code == 200
|
||||
assert 'data-tab="tools"' in r.text
|
||||
assert "devii-tools-form" in r.text
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import requests
|
||||
from tests.conftest import BASE_URL
|
||||
from devplacepy.database import get_table, refresh_snapshot
|
||||
|
||||
JSON = {"Accept": "application/json"}
|
||||
HTML = {"Accept": "text/html"}
|
||||
|
||||
|
||||
def _admin(seeded_db):
|
||||
refresh_snapshot()
|
||||
key = get_table("users").find_one(username="alice_test")["api_key"]
|
||||
session = requests.Session()
|
||||
session.headers.update({"X-API-KEY": key})
|
||||
return session
|
||||
|
||||
|
||||
def test_services_page_json_face(seeded_db):
|
||||
admin = _admin(seeded_db)
|
||||
r = admin.get(f"{BASE_URL}/admin/services", headers=JSON)
|
||||
assert r.status_code == 200, r.text[:300]
|
||||
body = r.json()
|
||||
names = {svc["name"] for svc in body["services"]}
|
||||
assert "seo_meta" in names
|
||||
assert body["services_total"] >= len(body["services"])
|
||||
|
||||
|
||||
def test_services_page_is_server_rendered(seeded_db):
|
||||
admin = _admin(seeded_db)
|
||||
r = admin.get(f"{BASE_URL}/admin/services", headers=HTML)
|
||||
assert r.status_code == 200
|
||||
assert 'data-service="seo_meta"' in r.text
|
||||
assert "Loading" not in r.text
|
||||
content = r.text.split('<main class="admin-content">', 1)[1].split("</main>", 1)[0]
|
||||
assert "btn-primary" not in content.replace("admin-btn-primary", "")
|
||||
|
||||
|
||||
def test_services_data_matches_page_json(seeded_db):
|
||||
admin = _admin(seeded_db)
|
||||
page = admin.get(f"{BASE_URL}/admin/services", headers=JSON).json()["services"]
|
||||
data = admin.get(f"{BASE_URL}/admin/services/data", headers=JSON).json()["services"]
|
||||
assert {s["name"] for s in page} == {s["name"] for s in data}
|
||||
|
||||
|
||||
def test_service_detail_json_face(seeded_db):
|
||||
admin = _admin(seeded_db)
|
||||
r = admin.get(f"{BASE_URL}/admin/services/seo_meta", headers=JSON)
|
||||
assert r.status_code == 200, r.text[:300]
|
||||
assert r.json()["service"]["name"] == "seo_meta"
|
||||
|
||||
|
||||
def test_service_detail_renders_metrics_on_the_server(seeded_db):
|
||||
admin = _admin(seeded_db)
|
||||
r = admin.get(f"{BASE_URL}/admin/services/seo_meta", headers=HTML)
|
||||
assert r.status_code == 200
|
||||
assert 'class="metric-card"' in r.text
|
||||
assert "service-btn" not in r.text
|
||||
assert "hint-text" not in r.text
|
||||
|
||||
|
||||
def test_service_detail_unknown_is_404(seeded_db):
|
||||
admin = _admin(seeded_db)
|
||||
r = admin.get(f"{BASE_URL}/admin/services/does_not_exist", headers=JSON)
|
||||
assert r.status_code == 404
|
||||
@@ -0,0 +1,57 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import re
|
||||
|
||||
import requests
|
||||
from tests.conftest import BASE_URL
|
||||
from devplacepy.database import get_table, refresh_snapshot
|
||||
|
||||
HTML = {"Accept": "text/html"}
|
||||
JSON = {"Accept": "application/json"}
|
||||
|
||||
|
||||
def _admin(seeded_db):
|
||||
refresh_snapshot()
|
||||
key = get_table("users").find_one(username="alice_test")["api_key"]
|
||||
session = requests.Session()
|
||||
session.headers.update({"X-API-KEY": key})
|
||||
return session
|
||||
|
||||
|
||||
def test_statistics_page_is_server_rendered(seeded_db):
|
||||
admin = _admin(seeded_db)
|
||||
r = admin.get(f"{BASE_URL}/admin/statistics", headers=HTML)
|
||||
assert r.status_code == 200
|
||||
assert "Loading" not in r.text
|
||||
assert 'class="metric-card"' in r.text
|
||||
assert 'id="statistics-initial"' in r.text
|
||||
assert "<time" in r.text
|
||||
|
||||
|
||||
def test_statistics_tab_and_window_navigate(seeded_db):
|
||||
admin = _admin(seeded_db)
|
||||
r = admin.get(f"{BASE_URL}/admin/statistics?tab=members&hours=24&compare=0", headers=HTML)
|
||||
assert r.status_code == 200, re.sub(r"\s+", " ", re.sub(r"<(script|style).*?</\1>", "", r.text, flags=re.S))[-500:]
|
||||
assert 'name="tab" value="members"' in r.text
|
||||
assert '<option value="24" selected>' in r.text
|
||||
assert '<option value="0" selected>No comparison</option>' in r.text
|
||||
|
||||
|
||||
def test_statistics_data_matches_page_json(seeded_db):
|
||||
admin = _admin(seeded_db)
|
||||
page = admin.get(f"{BASE_URL}/admin/statistics?tab=content", headers=JSON).json()
|
||||
data = admin.get(f"{BASE_URL}/admin/statistics/data?tab=content", headers=JSON).json()
|
||||
assert page["initial"]["tab"] == data["tab"] == "content"
|
||||
assert [c["key"] for c in page["initial"]["cards"]] == [c["key"] for c in data["cards"]]
|
||||
assert all(c["display"] for c in data["cards"])
|
||||
|
||||
|
||||
def test_statistics_params_are_clamped(seeded_db):
|
||||
admin = _admin(seeded_db)
|
||||
data = admin.get(
|
||||
f"{BASE_URL}/admin/statistics/data?tab=overview&hours=99999999&top_n=100000",
|
||||
headers=JSON,
|
||||
).json()
|
||||
assert data["window_hours"] == 2160
|
||||
unknown = admin.get(f"{BASE_URL}/admin/statistics/data?tab=nope", headers=JSON).json()
|
||||
assert unknown["tab"] == "overview"
|
||||
@@ -0,0 +1,102 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import requests
|
||||
|
||||
from devplacepy.database import get_table
|
||||
from devplacepy.services.containers import store
|
||||
from tests.conftest import BASE_URL
|
||||
|
||||
HTTP_TIMEOUT = 30
|
||||
JSON = {"Accept": "application/json"}
|
||||
PAGE_SIZE = 25
|
||||
|
||||
|
||||
def _user(username: str) -> dict:
|
||||
from devplacepy.database import refresh_snapshot
|
||||
|
||||
refresh_snapshot()
|
||||
return get_table("users").find_one(username=username)
|
||||
|
||||
|
||||
def _headers(user: dict) -> dict:
|
||||
return {**JSON, "X-API-KEY": user["api_key"]}
|
||||
|
||||
|
||||
def _seed(count: int, owner_uid: str) -> list[str]:
|
||||
uids = []
|
||||
for index in range(count):
|
||||
row = store.create_instance(
|
||||
{
|
||||
"project_uid": "proj-admin-ws-page",
|
||||
"name": f"ws-page-{index}",
|
||||
"status": "stopped",
|
||||
"desired_state": "stopped",
|
||||
"is_workspace": 1,
|
||||
"workspace_owner_uid": owner_uid,
|
||||
}
|
||||
)
|
||||
uids.append(row["uid"])
|
||||
return uids
|
||||
|
||||
|
||||
def _drop(uids: list[str]) -> None:
|
||||
table = get_table("instances")
|
||||
for uid in uids:
|
||||
table.delete(uid=uid)
|
||||
|
||||
|
||||
def test_workspaces_data_is_refused_for_a_member(app_server, seeded_db):
|
||||
member = _user("bob_test")
|
||||
response = requests.get(
|
||||
f"{BASE_URL}/admin/workspaces/data",
|
||||
headers=_headers(member),
|
||||
timeout=HTTP_TIMEOUT,
|
||||
allow_redirects=False,
|
||||
)
|
||||
assert response.status_code in (302, 303, 401, 403)
|
||||
|
||||
|
||||
def test_workspaces_data_is_paginated_and_matches_the_page(app_server, seeded_db):
|
||||
admin = _user("alice_test")
|
||||
owner = _user("bob_test")
|
||||
uids = _seed(PAGE_SIZE + 2, owner["uid"])
|
||||
try:
|
||||
first = requests.get(
|
||||
f"{BASE_URL}/admin/workspaces/data",
|
||||
headers=_headers(admin),
|
||||
timeout=HTTP_TIMEOUT,
|
||||
).json()
|
||||
assert {"workspaces", "flags", "flags_total", "pagination"} <= set(first)
|
||||
assert first["pagination"]["per_page"] == PAGE_SIZE
|
||||
assert first["pagination"]["total"] >= PAGE_SIZE + 2
|
||||
assert len(first["workspaces"]) == PAGE_SIZE
|
||||
second = requests.get(
|
||||
f"{BASE_URL}/admin/workspaces/data",
|
||||
headers=_headers(admin),
|
||||
params={"page": 2},
|
||||
timeout=HTTP_TIMEOUT,
|
||||
).json()
|
||||
assert second["workspaces"]
|
||||
assert not {w["uid"] for w in first["workspaces"]} & {
|
||||
w["uid"] for w in second["workspaces"]
|
||||
}
|
||||
finally:
|
||||
_drop(uids)
|
||||
|
||||
|
||||
def test_workspaces_page_is_server_rendered_with_pagination(app_server, seeded_db):
|
||||
admin = _user("alice_test")
|
||||
owner = _user("bob_test")
|
||||
uids = _seed(PAGE_SIZE + 1, owner["uid"])
|
||||
try:
|
||||
html = requests.get(
|
||||
f"{BASE_URL}/admin/workspaces",
|
||||
headers={"Accept": "text/html", "X-API-KEY": admin["api_key"]},
|
||||
timeout=HTTP_TIMEOUT,
|
||||
).text
|
||||
assert "Loading" not in html
|
||||
assert 'data-workspace-uid="' in html
|
||||
assert 'scope="col">Name</th>' in html
|
||||
assert 'class="pagination"' in html
|
||||
finally:
|
||||
_drop(uids)
|
||||
@@ -37,6 +37,22 @@ def _seed_admin_task(label, enabled=True):
|
||||
return uid
|
||||
|
||||
|
||||
def _goto_row(page, label, query=""):
|
||||
page_number = 1
|
||||
while True:
|
||||
separator = "&" if query else ""
|
||||
page.goto(
|
||||
f"{BASE_URL}/admin/devii-tasks?{query}{separator}page={page_number}",
|
||||
wait_until="domcontentloaded",
|
||||
)
|
||||
row = page.locator("table.admin-table tbody tr", has_text=label)
|
||||
if row.count():
|
||||
return row
|
||||
if not page.locator("a.pagination-btn:has-text('Next')").count():
|
||||
raise AssertionError(f"task {label} not found on any page")
|
||||
page_number += 1
|
||||
|
||||
|
||||
def test_devii_tasks_page_renders_for_admin(alice):
|
||||
page, _ = alice
|
||||
page.goto(f"{BASE_URL}/admin/devii-tasks", wait_until="domcontentloaded")
|
||||
@@ -56,8 +72,7 @@ def test_devii_tasks_disable_flow(alice):
|
||||
label = f"e2e-disable-{generate_uid()[:8]}"
|
||||
uid = _seed_admin_task(label, enabled=True)
|
||||
try:
|
||||
page.goto(f"{BASE_URL}/admin/devii-tasks", wait_until="domcontentloaded")
|
||||
row = page.locator("table.admin-table tbody tr", has_text=label)
|
||||
row = _goto_row(page, label)
|
||||
row.wait_for(state="visible")
|
||||
row.locator("form.admin-inline-form button:has-text('Disable')").click()
|
||||
page.wait_for_url("**/admin/devii-tasks", wait_until="domcontentloaded")
|
||||
@@ -67,8 +82,7 @@ def test_devii_tasks_disable_flow(alice):
|
||||
assert after["enabled"] is False
|
||||
assert after["status"] == "disabled"
|
||||
|
||||
page.goto(f"{BASE_URL}/admin/devii-tasks?state=inactive", wait_until="domcontentloaded")
|
||||
disabled_row = page.locator("table.admin-table tbody tr", has_text=label)
|
||||
disabled_row = _goto_row(page, label, "state=inactive")
|
||||
disabled_row.wait_for(state="visible")
|
||||
assert disabled_row.locator("button:has-text('Disable')").count() == 0
|
||||
finally:
|
||||
@@ -80,8 +94,7 @@ def test_devii_tasks_delete_flow(alice):
|
||||
label = f"e2e-delete-{generate_uid()[:8]}"
|
||||
uid = _seed_admin_task(label, enabled=True)
|
||||
try:
|
||||
page.goto(f"{BASE_URL}/admin/devii-tasks", wait_until="domcontentloaded")
|
||||
row = page.locator("table.admin-table tbody tr", has_text=label)
|
||||
row = _goto_row(page, label)
|
||||
row.wait_for(state="visible")
|
||||
|
||||
row.locator("form.admin-inline-form button:has-text('Delete')").click()
|
||||
|
||||
@@ -9,7 +9,7 @@ def test_planning_page_renders_for_admin(alice):
|
||||
f"{BASE_URL}/admin/issues/planning", wait_until="domcontentloaded"
|
||||
)
|
||||
assert page.url.endswith("/admin/issues/planning")
|
||||
page.locator("h1:has-text('Ticket Planning')").wait_for(state="visible")
|
||||
page.locator("h2:has-text('Ticket Planning')").wait_for(state="visible")
|
||||
assert page.is_visible("text=phased implementation document")
|
||||
|
||||
|
||||
@@ -19,4 +19,4 @@ def test_planning_page_blocks_members(bob):
|
||||
f"{BASE_URL}/admin/issues/planning", wait_until="domcontentloaded"
|
||||
)
|
||||
assert "/admin/issues/planning" not in page.url
|
||||
assert not page.is_visible("h1:has-text('Ticket Planning')")
|
||||
assert not page.is_visible("h2:has-text('Ticket Planning')")
|
||||
|
||||
@@ -783,7 +783,7 @@ def test_profile_info_section(alice):
|
||||
def test_profile_back_link(alice):
|
||||
page, user = alice
|
||||
page.goto(f"{BASE_URL}/profile/{user['username']}", wait_until="domcontentloaded")
|
||||
back = page.locator("a:has-text('Back')").first
|
||||
back = page.locator("a.back-link").first
|
||||
assert back.is_visible()
|
||||
back.click()
|
||||
page.wait_for_url(f"{BASE_URL}/feed", wait_until="domcontentloaded")
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from devplacepy.admin_sections import ADMIN_SECTION_KEYS, ADMIN_SECTIONS
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2] / "devplacepy"
|
||||
TEMPLATES = ROOT / "templates"
|
||||
ROUTERS = ROOT / "routers" / "admin"
|
||||
STATIC_JS = ROOT / "static" / "js"
|
||||
|
||||
ADMIN_TEMPLATES = sorted(
|
||||
path
|
||||
for path in TEMPLATES.glob("*.html")
|
||||
if re.search(r'{%\s*extends\s+"admin_base.html"\s*%}', path.read_text())
|
||||
)
|
||||
|
||||
FORBIDDEN_CLASSES = ("btn", "btn-primary", "btn-danger", "btn-secondary", "hint-text", "empty-state", "admin-header")
|
||||
CLASS_ATTR = re.compile(r'class="([^"]*)"')
|
||||
ADMIN_SCRIPT_REF = re.compile(r"/static/js/([A-Za-z0-9_]+\.js)")
|
||||
CHART_SRC = re.compile(r"""src="([^"]*chart[^"]*\.js)\"""")
|
||||
CANONICAL_CHART = "/static/vendor/chartjs/chart.umd.min.js"
|
||||
|
||||
|
||||
def ids(paths):
|
||||
return [path.name for path in paths]
|
||||
|
||||
|
||||
def test_admin_templates_discovered():
|
||||
assert len(ADMIN_TEMPLATES) >= 25
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ADMIN_TEMPLATES, ids=ids(ADMIN_TEMPLATES))
|
||||
def test_a1_no_loading_placeholder(path):
|
||||
assert not re.search(r"Loading[^<]{0,40}\.\.\.", path.read_text())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ADMIN_TEMPLATES, ids=ids(ADMIN_TEMPLATES))
|
||||
def test_a3_anatomy(path):
|
||||
text = path.read_text()
|
||||
assert "<h1" not in text
|
||||
assert "<style" not in text
|
||||
assert not re.search(r"\sstyle=", text)
|
||||
assert not re.search(r"\son(click|change|submit|input|load)=", text)
|
||||
assert "admin.css" not in text and "sidebar.css" not in text
|
||||
assert not re.search(r"<th(?![a-z])(?![^>]*scope=)", text)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ADMIN_TEMPLATES, ids=ids(ADMIN_TEMPLATES))
|
||||
def test_a4_class_vocabulary(path):
|
||||
for attribute in CLASS_ATTR.findall(path.read_text()):
|
||||
for name in attribute.split():
|
||||
assert name not in FORBIDDEN_CLASSES, f"{path.name}: forbidden class {name}"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ADMIN_TEMPLATES, ids=ids(ADMIN_TEMPLATES))
|
||||
def test_a5_instants_use_local_dt(path):
|
||||
assert "format_date(" not in path.read_text()
|
||||
assert "time_ago(" not in path.read_text()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ADMIN_TEMPLATES, ids=ids(ADMIN_TEMPLATES))
|
||||
def test_a9_single_chart_path(path):
|
||||
for src in CHART_SRC.findall(path.read_text()):
|
||||
assert CANONICAL_CHART in src, f"{path.name}: chart loaded from {src}"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ADMIN_TEMPLATES, ids=ids(ADMIN_TEMPLATES))
|
||||
def test_a10_no_hand_written_nav(path):
|
||||
assert 'class="sidebar-link' not in path.read_text()
|
||||
|
||||
|
||||
def test_a2_routes_use_respond():
|
||||
offenders = [
|
||||
leaf.name
|
||||
for leaf in ROUTERS.glob("*.py")
|
||||
if "TemplateResponse" in leaf.read_text()
|
||||
]
|
||||
assert offenders == []
|
||||
|
||||
|
||||
def test_a2_admin_section_keys_registered():
|
||||
used = set()
|
||||
for leaf in ROUTERS.glob("*.py"):
|
||||
used.update(re.findall(r'"admin_section":\s*"([a-z-]+)"', leaf.read_text()))
|
||||
assert used
|
||||
assert used <= ADMIN_SECTION_KEYS
|
||||
|
||||
|
||||
def test_a10_every_section_has_a_page():
|
||||
used = set()
|
||||
for leaf in ROUTERS.glob("*.py"):
|
||||
used.update(re.findall(r'"admin_section":\s*"([a-z-]+)"', leaf.read_text()))
|
||||
assert {section.key for section in ADMIN_SECTIONS} <= used
|
||||
|
||||
|
||||
def test_a10_registry_is_unique_and_well_formed():
|
||||
keys = [section.key for section in ADMIN_SECTIONS]
|
||||
hrefs = [section.href for section in ADMIN_SECTIONS]
|
||||
assert len(keys) == len(set(keys))
|
||||
assert len(hrefs) == len(set(hrefs))
|
||||
assert all(href.startswith("/admin/") for href in hrefs)
|
||||
|
||||
|
||||
def admin_scripts() -> list[Path]:
|
||||
names = set()
|
||||
for path in ADMIN_TEMPLATES:
|
||||
names.update(ADMIN_SCRIPT_REF.findall(path.read_text()))
|
||||
return sorted(STATIC_JS / name for name in names if (STATIC_JS / name).exists())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", admin_scripts(), ids=ids(admin_scripts()))
|
||||
def test_a8_admin_scripts_use_the_shared_poller_and_http(path):
|
||||
text = path.read_text()
|
||||
assert "setInterval" not in text
|
||||
assert not re.search(r"(?<![A-Za-z.])fetch\(", text)
|
||||
assert "toLocaleString" not in text and "toLocaleTimeString" not in text
|
||||
|
||||
|
||||
def test_a8_poll_floor_declared():
|
||||
from devplacepy.routers.admin._shared import ADMIN_LIST_CAP, ADMIN_POLL_FLOOR_SECONDS
|
||||
|
||||
assert ADMIN_POLL_FLOOR_SECONDS == 15
|
||||
assert ADMIN_LIST_CAP == 200
|
||||
Reference in New Issue
Block a user