diff --git a/package-lock.json b/package-lock.json index d7b693f1..e649491f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "codeburn", - "version": "0.9.12", + "version": "0.9.15", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "codeburn", - "version": "0.9.12", + "version": "0.9.15", "license": "MIT", "dependencies": { "@modelcontextprotocol/sdk": "^1.29.0", diff --git a/src/compare.tsx b/src/compare.tsx index 2fd71d49..565c840e 100644 --- a/src/compare.tsx +++ b/src/compare.tsx @@ -4,7 +4,7 @@ import { render, Box, Text, useInput, useApp, useStdout } from 'ink' import type { ModelStats, ComparisonRow, CategoryComparison, WorkingStyleRow } from './compare-stats.js' import { aggregateModelStats, computeComparison, computeCategoryComparison, computeWorkingStyle, scanSelfCorrections } from './compare-stats.js' import { formatCost } from './format.js' -import { parseAllSessions } from './parser.js' +import { parseAllSessions, setInteractiveScanUI } from './parser.js' import { getAllProviders } from './providers/index.js' import type { ProjectSummary, DateRange } from './types.js' import { patchStdoutForWindows } from './ink-win.js' @@ -467,6 +467,10 @@ export function CompareView({ projects, onBack }: CompareViewProps) { } export async function renderCompare(range: DateRange, provider: string): Promise { + // Interactive Ink UI: suppress the CLI scan-progress line for the whole + // lifetime so it can't print over the rendered comparison. Plain CLI + // commands still show progress. + setInteractiveScanUI() const isTTY = process.stdin.isTTY && process.stdout.isTTY if (!isTTY) { process.stdout.write('Model comparison requires an interactive terminal.\n') diff --git a/src/dashboard.tsx b/src/dashboard.tsx index a79c9c22..7ba2e7ba 100644 --- a/src/dashboard.tsx +++ b/src/dashboard.tsx @@ -5,7 +5,7 @@ import { render, Box, Text, useInput, useApp, useWindowSize } from 'ink' import { CATEGORY_LABELS, type DateRange, type ProjectSummary, type TaskCategory } from './types.js' import { formatCost, formatTokens } from './format.js' import { aggregateModelEfficiency } from './model-efficiency.js' -import { parseAllSessions, filterProjectsByName } from './parser.js' +import { parseAllSessions, filterProjectsByName, setInteractiveScanUI } from './parser.js' import { findUnpricedModels, loadPricing } from './models.js' import { getAllProviders } from './providers/index.js' import { scanAndDetect, type WasteFinding, type WasteAction, type OptimizeResult } from './optimize.js' @@ -1086,6 +1086,11 @@ function StaticDashboard({ projects, period, activeProvider, planUsages, label, } export async function renderDashboard(period: Period = 'week', provider: string = 'all', refreshSeconds?: number, projectFilter?: string[], excludeFilter?: string[], customRange?: DateRange | null, customRangeLabel?: string, initialDay?: string): Promise { + // Interactive Ink UI: it renders to the same terminal and has its own in-frame + // loading state, so the CLI scan-progress line must stay silent for its whole + // lifetime (initial scan and every 30s auto-refresh, including the + // getPlanUsages → parseAllSessions path). Plain CLI commands are unaffected. + setInteractiveScanUI() await loadPricing() const dayRange = initialDay ? getDayRange(initialDay) : null const range = dayRange ?? customRange ?? getPeriodRange(period) diff --git a/src/parser.ts b/src/parser.ts index 4d407b98..4fa95fd1 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -1530,6 +1530,8 @@ async function scanProjectDirs( const unchangedFiles: Array<{ filePath: string; dirName: string; cached: CachedFile }> = [] const changedFiles: Array<{ filePath: string; info: FileInfo }> = [] + const discoverProgress = createScanProgress('scanning claude project dirs', dirs.length) + let dirsDone = 0 for (const { path: dirPath, name: dirName } of dirs) { const jsonlFiles = await collectJsonlFiles(dirPath) for (const filePath of jsonlFiles) { @@ -1544,7 +1546,10 @@ async function scanProjectDirs( changedFiles.push({ filePath, info: { dirName, fp } }) } } + dirsDone++ + await discoverProgress.tick(dirsDone) } + discoverProgress.finish() // Pre-seed dedup set from cached (unchanged) files for (const { cached } of unchangedFiles) { @@ -1555,13 +1560,15 @@ async function scanProjectDirs( } } + const parseProgress = createScanProgress('parsing changed claude sessions', changedFiles.length) + let filesDone = 0 for (const { filePath, info } of changedFiles) { delete section.files[filePath] try { const tracker = { lastCompleteLineOffset: 0 } const entries = await parseClaudeEntries(filePath, tracker) - if (!entries) continue + if (!entries) { filesDone++; await parseProgress.tick(filesDone); continue } const turns = groupIntoTurns(dedupeStreamingMessageIds(entries), seenMsgIds) const cwd = extractCanonicalCwd(entries) @@ -1586,7 +1593,10 @@ async function scanProjectDirs( ;(diskCache as { _dirty?: boolean })._dirty = true warnProviderParseFailure('claude', filePath, err) } + filesDone++ + await parseProgress.tick(filesDone) } + parseProgress.finish() if (dirs.length > 0) { for (const cachedPath of Object.keys(section.files)) { @@ -1957,6 +1967,58 @@ function warnProviderParseFailure(providerName: string, sourcePath: string, err: ) } +// A cold-cache scan over a large ~/.claude/projects tree (hundreds of project +// dirs, e.g. a git-worktree-per-task workflow) can run long enough that it +// looks hung, and is CPU-heavy enough on a single thread to visibly compete +// with anything else running interactively on the same machine. Two cheap +// mitigations, neither of which reduces total CPU work: (1) a `\r`-updated +// progress line so a long cold run reads as "working" instead of "stuck", +// gated on isTTY so it never corrupts piped/captured output (export.ts, the +// --no-color path, or a subprocess capturing stderr); (2) yielding to the +// event loop every YIELD_EVERY items so the OS scheduler gets regular break +// points instead of one long uninterrupted synchronous block. This does NOT +// fix CPU contention with a separate process (that's the OS scheduler's job +// regardless), it only keeps this process itself responsive and honest about +// progress during the scan. +const YIELD_EVERY = 25 + +function yieldToEventLoop(): Promise { + return new Promise(resolve => setImmediate(resolve)) +} + +// Suppress the scan-progress line while an interactive Ink UI is live. The +// dashboard and compare render to stdout on the same terminal, and their scans +// run (dashboard) or re-run every 30s (dashboard auto-refresh, including the +// getPlanUsages → parseAllSessions path) AFTER render() has painted a frame, so +// a `\r` progress line on stderr prints over it and garbles the screen. isTTY +// alone can't tell them apart from a plain CLI command. The interactive +// entrypoints call setInteractiveScanUI() right before render(); a pre-render +// scan (e.g. compare's cold start) still shows progress and finish() clears the +// line before Ink paints. +let interactiveScanUI = false +export function setInteractiveScanUI(active = true): void { + interactiveScanUI = active +} + +export function createScanProgress(label: string, total: number) { + const show = !interactiveScanUI && total > 20 && process.stderr.isTTY === true + let lastWrite = 0 + return { + async tick(done: number): Promise { + if (done % YIELD_EVERY === 0) await yieldToEventLoop() + if (!show) return + const now = Date.now() + if (done !== total && now - lastWrite < 100) return + lastWrite = now + process.stderr.write(`\rcodeburn: ${label} ${done}/${total}…`) + }, + finish(): void { + if (!show) return + process.stderr.write('\r\x1b[K') + }, + } +} + async function parseProviderSources( providerName: string, sources: SessionSource[], diff --git a/tests/scan-progress.test.ts b/tests/scan-progress.test.ts new file mode 100644 index 00000000..0ffc7d29 --- /dev/null +++ b/tests/scan-progress.test.ts @@ -0,0 +1,66 @@ +import { describe, it, expect, vi, afterEach } from 'vitest' +import { createScanProgress, setInteractiveScanUI } from '../src/parser.js' + +// The scan-progress line must be silent while an interactive Ink UI (dashboard, +// compare) is live, because it renders to the same terminal. The end-to-end +// proof (cold dashboard WITH a plan stays silent; cold overview shows progress) +// is documented in the PR and was run under a PTY. +describe('createScanProgress gate', () => { + const origTTY = process.stderr.isTTY + + afterEach(() => { + setInteractiveScanUI(false) + Object.defineProperty(process.stderr, 'isTTY', { value: origTTY, configurable: true }) + vi.restoreAllMocks() + }) + + function forceTTY(v: boolean) { + Object.defineProperty(process.stderr, 'isTTY', { value: v, configurable: true }) + } + + it('writes progress for a plain CLI command in a TTY over the threshold', async () => { + forceTTY(true) + const w = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + const p = createScanProgress('scanning', 100) + await p.tick(100) // final tick bypasses the 100ms throttle + expect(w).toHaveBeenCalled() + expect(String(w.mock.calls[0]![0])).toContain('scanning 100/100') + }) + + it('goes silent once an interactive Ink UI is active, even in a TTY', async () => { + forceTTY(true) + setInteractiveScanUI() // dashboard/compare call this right before render() + const w = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + const p = createScanProgress('scanning', 100) + for (let i = 1; i <= 100; i++) await p.tick(i) + p.finish() + expect(w).not.toHaveBeenCalled() + }) + + it('finish() clears the line when progress was shown', async () => { + forceTTY(true) + const w = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + const p = createScanProgress('scanning', 100) + await p.tick(100) + w.mockClear() + p.finish() + expect(String(w.mock.calls[0]![0])).toBe('\r\x1b[K') + }) + + it('writes nothing when stderr is not a TTY (piped/captured output)', async () => { + forceTTY(false) + const w = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + const p = createScanProgress('scanning', 100) + await p.tick(100) + p.finish() + expect(w).not.toHaveBeenCalled() + }) + + it('stays silent below the small-tree threshold', async () => { + forceTTY(true) + const w = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + const p = createScanProgress('scanning', 5) + await p.tick(5) + expect(w).not.toHaveBeenCalled() + }) +})