Skip to content

Commit 089a153

Browse files
session window update
1 parent 94bd31e commit 089a153

4 files changed

Lines changed: 116 additions & 71 deletions

File tree

‎src/commands/sessions.ts‎

Lines changed: 43 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ export const sessionsCommand = define({
2222
claudePath: ctx.values.path,
2323
mode: ctx.values.mode,
2424
order: ctx.values.order,
25+
sessionLimit: ctx.values.sessionLimit,
26+
warningThreshold: ctx.values.warningThreshold,
2527
});
2628

2729
if (sessionData.length === 0) {
@@ -42,6 +44,7 @@ export const sessionsCommand = define({
4244
totalSessions: monthStats.totalSessions,
4345
remainingSessions: monthStats.remainingSessions,
4446
utilizationPercent: monthStats.utilizationPercent,
47+
sessionLimit: monthStats.sessionLimit,
4548
totalCost: monthStats.totalCost,
4649
totalTokens: monthStats.totalTokens,
4750
averageCostPerSession: monthStats.averageCostPerSession,
@@ -76,9 +79,9 @@ export const sessionsCommand = define({
7679
? 'yellow'
7780
: 'green';
7881

79-
logger.info(`\n${pc.bold(monthStats.month)} - ${pc[utilizationColor](`${monthStats.totalSessions} sessions used`)} (${pc[utilizationColor](`${monthStats.utilizationPercent.toFixed(1)}%`)} of 50 limit)`);
82+
logger.info(`\n${pc.bold(monthStats.month)} - ${pc[utilizationColor](`${monthStats.totalSessions} sessions used`)} (${pc[utilizationColor](`${monthStats.utilizationPercent.toFixed(1)}%`)} of ${monthStats.sessionLimit} limit)`);
8083

81-
if (monthStats.remainingSessions <= 5 && monthStats.remainingSessions > 0) {
84+
if (monthStats.remainingSessions <= ctx.values.warningThreshold && monthStats.remainingSessions > 0) {
8285
logger.warn(`⚠️ Only ${monthStats.remainingSessions} sessions remaining this month!`);
8386
}
8487
else if (monthStats.remainingSessions === 0) {
@@ -94,24 +97,6 @@ export const sessionsCommand = define({
9497
logger.info(`🕒 Current session: ${pc[timeColor](monthStats.currentSession.timeRemainingFormatted)} remaining`);
9598
}
9699

97-
// Monthly summary table
98-
const summaryTable = new Table({
99-
head: ['Metric', 'Value'],
100-
style: {
101-
head: ['cyan'],
102-
},
103-
colAligns: ['left', 'right'],
104-
});
105-
106-
summaryTable.push(
107-
['Total Cost', formatCurrency(monthStats.totalCost)],
108-
['Total Tokens', formatNumber(monthStats.totalTokens)],
109-
['Avg Cost/Session', formatCurrency(monthStats.averageCostPerSession)],
110-
['Avg Tokens/Session', formatNumber(monthStats.averageTokensPerSession)],
111-
);
112-
113-
log(summaryTable.toString());
114-
115100
// Individual session windows table
116101
if (monthStats.windows.length > 0) {
117102
const windowsTable = new Table({
@@ -122,8 +107,8 @@ export const sessionsCommand = define({
122107
'Convos',
123108
'Input',
124109
'Output',
125-
'Cache C',
126-
'Cache R',
110+
'Cache Create',
111+
'Cache Read',
127112
'Total Tokens',
128113
'Cost (USD)',
129114
],
@@ -156,7 +141,7 @@ export const sessionsCommand = define({
156141
+ window.cacheCreationTokens + window.cacheReadTokens;
157142

158143
windowsTable.push([
159-
startTime.toLocaleString().substring(0, 16), // Remove seconds
144+
startTime.toISOString().substring(0, 10), // YYYY-MM-DD format like daily
160145
durationStr,
161146
formatNumber(window.messageCount),
162147
formatNumber(window.conversationCount),
@@ -169,6 +154,41 @@ export const sessionsCommand = define({
169154
]);
170155
}
171156

157+
// Add separator and totals row (like daily command)
158+
const monthTotalSessions = monthStats.windows.length;
159+
const monthTotalCost = monthStats.totalCost;
160+
const monthTotalTokens = monthStats.totalTokens;
161+
const monthTotalInput = monthStats.windows.reduce((sum, w) => sum + w.inputTokens, 0);
162+
const monthTotalOutput = monthStats.windows.reduce((sum, w) => sum + w.outputTokens, 0);
163+
const monthTotalCacheCreate = monthStats.windows.reduce((sum, w) => sum + w.cacheCreationTokens, 0);
164+
const monthTotalCacheRead = monthStats.windows.reduce((sum, w) => sum + w.cacheReadTokens, 0);
165+
166+
windowsTable.push([
167+
'─'.repeat(10),
168+
'─'.repeat(8),
169+
'─'.repeat(8),
170+
'─'.repeat(6),
171+
'─'.repeat(7),
172+
'─'.repeat(7),
173+
'─'.repeat(12),
174+
'─'.repeat(11),
175+
'─'.repeat(12),
176+
'─'.repeat(10),
177+
]);
178+
179+
windowsTable.push([
180+
pc.yellow('Total'),
181+
pc.yellow(`${monthTotalSessions} windows`),
182+
pc.yellow(''),
183+
pc.yellow(''),
184+
pc.yellow(formatNumber(monthTotalInput)),
185+
pc.yellow(formatNumber(monthTotalOutput)),
186+
pc.yellow(formatNumber(monthTotalCacheCreate)),
187+
pc.yellow(formatNumber(monthTotalCacheRead)),
188+
pc.yellow(formatNumber(monthTotalTokens)),
189+
pc.yellow(formatCurrency(monthTotalCost)),
190+
]);
191+
172192
log(windowsTable.toString());
173193
}
174194

‎src/data-loader.ts‎

Lines changed: 62 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
1-
import type { CostMode, CurrentSessionInfo, SessionWindow, SessionWindowStats, SortOrder } from './types.internal.ts';
1+
import type { CostMode, SortOrder } from './types.internal.ts';
22
import { readFile } from 'node:fs/promises';
33
import { homedir } from 'node:os';
44
import path from 'node:path';
5-
import { unreachable } from '@core/errorutil';
5+
6+
function unreachable(x: never): never {
7+
throw new Error(`Unreachable case: ${String(x)}`);
8+
}
9+
610
import { sort } from 'fast-sort';
711
import { glob } from 'tinyglobby';
812
import * as v from 'valibot';
@@ -15,6 +19,50 @@ export function getDefaultClaudePath(): string {
1519
return path.join(homedir(), '.claude');
1620
}
1721

22+
const SessionWindowSchema = v.object({
23+
windowId: v.string(), // Format: YYYY-MM-DD-HH (start of 5-hour window)
24+
startTime: v.string(), // ISO timestamp of first message in window
25+
endTime: v.string(), // ISO timestamp of last message in window
26+
inputTokens: v.number(),
27+
outputTokens: v.number(),
28+
cacheCreationTokens: v.number(),
29+
cacheReadTokens: v.number(),
30+
totalCost: v.number(),
31+
messageCount: v.number(), // Number of messages in this window
32+
conversationCount: v.number(), // Number of unique conversations in this window
33+
});
34+
35+
type SessionWindow = v.InferOutput<typeof SessionWindowSchema>;
36+
37+
const CurrentSessionInfoSchema = v.object({
38+
hasActiveSession: v.boolean(),
39+
timeRemainingMs: v.number(),
40+
timeRemainingFormatted: v.string(),
41+
activeWindow: v.optional(SessionWindowSchema),
42+
});
43+
44+
type CurrentSessionInfo = v.InferOutput<typeof CurrentSessionInfoSchema>;
45+
46+
// eslint-disable-next-line ts/no-unused-vars
47+
const _SessionWindowStatsSchema = v.object({
48+
month: v.pipe(
49+
v.string(),
50+
v.regex(/^\d{4}-\d{2}$/), // YYYY-MM format
51+
),
52+
totalSessions: v.number(), // Total number of 5-hour windows with activity
53+
remainingSessions: v.number(), // sessionLimit - totalSessions
54+
utilizationPercent: v.number(), // (totalSessions / sessionLimit) * 100
55+
sessionLimit: v.number(), // Plan-specific session limit (50 for Max plan, etc.)
56+
totalCost: v.number(),
57+
totalTokens: v.number(),
58+
averageCostPerSession: v.number(),
59+
averageTokensPerSession: v.number(),
60+
windows: v.array(SessionWindowSchema),
61+
currentSession: v.optional(CurrentSessionInfoSchema),
62+
});
63+
64+
export type SessionWindowStats = v.InferOutput<typeof _SessionWindowStatsSchema>;
65+
1866
export const UsageDataSchema = v.object({
1967
timestamp: v.string(),
2068
version: v.optional(v.string()), // Claude Code version
@@ -125,6 +173,8 @@ export type LoadOptions = {
125173
claudePath?: string; // Custom path to Claude data directory
126174
mode?: CostMode; // Cost calculation mode
127175
order?: SortOrder; // Sort order for dates
176+
sessionLimit?: number; // Monthly session limit
177+
warningThreshold?: number; // Warning threshold for remaining sessions
128178
} & DateFilter;
129179

130180
export async function loadDailyUsageData(
@@ -636,7 +686,12 @@ export async function loadSessionWindowData(
636686
let newWindowStart = entry.timestamp;
637687
let newWindowId = getSessionWindowId(entry.data.timestamp);
638688

639-
// Ensure we don't overlap with existing windows
689+
// Ensure we don't overlap with existing windows. If a window already exists
690+
// for the calculated time slot, shift to the next 5-hour window until we
691+
// find an empty slot. This handles edge cases where multiple conversation
692+
// windows might start very close in time, ensuring each gets its own window ID.
693+
// Note: The resulting windowId might not directly correspond to the message's
694+
// actual timestamp, but this maintains unique window identification.
640695
while (sessionWindows.has(newWindowId)) {
641696
newWindowStart = new Date(newWindowStart.getTime() + 5 * 60 * 60 * 1000);
642697
newWindowId = getSessionWindowId(newWindowStart.toISOString());
@@ -703,8 +758,9 @@ export async function loadSessionWindowData(
703758
}
704759

705760
const totalSessions = windows.length;
706-
const remainingSessions = Math.max(0, 50 - totalSessions);
707-
const utilizationPercent = (totalSessions / 50) * 100;
761+
const sessionLimit = options?.sessionLimit ?? 50;
762+
const remainingSessions = Math.max(0, sessionLimit - totalSessions);
763+
const utilizationPercent = (totalSessions / sessionLimit) * 100;
708764

709765
const totals = windows.reduce((acc, window) => ({
710766
cost: acc.cost + window.totalCost,
@@ -719,6 +775,7 @@ export async function loadSessionWindowData(
719775
totalSessions,
720776
remainingSessions,
721777
utilizationPercent,
778+
sessionLimit,
722779
totalCost: totals.cost,
723780
totalTokens: totals.tokens,
724781
averageCostPerSession: totalSessions > 0 ? totals.cost / totalSessions : 0,

‎src/shared-args.internal.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,19 @@ export const sharedArgs = {
6161
type: 'enum',
6262
short: 'o',
6363
description: 'Sort order: desc (newest first) or asc (oldest first)',
64-
default: 'asc' as const satisfies SortOrder,
64+
default: 'desc' as const satisfies SortOrder,
6565
choices: SortOrders,
6666
},
67+
sessionLimit: {
68+
type: 'number',
69+
description: 'Monthly session limit (default: 50 for Max plan)',
70+
default: 50,
71+
},
72+
warningThreshold: {
73+
type: 'number',
74+
description: 'Warning threshold for remaining sessions (default: 5)',
75+
default: 5,
76+
},
6777
} as const satisfies Args;
6878

6979
export const sharedCommandConfig = {

‎src/types.internal.ts‎

Lines changed: 0 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -11,45 +11,3 @@ export type CostMode = TupleToUnion<typeof CostModes>;
1111

1212
export const SortOrders = ['desc', 'asc'] as const;
1313
export type SortOrder = TupleToUnion<typeof SortOrders>;
14-
15-
export const SessionWindowSchema = v.object({
16-
windowId: v.string(), // Format: YYYY-MM-DD-HH (start of 5-hour window)
17-
startTime: v.string(), // ISO timestamp of first message in window
18-
endTime: v.string(), // ISO timestamp of last message in window
19-
inputTokens: v.number(),
20-
outputTokens: v.number(),
21-
cacheCreationTokens: v.number(),
22-
cacheReadTokens: v.number(),
23-
totalCost: v.number(),
24-
messageCount: v.number(), // Number of messages in this window
25-
conversationCount: v.number(), // Number of unique conversations in this window
26-
});
27-
28-
export type SessionWindow = v.InferOutput<typeof SessionWindowSchema>;
29-
30-
export const CurrentSessionInfoSchema = v.object({
31-
hasActiveSession: v.boolean(),
32-
timeRemainingMs: v.number(),
33-
timeRemainingFormatted: v.string(),
34-
activeWindow: v.optional(SessionWindowSchema),
35-
});
36-
37-
export type CurrentSessionInfo = v.InferOutput<typeof CurrentSessionInfoSchema>;
38-
39-
export const SessionWindowStatsSchema = v.object({
40-
month: v.pipe(
41-
v.string(),
42-
v.regex(/^\d{4}-\d{2}$/), // YYYY-MM format
43-
),
44-
totalSessions: v.number(), // Total number of 5-hour windows with activity
45-
remainingSessions: v.number(), // 50 - totalSessions (Max plan limit)
46-
utilizationPercent: v.number(), // (totalSessions / 50) * 100
47-
totalCost: v.number(),
48-
totalTokens: v.number(),
49-
averageCostPerSession: v.number(),
50-
averageTokensPerSession: v.number(),
51-
windows: v.array(SessionWindowSchema),
52-
currentSession: v.optional(CurrentSessionInfoSchema),
53-
});
54-
55-
export type SessionWindowStats = v.InferOutput<typeof SessionWindowStatsSchema>;

0 commit comments

Comments
 (0)