Skip to content

Commit 509f361

Browse files
ItsLucasclaude
andcommitted
feat: add configurable context usage thresholds for statusline
- Move calculateContextTokens test to end of file - Add Zod schemas for transcript usage validation (transcriptUsageSchema, transcriptMessageSchema) - Make CONTEXT_USAGE_THRESHOLDS configurable via environment variables: - CCUSAGE_CONTEXT_LOW_THRESHOLD (default: 50) - CCUSAGE_CONTEXT_MEDIUM_THRESHOLD (default: 80) - Update statusline documentation with new environment variables and context usage display 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent 3a04ed1 commit 509f361

4 files changed

Lines changed: 129 additions & 57 deletions

File tree

‎docs/guide/statusline.md‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ If you need the latest pricing data from LiteLLM API, you can explicitly enable
4949
The statusline displays a compact, single-line summary:
5050

5151
```
52-
🤖 Opus | 💰 $0.23 session / $1.23 today / $0.45 block (2h 45m left) | 🔥 $0.12/hr
52+
🤖 Opus | 💰 $0.23 session / $1.23 today / $0.45 block (2h 45m left) | 🔥 $0.12/hr | 🧠 25,000 (12%)
5353
```
5454

5555
### Components Explained
@@ -62,6 +62,10 @@ The statusline displays a compact, single-line summary:
6262
- Green text: Normal (< 2,000 tokens/min)
6363
- Yellow text: Moderate (2,000-5,000 tokens/min)
6464
- Red text: High (> 5,000 tokens/min)
65+
- **Context Usage** (`🧠 25,000 (12%)`): Shows input tokens with percentage of context limit:
66+
- Green text: Low usage (< 50% by default)
67+
- Yellow text: Medium usage (50-80% by default)
68+
- Red text: High usage (> 80% by default)
6569

