From 337511cc3f0bf32d1ba41bbdb6e6ab05df576afd Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Mon, 23 Nov 2026 12:57:19 +0200 Subject: [PATCH 01/12] feat(hud): add an opt-in week forecast Show the estimate at reset from the Claude week data on stdin. Keep the saved forecast option in both init paths. Task: feat/805-hud-tokenmeter-forecast --- src/cli/commands/init.ts | 4 +- src/hud/components/week-forecast.ts | 64 ++++++++++++++++++++++ src/hud/config.ts | 7 ++- src/hud/render.ts | 4 +- src/hud/types.ts | 2 + tests/hud-components.test.ts | 85 +++++++++++++++++++++++++++-- tests/hud-render.test.ts | 7 ++- 7 files changed, 160 insertions(+), 13 deletions(-) create mode 100644 src/hud/components/week-forecast.ts diff --git a/src/cli/commands/init.ts b/src/cli/commands/init.ts index 30cb70814..f42b94800 100644 --- a/src/cli/commands/init.ts +++ b/src/cli/commands/init.ts @@ -1074,7 +1074,7 @@ export const initCommand = new Command('init') if (options.hudOnly) { // Save HUD config const existingHud = loadHudConfig(); - saveHudConfig({ enabled: true, detail: existingHud.detail }); + saveHudConfig({ ...existingHud, enabled: true }); // Update statusLine in settings.json const settingsPath = path.join(claudeDir, 'settings.json'); @@ -2660,7 +2660,7 @@ export const initCommand = new Command('init') // Configure HUD const existingHud = loadHudConfig(); - saveHudConfig({ enabled: hudEnabled, detail: existingHud.detail }); + saveHudConfig({ ...existingHud, enabled: hudEnabled }); // File extras — into the projects the Recommended summary's .claudeignore row checked. if (claudeignoreEnabled) { diff --git a/src/hud/components/week-forecast.ts b/src/hud/components/week-forecast.ts new file mode 100644 index 000000000..57d130edc --- /dev/null +++ b/src/hud/components/week-forecast.ts @@ -0,0 +1,64 @@ +import type { ComponentResult, GatherContext } from '../types.js'; +import { dim } from '../colors.js'; +import { formatCountdown } from './usage-quota.js'; + +const HOUR_MS = 3_600_000; +const DAY_MS = 24 * HOUR_MS; +const WEEK_MS = 7 * DAY_MS; +const BURN_FREE_FRACTION = 0.03; +const MAX_RESET_AHEAD_MS = 8 * DAY_MS; + +interface WeekPoint { + readonly usedPercent: number; + readonly resetsAtMs: number; +} + +export function parseWeekPoint(sevenDay: unknown, nowMs: number): WeekPoint | null { + if (sevenDay === null || typeof sevenDay !== 'object' || Array.isArray(sevenDay)) return null; + if (!('used_percentage' in sevenDay) || !('resets_at' in sevenDay)) return null; + + const { used_percentage: usedPercent, resets_at: resetsAt } = sevenDay; + if (typeof usedPercent !== 'number' || !Number.isFinite(usedPercent) || usedPercent < 0 || usedPercent > 100) { + return null; + } + if (typeof resetsAt !== 'number') return null; + const resetsAtMs = resetsAt * 1000; + if (!(resetsAtMs > nowMs && resetsAtMs <= nowMs + MAX_RESET_AHEAD_MS)) return null; + return { usedPercent, resetsAtMs }; +} + +/** + * D-HUD-WEEK-FORECAST: Copy forecastFrom from tokenmeter 0.3.0. + * The installed HUD cannot import the package. A devflow-only user has no stored Claude data. + * D-TOKENMETER-HUD covers only the Codex client. Like usageQuota, this part uses stdin. + */ +export function weekForecastFrom({ usedPercent, resetsAtMs }: WeekPoint, nowMs: number) { + const remainingMs = resetsAtMs - nowMs; + const elapsedMs = WEEK_MS - remainingMs; + if (!(elapsedMs >= BURN_FREE_FRACTION * WEEK_MS)) return null; + + const burn = usedPercent / (elapsedMs / HOUR_MS); + const atResetPct = usedPercent + burn * (remainingMs / HOUR_MS); + const runsOutAtMs = burn > 0 ? Math.round(nowMs + ((100 - usedPercent) / burn) * HOUR_MS) : Infinity; + return { atResetPct, runsOutAtMs: runsOutAtMs <= resetsAtMs ? runsOutAtMs : null }; +} + +export function forecastPercentText(pct: number): string { + const rounded = Math.round(pct); + return rounded > 999 ? '>999%' : `${rounded}%`; +} + +export default async function weekForecast(ctx: GatherContext): Promise { + const nowMs = Date.now(); + const point = parseWeekPoint(ctx.stdin?.rate_limits?.seven_day, nowMs); + if (!point) return null; + + const forecast = weekForecastFrom(point, nowMs); + if (!forecast || !Number.isFinite(forecast.atResetPct)) return null; + const { atResetPct, runsOutAtMs } = forecast; + if (runsOutAtMs !== null && !Number.isFinite(runsOutAtMs)) return null; + + const span = runsOutAtMs !== null && runsOutAtMs > nowMs ? formatCountdown(runsOutAtMs / 1000) : ''; + const raw = `→ ${forecastPercentText(atResetPct)} by reset${span ? `, runs out in ${span}` : ''}`; + return { text: dim(raw), raw }; +} diff --git a/src/hud/config.ts b/src/hud/config.ts index 87066f46d..2ef12ab1f 100644 --- a/src/hud/config.ts +++ b/src/hud/config.ts @@ -40,9 +40,10 @@ export function loadConfig(): HudConfig { return { enabled: parsed.enabled !== false, detail: parsed.detail === true, + forecast: parsed.forecast === true, }; } catch { - return { enabled: true, detail: false }; + return { enabled: true, detail: false, forecast: false }; } } @@ -56,7 +57,9 @@ export function saveConfig(config: HudConfig): void { } export function resolveComponents(config: HudConfig): ComponentId[] { - if (config.enabled) return [...HUD_COMPONENTS]; + if (config.enabled) { + return config.forecast === true ? [...HUD_COMPONENTS, 'weekForecast'] : [...HUD_COMPONENTS]; + } // Version badge always renders so users see upgrade notifications return ['versionBadge']; } diff --git a/src/hud/render.ts b/src/hud/render.ts index ecccf306e..bb06144d1 100644 --- a/src/hud/render.ts +++ b/src/hud/render.ts @@ -15,6 +15,7 @@ import contextUsage from './components/context-usage.js'; import versionBadge from './components/version-badge.js'; import sessionDuration from './components/session-duration.js'; import usageQuota from './components/usage-quota.js'; +import weekForecast from './components/week-forecast.js'; import codexQuota from './components/codex-quota.js'; import todoProgress from './components/todo-progress.js'; import configCounts from './components/config-counts.js'; @@ -33,6 +34,7 @@ const COMPONENT_MAP: Record = { versionBadge, sessionDuration, usageQuota, + weekForecast, codexQuota, todoProgress, configCounts, @@ -48,7 +50,7 @@ const COMPONENT_MAP: Record = { */ const LINE_GROUPS: ComponentId[][] = [ ['directory', 'gitBranch', 'gitAheadBehind', 'releaseInfo', 'worktreeCount', 'diffStats'], - ['contextUsage', 'usageQuota', 'codexQuota', 'todoProgress'], + ['contextUsage', 'usageQuota', 'weekForecast', 'codexQuota', 'todoProgress'], ['model', 'configCounts', 'sessionCost'], ['curationCounts'], ['versionBadge'], diff --git a/src/hud/types.ts b/src/hud/types.ts index 91d74c1ea..8566c4450 100644 --- a/src/hud/types.ts +++ b/src/hud/types.ts @@ -33,6 +33,7 @@ export type ComponentId = | 'versionBadge' | 'sessionDuration' | 'usageQuota' + | 'weekForecast' | 'codexQuota' | 'todoProgress' | 'configCounts' @@ -47,6 +48,7 @@ export type ComponentId = export interface HudConfig { enabled: boolean; detail: boolean; + forecast: boolean; } /** diff --git a/tests/hud-components.test.ts b/tests/hud-components.test.ts index 4880f5a23..65d96466b 100644 --- a/tests/hud-components.test.ts +++ b/tests/hud-components.test.ts @@ -1,8 +1,8 @@ -import { describe, it, expect, afterEach, vi } from 'vitest'; +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import type { GatherContext, GitStatus, TranscriptData } from '../src/hud/types.js'; +import type { GatherContext, GitStatus, StdinData, TranscriptData } from '../src/hud/types.js'; import { hudCacheDir, writeCache } from '../src/core/cache.js'; // Import components @@ -14,6 +14,7 @@ import model from '../src/hud/components/model.js'; import contextUsage from '../src/hud/components/context-usage.js'; import sessionDuration from '../src/hud/components/session-duration.js'; import usageQuota, { formatCountdown } from '../src/hud/components/usage-quota.js'; +import weekForecast, { parseWeekPoint } from '../src/hud/components/week-forecast.js'; import codexQuota from '../src/hud/components/codex-quota.js'; import todoProgress from '../src/hud/components/todo-progress.js'; import sessionCost from '../src/hud/components/session-cost.js'; @@ -21,7 +22,7 @@ import releaseInfo from '../src/hud/components/release-info.js'; import worktreeCount from '../src/hud/components/worktree-count.js'; import configCounts from '../src/hud/components/config-counts.js'; import versionBadge from '../src/hud/components/version-badge.js'; -import { stripAnsi } from '../src/hud/colors.js'; +import { dim, stripAnsi } from '../src/hud/colors.js'; function makeCtx(overrides: Partial = {}): GatherContext { return { @@ -31,9 +32,9 @@ function makeCtx(overrides: Partial = {}): GatherContext { usage: null, codexUsage: null, configCounts: null, - decisionsCounts: null, + curationCounts: null, costHistory: null, - config: { enabled: true, detail: false, components: [] }, + config: { enabled: true, detail: false, forecast: false, components: [] }, devflowDir: '/test/.devflow', sessionStartTime: null, terminalWidth: 120, @@ -474,6 +475,80 @@ describe('usageQuota component', () => { }); }); +describe('weekForecast component', () => { + const nowMs = Date.parse('2026-11-23T12:00:00Z'); + const hourMs = 3_600_000; + const resetIn = (hours: number) => (nowMs + hours * hourMs) / 1000; + const week = (usedPercentage: unknown, resetsAt: unknown = resetIn(84)) => ({ + rate_limits: { seven_day: { used_percentage: usedPercentage, resets_at: resetsAt } }, + }); + + beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(nowMs); + }); + afterEach(() => vi.useRealTimers()); + + function renderForecast(stdin: unknown) { + return weekForecast(makeCtx({ stdin: stdin as StdinData })); + } + + it.each([ + [40, 84, '→ 80% by reset'], + [80, 82, '→ 156% by reset, runs out in 21h 30m'], + [70, 84, '→ 140% by reset, runs out in 1d 12h'], + [50, 84, '→ 100% by reset, runs out in 3d 12h'], + [99, 162, '→ >999% by reset, runs out in 3m'], + [100, 84, '→ 200% by reset'], + [0, 84, '→ 0% by reset'], + [99.99, 84, '→ 200% by reset, runs out in 0m'], + ] as const)('shows dim text for %s%% used and %s hours left', async (percent, hours, expected) => { + expect(await renderForecast(week(percent, resetIn(hours)))).toEqual({ + text: dim(expected), + raw: expected, + }); + }); + + it.each([ + ['no rate_limits', {}], + ['no seven_day', { rate_limits: {} }], + ['a null seven_day', { rate_limits: { seven_day: null } }], + ['a string seven_day', { rate_limits: { seven_day: '40' } }], + ['an array seven_day', { rate_limits: { seven_day: [] } }], + ['a string percent', week('40')], + ['NaN percent', week(NaN)], + ['infinite percent', week(Infinity)], + ['negative percent', week(-1)], + ['percent above 100', week(101)], + ['no reset', { rate_limits: { seven_day: { used_percentage: 40 } } }], + ['a string reset', week(40, String(resetIn(84)))], + ['an infinite reset', week(40, Infinity)], + ['a reset at now', week(40, resetIn(0))], + ['a past reset', week(40, resetIn(-1))], + ['a reset more than 8 days away', week(40, resetIn(8 * 24) + 1)], + ['a reset in milliseconds', week(40, resetIn(84) * 1000)], + ['only 5 hours elapsed', week(40, resetIn(163))], + ] as const)('shows nothing with %s', async (_label, stdin) => { + expect(await renderForecast(stdin)).toBeNull(); + }); + + it('accepts a reset exactly 8 days away but not one second later', () => { + const reset = resetIn(8 * 24); + const accepted = parseWeekPoint(week(40, reset).rate_limits.seven_day, nowMs); + const refused = parseWeekPoint(week(40, reset + 1).rate_limits.seven_day, nowMs); + expect([accepted, refused]).toEqual([{ usedPercent: 40, resetsAtMs: reset * 1000 }, null]); + }); + + it('starts the forecast at exactly 5 hours and 144 seconds elapsed', async () => { + const reset = resetIn(163) - 144; + vi.setSystemTime(nowMs - 1); + const before = await renderForecast(week(1, reset)); + vi.setSystemTime(nowMs); + const at = await renderForecast(week(1, reset)); + expect([before, at]).toEqual([null, { text: dim('→ 33% by reset'), raw: '→ 33% by reset' }]); + }); +}); + describe('codexQuota component', () => { const nowSec = (): number => Math.floor(Date.now() / 1000); // 30 extra seconds keep each countdown off a minute boundary. diff --git a/tests/hud-render.test.ts b/tests/hud-render.test.ts index 654dd5136..c1474b146 100644 --- a/tests/hud-render.test.ts +++ b/tests/hud-render.test.ts @@ -47,6 +47,7 @@ function makeCtx( config: { enabled: true, detail: false, + forecast: false, components: [...HUD_COMPONENTS], ...configOverride, }, @@ -172,7 +173,7 @@ describe('render', () => { it('handles subset of components', async () => { const ctx = makeCtx({ - config: { enabled: true, detail: false, components: ['directory', 'model'] }, + config: { enabled: true, detail: false, forecast: false, components: ['directory', 'model'] }, }); const output = await render(ctx); const raw = stripAnsi(output); @@ -235,12 +236,12 @@ describe('config', () => { }); it('resolveComponents returns all components when enabled', () => { - const config: HudConfig = { enabled: true, detail: false }; + const config: HudConfig = { enabled: true, detail: false, forecast: false }; expect(resolveComponents(config)).toEqual([...HUD_COMPONENTS]); }); it('resolveComponents returns only versionBadge when disabled', () => { - const config: HudConfig = { enabled: false, detail: false }; + const config: HudConfig = { enabled: false, detail: false, forecast: false }; expect(resolveComponents(config)).toEqual(['versionBadge']); }); From ee88eee6ee09205b90671df5ce38c96ae52d8107 Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Mon, 23 Nov 2026 13:12:10 +0200 Subject: [PATCH 02/12] feat(hud): add forecast CLI flags Save detail and forecast changes together before the HUD switch. Show the forecast state in status output without a config change. Task: feat/805-hud-tokenmeter-forecast --- src/cli/commands/hud.ts | 35 +++++++++--- tests/hud.test.ts | 117 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 145 insertions(+), 7 deletions(-) diff --git a/src/cli/commands/hud.ts b/src/cli/commands/hud.ts index e22b439b1..1356e1714 100644 --- a/src/cli/commands/hud.ts +++ b/src/cli/commands/hud.ts @@ -22,6 +22,14 @@ interface Settings { [key: string]: unknown; } +interface HudOptions { + status?: boolean; + detail?: boolean; + forecast?: boolean; + enable?: boolean; + disable?: boolean; +} + /** * Add the HUD statusLine to settings JSON. * Idempotent — returns unchanged JSON if HUD already set. @@ -138,19 +146,24 @@ export function createHudCommand(): Command { .option('--status', 'Show current HUD config') .option('--detail', 'Show tool/agent descriptions in HUD') .option('--no-detail', 'Hide tool/agent descriptions') + .option('--forecast', 'Show the week quota forecast') + .option('--no-forecast', 'Hide the week quota forecast') .option('--enable', 'Enable HUD in settings') .option('--disable', 'Disable HUD (remove statusLine)') - .action(async (options) => { + .action(async (options: HudOptions) => { const hasFlag = options.status || options.enable || options.disable || - options.detail !== undefined; + options.detail !== undefined || + options.forecast !== undefined; if (!hasFlag) { p.intro(color.bgCyan(color.white(' HUD '))); p.note( `${color.cyan('devflow hud --detail')} Show tool/agent descriptions\n` + `${color.cyan('devflow hud --no-detail')} Hide tool/agent descriptions\n` + + `${color.cyan('devflow hud --forecast')} Show the week quota forecast\n` + + `${color.cyan('devflow hud --no-forecast')} Hide the week quota forecast\n` + `${color.cyan('devflow hud --status')} Show current config\n` + `${color.cyan('devflow hud --enable')} Enable HUD in settings\n` + `${color.cyan('devflow hud --disable')} Remove HUD from settings`, @@ -170,6 +183,7 @@ export function createHudCommand(): Command { p.note( `${color.dim('Enabled:')} ${config.enabled ? color.green('yes') : color.dim('no')}\n` + `${color.dim('Detail:')} ${config.detail ? color.green('on') : color.dim('off')}\n` + + `${color.dim('Forecast:')} ${config.forecast ? color.green('on') : color.dim('off')}\n` + `${color.dim('Components:')} ${HUD_COMPONENTS.length}`, 'Current config', ); @@ -189,12 +203,19 @@ export function createHudCommand(): Command { return; } - if (options.detail !== undefined) { + if (options.detail !== undefined || options.forecast !== undefined) { const config = loadConfig(); - config.detail = options.detail; - saveConfig(config); - p.log.success(`HUD detail ${config.detail ? 'enabled' : 'disabled'}`); - return; + saveConfig({ + ...config, + detail: options.detail ?? config.detail, + forecast: options.forecast ?? config.forecast, + }); + if (options.detail !== undefined) { + p.log.success(`HUD detail ${options.detail ? 'enabled' : 'disabled'}`); + } + if (options.forecast !== undefined) { + p.log.success(`HUD forecast ${options.forecast ? 'enabled' : 'disabled'}`); + } } if (options.enable) { diff --git a/tests/hud.test.ts b/tests/hud.test.ts index 3bc02b431..33709c8ad 100644 --- a/tests/hud.test.ts +++ b/tests/hud.test.ts @@ -10,6 +10,123 @@ import { createHudCommand, } from '../src/cli/commands/hud.js'; import { runCleanupPhase } from '../src/cli/commands/uninstall.js'; +import * as hudConfig from '../src/hud/config.js'; +import type { HudConfig } from '../src/hud/types.js'; +import { stripAnsi } from '../src/hud/colors.js'; + +describe('hud config flags', () => { + let tmpHome: string; + const runHud = (...args: string[]) => createHudCommand().exitOverride().parseAsync(args, { from: 'user' }); + const settingsPath = () => path.join(tmpHome, '.claude', 'settings.json'); + const statusLine = () => ({ type: 'command', command: path.join(tmpHome, '.devflow', 'scripts', 'hud.sh') }); + const readConfig = async (): Promise => JSON.parse(await fs.readFile(hudConfig.getConfigPath(), 'utf-8')); + const readSettings = async (): Promise => JSON.parse(await fs.readFile(settingsPath(), 'utf-8')); + + beforeEach(async () => { + tmpHome = await fs.mkdtemp(path.join(os.tmpdir(), 'devflow-hud-flags-')); + vi.stubEnv('HOME', tmpHome); + vi.stubEnv('CLAUDE_CONFIG_DIR', path.dirname(settingsPath())); + await fs.mkdir(path.dirname(settingsPath())); + }); + + afterEach(async () => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + await fs.rm(tmpHome, { recursive: true, force: true }); + }); + + it.each([ + ['--forecast', { enabled: false, detail: true, forecast: false }], + ['--no-forecast', { enabled: true, detail: false, forecast: true }], + ] as const)('%s saves only the forecast change', async (flag, config) => { + hudConfig.saveConfig(config); + + await runHud(flag); + + expect(await readConfig()).toEqual({ ...config, forecast: !config.forecast }); + }); + + it.each([ + [true, 'on', '--no-forecast'], + [false, 'off', '--forecast'], + ] as const)('--status reports forecast %s without a config change', async (forecast, label, flag) => { + const config: HudConfig = { enabled: true, detail: false, forecast }; + hudConfig.saveConfig(config); + const output = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + + await runHud('--status', flag); + + expect(stripAnsi(output.mock.calls.map(([text]) => String(text)).join(''))).toMatch( + new RegExp(`Forecast:\\s+${label}\\b`), + ); + expect(await readConfig()).toEqual(config); + }); + + it('lists both forecast flags without a change flag', async () => { + const output = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + + await runHud(); + + const text = stripAnsi(output.mock.calls.map(([chunk]) => String(chunk)).join('')); + expect(text).toContain('devflow hud --forecast'); + expect(text).toContain('devflow hud --no-forecast'); + expect(text).not.toContain('weekForecast'); + }); + + it('saves both detail and forecast in one write', async () => { + hudConfig.saveConfig({ enabled: false, detail: false, forecast: false }); + const save = vi.spyOn(hudConfig, 'saveConfig'); + + await runHud('--detail', '--forecast'); + + expect(save).toHaveBeenCalledTimes(1); + expect(await readConfig()).toEqual({ enabled: false, detail: true, forecast: true }); + }); + + it('--enable with --forecast saves both and registers the status line', async () => { + hudConfig.saveConfig({ enabled: false, detail: true, forecast: false }); + + await runHud('--enable', '--forecast'); + + expect(await readConfig()).toEqual({ enabled: true, detail: true, forecast: true }); + expect(await readSettings()).toEqual({ statusLine: statusLine() }); + }); + + it('--detail with --enable saves both and registers the status line', async () => { + hudConfig.saveConfig({ enabled: false, detail: false, forecast: true }); + + await runHud('--detail', '--enable'); + + expect(await readConfig()).toEqual({ enabled: true, detail: true, forecast: true }); + expect(await readSettings()).toEqual({ statusLine: statusLine() }); + }); + + it('--detail with --disable saves both and removes the status line', async () => { + hudConfig.saveConfig({ enabled: true, detail: false, forecast: true }); + await fs.writeFile(settingsPath(), JSON.stringify({ statusLine: statusLine(), model: 'opus' })); + + await runHud('--detail', '--disable'); + + expect(await readConfig()).toEqual({ enabled: false, detail: true, forecast: true }); + expect(await readSettings()).toEqual({ model: 'opus' }); + }); + + it('saves and reports both options when non-interactive --enable leaves a foreign status line', async () => { + const settings = { statusLine: { type: 'command', command: 'custom-status' } }; + await fs.writeFile(settingsPath(), JSON.stringify(settings)); + hudConfig.saveConfig({ enabled: false, detail: false, forecast: false }); + vi.spyOn(process, 'stdin', 'get').mockReturnValue(Object.create(process.stdin, { isTTY: { value: false } })); + const output = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + + await runHud('--enable', '--detail', '--forecast'); + + expect(await readConfig()).toEqual({ enabled: false, detail: true, forecast: true }); + expect(await readSettings()).toEqual(settings); + expect(stripAnsi(output.mock.calls.map(([text]) => String(text)).join(''))).toMatch( + /HUD detail enabled[\s\S]*HUD forecast enabled[\s\S]*Non-interactive mode/, + ); + }); +}); describe('addHudStatusLine', () => { it('adds statusLine to empty settings', () => { From bc11c32098c80524c82ab954c040cb0214e0762c Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Mon, 23 Nov 2026 13:12:32 +0200 Subject: [PATCH 03/12] test(hud): pin forecast output and input rules Keep the default render bytes fixed. Check the opt-in config, invalid input fallback, capacity line order, and import boundary. Task: feat/805-hud-tokenmeter-forecast --- tests/guards/hud-usage-source.test.ts | 13 ++- tests/hud-render.test.ts | 161 +++++++++++++++++++++----- 2 files changed, 141 insertions(+), 33 deletions(-) diff --git a/tests/guards/hud-usage-source.test.ts b/tests/guards/hud-usage-source.test.ts index 7666ab467..54d1fca1e 100644 --- a/tests/guards/hud-usage-source.test.ts +++ b/tests/guards/hud-usage-source.test.ts @@ -1,5 +1,6 @@ import { existsSync, readFileSync } from 'node:fs'; import { basename, extname, join, relative } from 'node:path'; +import ts from 'typescript'; import { describe, expect, it } from 'vitest'; import { ROOT, walkFiles, type CorpusEntry } from '../helpers.js'; @@ -53,7 +54,7 @@ const privatePath = (...parts: string[]): string => ['', ...parts].join('/'); // Pre-existing dummy paths in older tests. Do not exempt a whole file or folder prefix. const DUMMY_PATHS: Readonly> = { 'tests/hud-components.test.ts': [privatePath('home', 'user', 'projects', 'my-app')], - 'tests/hud-render.test.ts': [privatePath('home', 'user', 'project'), privatePath('tmp', 'nonexistent-devflow-test-home'), privatePath('tmp', 'hud-config-home')], + 'tests/hud-render.test.ts': [privatePath('home', 'user', 'project')], 'tests/uninstall-logic.test.ts': [ privatePath('tmp', 'devflow-d8-disjoint'), privatePath('Users', 'testuser'), privatePath('Users', 'testuser', '.devflow', 'skills'), privatePath('tmp', '.devflow'), @@ -124,6 +125,16 @@ describe('HUD Codex usage source', () => { expectClean([...hud, entry('src/core/cache.ts'), entry(BIN_OWNER), entry(BIN_READER)], matches(RETIRED_READER)); }); + it('uses only local stdin data for the week forecast, with no HUD entry gather', () => { + const forecast = read('src/hud/components/week-forecast.ts'); + const imports = ts.preProcessFile(forecast, true, true).importedFiles.map(({ fileName }) => fileName); + expect(imports.sort()).toEqual(['../colors.js', '../types.js', './usage-quota.js']); + + const hudEntry = read('src/hud/index.ts'); + expect(hudEntry).toContain('resolveComponents(config)'); + expect(hudEntry).not.toMatch(/forecast/i); + }); + it('names no relay package in the current docs or the new HUD sources', () => { expectClean([...codexDocs(), currentChangelog(), ...newHudSources()], matches(RELAY_NAME)); }); diff --git a/tests/hud-render.test.ts b/tests/hud-render.test.ts index c1474b146..38b0a1de2 100644 --- a/tests/hud-render.test.ts +++ b/tests/hud-render.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect } from 'vitest'; +import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; @@ -10,7 +10,7 @@ import { resolveComponents, } from '../src/hud/config.js'; import { stripAnsi } from '../src/hud/colors.js'; -import type { GatherContext, HudConfig, ComponentId } from '../src/hud/types.js'; +import type { GatherContext, HudConfig, ComponentId, StdinData } from '../src/hud/types.js'; function makeCtx( overrides: Partial & { config?: Partial & { components?: ComponentId[] } } = {}, @@ -205,43 +205,140 @@ describe('render', () => { }); }); +describe('week forecast on the capacity line', () => { + const nowMs = Date.parse('2026-11-23T12:00:00Z'); + const resetIn = (hours: number) => nowMs / 1000 + hours * 3600; + const week = (percent: unknown, reset: unknown = resetIn(84)) => ({ + rate_limits: { seven_day: { used_percentage: percent, resets_at: reset } }, + }); + + beforeEach(() => { + vi.spyOn(Date, 'now').mockReturnValue(nowMs); + }); + afterEach(() => vi.restoreAllMocks()); + + function renderWeek(forecast: boolean, stdin: unknown, percent = 40, reset = resetIn(84)) { + const config: HudConfig = { enabled: true, detail: false, forecast }; + return render(makeCtx({ + stdin: stdin as StdinData, + // The version badge can query npm. It is not part of the capacity line. + config: { ...config, components: resolveComponents(config).filter((id) => id !== 'versionBadge') }, + usage: { fiveHourPercent: 30, sevenDayPercent: percent, fiveHourResetsAt: null, sevenDayResetsAt: reset }, + codexUsage: { + windows: [{ minutes: 10080, usedPercent: 12, resetsAt: resetIn(24) }], + limitReached: null, + observedAt: nowMs, + }, + })); + } + + it('keeps the pre-forecast capacity line byte for byte when off', async () => { + const line = (await renderWeek(false, week(40))).split('\n')[1]; + + expect(line).toBe( + '\x1b[2m5h \x1b[0m\x1b[32m██\x1b[0m\x1b[2m░░░░░░\x1b[0m \x1b[32m30%\x1b[0m' + + '\x1b[2m · \x1b[0m\x1b[2m7d \x1b[0m\x1b[32m███\x1b[0m\x1b[2m░░░░░\x1b[0m \x1b[32m40%\x1b[0m\x1b[2m (3d 12h)\x1b[0m' + + '\x1b[2m · \x1b[0m\x1b[2mCodex \x1b[0m\x1b[2m7d \x1b[0m\x1b[32m█\x1b[0m\x1b[2m░░░░░░░\x1b[0m \x1b[32m12%\x1b[0m\x1b[2m (1d)\x1b[0m', + ); + }); + + it.each([ + [40, 84, '→ 80% by reset'], + [70, 84, '→ 140% by reset, runs out in 1d 12h'], + [99, 162, '→ >999% by reset, runs out in 3m'], + [100, 84, '→ 200% by reset'], + [0, 84, '→ 0% by reset'], + ] as const)('adds a dim forecast after 7d and keeps each quota at %s%% used', async (percent, hours, text) => { + const reset = resetIn(hours); + const line = (await renderWeek(true, week(percent, reset), percent, reset)).split('\n')[1] ?? ''; + + expect(stripAnsi(line).split(' · ')).toEqual([ + expect.stringMatching(/^5h .{8} 30%$/), + expect.stringMatching(new RegExp(`^7d .{8} ${percent}% \\(`)), + text, + expect.stringMatching(/^Codex 7d .{8} 12% \(1d\)$/), + ]); + expect(line).toContain(`\x1b[2m${text}\x1b[0m`); + }); + + it.each([ + ['no rate_limits', {}], + ['no seven_day', { rate_limits: {} }], + ['a null seven_day', { rate_limits: { seven_day: null } }], + ['a string seven_day', { rate_limits: { seven_day: '40' } }], + ['an array seven_day', { rate_limits: { seven_day: [] } }], + ['a string percent', week('40')], + ['NaN percent', week(NaN)], + ['negative percent', week(-1)], + ['percent above 100', week(101)], + ['no reset', { rate_limits: { seven_day: { used_percentage: 40 } } }], + ['a string reset', week(40, String(resetIn(84)))], + ['a reset at now', week(40, resetIn(0))], + ['a past reset', week(40, resetIn(-1))], + ['a reset more than 8 days away', week(40, resetIn(8 * 24) + 1)], + ['a reset in milliseconds', week(40, resetIn(84) * 1000)], + ['only 5 hours elapsed', week(40, resetIn(163))], + ] as const)('keeps the output byte-identical to off with %s', async (_label, stdin) => { + // The forecast must not fall back to the gathered quota when raw stdin is invalid. + const off = await renderWeek(false, stdin); + + expect(off).toContain('Codex'); + expect(await renderWeek(true, stdin)).toBe(off); + }); +}); + describe('config', () => { - it('loadConfig returns default when no file exists', () => { - // Point HOME at a directory with no .devflow (the HUD reads $HOME/.devflow only). - const originalHome = process.env.HOME; - process.env.HOME = '/tmp/nonexistent-devflow-test-home'; - try { - const config = loadConfig(); - expect(config.enabled).toBe(true); - expect(config.detail).toBe(false); - } finally { - process.env.HOME = originalHome; - } + let tmpHome: string; + + beforeEach(() => { + tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'devflow-hud-config-')); + vi.stubEnv('HOME', tmpHome); + fs.mkdirSync(path.join(tmpHome, '.devflow')); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + fs.rmSync(tmpHome, { recursive: true, force: true }); + }); + + it('loadConfig returns defaults when no file exists', () => { + expect(loadConfig()).toEqual({ enabled: true, detail: false, forecast: false }); + }); + + it.each([ + ['{"forecast":true}', true], + ['{"forecast":false}', false], + ['{}', false], + ['{"forecast":"true"}', false], + ['{"forecast":1}', false], + ['{"forecast":true', false], + ] as const)('loads the forecast opt-in from %s as %s', (json, forecast) => { + fs.writeFileSync(getConfigPath(), json); + + expect(loadConfig().forecast).toBe(forecast); }); it('getConfigPath resolves under $HOME/.devflow and ignores an exported DEVFLOW_DIR (D-ONE-HOME, AC-10)', () => { - const originalHome = process.env.HOME; - const canary = fs.mkdtempSync(path.join(os.tmpdir(), 'hud-config-canary-')); - process.env.HOME = '/tmp/hud-config-home'; - process.env.DEVFLOW_DIR = canary; - try { - expect(getConfigPath()).toBe(path.join('/tmp/hud-config-home', '.devflow', 'hud.json')); - loadConfig(); - expect(fs.readdirSync(canary)).toEqual([]); - } finally { - process.env.HOME = originalHome; - delete process.env.DEVFLOW_DIR; - fs.rmSync(canary, { recursive: true, force: true }); - } - }); - - it('resolveComponents returns all components when enabled', () => { + const canary = fs.mkdtempSync(path.join(tmpHome, 'hud-config-canary-')); + vi.stubEnv('DEVFLOW_DIR', canary); + + expect(getConfigPath()).toBe(path.join(tmpHome, '.devflow', 'hud.json')); + loadConfig(); + expect(fs.readdirSync(canary)).toEqual([]); + }); + + it('resolveComponents returns the default components when forecast is off', () => { const config: HudConfig = { enabled: true, detail: false, forecast: false }; - expect(resolveComponents(config)).toEqual([...HUD_COMPONENTS]); + expect(resolveComponents(config)).toEqual(HUD_COMPONENTS); + }); + + it('resolveComponents adds weekForecast when HUD and forecast are on', () => { + const config: HudConfig = { enabled: true, detail: false, forecast: true }; + expect(resolveComponents(config)).toEqual([...HUD_COMPONENTS, 'weekForecast']); }); - it('resolveComponents returns only versionBadge when disabled', () => { - const config: HudConfig = { enabled: false, detail: false, forecast: false }; + it('resolveComponents returns only versionBadge when HUD is off even with forecast on', () => { + const config: HudConfig = { enabled: false, detail: false, forecast: true }; expect(resolveComponents(config)).toEqual(['versionBadge']); }); From 12191d94ee3f089a9e7c4eee211b9ab53a716b2e Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Mon, 23 Nov 2026 13:22:31 +0200 Subject: [PATCH 04/12] test(hud): cover week forecast integration Check that init keeps each stored forecast choice. Compare HUD arithmetic with the pinned tokenmeter status line. Check that the installed HUD can show a forecast from stdin alone. Task: feat/805-hud-tokenmeter-forecast --- tests/hud-installed-layout.test.ts | 18 +++++++++ tests/init-machine-switch-e2e.test.ts | 18 +++++++++ tests/tokenmeter-contract.test.ts | 57 +++++++++++++++++++++++++-- 3 files changed, 90 insertions(+), 3 deletions(-) diff --git a/tests/hud-installed-layout.test.ts b/tests/hud-installed-layout.test.ts index 1bdf720bc..d9ef17003 100644 --- a/tests/hud-installed-layout.test.ts +++ b/tests/hud-installed-layout.test.ts @@ -125,6 +125,24 @@ describe('the HUD run from the installed scripts directory', { timeout: 30_000 } expect(line).not.toContain('Codex'); }); + it('renders the week forecast from stdin with no tokenmeter state or data', () => { + const forecastHome = fs.mkdtempSync(path.join(tmp, 'forecast-home-')); + const emptyPath = fs.mkdtempSync(path.join(tmp, 'forecast-path-')); + const devflowDir = path.join(forecastHome, '.devflow'); + fs.mkdirSync(devflowDir, { mode: 0o700 }); + fs.writeFileSync(path.join(devflowDir, 'hud.json'), JSON.stringify({ enabled: true, detail: false, forecast: true })); + const resetsAt = Math.floor(Date.now() / 1000) + 84 * 3600; + + const line = runInstalledHud(tmp, { + home: forecastHome, + lookupPath: emptyPath, + stdin: { rate_limits: { seven_day: { used_percentage: 40, resets_at: resetsAt } } }, + }); + + expect(line).toContain('→ 80% by reset'); + expect(line).not.toContain('Codex'); + }); + it('renders within its own two-second budget and saves a cache miss before exit', () => { const cacheHome = path.join(tmp, 'cache-home'); const marker = path.join(cacheHome, 'render-ms'); diff --git a/tests/init-machine-switch-e2e.test.ts b/tests/init-machine-switch-e2e.test.ts index c70138bbf..5e9ad21d9 100644 --- a/tests/init-machine-switch-e2e.test.ts +++ b/tests/init-machine-switch-e2e.test.ts @@ -529,6 +529,24 @@ describe('init --hud-only over a full install (D-HUD-ONLY-PRESERVE)', () => { }, MULTI_RUN_TIMEOUT_MS); }); +describe('init preserves the HUD forecast choice', () => { + it.each([ + ['--recommended', true], + ['--recommended', false], + ['--hud-only', true], + ['--hud-only', false], + ] as const)('%s keeps forecast: %s', async (mode, forecast) => { + runInit(repoA, '--recommended', '--hud'); + const configPath = path.join(devflowDir(), 'hud.json'); + await fs.writeFile(configPath, JSON.stringify({ enabled: false, detail: true, forecast })); + + runInit(repoA, mode); + + const config: unknown = JSON.parse(await fs.readFile(configPath, 'utf-8')); + expect(config).toEqual({ enabled: true, detail: true, forecast }); + }, MULTI_RUN_TIMEOUT_MS); +}); + // ───────────────────────────────────────────────────────────────────────────── // TP-8/TP-9 — on→off re-init transitions converge every artifact // ───────────────────────────────────────────────────────────────────────────── diff --git a/tests/tokenmeter-contract.test.ts b/tests/tokenmeter-contract.test.ts index e21ea6607..02817c20c 100644 --- a/tests/tokenmeter-contract.test.ts +++ b/tests/tokenmeter-contract.test.ts @@ -1,12 +1,16 @@ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; import { existsSync } from 'node:fs'; import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { isAbsolute, join, sep } from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { installTokenmeterState } from '../src/core/tokenmeter-bin.js'; +import { installTokenmeterState, resolvePackageBin } from '../src/core/tokenmeter-bin.js'; +import { forecastPercentText, parseWeekPoint, weekForecastFrom } from '../src/hud/components/week-forecast.js'; import { gatherTokenmeterUsage } from '../src/hud/tokenmeter.js'; +import { assertTempHome } from './setup/home-isolation.js'; -// Both contract cases took 744 ms total in isolation. Allow a 7 s Node start stall per process. +// Both Codex cases took 744 ms total in isolation. Allow a 7 s Node start stall per process. const CHILD_DEADLINE_MS = 10_000; // The app-server case starts the refresher and two fake Codex processes in sequence. const REFRESH_TIMEOUT_MS = 30_000; @@ -106,3 +110,50 @@ describe.skipIf(process.platform === 'win32')('pinned tokenmeter HUD contract', ]); }); }); + +describe.skipIf(process.platform === 'win32')('pinned tokenmeter week forecast contract', { timeout: TEST_TIMEOUT_MS }, () => { + const hourMs = 3_600_000; + + it.each([ + ['with no run-out', 40, 84, ' | 80% by reset'], + ['with a run-out', 80, 82, ' | 156% by reset, runs out in 21h'], + ['two hours into the week', 40, 166, ''], + ] as const)('matches the HUD forecast %s', async (_label, percent, hoursLeft, expectedSuffix) => { + const bin = await resolvePackageBin('@dean0x/tokenmeter', 'tokenmeter'); + if (!bin.ok) assert.fail(bin.error); + const home = await mkdtemp(join(root, 'home-')); + const dataDir = await realpath(await mkdtemp(join(root, 'data-'))); + assertTempHome(home); + expect(isAbsolute(dataDir)).toBe(true); + expect(dataDir.startsWith(root + sep)).toBe(true); + + const nowMs = Date.now(); + const sevenDay = { used_percentage: percent, resets_at: Math.floor((nowMs + hoursLeft * hourMs) / 1000) }; + const child = spawnSync(process.execPath, [bin.value.binPath, 'statusline'], { + input: JSON.stringify({ rate_limits: { seven_day: sevenDay } }), + env: { HOME: home, TOKENMETER_DATA_DIR: dataDir }, + cwd: home, + encoding: 'utf-8', + timeout: CHILD_DEADLINE_MS, + }); + + expect(child.error).toBeUndefined(); + expect(child.status).toBe(0); + expect(child.stderr).toBe(''); + expect(child.stdout.trim()).toBe(`Claude wk ${percent}%${expectedSuffix}`); + + const match = /(\d+|>999)% by reset(?:, runs out in (\d+)h)?/.exec(child.stdout); + const tokenmeter = match && { + percent: `${match[1]}%`, + hours: match[2] === undefined ? undefined : Number(match[2]), + }; + const point = parseWeekPoint(sevenDay, nowMs); + assert(point, 'The HUD must accept the week reading'); + const forecast = weekForecastFrom(point, nowMs); + const hud = forecast && { + percent: forecastPercentText(forecast.atResetPct), + hours: forecast.runsOutAtMs === null ? undefined : Math.floor((forecast.runsOutAtMs - nowMs) / hourMs), + }; + expect(hud).toEqual(tokenmeter); + }); +}); From c80efc30def3ee9c045b50198cdeede1d9badf46 Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Mon, 23 Nov 2026 13:28:33 +0200 Subject: [PATCH 05/12] test(snapshot): record the HUD week forecast The install now includes an opt-in HUD week forecast component. Record its file in all three install snapshots. Task: feat/805-hud-tokenmeter-forecast --- tests/fixtures/golden/install-snapshot-all-off.txt | 1 + tests/fixtures/golden/install-snapshot-github.txt | 1 + tests/fixtures/golden/install-snapshot-jira-hipaa.txt | 1 + 3 files changed, 3 insertions(+) diff --git a/tests/fixtures/golden/install-snapshot-all-off.txt b/tests/fixtures/golden/install-snapshot-all-off.txt index 3845d7bd8..2398a89f7 100644 --- a/tests/fixtures/golden/install-snapshot-all-off.txt +++ b/tests/fixtures/golden/install-snapshot-all-off.txt @@ -368,6 +368,7 @@ d .devflow/scripts/hud/components/ - .devflow/scripts/hud/components/todo-progress.js - .devflow/scripts/hud/components/usage-quota.js - .devflow/scripts/hud/components/version-badge.js +- .devflow/scripts/hud/components/week-forecast.js - .devflow/scripts/hud/components/worktree-count.js - .devflow/scripts/hud/config.js - .devflow/scripts/hud/cost-history.js diff --git a/tests/fixtures/golden/install-snapshot-github.txt b/tests/fixtures/golden/install-snapshot-github.txt index 49799caa2..326c3bd54 100644 --- a/tests/fixtures/golden/install-snapshot-github.txt +++ b/tests/fixtures/golden/install-snapshot-github.txt @@ -378,6 +378,7 @@ d .devflow/scripts/hud/components/ - .devflow/scripts/hud/components/todo-progress.js - .devflow/scripts/hud/components/usage-quota.js - .devflow/scripts/hud/components/version-badge.js +- .devflow/scripts/hud/components/week-forecast.js - .devflow/scripts/hud/components/worktree-count.js - .devflow/scripts/hud/config.js - .devflow/scripts/hud/cost-history.js diff --git a/tests/fixtures/golden/install-snapshot-jira-hipaa.txt b/tests/fixtures/golden/install-snapshot-jira-hipaa.txt index 45aea0e34..4d70cc233 100644 --- a/tests/fixtures/golden/install-snapshot-jira-hipaa.txt +++ b/tests/fixtures/golden/install-snapshot-jira-hipaa.txt @@ -396,6 +396,7 @@ d .devflow/scripts/hud/components/ - .devflow/scripts/hud/components/todo-progress.js - .devflow/scripts/hud/components/usage-quota.js - .devflow/scripts/hud/components/version-badge.js +- .devflow/scripts/hud/components/week-forecast.js - .devflow/scripts/hud/components/worktree-count.js - .devflow/scripts/hud/config.js - .devflow/scripts/hud/cost-history.js From 7215671fa50401a16999fe60cfcf913bc72cb548 Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Mon, 23 Nov 2026 13:39:17 +0200 Subject: [PATCH 06/12] docs: describe the HUD week forecast Explain the forecast flags, input, and fallback. Record how the HUD applies detail and forecast changes with enable or disable flags. Task: feat/805-hud-tokenmeter-forecast --- CHANGELOG.md | 8 ++++++++ README.md | 4 ++++ docs/cli-reference.md | 10 ++++++++++ docs/reference/file-organization.md | 14 ++++++++++---- 4 files changed, 32 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a13d91ed0..adfe89169 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- The HUD can show a Claude week quota forecast from the current session's data. The forecast is off by default and needs no tokenmeter data. Run `devflow hud --forecast` to turn it on. Run `devflow hud --no-forecast` to turn it off. + +### Fixed + +- The `hud` command applies detail and forecast changes if you also give `--enable` or `--disable`. + --- ## [3.20.0] - 2026-11-23 diff --git a/README.md b/README.md index dabaa720e..7c88b0a6e 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,10 @@ Context ████░░░░ 42% · 5h ████░░░░ 45% (2h 15m) Opus 4.6 (1M) · 3 MCPs 2 rules · $1.42 · $18.50/wk · $62.30/mo ``` +**Claude week forecast, opt-in.** The forecast is off by default. Run `devflow hud --forecast` to show the estimated quota use at reset next to `7d`. Run `devflow hud --no-forecast` to turn it off. Run `devflow hud --status` to see your choice. `devflow init` keeps that choice. + +The HUD uses the same formula as the tokenmeter forecast, but it needs no tokenmeter data. It uses the current session's `rate_limits.seven_day` from Claude Code on stdin. The HUD treats that value as current at each update. It omits the forecast if the week data is absent or invalid. It also omits the forecast for about the first five hours of the quota week. + For Codex limits, the HUD runs `tokenmeter hud` when its cache expires, usually after 30 seconds. tokenmeter checks recent Codex session logs in the background. By default, tokenmeter can start `codex app-server` at most about once per minute per data folder. Codex can then use its stored sign-in to request the limits and the account token usage from OpenAI over HTTP. To stop the app server and the account usage request, and keep the log source, run `npx @dean0x/tokenmeter@0.3.0 config app_server off`. diff --git a/docs/cli-reference.md b/docs/cli-reference.md index d152edcd6..527950e08 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -382,8 +382,18 @@ npx devflow-kit hud --enable # Enable HUD npx devflow-kit hud --disable # Disable HUD npx devflow-kit hud --detail # Show tool/agent descriptions npx devflow-kit hud --no-detail # Hide tool/agent descriptions +npx devflow-kit hud --forecast # Show the Claude week forecast +npx devflow-kit hud --no-forecast # Hide the Claude week forecast ``` +`--status` reports the forecast choice. It applies no changes, even with other flags. You can combine a detail flag and a forecast flag with `--enable` or `--disable`. + +**Claude week forecast.** The forecast is off by default. `devflow init` keeps your choice. When the HUD and the forecast are on, dim text after `7d` shows the estimated quota use at reset. If the rounded estimate exceeds 999%, the HUD shows `>999%`. If the quota will run out by reset, the HUD also shows how long it will last. At 100% used, the HUD omits the countdown. + +The HUD uses the same formula as the tokenmeter forecast, but it needs no tokenmeter data. The forecast starts no process and reads no extra file. The HUD uses `rate_limits.seven_day` from the current Claude Code session's JSON on stdin. It treats the value as current at each update. + +The forecast needs a quota value from 0% to 100% and a future reset time in epoch seconds. The reset must be no more than eight days away. If `rate_limits` is absent or the week data is absent or invalid, the HUD omits only the forecast. The HUD also omits it for about the first five hours of the quota week. + The HUD shows the weekly Codex quota next to the Claude quota. It also shows the 5-hour Codex quota if your plan has one. When the HUD cache expires, devflow runs `tokenmeter hud` from the path that `devflow init` saves. The cache usually lasts 30 seconds. For readings at least 60 seconds old but less than 10 minutes old, the cache lasts at most 5 seconds. The command returns the latest saved data. It does not wait for Codex. A refresh is due at 60 seconds. tokenmeter checks recent Codex session logs in the background. It uses the newest data from the logs or the app server. diff --git a/docs/reference/file-organization.md b/docs/reference/file-organization.md index 3c5f1d865..01637bb36 100644 --- a/docs/reference/file-organization.md +++ b/docs/reference/file-organization.md @@ -43,8 +43,8 @@ devflow/ │ ├── hud/ # HUD module (TypeScript source) │ │ ├── index.ts # Entry point: stdin → gather → render → stdout │ │ ├── render.ts # Smart multi-line layout assembly -│ │ ├── config.ts # PRESETS, loadConfig, saveConfig -│ │ └── components/ # 15 individual component renderers +│ │ ├── config.ts # HUD_COMPONENTS, loadConfig, saveConfig +│ │ └── components/ # 17 component renderers │ ├── targets/claude-code/ # Claude Code install target │ │ ├── installer.ts # installViaFileCopy, composeScripts, installScripts │ │ ├── claude-paths.ts # getInstallationPaths @@ -367,9 +367,15 @@ An entry's content changes only by re-projection from its log row (D-LOG-CONTENT ## HUD (Heads-Up Display) -The HUD (`dist/hud/index.js`) is a configurable TypeScript status line. The fixed component list is defined in `HUD_COMPONENTS` in `src/hud/config.ts` and includes: directory, git branch, git ahead/behind, diff stats, release info, worktree count, model, context usage, version badge, session cost, usage quota, Codex quota, todo progress, config counts, and curation counts. +The HUD (`dist/hud/index.js`) is a configurable TypeScript status line. `HUD_COMPONENTS` in `src/hud/config.ts` lists these 15 default components: -Configuration: `~/.devflow/hud.json` (`{ enabled, detail }`). Manage via `devflow hud --status | --enable | --disable | --detail | --no-detail`. +- Directory, Git branch, Git ahead/behind, diff stats, release info, and worktree count. +- Model, context usage, version badge, and session cost. +- Usage quota, Codex quota, todo progress, config counts, and curation counts. + +The HUD stores `{ enabled, detail, forecast }` in `~/.devflow/hud.json`. Use `devflow hud` with `--status`, `--enable`, `--disable`, `--detail`, `--no-detail`, `--forecast`, or `--no-forecast`. + +The `weekForecast` component is off by default. The HUD adds it only when the HUD is on and `forecast` is `true`. The component uses `rate_limits.seven_day` from stdin. The `sessionDuration` component is not in the default list. The HUD reads `context_window.current_usage` and `rate_limits` from Claude Code's JSON stdin. For Codex quota, it runs `tokenmeter hud` from the path in `~/.devflow/tokenmeter.json` when the HUD cache expires. `devflow init` saves this path. The HUD omits the Codex segment if it cannot use the saved path or get a reading. See [HUD (Status Line)](../cli-reference.md#hud-status-line) for the refresh rules and the app-server switch. From fd3352743c91c4ad33fe0161ea03b704879c5391 Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Mon, 23 Nov 2026 13:44:44 +0200 Subject: [PATCH 07/12] fix: address self-review issues --- src/hud/components/week-forecast.ts | 9 ++++----- tests/hud-components.test.ts | 2 ++ tests/hud-curation-counts.test.ts | 3 ++- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/hud/components/week-forecast.ts b/src/hud/components/week-forecast.ts index 57d130edc..1dc52f308 100644 --- a/src/hud/components/week-forecast.ts +++ b/src/hud/components/week-forecast.ts @@ -33,14 +33,13 @@ export function parseWeekPoint(sevenDay: unknown, nowMs: number): WeekPoint | nu * D-TOKENMETER-HUD covers only the Codex client. Like usageQuota, this part uses stdin. */ export function weekForecastFrom({ usedPercent, resetsAtMs }: WeekPoint, nowMs: number) { - const remainingMs = resetsAtMs - nowMs; - const elapsedMs = WEEK_MS - remainingMs; + const elapsedMs = nowMs - (resetsAtMs - WEEK_MS); if (!(elapsedMs >= BURN_FREE_FRACTION * WEEK_MS)) return null; const burn = usedPercent / (elapsedMs / HOUR_MS); - const atResetPct = usedPercent + burn * (remainingMs / HOUR_MS); - const runsOutAtMs = burn > 0 ? Math.round(nowMs + ((100 - usedPercent) / burn) * HOUR_MS) : Infinity; - return { atResetPct, runsOutAtMs: runsOutAtMs <= resetsAtMs ? runsOutAtMs : null }; + const atResetPct = usedPercent + burn * ((resetsAtMs - nowMs) / HOUR_MS); + const runsOut = burn > 0 ? nowMs + ((100 - usedPercent) / burn) * HOUR_MS : Infinity; + return { atResetPct, runsOutAtMs: runsOut <= resetsAtMs ? Math.round(runsOut) : null }; } export function forecastPercentText(pct: number): string { diff --git a/tests/hud-components.test.ts b/tests/hud-components.test.ts index 65d96466b..7631fc6a3 100644 --- a/tests/hud-components.test.ts +++ b/tests/hud-components.test.ts @@ -498,6 +498,8 @@ describe('weekForecast component', () => { [80, 82, '→ 156% by reset, runs out in 21h 30m'], [70, 84, '→ 140% by reset, runs out in 1d 12h'], [50, 84, '→ 100% by reset, runs out in 3d 12h'], + // The estimate reaches 100% less than half a millisecond after reset. + [49.99999998, 84, '→ 100% by reset'], [99, 162, '→ >999% by reset, runs out in 3m'], [100, 84, '→ 200% by reset'], [0, 84, '→ 0% by reset'], diff --git a/tests/hud-curation-counts.test.ts b/tests/hud-curation-counts.test.ts index 1b66cdbe9..ae61f7b9b 100644 --- a/tests/hud-curation-counts.test.ts +++ b/tests/hud-curation-counts.test.ts @@ -57,10 +57,11 @@ function makeCtx(data: CurationCountsData | null): GatherContext { git: null, transcript: null, usage: null, + codexUsage: null, configCounts: null, curationCounts: data, costHistory: null, - config: { enabled: true, detail: false, components: [] }, + config: { enabled: true, detail: false, forecast: false, components: [] }, devflowDir: '/test/.devflow', sessionStartTime: null, terminalWidth: 120, From f3d44938d40470781488b090ae4be262f702ac42 Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Mon, 23 Nov 2026 14:12:52 +0200 Subject: [PATCH 08/12] docs: name the HUD forecast field and component Show where Devflow saves the forecast option and name the component that displays it. Task: feat/805-hud-tokenmeter-forecast --- CHANGELOG.md | 2 +- README.md | 2 +- docs/cli-reference.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index adfe89169..3cba35c03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- The HUD can show a Claude week quota forecast from the current session's data. The forecast is off by default and needs no tokenmeter data. Run `devflow hud --forecast` to turn it on. Run `devflow hud --no-forecast` to turn it off. +- The HUD can show a Claude week quota forecast from the current session's data. The forecast is off by default and needs no tokenmeter data. Run `devflow hud --forecast` to turn it on. Run `devflow hud --no-forecast` to turn it off. Devflow saves your choice in the `forecast` field of `~/.devflow/hud.json`. When the HUD and the forecast are on, the HUD adds the `weekForecast` component. ### Fixed diff --git a/README.md b/README.md index 7c88b0a6e..c3d31435a 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,7 @@ Context ████░░░░ 42% · 5h ████░░░░ 45% (2h 15m) Opus 4.6 (1M) · 3 MCPs 2 rules · $1.42 · $18.50/wk · $62.30/mo ``` -**Claude week forecast, opt-in.** The forecast is off by default. Run `devflow hud --forecast` to show the estimated quota use at reset next to `7d`. Run `devflow hud --no-forecast` to turn it off. Run `devflow hud --status` to see your choice. `devflow init` keeps that choice. +**Claude week forecast, opt-in.** The forecast is off by default. Run `devflow hud --forecast` to show the estimated quota use at reset next to `7d`. Run `devflow hud --no-forecast` to turn it off. Run `devflow hud --status` to see your choice. Devflow saves your choice in the `forecast` field of `~/.devflow/hud.json`. `devflow init` keeps that choice. When the HUD and the forecast are on, the HUD adds the `weekForecast` component. The HUD uses the same formula as the tokenmeter forecast, but it needs no tokenmeter data. It uses the current session's `rate_limits.seven_day` from Claude Code on stdin. The HUD treats that value as current at each update. It omits the forecast if the week data is absent or invalid. It also omits the forecast for about the first five hours of the quota week. diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 527950e08..fa93ec458 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -388,7 +388,7 @@ npx devflow-kit hud --no-forecast # Hide the Claude week forecast `--status` reports the forecast choice. It applies no changes, even with other flags. You can combine a detail flag and a forecast flag with `--enable` or `--disable`. -**Claude week forecast.** The forecast is off by default. `devflow init` keeps your choice. When the HUD and the forecast are on, dim text after `7d` shows the estimated quota use at reset. If the rounded estimate exceeds 999%, the HUD shows `>999%`. If the quota will run out by reset, the HUD also shows how long it will last. At 100% used, the HUD omits the countdown. +**Claude week forecast.** The forecast is off by default. Devflow saves your choice in the `forecast` field of `~/.devflow/hud.json`. `devflow init` keeps your choice. When the HUD and forecast are on, the `weekForecast` component shows estimated quota use at reset in dim text after `7d`. If the rounded estimate exceeds 999%, the HUD shows `>999%`. If the quota will run out by reset, the HUD also shows how long it will last. At 100% used, the HUD omits the countdown. The HUD uses the same formula as the tokenmeter forecast, but it needs no tokenmeter data. The forecast starts no process and reads no extra file. The HUD uses `rate_limits.seven_day` from the current Claude Code session's JSON on stdin. It treats the value as current at each update. From a30bb33f6be3e1b4c7f7723d9d0e154beaf9ba04 Mon Sep 17 00:00:00 2001 From: Dean Sharon Date: Mon, 23 Nov 2026 14:50:25 +0200 Subject: [PATCH 09/12] docs(knowledge): add hud-status-line feature knowledge base --- .../features/hud-status-line/KNOWLEDGE.md | 139 ++++++++++++++++++ .devflow/features/index.md | 1 + 2 files changed, 140 insertions(+) create mode 100644 .devflow/features/hud-status-line/KNOWLEDGE.md diff --git a/.devflow/features/hud-status-line/KNOWLEDGE.md b/.devflow/features/hud-status-line/KNOWLEDGE.md new file mode 100644 index 000000000..bd6c8826c --- /dev/null +++ b/.devflow/features/hud-status-line/KNOWLEDGE.md @@ -0,0 +1,139 @@ +--- +feature: hud-status-line +name: HUD status line +description: "Use when adding or changing a HUD component, hud.json config, the week forecast, Codex quota, or the devflow hud command. Keywords: HUD, statusLine, hud.json, weekForecast, codexQuota, tokenmeter." +category: architecture +directories: [src/hud, src/hud/components, src/cli/commands/hud.ts, src/cli/commands/init.ts] +created: 2026-11-23 +updated: 2026-11-23 +--- + +# HUD status line + +## Rules + +- **KB-INV-1** The installed HUD runs from `~/.devflow/scripts/hud/index.js` with no `package.json` and no `node_modules` above it: a file in `src/hud` imports only modules that compile into that import closure, never an npm package. +- **KB-INV-2** All I/O happens in the gather step of `src/hud/index.ts`. A component is `(ctx) => Promise` and reads only `ctx`; `null` hides it. +- **KB-INV-3** A new component needs a `ComponentId` in `types.ts`, an entry in `COMPONENT_MAP` and in `LINE_GROUPS` in `render.ts`, and an entry in `HUD_COMPONENTS` in `config.ts` only if it is on by default. +- **KB-INV-4** `render` drops a component that throws or rejects and prints the others. If `run` fails or the `OVERALL_TIMEOUT` timer fires, `main` prints nothing. +- **KB-INV-5** `weekForecastFrom` is a copy of the `forecastFrom` formula of the pinned tokenmeter release. The contract test in `tests/tokenmeter-contract.test.ts` runs the pinned `tokenmeter statusline` and compares percent and run-out hours with the HUD. +- **KB-INV-6** The week forecast reads the raw `rate_limits.seven_day` from stdin through `parseWeekPoint`, not `ctx.usage`. Any invalid input gives output byte for byte equal to the output with the forecast off. +- **KB-INV-7** Codex quota comes only through `src/hud/tokenmeter.ts`: it runs the verified local tokenmeter binary read from install state, with no shell, no HUD stdin, an allowlisted env, a byte cap, a deadline and a cache. +- **KB-INV-8** `HudConfig` has three fields (`enabled`, `detail`, `forecast`). `loadConfig` builds the object from these known keys only. `detail` and `forecast` are on only for a strict `true`; `enabled` is off only for a strict `false`. +- **KB-INV-9** Every writer of `hud.json` spreads the loaded config and changes only its own field: `{ ...loadConfig(), field }`. `devflow hud` and both HUD saves in `init.ts` follow this. +- **KB-INV-10** The config path is always `$HOME/.devflow/hud.json`. No environment variable moves it. +- **KB-INV-11** A `statusLine` is devflow's only when its command ends in `/.devflow/scripts/hud.sh` or the legacy `/.devflow/scripts/statusline.sh`. `isDevFlowStatusLine` is the one predicate; every add, remove and check goes through it. +- **KB-INV-12** With the HUD off, `resolveComponents` returns only `versionBadge`, so users still see upgrade notices. +- **KB-AP-1** Adding a field to `HudConfig` without adding it to `loadConfig`: the loader drops it, so the next `devflow hud` or `devflow init` save erases it, with no error. The same applies to a key a user adds by hand. +- **KB-AP-2** Saving a fresh object such as `saveConfig({ enabled: true })`: it resets `detail` and `forecast`. Spread the loaded config. +- **KB-AP-3** Naming `forecast` in `src/hud/index.ts`, or importing anything but colors, types and usage-quota into `week-forecast.ts`: the guard in `tests/guards/hud-usage-source.test.ts` fails. The forecast must stay a no-I/O component. +- **KB-AP-4** Reading `ctx.usage` in the forecast: `index.ts` clamps it to 0-100, so an out-of-range stdin value would show a forecast instead of hiding it. +- **KB-AP-5** Opening a network connection, reading a credential file, looking up `tokenmeter` on PATH or reading Codex logs in `src/hud`: the same guard rejects each one. +- **KB-AP-6** Building a child env by copying `process.env` and deleting keys: use the `ENV_KEYS` allowlist in `tokenmeter.ts` and the filtered PATH, and keep `NODE_OPTIONS` out. +- **KB-AP-7** Adding a component to `COMPONENT_MAP` but not to `LINE_GROUPS`: TypeScript does not catch it and the component never shows, because `render` walks only `LINE_GROUPS`. +- **KB-AP-8** Detecting a user turn in the transcript by type `human`: Claude Code writes `user`. Build parser fixtures from sampled real entries. +- **KB-AP-9** Awaiting the Codex cache write inside the render budget: `index.ts` passes `waitForCache: false`, and the installed-layout test checks that the cache file exists after the process exits. + +## Overview + +The HUD is the status line that Claude Code starts through `~/.devflow/scripts/hud.sh`. That script runs `node hud/index.js`. Claude Code sends one JSON object on stdin (model, cwd, context window, cost, session id, transcript path and `rate_limits`). The HUD prints up to five ANSI lines. + +The flow has three steps. `src/hud/index.ts` reads stdin and `hud.json`, resolves the enabled component ids, and gathers only the data those components need (git, transcript, ledger counts, Codex quota) in parallel. Then it builds a `GatherContext`. `render.ts` then runs every enabled component in parallel and joins the results by line group. The `devflow hud` command (`src/cli/commands/hud.ts`) edits `hud.json` and the `statusLine` entry in `settings.json`. It never renders. + +## Components and config + +`HUD_COMPONENTS` in `config.ts` is the default list, in display order. The test `HUD_COMPONENTS has 15 components` in `tests/hud-render.test.ts` pins its length. A second test pins `codexQuota` right after `usageQuota`. + +Two components are outside the default list: + +- `weekForecast` is opt-in. `resolveComponents` appends it only when the HUD is on and `forecast` is `true`. Run `devflow hud --forecast` or `--no-forecast` to change it. +- `sessionDuration` is in the type, the map and the tests, but no config path enables it. `resolveComponents` never returns it. + +`detail` is saved by `devflow hud --detail` and shown by `--status`. No file in `src/hud` reads it today. + +`LINE_GROUPS` in `render.ts` sets the layout. The first line holds directory and git parts. The second is the capacity line: `contextUsage`, `usageQuota`, `weekForecast`, `codexQuota`, `todoProgress`. The third holds `model`, `configCounts` and `sessionCost`. `curationCounts` and `versionBadge` each get their own line. A component whose text contains a newline gets its own line, and the single-line parts before it flush first. Parts join with a dim dot separator. + +## Week forecast + +`weekForecast` shows `→ N% by reset` and, when the quota runs out before the reset, `, runs out in