Skip to content

Commit fb96122

Browse files
ItsLucasclaude
andcommitted
refactor: address PR #480 reviewer comments for statusline context display
- Move context token calculation logic to data-loader.ts for better organization - Add CONTEXT_LIMIT and CONTEXT_USAGE_THRESHOLDS constants to _consts.ts - Rename totalInputTokens to maxInputTokens for clarity - Refactor color-coding logic to use constants and ternary operators - Improve JSONL parsing based on Python reference implementation - Use Result.try pattern for better error handling - Include all token types (input + cache_creation + cache_read + output) for accuracy 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent 0145b67 commit fb96122

4 files changed

Lines changed: 113 additions & 88 deletions

File tree

‎src/_consts.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,21 @@ export const BURN_RATE_THRESHOLDS = {
140140
MODERATE: 500,
141141
} as const;
142142

143+
/**
144+
* Default Claude 4 context window limit (200,000 tokens)
145+
* Used for calculating context usage percentages in statusline
146+
*/
147+
export const CONTEXT_LIMIT = 200000;
148+
149+
/**
150+
* Context usage percentage thresholds for color coding
151+
*/
152+
export const CONTEXT_USAGE_THRESHOLDS = {
153+
LOW: 50, // Below 50% - green
154+
MEDIUM: 80, // 50-80% - yellow
155+
// Above 80% - red
156+
} as const;
157+
143158
/**
144159
* Days of the week for weekly aggregation
145160
*/