6670
When no active block exists:
6771
```
@@ -87,6 +91,26 @@ The statusline command:
8791
- Additional metrics display options
8892
- Session-specific cost tracking
8993

94+
## Configuration
95+
96+
### Environment Variables
97+
98+
You can customize the context usage color thresholds using environment variables:
99+
100+
- `CCUSAGE_CONTEXT_LOW_THRESHOLD` - Percentage below which context usage is shown in green (default: 50)
101+
- `CCUSAGE_CONTEXT_MEDIUM_THRESHOLD` - Percentage below which context usage is shown in yellow (default: 80)
102+
103+
For example:
104+
```bash
105+
export CCUSAGE_CONTEXT_LOW_THRESHOLD=60
106+
export CCUSAGE_CONTEXT_MEDIUM_THRESHOLD=90
107+
```
108+
109+
With these settings:
110+
- Green: < 60%
111+
- Yellow: 60-90%
112+
- Red: > 90%
113+
90114
## Troubleshooting
91115

92116
### No Output Displayed

‎src/_consts.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,12 +149,22 @@ export const CONTEXT_LIMIT = 200_000;
149149
/**
150150
* Context usage percentage thresholds for color coding
151151
*/
152-
export const CONTEXT_USAGE_THRESHOLDS = {
152+
export const DEFAULT_CONTEXT_USAGE_THRESHOLDS = {
153153
LOW: 50, // Below 50% - green
154154
MEDIUM: 80, // 50-80% - yellow
155155
// Above 80% - red
156156
} as const;
157157

158+
/**
159+
* Environment variable name for configuring context usage low threshold
160+
*/
161+
export const CONTEXT_LOW_THRESHOLD_ENV = 'CCUSAGE_CONTEXT_LOW_THRESHOLD';
162+
163+
/**
164+
* Environment variable name for configuring context usage medium threshold
165+
*/
166+
export const CONTEXT_MEDIUM_THRESHOLD_ENV = 'CCUSAGE_CONTEXT_MEDIUM_THRESHOLD';
167+
158168
/**
159169
* Days of the week for weekly aggregation
160170
*/

‎src/commands/statusline.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,12 @@ import process from 'node:process';
22
import getStdin from 'get-stdin';
33
import { define } from 'gunshi';
44
import pc from 'picocolors';
5-
import { CONTEXT_USAGE_THRESHOLDS } from '../_consts.ts';
65
import { calculateBurnRate } from '../_session-blocks.ts';
76
import { sharedArgs } from '../_shared-args.ts';
87
import { statuslineHookJsonSchema } from '../_types.ts';
98
import { formatCurrency } from '../_utils.ts';
109
import { calculateTotals } from '../calculate-cost.ts';
11-
import { calculateContextTokens, getClaudePaths, loadDailyUsageData, loadSessionBlockData, loadSessionUsageById } from '../data-loader.ts';
10+
import { calculateContextTokens, getClaudePaths, getContextUsageThresholds, loadDailyUsageData, loadSessionBlockData, loadSessionUsageById } from '../data-loader.ts';
1211
import { log, logger } from '../logger.ts';
1312

1413
/**
@@ -167,9 +166,10 @@ export const statuslineCommand = define({
167166
try {
168167
const contextData = await calculateContextTokens(hookData.transcript_path);
169168
if (contextData != null) {
170-
// Format context percentage with color coding using constants
169+
// Format context percentage with color coding using configurable thresholds
171170
const p = contextData.percentage;
172-
const color = p < CONTEXT_USAGE_THRESHOLDS.LOW ? pc.green : p < CONTEXT_USAGE_THRESHOLDS.MEDIUM ? pc.yellow : pc.red;
171+
const thresholds = getContextUsageThresholds();
172+
const color = p < thresholds.LOW ? pc.green : p < thresholds.MEDIUM ? pc.yellow : pc.red;
173173
const coloredPercentage = color(`${p}%`);
174174

175175
// Format token count with thousand separators

‎src/data-loader.ts‎

Lines changed: 89 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ import type {
1717
CostMode,
1818
ModelName,
1919
SortOrder,
20-
TranscriptMessage,
2120
Version,
2221
WeeklyDate,
2322
} from './_types.ts';
@@ -33,7 +32,7 @@ import { createFixture } from 'fs-fixture';
3332
import { isDirectorySync } from 'path-type';
3433
import { glob } from 'tinyglobby';
3534
import { z } from 'zod';
36-
import { CLAUDE_CONFIG_DIR_ENV, CLAUDE_PROJECTS_DIR_NAME, CONTEXT_LIMIT, DEFAULT_CLAUDE_CODE_PATH, DEFAULT_CLAUDE_CONFIG_PATH, USAGE_DATA_GLOB_PATTERN, USER_HOME_DIR } from './_consts.ts';
35+
import { CLAUDE_CONFIG_DIR_ENV, CLAUDE_PROJECTS_DIR_NAME, CONTEXT_LIMIT, CONTEXT_LOW_THRESHOLD_ENV, CONTEXT_MEDIUM_THRESHOLD_ENV, DEFAULT_CLAUDE_CODE_PATH, DEFAULT_CLAUDE_CONFIG_PATH, DEFAULT_CONTEXT_USAGE_THRESHOLDS, USAGE_DATA_GLOB_PATTERN, USER_HOME_DIR } from './_consts.ts';
3736
import {
3837
identifySessionBlocks,
3938
} from './_session-blocks.ts';
@@ -136,6 +135,22 @@ export function getClaudePaths(): string[] {
136135
return paths;
137136
}
138137

138+
/**
139+
* Get context usage percentage thresholds for color coding
140+
* Can be configured via environment variables or uses defaults
141+
* @returns Context usage thresholds with LOW and MEDIUM percentages
142+
*/
143+
export function getContextUsageThresholds(): { readonly LOW: number; readonly MEDIUM: number } {
144+
// Check environment variables with fallback to defaults
145+
const lowThreshold = process.env[CONTEXT_LOW_THRESHOLD_ENV];
146+
const mediumThreshold = process.env[CONTEXT_MEDIUM_THRESHOLD_ENV];
147+
148+
return {
149+
LOW: lowThreshold != null ? Number.parseInt(lowThreshold, 10) : DEFAULT_CONTEXT_USAGE_THRESHOLDS.LOW,
150+
MEDIUM: mediumThreshold != null ? Number.parseInt(mediumThreshold, 10) : DEFAULT_CONTEXT_USAGE_THRESHOLDS.MEDIUM,
151+
} as const;
152+
}
153+
139154
/**
140155
* Extract project name from Claude JSONL file path
141156
* @param jsonlPath - Absolute path to JSONL file
@@ -181,6 +196,26 @@ export const usageDataSchema = z.object({
181196
isApiErrorMessage: z.boolean().optional(),
182197
});
183198

199+
/**
200+
* Zod schema for transcript usage data from Claude messages
201+
*/
202+
export const transcriptUsageSchema = z.object({
203+
input_tokens: z.number().optional(),
204+
cache_creation_input_tokens: z.number().optional(),
205+
cache_read_input_tokens: z.number().optional(),
206+
output_tokens: z.number().optional(),
207+
});
208+
209+
/**
210+
* Zod schema for transcript message data
211+
*/
212+
export const transcriptMessageSchema = z.object({
213+
type: z.string().optional(),
214+
message: z.object({
215+
usage: transcriptUsageSchema.optional(),
216+
}).optional(),
217+
});
218+
184219
/**
185220
* Type definition for Claude usage data entries from JSONL files
186221
*/
@@ -1365,7 +1400,12 @@ export async function calculateContextTokens(transcriptPath: string): Promise<{
13651400
}
13661401

13671402
try {
1368-
const obj = JSON.parse(trimmedLine) as TranscriptMessage;
1403+
const parsed = JSON.parse(trimmedLine) as unknown;
1404+
const result = transcriptMessageSchema.safeParse(parsed);
1405+
if (!result.success) {
1406+
continue; // Skip malformed JSON lines
1407+
}
1408+
const obj = result.data;
13691409

13701410
// Check if this line contains the required token usage fields
13711411
if (obj.type === 'assistant'
@@ -1397,54 +1437,6 @@ export async function calculateContextTokens(transcriptPath: string): Promise<{
13971437
return null;
13981438
}
13991439

1400-
// Test for calculateContextTokens
1401-
if (import.meta.vitest != null) {
1402-
describe('calculateContextTokens', async () => {
1403-
it('returns null when transcript cannot be read', async () => {
1404-
const result = await calculateContextTokens('/nonexistent/path.jsonl');
1405-
expect(result).toBeNull();
1406-
});
1407-
const { createFixture } = await import('fs-fixture');
1408-
it('parses latest assistant line and excludes output tokens', async () => {
1409-
await using fixture = await createFixture({
1410-
'transcript.jsonl': [
1411-
JSON.stringify({ type: 'user', message: {} }),
1412-
JSON.stringify({ type: 'assistant', message: { usage: { input_tokens: 1000, output_tokens: 999 } } }),
1413-
JSON.stringify({ type: 'assistant', message: { usage: { input_tokens: 2000, cache_creation_input_tokens: 100, cache_read_input_tokens: 50 } } }),
1414-
].join('\n'),
1415-
});
1416-
const res = await calculateContextTokens(fixture.getPath('transcript.jsonl'));
1417-
expect(res).not.toBeNull();
1418-
// Should pick the last assistant line and exclude output tokens
1419-
expect(res?.inputTokens).toBe(2000 + 100 + 50);
1420-
expect(res?.percentage).toBeGreaterThan(0);
1421-
});
1422-
1423-
it('handles missing cache fields gracefully', async () => {
1424-
await using fixture = await createFixture({
1425-
'transcript.jsonl': [
1426-
JSON.stringify({ type: 'assistant', message: { usage: { input_tokens: 1000 } } }),
1427-
].join('\n'),
1428-
});
1429-
const res = await calculateContextTokens(fixture.getPath('transcript.jsonl'));
1430-
expect(res).not.toBeNull();
1431-
expect(res?.inputTokens).toBe(1000);
1432-
expect(res?.percentage).toBeGreaterThan(0);
1433-
});
1434-
1435-
it('clamps percentage to 0-100 range', async () => {
1436-
await using fixture = await createFixture({
1437-
'transcript.jsonl': [
1438-
JSON.stringify({ type: 'assistant', message: { usage: { input_tokens: 300_000 } } }),
1439-
].join('\n'),
1440-
});
1441-
const res = await calculateContextTokens(fixture.getPath('transcript.jsonl'));
1442-
expect(res).not.toBeNull();
1443-
expect(res?.percentage).toBe(100); // Should be clamped to 100
1444-
});
1445-
});
1446-
}
1447-
14481440
/**
14491441
* Loads usage data and organizes it into session blocks (typically 5-hour billing periods)
14501442
* Processes all usage data and groups it into time-based blocks for billing analysis
@@ -4681,4 +4673,50 @@ if (import.meta.vitest != null) {
46814673
expect(results.every(r => r.baseDir.includes('path1/projects'))).toBe(true);
46824674
});
46834675
});
4676+
4677+
// Test for calculateContextTokens
4678+
describe('calculateContextTokens', async () => {
4679+
it('returns null when transcript cannot be read', async () => {
4680+
const result = await calculateContextTokens('/nonexistent/path.jsonl');
4681+
expect(result).toBeNull();
4682+
});
4683+
const { createFixture } = await import('fs-fixture');
4684+
it('parses latest assistant line and excludes output tokens', async () => {
4685+
await using fixture = await createFixture({
4686+
'transcript.jsonl': [
4687+
JSON.stringify({ type: 'user', message: {} }),
4688+
JSON.stringify({ type: 'assistant', message: { usage: { input_tokens: 1000, output_tokens: 999 } } }),
4689+
JSON.stringify({ type: 'assistant', message: { usage: { input_tokens: 2000, cache_creation_input_tokens: 100, cache_read_input_tokens: 50 } } }),
4690+
].join('\n'),
4691+
});
4692+
const res = await calculateContextTokens(fixture.getPath('transcript.jsonl'));
4693+
expect(res).not.toBeNull();
4694+
// Should pick the last assistant line and exclude output tokens
4695+
expect(res?.inputTokens).toBe(2000 + 100 + 50);
4696+
expect(res?.percentage).toBeGreaterThan(0);
4697+
});
4698+
4699+
it('handles missing cache fields gracefully', async () => {
4700+
await using fixture = await createFixture({
4701+
'transcript.jsonl': [
4702+
JSON.stringify({ type: 'assistant', message: { usage: { input_tokens: 1000 } } }),
4703+
].join('\n'),
4704+
});
4705+
const res = await calculateContextTokens(fixture.getPath('transcript.jsonl'));
4706+
expect(res).not.toBeNull();
4707+
expect(res?.inputTokens).toBe(1000);
4708+
expect(res?.percentage).toBeGreaterThan(0);
4709+
});
4710+
4711+
it('clamps percentage to 0-100 range', async () => {
4712+
await using fixture = await createFixture({
4713+
'transcript.jsonl': [
4714+
JSON.stringify({ type: 'assistant', message: { usage: { input_tokens: 300_000 } } }),
4715+
].join('\n'),
4716+
});
4717+
const res = await calculateContextTokens(fixture.getPath('transcript.jsonl'));
4718+
expect(res).not.toBeNull();
4719+
expect(res?.percentage).toBe(100); // Should be clamped to 100
4720+
});
4721+
});
46844722
}

0 commit comments

Comments
 (0)