From 0653ad62f4471cf523fa64d6b0a1f7e51431f075 Mon Sep 17 00:00:00 2001 From: Martin Wilke Date: Sat, 19 Jul 2025 17:20:05 +0800 Subject: [PATCH 1/2] CLEANUP: Remove unnecessary development files and improve .gitignore MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Remove development markdown files (BUGS.md, PROVE.md, STATUS.md, Task.md) - Remove docs/CostCalculatorService.md (development artifact) - Add .DS_Store to .gitignore to prevent macOS system files - Keep essential files: README.md, LICENSE, CLAUDE.md, INSTALLATION.md, changelog.txt πŸ€– Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- .gitignore | 2 +- BUGS.md | 64 -------- PROVE.md | 114 -------------- STATUS.md | 280 ---------------------------------- Task.md | 139 ----------------- docs/CostCalculatorService.md | 185 ---------------------- 6 files changed, 1 insertion(+), 783 deletions(-) delete mode 100644 BUGS.md delete mode 100644 PROVE.md delete mode 100644 STATUS.md delete mode 100644 Task.md delete mode 100644 docs/CostCalculatorService.md diff --git a/.gitignore b/.gitignore index 5e4a4fc..c2ef837 100644 --- a/.gitignore +++ b/.gitignore @@ -66,4 +66,4 @@ temp/ # Claude Code files .claude/ -CLAUDE.md \ No newline at end of file +CLAUDE.md.DS_Store diff --git a/BUGS.md b/BUGS.md deleted file mode 100644 index fc4441d..0000000 --- a/BUGS.md +++ /dev/null @@ -1,64 +0,0 @@ -In .github/workflows/dependency-update.yml at line 61, the GitHub Action version -for peter-evans/create-pull-request is outdated and unsupported. Update the -version tag from v5 to the latest supported stable version by checking the -official repository or marketplace for the current recommended version and -replace the version string accordingly. - -In .github/workflows/ci.yml at line 181, the GitHub action -softprops/action-gh-release is pinned to an outdated version v1. Update the -version to the latest stable release by changing the version tag from v1 to the -most recent version available on the action's repository to ensure compatibility -with newer GitHub runners. - -In src/main/services/FileSystemPermissionService.ts at the top (lines 1-6) and -also around lines 88-89 and 162-163, replace all instances of require('os') with -an ES module import statement like "import os from 'os';" at the top of the -file. Then update all usages of the os module accordingly to use the imported -"os" object instead of the require call. This will ensure consistent ES module -style imports throughout the file. - -In src/main/services/SettingsService.ts around lines 109 to 113, remove the -unnecessary 'as any' type cast on this.settings.theme in the includes check. -Instead, ensure that this.settings.theme is properly typed or use a type-safe -comparison without casting to maintain TypeScript's type safety. - -In src/main/services/BackupService.ts around lines 326 to 344, the current use -of an async callback inside setInterval can cause overlapping backup executions -and unhandled promise rejections. Replace setInterval with a self-scheduling -pattern using setTimeout that waits for the backup operation to complete before -scheduling the next one. Implement a method that performs the backup inside a -try-catch block, logs errors properly, and then calls itself recursively with -setTimeout to ensure sequential execution without overlap. - -In src/main/services/BackupService.ts at lines 149, 250, 424, and 438, replace -all uses of the deprecated fs.rmdir method with the recursive option by using -fs.rm instead. Update each call from fs.rmdir(path, { recursive: true }) to -fs.rm(path, { recursive: true, force: true }) to ensure proper removal of -directories without deprecation warnings. - -In src/main/services/BackupService.ts at line 91, replace the logical OR -operator (||) with the nullish coalescing operator (??) when assigning the -default value to description. This change ensures that only null or undefined -values trigger the default 'Manual backup', allowing empty strings to be used as -valid descriptions. - -In src/main/services/BackupService.ts at lines 1 to 3, the fs module is imported -twice using different syntaxes. Remove the duplicate import by keeping only one -consistent import statement for fs, preferably the one using 'promises as fs' if -asynchronous file operations are needed, and remove the other import to avoid -redundancy. - -/Users/runner/work/CCTracker/CCTracker/src/main/services/BackupService.ts -Error: 3:1 error 'fs' import is duplicated no-duplicate-imports -Error: 47:3 error Type string trivially inferred from a string literal, remove type annotation @typescript-eslint/no-inferrable-types -Error: 48:3 error Type string trivially inferred from a string literal, remove type annotation @typescript-eslint/no-inferrable-types -Warning: 91:22 warning Unexpected nullable string value in conditional. Please handle the nullish/empty cases explicitly @typescript-eslint/strict-boolean-expressions -Error: 91:42 error Prefer using nullish coalescing operator (`??`) instead of a logical or (`||`), as it is a safer operator @typescript-eslint/prefer-nullish-coalescing -Error: 291:27 error Type number trivially inferred from a number literal, remove type annotation @typescript-eslint/no-inferrable-types -Error: 321:20 error Type number trivially inferred from a number literal, remove type annotation @typescript-eslint/no-inferrable-types -Error: 326:43 error Promise returned in function argument where a void return was expected @typescript-eslint/no-misused-promises -Error: 374:14 error 'error' is defined but never used. Allowed unused caught errors must match /^_/u @typescript-eslint/no-unused-vars -Error: 387:14 error 'error' is defined but never used. Allowed unused caught errors must match /^_/u @typescript-eslint/no-unused-vars -Error: 400:14 error 'error' is defined but never used. Allowed unused caught errors must match /^_/u @typescript-eslint/no-unused-vars - -please run local lint so we can fix the build diff --git a/PROVE.md b/PROVE.md deleted file mode 100644 index c35c846..0000000 --- a/PROVE.md +++ /dev/null @@ -1,114 +0,0 @@ -# PROVE.md - Claude CLI Data Analysis Commands - -This document contains terminal commands to analyze and verify Claude CLI usage data for the CCTracker application. - -## Data Range Analysis - -### Find Earliest Usage Data -```bash -find /Users/miwi/.claude/projects -name "*.jsonl" -print0 | xargs -0 grep '"type":"assistant"' | grep -o '"timestamp":"[^"]*"' | sed 's/"timestamp":"//g' | sed 's/"//g' | sort | head -1 -``` -**Result**: `2025-06-21T04:22:25.407Z` - -### Find Latest Usage Data -```bash -find /Users/miwi/.claude/projects -name "*.jsonl" -print0 | xargs -0 grep '"type":"assistant"' | grep -o '"timestamp":"[^"]*"' | sed 's/"timestamp":"//g' | sed 's/"//g' | sort | tail -1 -``` -**Result**: `2025-06-27T10:04:13.391Z` - -### Calculate Total Tracking Days -```bash -python3 -c " -from datetime import datetime -start = datetime.fromisoformat('2025-06-21T04:22:25.407Z'.replace('Z', '+00:00')) -end = datetime.fromisoformat('2025-06-27T10:04:13.391Z'.replace('Z', '+00:00')) -days = (end - start).days -print(f'Total tracking period: {days} days') -print(f'From: {start.strftime(\"%Y-%m-%d %H:%M:%S UTC\")}') -print(f'To: {end.strftime(\"%Y-%m-%d %H:%M:%S UTC\")}') -" -``` -**Result**: -``` -Total tracking period: 6 days -From: 2025-06-21 04:22:25 UTC -To: 2025-06-27 10:04:13 UTC -``` - -## Usage Statistics - -### Count Total Assistant Messages -```bash -find /Users/miwi/.claude/projects -name "*.jsonl" -print0 | xargs -0 grep -c '"type":"assistant"' -``` - -### Count Files with Usage Data -```bash -find /Users/miwi/.claude/projects -name "*.jsonl" -exec grep -l '"type":"assistant"' {} \; | wc -l -``` - -### List Projects with Usage Data -```bash -find /Users/miwi/.claude/projects -name "*.jsonl" -exec grep -l '"type":"assistant"' {} \; | sed 's|/[^/]*\.jsonl||' | sort -u -``` - -## Data Validation - -### Verify JSONL File Structure -```bash -# Check if files contain valid JSON -find /Users/miwi/.claude/projects -name "*.jsonl" | head -5 | xargs -I {} sh -c 'echo "=== {} ==="; head -2 "{}" | jq . || echo "Invalid JSON"' -``` - -### Check Model Distribution -```bash -find /Users/miwi/.claude/projects -name "*.jsonl" -print0 | xargs -0 grep '"type":"assistant"' | grep -o '"model":"[^"]*"' | sort | uniq -c | sort -nr -``` - -### Find Synthetic/Test Entries -```bash -find /Users/miwi/.claude/projects -name "*.jsonl" -print0 | xargs -0 grep '"model":""' | wc -l -``` - -## Date Range Queries - -### Get Usage Data for Specific Date -```bash -# Example: Get data for June 27, 2025 -find /Users/miwi/.claude/projects -name "*.jsonl" -print0 | xargs -0 grep '"type":"assistant"' | grep '"timestamp":"2025-06-27' | wc -l -``` - -### Get Usage Data for Last N Days -```bash -# Get data from last 3 days -python3 -c " -from datetime import datetime, timedelta -import subprocess -import json - -end_date = datetime.now() -start_date = end_date - timedelta(days=3) -start_str = start_date.strftime('%Y-%m-%d') - -cmd = f'find /Users/miwi/.claude/projects -name \"*.jsonl\" -print0 | xargs -0 grep \"\\\"type\\\":\\\"assistant\\\"\" | grep \"\\\"timestamp\\\":\\\"202[0-9]\" | grep -c \"\\\"timestamp\\\":\\\"[^\\\"]*{start_str}\"' -print(f'Assistant messages in last 3 days: (from {start_str})') -" -``` - -## Summary - -**Current Data Range**: 6 days (June 21 - June 27, 2025) -**Tracking Started**: 2025-06-21T04:22:25.407Z -**Latest Data**: 2025-06-27T10:04:13.391Z - -**Benefits for CCTracker**: -- ALL button can use actual earliest date (June 21) instead of arbitrary 2020-01-01 -- More efficient date filtering with 6 days instead of 5+ years -- Accurate data range representation in UI - -## Notes - -- Commands target `"type":"assistant"` messages as these contain usage/token data -- All timestamps are in UTC format -- JSONL files are located in `/Users/miwi/.claude/projects/` -- Each project has its own subdirectory with session-based JSONL files \ No newline at end of file diff --git a/STATUS.md b/STATUS.md deleted file mode 100644 index e35fdec..0000000 --- a/STATUS.md +++ /dev/null @@ -1,280 +0,0 @@ -# CCTracker Development Status - -**Last Updated**: December 27, 2025 -**Version**: 1.0.1 -**Architecture**: React/Electron Desktop Application -**Translation Status**: βœ… 100% Complete (6 Languages) -**Code Quality**: βœ… 100% Clean (Zero Hardcoded Strings) - ---- - -## 🎯 **Project Overview** - -CCTracker is a comprehensive desktop application for monitoring Claude API usage and costs in real-time. Built with React/Electron, it provides professional analytics, multi-language support, and advanced export capabilities. - ---- - -## βœ… **COMPLETED FEATURES (100%)** - -### **πŸ—οΈ Core Infrastructure** -- βœ… **Project Setup**: Complete package.json with all dependencies -- βœ… **TypeScript Configuration**: Separate configs for main/renderer processes -- βœ… **Webpack Build System**: Production and development builds working -- βœ… **Electron Architecture**: Main process, renderer process, IPC communication -- βœ… **Development Workflow**: `npm run dev` with file watching (no web server) - -### **πŸ”§ Backend Services** -- βœ… **UsageService**: JSONL parsing, cost calculation with 2025 pricing, data persistence -- βœ… **FileMonitorService**: Real-time file system monitoring using chokidar -- βœ… **SettingsService**: Persistent application settings with auto-save -- βœ… **CurrencyService**: Multi-currency support (USD, EUR, GBP, JPY, CNY, MYR) -- βœ… **ExportService**: Data export to CSV, JSON, Excel (TSV), PDF formats -- βœ… **IPC Communication**: All main↔renderer process communication channels - -### **🎨 Frontend & User Interface** -- βœ… **React Application**: Complete component hierarchy -- βœ… **UsageDashboard**: Comprehensive dashboard with metrics and charts -- βœ… **BusinessIntelligenceDashboard**: Advanced analytics dashboard with BI features -- βœ… **Layout System**: Header, Sidebar with navigation, responsive design -- βœ… **Theme System**: Light, Dark, Catppuccin themes with smooth CSS transitions -- βœ… **Context Management**: Settings, Theme, UsageData React contexts -- βœ… **Component Library**: All UI components implemented -- βœ… **Navigation System**: Multi-page routing between Dashboard and Business Intelligence - -### **🌍 Internationalization (100% Complete)** -- βœ… **6 Languages**: English, German, French, Spanish, Japanese, Chinese (Simplified) -- βœ… **220+ Translation Keys**: Complete coverage across all components -- βœ… **Zero Hardcoded Strings**: 100% professional translation implementation -- βœ… **Language Switching**: Header dropdown with native language names -- βœ… **Translation System**: react-i18next with browser detection and localStorage persistence -- βœ… **Complete Coverage**: All UI elements, charts, errors, and BI dashboard translated -- βœ… **Currency Updates Fixed**: Daily currency updates (was hourly) -- βœ… **Time Format Support**: Live 12h/24h switching with proper translations -- βœ… **Theme Translations**: All 4 Catppuccin themes with descriptions in all languages -- βœ… **Professional Quality**: Industry-standard translation architecture - -### **πŸ“Š Data Analytics & Visualization** -- βœ… **Cost Calculation**: Latest Claude API pricing models (2025) -- βœ… **Interactive Charts**: - - Line charts for cost over time - - Bar charts for token usage by model - - Pie charts for cost distribution - - Area charts for trend visualization -- βœ… **Session Analytics**: Grouping and statistics by session -- βœ… **Date Range Filtering**: 7/30/90 day presets + custom date ranges -- βœ… **Real-time Updates**: Live data refresh and file monitoring -- βœ… **Export Functionality**: Multiple format support with configurable options - -### **🧠 Business Intelligence System** -- βœ… **Model Efficiency Analysis**: Cost-per-token rankings and efficiency scoring -- βœ… **Predictive Analytics**: Monthly cost forecasting with confidence levels -- βœ… **Anomaly Detection**: Statistical analysis detecting 1,000+ usage anomalies -- βœ… **Trend Analysis**: Daily, weekly, monthly usage trends with growth rates -- βœ… **Time Pattern Analysis**: Peak usage hours and busiest day identification -- βœ… **Advanced Metrics**: Cost burn rate, session efficiency, model diversity scoring -- βœ… **Business Intelligence Export**: Comprehensive JSON reports with AI recommendations -- βœ… **Usage Optimization**: Real-time insights for cost optimization -- βœ… **Budget Risk Assessment**: Predictive budget overage warnings - -### **πŸ“Š Usage Analytics System** -- βœ… **Project-Level Cost Breakdown**: Complete project analytics with cost, tokens, sessions -- βœ… **Project Comparison Dashboard**: Cross-project analysis and efficiency rankings -- βœ… **Session Drill-down**: Detailed session-level analysis within projects -- βœ… **Interactive Project Cards**: Visual project overview with cost-per-token metrics -- βœ… **Cost Distribution Charts**: Bar charts and responsive visualizations for project analysis -- βœ… **Centralized Cost Calculator**: Unified calculation service ensuring consistent math across all pages -- βœ… **Simplified Analytics UI**: Clean, focused interface matching original Rust implementation -- βœ… **Real-time Project Analytics**: Live data refresh and file monitoring integration - -### **🎯 Advanced Features** -- βœ… **Multi-currency Display**: Real-time currency conversion -- βœ… **Loading States**: Skeleton animations and proper UX patterns -- βœ… **Error Handling**: Comprehensive error management throughout -- βœ… **TypeScript**: Full type safety with proper interfaces -- βœ… **Responsive Design**: Works on desktop, tablet, and mobile screen sizes -- βœ… **Accessibility**: WCAG 2.1 compliant components - -### **βš™οΈ Build & Development** -- βœ… **Build Process**: Both main and renderer processes compile successfully -- βœ… **Development Mode**: Auto-rebuild with file watching -- βœ… **Production Mode**: Optimized builds with minification -- βœ… **Code Quality**: TypeScript compilation with zero errors -- βœ… **Claude CLI Integration**: Real-time data loading from ~/.claude/projects/ -- βœ… **Live Data Processing**: Successfully processing 14,624+ real usage entries -- βœ… **Business Intelligence Engine**: Advanced analytics with sub-3-second report generation - ---- - -## ⚠️ **OUTSTANDING ISSUES** - -### **πŸ§ͺ Testing (Critical)** -- ❌ **Unit Test Fixes**: Test data format mismatches with actual service implementations -- ❌ **Integration Testing**: Limited test coverage for IPC communication -- ❌ **E2E Testing**: No end-to-end testing framework setup -- ❌ **Test Data**: Mock data doesn't match real Claude CLI JSONL format - -### **πŸ“¦ Distribution & Packaging** -- ❌ **App Packaging**: `npm run package` untested for distribution -- ❌ **Code Signing**: Not configured for macOS/Windows distribution -- ❌ **Auto-updater**: No update mechanism implemented -- ❌ **App Icons**: Using default Electron icon -- ❌ **Installer**: No custom installer or setup wizard - -### **πŸ” Claude CLI Integration** -- βœ… **Real Data Testing**: Successfully tested with 14,474+ actual Claude CLI entries -- βœ… **File Path Detection**: Auto-discovery of ~/.claude/projects/ directory implemented -- βœ… **JSONL Format Validation**: Real Claude CLI JSONL format parsing working perfectly -- βœ… **Auto-discovery**: Automatic detection and monitoring of ~/.claude/projects/ directory -- βœ… **Real-time Monitoring**: Live file monitoring with chokidar for new sessions -- βœ… **Data Deduplication**: Prevents duplicate entries when files are modified -- βœ… **Model Support**: Added Claude 4 models (claude-sonnet-4-20250514, claude-opus-4-20250514) - -### **πŸ“ˆ Performance & Scale** -- βœ… **Large Dataset Handling**: Successfully tested with 14,624+ real usage entries -- βœ… **BI Performance**: Business intelligence reports generated in <3 seconds -- ❌ **Memory Management**: No automatic cleanup of old data -- ❌ **Chart Performance**: May need virtualization for very large datasets (50k+) -- ❌ **Background Processing**: All processing happens on main thread - -### **πŸ› οΈ Development Experience** -- ❌ **ESLint Configuration**: Simplified due to ESLint 9 complexity -- ❌ **Pre-commit Hooks**: No code quality gates or formatting enforcement -- ❌ **CI/CD Pipeline**: No automated testing or building -- ❌ **Documentation**: Limited inline code documentation - -### **πŸš€ Production Readiness** -- ❌ **Error Reporting**: No crash reporting or user analytics -- ❌ **Logging System**: Console logs only, no structured file logging -- ❌ **Settings Migration**: No handling of version upgrades -- ❌ **Data Backup**: No automatic backup or restore functionality -- ❌ **Health Monitoring**: No system health checks or diagnostics - ---- - -## πŸš€ **CURRENT WORKING COMMANDS** - -### **Development** -```bash -npm install # Install all dependencies -npm run dev # Start development mode (file watching + Electron) -npm run dev:main # Build main process only (watch mode) -npm run dev:renderer # Build renderer process only (watch mode) -``` - -### **Production** -```bash -npm run build # Build both processes for production -npm run start # Start built Electron application -npm run package # Package for distribution (needs testing) -``` - -### **Code Quality** -```bash -npm run type-check # TypeScript compilation check -npm run lint # Code linting (simplified) -npm test # Jest tests (has failing tests) -``` - ---- - -## 🎯 **PRIORITY ROADMAP** - -### **πŸ”₯ HIGH PRIORITY (Immediate)** -1. **βœ… Test with Real Claude CLI Output** - COMPLETED - - βœ… Successfully loaded 14,474+ real Claude CLI entries - - βœ… Validated parsing and cost calculation accuracy - - βœ… Fixed format compatibility issues and added Claude 4 support - -2. **Fix Unit Test Suite** - - Correct test data format to match service implementations - - Add proper mocking for Electron APIs - - Achieve >80% test coverage - -3. **Distribution Setup** - - Configure electron-builder properly - - Test packaging on macOS, Windows, Linux - - Create installation instructions - -### **⚑ MEDIUM PRIORITY (Next Sprint)** -1. **Performance Optimization** - - Test with large datasets (1000+ entries) - - Implement data pagination or virtualization - - Add background processing for heavy operations - -2. **Enhanced Error Handling** - - Implement structured logging to files - - Add crash reporting and recovery - - Create user-friendly error messages - -3. **Auto-detection Features** - - Automatically find Claude CLI output directory - - Monitor multiple project directories - - Smart file format detection - -### **πŸ’‘ LOW PRIORITY (Future Enhancements)** -1. **Polish & Branding** - - Custom application icons and branding - - Improved onboarding experience - - Advanced analytics and insights - -2. **Advanced Features** - - Data export scheduling - - Usage alerts and notifications - - API usage prediction and budgeting - -3. **Developer Experience** - - Complete ESLint configuration - - CI/CD pipeline setup - - Automated testing and deployment - ---- - -## πŸ“Š **READINESS ASSESSMENT** - -| Component | Status | Completeness | -|-----------|--------|-------------| -| **Core Functionality** | βœ… Working | 100% | -| **User Interface** | βœ… Working | 100% | -| **Backend Services** | βœ… Working | 100% | -| **Build System** | βœ… Working | 100% | -| **Internationalization** | βœ… Working | 100% | -| **Translation Coverage** | βœ… Complete | 100% | -| **Code Quality** | βœ… Clean | 100% | -| **Testing** | ⚠️ Issues | 40% | -| **Distribution** | ❌ Not Ready | 20% | -| **Real-world Testing** | βœ… Working | 100% | -| **Business Intelligence** | βœ… Working | 100% | -| **Production Readiness** | βœ… Ready | 95% | - -**Overall Project Status**: **99% Complete** - Enterprise-ready with complete internationalization and advanced business intelligence - ---- - -## πŸŽ‰ **ACHIEVEMENTS** - -- βœ… **Full-featured Desktop App**: Professional-grade Electron application -- βœ… **Modern Tech Stack**: React 18, TypeScript 5.8, Electron 37 -- βœ… **Comprehensive Analytics**: Real-time cost monitoring with interactive charts -- βœ… **Multi-language Support**: 6 languages with native translations -- βœ… **Theme System**: Beautiful, accessible themes with smooth transitions -- βœ… **Export Capabilities**: Multiple format support for data portability -- βœ… **Real-time Monitoring**: File system watching with automatic updates -- βœ… **Type Safety**: 100% TypeScript coverage with zero compilation errors -- βœ… **Business Intelligence**: Enterprise-grade analytics with predictive insights -- βœ… **Statistical Analysis**: Anomaly detection and trend forecasting capabilities - ---- - -## πŸ”— **NEXT STEPS FOR PRODUCTION** - -1. **βœ… Immediate**: Claude CLI integration completed successfully -2. **Week 1**: Minor UI polish and performance optimization for very large datasets -3. **Week 2**: Configure and test distribution packaging -4. **Week 3**: Performance testing with large datasets -5. **Week 4**: Production deployment and user documentation - ---- - -**Status**: βœ… **Core Development Complete** - Ready for Production Use - -The CCTracker application successfully fulfills its primary objective of providing a comprehensive, real-time Claude API cost monitoring solution with a professional desktop interface. All core features are implemented and functional, with successful real-world testing using 14,624+ actual Claude CLI usage entries. The addition of enterprise-grade business intelligence transforms CCTracker from a simple monitoring tool into a sophisticated analytics platform with predictive capabilities. \ No newline at end of file diff --git a/Task.md b/Task.md deleted file mode 100644 index 313b4fd..0000000 --- a/Task.md +++ /dev/null @@ -1,139 +0,0 @@ -# Task: Bug Fixes - Complete Resolution of 5 Critical Issues - -## Goal -Fix ALL remaining 5 open bugs to achieve 100% completion with no partial fixes or "good enough" solutions. - -## Plan -1. **BUG #2**: Fix encapsulation violation in UsageService tests - βœ… Complete -2. **BUG #3**: Add proper test teardown and expand coverage - βœ… Complete -3. **BUG #8**: Add error handling for cleanup operations - βœ… Complete -4. **BUG #5**: Add comprehensive currency rate validation - βœ… Complete -5. **BUG #20**: Fix unsafe type assertions in ThemeContext - βœ… Complete - -## Completed Fixes - -### 1. **BUG #2**: Private Method Testing Encapsulation Violation βœ… -**Location**: `src/main/services/__tests__/UsageService.test.ts` lines 62-91 -**Issue**: Tests were accessing private method `parseJSONLLine` using unsafe type casting `(usageService as any).parseJSONLLine()` - -**Fix Applied**: -- Made `parseJSONLLine` method public in UsageService class with proper documentation -- Removed all unsafe type casting `(usageService as any)` from tests -- Now tests call `usageService.parseJSONLLine()` directly as a public method -- Maintains proper encapsulation while enabling thorough testing - -**Files Modified**: -- `src/main/services/UsageService.ts` - Changed method visibility from private to public -- `src/main/services/__tests__/UsageService.test.ts` - Removed type casting - -### 2. **BUG #3**: Missing Teardown Logic and Limited Test Coverage βœ… -**Location**: `src/main/services/__tests__/UsageService.test.ts` lines 11-17 -**Issue**: No proper cleanup logic and insufficient test coverage for core methods - -**Fix Applied**: -- Added comprehensive `afterEach()` cleanup with proper mock clearing -- Expanded test coverage with new test suites: - - `getAllUsageEntries` - Tests empty state and sorting functionality - - `getUsageStats` - Tests statistics calculation with zero and normal states - - `addUsageEntry` - Tests successful addition and error handling -- All tests now properly mock file system operations -- Comprehensive error case testing implemented - -**Files Modified**: -- `src/main/services/__tests__/UsageService.test.ts` - Added afterEach cleanup and 7 new test cases - -### 3. **BUG #8**: Missing Error Handling in Cleanup Operation βœ… -**Location**: `src/main/main.ts` lines 99-101 -**Issue**: No error handling around `stopMonitoring()` call in 'before-quit' event - -**Fix Applied**: -- Wrapped `stopMonitoring()` call in comprehensive try-catch block -- Added proper error logging for cleanup failures -- Ensured app can quit cleanly even if monitoring cleanup fails -- Added descriptive comment explaining the behavior - -**Files Modified**: -- `src/main/main.ts` - Added try-catch around stopMonitoring with error handling - -### 4. **BUG #5**: Missing Comprehensive Rate Validation βœ… -**Location**: `src/renderer/hooks/useCurrency.ts` lines 34-49 -**Issue**: `convertFromUSD` missing validation for rate existence and validity - -**Fix Applied**: -- Added comprehensive input validation for USD amount (type, finite, non-null) -- Added rate existence validation (undefined, null checks) -- Added rate validity validation (type checking, finite, positive value) -- Added conversion result validation to prevent invalid outputs -- Graceful fallback to USD for all error cases with proper error logging -- Extensive error messaging for debugging - -**Files Modified**: -- `src/renderer/hooks/useCurrency.ts` - Enhanced convertFromUSD with comprehensive validation - -### 5. **BUG #20**: Unsafe Type Assertions on Theme Values βœ… -**Location**: `src/renderer/contexts/ThemeContext.tsx` lines 34-51 -**Issue**: Unsafe type assertions `settings.theme as keyof typeof COLOR_PALETTES` without validation - -**Fix Applied**: -- Created `validateTheme()` function that safely validates theme values -- Added proper validation checking if theme exists in COLOR_PALETTES -- Added fallback to 'light' theme for invalid theme values -- Removed all unsafe type assertions throughout the component -- Used validated theme consistently in all theme utilities -- Added warning logging for invalid theme values - -**Files Modified**: -- `src/renderer/contexts/ThemeContext.tsx` - Added theme validation function and safe type handling - -## Quality Assurance - -### Test Results βœ… -```bash -βœ“ All 12 UsageService tests passing -βœ“ TypeScript compilation successful (npm run type-check) -βœ“ No type errors or warnings -βœ“ All edge cases properly handled -``` - -### Code Quality Improvements - -#### **Encapsulation & Testing** -- Resolved private method testing through proper public interface -- Comprehensive test coverage for core functionality -- Proper cleanup and teardown procedures - -#### **Error Handling** -- Robust error handling for app lifecycle events -- Comprehensive validation for financial calculations -- Safe type handling for theme management -- Graceful degradation in all error scenarios - -#### **Type Safety** -- Eliminated all unsafe type assertions -- Added proper validation before type operations -- Maintained full TypeScript compliance - -#### **Defensive Programming** -- Input validation for all critical functions -- Fallback mechanisms for all error cases -- Proper error logging for debugging -- Edge case handling throughout - -## Files Modified Summary - -1. **UsageService.ts** - Made parseJSONLLine public for proper testing -2. **UsageService.test.ts** - Fixed encapsulation, added teardown, expanded coverage -3. **main.ts** - Added error handling for cleanup operations -4. **useCurrency.ts** - Added comprehensive rate validation -5. **ThemeContext.tsx** - Replaced unsafe type assertions with validation - -## Result -All 5 critical bugs have been completely resolved with: -- βœ… **100% Bug Resolution** - Every issue addressed completely -- βœ… **No Partial Fixes** - Full implementation for each bug -- βœ… **Enhanced Test Coverage** - Comprehensive testing suite -- βœ… **Improved Error Handling** - Robust error management throughout -- βœ… **Type Safety** - Eliminated all unsafe operations -- βœ… **Production Ready** - All fixes suitable for production deployment - -The codebase now demonstrates enterprise-level code quality with proper error handling, comprehensive testing, and defensive programming practices. \ No newline at end of file diff --git a/docs/CostCalculatorService.md b/docs/CostCalculatorService.md deleted file mode 100644 index 538d77b..0000000 --- a/docs/CostCalculatorService.md +++ /dev/null @@ -1,185 +0,0 @@ -# CostCalculatorService - Centralized Cost Calculation - -## Overview - -The `CostCalculatorService` provides centralized, consistent cost calculations across all CCTracker components. This service eliminates calculation inconsistencies and ensures all pages display the same metrics. - -## Problem Solved - -**Before**: Multiple scattered calculation methods with inconsistent logic: -- Project Analytics: Efficiency score = `(cost/tokens) * 1000000` (cost per million tokens) -- Model Efficiency: Efficiency score = `costPerToken * 1000000 + (1/usageCount) * 0.1` (complex formula) -- UI Components: Expected 0-10 scale efficiency scores but received cost per million tokens - -**After**: Single source of truth with consistent methodology across all components. - -## Key Features - -### 1. **Consistent Efficiency Scoring (0-10 Scale)** -- **0**: Very poor efficiency (high cost per token) -- **3-6**: Average efficiency -- **7-9**: Good efficiency -- **10**: Extremely efficient (very low cost per token) - -```typescript -// Uses baseline Claude 3.5 Sonnet cost as reference -const score = CostCalculatorService.calculateEfficiencyScore(totalCost, totalTokens); -``` - -### 2. **Accurate Cost Calculation** -```typescript -// Validates against Claude API pricing -const cost = CostCalculatorService.calculateCost(model, inputTokens, outputTokens); -``` - -### 3. **Standardized Project Analytics** -```typescript -// Complete project metrics with consistent efficiency scoring -const analytics = CostCalculatorService.calculateProjectAnalytics(projectName, entries); -``` - -### 4. **Unified Trend Analysis** -```typescript -// Consistent trend calculation for all time periods -const trends = CostCalculatorService.calculateUsageTrends(entries, 'daily'); -``` - -## Methods - -### Core Calculations - -#### `calculateCost(model, inputTokens, outputTokens)` -- **Purpose**: Calculate exact cost using Claude API pricing -- **Returns**: Cost in USD -- **Validation**: Includes price validation and error detection - -#### `calculateEfficiencyScore(totalCost, totalTokens)` -- **Purpose**: Convert cost per token to 0-10 efficiency scale -- **Algorithm**: Logarithmic scaling compared to Claude 3.5 Sonnet baseline -- **Returns**: Score from 0 (poor) to 10 (excellent) - -#### `calculateCostTrend(recentCost, previousCost, threshold)` -- **Purpose**: Determine cost trend direction -- **Returns**: 'increasing' | 'decreasing' | 'stable' -- **Threshold**: Default 10% change required for trend detection - -### Advanced Analytics - -#### `calculateProjectAnalytics(projectName, entries)` -- **Purpose**: Complete project metrics calculation -- **Includes**: Cost, tokens, sessions, efficiency, trends, models -- **Returns**: Standardized `ProjectAnalytics` object - -#### `calculateModelEfficiency(entries)` -- **Purpose**: Model performance comparison -- **Includes**: Cost per token, efficiency scoring, usage statistics -- **Returns**: Array sorted by efficiency (best first) - -#### `calculateUsageTrends(entries, granularity)` -- **Purpose**: Time-series trend analysis -- **Granularity**: 'daily' | 'weekly' | 'monthly' -- **Returns**: Trends with growth rates - -### Utility Methods - -#### `validateCostCalculation(model, inputTokens, outputTokens, expectedCost)` -- **Purpose**: Validate cost calculations with detailed breakdown -- **Returns**: Validation result with detailed analysis -- **Use Case**: Debugging cost discrepancies - -## Integration - -### Service Usage -```typescript -import CostCalculatorService from './CostCalculatorService'; - -// In UsageService.ts -const analytics = CostCalculatorService.calculateProjectAnalytics(projectName, entries); -const efficiency = CostCalculatorService.calculateModelEfficiency(allEntries); -const trends = CostCalculatorService.calculateUsageTrends(entries, 'daily'); -``` - -### Deprecated Methods -The following methods in `UsageService` now delegate to `CostCalculatorService`: -- `calculateCost()` β†’ `CostCalculatorService.calculateCost()` -- `generateUsageTrends()` β†’ `CostCalculatorService.calculateUsageTrends()` - -## Benefits - -### βœ… **Consistency** -- All components use identical calculation logic -- UI displays match backend calculations -- Efficiency scores are always on 0-10 scale - -### βœ… **Accuracy** -- Single source of truth for pricing -- Validated calculations with error detection -- Proper handling of edge cases - -### βœ… **Maintainability** -- Centralized logic easier to update -- Single place to fix calculation bugs -- Clear separation of concerns - -### βœ… **Testability** -- Isolated calculation logic -- Comprehensive validation methods -- Easy to unit test - -## Examples - -### Before (Inconsistent) -```typescript -// Project Analytics - Cost per million tokens -const efficiencyScore = totalTokens > 0 ? (totalCost / totalTokens) * 1000000 : 0; - -// Model Efficiency - Complex formula -const efficiencyScore = costPerToken * 1000000 + (1 / usageCount) * 0.1; - -// UI - Expected 0-10 scale but received cost per million -{project.efficiency_score.toFixed(1)}/10 // Shows "1532.4/10" instead of "6.2/10" -``` - -### After (Consistent) -```typescript -// All components use same calculation -const efficiencyScore = CostCalculatorService.calculateEfficiencyScore(totalCost, totalTokens); - -// UI correctly displays 0-10 scale -{project.efficiency_score.toFixed(1)}/10 // Shows "7.3/10" correctly -``` - -## Issue Resolution - -### Fixed: 53K USD Cost Anomaly -- **Problem**: Predictions used historical totals instead of recent data -- **Solution**: Centralized calculator filters to recent 30-day windows -- **Result**: Accurate monthly projections (~$60-300 vs $53,000) - -### Fixed: Efficiency Score Mismatch -- **Problem**: Backend calculated cost per million tokens, UI expected 0-10 scale -- **Solution**: Standardized 0-10 efficiency scoring algorithm -- **Result**: Consistent efficiency displays across all components - -### Fixed: Calculation Inconsistencies -- **Problem**: Different logic in project analytics vs model efficiency -- **Solution**: Single calculation service with standardized methods -- **Result**: All pages show identical metrics for same data - -## Future Enhancements - -1. **Cache Optimization**: Add calculation caching for large datasets -2. **Custom Baselines**: Allow user-defined efficiency baselines -3. **Advanced Metrics**: Add more sophisticated efficiency algorithms -4. **Real-time Validation**: Continuous validation against Claude API changes -5. **Performance Monitoring**: Track calculation performance and accuracy - -## Testing - -The service includes comprehensive validation methods: -- Cost calculation accuracy verification -- Efficiency score boundary testing -- Trend analysis validation -- Edge case handling (zero costs, empty datasets) - -This centralized approach ensures CCTracker provides consistent, accurate cost analysis across all features. \ No newline at end of file From 239341be2c2bbf8b5cb7437d064c9e75097ec6db Mon Sep 17 00:00:00 2001 From: Martin Wilke Date: Sat, 19 Jul 2025 17:32:58 +0800 Subject: [PATCH 2/2] FIX: Update dependencies to resolve npm audit vulnerabilities MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Update compression from 1.8.0 to 1.8.1 - Update on-headers from 1.0.2 to 1.1.0 - Resolves http response header manipulation vulnerability (GHSA-76c9-3jph-rj3q) - Fixes CI build failure due to npm audit check πŸ€– Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- package-lock.json | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/package-lock.json b/package-lock.json index e326240..3c4e546 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "cost-tracker", - "version": "1.0.1", + "version": "1.0.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "cost-tracker", - "version": "1.0.1", + "version": "1.0.4", "hasInstallScript": true, "license": "MIT", "dependencies": { @@ -5163,9 +5163,9 @@ } }, "node_modules/compression": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/compression/-/compression-1.8.0.tgz", - "integrity": "sha512-k6WLKfunuqCYD3t6AsuPGvQWaKwuLLh2/xHNcX4qE+vIfDNXpSqnrhwA7O53R7WVQUnt8dVAIW+YHr7xTgOgGA==", + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/compression/-/compression-1.8.1.tgz", + "integrity": "sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w==", "dev": true, "license": "MIT", "dependencies": { @@ -5173,7 +5173,7 @@ "compressible": "~2.0.18", "debug": "2.6.9", "negotiator": "~0.6.4", - "on-headers": "~1.0.2", + "on-headers": "~1.1.0", "safe-buffer": "5.2.1", "vary": "~1.1.2" }, @@ -12012,9 +12012,9 @@ } }, "node_modules/on-headers": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz", - "integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.1.0.tgz", + "integrity": "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==", "dev": true, "license": "MIT", "engines": {