Skip to content

Commit 58d0b07

Browse files
ryoppippia-c-m
andcommitted
feat(blocks): improve live monitoring display with better text measurement
- Replace custom ANSI implementations with ansi-escapes and string-width packages - Fix table layout issues in live monitoring dashboard - Add comprehensive tests for LiveMonitor class with proper fixture setup - Reuse shared types from _types.ts instead of duplicating - Fix readonly assignment error in refresh interval validation - Update README documentation to highlight live monitoring feature Co-authored-by: a-c-m <[email protected]>
1 parent 0cf6cd0 commit 58d0b07

7 files changed

Lines changed: 176 additions & 66 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ This tool helps you understand the value you're getting from your subscription b
4848
- 📅 **Monthly Report**: View token usage and costs aggregated by month
4949
- 💬 **Session Report**: View usage grouped by conversation sessions
5050
- ⏰ **5-Hour Blocks Report**: Track usage within Claude's billing windows with active block monitoring
51+
- 📈 **Live Monitoring**: Real-time dashboard showing active session progress, token burn rate, and cost projections with `blocks --live`
5152
- 🤖 **Model Tracking**: See which Claude models you're using (Opus, Sonnet, etc.)
5253
- 📊 **Model Breakdown**: View per-model cost breakdown with `--breakdown` flag
5354
- 📅 **Date Filtering**: Filter reports by date range using `--since` and `--until`

‎bun.lock‎

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,13 @@
4848
"@core/errorutil": "npm:@jsr/core__errorutil",
4949
"@hono/mcp": "^0.1.0",
5050
"@hono/node-server": "^1.14.4",
51+
"@jsr/std__async": "1",
5152
"@modelcontextprotocol/sdk": "^1.12.3",
5253
"@oxc-project/runtime": "^0.73.2",
5354
"@ryoppippi/eslint-config": "^0.3.7",
5455
"@types/bun": "^1.2.16",
5556
"@typescript/native-preview": "^7.0.0-dev.20250618.1",
57+
"ansi-escapes": "^7.0.0",
5658
"bumpp": "^10.2.0",
5759
"clean-pkg-json": "^1.3.0",
5860
"cli-table3": "^0.6.5",
Lines changed: 88 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,13 @@
88
* Used exclusively by blocks-live.ts for the --live flag functionality.
99
*/
1010