‎src/_types.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,3 +158,21 @@ export const statuslineHookJsonSchema = z.object({
158158
* Type definition for Claude Code statusline hook JSON data
159159
*/
160160
export type StatuslineHookJson = z.infer<typeof statuslineHookJsonSchema>;
161+
162+
/**
163+
* Type definition for transcript usage data from Claude messages
164+
*/
165+
166+
export type TranscriptUsage = {
167+
input_tokens?: number;
168+
cache_creation_input_tokens?: number;
169+
cache_read_input_tokens?: number;
170+
output_tokens?: number;
171+
};
172+
173+
export type TranscriptMessage = {
174+
type?: string;
175+
message?: {
176+
usage?: TranscriptUsage;
177+
};
178+
};

‎src/commands/statusline.ts‎

Lines changed: 9 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
import { readFile } from 'node:fs/promises';
21
import process from 'node:process';
32
import getStdin from 'get-stdin';
43
import { define } from 'gunshi';
54
import pc from 'picocolors';
5+
import { CONTEXT_USAGE_THRESHOLDS } from '../_consts.ts';
66
import { calculateBurnRate } from '../_session-blocks.ts';
77
import { sharedArgs } from '../_shared-args.ts';
88
import { statuslineHookJsonSchema } from '../_types.ts';
99
import { formatCurrency } from '../_utils.ts';
1010
import { calculateTotals } from '../calculate-cost.ts';
11-
import { getClaudePaths, loadDailyUsageData, loadSessionBlockData, loadSessionUsageById } from '../data-loader.ts';
11+
import { calculateContextTokens, getClaudePaths, loadDailyUsageData, loadSessionBlockData, loadSessionUsageById } from '../data-loader.ts';
1212
import { log, logger } from '../logger.ts';
1313

1414
/**
@@ -26,79 +26,6 @@ function formatRemainingTime(remaining: number): string {
2626
return `${remainingMins}m left`;
2727
}
2828

29-
/**
30-
* Interface for transcript structure
31-
*/
32-
type TranscriptUsage = {
33-
input_tokens?: number;
34-
};
35-
36-
type TranscriptMessage = {
37-
usage?: TranscriptUsage;
38-
};
39-
40-
type TranscriptData = {
41-
messages?: TranscriptMessage[];
42-
usage?: TranscriptUsage;
43-
};
44-
45-
/**
46-
* Calculate context tokens from transcript file
47-
* @param transcriptPath - Path to the transcript JSON file
48-
* @returns Object with context tokens info or null if unavailable
49-
*/
50-
async function calculateContextTokens(transcriptPath: string): Promise<{
51-
totalInputTokens: number;
52-
percentage: number;
53-
contextLimit: number;
54-
} | null> {
55-
let transcript: TranscriptData;
56-
try {
57-
const content = await readFile(transcriptPath, 'utf-8');
58-
transcript = JSON.parse(content) as TranscriptData;
59-
}
60-
catch (error) {
61-
logger.debug('Failed to read transcript file:', error);
62-
return null;
63-
}
64-
65-
// Calculate total input tokens from all messages with usage information
66-
let totalInputTokens = 0;
67-
const contextLimit = 200000; // Default Claude 4 context limit
68-
let foundUsage = false;
69-
70-
// Look for usage information in the transcript
71-
if (transcript.messages != null && Array.isArray(transcript.messages)) {
72-
for (const message of transcript.messages) {
73-
if (message.usage?.input_tokens != null) {
74-
totalInputTokens = Math.max(totalInputTokens, message.usage.input_tokens);
75-
foundUsage = true;
76-
}
77-
}
78-
}
79-
80-
// If no usage found in messages, check if there's a direct usage field
81-
if (!foundUsage && transcript.usage?.input_tokens != null) {
82-
totalInputTokens = transcript.usage.input_tokens;
83-
foundUsage = true;
84-
}
85-
86-
// If still no usage found, return null
87-
if (!foundUsage) {
88-
logger.debug('No usage information found in transcript');
89-
return null;
90-
}
91-
92-
// Calculate percentage
93-
const percentage = Math.round((totalInputTokens / contextLimit) * 100);
94-
95-
return {
96-
totalInputTokens,
97-
percentage,
98-
contextLimit,
99-
};
100-
}
101-
10229
export const statuslineCommand = define({
10330
name: 'statusline',
10431
description: 'Display compact status line for Claude Code hooks (Beta)',
@@ -240,20 +167,15 @@ export const statuslineCommand = define({
240167
try {
241168
const contextData = await calculateContextTokens(hookData.transcript_path);
242169
if (contextData != null) {
243-
// Format context percentage with color coding
244-
let coloredPercentage = `${contextData.percentage}%`;
245-
if (contextData.percentage < 50) {
246-
coloredPercentage = pc.green(`${contextData.percentage}%`);
247-
}
248-
else if (contextData.percentage < 80) {
249-
coloredPercentage = pc.yellow(`${contextData.percentage}%`);
250-
}
251-
else {
252-
coloredPercentage = pc.red(`${contextData.percentage}%`);
253-
}
170+
// Format context percentage with color coding using constants
171+
const coloredPercentage = contextData.percentage < CONTEXT_USAGE_THRESHOLDS.LOW
172+
? pc.green(`${contextData.percentage}%`)
173+
: contextData.percentage < CONTEXT_USAGE_THRESHOLDS.MEDIUM
174+
? pc.yellow(`${contextData.percentage}%`)
175+
: pc.red(`${contextData.percentage}%`);
254176

255177
// Format token count with thousand separators
256-
const tokenDisplay = contextData.totalInputTokens.toLocaleString();
178+
const tokenDisplay = contextData.maxInputTokens.toLocaleString();
257179
contextInfo = ` | 🧠 ${tokenDisplay} (${coloredPercentage})`;
258180
}
259181
}

‎src/data-loader.ts‎

Lines changed: 71 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import type {
1717
CostMode,
1818
ModelName,
1919
SortOrder,
20+
TranscriptMessage,
2021
Version,
2122
WeeklyDate,
2223
} from './_types.ts';
@@ -32,7 +33,7 @@ import { createFixture } from 'fs-fixture';
3233
import { isDirectorySync } from 'path-type';
3334
import { glob } from 'tinyglobby';
3435
import { z } from 'zod';
35-
import { CLAUDE_CONFIG_DIR_ENV, CLAUDE_PROJECTS_DIR_NAME, DEFAULT_CLAUDE_CODE_PATH, DEFAULT_CLAUDE_CONFIG_PATH, USAGE_DATA_GLOB_PATTERN, USER_HOME_DIR } from './_consts.ts';
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';
3637
import {
3738
identifySessionBlocks,
3839
} from './_session-blocks.ts';
@@ -1335,6 +1336,75 @@ export async function loadBucketUsageData(
13351336
return sortByDate(buckets, item => item.bucket, options?.order);
13361337
}
13371338

1339+
/**
1340+
* Calculate context tokens from transcript file using improved JSONL parsing
1341+
* Based on the Python reference implementation for better accuracy
1342+
* @param transcriptPath - Path to the transcript JSONL file
1343+
* @returns Object with context tokens info or null if unavailable
1344+
*/
1345+
export async function calculateContextTokens(transcriptPath: string): Promise<{
1346+
maxInputTokens: number;
1347+
percentage: number;
1348+
contextLimit: number;
1349+
} | null> {
1350+
let content: string;
1351+
try {
1352+
content = await readFile(transcriptPath, 'utf-8');
1353+
}
1354+
catch (error) {
1355+
logger.debug('Failed to read transcript file:', error);
1356+
return null;
1357+
}
1358+
1359+
const lines = content.split('\n').reverse(); // Iterate from last line to first line
1360+
1361+
for (const line of lines) {
1362+
const trimmedLine = line.trim();
1363+
if (trimmedLine === '') {
1364+
continue;
1365+
}
1366+
1367+
const parseParser = Result.try({
1368+
try: () => JSON.parse(trimmedLine) as TranscriptMessage,
1369+
catch: () => new Error('Invalid JSON'),
1370+
});
1371+
const parseResult = parseParser();
1372+
if (Result.isFailure(parseResult)) {
1373+
continue; // Skip malformed JSON lines
1374+
}
1375+
1376+
const obj = parseResult.value;
1377+
1378+
// Check if this line contains the required token usage fields
1379+
if (obj.type === 'assistant'
1380+
&& obj.message != null
1381+
&& obj.message.usage != null
1382+
&& obj.message.usage.input_tokens != null
1383+
&& obj.message.usage.cache_creation_input_tokens != null
1384+
&& obj.message.usage.cache_read_input_tokens != null
1385+
&& obj.message.usage.output_tokens != null) {
1386+
const usage = obj.message.usage;
1387+
const maxInputTokens
1388+
= usage.input_tokens!
1389+
+ usage.cache_creation_input_tokens!
1390+
+ usage.cache_read_input_tokens!
1391+
+ usage.output_tokens!;
1392+
1393+
const percentage = Math.round((maxInputTokens / CONTEXT_LIMIT) * 100);
1394+
1395+
return {
1396+
maxInputTokens,
1397+
percentage,
1398+
contextLimit: CONTEXT_LIMIT,
1399+
};
1400+
}
1401+
}
1402+
1403+
// No valid usage information found
1404+
logger.debug('No usage information found in transcript');
1405+
return null;
1406+
}
1407+
13381408
/**
13391409
* Loads usage data and organizes it into session blocks (typically 5-hour billing periods)
13401410
* Processes all usage data and groups it into time-based blocks for billing analysis

0 commit comments

Comments
 (0)