Skip to content

Commit 75cc6e2

Browse files
committed
fix(claude): harden usage data fetch and cache validation
- write api response to temp file before promoting to cache - validate json contains utilization data before updating cache - replace xargs printf with jq round for percentage calculation - add fallback for empty percentage values
1 parent 25b676b commit 75cc6e2

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

ai-stuff/claude/scripts/statusline.sh

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -133,13 +133,23 @@ fetch_usage_data() {
133133
local token
134134
token=$(get_oauth_token)
135135
if [ -z "$token" ]; then return 1; fi
136-
curl -s --max-time 5 \
136+
local tmp_file="${CACHE_FILE}.tmp"
137+
if curl -s --max-time 5 \
137138
-H "Accept: application/json" \
138139
-H "Content-Type: application/json" \
139140
-H "Authorization: Bearer $token" \
140141
-H "anthropic-beta: oauth-2025-04-20" \
141142
-H "User-Agent: claude-code/2.1.34" \
142-
"https://api.anthropic.com/api/oauth/usage" >"$CACHE_FILE" 2>/dev/null
143+
"https://api.anthropic.com/api/oauth/usage" >"$tmp_file" 2>/dev/null; then
144+
# Only update cache if we got valid JSON with utilization data
145+
if jq -e '.five_hour.utilization' "$tmp_file" >/dev/null 2>&1; then
146+
mv "$tmp_file" "$CACHE_FILE"
147+
else
148+
rm -f "$tmp_file"
149+
fi
150+
else
151+
rm -f "$tmp_file"
152+
fi
143153
}
144154

145155
needs_refresh=true
@@ -197,11 +207,13 @@ format_reset_time() {
197207
}
198208

199209
if [ -n "$usage_data" ]; then
200-
five_hour_pct=$(echo "$usage_data" | jq -r '.five_hour.utilization // 0' 2>/dev/null | xargs printf "%.0f" 2>/dev/null || echo 0)
210+
five_hour_pct=$(echo "$usage_data" | jq -r '(.five_hour.utilization // 0) | round' 2>/dev/null)
211+
[ -z "$five_hour_pct" ] && five_hour_pct=0
201212
five_hour_reset_iso=$(echo "$usage_data" | jq -r '.five_hour.resets_at // empty' 2>/dev/null)
202213
five_hour_reset=$(format_reset_time "$five_hour_reset_iso" "time")
203214

204-
seven_day_pct=$(echo "$usage_data" | jq -r '.seven_day.utilization // 0' 2>/dev/null | xargs printf "%.0f" 2>/dev/null || echo 0)
215+
seven_day_pct=$(echo "$usage_data" | jq -r '(.seven_day.utilization // 0) | round' 2>/dev/null)
216+
[ -z "$seven_day_pct" ] && seven_day_pct=0
205217
seven_day_reset_iso=$(echo "$usage_data" | jq -r '.seven_day.resets_at // empty' 2>/dev/null)
206218
seven_day_reset=$(format_reset_time "$seven_day_reset_iso" "datetime")
207219
fi

0 commit comments

Comments
 (0)