From 61d93f8b6f36bd2350a0e6fb490b11cf94ff2dee Mon Sep 17 00:00:00 2001 From: Max Thomas Date: Fri, 13 Nov 2026 16:04:07 -0600 Subject: [PATCH] fix(usage): show real project names in usage history Claude sessions found by the disk backfill were filed under Claude's encoded project folder name ("C--repo-tether"), which is what the Project column and filter showed. Read the working directory from the transcript head instead, and relabel summaries saved by older builds in one database write. The Project column and filter now show the folder name, with the parent added where two projects share one and the full path on hover. Co-Authored-By: Claude Fable 5.2 --- src/docs/usage-quota.md | 2 +- src/main/claude/transcripts.test.ts | 21 +++++++ src/main/claude/transcripts.ts | 32 +++++++++++ src/main/usage/native-opencode-usage.test.ts | 2 +- .../usage/remote-usage-service-auth.test.ts | 2 +- src/main/usage/remote-usage-service.test.ts | 2 +- src/main/usage/usage-service.test.ts | 56 +++++++++++++++++++ src/main/usage/usage-service.ts | 31 +++++++++- .../components/UsageHistoryDialog.test.ts | 2 +- .../components/UsageHistoryDialog.tsx | 9 +-- src/renderer/utils/usage-explorer.test.ts | 23 +++++++- src/renderer/utils/usage-explorer.ts | 33 ++++++++++- 12 files changed, 200 insertions(+), 15 deletions(-) diff --git a/src/docs/usage-quota.md b/src/docs/usage-quota.md index e47d29c4..e4070ca7 100644 --- a/src/docs/usage-quota.md +++ b/src/docs/usage-quota.md @@ -95,7 +95,7 @@ The sidebar footer shows today's cost and a seven-day sparkline. Click it to ope ## Usage History Dialog -Filter by CLI, project, environment, model and UTC date range. Compare the selected period with the preceding period of the same length, inspect the daily trend and click a day to narrow the session ledger. +Filter by CLI, project, environment, model and UTC date range. Compare the selected period with the preceding period of the same length, inspect the daily trend and click a day to narrow the session ledger. Projects are listed by folder name, with the parent folder added when two share a name; hover a name for the full path. Claude sessions that Tether did not launch take their path from the transcript, and fall back to Claude's own project folder name (for example `C--repo-tether`) only when the transcript records none. Filter checkboxes use the current theme's accent color and follow its light or dark appearance. diff --git a/src/main/claude/transcripts.test.ts b/src/main/claude/transcripts.test.ts index bf999011..47e1b785 100644 --- a/src/main/claude/transcripts.test.ts +++ b/src/main/claude/transcripts.test.ts @@ -15,6 +15,7 @@ import { getClaudeProjectsRoot, getProjectDir, listTranscripts, + readTranscriptCwd, transcriptExists, transcriptPath, } from './transcripts'; @@ -92,6 +93,26 @@ describe('Claude transcript path boundaries', () => { }, ); + it('reads the working directory from the first transcript entry that carries one', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tether-transcript-cwd-')); + try { + const file = path.join(dir, 'session.jsonl'); + fs.writeFileSync(file, [ + JSON.stringify({ type: 'mode', mode: 'normal' }), + JSON.stringify({ type: 'user', message: { content: 'the "cwd" is not here' } }), + JSON.stringify({ type: 'user', cwd: 'C:\\repo\\tether', message: { content: 'hi' } }), + JSON.stringify({ type: 'user', cwd: '/elsewhere' }), + '{"type":"user","cwd":"/cut-off', + ].join('\n')); + expect(readTranscriptCwd(file)).toBe('C:\\repo\\tether'); + fs.writeFileSync(file, JSON.stringify({ type: 'summary', summary: 'no cwd' }) + '\n'); + expect(readTranscriptCwd(file)).toBeNull(); + expect(readTranscriptCwd(path.join(dir, 'missing.jsonl'))).toBeNull(); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); + it('encodes every character other than a letter or digit, as Claude names project folders', () => { expect(encodeCwdForClaude('/opt/nkp/nkp-v2.17.1/cli')).toBe('-opt-nkp-nkp-v2-17-1-cli'); expect(encodeCwdForClaude('C:\\Users\\max.thomas\\my_repo')).toBe('C--Users-max-thomas-my-repo'); diff --git a/src/main/claude/transcripts.ts b/src/main/claude/transcripts.ts index 172658d9..2a3bf5cc 100644 --- a/src/main/claude/transcripts.ts +++ b/src/main/claude/transcripts.ts @@ -99,6 +99,38 @@ export interface DiscoveredTranscript { mtimeMs: number; } +const CWD_HEAD_BYTES = 256 * 1024; + +/** + * The working directory a transcript was recorded in, from the first entry that carries one. + * The project folder name cannot give this back: it replaces every separator with `-`. + * Reads only the head of the file, and returns null when no complete entry there has a `cwd`. + */ +export function readTranscriptCwd(filePath: string): string | null { + let head: string; + try { + const fd = fs.openSync(filePath, 'r'); + try { + const buffer = Buffer.alloc(CWD_HEAD_BYTES); + head = buffer.toString('utf8', 0, fs.readSync(fd, buffer, 0, CWD_HEAD_BYTES, 0)); + } finally { + fs.closeSync(fd); + } + } catch { + return null; + } + for (const line of head.split('\n')) { + if (!line.includes('"cwd"')) continue; + try { + const cwd = (JSON.parse(line) as { cwd?: unknown }).cwd; + if (typeof cwd === 'string' && cwd.trim()) return cwd; + } catch { + // A partial last line, or an entry too long to fit in the head. + } + } + return null; +} + /** * Enumerate every Claude Code transcript under ~/.claude/projects/. * Skips files whose stem isn't a UUID (defensively — Claude occasionally diff --git a/src/main/usage/native-opencode-usage.test.ts b/src/main/usage/native-opencode-usage.test.ts index 9a71f828..63569838 100644 --- a/src/main/usage/native-opencode-usage.test.ts +++ b/src/main/usage/native-opencode-usage.test.ts @@ -9,7 +9,7 @@ const mocks = vi.hoisted(() => ({ vi.mock('electron', () => ({ app: { getPath: () => '' } })); vi.mock('../db/database', () => ({ getDb: () => mocks.db, saveDb: mocks.save })); vi.mock('../logger', () => ({ createLogger: () => ({ info: vi.fn(), warn: vi.fn() }) })); -vi.mock('../claude/transcripts', () => ({ transcriptPath: vi.fn(), scanAllTranscripts: () => [] })); +vi.mock('../claude/transcripts', () => ({ transcriptPath: vi.fn(), scanAllTranscripts: () => [], readTranscriptCwd: () => null })); vi.mock('../codex/transcripts', () => ({ scanAllCodexTranscripts: () => [] })); vi.mock('../opencode/usage-reader', () => ({ readCrushSessions: mocks.crush })); vi.mock('../cli/metadata-command', () => ({ runCliMetadata: mocks.command })); diff --git a/src/main/usage/remote-usage-service-auth.test.ts b/src/main/usage/remote-usage-service-auth.test.ts index efec73b9..56049e3b 100644 --- a/src/main/usage/remote-usage-service-auth.test.ts +++ b/src/main/usage/remote-usage-service-auth.test.ts @@ -10,7 +10,7 @@ vi.mock('../cli/metadata-command', () => ({ runCliMetadata: async () => ({ ok: f vi.mock('../db/database'); vi.mock('../logger', () => ({ createLogger: () => ({ info: vi.fn(), debug: vi.fn(), warn: vi.fn() }) })); vi.mock('./remote-command', () => ({ connectRemoteUsage: vi.fn() })); -vi.mock('../claude/transcripts', () => ({ transcriptPath: vi.fn(), scanAllTranscripts: () => [] })); +vi.mock('../claude/transcripts', () => ({ transcriptPath: vi.fn(), scanAllTranscripts: () => [], readTranscriptCwd: () => null })); vi.mock('../codex/transcripts', () => ({ scanAllCodexTranscripts: () => [] })); vi.mock('../opencode/usage-reader', () => ({ readCrushSessions: () => [] })); diff --git a/src/main/usage/remote-usage-service.test.ts b/src/main/usage/remote-usage-service.test.ts index 9c7900f1..0a5607f6 100644 --- a/src/main/usage/remote-usage-service.test.ts +++ b/src/main/usage/remote-usage-service.test.ts @@ -9,7 +9,7 @@ vi.mock('../cli/metadata-command', () => ({ runCliMetadata: async () => ({ ok: f vi.mock('../db/database'); vi.mock('../logger', () => ({ createLogger: () => ({ info: vi.fn(), debug: vi.fn(), warn: vi.fn() }) })); vi.mock('./remote-command', () => ({ connectRemoteUsage: vi.fn() })); -vi.mock('../claude/transcripts', () => ({ transcriptPath: vi.fn(), scanAllTranscripts: () => [] })); +vi.mock('../claude/transcripts', () => ({ transcriptPath: vi.fn(), scanAllTranscripts: () => [], readTranscriptCwd: () => null })); vi.mock('../codex/transcripts', () => ({ scanAllCodexTranscripts: () => [] })); vi.mock('../opencode/usage-reader', () => ({ readCrushSessions: () => [] })); diff --git a/src/main/usage/usage-service.test.ts b/src/main/usage/usage-service.test.ts index e1bf7886..a6487e7d 100644 --- a/src/main/usage/usage-service.test.ts +++ b/src/main/usage/usage-service.test.ts @@ -29,6 +29,7 @@ const mocks = vi.hoisted(() => ({ } as DbData, saveDb: vi.fn(), scanAllTranscripts: vi.fn(() => []), + readTranscriptCwd: vi.fn((): string | null => null), scanAllCodexTranscripts: vi.fn(() => []), readCrushSessions: vi.fn(() => []), })); @@ -41,6 +42,7 @@ vi.mock('../db/database', () => ({ vi.mock('../claude/transcripts', () => ({ transcriptPath: (workingDir: string, sessionId: string) => `${workingDir}/${sessionId}.jsonl`, scanAllTranscripts: mocks.scanAllTranscripts, + readTranscriptCwd: mocks.readTranscriptCwd, })); vi.mock('../codex/transcripts', () => ({ @@ -61,6 +63,8 @@ beforeEach(() => { mocks.db.usageSummaries = []; mocks.saveDb.mockClear(); mocks.scanAllTranscripts.mockReturnValue([]); + mocks.readTranscriptCwd.mockReset(); + mocks.readTranscriptCwd.mockReturnValue(null); mocks.scanAllCodexTranscripts.mockReturnValue([]); mocks.readCrushSessions.mockReturnValue([]); }); @@ -535,4 +539,56 @@ describe('usage-service helpers', () => { expect(service.getAll().sessions['claude-cwd'].workingDir).toBe(realDir); expect(mocks.db.usageSummaries[0].workingDir).toBe(realDir); }); + + it('names a backfilled Claude session by the cwd in its transcript, not the encoded folder', () => { + const fs = require('node:fs') as typeof import('node:fs'); + const os = require('node:os') as typeof import('node:os'); + const path = require('node:path') as typeof import('node:path'); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tether-usage-cwd-')); + const filePath = path.join(dir, 'session.jsonl'); + fs.writeFileSync(filePath, ''); + mocks.scanAllTranscripts.mockReturnValue([{ sessionId: 'claude-named', projectDirName: 'C--repo-tether', filePath, size: 0, mtimeMs: Date.now() }]); + mocks.readTranscriptCwd.mockReturnValue('C:\\repo\\tether'); + + const service = new UsageService(); + (service as unknown as { backfillFromDisk: () => void }).backfillFromDisk(); + service.stop(); + fs.rmSync(dir, { recursive: true, force: true }); + + expect(service.getAll().sessions['claude-named'].workingDir).toBe('C:\\repo\\tether'); + }); + + it('relabels a summary saved under the encoded folder name with one database write', () => { + const fs = require('node:fs') as typeof import('node:fs'); + const os = require('node:os') as typeof import('node:os'); + const path = require('node:path') as typeof import('node:path'); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tether-usage-relabel-')); + const scanned = ['old-a', 'old-b'].map(sessionId => { + const filePath = path.join(dir, `${sessionId}.jsonl`); + fs.writeFileSync(filePath, ''); + return { sessionId, projectDirName: 'C--repo-tether', filePath, size: 0, mtimeMs: Date.now() }; + }); + mocks.scanAllTranscripts.mockReturnValue(scanned); + + // First pass stands in for an older build: no cwd was read, so both carry the folder name. + const service = new UsageService(); + const backfill = () => (service as unknown as { backfillFromDisk: () => void }).backfillFromDisk(); + backfill(); + expect(service.getAll().sessions['old-a'].workingDir).toBe('C--repo-tether'); + + mocks.readTranscriptCwd.mockReset(); + mocks.readTranscriptCwd.mockImplementation((file: string) => file.includes('old-a') ? '/repo/tether' : null); + mocks.saveDb.mockClear(); + backfill(); + expect(mocks.saveDb).toHaveBeenCalledTimes(1); + backfill(); + service.stop(); + fs.rmSync(dir, { recursive: true, force: true }); + + expect(service.getAll().sessions['old-a'].workingDir).toBe('/repo/tether'); + expect(service.getAll().sessions['old-b'].workingDir).toBe('C--repo-tether'); + // old-b has no cwd in its transcript: looked up once, not on every rescan. + expect(mocks.readTranscriptCwd.mock.calls.filter(([file]) => String(file).includes('old-b'))).toHaveLength(1); + expect(mocks.saveDb).toHaveBeenCalledTimes(1); + }); }); diff --git a/src/main/usage/usage-service.ts b/src/main/usage/usage-service.ts index b276634f..4248641e 100644 --- a/src/main/usage/usage-service.ts +++ b/src/main/usage/usage-service.ts @@ -1,7 +1,7 @@ import * as fs from 'node:fs'; import path from 'node:path'; import { createLogger } from '../logger'; -import { transcriptPath, scanAllTranscripts } from '../claude/transcripts'; +import { transcriptPath, scanAllTranscripts, readTranscriptCwd } from '../claude/transcripts'; import { scanAllCodexTranscripts } from '../codex/transcripts'; import { parseJsonlFile, parseClaudeUsageText, type ParsedMessage } from './jsonl-parser'; import { parseCodexJsonl, parseCodexUsageText, type CodexTokenUsageCounters, type CodexRequestUsageCheckpoint } from './codex-jsonl-parser'; @@ -307,6 +307,8 @@ export class UsageService { private nativeGeneration = 0; private nativeRevision = 0; private stopped = false; + /** Claude sessions whose transcript head has no `cwd`, so the lookup is not repeated every rescan. */ + private readonly unresolvedWorkingDirs = new Set(); private backfillTask: ReturnType | null = null; onUpdate(cb: (info: UsageInfo) => void): void { @@ -358,6 +360,24 @@ export class UsageService { this.rescanTimer = setInterval(() => this.backfillFromDisk(), RESCAN_INTERVAL_MS); } + /** + * Summaries saved before transcripts were read for their `cwd` carry the encoded project folder + * name ("C--repo-tether") as the working directory. Replace it with the real path, once per run. + */ + private resolveEncodedWorkingDir(session: TrackedSession, projectDirName: string): boolean { + if (session.workingDir !== projectDirName || this.unresolvedWorkingDirs.has(session.sessionId)) return false; + const cwd = readTranscriptCwd(session.filePath); + if (!cwd) { + this.unresolvedWorkingDirs.add(session.sessionId); + return false; + } + session.workingDir = cwd; + session.usage.workingDir = cwd; + const saved = getDb().usageSummaries.find(summary => summary.sessionId === session.sessionId); + if (saved) saved.workingDir = cwd; + return true; + } + /** * Scan ~/.claude/projects/ for every JSONL transcript, and parse any new * files or any appends to files we've already seen. Only token counts, @@ -379,6 +399,7 @@ export class UsageService { let newSessions = 0; let updatedSessions = 0; + let relabelled = 0; for (const d of discovered) { const existing = this.tracked.get(d.sessionId); @@ -387,7 +408,7 @@ export class UsageService { const session: TrackedSession = { sessionId: d.sessionId, cliTool: 'claude', - workingDir: d.projectDirName, + workingDir: readTranscriptCwd(d.filePath) ?? d.projectDirName, filePath: d.filePath, watching: false, debounceTimer: null, @@ -399,6 +420,7 @@ export class UsageService { continue; } existing.filePath = d.filePath; + if (this.resolveEncodedWorkingDir(existing, d.projectDirName)) relabelled++; if (!existing.watching) this.startWatching(existing); if (needsTrackedUsageReparse(existing.usage, existing.filePath)) { this.reparseSessionPreservingLegacy(existing); @@ -416,6 +438,9 @@ export class UsageService { } } + // One write for the whole pass: a first run after upgrading can relabel every saved summary. + if (relabelled > 0) saveDb(); + // 1b. Backfill Codex transcripts (JSONL with event_msg/token_count lines). let codexDiscovered: ReturnType = []; try { @@ -534,7 +559,7 @@ export class UsageService { } } - if (newSessions > 0 || updatedSessions > 0) { + if (newSessions > 0 || updatedSessions > 0 || relabelled > 0) { log.info('Transcript scan complete', { total: discovered.length + codexDiscovered.length + crushSessions.length, newSessions, diff --git a/src/renderer/components/UsageHistoryDialog.test.ts b/src/renderer/components/UsageHistoryDialog.test.ts index 23f0611c..c05b0fb7 100644 --- a/src/renderer/components/UsageHistoryDialog.test.ts +++ b/src/renderer/components/UsageHistoryDialog.test.ts @@ -65,7 +65,7 @@ describe('usage history interactions', () => { it('filters each dimension, toggles filters off, and restores the default range', async () => { await render(); await click(button(view.container, 'All time')); - for (const [legend, option] of [['CLI', 'Codex CLI'], ['Project', '/alpha'], ['Environment', 'Local'], ['Model', 'gpt-5']]) { + for (const [legend, option] of [['CLI', 'Codex CLI'], ['Project', 'alpha'], ['Environment', 'Local'], ['Model', 'gpt-5']]) { const group = [...view.container.querySelectorAll('fieldset')].find(field => field.querySelector('legend')?.textContent === legend)!; const checkbox = [...group.querySelectorAll('label')].find(label => label.textContent === option)!.querySelector('input')!; await click(checkbox); diff --git a/src/renderer/components/UsageHistoryDialog.tsx b/src/renderer/components/UsageHistoryDialog.tsx index f4f92a0b..20067cdf 100644 --- a/src/renderer/components/UsageHistoryDialog.tsx +++ b/src/renderer/components/UsageHistoryDialog.tsx @@ -7,6 +7,7 @@ import { buildUsageExplorer, cacheReadRatio, createDefaultUsageExplorerFilters, + projectDisplayName, type UsageDatePreset, type UsageExplorerFilters, type UsageExplorerSessionRow, @@ -71,7 +72,7 @@ function SummaryTile({ label, value, meta }: SummaryTileProps) { interface FilterGroupProps { label: string; - options: Array<{ value: string; label: string }>; + options: Array<{ value: string; label: string; title?: string }>; selected: string[]; onToggle: (value: string) => void; } @@ -83,7 +84,7 @@ function FilterGroup({ label, options, selected, onToggle }: FilterGroupProps) { {label}
{options.map(option => ( -