diff --git a/CHANGELOG.md b/CHANGELOG.md index 057e23f..2ca711e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ and the project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Added +- Repo-wide session counts on line 1 (`STATUSLINE_PEERS`, on by default). When another Claude Code session works in the same repository (linked worktrees included), the right edge of line 1 counts every session, this one included, by state: `⚙` busy, `◷` background shells running, `?` idle and waiting on your answer (reverse video), `○` idle. Zero counts are omitted, the segment is hidden for a lone session, and the count the current session belongs to is bracketed (`[⚙N]`, `[◷N]` or `[○N]`); the current session never counts as `?`. States come from Claude Code's internal session registry; `?` is a hint from the end of each idle session's transcript. Codex peer threads are not counted. The segment shares line 1's spare columns with the update indicator and is dropped, never truncated, when it does not fit. + ## [v3.5.1] - 2026-09-30 ### Changed diff --git a/CLAUDE.md b/CLAUDE.md index 52024bb..a00beb1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -201,6 +201,8 @@ Line 1 leads with two identifiers that come straight from Claude Code, sourced i - **`@handle`** (`SESSION_HANDLE`): the addressable name peers message (`SendMessage({to})`), e.g. `@uzi-60`. Read from Claude Code's per-session registry `~/.claude/sessions/.json`, selecting the file whose `.sessionId` matches the stdin `.session_id` and taking `.name`. This covers both the auto-derived handle and a `/rename` value. **This registry is an UNDOCUMENTED internal file** (verified against Claude Code 2.1.233: `.sessionId`, `.name`, `.nameSource`, `.status`, `.messagingSocketPath`); its shape may change across versions, so the read is fully guarded and the handle just doesn't show on any miss. Toggle: `STATUSLINE_SESSION_NAME` (default 1). Test seam: `CC_STATUSLINE_SESSIONS_DIR`. - **Title** (`SESSION_TITLE` -> `TOPIC`): the descriptive label, from the **documented** stdin `.session_name` field (Claude Code's `/rename` value, else its auto-generated session title, which it also stores in the transcript as `.aiTitle`). Absent until a title exists, so a brand-new session shows none. Toggle: `STATUSLINE_TOPIC` (default 1). +**Repo-wide session counts** (`PEER_SEG`, toggle `STATUSLINE_PEERS`) read the same registry for every live session (`.pid` alive, `.status` busy/shell/idle, `.cwd` inside a `git worktree list` path), excluding `.entrypoint == "codex"` shims. The `?` state tails each idle peer's transcript, found by glob `~/.claude/projects/*/.jsonl`. Test seams: `CC_STATUSLINE_SESSIONS_DIR`, `CC_STATUSLINE_PROJECTS_DIR`. Verified: a running background subagent keeps a session `busy`; `shell` means background shells are still running after the turn (observed, undocumented). SGR 5 blink does not render in the statusline (tried and removed). + Do NOT conflate the two: `.session_name` is the *title*, never the addressable handle. The default `my-app-3f`-style display name does NOT populate `.session_name` (it stays absent), which is why the handle has to come from the registry. Both values are user/model-controlled, so both get the standard control-byte strip and a 40-codepoint cap, and both ride the line-1 truncation ladder (title on the `TOPIC` rung, handle on the `NAME` rung). **History:** the title was previously synthesized by an opt-in `UserPromptSubmit` hook (`hooks/session-topic-capture.sh`) that called Claude Haiku and wrote `~/.claude/session-topics/.txt`. That hook was removed once Claude Code exposed `.session_name` natively (no credential, transcript excerpt, or quota needed). If you see references to `session-topic-capture.sh`, `_strip_ctl`, or `session-topics/` in old commits/docs, they predate that removal. diff --git a/KNOWN_ISSUES.md b/KNOWN_ISSUES.md index 64d9521..6b25178 100644 --- a/KNOWN_ISSUES.md +++ b/KNOWN_ISSUES.md @@ -157,3 +157,32 @@ active Claude/OpenAI provider) so they are clickable; glyphs, which are never truncated. `measure_cols` (and the test harness's `vis_cols`/`_strip_ansi`) strip the OSC 8 wrapper, so it is zero-width for layout, matching what a terminal actually renders. + +## Repo-wide session counts read an internal registry + +The line-1 session counts (`STATUSLINE_PEERS`) depend on Claude Code +internals and on redraw timing: + +- **The registry is undocumented.** `~/.claude/sessions/.json` and its + `.status` values (`busy`, `shell`, `idle`) are internal to Claude Code and + may change in any release. The read is guarded: an unknown status is ignored + and a missing registry hides the segment. The meaning of `shell` (turn ended, + background shells still running) is inferred from observation, not + documented. +- **`?` is a guess.** It reads the end of an idle session's transcript and + flags a pending question prompt or a final line ending in `?`. A rhetorical + question shows as `?`; a request phrased without a question mark shows as + `○`. +- **A waiting session sees itself as `○`.** The current session is never + counted as `?` (you are already looking at it), so its own statusline and + the others' show the same total but a different split for as long as it + waits on you: with idle sessions A and B where only A asked something, A + shows `[○2]` and B shows `?1 [○1]`. This is intentional. +- **Counts can disagree briefly.** Each statusline counts when it redraws, so + two sessions can differ by one for up to the `refreshInterval` while a + session changes state. Without `refreshInterval`, an idle session never + redraws and its counts go stale. +- **Paths are compared literally.** A session counts when its registry `.cwd` + sits inside one of the repo's `git worktree list` paths. A cwd reached + through a symlink, or a separate repository nested inside a worktree, can be + miscounted. diff --git a/README.md b/README.md index ca5574b..34490d7 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ A two-line, ANSI-colored statusline for [Claude Code](https://claude.com/claude- - **GitHub service status**: line-1 icon (same glyphs/colors as the provider one), shown on repos with a `github.com` remote; on by default, disable with `STATUSLINE_GITHUB_STATUS=0` - **Clickable status icons**: both service-status icons are OSC 8 hyperlinks (GitHub icon to `githubstatus.com`, provider icon to `status.claude.com` or `status.openai.com`), so Cmd+click (macOS) / Ctrl+click opens the status page in a supporting terminal; on by default, disable with `STATUSLINE_HYPERLINKS=0` - **Update indicator**: a gold `⇡ X.Y.Z` at the right edge of line 1 when a newer cc-statusline release exists (checked hourly against GitHub, hyperlinked to the release page); hidden entirely when you are current, disable with `STATUSLINE_UPDATE_CHECK=0` +- **Sessions in this repo**: right-aligned on line 1 when another Claude Code session works in the same repository, a repo-wide count of every session by state (`⚙` busy, `◷` background shells running, `?` waiting on your answer, `○` idle), with the count your own session belongs to bracketed; disable with `STATUSLINE_PEERS=0` - **Session name (`@handle`)**: the addressable name other Claude sessions use to message this one (Claude Code's per-session registry), shown first on line 1; on by default, hide with `STATUSLINE_SESSION_NAME=0` - **Session title**: Claude Code's native session name (its `/rename` value or auto-generated title, from `.session_name`) as a descriptive label after the handle; hide with `STATUSLINE_TOPIC=0` - **Tab title**: sets the terminal tab title from the session title or directory @@ -160,6 +161,7 @@ The key is the project root (resolved via `git rev-parse --show-toplevel`); the | `STATUSLINE_CACHE_TIMER` | `1` | Set to `0` to hide the prompt-cache cooldown timer on line 2 (fire + minutes left while warm, snowflake + tokens to re-cache once cold), independent of `STATUSLINE_CACHE`. When line 2 is short on room it keeps the timer and drops the hit rate first. Claude Code redraws when the cache expires, but the minutes only count down while idle with `refreshInterval` set. Hidden on GPT panes. | | `STATUSLINE_CTX` | `1` | Set to `0` to hide the context-fill segment (`ctx NN%`) on the phone/slim layout's line 2. Shown before the rate limits with the same color thresholds; the first line-2 segment to shed as the viewport tightens. The wide layout's context readout is unaffected. | | `STATUSLINE_SESSION_NAME` | `1` | Set to `0` to hide the `@handle` (the addressable session name peers message, read from Claude Code's per-session registry) at the start of line 1. | +| `STATUSLINE_PEERS` | `1` | Set to `0` to hide the repo-wide session counts right-aligned on line 1 (see [Sessions in this repo](#sessions-in-this-repo)). | | `STATUSLINE_TOPIC` | `1` | Set to `0` to hide the descriptive session title on line 1 (Claude Code's `/rename` value or auto-generated title, from the `.session_name` payload field). | | `STATUSLINE_GITHUB_STATUS` | `1` | Set to `0` to hide the GitHub service-status icon on line 1 after the branch (same glyphs/colors as the Claude icon). Shown only when the current repo has a `github.com` remote; polls `githubstatus.com` every 60s in the background. | | `STATUSLINE_HYPERLINKS` | `1` | Set to `0` to disable the OSC 8 hyperlinks on the service-status icons (GitHub plus the active Claude/OpenAI provider). Needs a terminal that supports OSC 8 (Ghostty, iTerm2, Kitty, WezTerm); elsewhere the escape is swallowed and the icon shows as plain text. | @@ -253,6 +255,21 @@ Line 1 leads with two identifiers Claude Code provides natively, so neither need Earlier versions synthesized the title with an opt-in `UserPromptSubmit` hook that called Claude Haiku; that hook has been removed in favor of the native field, which needs no credential, transcript excerpt, or quota. If you registered that hook in `settings.json` before upgrading, remove its `UserPromptSubmit` entry: otherwise Claude Code prints `session-topic-capture.sh: No such file or directory` on every prompt (harmless but noisy). The stale `~/.claude/session-topics/` cache it wrote is safe to delete. +### Sessions in this repo + +When more than one Claude Code session works in the same repository, line 1 shows a repo-wide count of all of them, your own included, at its right edge, for example `[⚙2] ◷1 ?1 ○2`: + +| Glyph | Meaning | +|---|---| +| `⚙N` | busy: a turn is running (a running background subagent keeps a session busy too) | +| `◷N` | the turn ended but background shells are still running, e.g. a watcher waiting on a delegated run | +| `?N` | idle, and its last reply asked you something (an unanswered question prompt, or its final line ends with `?`); drawn in reverse video so it stands out | +| `○N` | idle and asked nothing: probably finished, a candidate for a final check | + +Zero counts are left out, and the whole segment is hidden when a session is alone in its repo. The count your own session belongs to is bracketed (`[⚙N]`, `[◷N]` or `[○N]`), so each session shows where it stands; it is never counted as `?`, since you are already looking at it. "Same repo" follows `git worktree list`, so sessions in linked worktrees at other paths count too. Codex threads attached as session peers are not counted; they are Codex runs, not Claude Code sessions. + +The states come from Claude Code's per-session registry (`~/.claude/sessions/*.json`, the same internal file the `@handle` uses), and `?` is a hint read from the end of each idle session's transcript, not a guarantee. Every session in the repo shows the same total, but not always the same split: a session waiting on you counts itself as `○` while the others count it as `?`, so with two idle sessions where only A asked something, A shows `[○2]` and B shows `?1 [○1]`. Each statusline also counts at its own redraw, so two sessions can briefly disagree by one; set `refreshInterval` on your `statusLine` so idle sessions redraw (60 seconds is plenty). The segment sits in line 1's spare columns next to the update indicator and is dropped, never truncated, when it does not fit. Disable with `STATUSLINE_PEERS=0`. + ### Per-account usage fetcher `claude-usage-fetch.sh` runs in the background (spawned by the statusline, throttled to once a minute across all your sessions per account) and asks `api.anthropic.com/api/oauth/usage` for the account's true 5h/7d usage, authenticated as the session itself: the session's `CLAUDE_CODE_OAUTH_TOKEN` when it was launched with one, your stored login otherwise. This exists because Claude Code feeds every session the same cached rate-limit numbers regardless of which account the session bills (shared `~/.claude.json` state), so on multi-account machines the bars were whichever account fetched last. The credential is never logged, never put in argv/env, and is only sent to `api.anthropic.com` over HTTPS. Set `STATUSLINE_RL_FETCH=0` to disable (the statusline then falls back to whatever Claude Code reports). diff --git a/statusline.sh b/statusline.sh index 8a70b7f..ec8f514 100755 --- a/statusline.sh +++ b/statusline.sh @@ -1408,6 +1408,156 @@ if [ "${STATUSLINE_UPDATE_CHECK:-1}" != "0" ]; then fi fi +# ── Peer sessions in this repo (line 1, right-aligned) ────────────────────── +# On by default; opt OUT with STATUSLINE_PEERS=0. Counts EVERY live session +# working in the same repository, this one included, by state, so all of the +# repo's sessions show the same repo-wide total (up to each one's own render +# moment; the split differs by design where a session waits on you, since it +# counts itself as ○ while the others count it as ?) and a multi-session setup +# shows at a glance which need attention: +# ⚙N busy (a turn, background subagent, or similar is running) +# ◷N shell (the turn ended but background shells are still running, e.g. a +# watcher that will wake the session when a delegated run finishes) +# ?N asks (idle, and its last reply asked you something: a pending +# AskUserQuestion, or the final line of its last text ends with "?"). +# Drawn in reverse video so it stands out. The session showing the +# segment never counts itself here (you are already looking at it); +# it falls to ○ instead +# ○N idle (idle and asked nothing: probably finished, NOT proof of it). +# The count this session belongs to is bracketed ([⚙N], [◷N] or [○N]), so each +# session shows its own state within the repo-wide picture. +# The ? test is a HINT from the transcript tail, not a guarantee. +# Zero counts are omitted, and the whole segment is absent unless at least one +# OTHER session shares the repo, so a solo session renders exactly as before. +# Source: the same UNDOCUMENTED per-session registry as the @handle +# (~/.claude/sessions/.json: .sessionId, .pid, .status, .cwd). Only +# Claude Code sessions count: Codex threads attached through session-peers shims +# register there too (.entrypoint "codex"), but they are Codex runs helping a +# Claude session, not sessions of their own. An entry counts only when its pid +# is alive (registry files can outlive a crashed process) and its .cwd sits +# inside one of this repo's worktrees: one `git worktree list` per render covers +# linked worktrees at any path, with no per-peer git call. Unknown .status +# values are ignored. An idle peer's transcript is found by session id under +# ~/.claude/projects/*/ (no reliance on how Claude Code names those folders) and +# only its last 300 lines are read. Placed in the padding pass at the bottom, +# like the update indicator: dropped, never truncated, when it does not fit. +# Test seams: CC_STATUSLINE_SESSIONS_DIR, CC_STATUSLINE_PROJECTS_DIR. +PEER_SEG="" +if [ "${STATUSLINE_PEERS:-1}" != "0" ] && [ -n "$SESSION_ID" ]; then + _PEER_DIR="${CC_STATUSLINE_SESSIONS_DIR:-$HOME/.claude/sessions}" + _PROJ_DIR="${CC_STATUSLINE_PROJECTS_DIR:-$HOME/.claude/projects}" + _PEER_WTS="" + [ -d "$_PEER_DIR" ] && _PEER_WTS=$(git -C "$CWD_FULL" worktree list --porcelain 2>/dev/null \ + | sed -n 's/^worktree //p' || true) + if [ -n "$_PEER_WTS" ]; then + _in_repo() { # _in_repo : is it one of this repo's worktrees, or under one? + local w + while IFS= read -r w; do + [ -n "$w" ] || continue + case "$1" in "$w"|"$w"/*) return 0 ;; esac + done <<<"$_PEER_WTS" + return 1 + } + P_BUSY=0 P_SHELL=0 P_ASK=0 P_IDLE=0 P_OTHERS=0 P_SELF="" + _P_IDLE_SIDS="" # idle peers (not this session) whose transcript to check + # Registry files are joined with an RS byte and parsed one by one + # (fromjson?), so a malformed or half-written file is skipped instead of + # aborting the read for every session after it. Files come both compact + # and pretty-printed, which rules out line-based parsing. + while IFS=$'\t' read -r _p_sid _p_pid _p_status _p_cwd; do + case "$_p_pid" in ''|0|*[!0-9]*) continue ;; esac # kill -0 0 probes our own group + kill -0 "$_p_pid" 2>/dev/null || continue + if ! _in_repo "$_p_cwd"; then + # Git reports physical paths; the registry may hold a symlinked + # one (macOS /tmp vs /private/tmp). Resolve only on a miss, so + # the common case costs no subshell. + _p_phys=$(cd "$_p_cwd" 2>/dev/null && pwd -P) || continue + _in_repo "$_p_phys" || continue + fi + case "$_p_status" in + busy) P_BUSY=$((P_BUSY + 1)) ;; + shell) P_SHELL=$((P_SHELL + 1)) ;; + idle) + if [ "$_p_sid" = "$SESSION_ID" ]; then + P_IDLE=$((P_IDLE + 1)) + else + # Classified in one batch below; until then it is idle. + P_IDLE=$((P_IDLE + 1)) + # The id becomes a file name and a JSON string: only a + # plain id is looked up, anything else stays idle. + case "$_p_sid" in ''|*[!A-Za-z0-9_-]*) ;; *) _P_IDLE_SIDS+="$_p_sid " ;; esac + fi ;; + *) continue ;; + esac + if [ "$_p_sid" = "$SESSION_ID" ]; then P_SELF="$_p_status"; else P_OTHERS=$((P_OTHERS + 1)); fi + done < <(for _p_f in "$_PEER_DIR"/*.json; do + [ -f "$_p_f" ] && { cat "$_p_f"; printf '\036'; } + done 2>/dev/null | jq -Rrs ' + split("\u001e")[] | fromjson? | objects + | select(.entrypoint != "codex") + | [(.sessionId // "" | tostring), (.pid // "" | tostring), + (.status // "" | tostring), (.cwd // "" | tostring)] | @tsv' 2>/dev/null || true) + # "?" check, one jq pass for every idle peer: each transcript tail is + # preceded by a {"__peer":id} marker. A peer asks when an AskUserQuestion + # call has no tool_result yet (answered and cancelled prompts both write + # one), or when its last assistant block is text whose final non-blank + # line ends with "?" (trailing markdown stripped). Lines are prefiltered + # to assistant records and tool results; fromjson? skips any line the + # tail cut in half. + if [ -n "$_P_IDLE_SIDS" ]; then + P_ASK=$(for _p_sid in $_P_IDLE_SIDS; do + for _p_tr in "$_PROJ_DIR"/*/"$_p_sid".jsonl; do + [ -f "$_p_tr" ] || break + printf '{"__peer":"%s"}\n' "$_p_sid" + tail -n 300 "$_p_tr" 2>/dev/null | grep -F -e '"assistant"' -e '"tool_result"' || true + break + done + done 2>/dev/null | jq -nR ' + reduce (inputs | fromjson? | objects) as $r ({cur: null, s: {}}; + if $r.__peer then .cur = $r.__peer | .s[.cur] = {pend: {}, last: "no"} + elif .cur == null then . + elif $r.type == "assistant" and ($r.message.content | type) == "array" then + reduce $r.message.content[] as $c (.; + if $c.type == "tool_use" then + (if $c.name == "AskUserQuestion" then .s[.cur].pend[($c.id // "?") | tostring] = true else . end) + | .s[.cur].last = "no" + elif $c.type == "text" then + .s[.cur].last = ($c.text | tostring | split("\n") | map(select(test("\\S"))) | last // "" + | gsub("[\\s*_`)\\]]+$"; "") + | if endswith("?") then "ask" else "no" end) + else . end) + elif ($r.message.content | type) == "array" then + reduce ($r.message.content[] | objects | select(.type == "tool_result") + | (.tool_use_id // "") | tostring) as $id (.; .s[.cur].pend |= del(.[$id])) + else . end) + | [.s[] | select((.pend | length) > 0 or .last == "ask")] | length' 2>/dev/null || echo 0) + P_ASK=$(_gate_int "$P_ASK" 0) + [ "$P_ASK" -gt "$P_IDLE" ] && P_ASK=$P_IDLE + P_IDLE=$((P_IDLE - P_ASK)) + fi + # Weight, not hue, carries urgency: the 12 project backgrounds make any + # fixed color unreadable on some of them, while the palette's own dark + # text stays legible on all. Busy is bold, idle is the dim separator + # tone, and a waiting question is reversed (dark chip, light text). + _P_DIM="\033[38;2;${SEP_R};${SEP_G};${SEP_B}m" + _P_BODY="" + _p_add() { # _p_add