Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/docs/usage-quota.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
21 changes: 21 additions & 0 deletions src/main/claude/transcripts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
getClaudeProjectsRoot,
getProjectDir,
listTranscripts,
readTranscriptCwd,
transcriptExists,
transcriptPath,
} from './transcripts';
Expand Down Expand Up @@ -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');
Expand Down
32 changes: 32 additions & 0 deletions src/main/claude/transcripts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,13 @@
* Subsequent "user" entries are tool results with `content: [...]` arrays —
* we skip those and only return the first plain-string content.
*/
function extractFirstUserPrompt(filePath: string): string {

Check warning on line 63 in src/main/claude/transcripts.ts

View workflow job for this annotation

GitHub Actions / tests

Refactor this function to reduce its Cognitive Complexity from 17 to the 15 allowed
let fd: number | null = null;
try {
fd = fs.openSync(filePath, 'r');
const buf = Buffer.alloc(32 * 1024);
const n = fs.readSync(fd, buf, 0, buf.length, 0);
const text = buf.slice(0, n).toString('utf-8');

Check warning on line 69 in src/main/claude/transcripts.ts

View workflow job for this annotation

GitHub Actions / tests

The signature '(start?: number | undefined, end?: number | undefined): Buffer<ArrayBuffer>' of 'buf.slice' is deprecated
for (const line of text.split('\n')) {
if (!line.startsWith('{')) continue;
let entry: { type?: string; message?: { role?: string; content?: unknown } };
Expand Down Expand Up @@ -99,12 +99,44 @@
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
* drops stray files). Does not read or parse any file contents.
*/
export function scanAllTranscripts(): DiscoveredTranscript[] {

Check warning on line 139 in src/main/claude/transcripts.ts

View workflow job for this annotation

GitHub Actions / tests

Refactor this function to reduce its Cognitive Complexity from 17 to the 15 allowed
const root = getClaudeProjectsRoot();
const results: DiscoveredTranscript[] = [];
let projectDirs: fs.Dirent[];
Expand Down
2 changes: 1 addition & 1 deletion src/main/usage/native-opencode-usage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }));
Expand Down
2 changes: 1 addition & 1 deletion src/main/usage/remote-usage-service-auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: () => [] }));

Expand Down
2 changes: 1 addition & 1 deletion src/main/usage/remote-usage-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: () => [] }));

Expand Down
56 changes: 56 additions & 0 deletions src/main/usage/usage-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => []),
}));
Expand All @@ -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', () => ({
Expand All @@ -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([]);
});
Expand Down Expand Up @@ -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);
});
});
31 changes: 28 additions & 3 deletions src/main/usage/usage-service.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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<string>();
private backfillTask: ReturnType<typeof setImmediate> | null = null;

onUpdate(cb: (info: UsageInfo) => void): void {
Expand Down Expand Up @@ -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,
Expand All @@ -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);
Expand All @@ -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,
Expand All @@ -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);
Expand All @@ -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<typeof scanAllCodexTranscripts> = [];
try {
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion src/renderer/components/UsageHistoryDialog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
9 changes: 5 additions & 4 deletions src/renderer/components/UsageHistoryDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
buildUsageExplorer,
cacheReadRatio,
createDefaultUsageExplorerFilters,
projectDisplayName,
type UsageDatePreset,
type UsageExplorerFilters,
type UsageExplorerSessionRow,
Expand Down Expand Up @@ -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;
}
Expand All @@ -83,7 +84,7 @@ function FilterGroup({ label, options, selected, onToggle }: FilterGroupProps) {
<legend>{label}</legend>
<div className="usage-explorer-filter__choices">
{options.map(option => (
<label key={option.value} className="usage-explorer-check">
<label key={option.value} className="usage-explorer-check" title={option.title}>
<input
type="checkbox"
checked={selected.includes(option.value)}
Expand Down Expand Up @@ -127,7 +128,7 @@ function SessionRow({ row, expanded, onToggle }: SessionRowProps) {
</td>
<td>{cliToolName(row.cliTool)}</td>
<td>{row.environmentLabel}</td>
<td>{row.project}</td>
<td title={row.project}>{projectDisplayName(row.project)}</td>
<td>{row.lastDate ?? 'Unknown'}</td>
<td className="usage-explorer-number">{formatTokens(row.tokens)}</td>
<td className="usage-explorer-number">{formatCost(row.cost)}</td>
Expand Down Expand Up @@ -320,7 +321,7 @@ export function UsageHistoryDialog({ isOpen, onClose }: UsageHistoryDialogProps)

<div className="usage-explorer-filters">
<FilterGroup label="CLI" options={explorer.options.cliTools.map(option => ({ ...option, label: cliToolName(option.value) }))} selected={filters.cliTools} onToggle={value => setFilterList('cliTools', value as CliToolId)} />
<FilterGroup label="Project" options={explorer.options.projects} selected={filters.projects} onToggle={value => setFilterList('projects', value)} />
<FilterGroup label="Project" options={explorer.options.projects.map(option => ({ ...option, title: option.value }))} selected={filters.projects} onToggle={value => setFilterList('projects', value)} />
<FilterGroup label="Environment" options={explorer.options.environments} selected={filters.environments} onToggle={value => setFilterList('environments', value)} />
<FilterGroup label="Model" options={explorer.options.models} selected={filters.models} onToggle={value => setFilterList('models', value)} />
</div>
Expand Down
23 changes: 22 additions & 1 deletion src/renderer/utils/usage-explorer.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import type { CliToolId, SessionUsage, UsageInfo } from '../../shared/types';
import { buildUsageExplorer, cacheReadRatio, createDefaultUsageExplorerFilters, type UsageExplorerFilters } from './usage-explorer';
import { buildUsageExplorer, cacheReadRatio, createDefaultUsageExplorerFilters, projectDisplayName, type UsageExplorerFilters } from './usage-explorer';

function model(model: string, inputTokens: number, outputTokens: number, cost: number, cacheReadTokens = 0, reasoningTokens = 0, cacheCreationTokens = 0) {
return {
Expand Down Expand Up @@ -69,6 +69,27 @@ function build(input: UsageInfo, filterOverrides: Partial<UsageExplorerFilters>
}

describe('buildUsageExplorer', () => {
it('names projects by folder and adds the parent only where two folders share a name', () => {
const result = build(usage([
session({ sessionId: 'a', workingDir: 'C:\\repo\\tether' }),
session({ sessionId: 'b', workingDir: '/home/max/work/api' }),
session({ sessionId: 'c', workingDir: '/home/max/play/api/' }),
session({ sessionId: 'd', workingDir: 'C--repo-legacy' }),
session({ sessionId: 'e' }),
]), { datePreset: 'all' });

expect(result.options.projects).toEqual([
{ value: 'C--repo-legacy', label: 'C--repo-legacy' },
{ value: '/home/max/play/api/', label: 'play/api' },
{ value: 'C:\\repo\\tether', label: 'tether' },
{ value: 'Unknown project', label: 'Unknown project' },
{ value: '/home/max/work/api', label: 'work/api' },
]);
expect(projectDisplayName('C:\\repo\\tether')).toBe('tether');
// The filter value is still the whole path.
expect(build(usage([session({ sessionId: 'a', workingDir: 'C:\\repo\\tether' })]), { datePreset: 'all', projects: ['C:\\repo\\tether'] }).sessions).toHaveLength(1);
});

it('uses UTC date boundaries for today', () => {
const result = build(usage([
session({
Expand Down
Loading
Loading