Compare commits

..
2 Commits
3 changed files with 174 additions and 25 deletions

No files matched your search

+11
View File
@@ -87,6 +87,17 @@ Other command options:
--no-cache --no-cache
``` ```
## Terminal mode
For a readable terminal display instead of Waybar JSON, use either command:
```bash
codex-waybar --terminal
# or: codex-waybar --mode terminal
```
It shows both usage windows as color-coded progress bars, reset countdowns, and an overall status. Colors are enabled for interactive terminals; use `--color always` or `--color never` to override that behavior.
## Styling ## Styling
The command emits these Waybar CSS classes: The command emits these Waybar CSS classes:
+107 -22
View File
@@ -24,6 +24,8 @@ DEFAULT_TOOLTIP = (
"5-hour: {five_hour_used}% used, resets {five_hour_reset_at} ({five_hour_reset_in})\n" "5-hour: {five_hour_used}% used, resets {five_hour_reset_at} ({five_hour_reset_in})\n"
"Weekly: {weekly_used}% used, resets {weekly_reset_at} ({weekly_reset_in})" "Weekly: {weekly_used}% used, resets {weekly_reset_at} ({weekly_reset_in})"
) )
TERMINAL_BAR_WIDTH = 24
TERMINAL_WIDTH = 78
ALLOWED_FIELDS = { ALLOWED_FIELDS = {
"five_hour_used", "five_hour_used",
"weekly_used", "weekly_used",
@@ -80,30 +82,33 @@ def fetch_rate_limits(timeout: float, codex_command: str = "codex") -> dict[str,
stdin=subprocess.PIPE, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, bufsize=0,
bufsize=1,
) )
assert process.stdin is not None assert process.stdin is not None
assert process.stdout is not None assert process.stdout is not None
process.stdin.write(payload) process.stdin.write(payload.encode())
process.stdin.flush() process.stdin.flush()
deadline = time.monotonic() + timeout deadline = time.monotonic() + timeout
selector = selectors.DefaultSelector() selector = selectors.DefaultSelector()
selector.register(process.stdout, selectors.EVENT_READ) selector.register(process.stdout, selectors.EVENT_READ)
buffered = b""
while time.monotonic() < deadline: while time.monotonic() < deadline:
events = selector.select(deadline - time.monotonic()) events = selector.select(deadline - time.monotonic())
if not events: if not events:
break break
line = process.stdout.readline() chunk = os.read(process.stdout.fileno(), 65_536)
if not line: if not chunk:
break break
buffered += chunk
while b"\n" in buffered:
line, buffered = buffered.split(b"\n", 1)
try: try:
message = json.loads(line) message = json.loads(line)
except json.JSONDecodeError: except (UnicodeDecodeError, json.JSONDecodeError):
continue continue
if message.get("id") == 2: if message.get("id") == 2:
return parse_json_lines(line) return parse_json_lines(line.decode())
raise UsageError("Codex app-server timed out or returned no rate-limit data") raise UsageError("Codex app-server timed out or returned no rate-limit data")
except FileNotFoundError as exc: except FileNotFoundError as exc:
raise UsageError(f"{codex_command!r} was not found") from exc raise UsageError(f"{codex_command!r} was not found") from exc
@@ -121,6 +126,9 @@ def fetch_rate_limits(timeout: float, codex_command: str = "codex") -> dict[str,
except subprocess.TimeoutExpired: except subprocess.TimeoutExpired:
process.kill() process.kill()
process.wait() process.wait()
for stream in (process.stdout, process.stderr):
if stream:
stream.close()
def select_snapshot(result: dict[str, Any]) -> dict[str, Any]: def select_snapshot(result: dict[str, Any]) -> dict[str, Any]:
@@ -138,7 +146,7 @@ def select_snapshot(result: dict[str, Any]) -> dict[str, Any]:
raise UsageError("No Codex rate-limit snapshot is available") raise UsageError("No Codex rate-limit snapshot is available")
def select_windows(snapshot: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]: def select_windows(snapshot: dict[str, Any]) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
windows = [ windows = [
window window
for key in ("primary", "secondary") for key in ("primary", "secondary")
@@ -147,8 +155,8 @@ def select_windows(snapshot: dict[str, Any]) -> tuple[dict[str, Any], dict[str,
by_duration = {window.get("windowDurationMins"): window for window in windows} by_duration = {window.get("windowDurationMins"): window for window in windows}
five_hour = by_duration.get(FIVE_HOUR_MINS) five_hour = by_duration.get(FIVE_HOUR_MINS)
weekly = by_duration.get(WEEKLY_MINS) weekly = by_duration.get(WEEKLY_MINS)
if not isinstance(five_hour, dict) or not isinstance(weekly, dict): if not isinstance(five_hour, dict) and not isinstance(weekly, dict):
raise UsageError("The 5-hour or weekly Codex limit window is unavailable") raise UsageError("Codex returned no supported rate-limit windows")
return five_hour, weekly return five_hour, weekly
@@ -208,18 +216,29 @@ def validate_template(template: str) -> None:
def format_values(snapshot: dict[str, Any], now: int) -> tuple[dict[str, Any], int]: def format_values(snapshot: dict[str, Any], now: int) -> tuple[dict[str, Any], int]:
five_hour, weekly = select_windows(snapshot) five_hour, weekly = select_windows(snapshot)
five_used = int(five_hour.get("usedPercent", 0))
weekly_used = int(weekly.get("usedPercent", 0)) def window_values(window: dict[str, Any] | None) -> tuple[int | str, str, str]:
if window is None:
return "n/a", "n/a", "n/a"
return (
int(window.get("usedPercent", 0)),
human_countdown(window.get("resetsAt"), now),
reset_time(window.get("resetsAt")),
)
five_used, five_reset_in, five_reset_at = window_values(five_hour)
weekly_used, weekly_reset_in, weekly_reset_at = window_values(weekly)
values = { values = {
"five_hour_used": five_used, "five_hour_used": five_used,
"weekly_used": weekly_used, "weekly_used": weekly_used,
"five_hour_reset_in": human_countdown(five_hour.get("resetsAt"), now), "five_hour_reset_in": five_reset_in,
"weekly_reset_in": human_countdown(weekly.get("resetsAt"), now), "weekly_reset_in": weekly_reset_in,
"five_hour_reset_at": reset_time(five_hour.get("resetsAt")), "five_hour_reset_at": five_reset_at,
"weekly_reset_at": reset_time(weekly.get("resetsAt")), "weekly_reset_at": weekly_reset_at,
"plan": snapshot.get("planType") or "unknown", "plan": snapshot.get("planType") or "unknown",
} }
return values, max(five_used, weekly_used) percentages = [value for value in (five_used, weekly_used) if isinstance(value, int)]
return values, max(percentages, default=0)
def output_json( def output_json(
@@ -257,6 +276,60 @@ def unavailable_json(reason: str) -> dict[str, Any]:
} }
def terminal_color(text: str, code: str, color: str) -> str:
if color == "never" or (color == "auto" and (not sys.stdout.isatty() or os.environ.get("NO_COLOR"))):
return text
return f"\033[{code}m{text}\033[0m"
def terminal_bar(used: int | str, color: str) -> str:
if not isinstance(used, int):
return "░" * TERMINAL_BAR_WIDTH
filled = round(max(0, min(100, used)) * TERMINAL_BAR_WIDTH / 100)
bar = "█" * filled + "░" * (TERMINAL_BAR_WIDTH - filled)
code = "31" if used >= 90 else "33" if used >= 70 else "36"
return terminal_color(bar, code, color)
def terminal_output(
result: dict[str, Any],
warning: int,
critical: int,
color: str,
stale: bool = False,
stale_reason: str | None = None,
now: int | None = None,
) -> str:
snapshot = select_snapshot(result)
values, percentage = format_values(snapshot, now or int(time.time()))
state = "CRITICAL" if percentage >= critical else "WARNING" if percentage >= warning else "OK"
state_code = "31" if state == "CRITICAL" else "33" if state == "WARNING" else "32"
def row(label: str, used: int | str, reset_in: str) -> str:
usage = f"{used:>3}% used" if isinstance(used, int) else f"{used:>8}"
suffix = f" {usage} · resets in {reset_in}"
padding = TERMINAL_WIDTH - 36 - len(suffix)
return f"│ {label:<7} {terminal_bar(used, color)}{suffix}{' ' * max(0, padding)}│"
title = f" Codex usage · {values['plan']} "
lines = [
f"╭{'─' * 2}{title}{'─' * max(2, TERMINAL_WIDTH - 4 - len(title))}╮",
row("5-hour", values["five_hour_used"], values["five_hour_reset_in"]),
row("Weekly", values["weekly_used"], values["weekly_reset_in"]),
]
status_text = state
if stale:
status_text += f" · cached data ({stale_reason or 'refresh failed'})"
status = terminal_color(state, state_code, color) + status_text[len(state) :]
status_padding = TERMINAL_WIDTH - 5 - len(status_text)
lines.append(f"╰{'─' * 2} {status}{' ' * max(0, status_padding)}╯")
return "\n".join(lines)
def unavailable_terminal(reason: str, color: str) -> str:
label = terminal_color("Codex usage unavailable", "31", color)
return f"{label}\n{reason}"
def parse_args(argv: list[str] | None = None) -> argparse.Namespace: def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__) parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--format", default=DEFAULT_FORMAT, help="Waybar text template") parser.add_argument("--format", default=DEFAULT_FORMAT, help="Waybar text template")
@@ -266,6 +339,9 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser.add_argument("--timeout", type=float, default=10, help="Codex app-server timeout in seconds") parser.add_argument("--timeout", type=float, default=10, help="Codex app-server timeout in seconds")
parser.add_argument("--codex-command", default="codex", help=argparse.SUPPRESS) parser.add_argument("--codex-command", default="codex", help=argparse.SUPPRESS)
parser.add_argument("--no-cache", action="store_true", help="Disable cached fallback data") parser.add_argument("--no-cache", action="store_true", help="Disable cached fallback data")
parser.add_argument("--mode", choices=("waybar", "terminal"), default="waybar", help="Output mode (default: waybar)")
parser.add_argument("--terminal", dest="mode", action="store_const", const="terminal", help="Alias for --mode terminal")
parser.add_argument("--color", choices=("auto", "always", "never"), default="auto", help="Terminal color mode (default: auto)")
return parser.parse_args(argv) return parser.parse_args(argv)
@@ -277,21 +353,29 @@ def main(argv: list[str] | None = None) -> int:
if not 0 <= args.warning <= args.critical <= 100: if not 0 <= args.warning <= args.critical <= 100:
raise UsageError("thresholds must satisfy 0 <= warning <= critical <= 100") raise UsageError("thresholds must satisfy 0 <= warning <= critical <= 100")
except UsageError as exc: except UsageError as exc:
print(json.dumps(unavailable_json(str(exc)), separators=(",", ":"))) output = unavailable_terminal(str(exc), args.color) if args.mode == "terminal" else json.dumps(unavailable_json(str(exc)), separators=(",", ":"))
print(output)
return 2 return 2
path = cache_path() path = cache_path()
try: try:
result = fetch_rate_limits(args.timeout, args.codex_command) result = fetch_rate_limits(args.timeout, args.codex_command)
save_cache(path, result) save_cache(path, result)
output = output_json(result, args.format, args.tooltip_format, args.warning, args.critical) output = (
terminal_output(result, args.warning, args.critical, args.color)
if args.mode == "terminal"
else output_json(result, args.format, args.tooltip_format, args.warning, args.critical)
)
except UsageError as exc: except UsageError as exc:
cached = None if args.no_cache else load_cache(path) cached = None if args.no_cache else load_cache(path)
cached_result = cached.get("result") if isinstance(cached, dict) else None cached_result = cached.get("result") if isinstance(cached, dict) else None
try: try:
if not isinstance(cached_result, dict): if not isinstance(cached_result, dict):
raise UsageError(str(exc)) raise UsageError(str(exc))
output = output_json( output = (
terminal_output(cached_result, args.warning, args.critical, args.color, stale=True, stale_reason=str(exc))
if args.mode == "terminal"
else output_json(
cached_result, cached_result,
args.format, args.format,
args.tooltip_format, args.tooltip_format,
@@ -300,10 +384,11 @@ def main(argv: list[str] | None = None) -> int:
stale=True, stale=True,
stale_reason=str(exc), stale_reason=str(exc),
) )
)
except UsageError: except UsageError:
output = unavailable_json(str(exc)) output = unavailable_terminal(str(exc), args.color) if args.mode == "terminal" else unavailable_json(str(exc))
print(json.dumps(output, separators=(",", ":"))) print(output if args.mode == "terminal" else json.dumps(output, separators=(",", ":")))
return 0 return 0
+56 -3
View File
@@ -3,6 +3,7 @@ from importlib.machinery import SourceFileLoader
import io import io
import json import json
import os import os
import subprocess
import sys import sys
import tempfile import tempfile
import unittest import unittest
@@ -44,6 +45,30 @@ def rate_result(five_used=22, weekly_used=18):
class UsageModuleTests(unittest.TestCase): class UsageModuleTests(unittest.TestCase):
def test_fetch_handles_multiple_responses_in_one_pipe_read(self):
server = """import json, sys
for line in sys.stdin:
message = json.loads(line)
if message.get('id') == 2:
result = {'rateLimits': {'limitId': 'codex'}}
responses = [
{'id': 1, 'result': {}},
{'method': 'notification', 'params': {}},
{'id': 2, 'result': result},
]
sys.stdout.write(''.join(json.dumps(item) + '\\n' for item in responses))
sys.stdout.flush()
break
"""
real_popen = subprocess.Popen
def fake_popen(command, **kwargs):
return real_popen([sys.executable, "-c", server], **kwargs)
with patch.object(module.subprocess, "Popen", side_effect=fake_popen):
result = module.fetch_rate_limits(timeout=1)
self.assertEqual(result, {"rateLimits": {"limitId": "codex"}})
def test_parse_json_lines_ignores_notifications(self): def test_parse_json_lines_ignores_notifications(self):
output = "\n".join( output = "\n".join(
[ [
@@ -83,11 +108,12 @@ class UsageModuleTests(unittest.TestCase):
self.assertEqual(output["class"], ["warning"]) self.assertEqual(output["class"], ["warning"])
self.assertEqual(output["percentage"], 72) self.assertEqual(output["percentage"], 72)
def test_missing_window_is_rejected(self): def test_missing_window_is_rendered_as_unavailable(self):
result = rate_result() result = rate_result()
result["rateLimits"]["secondary"] = None result["rateLimits"]["secondary"] = None
with self.assertRaises(module.UsageError): output = module.output_json(result, module.DEFAULT_FORMAT, module.DEFAULT_TOOLTIP, 70, 90)
module.output_json(result, module.DEFAULT_FORMAT, module.DEFAULT_TOOLTIP, 70, 90) self.assertIn("W n/a%", output["text"])
self.assertEqual(output["percentage"], 22)
def test_unknown_template_field_is_rejected(self): def test_unknown_template_field_is_rejected(self):
with self.assertRaises(module.UsageError): with self.assertRaises(module.UsageError):
@@ -122,6 +148,33 @@ class UsageModuleTests(unittest.TestCase):
self.assertEqual(output["class"], ["unavailable"]) self.assertEqual(output["class"], ["unavailable"])
self.assertIn("offline", output["tooltip"]) self.assertIn("offline", output["tooltip"])
def test_terminal_mode_renders_readable_usage(self):
stdout = io.StringIO()
with (
patch.object(module, "fetch_rate_limits", return_value=rate_result(five_used=72, weekly_used=18)),
redirect_stdout(stdout),
):
exit_code = module.main(["--terminal", "--color", "never"])
output = stdout.getvalue()
self.assertEqual(exit_code, 0)
self.assertIn("Codex usage · plus", output)
self.assertIn("5-hour", output)
self.assertIn("72% used", output)
self.assertIn("Weekly", output)
self.assertIn("WARNING", output)
self.assertNotIn("\033[", output)
def test_terminal_mode_reports_unavailable_without_json(self):
stdout = io.StringIO()
with (
patch.object(module, "fetch_rate_limits", side_effect=module.UsageError("offline")),
patch.object(module, "load_cache", return_value=None),
redirect_stdout(stdout),
):
module.main(["--mode", "terminal", "--color", "never"])
self.assertIn("Codex usage unavailable", stdout.getvalue())
self.assertNotIn('{"text"', stdout.getvalue())
class ConfigureTests(unittest.TestCase): class ConfigureTests(unittest.TestCase):
CONFIG = """{ CONFIG = """{