From 3d06e0cb57575355641d518b333d4b80d15a60c4 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 12 Nov 2025 12:09:42 -0600 Subject: [PATCH] Accumulate and persist total project cost and display in Project Details dialog --- src/components/ProjectDetailsDialog.tsx | 30 ++++++++++++ src/lib/DotAI.test.ts | 63 +++++++++++++++++++++++++ src/lib/DotAI.ts | 34 +++++++++++++ src/lib/SessionManager.ts | 28 ++++++++++- 4 files changed, 154 insertions(+), 1 deletion(-) diff --git a/src/components/ProjectDetailsDialog.tsx b/src/components/ProjectDetailsDialog.tsx index c6af9d0f..bbd10452 100644 --- a/src/components/ProjectDetailsDialog.tsx +++ b/src/components/ProjectDetailsDialog.tsx @@ -33,9 +33,11 @@ import { Loader2, Trash2, Save, + DollarSign, } from 'lucide-react'; import JSZip from 'jszip'; import { Separator } from './ui/separator'; +import { DotAI } from '@/lib/DotAI'; interface ProjectDetailsDialogProps { project: Project; @@ -49,6 +51,7 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel const [isDeleting, setIsDeleting] = useState(false); const [isRenaming, setIsRenaming] = useState(false); const [newProjectName, setNewProjectName] = useState(project.id); + const [totalCost, setTotalCost] = useState(null); const { toast } = useToast(); const { fs } = useFS(); const { projectsPath } = useFSPaths(); @@ -62,6 +65,24 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel setIsRenaming(false); }, [project.id]); + // Load total project cost + useEffect(() => { + const loadCost = async () => { + try { + const dotAI = new DotAI(fs, `${projectsPath}/${project.id}`); + const cost = await dotAI.readCost(); + setTotalCost(cost); + } catch (error) { + console.warn('Failed to load project cost:', error); + setTotalCost(null); + } + }; + + if (open) { + loadCost(); + } + }, [fs, projectsPath, project.id, open]); + const formatDistanceToNow = (date: Date) => { const now = new Date(); const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000); @@ -226,6 +247,15 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel {formatDistanceToNow(project.lastModified)} + {/* Total Cost */} + {totalCost !== null && totalCost > 0 && ( +
+ + Total Cost: + ${totalCost.toFixed(6)} +
+ )} + {/* Project Name */}
diff --git a/src/lib/DotAI.test.ts b/src/lib/DotAI.test.ts index f3a9e90c..b4d050b3 100644 --- a/src/lib/DotAI.test.ts +++ b/src/lib/DotAI.test.ts @@ -260,4 +260,67 @@ invalid json line expect(sessionName1).not.toBe(sessionName2); }); }); + + describe('readCost', () => { + it('should return 0 when COST file does not exist', async () => { + vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found')); + + const cost = await dotAI.readCost(); + expect(cost).toBe(0); + }); + + it('should read and parse cost from COST file', async () => { + vi.mocked(mockFS.readFile).mockResolvedValue('0.123456\n'); + + const cost = await dotAI.readCost(); + expect(cost).toBe(0.123456); + }); + + it('should return 0 for invalid cost value', async () => { + vi.mocked(mockFS.readFile).mockResolvedValue('invalid\n'); + + const cost = await dotAI.readCost(); + expect(cost).toBe(0); + }); + + it('should handle cost with whitespace', async () => { + vi.mocked(mockFS.readFile).mockResolvedValue(' 0.050000 \n'); + + const cost = await dotAI.readCost(); + expect(cost).toBe(0.05); + }); + }); + + describe('writeCost', () => { + it('should create shakespeare directory if it does not exist', async () => { + await dotAI.writeCost(0.123456); + + expect(mockFS.mkdir).toHaveBeenCalledWith('/test-project/.git/shakespeare', { recursive: true }); + }); + + it('should write cost with 6 decimal places', async () => { + await dotAI.writeCost(0.123456789); + + expect(mockFS.writeFile).toHaveBeenCalledWith( + '/test-project/.git/shakespeare/COST', + '0.123457\n' + ); + }); + + it('should write zero cost correctly', async () => { + await dotAI.writeCost(0); + + expect(mockFS.writeFile).toHaveBeenCalledWith( + '/test-project/.git/shakespeare/COST', + '0.000000\n' + ); + }); + + it('should handle write errors gracefully', async () => { + vi.mocked(mockFS.writeFile).mockRejectedValue(new Error('Write failed')); + + // Should not throw + await expect(dotAI.writeCost(0.123456)).resolves.toBeUndefined(); + }); + }); }); \ No newline at end of file diff --git a/src/lib/DotAI.ts b/src/lib/DotAI.ts index 20b246fc..19ddb179 100644 --- a/src/lib/DotAI.ts +++ b/src/lib/DotAI.ts @@ -278,4 +278,38 @@ export class DotAI { return null; } } + + /** + * Read the accumulated cost from .git/shakespeare/COST file + * @returns The accumulated cost as a number, or 0 if the file doesn't exist + */ + async readCost(): Promise { + try { + const costPath = join(this.workingDir, ".git", "shakespeare", "COST"); + const content = await this.fs.readFile(costPath, "utf8"); + const cost = parseFloat(content.trim()); + return isNaN(cost) ? 0 : cost; + } catch { + return 0; + } + } + + /** + * Write the accumulated cost to .git/shakespeare/COST file + * @param cost The accumulated cost in USD + */ + async writeCost(cost: number): Promise { + const shakespeareDir = join(this.workingDir, ".git", "shakespeare"); + const costPath = join(shakespeareDir, "COST"); + + try { + // Ensure .git/shakespeare directory exists + await this.fs.mkdir(shakespeareDir, { recursive: true }); + + // Write the cost with 6 decimal places for precision + await this.fs.writeFile(costPath, cost.toFixed(6) + "\n"); + } catch (error) { + console.warn(`Failed to write .git/shakespeare/COST file: ${error}`); + } + } } diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index 0afe1d9e..82918d3e 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -525,7 +525,7 @@ export class SessionManager { /** * Update session cost and context usage based on usage data */ - private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number; cost?: number }, providerModel: string): void { + private async updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number; cost?: number }, providerModel: string): Promise { if (!this.getProviderModels) return; const session = this.sessions.get(projectId); @@ -535,6 +535,9 @@ export class SessionManager { if (typeof usage.cost === 'number') { session.totalCost = (session.totalCost || 0) + usage.cost; this.emit('costUpdated', projectId, session.totalCost); + + // Accumulate cost to project total + await this.accumulateProjectCost(projectId, usage.cost); return; } @@ -564,6 +567,9 @@ export class SessionManager { // Update session total cost session.totalCost = (session.totalCost || 0) + requestCost; this.emit('costUpdated', projectId, session.totalCost); + + // Accumulate cost to project total + await this.accumulateProjectCost(projectId, requestCost); } catch (error) { console.warn('Failed to calculate session cost:', error); } @@ -584,6 +590,26 @@ export class SessionManager { } } + /** + * Accumulate request cost to the project's total cost file + */ + private async accumulateProjectCost(projectId: string, requestCost: number): Promise { + try { + const dotAI = new DotAI(this.fs, `${this.projectsPath}/${projectId}`); + + // Read current project total + const currentTotal = await dotAI.readCost(); + + // Add this request's cost + const newTotal = currentTotal + requestCost; + + // Write back the new total + await dotAI.writeCost(newTotal); + } catch (error) { + console.warn('Failed to accumulate project cost:', error); + } + } + /** * Simplified event system */