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
2 changes: 2 additions & 0 deletions docs/USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ ccstatusline --version
- **Tokens Input** / **Tokens Output** / **Tokens Cached** / **Tokens Total** - Show current-session token counts. Input/output prefer cumulative transcript metrics and fall back to `context_window.total_input_tokens` / `context_window.total_output_tokens` when transcript metrics are unavailable; cached/total use transcript metrics.
- **Cache Hit Rate** / **Cache Read** / **Cache Write** - Show prompt-cache efficiency. Cache Hit Rate uses cache reads divided by cache reads plus cache writes; Cache Read and Cache Write include each value's share of prompt context. They default to the latest turn from `context_window.current_usage`, can switch to cumulative session totals, and can hide when empty.
- **Cache Timer** - Show time remaining before the current prompt-cache entry expires. When Claude Code provides usable `prompt_cache` data, the widget counts down to `expires_at` or shows `COLD` when `warm` is false. The reported `ttl` (`5m` or `1h`) controls the fresh/draining/urgent glyph thresholds. This reported state takes precedence even during a turn, so the Working glyph (`🔥 HOT`) is used only in the transcript fallback. Without usable reported state (including `caching_observed: false`), the widget shows `HOT` while a main-chain turn is active, then estimates expiry from the latest assistant request with cache activity. Interrupts and local slash commands such as `/cost` end that working state without refreshing the cache anchor. The `t` setting selects a 5-minute or 1-hour TTL for this fallback countdown; it also supplies glyph thresholds when a reported expiry has no recognized TTL. Each state's glyph can be customized, and the widget can hide when neither reported state nor a transcript cache anchor is available.
- **Cache Misses** / **Last Cache Miss** / **Cache Miss Tokens** / **Cache If Cold** - Show the prompt cache statistics Claude Code reports for the main conversation (Claude Code 2.1.251 or later), the same figures as the `Prompt cache (main)` line of `/usage`. Cache Misses shows the misses out of the session's requests (`2/14`); a miss is a request that re-processed content the cache already held, so rebuilds after a compaction don't count. Last Cache Miss shows when the last miss happened and its likely cause (`3m ago, tools changed (+2)`, `5m TTL expired`, `system prompt changed (+120 chars)`); causes need Claude Code 2.1.260 or later and read `cause unknown` when Claude Code identified none. Cache Miss Tokens shows the tokens the misses wrote back to the cache (`310.2k`), and Cache If Cold what the next request re-caches if the cache has gone cold by then (`45.0k`). They read only the status line payload, so they render nothing until the session's first API response; Last Cache Miss also stays empty until the first miss, and Cache If Cold right after a compaction until the next request.
- **Input Speed** / **Output Speed** / **Total Speed** - Show session-average token throughput with an optional per-widget rolling window (`0-120` seconds; `0` = full-session average). Token totals and speed metrics count repeated content-block records with the same response ID once, including interleaved records.
- **Context Length** / **Context Window** / **Context %** / **Context % (usable)** / **Context Bar** - Show current context length, total context window size, used/remaining percentage, usable-window percentage, or a progress bar. When Claude Code omits a percentage, the percentage calculated from its current usage counts input, cache-read, and cache-write tokens, excluding output tokens until a later turn reads them as input. Reported percentages retain precedence. The window size is taken from Claude Code's reported `context_window.context_window_size` when present, then from a model-name hint (e.g. a `[1m]` suffix), and finally from a fixed fallback. Set `CCSTATUSLINE_CONTEXT_SIZE_FALLBACK` to a positive integer to override that last-resort fallback (defaults to `200000`) — useful when an older Claude Code does not report the window size for a 1M-context model, so the bar would otherwise read against 200k. Immediately after `/compact`, transcript fallback uses the latest `compact_boundary.postTokens` value until a new main-chain turn reports the current size, so the widgets do not retain the pre-compaction context.
- **Compaction Counter** - Show how many context compactions have been detected in the current session by scanning transcript compaction markers. It can render as icon plus number, text plus number, or number-only, and can hide while the count is zero. Two optional, independent per-item add-ons toggle extra detail: a trigger split (`↻ 3 (2 auto, 1 manual)`; a compaction whose trigger is missing or unrecognized is bucketed as `unknown`) and tokens reclaimed (`↻ 3 ↓887.0k`, each compaction's `preTokens - postTokens` floored at 0 and summed, shown only when greater than 0 — so very old transcripts predating the `postTokens` field display nothing). Its value selector can instead render the total count, one trigger count (`auto`, `manual`, or `unknown`), or reclaimed tokens as a standalone value; hide-when-zero applies to the selected value.
Expand Down Expand Up @@ -372,6 +373,7 @@ Supported states by widget family:
- **Extra Usage widgets**: `disabled` hides the `n/a` display when extra usage is off, `no-data` hides the error placeholder when usage data is unavailable
- **Block / Weekly / Weekly Sonnet / Weekly Opus / Weekly Fable Usage**: `no-data` hides the error placeholder (`[No credentials]`, `[Timeout]`, `[Rate limited]`, `[API Error]`, `[Parse Error]`) when usage data is unavailable
- **Cache widgets** (`Cache Hit Rate`, `Cache Read`, `Cache Write`, `Cache Timer`): `empty` hides the widget when there is no cache activity, and on Cache Timer when neither usable reported cache state nor a transcript cache anchor is available
- **Cache Misses / Cache Miss Tokens**: `zero` hides the widget while the session has no prompt cache misses
- **Custom Text / Custom Symbol**: `merge-target-hidden` hides the item when the widget it is merged with renders nothing, so icon prefixes/suffixes disappear together with their widget

In `settings.json`, the enabled states are stored as a comma-separated list in
Expand Down
43 changes: 35 additions & 8 deletions src/types/StatusJSON.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,40 @@ const SpendLimitSchema = RateLimitPeriodSchema.extend({

export type RateLimitPeriod = z.infer<typeof RateLimitPeriodSchema>;

// A field Claude Code sends in a shape this version doesn't know is dropped,
// so the rest of the payload (and the status line) still renders.
function tolerant<T extends z.ZodType>(schema: T) {
return schema.nullable().optional().catch(undefined);
}

// The likely cause of the last prompt cache miss (Claude Code 2.1.260+): cause
// names such as tools_changed, plus counts for some of them.
const LastMissCauseSchema = z.looseObject({
causes: z.array(z.string()).catch([]),
tools_added: tolerant(CoercedNumberSchema),
tools_removed: tolerant(CoercedNumberSchema),
system_char_delta: tolerant(CoercedNumberSchema)
});

// Prompt cache statistics for the main conversation (Claude Code 2.1.251+).
// Absent until the session's first API response. Timestamps are epoch seconds.
const PromptCacheSchema = z.object({
warm: tolerant(z.boolean()),
caching_observed: tolerant(z.boolean()),
ttl: tolerant(z.string()),
expires_at: tolerant(CoercedNumberSchema),
requests: tolerant(CoercedNumberSchema),
misses: tolerant(CoercedNumberSchema),
expected_rebuilds: tolerant(CoercedNumberSchema),
hit_ratio: tolerant(CoercedNumberSchema),
cache_write_tokens: tolerant(CoercedNumberSchema),
miss_recache_tokens: tolerant(CoercedNumberSchema),
last_miss_at: tolerant(CoercedNumberSchema),
last_miss_cause: tolerant(LastMissCauseSchema),
miss_causes: tolerant(z.record(z.string(), CoercedNumberSchema)),
recache_tokens_if_cold: tolerant(CoercedNumberSchema)
});

export const StatusJSONSchema = z.looseObject({
hook_event_name: z.string().optional(),
session_id: z.string().optional(),
Expand Down Expand Up @@ -85,14 +119,7 @@ export const StatusJSONSchema = z.looseObject({
// Claude Code reports the live prompt-cache state, including the real
// expiry timestamp, so consumers do not have to infer it from transcript
// timings. Absent on older Claude Code versions.
prompt_cache: z.object({
warm: z.boolean().nullable().optional(),
caching_observed: z.boolean().nullable().optional(),
ttl: z.string().nullable().optional(),
expires_at: CoercedNumberSchema.nullable().optional(), // Unix epoch seconds
hit_ratio: CoercedNumberSchema.nullable().optional(),
recache_tokens_if_cold: CoercedNumberSchema.nullable().optional()
}).nullable().optional(),
prompt_cache: tolerant(PromptCacheSchema),
rate_limits: z.object({
five_hour: RateLimitPeriodSchema.optional(),
seven_day: RateLimitPeriodSchema.optional(),
Expand Down
93 changes: 93 additions & 0 deletions src/types/__tests__/StatusJSON.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,4 +232,97 @@ describe('StatusJSONSchema numeric coercion', () => {
expect(result.data.fast_mode).toBeUndefined();
expect(result.data.model).toEqual({ id: 'claude-opus-4-6' });
});

it('parses prompt_cache with every documented field', () => {
const result = StatusJSONSchema.safeParse({
prompt_cache: {
warm: true,
caching_observed: true,
ttl: '1h',
expires_at: 1738429200,
requests: 14,
misses: '2',
expected_rebuilds: 1,
hit_ratio: 0.91,
cache_write_tokens: 352000,
miss_recache_tokens: 310200,
last_miss_at: 1738425230,
last_miss_cause: { causes: ['tools_changed'], tools_added: 2, tools_removed: 0 },
miss_causes: { tools_changed: 2 },
recache_tokens_if_cold: 45000
}
});

expect(result.success).toBe(true);
if (!result.success) {
return;
}

expect(result.data.prompt_cache).toEqual({
warm: true,
caching_observed: true,
ttl: '1h',
expires_at: 1738429200,
requests: 14,
misses: 2,
expected_rebuilds: 1,
hit_ratio: 0.91,
cache_write_tokens: 352000,
miss_recache_tokens: 310200,
last_miss_at: 1738425230,
last_miss_cause: { causes: ['tools_changed'], tools_added: 2, tools_removed: 0 },
miss_causes: { tools_changed: 2 },
recache_tokens_if_cold: 45000
});
});

it('accepts the nulls prompt_cache documents', () => {
const promptCache = { expires_at: null, hit_ratio: null, last_miss_at: null, last_miss_cause: null, recache_tokens_if_cold: null };
const result = StatusJSONSchema.safeParse({ prompt_cache: promptCache });

expect(result.success).toBe(true);
if (!result.success) {
return;
}

expect(result.data.prompt_cache?.last_miss_at).toBeNull();
expect(result.data.prompt_cache?.last_miss_cause).toBeNull();
});

// The status line keeps rendering when Claude Code sends a prompt_cache
// field in a shape this version doesn't know
it('drops a malformed prompt_cache field instead of rejecting the payload', () => {
const result = StatusJSONSchema.safeParse({
model: { display_name: 'Opus' },
prompt_cache: {
requests: 14,
misses: 'several',
last_miss_cause: 'tools_changed',
miss_causes: { tools_changed: 'two' }
}
});

expect(result.success).toBe(true);
if (!result.success) {
return;
}

expect(result.data.model).toEqual({ display_name: 'Opus' });
expect(result.data.prompt_cache?.requests).toBe(14);
expect(result.data.prompt_cache?.misses).toBeUndefined();
expect(result.data.prompt_cache?.last_miss_cause).toBeUndefined();
expect(result.data.prompt_cache?.miss_causes).toBeUndefined();
});

it('drops a prompt_cache that is not an object instead of rejecting the payload', () => {
const result = StatusJSONSchema.safeParse({ model: { display_name: 'Opus' }, prompt_cache: 42 });

expect(result.success).toBe(true);
if (!result.success) {
return;
}

expect(result.data.model).toEqual({ display_name: 'Opus' });
expect(result.data.prompt_cache).toBeUndefined();
});
});
6 changes: 5 additions & 1 deletion src/utils/widget-manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,11 @@ export const WIDGET_MANIFEST: WidgetManifestEntry[] = [
{ type: 'worktree-branch', create: () => new widgets.GitWorktreeBranchWidget() },
{ type: 'worktree-original-branch', create: () => new widgets.GitWorktreeOriginalBranchWidget() },
{ type: 'compaction-counter', create: () => new widgets.CompactionCounterWidget() },
{ type: 'cache-timer', create: () => new widgets.CacheTimerWidget() }
{ type: 'cache-timer', create: () => new widgets.CacheTimerWidget() },
{ type: 'cache-misses', create: () => new widgets.CacheMissesWidget() },
{ type: 'last-cache-miss', create: () => new widgets.LastCacheMissWidget() },
{ type: 'cache-miss-tokens', create: () => new widgets.CacheMissTokensWidget() },
{ type: 'cache-if-cold', create: () => new widgets.CacheIfColdWidget() }
];

export const LAYOUT_WIDGET_MANIFEST: LayoutWidgetManifestEntry[] = [
Expand Down
40 changes: 40 additions & 0 deletions src/widgets/CacheIfCold.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import type { RenderContext } from '../types/RenderContext';
import type { Settings } from '../types/Settings';
import type {
Widget,
WidgetEditorDisplay,
WidgetItem
} from '../types/Widget';
import { formatTokens } from '../utils/format-tokens';
import { resolveNumberFormat } from '../utils/number-format';

import { getPromptCache } from './shared/prompt-cache';
import { formatRawOrLabeledValue } from './shared/raw-or-labeled';

const LABEL = 'If cold: ';

// Claude Code leaves the figure null right after a compaction or a clearing of
// old tool results, until the next request records the conversation's new size
export class CacheIfColdWidget implements Widget {
getDefaultColor(): string { return 'brightCyan'; }
getDescription(): string { return 'Shows the tokens the next request re-caches if the prompt cache has gone cold by then'; }
getDisplayName(): string { return 'Cache If Cold'; }
getCategory(): string { return 'Cache'; }
getLabelPrefix(): string { return LABEL; }
getEditorDisplay(item: WidgetItem): WidgetEditorDisplay {
return { displayText: this.getDisplayName() };
}

render(item: WidgetItem, context: RenderContext, settings: Settings): string | null {
const tokens = getPromptCache(context)?.recache_tokens_if_cold;
if (typeof tokens !== 'number') {
return null;
}

return formatRawOrLabeledValue(item, LABEL, formatTokens(tokens, resolveNumberFormat('token', item, settings)));
}

supportsRawValue(): boolean { return true; }
supportsColors(item: WidgetItem): boolean { return true; }
supportsNumberFormat(): boolean { return true; }
}
53 changes: 53 additions & 0 deletions src/widgets/CacheMissTokens.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import type { RenderContext } from '../types/RenderContext';
import type { Settings } from '../types/Settings';
import type {
HideableState,
Widget,
WidgetEditorDisplay,
WidgetItem
} from '../types/Widget';
import { formatTokens } from '../utils/format-tokens';
import { resolveNumberFormat } from '../utils/number-format';

import { isHidden } from './shared/hideable';
import {
NO_MISSES_HIDEABLE_STATE,
getPromptCache,
hasNoMisses
} from './shared/prompt-cache';
import { formatRawOrLabeledValue } from './shared/raw-or-labeled';

const LABEL = 'Miss recache: ';

export class CacheMissTokensWidget implements Widget {
getDefaultColor(): string { return 'yellow'; }
getDescription(): string { return 'Shows the tokens this session\'s prompt cache misses wrote back to the cache'; }
getDisplayName(): string { return 'Cache Miss Tokens'; }
getCategory(): string { return 'Cache'; }
getLabelPrefix(): string { return LABEL; }
getEditorDisplay(item: WidgetItem): WidgetEditorDisplay {
return { displayText: this.getDisplayName() };
}

getHideableStates(): HideableState[] {
return [NO_MISSES_HIDEABLE_STATE];
}

render(item: WidgetItem, context: RenderContext, settings: Settings): string | null {
const cache = getPromptCache(context);
if (typeof cache?.miss_recache_tokens !== 'number') {
return null;
}

if (hasNoMisses(cache) && isHidden(item, NO_MISSES_HIDEABLE_STATE.key)) {
return null;
}

const value = formatTokens(cache.miss_recache_tokens, resolveNumberFormat('token', item, settings));
return formatRawOrLabeledValue(item, LABEL, value);
}

supportsRawValue(): boolean { return true; }
supportsColors(item: WidgetItem): boolean { return true; }
supportsNumberFormat(): boolean { return true; }
}
50 changes: 50 additions & 0 deletions src/widgets/CacheMisses.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import type { RenderContext } from '../types/RenderContext';
import type { Settings } from '../types/Settings';
import type {
HideableState,
Widget,
WidgetEditorDisplay,
WidgetItem
} from '../types/Widget';

import { isHidden } from './shared/hideable';
import {
NO_MISSES_HIDEABLE_STATE,
getPromptCache,
hasNoMisses
} from './shared/prompt-cache';
import { formatRawOrLabeledValue } from './shared/raw-or-labeled';

const LABEL = 'Misses: ';

export class CacheMissesWidget implements Widget {
getDefaultColor(): string { return 'yellow'; }
getDescription(): string { return 'Shows prompt cache misses out of the session\'s requests, as Claude Code reports them'; }
getDisplayName(): string { return 'Cache Misses'; }
getCategory(): string { return 'Cache'; }
getLabelPrefix(): string { return LABEL; }
getEditorDisplay(item: WidgetItem): WidgetEditorDisplay {
return { displayText: this.getDisplayName() };
}

getHideableStates(): HideableState[] {
return [NO_MISSES_HIDEABLE_STATE];
}

render(item: WidgetItem, context: RenderContext, settings: Settings): string | null {
const cache = getPromptCache(context);
if (typeof cache?.misses !== 'number') {
return null;
}

if (hasNoMisses(cache) && isHidden(item, NO_MISSES_HIDEABLE_STATE.key)) {
return null;
}

const value = typeof cache.requests === 'number' ? `${cache.misses}/${cache.requests}` : `${cache.misses}`;
return formatRawOrLabeledValue(item, LABEL, value);
}

supportsRawValue(): boolean { return true; }
supportsColors(item: WidgetItem): boolean { return true; }
}
Loading
Loading