ctxline 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ .venv/
4
+ dist/
5
+ node_modules/
6
+ *.tgz
ctxline-0.1.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Eric Wafula
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
ctxline-0.1.1/PKG-INFO ADDED
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.5
2
+ Name: ctxline
3
+ Version: 0.1.1
4
+ Summary: A Claude Code status line for context and usage limits
5
+ Project-URL: Repository, https://github.com/ericwafula/ctxline
6
+ Author: Eric Wafula
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.9
10
+ Description-Content-Type: text/markdown
11
+
12
+ # ctxline
13
+
14
+ A status line for Claude Code that shows how much context you've used and how close you are to your usage limits.
15
+
16
+ ```
17
+ Opus 5.5 · stovetime ⑂ main · ctx 186k (19%) · 5h 8%(3h) · wk 28%(2d) · $8.30
18
+ ```
19
+
20
+ | Field | Meaning |
21
+ |---|---|
22
+ | `Opus 5.5` | The model |
23
+ | `stovetime ⑂ main` | Folder and git branch |
24
+ | `ctx 186k (19%)` | Tokens in the context window, and the share of the window they fill |
25
+ | `5h 8%(3h)` | Share of your 5-hour limit used, and time until it resets |
26
+ | `wk 28%(2d)` | Same for the weekly limit |
27
+ | `$8.30` | What the session would cost at API prices |
28
+
29
+ Each field turns yellow when a quarter or less is left, and red at a tenth. Fields with no data yet are left out. The limits only appear on Pro, Max and Ultra plans, after the first reply in a session.
30
+
31
+ It uses no tokens. Claude Code runs it on your machine and sends it the session details as JSON. Nothing it prints goes to the model.
32
+
33
+ ## Install
34
+
35
+ With uv:
36
+
37
+ ```bash
38
+ uv tool install ctxline
39
+ ctxline install
40
+ ```
41
+
42
+ With pipx:
43
+
44
+ ```bash
45
+ pipx install ctxline
46
+ ctxline install
47
+ ```
48
+
49
+ With Homebrew:
50
+
51
+ ```bash
52
+ brew install ericwafula/tools/ctxline
53
+ ctxline install
54
+ ```
55
+
56
+ With Node 18 or newer:
57
+
58
+ ```bash
59
+ npm install -g github:ericwafula/ctxline
60
+ ctxline install
61
+ ```
62
+
63
+ `ctxline install` adds a `statusLine` entry to `~/.claude/settings.json`, using the full path to the command so it works from the desktop app too. If you already had a status line, it's saved to `~/.claude/ctxline-previous.json`.
64
+
65
+ The Node version records the path of the Node it was installed with. If you remove that Node version (with nvm, say), run `ctxline install` again.
66
+
67
+ ## Remove
68
+
69
+ ```bash
70
+ ctxline uninstall
71
+ ```
72
+
73
+ This puts back the status line you had before, or removes the entry if there wasn't one. Then uninstall the package with `uv tool uninstall ctxline`, `pipx uninstall ctxline`, `brew uninstall ctxline` or `npm uninstall -g ctxline`.
74
+
75
+ ## Try it without Claude Code
76
+
77
+ ```bash
78
+ echo '{"model":{"display_name":"Opus"},"context_window":{"total_input_tokens":42000,"context_window_size":200000}}' | ctxline
79
+ ```
80
+
81
+ Set `NO_COLOR=1` for plain text. `CLAUDE_CONFIG_DIR` changes where settings are written.
82
+
83
+ ## Development
84
+
85
+ The Python version lives in `src/ctxline`, the Node version in `lib` and `bin`. Both are tested against the same cases in `tests/fixtures/cases.json`, so they print identical lines.
86
+
87
+ ```bash
88
+ python3 -m unittest discover -s tests
89
+ ```
90
+
91
+ ```bash
92
+ npm test
93
+ ```
@@ -0,0 +1,82 @@
1
+ # ctxline
2
+
3
+ A status line for Claude Code that shows how much context you've used and how close you are to your usage limits.
4
+
5
+ ```
6
+ Opus 5.5 · stovetime ⑂ main · ctx 186k (19%) · 5h 8%(3h) · wk 28%(2d) · $8.30
7
+ ```
8
+
9
+ | Field | Meaning |
10
+ |---|---|
11
+ | `Opus 5.5` | The model |
12
+ | `stovetime ⑂ main` | Folder and git branch |
13
+ | `ctx 186k (19%)` | Tokens in the context window, and the share of the window they fill |
14
+ | `5h 8%(3h)` | Share of your 5-hour limit used, and time until it resets |
15
+ | `wk 28%(2d)` | Same for the weekly limit |
16
+ | `$8.30` | What the session would cost at API prices |
17
+
18
+ Each field turns yellow when a quarter or less is left, and red at a tenth. Fields with no data yet are left out. The limits only appear on Pro, Max and Ultra plans, after the first reply in a session.
19
+
20
+ It uses no tokens. Claude Code runs it on your machine and sends it the session details as JSON. Nothing it prints goes to the model.
21
+
22
+ ## Install
23
+
24
+ With uv:
25
+
26
+ ```bash
27
+ uv tool install ctxline
28
+ ctxline install
29
+ ```
30
+
31
+ With pipx:
32
+
33
+ ```bash
34
+ pipx install ctxline
35
+ ctxline install
36
+ ```
37
+
38
+ With Homebrew:
39
+
40
+ ```bash
41
+ brew install ericwafula/tools/ctxline
42
+ ctxline install
43
+ ```
44
+
45
+ With Node 18 or newer:
46
+
47
+ ```bash
48
+ npm install -g github:ericwafula/ctxline
49
+ ctxline install
50
+ ```
51
+
52
+ `ctxline install` adds a `statusLine` entry to `~/.claude/settings.json`, using the full path to the command so it works from the desktop app too. If you already had a status line, it's saved to `~/.claude/ctxline-previous.json`.
53
+
54
+ The Node version records the path of the Node it was installed with. If you remove that Node version (with nvm, say), run `ctxline install` again.
55
+
56
+ ## Remove
57
+
58
+ ```bash
59
+ ctxline uninstall
60
+ ```
61
+
62
+ This puts back the status line you had before, or removes the entry if there wasn't one. Then uninstall the package with `uv tool uninstall ctxline`, `pipx uninstall ctxline`, `brew uninstall ctxline` or `npm uninstall -g ctxline`.
63
+
64
+ ## Try it without Claude Code
65
+
66
+ ```bash
67
+ echo '{"model":{"display_name":"Opus"},"context_window":{"total_input_tokens":42000,"context_window_size":200000}}' | ctxline
68
+ ```
69
+
70
+ Set `NO_COLOR=1` for plain text. `CLAUDE_CONFIG_DIR` changes where settings are written.
71
+
72
+ ## Development
73
+
74
+ The Python version lives in `src/ctxline`, the Node version in `lib` and `bin`. Both are tested against the same cases in `tests/fixtures/cases.json`, so they print identical lines.
75
+
76
+ ```bash
77
+ python3 -m unittest discover -s tests
78
+ ```
79
+
80
+ ```bash
81
+ npm test
82
+ ```
@@ -0,0 +1,25 @@
1
+ [project]
2
+ name = "ctxline"
3
+ dynamic = ["version"]
4
+ description = "A Claude Code status line for context and usage limits"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ authors = [{ name = "Eric Wafula" }]
8
+ requires-python = ">=3.9"
9
+ dependencies = []
10
+
11
+ [project.urls]
12
+ Repository = "https://github.com/ericwafula/ctxline"
13
+
14
+ [project.scripts]
15
+ ctxline = "ctxline.cli:main"
16
+
17
+ [build-system]
18
+ requires = ["hatchling"]
19
+ build-backend = "hatchling.build"
20
+
21
+ [tool.hatch.version]
22
+ path = "src/ctxline/__init__.py"
23
+
24
+ [tool.hatch.build.targets.sdist]
25
+ include = ["src", "tests", "README.md", "LICENSE"]
@@ -0,0 +1 @@
1
+ __version__ = "0.1.1"
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from ctxline.cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,77 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import shlex
6
+ import shutil
7
+ import sys
8
+ import time
9
+ from pathlib import Path
10
+
11
+ from ctxline import __version__, settings
12
+ from ctxline.limits import current_limits
13
+ from ctxline.line import git_branch, render, section
14
+
15
+ USAGE = """usage: ctxline [install | uninstall | --version]
16
+
17
+ (piped JSON) print the status line for a Claude Code session
18
+ install make ctxline your Claude Code status line
19
+ uninstall remove it and restore the status line you had before
20
+ """
21
+
22
+ EPHEMERAL_MARKERS = ("/cache/uv/", "/.cache/uv/", "/archive-v")
23
+
24
+
25
+ def own_command() -> str:
26
+ on_path = shutil.which("ctxline")
27
+ executable = Path(on_path) if on_path else Path(sys.argv[0]).absolute()
28
+ return shlex.quote(str(executable))
29
+
30
+
31
+ def print_line() -> int:
32
+ try:
33
+ payload = json.load(sys.stdin)
34
+ except ValueError:
35
+ payload = {}
36
+ if not isinstance(payload, dict):
37
+ payload = {}
38
+ directory = section(payload, "workspace").get("current_dir") or payload.get("cwd")
39
+ color = not os.environ.get("NO_COLOR")
40
+ now = time.time()
41
+ print(render(payload, now, git_branch(directory), color, current_limits(payload, now)))
42
+ return 0
43
+
44
+
45
+ def run_install() -> int:
46
+ command = own_command()
47
+ if any(marker in command for marker in EPHEMERAL_MARKERS):
48
+ print("Install it for good first: uv tool install ctxline, then run ctxline install.", file=sys.stderr)
49
+ return 1
50
+ note = settings.install(command)
51
+ print(f"ctxline is now your status line ({settings.settings_path()}).")
52
+ if note:
53
+ print(note)
54
+ return 0
55
+
56
+
57
+ def main(argv: list[str] | None = None) -> int:
58
+ args = sys.argv[1:] if argv is None else argv
59
+ if not args:
60
+ if sys.stdin.isatty():
61
+ print(USAGE, end="")
62
+ return 0
63
+ try:
64
+ return print_line()
65
+ except Exception:
66
+ print("")
67
+ return 0
68
+ if args[0] == "install":
69
+ return run_install()
70
+ if args[0] == "uninstall":
71
+ print(settings.uninstall())
72
+ return 0
73
+ if args[0] in ("--version", "-V"):
74
+ print(__version__)
75
+ return 0
76
+ print(USAGE, end="", file=sys.stderr)
77
+ return 2
@@ -0,0 +1,26 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ from ctxline.line import has_limits, section
7
+ from ctxline.settings import claude_home, write_json
8
+
9
+
10
+ def memory_path() -> Path:
11
+ return claude_home() / "cache" / "ctxline-limits.json"
12
+
13
+
14
+ def current_limits(payload: dict, now: float) -> dict:
15
+ live = section(payload, "rate_limits")
16
+ if has_limits(live):
17
+ try:
18
+ write_json(memory_path(), live)
19
+ except OSError:
20
+ pass
21
+ return live
22
+ try:
23
+ remembered = json.loads(memory_path().read_text())
24
+ except (OSError, ValueError):
25
+ return live
26
+ return remembered if isinstance(remembered, dict) else live
@@ -0,0 +1,153 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from pathlib import Path
5
+
6
+ SEPARATOR = " · "
7
+ RESET = "\033[0m"
8
+ DIM = "\033[2m"
9
+ CYAN = "\033[36m"
10
+ GREEN = "\033[32m"
11
+ YELLOW = "\033[33m"
12
+ RED = "\033[31m"
13
+
14
+ LIMIT_LABELS = (("five_hour", "5h"), ("seven_day", "wk"))
15
+
16
+
17
+ def round_half_up(value: float) -> int:
18
+ return math.floor(value + 0.5)
19
+
20
+
21
+ def paint(code: str, text: str, color: bool) -> str:
22
+ return f"{code}{text}{RESET}" if color else text
23
+
24
+
25
+ def tone_for(remaining_pct: float) -> str:
26
+ if remaining_pct <= 10:
27
+ return RED
28
+ if remaining_pct <= 25:
29
+ return YELLOW
30
+ return GREEN
31
+
32
+
33
+ def time_until(seconds: float) -> str:
34
+ if seconds <= 60:
35
+ return "now"
36
+ minutes = int(seconds // 60)
37
+ if minutes >= 24 * 60:
38
+ return f"{minutes // (24 * 60)}d"
39
+ if minutes >= 60:
40
+ return f"{minutes // 60}h"
41
+ return f"{minutes}m"
42
+
43
+
44
+ def token_amount(tokens: int) -> str:
45
+ if tokens < 1_000_000:
46
+ return f"{round_half_up(tokens / 1000)}k"
47
+ return f"{round_half_up(tokens / 10_000) / 100:.2f}M"
48
+
49
+
50
+ def is_number(value: object) -> bool:
51
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
52
+
53
+
54
+ def section(payload: dict, key: str) -> dict:
55
+ value = payload.get(key)
56
+ return value if isinstance(value, dict) else {}
57
+
58
+
59
+ def git_branch(directory: str | None) -> str | None:
60
+ if not directory:
61
+ return None
62
+ for folder in (Path(directory), *Path(directory).parents):
63
+ dot_git = folder / ".git"
64
+ try:
65
+ if dot_git.is_file():
66
+ pointer = dot_git.read_text().strip()
67
+ if not pointer.startswith("gitdir:"):
68
+ return None
69
+ dot_git = (folder / pointer.removeprefix("gitdir:").strip()).resolve()
70
+ if not dot_git.is_dir():
71
+ continue
72
+ head = (dot_git / "HEAD").read_text().strip()
73
+ except OSError:
74
+ return None
75
+ if head.startswith("ref: refs/heads/"):
76
+ return head.removeprefix("ref: refs/heads/")
77
+ return head[:7] or None
78
+ return None
79
+
80
+
81
+ def session_fields(payload: dict, branch: str | None, color: bool) -> list[str]:
82
+ fields = []
83
+ model = section(payload, "model").get("display_name")
84
+ if model:
85
+ fields.append(paint(CYAN, model, color))
86
+ directory = section(payload, "workspace").get("current_dir") or payload.get("cwd")
87
+ if directory:
88
+ place = Path(directory).name or directory
89
+ fields.append(paint(DIM, f"{place} ⑂ {branch}" if branch else place, color))
90
+ return fields
91
+
92
+
93
+ def context_field(payload: dict, color: bool) -> str | None:
94
+ window = section(payload, "context_window")
95
+ tokens = sum(
96
+ window.get(key) for key in ("total_input_tokens", "total_output_tokens") if is_number(window.get(key))
97
+ )
98
+ used = window.get("used_percentage")
99
+ size = window.get("context_window_size")
100
+ if not is_number(used):
101
+ if not tokens or not is_number(size) or size <= 0:
102
+ return None
103
+ used = tokens / size * 100
104
+ text = f"ctx {token_amount(tokens)} ({round_half_up(used)}%)" if tokens else f"ctx {round_half_up(used)}%"
105
+ return paint(tone_for(100 - used), text, color)
106
+
107
+
108
+ def is_live(window: dict, now: float) -> bool:
109
+ resets_at = window.get("resets_at")
110
+ return is_number(window.get("used_percentage")) and (not is_number(resets_at) or resets_at > now)
111
+
112
+
113
+ def has_limits(limits: dict) -> bool:
114
+ return any(is_number(section(limits, key).get("used_percentage")) for key, _ in LIMIT_LABELS)
115
+
116
+
117
+ def limit_fields(limits: dict, now: float, color: bool) -> list[str]:
118
+ if not has_limits(limits):
119
+ return []
120
+ fields = []
121
+ for key, label in LIMIT_LABELS:
122
+ window = section(limits, key)
123
+ if not is_live(window, now):
124
+ fields.append(paint(GREEN, f"{label} 0%", color))
125
+ continue
126
+ used = window["used_percentage"]
127
+ text = paint(tone_for(100 - used), f"{label} {round_half_up(used)}%", color)
128
+ resets_at = window.get("resets_at")
129
+ if is_number(resets_at):
130
+ text += paint(DIM, f"({time_until(resets_at - now)})", color)
131
+ fields.append(text)
132
+ return fields
133
+
134
+
135
+ def cost_field(payload: dict, color: bool) -> str | None:
136
+ cost = section(payload, "cost").get("total_cost_usd")
137
+ if not is_number(cost):
138
+ return None
139
+ return paint(DIM, f"${round_half_up(cost * 100) / 100:,.2f}", color)
140
+
141
+
142
+ def render(
143
+ payload: dict,
144
+ now: float,
145
+ branch: str | None = None,
146
+ color: bool = True,
147
+ limits: dict | None = None,
148
+ ) -> str:
149
+ fields = session_fields(payload, branch, color)
150
+ fields.append(context_field(payload, color))
151
+ fields.extend(limit_fields(section(payload, "rate_limits") if limits is None else limits, now, color))
152
+ fields.append(cost_field(payload, color))
153
+ return SEPARATOR.join(field for field in fields if field)
@@ -0,0 +1,69 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+
7
+ REFRESH_SECONDS = 60
8
+
9
+
10
+ def claude_home() -> Path:
11
+ return Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude")
12
+
13
+
14
+ def settings_path() -> Path:
15
+ return claude_home() / "settings.json"
16
+
17
+
18
+ def previous_path() -> Path:
19
+ return claude_home() / "ctxline-previous.json"
20
+
21
+
22
+ def read_json(path: Path) -> dict:
23
+ if not path.is_file():
24
+ return {}
25
+ return json.loads(path.read_text() or "{}")
26
+
27
+
28
+ def write_json(path: Path, data: dict) -> None:
29
+ path.parent.mkdir(parents=True, exist_ok=True)
30
+ staging = path.with_name(f"{path.name}.{os.getpid()}.tmp")
31
+ staging.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n")
32
+ staging.replace(path)
33
+
34
+
35
+ def is_ours(status_line: object) -> bool:
36
+ return isinstance(status_line, dict) and "ctxline" in str(status_line.get("command", ""))
37
+
38
+
39
+ def install(command: str) -> str:
40
+ settings = read_json(settings_path())
41
+ current = settings.get("statusLine")
42
+ if current and not is_ours(current):
43
+ write_json(previous_path(), {"statusLine": current})
44
+ settings["statusLine"] = {
45
+ "type": "command",
46
+ "command": command,
47
+ "padding": 0,
48
+ "refreshInterval": REFRESH_SECONDS,
49
+ }
50
+ write_json(settings_path(), settings)
51
+ if current and not is_ours(current):
52
+ return f"Saved your old status line to {previous_path()}. `ctxline uninstall` puts it back."
53
+ return ""
54
+
55
+
56
+ def uninstall() -> str:
57
+ settings = read_json(settings_path())
58
+ if not is_ours(settings.get("statusLine")):
59
+ return "ctxline isn't your status line, so nothing changed."
60
+ previous = read_json(previous_path()).get("statusLine")
61
+ if previous:
62
+ settings["statusLine"] = previous
63
+ message = "Put your previous status line back."
64
+ else:
65
+ settings.pop("statusLine")
66
+ message = "Removed the ctxline status line."
67
+ write_json(settings_path(), settings)
68
+ previous_path().unlink(missing_ok=True)
69
+ return message
@@ -0,0 +1,166 @@
1
+ [
2
+ {
3
+ "name": "full session",
4
+ "now": 1800000000,
5
+ "branch": "main",
6
+ "payload": {
7
+ "model": {
8
+ "display_name": "Opus 5.5"
9
+ },
10
+ "workspace": {
11
+ "current_dir": "/Users/me/stovetime"
12
+ },
13
+ "context_window": {
14
+ "total_input_tokens": 180500,
15
+ "total_output_tokens": 5500,
16
+ "context_window_size": 1000000,
17
+ "used_percentage": 18.6
18
+ },
19
+ "rate_limits": {
20
+ "five_hour": {
21
+ "used_percentage": 8.4,
22
+ "resets_at": 1800010800
23
+ },
24
+ "seven_day": {
25
+ "used_percentage": 28,
26
+ "resets_at": 1800172800
27
+ }
28
+ },
29
+ "cost": {
30
+ "total_cost_usd": 8.2961
31
+ }
32
+ },
33
+ "expected": "Opus 5.5 · stovetime ⑂ main · ctx 186k (19%) · 5h 8%(3h) · wk 28%(2d) · $8.30"
34
+ },
35
+ {
36
+ "name": "before the first response",
37
+ "now": 1800000000,
38
+ "branch": null,
39
+ "payload": {
40
+ "model": {
41
+ "display_name": "Sonnet 5.5"
42
+ },
43
+ "cwd": "/tmp/scratch",
44
+ "context_window": {
45
+ "total_input_tokens": 0,
46
+ "total_output_tokens": 0,
47
+ "context_window_size": 200000,
48
+ "used_percentage": null
49
+ },
50
+ "cost": {
51
+ "total_cost_usd": 0
52
+ }
53
+ },
54
+ "expected": "Sonnet 5.5 · scratch · $0.00"
55
+ },
56
+ {
57
+ "name": "percentage missing, worked out from the window size",
58
+ "now": 1800000000,
59
+ "branch": null,
60
+ "payload": {
61
+ "workspace": {
62
+ "current_dir": "/srv/api"
63
+ },
64
+ "context_window": {
65
+ "total_input_tokens": 150000,
66
+ "context_window_size": 200000
67
+ }
68
+ },
69
+ "expected": "api · ctx 150k (75%)"
70
+ },
71
+ {
72
+ "name": "over a million tokens, resets soon, big spend",
73
+ "now": 1800000000,
74
+ "branch": "feature/login",
75
+ "payload": {
76
+ "model": {
77
+ "display_name": "Opus 5.5"
78
+ },
79
+ "workspace": {
80
+ "current_dir": "/code/app"
81
+ },
82
+ "context_window": {
83
+ "total_input_tokens": 1204000,
84
+ "total_output_tokens": 1000,
85
+ "used_percentage": 60.25
86
+ },
87
+ "rate_limits": {
88
+ "five_hour": {
89
+ "used_percentage": 97.5,
90
+ "resets_at": 1800000030
91
+ },
92
+ "seven_day": {
93
+ "used_percentage": 50
94
+ }
95
+ },
96
+ "cost": {
97
+ "total_cost_usd": 1234.5
98
+ }
99
+ },
100
+ "expected": "Opus 5.5 · app ⑂ feature/login · ctx 1.21M (60%) · 5h 98%(now) · wk 50% · $1,234.50"
101
+ },
102
+ {
103
+ "name": "the 5-hour window has reset, so it shows 0%",
104
+ "now": 1800000000,
105
+ "branch": null,
106
+ "payload": {
107
+ "rate_limits": {
108
+ "seven_day": {
109
+ "used_percentage": 12.5,
110
+ "resets_at": 1800002700
111
+ }
112
+ }
113
+ },
114
+ "expected": "5h 0% · wk 13%(45m)"
115
+ },
116
+ {
117
+ "name": "a window past its reset time counts as 0%",
118
+ "now": 1800000000,
119
+ "branch": null,
120
+ "payload": {
121
+ "rate_limits": {
122
+ "five_hour": {
123
+ "used_percentage": 91,
124
+ "resets_at": 1799999000
125
+ },
126
+ "seven_day": {
127
+ "used_percentage": 40,
128
+ "resets_at": 1800090000
129
+ }
130
+ }
131
+ },
132
+ "expected": "5h 0% · wk 40%(1d)"
133
+ },
134
+ {
135
+ "name": "every window has reset, so both show 0%",
136
+ "now": 1800000000,
137
+ "branch": null,
138
+ "payload": {
139
+ "rate_limits": {
140
+ "five_hour": {
141
+ "used_percentage": 91,
142
+ "resets_at": 1799999000
143
+ }
144
+ }
145
+ },
146
+ "expected": "5h 0% · wk 0%"
147
+ },
148
+ {
149
+ "name": "nothing usable",
150
+ "now": 1800000000,
151
+ "branch": null,
152
+ "payload": {
153
+ "model": null,
154
+ "context_window": "broken",
155
+ "rate_limits": {
156
+ "five_hour": {
157
+ "used_percentage": "high"
158
+ }
159
+ },
160
+ "cost": {
161
+ "total_cost_usd": true
162
+ }
163
+ },
164
+ "expected": ""
165
+ }
166
+ ]
@@ -0,0 +1,120 @@
1
+ 'use strict';
2
+
3
+ const assert = require('node:assert/strict');
4
+ const { execFileSync } = require('node:child_process');
5
+ const fs = require('node:fs');
6
+ const os = require('node:os');
7
+ const path = require('node:path');
8
+ const { test, describe, beforeEach, afterEach } = require('node:test');
9
+
10
+ const { render, gitBranch } = require('../lib/line');
11
+ const settings = require('../lib/settings');
12
+ const { currentLimits } = require('../lib/limits');
13
+
14
+ const cases = JSON.parse(fs.readFileSync(path.join(__dirname, 'fixtures', 'cases.json'), 'utf8'));
15
+ const tempDir = () => fs.mkdtempSync(path.join(os.tmpdir(), 'ctxline-'));
16
+
17
+ describe('render', () => {
18
+ for (const testCase of cases) {
19
+ test(testCase.name, () => {
20
+ assert.equal(render(testCase.payload, testCase.now, testCase.branch, false), testCase.expected);
21
+ });
22
+ }
23
+
24
+ test('tone follows what is left', () => {
25
+ const line = render({ rate_limits: { five_hour: { used_percentage: 80 }, seven_day: { used_percentage: 95 } } }, 0);
26
+ assert.ok(line.includes('\x1b[33m5h 80%'));
27
+ assert.ok(line.includes('\x1b[31mwk 95%'));
28
+ });
29
+ });
30
+
31
+ describe('gitBranch', () => {
32
+ test('reads HEAD from a parent folder', () => {
33
+ const repo = tempDir();
34
+ fs.mkdirSync(path.join(repo, '.git'));
35
+ fs.writeFileSync(path.join(repo, '.git', 'HEAD'), 'ref: refs/heads/workshop/level-3\n');
36
+ const nested = path.join(repo, 'app', 'src');
37
+ fs.mkdirSync(nested, { recursive: true });
38
+ assert.equal(gitBranch(nested), 'workshop/level-3');
39
+ });
40
+
41
+ test('follows a worktree pointer', () => {
42
+ const root = tempDir();
43
+ const gitdir = path.join(root, 'main', '.git', 'worktrees', 'feature');
44
+ fs.mkdirSync(gitdir, { recursive: true });
45
+ fs.writeFileSync(path.join(gitdir, 'HEAD'), 'ref: refs/heads/feature\n');
46
+ const worktree = path.join(root, 'feature');
47
+ fs.mkdirSync(worktree);
48
+ fs.writeFileSync(path.join(worktree, '.git'), `gitdir: ${gitdir}\n`);
49
+ assert.equal(gitBranch(worktree), 'feature');
50
+ });
51
+
52
+ test('detached HEAD shows a short hash', () => {
53
+ const repo = tempDir();
54
+ fs.mkdirSync(path.join(repo, '.git'));
55
+ fs.writeFileSync(path.join(repo, '.git', 'HEAD'), '1c9ddeb0a1b2c3d4\n');
56
+ assert.equal(gitBranch(repo), '1c9ddeb');
57
+ });
58
+ });
59
+
60
+ describe('settings', () => {
61
+ let home;
62
+ const settingsFile = () => path.join(home, 'settings.json');
63
+ const readSettings = () => JSON.parse(fs.readFileSync(settingsFile(), 'utf8'));
64
+
65
+ beforeEach(() => {
66
+ home = tempDir();
67
+ process.env.CLAUDE_CONFIG_DIR = home;
68
+ });
69
+ afterEach(() => delete process.env.CLAUDE_CONFIG_DIR);
70
+
71
+ test('install keeps other settings and the old line', () => {
72
+ const old = { type: 'command', command: '~/.claude/scripts/claude-statusline' };
73
+ fs.writeFileSync(settingsFile(), JSON.stringify({ model: 'opus', statusLine: old }));
74
+ settings.install('/bin/ctxline');
75
+ assert.equal(readSettings().model, 'opus');
76
+ assert.equal(readSettings().statusLine.command, '/bin/ctxline');
77
+ assert.equal(readSettings().statusLine.refreshInterval, 60);
78
+ settings.uninstall();
79
+ assert.deepEqual(readSettings().statusLine, old);
80
+ assert.equal(fs.existsSync(path.join(home, 'ctxline-previous.json')), false);
81
+ });
82
+
83
+ test('reinstall does not save itself as the old line', () => {
84
+ settings.install('/bin/ctxline');
85
+ settings.install('/usr/local/bin/ctxline');
86
+ settings.uninstall();
87
+ assert.equal('statusLine' in readSettings(), false);
88
+ });
89
+
90
+ test("uninstall leaves someone else's line alone", () => {
91
+ fs.writeFileSync(settingsFile(), JSON.stringify({ statusLine: { type: 'command', command: 'other' } }));
92
+ settings.uninstall();
93
+ assert.equal(readSettings().statusLine.command, 'other');
94
+ });
95
+ });
96
+
97
+ describe('remembered limits', () => {
98
+ beforeEach(() => {
99
+ process.env.CLAUDE_CONFIG_DIR = tempDir();
100
+ });
101
+ afterEach(() => delete process.env.CLAUDE_CONFIG_DIR);
102
+
103
+ test('a new session shows the last limits seen', () => {
104
+ const seen = { five_hour: { used_percentage: 8, resets_at: 2000 }, seven_day: { used_percentage: 28, resets_at: 9000 } };
105
+ currentLimits({ rate_limits: seen }, 1000);
106
+ assert.equal(render({}, 1500, null, false, currentLimits({}, 1500)), '5h 8%(8m) · wk 28%(2h)');
107
+ });
108
+
109
+ test('nothing is shown before any limits are seen', () => {
110
+ assert.equal(render({}, 0, null, false, currentLimits({}, 0)), '');
111
+ });
112
+ });
113
+
114
+ test('bad input prints an empty line', () => {
115
+ const output = execFileSync(process.execPath, [path.join(__dirname, '..', 'bin', 'ctxline.js')], {
116
+ input: 'not json',
117
+ env: { ...process.env, CLAUDE_CONFIG_DIR: tempDir() },
118
+ });
119
+ assert.equal(output.toString(), '\n');
120
+ });
@@ -0,0 +1,130 @@
1
+ import json
2
+ import os
3
+ import subprocess
4
+ import sys
5
+ import tempfile
6
+ import unittest
7
+ from pathlib import Path
8
+
9
+ ROOT = Path(__file__).resolve().parent.parent
10
+ sys.path.insert(0, str(ROOT / "src"))
11
+
12
+ from ctxline import settings
13
+ from ctxline.limits import current_limits
14
+ from ctxline.line import git_branch, render
15
+
16
+ CASES = json.loads((ROOT / "tests" / "fixtures" / "cases.json").read_text())
17
+
18
+
19
+ class RenderTest(unittest.TestCase):
20
+ def test_shared_cases(self):
21
+ for case in CASES:
22
+ with self.subTest(case["name"]):
23
+ self.assertEqual(render(case["payload"], case["now"], case["branch"], color=False), case["expected"])
24
+
25
+ def test_tone_follows_what_is_left(self):
26
+ line = render({"rate_limits": {"five_hour": {"used_percentage": 80}, "seven_day": {"used_percentage": 95}}}, 0)
27
+ self.assertIn("\033[33m5h 80%", line)
28
+ self.assertIn("\033[31mwk 95%", line)
29
+
30
+
31
+ class GitBranchTest(unittest.TestCase):
32
+ def test_reads_head_from_a_parent_folder(self):
33
+ with tempfile.TemporaryDirectory() as repo:
34
+ (Path(repo) / ".git").mkdir()
35
+ (Path(repo) / ".git" / "HEAD").write_text("ref: refs/heads/workshop/level-3\n")
36
+ nested = Path(repo) / "app" / "src"
37
+ nested.mkdir(parents=True)
38
+ self.assertEqual(git_branch(str(nested)), "workshop/level-3")
39
+
40
+ def test_follows_a_worktree_pointer(self):
41
+ with tempfile.TemporaryDirectory() as root:
42
+ gitdir = Path(root) / "main" / ".git" / "worktrees" / "feature"
43
+ gitdir.mkdir(parents=True)
44
+ (gitdir / "HEAD").write_text("ref: refs/heads/feature\n")
45
+ worktree = Path(root) / "feature"
46
+ worktree.mkdir()
47
+ (worktree / ".git").write_text(f"gitdir: {gitdir}\n")
48
+ self.assertEqual(git_branch(str(worktree)), "feature")
49
+
50
+ def test_detached_head_shows_a_short_hash(self):
51
+ with tempfile.TemporaryDirectory() as repo:
52
+ (Path(repo) / ".git").mkdir()
53
+ (Path(repo) / ".git" / "HEAD").write_text("1c9ddeb0a1b2c3d4\n")
54
+ self.assertEqual(git_branch(repo), "1c9ddeb")
55
+
56
+
57
+ class SettingsTest(unittest.TestCase):
58
+ def setUp(self):
59
+ self.home = tempfile.TemporaryDirectory()
60
+ os.environ["CLAUDE_CONFIG_DIR"] = self.home.name
61
+
62
+ def tearDown(self):
63
+ del os.environ["CLAUDE_CONFIG_DIR"]
64
+ self.home.cleanup()
65
+
66
+ def write_settings(self, data):
67
+ (Path(self.home.name) / "settings.json").write_text(json.dumps(data))
68
+
69
+ def read_settings(self):
70
+ return json.loads((Path(self.home.name) / "settings.json").read_text())
71
+
72
+ def test_install_keeps_other_settings_and_the_old_line(self):
73
+ old = {"type": "command", "command": "~/.claude/scripts/claude-statusline"}
74
+ self.write_settings({"model": "opus", "statusLine": old})
75
+ settings.install("/bin/ctxline")
76
+ saved = self.read_settings()
77
+ self.assertEqual(saved["model"], "opus")
78
+ self.assertEqual(saved["statusLine"]["command"], "/bin/ctxline")
79
+ self.assertEqual(saved["statusLine"]["refreshInterval"], 60)
80
+ settings.uninstall()
81
+ self.assertEqual(self.read_settings()["statusLine"], old)
82
+ self.assertFalse((Path(self.home.name) / "ctxline-previous.json").exists())
83
+
84
+ def test_reinstall_does_not_save_itself_as_the_old_line(self):
85
+ settings.install("/bin/ctxline")
86
+ settings.install("/usr/local/bin/ctxline")
87
+ settings.uninstall()
88
+ self.assertNotIn("statusLine", self.read_settings())
89
+
90
+ def test_uninstall_leaves_someone_elses_line_alone(self):
91
+ self.write_settings({"statusLine": {"type": "command", "command": "other"}})
92
+ settings.uninstall()
93
+ self.assertEqual(self.read_settings()["statusLine"]["command"], "other")
94
+
95
+
96
+ class LimitsMemoryTest(unittest.TestCase):
97
+ def setUp(self):
98
+ self.home = tempfile.TemporaryDirectory()
99
+ os.environ["CLAUDE_CONFIG_DIR"] = self.home.name
100
+
101
+ def tearDown(self):
102
+ del os.environ["CLAUDE_CONFIG_DIR"]
103
+ self.home.cleanup()
104
+
105
+ def test_a_new_session_shows_the_last_limits_seen(self):
106
+ seen = {"five_hour": {"used_percentage": 8, "resets_at": 2000}, "seven_day": {"used_percentage": 28, "resets_at": 9000}}
107
+ current_limits({"rate_limits": seen}, 1000)
108
+ limits = current_limits({}, 1500)
109
+ self.assertEqual(render({}, 1500, color=False, limits=limits), "5h 8%(8m) · wk 28%(2h)")
110
+
111
+ def test_nothing_is_shown_before_any_limits_are_seen(self):
112
+ self.assertEqual(render({}, 0, color=False, limits=current_limits({}, 0)), "")
113
+
114
+
115
+ class CliTest(unittest.TestCase):
116
+ def test_bad_input_prints_an_empty_line(self):
117
+ home = tempfile.TemporaryDirectory()
118
+ self.addCleanup(home.cleanup)
119
+ result = subprocess.run(
120
+ [sys.executable, "-m", "ctxline"],
121
+ input="not json",
122
+ capture_output=True,
123
+ text=True,
124
+ env={**os.environ, "PYTHONPATH": str(ROOT / "src"), "CLAUDE_CONFIG_DIR": home.name},
125
+ )
126
+ self.assertEqual((result.returncode, result.stdout), (0, "\n"))
127
+
128
+
129
+ if __name__ == "__main__":
130
+ unittest.main()