The CLD panel went blank with no reason when Claude Code's saved OAuth token had expired and the widget's own renewal was refused. - Collapsed panel shows EXPIRED/ERR instead of dashes; failures are logged to `qs log`. - Retry every minute after a failure instead of every 5. - claude-usage identifies as claude-cli, the suspected cause of the refresh 429s. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
62 lines
2.2 KiB
Bash
62 lines
2.2 KiB
Bash
creds="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/.credentials.json"
|
|
|
|
fail() {
|
|
jq -cn --arg e "$1" '{error: $e}'
|
|
exit 0
|
|
}
|
|
|
|
[ -r "$creds" ] || fail "not logged in"
|
|
|
|
# Identify as Claude Code: the suspected cause of refreshes failing with 429.
|
|
version="$(claude --version 2>/dev/null | cut -d" " -f1)" || true
|
|
ua="claude-cli/${version:-2.1.0} (external, cli)"
|
|
|
|
# The refresh token rotates, so the new one must be written back or the CLI's
|
|
# next refresh fails and forces a re-login.
|
|
refresh() {
|
|
local rt scope body code tmp
|
|
rt="$(jq -r '.claudeAiOauth.refreshToken // empty' "$creds")"
|
|
[ -n "$rt" ] || fail "no refresh token"
|
|
scope="$(jq -r '.claudeAiOauth.scopes // [] | join(" ")' "$creds")"
|
|
body="$(mktemp)"
|
|
code="$(jq -cn --arg rt "$rt" --arg s "$scope" \
|
|
'{grant_type: "refresh_token", refresh_token: $rt,
|
|
client_id: "9d1c250a-e61b-44d9-88ed-5944d1962f5e", scope: $s}' \
|
|
| curl -s -m 20 -o "$body" -w '%{http_code}' \
|
|
https://platform.claude.com/v1/oauth/token \
|
|
-H 'Content-Type: application/json' -A "$ua" --data-binary @-)" || code=000
|
|
if [ "$code" != 200 ]; then
|
|
rm -f "$body"
|
|
fail "token refresh HTTP $code"
|
|
fi
|
|
tmp="$(mktemp "$creds.XXXXXX")"
|
|
chmod 600 "$tmp"
|
|
jq --slurpfile r "$body" '.claudeAiOauth += {
|
|
accessToken: $r[0].access_token,
|
|
refreshToken: ($r[0].refresh_token // .claudeAiOauth.refreshToken),
|
|
expiresAt: (now * 1000 + $r[0].expires_in * 1000 | floor)
|
|
}' "$creds" > "$tmp" && mv "$tmp" "$creds"
|
|
rm -f "$body" "$tmp"
|
|
}
|
|
|
|
expired() {
|
|
jq -e '(.claudeAiOauth.expiresAt // 0) < (now * 1000 + 300000)' "$creds" >/dev/null
|
|
}
|
|
|
|
if expired; then
|
|
exec 9>"${XDG_RUNTIME_DIR:-/tmp}/claude-usage.lock"
|
|
flock 9
|
|
# Another run may have refreshed while this one waited.
|
|
if expired; then refresh; fi
|
|
fi
|
|
|
|
token="$(jq -r '.claudeAiOauth.accessToken // empty' "$creds")"
|
|
[ -n "$token" ] || fail "not logged in"
|
|
|
|
body="$(curl -s -m 20 -w '\n%{http_code}' https://api.anthropic.com/api/oauth/usage \
|
|
-H "Authorization: Bearer $token" \
|
|
-H 'anthropic-beta: oauth-2025-04-20' -A "$ua")" || fail "usage request failed"
|
|
code="${body##*$'\n'}"
|
|
[ "$code" = 200 ] || fail "usage HTTP $code"
|
|
printf '%s' "${body%$'\n'*}" | jq -c . || fail "bad usage response"
|