Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ bun run docs
- `~/.cache/ccstatusline/usage-<profileHash>.json` and `~/.cache/ccstatusline/usage-<profileHash>.lock` - per-profile usage API data cache and fetch backoff lock
- `~/.cache/ccstatusline/usage-<profileHash>.credentials.lock` - per-profile 30-second backoff after a usage credential lookup finds no OAuth login, also tagged with its credential source
- `~/.cache/ccstatusline/session-usage-history.json` and `~/.cache/ccstatusline/session-usage-history.json.lock` - 5-hour usage readings for Block Forecast and Block Limit Timer, per Claude config directory and login, and the lock a render holds while writing them
- `~/.cache/ccstatusline/account-email-<loginFingerprint>.json`, `.lock`, and `.inflight` - owner-only Claude Account Email caches, independent failure backoffs, and exclusive in-flight leases per login
- `~/.cache/ccstatusline/claude-status.json` and `~/.cache/ccstatusline/claude-status.lock` - Claude service-status cache and failed-fetch backoff lock
- `~/.cache/ccstatusline/skills/skills-<sessionId>.jsonl` - skill hook records; session IDs must contain only ASCII letters, digits, `-`, or `_`

Expand Down Expand Up @@ -100,13 +101,14 @@ After a complete successful usage fetch, the process clears the lock only if its
- **JJ widgets** invoke `runJjArgs()` with a five-second timeout and use their normal missing-data behavior when the command fails or times out.
- **Git PR and Git CI Status** render from the versioned disk cache under `~/.cache/ccstatusline/git-review`. Missing or stale entries are refreshed in a detached helper so network-bound `gh` or `glab` calls do not block rendering. Git CI Status adds GitHub's `statusCheckRollup`; if the authenticated `gh` token cannot read checks, the refresh retries with PR metadata only so Git PR still works.
- **Usage widgets** merge Claude Code's stdin `rate_limits` with `/api/oauth/usage` only for fields required by the active widgets. Session and aggregate weekly fields prefer the flat API buckets and fall back to `limits[]`; per-model weekly fields prefer `weekly_scoped` entries. A model-scoped entry reporting 0% without `resets_at` is valid zero usage, while unscoped empty placeholders remain filtered out. `WEEKLY_MODEL_USAGE_BUCKETS` in `src/utils/usage-types.ts` is the shared registry for Sonnet, Opus, and Fable widget wiring, field requirements, reset fields, and scoped-limit matching. Session and weekly percentage widgets delegate rendering and editor behavior to `src/widgets/shared/usage-percent-widget.ts`; the Fable label is `Weekly Fable:`. Spend Limit Usage and Spend Limit Amount read `rate_limits.spend_limit` from stdin only (no `USAGE_WIDGET_REQUIREMENTS` entry, so they never trigger an API fetch); the percentage widget goes through the same shared renderer with `ignoreApiError` set and no time cursor.
- **Claude Account Email** asks `/api/oauth/profile` which account the usage credentials belong to. Answers are cached under the usage cache's login fingerprint, so an access-token refresh reuses them and only a login change triggers another request. A failed lookup backs off for that login only: 30 seconds, or after a 429 the server's `Retry-After` (five minutes without one). `fetchAccountEmail()` distinguishes an available email, no OAuth credentials, and an unavailable email for an existing login. Only the no-credentials case falls back to `oauthAccount.emailAddress` in `.claude.json`; a failed or backed-off lookup for an existing login hides the widget. Independent lock files retain each login’s deadline across alternating failures and access-token refreshes. An exclusive 30-second lease coordinates requests and writes for each login; the request itself still has a five-second deadline. Expired owners cannot write results, and a failure never shortens an existing valid backoff. Cache entries are written atomically to separate owner-only files, so concurrent logins cannot discard each other’s answers. Matching entries in the old shared `account-email.json` remain readable; the shared file is never rewritten.
- **Custom Command** delegates to `src/utils/custom-command.ts`. `customCommandCacheTtlSeconds` defaults to `0` (disabled), with a maximum of 60 seconds. Both successes and failures are cached, with TTL measured from command completion; without a session ID, entries stay in process memory. Other stdin fields are deliberately excluded from the key. A helper in the current runtime captures stdout in memory, limits it to 1 MiB, and retains at most 16,384 characters; it enforces command deadlines and closes inherited pipes, terminating the process group on POSIX or the shell on Windows when a command times out. Cached raw output is formatted separately by each widget, and previews never execute commands.
- **Terminal width** is memoized once per render, including a `null` probe result. Linux first probes ancestor terminal devices through `/proc` and `tty.WriteStream`; portable fallbacks use `execFileSync` for `ps` and `stty`. `CCSTATUSLINE_WIDTH` takes precedence, including on Windows where probing is disabled. Only no-width results are persisted per session, for `terminalWidthCacheTtlSeconds` (default 5, range 0–300); `0` disables cross-process reuse. Numeric widths are re-probed on the next render.
- **Context length transcript fallback** treats the latest `compact_boundary` as the start of the current context. It uses the first main-chain usage entry after that boundary, then `compactMetadata.postTokens`, then zero, while session token totals remain cumulative.
- **Sandbox Status** reads `sandbox.enabled` from Claude Code's layered project-local, project, user-local, and user settings on every refresh. This reflects `/sandbox` file updates but remains a best-effort indicator when managed or CLI settings take precedence.
- **Skills** reads only logs for session IDs accepted by `getSkillsFilePath()`. Rejected IDs return no metrics, and the hook handler exits before creating directories or writing a log.

