latest changes

This commit is contained in:
Joren de Graaf
2026-10-22 10:24:33 +02:00
parent 9a5210a48f
commit 3a12d56f8b
33 changed files with 1179 additions and 96 deletions
+85
View File
@@ -0,0 +1,85 @@
"""Server-side adapter for the local Codex usage service."""
import json
import math
import os
import urllib.error
import urllib.request
from datetime import datetime, timezone
from django.core.cache import caches
URL = os.environ.get("DASHBOARD_CODEX_USAGE_URL", "http://192.168.1.122:3100/api/usage")
CACHE = caches["weather"]
FRESH_SECONDS = 45
STALE_SECONDS = 15 * 60
def _percentage(value):
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
return None
return round(max(0, min(100, 100 - value)))
def _time(value):
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
return None
try:
return datetime.fromtimestamp(value, timezone.utc)
except (ValueError, OverflowError, OSError):
return None
def _display(data):
if not isinstance(data, dict) or data.get("service") != "codex":
raise ValueError("Unexpected usage response")
raw = data.get("raw")
if not isinstance(raw, dict):
raise ValueError("Usage details unavailable")
buckets = raw.get("rateLimitsByLimitId")
if not isinstance(buckets, dict) or not buckets:
buckets = {"codex": raw.get("rateLimits")}
windows = []
for name, bucket in list(buckets.items())[:10]:
if not isinstance(bucket, dict):
continue
for key in ("primary", "secondary"):
window = bucket.get(key)
if not isinstance(window, dict):
continue
duration = window.get("windowDurationMins")
title = {300: "5 hours", 10080: "Weekly"}.get(duration, f"{duration} min" if type(duration) is int and 0 < duration < 100000 else key.title())
windows.append({
"title": title,
"remaining": _percentage(window.get("usedPercent")),
"reset": _time(window.get("resetsAt")),
"bucket": str(name)[:32],
})
checked = data.get("last_checked")
try:
checked = datetime.fromisoformat(checked.replace("Z", "+00:00")) if isinstance(checked, str) else None
except ValueError:
checked = None
return {"windows": windows, "checked": checked, "stale": bool(data.get("stale") or data.get("status") != "ok"), "allowed": raw.get("ordinaryUsageAllowed") is True}
def get_usage():
cached = CACHE.get("codex-usage:v1")
if cached and cached.get("fresh"):
return cached["display"]
try:
request = urllib.request.Request(URL, headers={"Accept": "application/json"})
with urllib.request.urlopen(request, timeout=5) as response:
body = response.read(1024 * 1024 + 1)
if len(body) > 1024 * 1024:
raise ValueError("Usage response too large")
display = _display(json.loads(body))
if display["stale"] and cached:
raise ValueError("Usage service returned stale data")
CACHE.set("codex-usage:v1", {"display": display, "fresh": True}, FRESH_SECONDS)
CACHE.set("codex-usage:last-good", display, STALE_SECONDS)
return display
except (urllib.error.URLError, OSError, ValueError, TypeError, json.JSONDecodeError):
previous = CACHE.get("codex-usage:last-good")
return {**previous, "stale": True} if previous else None
+1
View File
@@ -20,5 +20,6 @@ WIDGETS = {
WidgetType("shortcuts", "Shortcuts", "Links to useful pages", "bi-grid", "dashboard/widgets/shortcuts.html"),
WidgetType("open_meteo", "Weather forecast", "Current weather and hourly outlook from Open-Meteo", "bi-cloud-sun", "dashboard/widgets/open_meteo.html", 2),
WidgetType("buienradar", "Rain radar", "Netherlands radar and local rain forecast from Buienradar", "bi-cloud-rain", "dashboard/widgets/buienradar.html", 2),
WidgetType("codex_usage", "Codex usage", "Remaining five-hour and weekly capacity", "bi-speedometer2", "dashboard/widgets/codex_usage.html", 2),
)
}
+12 -8
View File
@@ -20,20 +20,24 @@
indicator.className = 'widget-drop-indicator';
indicator.setAttribute('aria-hidden', 'true');
grid.append(indicator);
const icons = { welcome: 'bi-sun', notes: 'bi-sticky', shortcuts: 'bi-grid', open_meteo: 'bi-cloud-sun', buienradar: 'bi-cloud-rain' };
const titles = { welcome: 'Welcome', notes: 'Quick notes', shortcuts: 'Shortcuts', open_meteo: 'Weather forecast', buienradar: 'Rain radar' };
const spans = { welcome: 2, notes: 1, shortcuts: 1, open_meteo: 2, buienradar: 2 };
const multiple = { welcome: false, notes: true, shortcuts: false, open_meteo: false, buienradar: false };
const icons = { welcome: 'bi-sun', notes: 'bi-sticky', shortcuts: 'bi-grid', open_meteo: 'bi-cloud-sun', buienradar: 'bi-cloud-rain', codex_usage: 'bi-speedometer2' };
const titles = { welcome: 'Welcome', notes: 'Quick notes', shortcuts: 'Shortcuts', open_meteo: 'Weather forecast', buienradar: 'Rain radar', codex_usage: 'Codex usage' };
const spans = { welcome: 2, notes: 1, shortcuts: 1, open_meteo: 2, buienradar: 2, codex_usage: 2 };
const multiple = { welcome: false, notes: true, shortcuts: false, open_meteo: false, buienradar: false, codex_usage: false };
function setStatus(message, error = false) {
status.textContent = message;
status.classList.toggle('error', error);
}
function widgetCards(root) {
if (!root || typeof root.querySelectorAll !== 'function') return [];
return root.matches?.('.widget-card') ? [root] : [...root.querySelectorAll('.widget-card')];
}
function cards() { return [...grid.querySelectorAll(':scope > .widget-card')]; }
function updateEmpty() { document.querySelector('#empty-layout').hidden = cards().length > 0; }
function markDirty() { dirty = true; setStatus('Unsaved layout changes'); updateEmpty(); }
function mount(root) {
const targets = root.matches?.('.widget-card') ? [root] : [...root.querySelectorAll('.widget-card')];
const targets = widgetCards(root);
targets.forEach(card => {
if (lifecycle.has(card)) return;
const controller = new AbortController();
@@ -43,13 +47,13 @@
markDirty();
}, { signal: controller.signal });
}
const widgetCleanup = card.dataset.widgetType === 'open_meteo' ? window.DashboardOpenMeteo?.mount(card) : card.dataset.widgetType === 'buienradar' ? window.DashboardBuienradar?.mount(card) : null;
const widgetCleanup = card.dataset.widgetType === 'open_meteo' ? window.DashboardOpenMeteo?.mount(card) : card.dataset.widgetType === 'buienradar' ? window.DashboardBuienradar?.mount(card) : card.dataset.widgetType === 'codex_usage' ? window.DashboardCodexUsage?.mount(card) : null;
lifecycle.set(card, () => { controller.abort(); widgetCleanup?.(); });
card.dispatchEvent(new CustomEvent('dashboard:widget-mounted', { bubbles: true }));
});
}
function unmount(root) {
const targets = root.matches?.('.widget-card') ? [root] : [...root.querySelectorAll('.widget-card')];
const targets = widgetCards(root);
targets.forEach(card => { lifecycle.get(card)?.(); lifecycle.delete(card); card.dispatchEvent(new CustomEvent('dashboard:widget-unmounted', { bubbles: true })); });
}
document.addEventListener('htmx:beforeCleanupElement', event => unmount(event.detail.elt));
@@ -103,7 +107,7 @@
}
function widgetMarkup(type) {
const icon = icons[type], title = titles[type];
const body = type === 'open_meteo' ? document.querySelector('#open-meteo-widget-template').innerHTML : type === 'buienradar' ? document.querySelector('#buienradar-widget-template').innerHTML : type === 'notes' ? '<p class="note-preview">Add a note in widget settings.</p>' : type === 'welcome' ? '<p>Welcome to your dashboard. Arrange the cards to fit your day.</p><p class="widget-muted">This is a placeholder widget. Live data widgets will be added separately.</p>' : '<nav class="widget-shortcuts" aria-label="Quick links"><a href="/projects/">Projects ↗</a><a href="/examples/today/">Design examples ↗</a></nav>';
const body = type === 'open_meteo' ? document.querySelector('#open-meteo-widget-template').innerHTML : type === 'buienradar' ? document.querySelector('#buienradar-widget-template').innerHTML : type === 'codex_usage' ? document.querySelector('#codex-usage-widget-template').innerHTML : type === 'notes' ? '<p class="note-preview">Add a note in widget settings.</p>' : type === 'welcome' ? '<p>Welcome to your dashboard. Arrange the cards to fit your day.</p><p class="widget-muted">This is a placeholder widget. Live data widgets will be added separately.</p>' : '<nav class="widget-shortcuts" aria-label="Quick links"><a href="/projects/">Projects ↗</a><a href="/examples/today/">Design examples ↗</a></nav>';
return `<header class="widget-card-head"><div><i class="bi ${icon}" aria-hidden="true"></i><h2>${title}</h2></div><div class="widget-controls"><button type="button" data-move="left" aria-label="Move ${title} earlier" title="Move earlier">←</button><button type="button" data-move="right" aria-label="Move ${title} later" title="Move later">→</button><button type="button" data-span-toggle aria-label="Resize ${title}" title="Resize">↔</button><button type="button" data-settings-toggle aria-label="Settings for ${title}" title="Settings"><i class="bi bi-sliders"></i></button><button type="button" data-remove aria-label="Remove ${title}" title="Remove"><i class="bi bi-x-lg"></i></button><span class="drag-handle" draggable="true" aria-hidden="true"><i class="bi bi-grip-vertical"></i></span></div></header><div class="widget-body">${body}</div><div class="widget-settings" hidden>${type === 'notes' ? '<label>Note text <textarea data-setting="text" maxlength="1000"></textarea></label>' : '<p>No settings for this widget.</p>'}</div>`;
}
function add(type, before = null) {
@@ -0,0 +1 @@
.codex-usage{min-width:0}.codex-usage-top,.codex-usage-footer{display:flex;justify-content:space-between;align-items:center;gap:12px}.codex-usage-top{margin-bottom:18px}.codex-usage-state{display:inline-flex;align-items:center;gap:7px;font-size:12px;font-weight:700;color:var(--accent)}.codex-usage-state:before{content:"";width:7px;height:7px;border-radius:50%;background:currentColor}.codex-usage-state.is-stale,.codex-usage-state.is-limited{color:var(--text-secondary)}.codex-usage-state.is-error{color:var(--negative)}.codex-usage-checked,.codex-usage-reset,.codex-usage-footer,.codex-usage-note{font-size:12px;color:var(--text-secondary)}.codex-usage-gauges{display:grid;grid-template-columns:repeat(auto-fit,minmax(145px,1fr));gap:20px}.codex-usage-window{display:flex;flex-direction:column;align-items:center;gap:4px;text-align:center;padding:12px;border-radius:var(--radius-md);background:var(--surface-secondary)}.codex-usage-ring{width:116px;aspect-ratio:1;border-radius:50%;display:grid;place-items:center;background:conic-gradient(var(--accent) var(--usage-progress,0%),var(--border) 0);margin-bottom:5px}.codex-usage-ring-inner{width:88px;aspect-ratio:1;border-radius:50%;display:flex;flex-direction:column;align-items:center;justify-content:center;background:var(--surface-secondary);color:var(--text)}.codex-usage-ring-inner strong{font-size:26px;line-height:1.1}.codex-usage-ring-inner small{font-size:11px;color:var(--text-secondary)}.codex-usage-label{font-size:13px;color:var(--text)}.codex-usage-reset{line-height:1.4}.codex-usage-note{margin:14px 0 0!important}.codex-usage-footer{border-top:1px solid var(--border);margin:16px 0 0!important;padding-top:10px}.codex-usage-panel[aria-busy="true"]{opacity:.75}@media(max-width:420px){.codex-usage-gauges{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.codex-usage-window{padding:10px 4px}.codex-usage-ring{width:96px}.codex-usage-ring-inner{width:73px}.codex-usage-ring-inner strong{font-size:22px}}
+26
View File
@@ -0,0 +1,26 @@
(() => {
window.DashboardCodexUsage = {
mount(card) {
const root = card.querySelector('[data-codex-usage]');
if (!root) return () => {};
const panel = root.querySelector('.codex-usage-panel');
const next = root.querySelector('[data-next-refresh]');
const controller = new AbortController();
let due = Date.now() + 60000;
function updateTimes() {
next.dateTime = new Date(due).toISOString();
next.textContent = new Date(due).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
panel.querySelectorAll('time[datetime]').forEach(time => {
const date = new Date(time.dateTime);
if (!Number.isNaN(date.getTime())) time.textContent = date.toLocaleString([], { day: 'numeric', month: 'short', hour: 'numeric', minute: '2-digit' });
});
}
panel.addEventListener('htmx:beforeRequest', () => { panel.setAttribute('aria-busy', 'true'); }, { signal: controller.signal });
panel.addEventListener('htmx:afterRequest', () => { panel.setAttribute('aria-busy', 'false'); }, { signal: controller.signal });
panel.addEventListener('htmx:afterSwap', () => { due = Date.now() + 60000; updateTimes(); }, { signal: controller.signal });
updateTimes();
window.htmx?.process(panel);
return () => { controller.abort(); };
},
};
})();
+3 -2
View File
@@ -1,4 +1,4 @@
{% extends 'core/base.html' %}{% load static %}{% block content %}<link rel="stylesheet" href="{% static 'dashboard/builder.css' %}"><link rel="stylesheet" href="{% static 'dashboard/open_meteo.css' %}"><link rel="stylesheet" href="{% static 'dashboard/buienradar.css' %}"><link rel="stylesheet" href="{% static 'dashboard/companion.css' %}">
{% extends 'core/base.html' %}{% load static %}{% block content %}<link rel="stylesheet" href="{% static 'dashboard/builder.css' %}"><link rel="stylesheet" href="{% static 'dashboard/open_meteo.css' %}"><link rel="stylesheet" href="{% static 'dashboard/buienradar.css' %}"><link rel="stylesheet" href="{% static 'dashboard/codex_usage.css' %}?v=20261022"><link rel="stylesheet" href="{% static 'dashboard/companion.css' %}">
<div class="page-heading dashboard-heading"><div><div class="eyebrow"><span class="eyebrow-line"></span> YOUR WORKSPACE</div><h1>{{ title }}<span class="heading-period">.</span></h1><p>Make this space your own with a few useful widgets.</p></div><div class="dashboard-actions"><button class="button secondary" id="catalogue-toggle" type="button" aria-controls="widget-catalogue" aria-expanded="false" aria-label="Open widget catalogue"><i class="bi bi-gear"></i> Widgets</button><button class="button secondary" id="reset-layout" type="button" hidden>Reset</button><button class="button primary" id="edit-layout" type="button">Edit layout</button></div></div>
<div id="layout-status" class="layout-status" role="status" aria-live="polite">Layout saved</div><button class="button secondary" id="companion-toggle" type="button" aria-pressed="false">Show companion</button>
<div class="dashboard-pages" aria-label="Dashboard pages"><a href="{% url 'dashboard:index' %}" {% if dashboard_page == 'overview' %}aria-current="page"{% endif %}>Overview</a><a href="{% url 'dashboard:page' 'personal' %}" {% if dashboard_page == 'personal' %}aria-current="page"{% endif %}>Personal</a></div>
@@ -8,7 +8,8 @@
<p id="empty-layout" class="empty-layout" {% if instances %}hidden{% endif %}>This page is empty. Choose <strong>Edit layout</strong>, then add a widget.</p>
<template id="open-meteo-widget-template">{% include 'dashboard/widgets/open_meteo.html' %}</template>
<template id="buienradar-widget-template">{% include 'dashboard/widgets/buienradar.html' %}</template>
<template id="codex-usage-widget-template">{% include 'dashboard/widgets/codex_usage.html' %}</template>
<aside id="widget-catalogue" class="widget-catalogue" aria-label="Widget catalogue" aria-hidden="true" inert><div class="catalogue-head"><div><span class="eyebrow">BUILD YOUR PAGE</span><h2>Widgets</h2></div><button type="button" id="catalogue-close" class="button ghost" aria-label="Close widget catalogue"><i class="bi bi-x-lg"></i></button></div><label for="widget-search">Search widgets</label><input id="widget-search" type="search" placeholder="Search by name or description"><div class="catalogue-list">{% for widget in catalogue %}<div class="catalogue-entry" draggable="true" data-widget-type="{{ widget.id }}" data-title="{{ widget.title|lower }}" data-description="{{ widget.description|lower }}"><i class="bi {{ widget.icon }}" aria-hidden="true"></i><div><strong>{{ widget.title }}</strong><small>{{ widget.description }}</small></div><button type="button" class="button secondary" data-add="{{ widget.id }}">Add</button></div>{% endfor %}</div><p class="catalogue-hint">Drag onto a dashed slot, or use Add and the Move controls. Changes save when you select Done.</p></aside><div id="catalogue-backdrop" class="catalogue-backdrop" hidden></div>
{{ catalogue|length|json_script:"widget-count" }}
<script src="{% static 'dashboard/location.js' %}" defer></script><script src="{% static 'dashboard/open_meteo.js' %}" defer></script><script src="{% static 'dashboard/buienradar.js' %}" defer></script><script src="{% static 'dashboard/builder.js' %}" defer></script><script src="{% static 'dashboard/companion.js' %}" defer></script><script src="{% static 'dashboard/companion-dashboard.js' %}" defer></script>
<script src="{% static 'dashboard/location.js' %}" defer></script><script src="{% static 'dashboard/open_meteo.js' %}" defer></script><script src="{% static 'dashboard/buienradar.js' %}" defer></script><script src="{% static 'dashboard/codex_usage.js' %}?v=20261022" defer></script><script src="{% static 'dashboard/builder.js' %}?v=20261022" defer></script><script src="{% static 'dashboard/companion.js' %}" defer></script><script src="{% static 'dashboard/companion-dashboard.js' %}" defer></script><script src="https://unpkg.com/htmx.org@2.0.4" defer></script>
{% endblock %}
@@ -0,0 +1,5 @@
{% if usage %}
<div class="codex-usage-top"><span class="codex-usage-state {% if usage.stale %}is-stale{% elif not usage.allowed %}is-limited{% endif %}">{% if usage.stale %}Stale data{% elif not usage.allowed %}Usage limited{% else %}Live usage{% endif %}</span>{% if usage.checked %}<span class="codex-usage-checked">Checked <time datetime="{{ usage.checked|date:'c' }}">{{ usage.checked|date:'j M H:i' }}</time></span>{% endif %}</div>
{% if usage.windows %}<div class="codex-usage-gauges">{% for window in usage.windows %}<div class="codex-usage-window"><div class="codex-usage-ring" {% if window.remaining is not None %}style="--usage-progress:{{ window.remaining }}%"{% endif %} role="img" aria-label="{{ window.bucket }} {{ window.title }}: {% if window.remaining is not None %}{{ window.remaining }} percent remaining{% else %}remaining usage unknown{% endif %}"><div class="codex-usage-ring-inner"><strong>{% if window.remaining is not None %}{{ window.remaining }}%{% else %}—{% endif %}</strong><small>left</small></div></div><strong class="codex-usage-label">{{ window.title }}</strong>{% if window.reset %}<span class="codex-usage-reset">Resets <time datetime="{{ window.reset|date:'c' }}">{{ window.reset|date:'j M H:i' }}</time></span>{% else %}<span class="codex-usage-reset">Reset time unavailable</span>{% endif %}</div>{% endfor %}</div>{% else %}<p class="codex-usage-state">No usage windows available.</p>{% endif %}
{% if usage.stale %}<p class="codex-usage-note">Showing the last available snapshot. The next refresh will retry.</p>{% endif %}
{% else %}<p class="codex-usage-state is-error" role="status">Usage is unavailable right now. The next refresh will retry.</p>{% endif %}
@@ -0,0 +1,6 @@
{% load static %}<div class="codex-usage" data-codex-usage>
<div class="codex-usage-panel" hx-get="{% url 'dashboard:codex_usage' %}" hx-trigger="load, every 60s" hx-swap="innerHTML" aria-busy="true">
<p class="codex-usage-state" role="status">Loading usage…</p>
</div>
<p class="codex-usage-footer">Next refresh <time data-next-refresh>soon</time></p>
</div>
+31
View File
@@ -14,6 +14,7 @@ from .models import DashboardLayout
from .views import validate_widgets
from .weather import ForecastUnavailable, coordinates, get_forecast
from .buienradar import RainUnavailable, get_rain, parse_forecast
from .codex_usage import _display, get_usage
class DashboardTests(TestCase):
@@ -130,6 +131,36 @@ class DashboardTests(TestCase):
def test_buienradar_stale_fallback(self):
cache = caches["weather"]
cache.clear()
def test_codex_usage_registry_and_private_panel(self):
from .registry import WIDGETS
self.assertIn("codex_usage", WIDGETS)
item = {"id": str(uuid.uuid4()), "type": "codex_usage", "span": 2, "settings": {}, "visible": True}
self.assertEqual(validate_widgets([item])[0]["type"], "codex_usage")
with self.assertRaises(ValueError):
validate_widgets([item, {**item, "id": str(uuid.uuid4())}])
url = reverse("dashboard:codex_usage")
self.assertEqual(self.client.get(url).status_code, 302)
self.client.force_login(self.one)
with patch("dashboard.views.get_usage", return_value={"windows": [{"title": "5 hours", "remaining": 17, "reset": None, "bucket": "codex"}], "checked": None, "stale": False, "allowed": True}):
response = self.client.get(url)
self.assertContains(response, "17%")
self.assertContains(response, "Reset time unavailable")
def test_codex_usage_normalizes_live_shape_and_stale_cache(self):
raw = {"service": "codex", "status": "ok", "last_checked": "2026-10-21T22:56:50.106Z", "raw": {"ordinaryUsageAllowed": True, "accountId": "private", "rateLimitsByLimitId": {"codex": {"primary": {"usedPercent": 83, "windowDurationMins": 300, "resetsAt": 1792625545}, "secondary": {"usedPercent": 60, "windowDurationMins": 10080, "resetsAt": 1793101162}}}}}
display = _display(raw)
self.assertEqual([window["remaining"] for window in display["windows"]], [17, 40])
self.assertNotIn("private", str(display))
cache = caches["weather"]
cache.delete("codex-usage:v1")
cache.delete("codex-usage:last-good")
cache.set("codex-usage:last-good", display, 60)
with patch("dashboard.codex_usage.urllib.request.urlopen", side_effect=OSError("offline")):
fallback = get_usage()
self.assertTrue(fallback["stale"])
self.assertEqual(fallback["windows"][0]["remaining"], 17)
cache.delete("codex-usage:last-good")
key = hashlib.sha256(b"buienradar:v1:52.96:5.92").hexdigest()
cache.set(f"stale:{key}", {"points": [{"time": "2026-10-14T23:55:00+02:00", "mm_per_hour": 0, "label": "None"}], "fetched_at": "2026-10-14T21:55:00+00:00"}, 60)
with patch("dashboard.buienradar.request_rain", side_effect=OSError("offline")):
+2 -1
View File
@@ -4,8 +4,9 @@ from . import views
app_name = "dashboard"
urlpatterns = [
path("", views.index, name="index"),
path("dashboard/<slug:page>/", views.page, name="page"),
path("dashboard/<slug:page>/layout/", views.layout_api, name="layout"),
path("dashboard/weather/open-meteo/", views.open_meteo_api, name="open_meteo"),
path("dashboard/weather/buienradar/", views.buienradar_api, name="buienradar"),
path("dashboard/codex-usage/", views.codex_usage_panel, name="codex_usage"),
path("dashboard/<slug:page>/", views.page, name="page"),
]
+7
View File
@@ -12,6 +12,7 @@ from .models import DashboardLayout
from .registry import WIDGETS
from .weather import ForecastUnavailable, get_forecast
from .buienradar import RainUnavailable, get_rain
from .codex_usage import get_usage
PAGES = {"overview": "Overview", "personal": "Personal"}
@@ -120,3 +121,9 @@ def buienradar_api(request):
except RainUnavailable as exc:
return JsonResponse({"error": str(exc)}, status=503)
return JsonResponse(rain)
@login_required
@require_http_methods(["GET"])
def codex_usage_panel(request):
return render(request, "dashboard/widgets/_codex_usage_panel.html", {"usage": get_usage()})