Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

feat: add OpenAI Codex rate-limit window tracking

JerrettDavisa3abbec4a30e
diff --git a/docs/screenshots/subscription_window_active.png b/docs/screenshots/subscription_window_active.png
index 7b8b9d0a2..d826cf4f1 100644
Binary files a/docs/screenshots/subscription_window_active.png and b/docs/screenshots/subscription_window_active.png differ
diff --git a/headroom/dashboard/templates/dashboard.html b/headroom/dashboard/templates/dashboard.html
index 1fc4dd8d1..007540bed 100644
--- a/headroom/dashboard/templates/dashboard.html
+++ b/headroom/dashboard/templates/dashboard.html
@@ -297,6 +297,79 @@
</template>
</div>
</template>
+ <!-- Codex Rate-Limit Window -->
+ <template x-if="stats.codex_rate_limits && stats.codex_rate_limits.primary">
+ <div class="bg-surface rounded-lg p-4 border border-border mb-6">
+ <div class="flex justify-between items-center mb-3">
+ <div class="text-sm font-medium text-gray-300">OpenAI Codex Rate-Limit Window</div>
+ <div class="flex items-center gap-2">
+ <template x-if="stats.codex_rate_limits.limit_name">
+ <span class="text-xs text-gray-500 font-mono" x-text="stats.codex_rate_limits.limit_name"></span>
+ </template>
+ <template x-if="stats.codex_rate_limits.credits">
+ <span class="text-xs font-mono"
+ :class="stats.codex_rate_limits.credits.unlimited ? 'text-purple-400' : stats.codex_rate_limits.credits.has_credits ? 'text-emerald-400' : 'text-red-400'"
+ x-text="stats.codex_rate_limits.credits.unlimited ? '∞ Unlimited' : stats.codex_rate_limits.credits.balance ? stats.codex_rate_limits.credits.balance : (stats.codex_rate_limits.credits.has_credits ? 'Credits' : 'No Credits')"></span>
+ </template>
+ </div>
+ </div>
+ <!-- Primary window -->
+ <div class="mb-3">
+ <div class="flex justify-between items-center mb-1">
+ <div class="flex items-center gap-2">
+ <span class="text-xs text-gray-500">Primary</span>
+ <template x-if="stats.codex_rate_limits.primary.window_label">
+ <span class="text-xs text-gray-600 font-mono"
+ x-text="'(' + stats.codex_rate_limits.primary.window_label + ' window)'"></span>
+ </template>
+ </div>
+ <span class="text-sm font-mono font-semibold"
+ :class="(stats.codex_rate_limits.primary.used_percent||0) > 80 ? 'text-red-400' : (stats.codex_rate_limits.primary.used_percent||0) > 60 ? 'text-amber-400' : 'text-emerald-400'"
+ x-text="(stats.codex_rate_limits.primary.used_percent||0).toFixed(1) + '%'"></span>
+ </div>
+ <div class="w-full bg-gray-700 rounded-full h-2">
+ <div class="h-2 rounded-full transition-all duration-500"
+ :class="(stats.codex_rate_limits.primary.used_percent||0) > 80 ? 'bg-red-500' : (stats.codex_rate_limits.primary.used_percent||0) > 60 ? 'bg-amber-500' : 'bg-emerald-500'"
+ :style="'width: ' + Math.min(stats.codex_rate_limits.primary.used_percent||0, 100) + '%'"></div>
+ </div>
+ <template x-if="stats.codex_rate_limits.primary.seconds_until_reset !== null">
+ <div class="text-xs text-gray-500 mt-1"
+ x-text="'Resets in ' + formatResetTime(stats.codex_rate_limits.primary.seconds_until_reset)"></div>
+ </template>
+ </div>
+ <!-- Secondary window (if present) -->
+ <template x-if="stats.codex_rate_limits.secondary">
+ <div class="mb-3">
+ <div class="flex justify-between items-center mb-1">
+ <div class="flex items-center gap-2">
+ <span class="text-xs text-gray-500">Secondary</span>
+ <template x-if="stats.codex_rate_limits.secondary.window_label">
+ <span class="text-xs text-gray-600 font-mono"
+ x-text="'(' + stats.codex_rate_limits.secondary.window_label + ' window)'"></span>
+ </template>
+ </div>
+ <span class="text-sm font-mono font-semibold"
+ :class="(stats.codex_rate_limits.secondary.used_percent||0) > 80 ? 'text-red-400' : (stats.codex_rate_limits.secondary.used_percent||0) > 60 ? 'text-amber-400' : 'text-emerald-400'"
+ x-text="(stats.codex_rate_limits.secondary.used_percent||0).toFixed(1) + '%'"></span>
+ </div>
+ <div class="w-full bg-gray-700 rounded-full h-2">
+ <div class="h-2 rounded-full transition-all duration-500"
+ :class="(stats.codex_rate_limits.secondary.used_percent||0) > 80 ? 'bg-red-500' : (stats.codex_rate_limits.secondary.used_percent||0) > 60 ? 'bg-amber-500' : 'bg-emerald-500'"
+ :style="'width: ' + Math.min(stats.codex_rate_limits.secondary.used_percent||0, 100) + '%'"></div>
+ </div>
+ <template x-if="stats.codex_rate_limits.secondary.seconds_until_reset !== null">
+ <div class="text-xs text-gray-500 mt-1"
+ x-text="'Resets in ' + formatResetTime(stats.codex_rate_limits.secondary.seconds_until_reset)"></div>
+ </template>
+ </div>
+ </template>
+ <!-- Promo message -->
+ <template x-if="stats.codex_rate_limits.promo_message">
+ <div class="mt-2 text-xs text-blue-400 italic"
+ x-text="stats.codex_rate_limits.promo_message"></div>
+ </template>
+ </div>
+ </template>
<template x-if="(stats.prefix_cache?.totals?.requests || 0) > 0">
<div class="bg-surface rounded-lg p-4 border border-border mb-6">
<div class="flex justify-between items-center mb-3">
diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.py
index c4c2b4745..ca081ebaf 100644
--- a/headroom/proxy/handlers/openai.py
+++ b/headroom/proxy/handlers/openai.py
@@ -701,6 +701,13 @@ class OpenAIHandlerMixin:
tokens_saved,
)
+ # Capture Codex rate-limit window data from response headers
+ from headroom.subscription.codex_rate_limits import (
+ get_codex_rate_limit_state,
+ )
+
+ get_codex_rate_limit_state().update_from_headers(dict(response.headers))
+
await self.metrics.record_request(
provider="openai",
model=model,
@@ -994,6 +1001,13 @@ class OpenAIHandlerMixin:
logger.info(f"[{request_id}] /v1/responses {model}: {total_input_tokens:,} tokens")
+ # Capture Codex rate-limit window data from response headers
+ from headroom.subscription.codex_rate_limits import (
+ get_codex_rate_limit_state,
+ )
+
+ get_codex_rate_limit_state().update_from_headers(dict(response.headers))
+
# Remove compression headers
response_headers = dict(response.headers)
response_headers.pop("content-encoding", None)
diff --git a/headroom/proxy/server.py b/headroom/proxy/server.py
index e0e584be7..70d62263e 100644
--- a/headroom/proxy/server.py
+++ b/headroom/proxy/server.py
@@ -127,6 +127,7 @@ from headroom.proxy.prometheus_metrics import PrometheusMetrics # noqa: F401
from headroom.proxy.rate_limiter import TokenBucketRateLimiter # noqa: F401
from headroom.proxy.request_logger import RequestLogger # noqa: F401
from headroom.proxy.semantic_cache import SemanticCache # noqa: F401
+from headroom.subscription.codex_rate_limits import get_codex_rate_limit_state
from headroom.subscription.tracker import (
configure_subscription_tracker,
get_subscription_tracker,
@@ -153,6 +154,12 @@ _build_prefix_cache_stats = build_prefix_cache_stats
_build_session_summary = build_session_summary
_merge_cost_stats = merge_cost_stats
+
+def _get_codex_rate_limit_stats() -> dict | None:
+ """Return the latest Codex rate-limit snapshot for the /stats endpoint."""
+ return get_codex_rate_limit_state().get_stats()
+
+
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
@@ -1393,6 +1400,7 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
"subscription_window": get_subscription_tracker().state
if get_subscription_tracker()
else None,
+ "codex_rate_limits": _get_codex_rate_limit_stats(),
}
@app.get("/stats-history")
diff --git a/headroom/subscription/__init__.py b/headroom/subscription/__init__.py
index c7f11cb2e..57661d947 100644
--- a/headroom/subscription/__init__.py
+++ b/headroom/subscription/__init__.py
@@ -1,6 +1,14 @@
-"""Subscription window tracking for Anthropic Claude Code accounts."""
+"""Subscription window tracking for Anthropic Claude Code accounts and Codex rate limits."""
from headroom.subscription.client import SubscriptionClient, read_cached_oauth_token
+from headroom.subscription.codex_rate_limits import (
+ CodexCreditsSnapshot,
+ CodexRateLimitSnapshot,
+ CodexRateLimitState,
+ CodexRateLimitWindow,
+ get_codex_rate_limit_state,
+ parse_codex_rate_limits,
+)
from headroom.subscription.models import (
ExtraUsage,
HeadroomContribution,
@@ -18,6 +26,10 @@ from headroom.subscription.tracker import (
)
__all__ = [
+ "CodexCreditsSnapshot",
+ "CodexRateLimitSnapshot",
+ "CodexRateLimitState",
+ "CodexRateLimitWindow",
"ExtraUsage",
"HeadroomContribution",
"RateLimitWindow",
@@ -28,7 +40,9 @@ __all__ = [
"WindowDiscrepancy",
"WindowTokens",
"configure_subscription_tracker",
+ "get_codex_rate_limit_state",
"get_subscription_tracker",
+ "parse_codex_rate_limits",
"read_cached_oauth_token",
"shutdown_subscription_tracker",
]
diff --git a/headroom/subscription/codex_rate_limits.py b/headroom/subscription/codex_rate_limits.py
new file mode 100644
index 000000000..8a87e29f0
--- /dev/null
+++ b/headroom/subscription/codex_rate_limits.py
@@ -0,0 +1,238 @@
+"""Passive tracking of OpenAI Codex rate-limit window data from response headers.
+
+Codex (OpenAI) embeds rate-limit data directly in API response headers
+(``x-codex-primary-used-percent``, ``x-codex-primary-window-minutes``, etc.)
+rather than exposing a dedicated usage endpoint. This module captures those
+headers from responses that headroom proxies and makes them available in
+``/stats`` and the dashboard.
+
+Header schema (parsed by codex-rs ``rate_limits.rs``):
+ x-codex-primary-used-percent float 0-100
+ x-codex-primary-window-minutes int window size
+ x-codex-primary-reset-at int Unix timestamp (seconds)
+ x-codex-secondary-used-percent float 0-100 (optional)
+ x-codex-secondary-window-minutes int (optional)
+ x-codex-secondary-reset-at int (optional)
+ x-codex-credits-has-credits bool
+ x-codex-credits-unlimited bool
+ x-codex-credits-balance str e.g. "$5.00"
+ x-codex-promo-message str server announcement
+ x-codex-limit-name str e.g. "gpt-5.2-codex-sonic"
+"""
+
+from __future__ import annotations
+
+import time
+from dataclasses import dataclass, field
+from threading import Lock
+
+
+@dataclass
+class CodexRateLimitWindow:
+ """Usage data for a single rolling rate-limit window."""
+
+ used_percent: float
+ window_minutes: int | None = None
+ resets_at: int | None = None # Unix timestamp (seconds)
+
+ @property
+ def window_label(self) -> str:
+ if self.window_minutes is None:
+ return "unknown"
+ if self.window_minutes < 60:
+ return f"{self.window_minutes}m"
+ hours = self.window_minutes // 60
+ mins = self.window_minutes % 60
+ return f"{hours}h{mins:02d}m" if mins else f"{hours}h"
+
+ @property
+ def seconds_until_reset(self) -> int | None:
+ if self.resets_at is None:
+ return None
+ return max(0, self.resets_at - int(time.time()))
+
+ def to_dict(self) -> dict:
+ return {
+ "used_percent": self.used_percent,
+ "window_minutes": self.window_minutes,
+ "window_label": self.window_label,
+ "resets_at": self.resets_at,
+ "seconds_until_reset": self.seconds_until_reset,
+ }
+
+
+@dataclass
+class CodexCreditsSnapshot:
+ """OpenAI credits balance for Codex."""
+
+ has_credits: bool
+ unlimited: bool
+ balance: str | None = None
+
+ def to_dict(self) -> dict:
+ return {
+ "has_credits": self.has_credits,
+ "unlimited": self.unlimited,
+ "balance": self.balance,
+ }
+
+
+@dataclass
+class CodexRateLimitSnapshot:
+ """Full rate-limit snapshot parsed from a single Codex API response."""
+
+ limit_id: str = "codex"
+ limit_name: str | None = None
+ primary: CodexRateLimitWindow | None = None
+ secondary: CodexRateLimitWindow | None = None
+ credits: CodexCreditsSnapshot | None = None
+ promo_message: str | None = None
+ captured_at: float = field(default_factory=time.time)
+
+ def to_dict(self) -> dict:
+ return {
+ "limit_id": self.limit_id,
+ "limit_name": self.limit_name,
+ "primary": self.primary.to_dict() if self.primary else None,
+ "secondary": self.secondary.to_dict() if self.secondary else None,
+ "credits": self.credits.to_dict() if self.credits else None,
+ "promo_message": self.promo_message,
+ "captured_at": self.captured_at,
+ }
+
+
+# ---------------------------------------------------------------------------
+# Header parsing helpers
+# ---------------------------------------------------------------------------
+
+
+def _parse_float(headers: dict[str, str], name: str) -> float | None:
+ raw = headers.get(name)
+ if raw is None:
+ return None
+ try:
+ v = float(raw)
+ return v if v == v else None # NaN guard
+ except (ValueError, TypeError):
+ return None
+
+
+def _parse_int(headers: dict[str, str], name: str) -> int | None:
+ raw = headers.get(name)
+ if raw is None:
+ return None
+ try:
+ return int(raw)
+ except (ValueError, TypeError):
+ return None
+
+
+def _parse_bool(headers: dict[str, str], name: str) -> bool | None:
+ raw = headers.get(name)
+ if raw is None:
+ return None
+ if raw.lower() in ("true", "1"):
+ return True
+ if raw.lower() in ("false", "0"):
+ return False
+ return None
+
+
+def _parse_window(headers: dict[str, str], prefix: str, which: str) -> CodexRateLimitWindow | None:
+ used_pct = _parse_float(headers, f"{prefix}-{which}-used-percent")
+ if used_pct is None:
+ return None
+ return CodexRateLimitWindow(
+ used_percent=used_pct,
+ window_minutes=_parse_int(headers, f"{prefix}-{which}-window-minutes"),
+ resets_at=_parse_int(headers, f"{prefix}-{which}-reset-at"),
+ )
+
+
+def _parse_credits(headers: dict[str, str]) -> CodexCreditsSnapshot | None:
+ has_credits = _parse_bool(headers, "x-codex-credits-has-credits")
+ if has_credits is None:
+ return None
+ unlimited = _parse_bool(headers, "x-codex-credits-unlimited") or False
+ raw_balance = headers.get("x-codex-credits-balance", "").strip()
+ return CodexCreditsSnapshot(
+ has_credits=has_credits,
+ unlimited=unlimited,
+ balance=raw_balance or None,
+ )
+
+
+def parse_codex_rate_limits(headers: dict[str, str]) -> CodexRateLimitSnapshot | None:
+ """Parse a :class:`CodexRateLimitSnapshot` from a dict of HTTP response headers.
+
+ Returns ``None`` when no Codex rate-limit headers are present (e.g. the
+ response came from a non-Codex OpenAI endpoint or a cached reply).
+ """
+ prefix = "x-codex"
+ primary = _parse_window(headers, prefix, "primary")
+ secondary = _parse_window(headers, prefix, "secondary")
+ credits = _parse_credits(headers)
+ raw_promo = headers.get("x-codex-promo-message", "").strip()
+ promo = raw_promo or None
+ raw_limit_name = headers.get("x-codex-limit-name", "").strip()
+ limit_name = raw_limit_name or None
+
+ if primary is None and secondary is None and credits is None and promo is None:
+ return None # Not a Codex response with rate-limit headers
+
+ return CodexRateLimitSnapshot(
+ limit_id="codex",
+ limit_name=limit_name,
+ primary=primary,
+ secondary=secondary,
+ credits=credits,
+ promo_message=promo,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Singleton state store
+# ---------------------------------------------------------------------------
+
+
+class CodexRateLimitState:
+ """Thread-safe store for the latest Codex rate-limit snapshot.
+
+ Updated by the OpenAI proxy handler each time a response containing
+ ``x-codex-*`` headers passes through headroom.
+ """
+
+ def __init__(self) -> None:
+ self._lock = Lock()
+ self._latest: CodexRateLimitSnapshot | None = None
+
+ def update_from_headers(self, headers: dict[str, str]) -> None:
+ """Update state from a response header dict (no-op if no Codex headers)."""
+ snapshot = parse_codex_rate_limits(headers)
+ if snapshot is None:
+ return
+ with self._lock:
+ self._latest = snapshot
+
+ @property
+ def latest(self) -> CodexRateLimitSnapshot | None:
+ with self._lock:
+ return self._latest
+
+ def get_stats(self) -> dict | None:
+ snap = self.latest
+ return snap.to_dict() if snap is not None else None
+
+
+_state: CodexRateLimitState | None = None
+_state_lock = Lock()
+
+
+def get_codex_rate_limit_state() -> CodexRateLimitState:
+ """Return the process-global :class:`CodexRateLimitState` singleton."""
+ global _state
+ if _state is None:
+ with _state_lock:
+ if _state is None:
+ _state = CodexRateLimitState()
+ return _state
diff --git a/tests/test_codex_rate_limits.py b/tests/test_codex_rate_limits.py
new file mode 100644
index 000000000..58586e533
--- /dev/null
+++ b/tests/test_codex_rate_limits.py
@@ -0,0 +1,227 @@
+"""Unit tests for headroom.subscription.codex_rate_limits."""
+
+from __future__ import annotations
+
+import time
+
+from headroom.subscription.codex_rate_limits import (
+ CodexRateLimitState,
+ CodexRateLimitWindow,
+ parse_codex_rate_limits,
+)
+
+# ---------------------------------------------------------------------------
+# CodexRateLimitWindow helpers
+# ---------------------------------------------------------------------------
+
+
+class TestCodexRateLimitWindow:
+ def test_window_label_minutes(self):
+ w = CodexRateLimitWindow(used_percent=10.0, window_minutes=45)
+ assert w.window_label == "45m"
+
+ def test_window_label_hours(self):
+ w = CodexRateLimitWindow(used_percent=10.0, window_minutes=60)
+ assert w.window_label == "1h"
+
+ def test_window_label_hours_with_minutes(self):
+ w = CodexRateLimitWindow(used_percent=10.0, window_minutes=90)
+ assert w.window_label == "1h30m"
+
+ def test_window_label_unknown(self):
+ w = CodexRateLimitWindow(used_percent=10.0, window_minutes=None)
+ assert w.window_label == "unknown"
+
+ def test_seconds_until_reset_future(self):
+ future = int(time.time()) + 3600
+ w = CodexRateLimitWindow(used_percent=10.0, resets_at=future)
+ secs = w.seconds_until_reset
+ assert secs is not None
+ assert 3590 <= secs <= 3600
+
+ def test_seconds_until_reset_past(self):
+ past = int(time.time()) - 100
+ w = CodexRateLimitWindow(used_percent=10.0, resets_at=past)
+ assert w.seconds_until_reset == 0
+
+ def test_seconds_until_reset_none(self):
+ w = CodexRateLimitWindow(used_percent=10.0, resets_at=None)
+ assert w.seconds_until_reset is None
+
+ def test_to_dict_keys(self):
+ w = CodexRateLimitWindow(used_percent=42.5, window_minutes=60, resets_at=9999999)
+ d = w.to_dict()
+ assert set(d.keys()) == {
+ "used_percent",
+ "window_minutes",
+ "window_label",
+ "resets_at",
+ "seconds_until_reset",
+ }
+ assert d["used_percent"] == 42.5
+ assert d["window_label"] == "1h"
+
+
+# ---------------------------------------------------------------------------
+# parse_codex_rate_limits
+# ---------------------------------------------------------------------------
+
+
+class TestParseCodexRateLimits:
+ def test_returns_none_for_empty_headers(self):
+ assert parse_codex_rate_limits({}) is None
+
+ def test_returns_none_for_non_codex_headers(self):
+ headers = {"content-type": "application/json", "x-request-id": "abc"}
+ assert parse_codex_rate_limits(headers) is None
+
+ def test_parses_primary_window(self):
+ headers = {
+ "x-codex-primary-used-percent": "35.5",
+ "x-codex-primary-window-minutes": "60",
+ "x-codex-primary-reset-at": "1704069000",
+ }
+ snap = parse_codex_rate_limits(headers)
+ assert snap is not None
+ assert snap.limit_id == "codex"
+ assert snap.primary is not None
+ assert snap.primary.used_percent == 35.5
+ assert snap.primary.window_minutes == 60
+ assert snap.primary.resets_at == 1704069000
+ assert snap.secondary is None
+
+ def test_parses_secondary_window(self):
+ headers = {
+ "x-codex-primary-used-percent": "10.0",
+ "x-codex-secondary-used-percent": "80.0",
+ "x-codex-secondary-window-minutes": "1440",
+ "x-codex-secondary-reset-at": "1704100000",
+ }
+ snap = parse_codex_rate_limits(headers)
+ assert snap is not None
+ assert snap.secondary is not None
+ assert snap.secondary.used_percent == 80.0
+ assert snap.secondary.window_minutes == 1440
+
+ def test_parses_credits(self):
+ headers = {
+ "x-codex-primary-used-percent": "5.0",
+ "x-codex-credits-has-credits": "true",
+ "x-codex-credits-unlimited": "false",
+ "x-codex-credits-balance": "$12.50",
+ }
+ snap = parse_codex_rate_limits(headers)
+ assert snap is not None
+ assert snap.credits is not None
+ assert snap.credits.has_credits is True
+ assert snap.credits.unlimited is False
+ assert snap.credits.balance == "$12.50"
+
+ def test_parses_unlimited_credits(self):
+ headers = {
+ "x-codex-primary-used-percent": "0.0",
+ "x-codex-credits-has-credits": "true",
+ "x-codex-credits-unlimited": "true",
+ }
+ snap = parse_codex_rate_limits(headers)
+ assert snap is not None
+ assert snap.credits is not None
+ assert snap.credits.unlimited is True
+ assert snap.credits.balance is None
+
+ def test_parses_limit_name(self):
+ headers = {
+ "x-codex-primary-used-percent": "20.0",
+ "x-codex-limit-name": "gpt-5.2-codex-sonic",
+ }
+ snap = parse_codex_rate_limits(headers)
+ assert snap is not None
+ assert snap.limit_name == "gpt-5.2-codex-sonic"
+
+ def test_parses_promo_message(self):
+ headers = {
+ "x-codex-primary-used-percent": "50.0",
+ "x-codex-promo-message": "Try our new model!",
+ }
+ snap = parse_codex_rate_limits(headers)
+ assert snap is not None
+ assert snap.promo_message == "Try our new model!"
+
+ def test_only_credits_header_triggers_parse(self):
+ headers = {
+ "x-codex-credits-has-credits": "true",
+ "x-codex-credits-unlimited": "false",
+ }
+ snap = parse_codex_rate_limits(headers)
+ assert snap is not None
+ assert snap.primary is None
+ assert snap.credits is not None
+
+ def test_invalid_float_ignored(self):
+ headers = {"x-codex-primary-used-percent": "not_a_number"}
+ assert parse_codex_rate_limits(headers) is None
+
+ def test_to_dict_structure(self):
+ headers = {
+ "x-codex-primary-used-percent": "42.0",
+ "x-codex-primary-window-minutes": "60",
+ }
+ snap = parse_codex_rate_limits(headers)
+ assert snap is not None
+ d = snap.to_dict()
+ assert "limit_id" in d
+ assert "primary" in d
+ assert "secondary" in d
+ assert "credits" in d
+ assert "captured_at" in d
+
+
+# ---------------------------------------------------------------------------
+# CodexRateLimitState
+# ---------------------------------------------------------------------------
+
+
+class TestCodexRateLimitState:
+ def test_initial_state_is_none(self):
+ state = CodexRateLimitState()
+ assert state.latest is None
+ assert state.get_stats() is None
+
+ def test_update_from_headers_stores_snapshot(self):
+ state = CodexRateLimitState()
+ headers = {
+ "x-codex-primary-used-percent": "55.0",
+ "x-codex-primary-window-minutes": "60",
+ }
+ state.update_from_headers(headers)
+ snap = state.latest
+ assert snap is not None
+ assert snap.primary is not None
+ assert snap.primary.used_percent == 55.0
+
+ def test_update_from_empty_headers_is_noop(self):
+ state = CodexRateLimitState()
+ state.update_from_headers({})
+ assert state.latest is None
+
+ def test_update_from_non_codex_headers_is_noop(self):
+ state = CodexRateLimitState()
+ state.update_from_headers({"content-type": "application/json"})
+ assert state.latest is None
+
+ def test_get_stats_returns_dict_when_data_present(self):
+ state = CodexRateLimitState()
+ state.update_from_headers({"x-codex-primary-used-percent": "10.0"})
+ stats = state.get_stats()
+ assert stats is not None
+ assert isinstance(stats, dict)
+ assert stats["limit_id"] == "codex"
+
+ def test_update_overwrites_previous_snapshot(self):
+ state = CodexRateLimitState()
+ state.update_from_headers({"x-codex-primary-used-percent": "10.0"})
+ state.update_from_headers({"x-codex-primary-used-percent": "90.0"})
+ snap = state.latest
+ assert snap is not None
+ assert snap.primary is not None
+ assert snap.primary.used_percent == 90.0