From 9b40251b5e7c8faa65526d28fde827172b039737 Mon Sep 17 00:00:00 2001 From: Vlad Mocanu Date: Sun, 4 Oct 2026 21:29:27 +0300 Subject: [PATCH 1/4] feat: line-1 repo-wide session state counts Count every live Claude Code session in the same repo (this one included) from the session registry and show them right-aligned on line 1: busy, background shells, waiting on you (?), and idle. Hidden when the session is alone in its repo; STATUSLINE_PEERS=0 opts out. Codex shim entries are excluded. The ? state is a transcript-tail hint. Docs pending. --- statusline.sh | 141 ++++++++++++++++++++++++++++++++--- tests/run-tests.sh | 182 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 311 insertions(+), 12 deletions(-) diff --git a/statusline.sh b/statusline.sh index 8a70b7f..891f4c7 100755 --- a/statusline.sh +++ b/statusline.sh @@ -1408,6 +1408,110 @@ 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 picture (up to each one's own render +# moment) 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). +# Bracketed, [○N], when this session is one of them, so an idle +# session you switch to is easy to spot +# 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. +_asked_user() { # _asked_user -> "ask" when the last reply asked something + tail -n 300 "$1" 2>/dev/null | jq -rR ' + fromjson? | select(.type == "assistant" and (.message.content | type) == "array") + | .message.content as $c + | if any($c[]; .type == "tool_use" and .name == "AskUserQuestion") then "ask" + else ([$c[] | select(.type == "text") | .text] | last // empty + | split("\n") | map(select(test("\\S"))) | last // "" + | gsub("[\\s*_`)\\]]+$"; "") + | if endswith("?") then "ask" else "no" end) + end' 2>/dev/null | tail -n1 +} +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 + P_BUSY=0 P_SHELL=0 P_ASK=0 P_IDLE=0 P_OTHERS=0 P_SELF_IDLE=0 + while IFS=$'\t' read -r _p_sid _p_pid _p_status _p_cwd; do + case "$_p_pid" in ''|*[!0-9]*) continue ;; esac + kill -0 "$_p_pid" 2>/dev/null || continue + _p_in=0 + while IFS= read -r _wt; do + [ -n "$_wt" ] || continue + case "$_p_cwd" in "$_wt"|"$_wt"/*) _p_in=1; break ;; esac + done <<<"$_PEER_WTS" + [ "$_p_in" = "1" ] || continue + case "$_p_status" in + busy) P_BUSY=$((P_BUSY + 1)) ;; + shell) P_SHELL=$((P_SHELL + 1)) ;; + idle) + _p_q="" + # sessionId is only ever used as a file name: refuse any + # value that could walk out of the projects folder. + if [ "$_p_sid" != "$SESSION_ID" ]; then + case "$_p_sid" in + ''|*/*|*..*) ;; + *) for _p_tr in "$_PROJ_DIR"/*/"$_p_sid".jsonl; do + [ -f "$_p_tr" ] && _p_q=$(_asked_user "$_p_tr" || true) + break + done ;; + esac + fi + if [ "$_p_q" = "ask" ]; then P_ASK=$((P_ASK + 1)); else P_IDLE=$((P_IDLE + 1)); fi + [ "$_p_sid" = "$SESSION_ID" ] && P_SELF_IDLE=1 ;; + *) continue ;; + esac + [ "$_p_sid" = "$SESSION_ID" ] || P_OTHERS=$((P_OTHERS + 1)) + done < <(jq -r \ + 'select(.entrypoint != "codex") + | [(.sessionId // ""), (.pid | tostring), (.status // ""), (.cwd // "")] | @tsv' \ + "$_PEER_DIR"/*.json 2>/dev/null || true) + # 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_BUSY" -gt 0 ] && _P_BODY+=" ${TXT_BOLD}⚙${P_BUSY}${B}" + [ "$P_SHELL" -gt 0 ] && _P_BODY+=" ${TXT_FG}◷${P_SHELL}${B}" + [ "$P_ASK" -gt 0 ] && _P_BODY+=" \033[7m${TXT_BOLD}?${P_ASK}${B}" + if [ "$P_SELF_IDLE" = "1" ]; then + _P_BODY+=" ${TXT_BOLD}[${_P_DIM}○${P_IDLE}${TXT_BOLD}]${B}" + elif [ "$P_IDLE" -gt 0 ]; then + _P_BODY+=" ${_P_DIM}○${P_IDLE}${B}" + fi + [ "$P_OTHERS" -gt 0 ] && [ -n "$_P_BODY" ] && PEER_SEG="${SEP}${B}${_P_BODY} " + fi +fi + # ── GitHub service status (line 1, after the branch; repo-scoped) ─────────── # On by default; opt OUT with STATUSLINE_GITHUB_STATUS=0. Uses the SAME status # glyphs and colors as the Claude icon above (green ✓ / gold ~ / orange ⚠ / @@ -1701,24 +1805,37 @@ _TAB_TITLE="${TOPIC:-${DIR:-Claude}}" { printf '\033]1;%s\007' "$_TAB_TITLE" > /dev/tty; } 2>/dev/null || true # ── Pad shorter line to match longer ──────────────────────────────────────── -# The update indicator (UPD_SEG, empty when current) is placed here rather than -# in assemble_l1: right-aligned into line 1's padding zone. It is shown when it -# fits in the gap below line 2's width, or when appending it keeps line 1 +# The right-aligned segments (peer sessions PEER_SEG, then the update indicator +# UPD_SEG; each empty when it has nothing to say) are placed here rather than in +# assemble_l1: right-aligned into line 1's padding zone. A segment is shown when +# it fits in the gap below line 2's width, or when appending it keeps line 1 # within TARGET (line 2 then pads to match); otherwise it is dropped, never # truncated, so it can neither widen a line past the budget nor be sliced -# mid-escape. +# mid-escape. Both are tried together first; when only one fits, the peer +# counts win (they change minute to minute, the update notice can wait). { - # Single perl invocation for both line measurements plus the indicator - read -r L1_COLS L2_COLS UPD_W < <( - measure_cols "$L1C" "$L2C" "$UPD_SEG" | tr '\n' ' ' + # Single perl invocation for both line measurements plus both segments + read -r L1_COLS L2_COLS UPD_W PEER_W < <( + measure_cols "$L1C" "$L2C" "$UPD_SEG" "$PEER_SEG" | tr '\n' ' ' ) - L1_COLS=${L1_COLS:-0}; L2_COLS=${L2_COLS:-0}; UPD_W=${UPD_W:-0} + L1_COLS=${L1_COLS:-0}; L2_COLS=${L2_COLS:-0}; UPD_W=${UPD_W:-0}; PEER_W=${PEER_W:-0} SYNC_W=$L2_COLS [ "$L1_COLS" -gt "$SYNC_W" ] 2>/dev/null && SYNC_W=$L1_COLS - if [ -n "$UPD_SEG" ] && [ "$UPD_W" -gt 0 ] 2>/dev/null && [ "$L1_COLS" -gt 10 ] 2>/dev/null \ - && { [ "$((L1_COLS + UPD_W))" -le "$SYNC_W" ] || [ "$((L1_COLS + UPD_W))" -le "$TARGET" ]; } 2>/dev/null; then - [ "$((L1_COLS + UPD_W))" -gt "$SYNC_W" ] && SYNC_W=$((L1_COLS + UPD_W)) - L1C+="${BG1}$(printf '%*s' "$((SYNC_W - L1_COLS - UPD_W))" '')${UPD_SEG}" + _right_fits() { # _right_fits : does a right segment of that width fit? + [ "$1" -gt 0 ] && [ "$L1_COLS" -gt 10 ] \ + && { [ "$((L1_COLS + $1))" -le "$SYNC_W" ] || [ "$((L1_COLS + $1))" -le "$TARGET" ]; } + } 2>/dev/null + RIGHT_SEG=""; RIGHT_W=0 + if [ -n "$PEER_SEG" ] && [ -n "$UPD_SEG" ] && _right_fits "$((PEER_W + UPD_W))"; then + RIGHT_SEG="${PEER_SEG}${UPD_SEG}"; RIGHT_W=$((PEER_W + UPD_W)) + elif [ -n "$PEER_SEG" ] && _right_fits "$PEER_W"; then + RIGHT_SEG="$PEER_SEG"; RIGHT_W=$PEER_W + elif [ -n "$UPD_SEG" ] && _right_fits "$UPD_W"; then + RIGHT_SEG="$UPD_SEG"; RIGHT_W=$UPD_W + fi + if [ -n "$RIGHT_SEG" ]; then + [ "$((L1_COLS + RIGHT_W))" -gt "$SYNC_W" ] && SYNC_W=$((L1_COLS + RIGHT_W)) + L1C+="${BG1}$(printf '%*s' "$((SYNC_W - L1_COLS - RIGHT_W))" '')${RIGHT_SEG}" L1_COLS=$SYNC_W fi if [ "$L1_COLS" -gt 10 ] 2>/dev/null && [ "$L1_COLS" -lt "$SYNC_W" ] 2>/dev/null; then diff --git a/tests/run-tests.sh b/tests/run-tests.sh index 76a63c8..37a0731 100644 --- a/tests/run-tests.sh +++ b/tests/run-tests.sh @@ -2273,6 +2273,187 @@ cache_timer_tests() { _pc_case pc-narrow-hitrate-only-2 "-" "$(_pc_json "{$w,\"ttl\":\"5m\",\"expires_at\":1700000040}")" STATUSLINE_CACHE=1 STATUSLINE_WIDTH=83 } +# ── Peer-session tests ───────────────────────────────────────────────────── +# The right-aligned line-1 segment counts EVERY live session in the same repo +# (this one included; shown only when at least one other exists) +# from the session registry (CC_STATUSLINE_SESSIONS_DIR seam): ⚙ busy, ◷ shell, +# ○ idle, zero counts omitted. A throwaway repo with a linked worktree at an +# unrelated path proves "same repo" follows `git worktree list`, not the path. +# Live pids come from this harness ($$); a reaped background job supplies a +# pid that is certainly dead. +peer_tests() { + printf '\n' + printf 'peer-session tests\n' + printf '%s\n' "------------------------------------------------------------" + + local name out err l1 reg repo wt other dead w1 w2 + reg="$SCRATCH/peer-reg" + # cd -P: git reports physical paths (macOS TMPDIR sits behind /var -> /private/var) + repo="$(mkdir -p "$SCRATCH/peer-repo" && cd -P "$SCRATCH/peer-repo" && pwd)" + wt="$(cd -P "$SCRATCH" && pwd)/peer-wt-elsewhere" + other="$(mkdir -p "$SCRATCH/peer-other" && cd -P "$SCRATCH/peer-other" && pwd)" + git -C "$repo" init -q 2>/dev/null + git -C "$repo" -c user.name=t -c user.email=t@t commit -q --allow-empty -m init 2>/dev/null + git -C "$repo" worktree add -q -b peer-wt "$wt" 2>/dev/null + mkdir -p "$repo/sub" + git -C "$other" init -q 2>/dev/null + sleep 0 & dead=$!; wait "$dead" 2>/dev/null + + _peer_entry() { # _peer_entry + printf '{"pid":%s,"sessionId":"%s","name":"p-%s","status":"%s","cwd":"%s"}\n' \ + "$2" "$3" "$1" "$4" "$5" > "$reg/$1.json" + } + _peer_run() { # _peer_run + local o="$1" e="$2"; shift 2 + ( cd "$SCRATCH" && printf '{"model":{"display_name":"Claude Opus 5","id":"opus"},"cwd":"%s","context_window":{"remaining_percentage":50,"context_window_size":1000000},"cost":{"total_duration_ms":300000},"session_id":"self-sid"}' "$repo" \ + | env CC_STATUSLINE_SESSIONS_DIR="$reg" CC_STATUSLINE_RL_CACHE="$SCRATCH/peer.cache" "$@" \ + bash "$STATUSLINE" ) >"$o" 2>"$e" + } + _peer_full_reg() { + rm -rf "$reg"; mkdir -p "$reg" + _peer_entry self "$$" self-sid busy "$repo" # this session: counted ⚙ (repo-wide view) + _peer_entry busy "$$" sid-b busy "$repo" # counted ⚙ + _peer_entry shell "$$" sid-s shell "$wt" # linked worktree: counted ◷ + _peer_entry idle "$$" sid-i idle "$repo/sub" # subdir: counted ○ + _peer_entry other "$$" sid-o busy "$other" # other repo: excluded + _peer_entry dead "$dead" sid-d busy "$repo" # dead pid: excluded + _peer_entry odd "$$" sid-u weird "$repo" # unknown status: ignored + _peer_entry pref "$$" sid-p busy "${repo}-sibling" # path-prefix lookalike: excluded + # Codex shim (session-peers): a Codex run, not a Claude session: excluded + printf '{"pid":%s,"sessionId":"sid-c","name":"codex-x","status":"busy","cwd":"%s","entrypoint":"codex"}\n' \ + "$$" "$repo" > "$reg/codex.json" + } + + # 1. Mixed registry -> self + one busy peer = ⚙2, one shell, one idle; + # every other entry filtered. + name="peers-counts-and-filters"; out="$SCRATCH/pe1.out"; err="$SCRATCH/pe1.err" + _peer_full_reg + _peer_run "$out" "$err" + l1=$(sed -n '1p' "$out" | _strip_ansi) + if [ -s "$err" ]; then _rl_fail "$name" "non-empty stderr: $(head -1 "$err")" + elif ! _has "$l1" "⚙2 ◷1 ○1"; then _rl_fail "$name" "expected '⚙2 ◷1 ○1' on line 1: $l1" + else _rl_pass "$name"; fi + + # 2. Both lines stay the same width and within budget with the segment placed. + name="peers-width" + w1=$(sed -n '1p' "$out" | vis_cols); w2=$(sed -n '2p' "$out" | vis_cols) + if [ "$w1" -ne "$w2" ]; then _rl_fail "$name" "line widths differ: $w1 vs $w2" + elif [ "$w1" -gt "$((SAFE_WIDTH + WIDTH_SLOP))" ]; then _rl_fail "$name" "width $w1 exceeds budget" + else _rl_pass "$name"; fi + + # 3. Zero counts are omitted: only an idle peer -> "○1", no busy/shell glyph. + name="peers-zero-counts-hidden"; out="$SCRATCH/pe3.out"; err="$SCRATCH/pe3.err" + rm -rf "$reg"; mkdir -p "$reg" + _peer_entry idle "$$" sid-i idle "$repo" + _peer_run "$out" "$err" + l1=$(sed -n '1p' "$out" | _strip_ansi) + if [ -s "$err" ]; then _rl_fail "$name" "non-empty stderr: $(head -1 "$err")" + elif ! _has "$l1" "○1"; then _rl_fail "$name" "idle count missing: $l1" + elif _has "$l1" "⚙" || _has "$l1" "◷"; then _rl_fail "$name" "zero count rendered: $l1" + else _rl_pass "$name"; fi + + # 4. Only this session (and filtered entries) -> no segment at all: a solo + # session renders as before even though it would count itself. + name="peers-none-no-segment"; out="$SCRATCH/pe4.out"; err="$SCRATCH/pe4.err" + rm -rf "$reg"; mkdir -p "$reg" + _peer_entry self "$$" self-sid busy "$repo" + _peer_entry dead "$dead" sid-d busy "$repo" + _peer_entry other "$$" sid-o idle "$other" + _peer_run "$out" "$err" + l1=$(sed -n '1p' "$out" | _strip_ansi) + if [ -s "$err" ]; then _rl_fail "$name" "non-empty stderr: $(head -1 "$err")" + elif _has "$l1" "⚙" || _has "$l1" "◷" || _has "$l1" "○"; then _rl_fail "$name" "segment shown with no peers: $l1" + else _rl_pass "$name"; fi + + # 5. STATUSLINE_PEERS=0 opts out. + name="peers-opt-out"; out="$SCRATCH/pe5.out"; err="$SCRATCH/pe5.err" + _peer_full_reg + _peer_run "$out" "$err" STATUSLINE_PEERS=0 + l1=$(sed -n '1p' "$out" | _strip_ansi) + if [ -s "$err" ]; then _rl_fail "$name" "non-empty stderr: $(head -1 "$err")" + elif _has "$l1" "⚙" || _has "$l1" "◷" || _has "$l1" "○"; then _rl_fail "$name" "STATUSLINE_PEERS=0 still rendered: $l1" + else _rl_pass "$name"; fi + + # 6. Peers and the update indicator share the right edge, peers first. + name="peers-with-update-indicator"; out="$SCRATCH/pe6.out"; err="$SCRATCH/pe6.err" + printf 'v99.0.0\n' > "$SCRATCH/peer-upd-cache" + _peer_run "$out" "$err" CC_STATUSLINE_UPDATE_CACHE="$SCRATCH/peer-upd-cache" + l1=$(sed -n '1p' "$out" | _strip_ansi) + w1=$(sed -n '1p' "$out" | vis_cols) + if [ -s "$err" ]; then _rl_fail "$name" "non-empty stderr: $(head -1 "$err")" + elif ! _has "$l1" "⚙2 ◷1 ○1 │ ⇡ 99.0.0"; then _rl_fail "$name" "expected peers then update: $l1" + elif [ "$w1" -gt "$((SAFE_WIDTH + WIDTH_SLOP))" ]; then _rl_fail "$name" "width $w1 exceeds budget" + else _rl_pass "$name"; fi + + # 7. Narrow viewport: the segment is dropped, never truncated, and the + # line still fits. + name="peers-narrow-dropped-not-cut"; out="$SCRATCH/pe7.out"; err="$SCRATCH/pe7.err" + _peer_run "$out" "$err" STATUSLINE_WIDTH=40 + l1=$(sed -n '1p' "$out" | _strip_ansi) + w1=$(sed -n '1p' "$out" | vis_cols) + if [ -s "$err" ]; then _rl_fail "$name" "non-empty stderr: $(head -1 "$err")" + elif [ "$w1" -gt 40 ]; then _rl_fail "$name" "width $w1 exceeds 40" + elif { _has "$l1" "⚙" || _has "$l1" "○"; } && ! _has "$l1" "⚙2 ◷1 ○1"; then _rl_fail "$name" "segment partially rendered: $l1" + else _rl_pass "$name"; fi + + git -C "$repo" worktree remove --force "$wt" 2>/dev/null || true + + # ── "?" state: an idle session whose last reply asked something. The + # transcript is found by session id under CC_STATUSLINE_PROJECTS_DIR. + local proj ask_txt done_txt ask_tool + proj="$SCRATCH/peer-projects" + ask_txt='{"type":"assistant","message":{"content":[{"type":"text","text":"Done the first part.\n\nShall I **continue?**"}]}}' + done_txt='{"type":"assistant","message":{"content":[{"type":"text","text":"Is it fixed? Yes.\n\nAll tests pass."}]}}' + ask_tool='{"type":"assistant","message":{"content":[{"type":"tool_use","name":"AskUserQuestion","input":{}}]}}' + _peer_tr() { # _peer_tr + mkdir -p "$proj/-some-project" + printf '%s\n' "$2" > "$proj/-some-project/$1.jsonl" + } + _ask_case() { # _ask_case + local n="$1" want="$2" reject="$3" + out="$SCRATCH/$n.out"; err="$SCRATCH/$n.err" + _peer_run "$out" "$err" CC_STATUSLINE_PROJECTS_DIR="$proj" + raw=$(sed -n '1p' "$out"); l1=$(printf '%s' "$raw" | _strip_ansi) + if [ -s "$err" ]; then _rl_fail "$n" "non-empty stderr: $(head -1 "$err")" + elif ! _has "$l1" "$want"; then _rl_fail "$n" "expected '$want': $l1" + elif [ -n "$reject" ] && _has "$l1" "$reject"; then _rl_fail "$n" "unexpected '$reject': $l1" + else _rl_pass "$n"; fi + } + local raw + rm -rf "$reg" "$proj"; mkdir -p "$reg" + _peer_entry self "$$" self-sid busy "$repo" + _peer_entry q "$$" sid-q idle "$repo" + _peer_entry d "$$" sid-d2 idle "$repo" + _peer_tr sid-q "$ask_txt" + _peer_tr sid-d2 "$done_txt" + _ask_case peers-ask-question-mark "⚙1 ?1 ○1" "" + # The "?" chip is drawn in reverse video + if _has "$raw" $'\e[7m'; then _rl_pass peers-ask-reverse-video + else _rl_fail peers-ask-reverse-video "no SGR 7 on the ? chip"; fi + + rm -rf "$reg" "$proj"; mkdir -p "$reg" + _peer_entry self "$$" self-sid busy "$repo" + _peer_entry q "$$" sid-q idle "$repo" + _peer_tr sid-q "$ask_tool" + _ask_case peers-ask-tool "?1" "○" + + # This session never counts itself as "?" (you are looking at it): ○ instead, + # and the idle count it joined is bracketed so the idle session stands out + rm -rf "$reg" "$proj"; mkdir -p "$reg" + _peer_entry self "$$" self-sid idle "$repo" + _peer_entry b "$$" sid-b busy "$repo" + _peer_tr self-sid "$ask_txt" + _ask_case peers-ask-not-self "⚙1 [○1]" "?" # and bracketed: this session is idle + + # No transcript, or a session id that tries to walk out of the folder -> ○ + rm -rf "$reg" "$proj"; mkdir -p "$reg" + _peer_entry self "$$" self-sid busy "$repo" + _peer_entry n "$$" sid-none idle "$repo" + _peer_entry e "$$" '../evil' idle "$repo" + mkdir -p "$proj"; printf '%s\n' "$ask_txt" > "$SCRATCH/evil.jsonl" + _ask_case peers-ask-missing-or-unsafe "⚙1 ○2" "?" +} + if [ ! -d "$FIXTURES" ]; then printf 'error: fixtures dir not found: %s\n' "$FIXTURES" >&2 exit 2 @@ -2293,6 +2474,7 @@ phone_truncation_tests phone_gap_tests github_status_tests session_name_tests +peer_tests env_hardening_tests effort_tests update_check_tests From 03135ca609e219e9bf48634c3095800e2b7b9ca7 Mon Sep 17 00:00:00 2001 From: Vlad Mocanu Date: Sun, 4 Oct 2026 21:34:07 +0300 Subject: [PATCH 2/4] docs: document repo-wide session counts --- CHANGELOG.md | 3 +++ CLAUDE.md | 2 ++ KNOWN_ISSUES.md | 24 ++++++++++++++++++++++++ README.md | 17 +++++++++++++++++ 4 files changed, 46 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 057e23f..f4fd28a 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 your own session's idle count is bracketed (`[○N]`). 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..a14c367 100644 --- a/KNOWN_ISSUES.md +++ b/KNOWN_ISSUES.md @@ -157,3 +157,27 @@ 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 + `○`. +- **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..887feea 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 your own session's idle count 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. Your own session is never counted as `?` (you are already looking at it); when it is idle, the `○` count it belongs to is bracketed, `[○N]`. "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. Each statusline 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). From 6318320024d6b7e51e345735049dde19d1fa7485 Mon Sep 17 00:00:00 2001 From: Vlad Mocanu Date: Sun, 4 Oct 2026 21:46:20 +0300 Subject: [PATCH 3/4] fix: harden session counts and bracket each session's own state Review fixes: parse registry files one by one so a malformed file cannot hide the rest; reject pid 0; resolve a symlinked cwd before the worktree match; treat an answered or cancelled question prompt as settled; read every idle peer's transcript tail in one batched jq pass. The count the current session belongs to is now bracketed in any state. --- CHANGELOG.md | 2 +- README.md | 6 +- statusline.sh | 140 +++++++++++++++++++++++++++++---------------- tests/run-tests.sh | 39 +++++++++++-- 4 files changed, 130 insertions(+), 57 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f4fd28a..2ca711e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ 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 your own session's idle count is bracketed (`[○N]`). 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. +- 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 diff --git a/README.md b/README.md index 887feea..891489b 100644 --- a/README.md +++ b/README.md @@ -27,7 +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 your own session's idle count bracketed; disable with `STATUSLINE_PEERS=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 @@ -257,7 +257,7 @@ Earlier versions synthesized the title with an opt-in `UserPromptSubmit` hook th ### 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]`: +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 | |---|---| @@ -266,7 +266,7 @@ When more than one Claude Code session works in the same repository, line 1 show | `?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. Your own session is never counted as `?` (you are already looking at it); when it is idle, the `○` count it belongs to is bracketed, `[○N]`. "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. +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. Each statusline 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`. diff --git a/statusline.sh b/statusline.sh index 891f4c7..61cac78 100755 --- a/statusline.sh +++ b/statusline.sh @@ -1422,8 +1422,8 @@ fi # 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). -# Bracketed, [○N], when this session is one of them, so an idle -# session you switch to is easy to spot +# 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. @@ -1440,17 +1440,6 @@ fi # 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. -_asked_user() { # _asked_user -> "ask" when the last reply asked something - tail -n 300 "$1" 2>/dev/null | jq -rR ' - fromjson? | select(.type == "assistant" and (.message.content | type) == "array") - | .message.content as $c - | if any($c[]; .type == "tool_use" and .name == "AskUserQuestion") then "ask" - else ([$c[] | select(.type == "text") | .text] | last // empty - | split("\n") | map(select(test("\\S"))) | last // "" - | gsub("[\\s*_`)\\]]+$"; "") - | if endswith("?") then "ask" else "no" end) - end' 2>/dev/null | tail -n1 -} PEER_SEG="" if [ "${STATUSLINE_PEERS:-1}" != "0" ] && [ -n "$SESSION_ID" ]; then _PEER_DIR="${CC_STATUSLINE_SESSIONS_DIR:-$HOME/.claude/sessions}" @@ -1459,55 +1448,110 @@ if [ "${STATUSLINE_PEERS:-1}" != "0" ] && [ -n "$SESSION_ID" ]; then [ -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 - P_BUSY=0 P_SHELL=0 P_ASK=0 P_IDLE=0 P_OTHERS=0 P_SELF_IDLE=0 + _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-9]*) continue ;; esac + case "$_p_pid" in ''|0|*[!0-9]*) continue ;; esac # kill -0 0 probes our own group kill -0 "$_p_pid" 2>/dev/null || continue - _p_in=0 - while IFS= read -r _wt; do - [ -n "$_wt" ] || continue - case "$_p_cwd" in "$_wt"|"$_wt"/*) _p_in=1; break ;; esac - done <<<"$_PEER_WTS" - [ "$_p_in" = "1" ] || 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) - _p_q="" - # sessionId is only ever used as a file name: refuse any - # value that could walk out of the projects folder. - if [ "$_p_sid" != "$SESSION_ID" ]; then - case "$_p_sid" in - ''|*/*|*..*) ;; - *) for _p_tr in "$_PROJ_DIR"/*/"$_p_sid".jsonl; do - [ -f "$_p_tr" ] && _p_q=$(_asked_user "$_p_tr" || true) - break - done ;; - esac - fi - if [ "$_p_q" = "ask" ]; then P_ASK=$((P_ASK + 1)); else P_IDLE=$((P_IDLE + 1)); fi - [ "$_p_sid" = "$SESSION_ID" ] && P_SELF_IDLE=1 ;; + 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 - [ "$_p_sid" = "$SESSION_ID" ] || P_OTHERS=$((P_OTHERS + 1)) - done < <(jq -r \ - 'select(.entrypoint != "codex") - | [(.sessionId // ""), (.pid | tostring), (.status // ""), (.cwd // "")] | @tsv' \ - "$_PEER_DIR"/*.json 2>/dev/null || true) + 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_BUSY" -gt 0 ] && _P_BODY+=" ${TXT_BOLD}⚙${P_BUSY}${B}" - [ "$P_SHELL" -gt 0 ] && _P_BODY+=" ${TXT_FG}◷${P_SHELL}${B}" - [ "$P_ASK" -gt 0 ] && _P_BODY+=" \033[7m${TXT_BOLD}?${P_ASK}${B}" - if [ "$P_SELF_IDLE" = "1" ]; then - _P_BODY+=" ${TXT_BOLD}[${_P_DIM}○${P_IDLE}${TXT_BOLD}]${B}" - elif [ "$P_IDLE" -gt 0 ]; then - _P_BODY+=" ${_P_DIM}○${P_IDLE}${B}" - fi + _p_add() { # _p_add