Skip to content

Commit 88e8cde

Browse files
feat: extract session names from sessionId for better UI display (JeongJaeSoon#15)
Co-authored-by: jason <[email protected]> Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
1 parent 0b34f52 commit 88e8cde

File tree

3 files changed

+48
-28
lines changed

3 files changed

+48
-28
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "ccusage-widget",
3-
"version": "1.1.2",
3+
"version": "1.2.0",
44
"description": "A beautiful macOS desktop widget that displays your Claude Code usage statistics in real-time",
55
"main": "dist/main.js",
66
"bin": {

src/main.ts

Lines changed: 37 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,30 @@ import { promisify } from 'util';
55

66
const execAsync = promisify(exec);
77

8+
// Helper function to extract session name from sessionId
9+
function extractSessionNameFromId(sessionId: string): string {
10+
if (!sessionId) return 'session';
11+
12+
// Match pattern: -Users-${whoami}-workspace-${sessionType}-${sessionName}
13+
// Extract the session name (the part after the second dash after workspace)
14+
const match = sessionId.match(/-workspace-[^-]+-([^-]+)/);
15+
if (match && match[1]) {
16+
return match[1];
17+
}
18+
19+
// If that doesn't work, try to get anything after the last dash
20+
const parts = sessionId.split('-');
21+
if (parts.length > 0) {
22+
const lastPart = parts[parts.length - 1];
23+
if (lastPart && lastPart !== 'workspace') {
24+
return lastPart;
25+
}
26+
}
27+
28+
// Fallback to 'session' if pattern doesn't match
29+
return 'session';
30+
}
31+
832
let mainWindow: BrowserWindow | null = null;
933
let tray: Tray | null = null;
1034
let isQuitting = false;
@@ -84,9 +108,6 @@ function createWindow() {
84108
? path.join(__dirname, '..', 'src', 'index.html')
85109
: path.join(__dirname, 'index.html');
86110

87-
console.log('Loading index.html from:', indexPath);
88-
console.log('__dirname:', __dirname);
89-
console.log('isDev:', isDev);
90111

91112
mainWindow.loadFile(indexPath);
92113

@@ -249,7 +270,6 @@ app.on('before-quit', () => {
249270
ipcMain.handle('get-usage-data', async () => {
250271
try {
251272
// Execute ccusage commands to get data
252-
console.log('Executing ccusage commands...');
253273
// Try different ways to execute ccusage
254274
let dailyResult, monthlyResult, sessionResult, blocksResult;
255275

@@ -262,7 +282,7 @@ ipcMain.handle('get-usage-data', async () => {
262282
execAsync('npx ccusage blocks --json')
263283
]);
264284
} catch (error) {
265-
console.error('Failed with npx, trying direct ccusage:', error);
285+
// Try with direct ccusage command
266286
// Try with direct ccusage command
267287
try {
268288
[dailyResult, monthlyResult, sessionResult, blocksResult] = await Promise.all([
@@ -272,7 +292,7 @@ ipcMain.handle('get-usage-data', async () => {
272292
execAsync('ccusage blocks --json')
273293
]);
274294
} catch (error2) {
275-
console.error('Failed with direct ccusage, trying node_modules:', error2);
295+
// Try with local node_modules
276296
// Try with local node_modules
277297
const ccusagePath = path.join(__dirname, '..', 'node_modules', '.bin', 'ccusage');
278298
[dailyResult, monthlyResult, sessionResult, blocksResult] = await Promise.all([
@@ -284,10 +304,6 @@ ipcMain.handle('get-usage-data', async () => {
284304
}
285305
}
286306

287-
console.log('Daily result:', dailyResult.stdout);
288-
console.log('Monthly result:', monthlyResult.stdout);
289-
console.log('Session result:', sessionResult.stdout);
290-
console.log('Blocks result:', blocksResult.stdout);
291307

292308
let dailyData, monthlyData, sessionData, blocksData;
293309

@@ -297,10 +313,6 @@ ipcMain.handle('get-usage-data', async () => {
297313
const sessionParsed = JSON.parse(sessionResult.stdout || '{}');
298314
const blocksParsed = JSON.parse(blocksResult.stdout || '{}');
299315

300-
console.log('Parsed daily data structure:', Object.keys(dailyParsed));
301-
console.log('Parsed monthly data structure:', Object.keys(monthlyParsed));
302-
console.log('Parsed session data structure:', Object.keys(sessionParsed));
303-
console.log('Parsed blocks data structure:', Object.keys(blocksParsed));
304316

305317
// Adjust to actual ccusage output structure
306318
dailyData = dailyParsed;
@@ -327,38 +339,40 @@ ipcMain.handle('get-usage-data', async () => {
327339
const todayDate = `${year}-${month}-${day}`;
328340

329341
const dailyArray = dailyData.daily || dailyData.data || [];
330-
console.log('Looking for today (local):', todayDate);
331-
console.log('Available dates:', dailyArray.map((d: any) => d.date));
332342

333343
// Find today's data or get the most recent day
334344
let today = dailyArray.find((d: any) => d.date === todayDate);
335345

336346
// If today's data is not found, get the most recent (last item in array)
337347
if (!today && dailyArray.length > 0) {
338348
today = dailyArray[dailyArray.length - 1];
339-
console.log('Today not found, using most recent:', today.date);
340349
}
341350

342-
console.log('Today data:', today);
343351

344352
// Get this month's usage
345353
const thisMonthDate = new Date().toISOString().substring(0, 7); // YYYY-MM format
346354
const monthlyArray = monthlyData.monthly || monthlyData.data || [];
347355
const thisMonth = monthlyArray.find((m: any) => m.month === thisMonthDate) || monthlyArray[0] || null;
348-
console.log('This month data:', thisMonth);
349356

350357
// Get total from summary
351358
const totalDaily = dailyData.totals || dailyData.summary || {};
352-
console.log('Total daily:', totalDaily);
353359

354360
// Get recent sessions
355361
const sessionsArray = sessionData.sessions || sessionData.data || [];
356-
console.log('Sessions array:', sessionsArray);
357362

358363
const recentSessions = sessionsArray.slice(0, 5).map((s: any) => {
359-
console.log('Session item:', s);
364+
365+
// Extract session name from sessionId if available, otherwise use fallback names
366+
let sessionName = s.sessionName || s.session || s.name || 'Unknown Session';
367+
368+
// If we have a sessionId, try to extract the session name from it
369+
if (s.sessionId) {
370+
const extractedName = extractSessionNameFromId(s.sessionId);
371+
sessionName = extractedName;
372+
}
373+
360374
return {
361-
name: s.sessionName || s.session || s.name || 'Unknown Session',
375+
name: sessionName,
362376
tokens: s.totalTokens || 0,
363377
cost: s.totalCost || s.costUSD || s.totalCostUSD || 0,
364378
lastActivity: s.lastActivity || s.lastUpdated || new Date().toISOString()
@@ -367,13 +381,11 @@ ipcMain.handle('get-usage-data', async () => {
367381

368382
// Get blocks data
369383
const blocksArray = Array.isArray(blocksData.blocks) ? blocksData.blocks : [];
370-
console.log('Blocks array:', blocksArray);
371384

372385
// Find current active block
373386
const currentBlock = blocksArray.find((block: any) =>
374387
block && typeof block === 'object' && block.isActive === true
375388
);
376-
console.log('Current active block:', currentBlock);
377389
const result = {
378390
today: today ? {
379391
date: today.date,
@@ -400,7 +412,6 @@ ipcMain.handle('get-usage-data', async () => {
400412
lastUpdated: new Date().toISOString()
401413
};
402414

403-
console.log('Returning result:', result);
404415
return result;
405416
} catch (error) {
406417
console.error('Error loading usage data:', error);

src/renderer.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,16 @@ async function loadUsageData() {
188188
if (session && session.name) {
189189
const sessionEl = document.createElement('div');
190190
sessionEl.className = 'session-item';
191-
const displayName = session.name.replace('Unknown Session', 'Session');
191+
192+
// Format session name for display - capitalize first letter
193+
let displayName = session.name;
194+
if (displayName === 'Unknown Session') {
195+
displayName = 'session';
196+
}
197+
198+
// Capitalize first letter for better display
199+
displayName = displayName.charAt(0).toUpperCase() + displayName.slice(1);
200+
192201
sessionEl.innerHTML = `
193202
<span class="session-name" title="${displayName}">${displayName}</span>
194203
<span class="session-cost">${formatCost(session.cost || 0)}</span>

0 commit comments

Comments
 (0)