11-
import type { CostMode, SortOrder } from './types.internal.ts';
11+
import type { LoadedUsageEntry, SessionBlock } from './_session-blocks.ts';
12+
import type { CostMode, SortOrder } from './_types.ts';
1213
import { readFile } from 'node:fs/promises';
1314
import path from 'node:path';
1415
import { glob } from 'tinyglobby';
15-
import { CLAUDE_PROJECTS_DIR_NAME, USAGE_DATA_GLOB_PATTERN } from './consts.internal.js';
16+
import { CLAUDE_PROJECTS_DIR_NAME, USAGE_DATA_GLOB_PATTERN } from './_consts.ts';
17+
import { identifySessionBlocks } from './_session-blocks.ts';
1618
import {
1719
calculateCostForEntry,
1820
createUniqueHash,
@@ -21,11 +23,6 @@ import {
2123
usageDataSchema,
2224
} from './data-loader.ts';
2325
import { PricingFetcher } from './pricing-fetcher.ts';
24-
import {
25-
identifySessionBlocks,
26-
type LoadedUsageEntry,
27-
type SessionBlock,
28-
} from './session-blocks.internal.ts';
2926

3027
/**
3128
* Configuration for live monitoring
@@ -172,3 +169,87 @@ export class LiveMonitor implements Disposable {
172169
this.allEntries = [];
173170
}
174171
}
172+
173+
if (import.meta.vitest != null) {
174+
const { describe, it, expect, beforeEach, afterEach } = import.meta.vitest;
175+
176+
describe('LiveMonitor', () => {
177+
let tempDir: string;
178+
let monitor: LiveMonitor;
179+
180+
beforeEach(async () => {
181+
const { createFixture } = await import('fs-fixture');
182+
const now = new Date();
183+
const recentTimestamp = new Date(now.getTime() - 60 * 60 * 1000); // 1 hour ago
184+
185+
const fixture = await createFixture({
186+
'projects/test-project/session1/usage.jsonl': `${JSON.stringify({
187+
timestamp: recentTimestamp.toISOString(),
188+
message: {
189+
model: 'claude-sonnet-4-20250514',
190+
usage: {
191+
input_tokens: 100,
192+
output_tokens: 50,
193+
cache_creation_input_tokens: 0,
194+
cache_read_input_tokens: 0,
195+
},
196+
},
197+
costUSD: 0.01,
198+
version: '1.0.0',
199+
})}\n`,
200+
});
201+
tempDir = fixture.path;
202+
203+
monitor = new LiveMonitor({
204+
claudePath: tempDir,
205+
sessionDurationHours: 5,
206+
mode: 'display',
207+
order: 'desc',
208+
});
209+
});
210+
211+
afterEach(() => {
212+
monitor[Symbol.dispose]();
213+
});
214+
215+
it('should initialize and handle clearing cache', async () => {
216+
// Test initial state by calling getActiveBlock which should work
217+
const initialBlock = await monitor.getActiveBlock();
218+
expect(initialBlock).not.toBeNull();
219+
220+
// Clear cache and test again
221+
monitor.clearCache();
222+
const afterClearBlock = await monitor.getActiveBlock();
223+
expect(afterClearBlock).not.toBeNull();
224+
});
225+
226+
it('should load and process usage data', async () => {
227+
const activeBlock = await monitor.getActiveBlock();
228+
229+
expect(activeBlock).not.toBeNull();
230+
if (activeBlock != null) {
231+
expect(activeBlock.tokenCounts.inputTokens).toBe(100);
232+
expect(activeBlock.tokenCounts.outputTokens).toBe(50);
233+
expect(activeBlock.costUSD).toBe(0.01);
234+
expect(activeBlock.models).toContain('claude-sonnet-4-20250514');
235+
}
236+
});
237+
238+
it('should handle empty directories', async () => {
239+
const { createFixture } = await import('fs-fixture');
240+
const emptyFixture = await createFixture({});
241+
242+
const emptyMonitor = new LiveMonitor({
243+
claudePath: emptyFixture.path,
244+
sessionDurationHours: 5,
245+
mode: 'display',
246+
order: 'desc',
247+
});
248+
249+
const activeBlock = await emptyMonitor.getActiveBlock();
250+
expect(activeBlock).toBeNull();
251+
252+
emptyMonitor[Symbol.dispose]();
253+
});
254+
});
255+
}
Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,25 @@
11
import type { WriteStream } from 'node:tty';
22
import process from 'node:process';
3+
import ansiEscapes from 'ansi-escapes';
4+
import stringWidth from 'string-width';
35

46
/**
57
* Terminal control sequences for live display updates
68
*/
79
export const TERMINAL_CONTROL = {
810
// Cursor control
9-
HIDE_CURSOR: '\u001B[?25l',
10-
SHOW_CURSOR: '\u001B[?25h',
11+
HIDE_CURSOR: ansiEscapes.cursorHide,
12+
SHOW_CURSOR: ansiEscapes.cursorShow,
1113

1214
// Screen control
13-
CLEAR_SCREEN: '\u001B[2J',
14-
CLEAR_LINE: '\u001B[2K',
15-
MOVE_TO_TOP: '\u001B[H',
15+
CLEAR_SCREEN: ansiEscapes.clearScreen,
16+
CLEAR_LINE: ansiEscapes.eraseLine,
17+
MOVE_TO_TOP: ansiEscapes.cursorTo(0, 0),
1618

1719
// Movement
18-
MOVE_UP: (n: number) => `\u001B[${n}A`,
19-
MOVE_DOWN: (n: number) => `\u001B[${n}B`,
20-
MOVE_TO_COLUMN: (n: number) => `\u001B[${n}G`,
20+
MOVE_UP: (n: number) => ansiEscapes.cursorUp(n),
21+
MOVE_DOWN: (n: number) => ansiEscapes.cursorDown(n),
22+
MOVE_TO_COLUMN: (n: number) => ansiEscapes.cursorTo(n - 1, undefined),
2123
} as const;
2224

2325
/**
@@ -235,6 +237,7 @@ export function formatDuration(minutes: number): string {
235237
* Strip ANSI color codes from a string
236238
* @param str - String with potential ANSI codes
237239
* @returns String with ANSI codes removed
240+
* @deprecated Use stringWidth() for measuring display width
238241
*/
239242
export function stripAnsi(str: string): string {
240243
// eslint-disable-next-line no-control-regex
@@ -248,7 +251,7 @@ export function stripAnsi(str: string): string {
248251
* @returns Centered text with padding
249252
*/
250253
export function centerText(text: string, width: number): string {
251-
const textLength = stripAnsi(text).length;
254+
const textLength = stringWidth(text);
252255
if (textLength >= width) {
253256
return text;
254257
}

0 commit comments

Comments
 (0)