Both usage and service-status requests honor uppercase `HTTPS_PROXY` and share `isExcludedFromProxy()` for the `NO_PROXY`/`no_proxy` rules described in [Usage](USAGE.md#proxy-settings). Each request has a total five-second deadline in addition to its socket timeout. On expiry, `createProxyAgent().close()` aborts the pending proxy connection when `AbortController` is available; on older runtimes without it, that connection can remain open. The proxy integration tests require permission to listen on a local socket.
Usage, account profile, and service-status requests honor uppercase `HTTPS_PROXY` and share `isExcludedFromProxy()` for the `NO_PROXY`/`no_proxy` rules described in [Usage](USAGE.md#proxy-settings). Each request has a total five-second deadline in addition to its socket timeout. On expiry, `createProxyAgent().close()` aborts the pending proxy connection when `AbortController` is available; on older runtimes without it, that connection can remain open. The proxy integration tests require permission to listen on a local socket.

## Widget Implementation

Expand Down
6 changes: 4 additions & 2 deletions docs/USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ ccstatusline --version
### Claude & Session

- **Model** / **Output Style** / **Version** - Show the active Claude model, output style, and Claude Code CLI version. Model names omit trailing context suffixes like `(1M context)`; use **Context Window** when you want the total window size shown.
- **Claude Session ID** / **Session Name** / **Claude Account Email** - Show session identifiers plus the currently signed-in Claude account email.
- **Claude Session ID** / **Session Name** / **Claude Account Email** - Show session identifiers plus the currently signed-in Claude account email. Claude Account Email names the account the usage credentials belong to, looked up from `api.anthropic.com` once per login; see [Usage Credentials and Cache](#usage-credentials-and-cache).
- **Claude Status** - Show the current Claude/Anthropic service status from `status.claude.com` (`ok` when the indicator is `none`, otherwise the indicator word such as `minor`, `major`, `critical`, or `maintenance`). Press `h` in the editor to add a 48-hour incident-history strip of eight six-hour blocks (oldest to newest), each colored by the worst incident overlapping that block: green (none), yellow (minor), orange (major), red (critical). Responses are cached for about five minutes; on network failure the widget shows stale data when available or degrades to `?`. With the history strip enabled the widget colors itself by severity, so per-widget foreground colors and theme foregrounds are skipped, like Custom Command's preserve-colors mode. Press `l` to make the widget a link to the status page (`https://status.claude.com`), in terminals that support OSC 8 hyperlinks.
- **Voice Status** - Show whether Claude Code voice input is enabled. It can render as an icon, icon plus text, plain text, or `voice on/off`, with optional Nerd Font microphone icons.
- **Fast Mode** - Show whether Claude Code's fast mode is on, from the status line's `fast_mode` field. It can render as icon plus text (`⚡ on` / `⚡ off`, the default), an icon with a state dot, plain text, or `fast on/off`, with optional Nerd Font lightning icons. It can hide while fast mode is off, and shows nothing on Claude Code versions that don't report fast mode.
Expand Down Expand Up @@ -199,9 +199,11 @@ The usage cache uses a fingerprint of the refresh token when available, falling

Each macOS Keychain command has a five-second timeout. If a command times out, ccstatusline skips all remaining Keychain probes for that lookup and tries the current profile’s credentials file. When no OAuth credentials are found, the lookup backs off for 30 seconds for that profile, so a newly signed-in account may take up to 30 seconds to appear. Usage cache files dated more than 180 seconds into the future are treated as stale.

Claude Account Email uses the same credentials to look up the account's email from `/api/oauth/profile`. The answer is cached per login fingerprint, so an access-token refresh does not repeat the request. A failed lookup is retried after 30 seconds, or after the `Retry-After` of a 429 response (five minutes without one). Each login has its own cache and backoff files. Concurrent lookups for the same login are coordinated, and a failure does not shorten an existing backoff deadline. Concurrent lookups for different logins retain both cached emails. Existing matching entries in the old shared email cache remain usable. If credentials exist but their email lookup fails or is backed off, the widget is hidden instead of showing an unverified previous account. Without OAuth credentials, it can still show `oauthAccount.emailAddress` from `.claude.json`. Cached email is used only for the current login fingerprint.

### Proxy Settings

Usage requests to `api.anthropic.com` and Claude Status requests to `status.claude.com` honor uppercase `HTTPS_PROXY`. Both `NO_PROXY` and `no_proxy` supply exclusions; matching either variable sends the request directly.
Usage and Claude Account Email requests to `api.anthropic.com` and Claude Status requests to `status.claude.com` honor uppercase `HTTPS_PROXY`. Both `NO_PROXY` and `no_proxy` supply exclusions; matching either variable sends the request directly.

Exclusions are separated by commas or whitespace and matched without regard to case. Use `*` for all hosts, a hostname such as `api.anthropic.com`, or a domain such as `anthropic.com`, `.anthropic.com`, or `*.anthropic.com` to match that domain and its subdomains. An optional `:443` suffix is supported; entries for other ports do not match these HTTPS requests.

Expand Down
8 changes: 6 additions & 2 deletions src/ccstatusline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import {
getTerminalWidth
} from './utils/terminal';
import { sanitizeTerminalText } from './utils/terminal-sanitize';
import { fetchAccountEmail } from './utils/usage';
import { prefetchUsageDataIfNeeded } from './utils/usage-prefetch';
import { ensureWindowsUtf8CodePage } from './utils/windows-code-page';

Expand Down Expand Up @@ -104,6 +105,7 @@ async function renderMultipleLines(data: StatusJSON) {
const hasCompactionWidget = lines.some(line => line.some(item => item.type === 'compaction-counter'));
const hasThinkingEffortWidget = lines.some(line => line.some(item => item.type === 'thinking-effort'));
const hasSessionNameWidget = lines.some(line => line.some(item => item.type === 'session-name'));
const hasAccountEmailWidget = lines.some(line => line.some(item => item.type === 'claude-account-email'));
const needsTranscriptThinkingEffort = hasThinkingEffortWidget
&& (!data.effort || !('level' in data.effort));
const requestedSpeedWindows = new Set<number>();
Expand All @@ -126,10 +128,11 @@ async function renderMultipleLines(data: StatusJSON) {
includeSessionName: hasSessionNameWidget
})
: Promise.resolve(null);
const [transcriptAnalysis, usageData, claudeStatusData] = await Promise.all([
const [transcriptAnalysis, usageData, claudeStatusData, accountEmail] = await Promise.all([
transcriptAnalysisPromise,
prefetchUsageDataIfNeeded(lines, data),
prefetchClaudeStatusIfNeeded(lines)
prefetchClaudeStatusIfNeeded(lines),
hasAccountEmailWidget ? fetchAccountEmail() : Promise.resolve(undefined)
]);
const sessionForecast = computeSessionForecastIfNeeded(lines, usageData, getDefaultSessionUsageHistoryDeps(data));

Expand All @@ -156,6 +159,7 @@ async function renderMultipleLines(data: StatusJSON) {
usageData,
sessionForecast,
claudeStatusData,
accountEmail,
sessionDuration,
transcriptSessionName: hasSessionNameWidget
? (transcriptAnalysis?.sessionName ?? null)
Expand Down
3 changes: 3 additions & 0 deletions src/types/AccountEmail.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export type AccountEmailResult = { status: 'available'; email: string }
| { status: 'no-credentials' }
| { status: 'unavailable' };
2 changes: 2 additions & 0 deletions src/types/RenderContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type {
SkillsMetrics
} from '../types';

import type { AccountEmailResult } from './AccountEmail';
import type { SessionForecast } from './SessionForecast';
import type { SpeedMetrics } from './SpeedMetrics';
import type { StatusJSON } from './StatusJSON';
Expand Down Expand Up @@ -55,6 +56,7 @@ export interface RenderContext {
usageData?: RenderUsageData | null;
sessionForecast?: SessionForecast | null;
claudeStatusData?: ClaudeStatusRenderData | null;
accountEmail?: AccountEmailResult; // Email of the account the live OAuth credentials belong to
sessionDuration?: string | null;
transcriptSessionName?: string | null;
transcriptThinkingEffort?: { value: string; known: boolean } | null;
Expand Down
Loading
Loading