{{ project.name }}
+{{ project.description|default:'No project description yet.'|truncatechars:180 }}
+diff --git a/codex-usage.py b/codex-usage.py new file mode 100644 index 0000000..3580fc3 --- /dev/null +++ b/codex-usage.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +"""Portable, dependency-free Codex usage display (Python 3.8+).""" + +import argparse +import datetime as dt +import json +import math +import os +import tempfile +import hashlib +import shutil +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + + +def clean(value): + # Never allow API text to inject terminal control sequences. + return "".join(c for c in str(value) if c.isprintable()) + + +def timestamp(value): + try: + if isinstance(value, str): + result = dt.datetime.fromisoformat(value.replace("Z", "+00:00")) + else: + result = dt.datetime.fromtimestamp(value, dt.timezone.utc) + return result.astimezone().strftime("%d %b %H:%M %Z") + except (ValueError, TypeError, OverflowError, OSError): + return "unknown" + + +def window_line(label, window, width): + if not isinstance(window, dict): + return [label + ": unavailable"] + used = window.get("usedPercent") + if isinstance(used, (int, float)) and not isinstance(used, bool) and math.isfinite(used): + used = max(0, min(100, used)) + size = max(5, min(30, width - 40)) + filled = round(size * used / 100) + bar = "#" * filled + "-" * (size - filled) + summary = "{} [{}] {:g}% used / {:g}% left".format(label, bar, used, 100 - used) + else: + summary = label + ": usage unknown" + reset = window.get("resetsAt") + countdown = "" + if isinstance(reset, (int, float)) and math.isfinite(reset): + seconds = max(0, int(reset - time.time())) + hours, minutes = divmod(seconds // 60, 60) + countdown = " (in {}h {:02d}m)".format(hours, minutes) if seconds else " (awaiting fresh poll)" + return [summary, " Reset: " + timestamp(reset) + countdown] + + +def render(data, failure, width): + lines = ["CODEX USAGE", ""] + if failure: + lines += ["OFFLINE - " + failure, "Showing last successful response" if data else "No usage data yet", ""] + if data: + stale = data.get("stale") or data.get("status") != "ok" or bool(failure) + raw = data.get("raw") or {} + if not isinstance(raw, dict): + raw = {} + allowed = raw.get("ordinaryUsageAllowed") + lines += ["State: {} | Allowed: {}".format("STALE" if stale else "OK", {True: "yes", False: "no"}.get(allowed, "unknown")), + "Last server poll: " + timestamp(data.get("last_checked")), ""] + buckets = raw.get("rateLimitsByLimitId") + if not isinstance(buckets, dict) or not buckets: + buckets = {"codex": raw.get("rateLimits")} + for name, bucket in list(buckets.items())[:20]: + if not isinstance(bucket, dict): + continue + lines.append("{} | Plan: {}".format(clean(name), clean(bucket.get("planType") or "unknown"))) + for key in ("primary", "secondary"): + window = bucket.get(key) + duration = window.get("windowDurationMins") if isinstance(window, dict) else None + label = {300: "5-hour", 10080: "Weekly"}.get(duration, "{} min".format(duration) if duration else key.title()) + lines.extend(window_line(label, window, width)) + credits = bucket.get("credits") + if isinstance(credits, dict): + lines.append("Credits: " + ("unlimited" if credits.get("unlimited") else clean(credits.get("balance", "unknown")))) + lines.append("") + lines.append("Display: {} | Ctrl-C to quit".format(time.strftime("%H:%M:%S"))) + return [clean(line)[:width] for line in lines] + + +def fetch(url, timeout=5): + request = urllib.request.Request(url, headers={"Accept": "application/json"}) + try: + response = urllib.request.urlopen(request, timeout=timeout) + except urllib.error.HTTPError as exc: + if exc.code != 503: + raise + response = exc + with response: + body = response.read(1024 * 1024 + 1) + if len(body) > 1024 * 1024: + raise ValueError("response exceeds 1 MiB") + data = json.loads(body) + if not isinstance(data, dict) or data.get("service") != "codex": + raise ValueError("endpoint did not return Codex usage data") + return data + + +def cache_path(url): + digest = hashlib.sha256(url.encode("utf-8")).hexdigest()[:16] + return os.path.join(tempfile.gettempdir(), "codex-usage-{}-{}.json".format(os.getuid(), digest)) + + +def cached_fetch(url, ttl, timeout): + path = cache_path(url) + cached = None + try: + info = os.lstat(path) + if info.st_uid == os.getuid() and info.st_mode & 0o077 == 0 and info.st_size <= 1024 * 1024: + with open(path, "r") as stream: + cached = json.load(stream) + if (not isinstance(cached, dict) or not isinstance(cached.get("data"), dict) + or not isinstance(cached.get("fetched_at"), (int, float))): + cached = None + except (OSError, ValueError, TypeError): + pass + if cached and 0 <= time.time() - cached["fetched_at"] < ttl: + return cached["data"], None + try: + data = fetch(url, timeout) + if data.get("status") == "unavailable": + return cached["data"] if cached else None, "offline" + fd, temporary = tempfile.mkstemp(prefix=".codex-usage-", dir=tempfile.gettempdir()) + try: + with os.fdopen(fd, "w") as stream: + json.dump({"fetched_at": time.time(), "data": data}, stream) + os.replace(temporary, path) + finally: + if os.path.exists(temporary): + os.unlink(temporary) + return data, None + except (urllib.error.URLError, OSError, ValueError, TimeoutError): + return cached["data"] if cached else None, "offline" + + +def tmux_line(data, failure, compact=True, width=30): + if failure or not data: + return "C OFFLINE" if compact or width < 22 else "CODEX OFFLINE" + if data.get("stale") or data.get("status") != "ok": + return "C STALE" if compact or width < 22 else "CODEX STALE" + raw = data.get("raw") + if not isinstance(raw, dict): + return "C STALE" if compact or width < 22 else "CODEX STALE" + buckets = raw.get("rateLimitsByLimitId") + if not isinstance(buckets, dict) or not buckets: + buckets = {"codex": raw.get("rateLimits")} + values = {} + for bucket in list(buckets.values())[:20]: + 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") + used = window.get("usedPercent") + if isinstance(used, (int, float)) and not isinstance(used, bool) and math.isfinite(used): + if duration == 300: + values.setdefault("5h", round(max(0, min(100, 100 - used)))) + elif duration == 10080: + values.setdefault("W", round(max(0, min(100, 100 - used)))) + if not values: + return "C STALE" if compact or width < 22 else "CODEX STALE" + short = compact or width < 30 + prefix = "C" if short else "CODEX" + parts = [prefix] + if "5h" in values: + parts.append(("" if short else "5h ") + "{}%".format(values["5h"])) + if "W" in values: + parts.append("W {}%".format(values["W"])) + return " ".join(parts)[:width] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--url", default=os.environ.get("CODEX_USAGE_URL", "http://127.0.0.1:3100"), help="server base URL or full /api/usage URL (env: CODEX_USAGE_URL)") + parser.add_argument("--interval", type=float, default=10, help="display fetch interval in seconds (default: 10)") + parser.add_argument("--once", action="store_true", help="print once without terminal controls") + parser.add_argument("--tmux", action="store_true", help="print one compact status-bar line") + parser.add_argument("--compact", action="store_true", help="use short status labels") + parser.add_argument("--width", type=int, default=30, help="maximum tmux output width (default: 30)") + parser.add_argument("--cache-ttl", type=float, default=45, help="cache lifetime in seconds (default: 45)") + args = parser.parse_args() + if not math.isfinite(args.interval) or args.interval < 1: + parser.error("--interval must be at least 1 second") + if args.width < 8 or not math.isfinite(args.cache_ttl) or args.cache_ttl < 0: + parser.error("--width must be at least 8 and --cache-ttl must be nonnegative") + url = args.url.rstrip("/") + parsed = urllib.parse.urlsplit(url) + if parsed.scheme not in ("http", "https") or not parsed.hostname or parsed.query or parsed.fragment or parsed.username: + parser.error("--url must be an HTTP(S) URL without credentials, query or fragment") + if not parsed.path or parsed.path == "/": + url += "/api/usage" + if args.tmux: + data, failure = cached_fetch(url, args.cache_ttl, 2) + print(tmux_line(data, failure, True, args.width)) + return 1 if failure else 0 + interactive = sys.stdout.isatty() and os.environ.get("TERM") != "dumb" and not args.once + data, failure = None, None + if interactive: + sys.stdout.write("\033[?1049h\033[?25l") + try: + while True: + failure = None + try: + received, cache_failure = cached_fetch(url, 0, 5) + if cache_failure: + raise ValueError("usage API unavailable") + if received.get("status") == "unavailable": + failure = "server has no successful usage snapshot" + else: + data = received + except (urllib.error.URLError, OSError, ValueError, TimeoutError): + failure = "cannot fetch usage; check endpoint, network and service" + width, height = shutil.get_terminal_size((80, 24)) + lines = render(data, failure, width) + if interactive: + sys.stdout.write("\033[H\033[2J") + lines = lines[:max(1, height - 1)] + print("\n".join(lines), flush=True) + if args.once: + return 1 if failure else 0 + time.sleep(args.interval) + except KeyboardInterrupt: + return 0 + finally: + if interactive: + sys.stdout.write("\033[?25h\033[?1049l") + sys.stdout.flush() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/dashboard/codex_usage.py b/dashboard/codex_usage.py new file mode 100644 index 0000000..7fbe3eb --- /dev/null +++ b/dashboard/codex_usage.py @@ -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 diff --git a/dashboard/registry.py b/dashboard/registry.py index ac0e234..87c11e4 100644 --- a/dashboard/registry.py +++ b/dashboard/registry.py @@ -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), ) } diff --git a/dashboard/static/dashboard/builder.js b/dashboard/static/dashboard/builder.js index 0cf51f9..8e2c30c 100644 --- a/dashboard/static/dashboard/builder.js +++ b/dashboard/static/dashboard/builder.js @@ -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' ? '
Add a note in widget settings.
' : type === 'welcome' ? 'Welcome to your dashboard. Arrange the cards to fit your day.
' : ''; + 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' ? 'Add a note in widget settings.
' : type === 'welcome' ? 'Welcome to your dashboard. Arrange the cards to fit your day.
' : ''; return `Make this space your own with a few useful widgets.
This page is empty. Choose Edit layout, then add a widget.
{% include 'dashboard/widgets/open_meteo.html' %} {% include 'dashboard/widgets/buienradar.html' %} +{% include 'dashboard/widgets/codex_usage.html' %} {{ catalogue|length|json_script:"widget-count" }} - + {% endblock %} diff --git a/dashboard/templates/dashboard/widgets/_codex_usage_panel.html b/dashboard/templates/dashboard/widgets/_codex_usage_panel.html new file mode 100644 index 0000000..89e4bce --- /dev/null +++ b/dashboard/templates/dashboard/widgets/_codex_usage_panel.html @@ -0,0 +1,5 @@ +{% if usage %} +No usage windows available.
{% endif %} +{% if usage.stale %}Showing the last available snapshot. The next refresh will retry.
{% endif %} +{% else %}Usage is unavailable right now. The next refresh will retry.
{% endif %} diff --git a/dashboard/templates/dashboard/widgets/codex_usage.html b/dashboard/templates/dashboard/widgets/codex_usage.html new file mode 100644 index 0000000..f9a5eb9 --- /dev/null +++ b/dashboard/templates/dashboard/widgets/codex_usage.html @@ -0,0 +1,6 @@ +{% load static %}Loading usage…
+{% if show_archived %}No archived cards in this column.{% else %}No cards in this column yet.{% endif %}
{% endif %}{{ project.description|truncatechars:180 }}
{{ project.card_count }} cardsNo projects found.
{% endfor %}{{ project.description|default:'No project description yet.'|truncatechars:180 }}
+{% if query %}Try a different project or card search.{% elif show_archived %}Archived projects will appear here.{% else %}Create a project to start organizing cards and specifications.{% endif %}
{% if not query and not show_archived %} New project{% endif %}{{ project.description }}
{% if project.git_repository_url %}Repository{% endif %}{{ done_count }} of {{ total_count }} cards done
{{ project.description }}
{% endif %} +On narrow screens, scroll horizontally to see more columns. Use the move controls on each card to move it without dragging.
{% if columns|length > 1 %}{% endif %}UPDATES
{% if event.card %}{{ event.card.title }} {{ event.display_action }}{% else %}{{ event.display_action }}{% endif %}
{% if event.actor %}{{ event.actor }}{% else %}A former member{% endif %} ·{% if event.card %}{{ event.card.title }} {{ event.display_action }}{% else %}{{ event.display_action }}{% endif %}
{% if event.actor %}{{ event.actor }}{% else %}A former member{% endif %} ·No activity yet. Updates will appear here.
{% endif %} +{{ card.get_priority_display }} {{ card.column.name }} · {{ card.get_card_type_display }} · Revision {{ card.revision }}
-{{ card.description_markdown }}{{ comment.body|linebreaksbr }}
This card is archived.
{% endif %} +{{ card.project.name }}
CARD DETAILS
No description has been added to this card.
{% endif %} +{{ card.description_markdown }}DISCUSSION
{{ comment.body|linebreaksbr }}
No progress notes yet.
{% endfor %}Boards and specifications across your workspace.
WORKSPACE
Boards and specifications across your workspace.