Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor([issue-2484]): apply /simplify review findings
[._.]/ Adam Eivy31cee2492b29
diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsxindex b54bf16a2f..85898d3466 100644--- a/client/src/pages/UsagePage.jsx+++ b/client/src/pages/UsagePage.jsx@@ -3,6 +3,7 @@ import { useSearchParams } from 'react-router-dom';import { RefreshCw, Clock, AlertTriangle } from 'lucide-react';import * as api from '../services/api';import BrailleSpinner from '../components/BrailleSpinner';+import Pill from '../components/ui/Pill';import { formatCompactCount } from '../utils/formatters';const PERIOD_OPTIONS = [@@ -71,9 +72,7 @@ function ProviderQuotaCard({ quota }) {<div className="flex items-center justify-between mb-2"><h3 className="text-base font-semibold text-white">{quota.label}</h3>{quota.plan && quota.plan !== 'unknown' && (- <span className="text-[10px] sm:text-xs uppercase tracking-wide text-gray-400 border border-port-border rounded-full px-2 py-0.5">- {quota.plan}- </span>+ <Pill tone="context" size="xs">{quota.plan}</Pill>)}</div>@@ -231,15 +230,13 @@ function ProviderCostRows({ provider }) {<td className="py-2 pr-2"><span className="font-medium">{provider.name}</span>{provider.free && (- <span className="ml-2 text-[10px] uppercase tracking-wide text-port-success border border-port-success/40 rounded-full px-1.5 py-0.5">- Local — free- </span>+ <Pill tone="success" size="xs" className="ml-2 uppercase tracking-wide">Local — free</Pill>)}</td><td className="py-2 px-2 text-right">{formatNumber(provider.sessions)}</td><td className="py-2 px-2 text-right">{formatNumber(provider.tokensIn)}</td><td className="py-2 px-2 text-right">{formatNumber(provider.tokensOut)}</td>- <td className="py-2 pl-2 text-right">{provider.free ? formatCost(0) : formatCost(provider.estimatedCost)}</td>+ <td className="py-2 pl-2 text-right">{formatCost(provider.estimatedCost)}</td></tr>{provider.models.map((m) => (<tr key={m.model} className="text-gray-400">@@ -250,7 +247,7 @@ function ProviderCostRows({ provider }) {<td className="py-1.5 px-2 text-right text-xs">{formatNumber(m.tokensIn)}</td><td className="py-1.5 px-2 text-right text-xs">{formatNumber(m.tokensOut)}</td><td className="py-1.5 pl-2 text-right text-xs" title={approxMark(m.rateMatch) ? 'Approximate — no exact published rate for this model id' : undefined}>- {approxMark(m.rateMatch)}{m.rateMatch === 'free' ? formatCost(0) : formatCost(m.estimatedCost)}+ {approxMark(m.rateMatch)}{formatCost(m.estimatedCost)}</td></tr>))}diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 2293dbc9e6..b00f045ad5 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -105,12 +105,6 @@ export const resetUsage = () => request('/usage', { method: 'DELETE' });export const getProviderUsage = ({ refresh = false, ...options } = {}) =>request(`/usage/providers${refresh ? '?refresh=1' : ''}`, { silent: true, ...options });-// Claude Code subscription rate-limit usage (parsed from the CLI `/usage` output).-// Callers own their own inline error UI, so default to silent to avoid a toast-// on machines without the `claude` CLI.-export const getClaudeCodeUsage = ({ refresh = false, ...options } = {}) =>- request(`/usage/claude-code${refresh ? '?refresh=1' : ''}`, { silent: true, ...options });-// Backupexport const getBackupStatus = (options) => request('/backup/status', options);export const triggerBackup = (options) => request('/backup/run', { method: 'POST', ...options });diff --git a/server/index.js b/server/index.jsindex 1816f91e03..aec2148b2f 100644--- a/server/index.js+++ b/server/index.js@@ -5,7 +5,7 @@ import { dirname, join } from 'path';import { PATHS } from './lib/fileUtils.js';import { resolveInstallRoot } from './lib/dataRoot.js';import { PORTS } from './lib/ports.js';-import { estimateTokens, CHARS_PER_TOKEN } from './lib/contextBudget.js';+import { estimateTokens, estimateTokensFromChars } from './lib/contextBudget.js';import { existsSync } from 'fs';import { createTailscaleServers } from '../lib/tailscale-https.js';import { certPaths } from '../lib/certPaths.js';@@ -292,7 +292,7 @@ const aiToolkitHooks = {},onRunCompleted: (metadata, output) => {const estimatedTokens = estimateTokens(output);- const inputTokens = Math.ceil((metadata.promptLength || 0) / CHARS_PER_TOKEN);+ const inputTokens = estimateTokensFromChars(metadata.promptLength);recordMessages(metadata.providerId, metadata.model, 1, estimatedTokens, inputTokens).catch(err => {console.error(`❌ Failed to record usage: ${err.message}`);});diff --git a/server/lib/README.md b/server/lib/README.mdindex 7df07e4785..e358f83aad 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -97,6 +97,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `mediaModels.js` | Single source of truth for image/video model metadata. || `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, model-flag scan helpers). || `modelPricing.js` | Per-model API billing rates for the /devtools/usage cost estimates — `resolveModelRates(providerId, model)` (exact → family regex → provider default → blended fallback, with a `matched` tier), `isFreeProvider` (ollama/lmstudio/`ollamaBacked`/localhost = free), `estimateCostUsd`, `PRICING_AS_OF`. Informational only (PortOS runs on subscriptions); excludes cache/batch/tier discounts. |+| `usageRange.js` | `resolveUsageRange({ period, from, to })` — pure period→inclusive-YYYY-MM-DD range resolution for the usage cost report (explicit dates win; `all` unbounded; default 7d). || `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring the models map under `provider.ollama.models` (bare ids) for Ollama-backed OpenCode providers. Fixes --model rejection. || `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. || `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. |@@ -104,7 +105,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `runners.js` | Image-runner family constants. || `codexAssistantExtract.js` | Strip Codex CLI banner + echoed metadata from session transcript. || `codexCliOutput.js` | Network/system error patterns for `agentErrorAnalysis.js`. |-| `contextBudget.js` | Context-window budgeter for editorial passes. `estimateTokens` (chars/4), `usableInputTokens`, `manuscriptContentBudgetChars` (single-block content cap floored at a manuscript minimum so a standalone stage trims to fit a small window instead of overflowing a fixed 48–60K floor, #1488), `planManuscriptPass({ contextWindow, sections })` → `{ mode: 'whole' \| 'chunked', chunks }`. Also `fitContextToManuscriptFloor`/`capContextOverhead`/`trimContextToBudget` — trim a re-sent context block (scene map, character arcs, …) so a large reverse outline on a small window can't starve the manuscript chunk below a budget floor (#1459). Decides whole-manuscript vs chunked given a model's window. |+| `contextBudget.js` | Context-window budgeter for editorial passes. `estimateTokens`/`estimateTokensFromChars` (chars/4), `usableInputTokens`, `manuscriptContentBudgetChars` (single-block content cap floored at a manuscript minimum so a standalone stage trims to fit a small window instead of overflowing a fixed 48–60K floor, #1488), `planManuscriptPass({ contextWindow, sections })` → `{ mode: 'whole' \| 'chunked', chunks }`. Also `fitContextToManuscriptFloor`/`capContextOverhead`/`trimContextToBudget` — trim a re-sent context block (scene map, character arcs, …) so a large reverse outline on a small window can't starve the manuscript chunk below a budget floor (#1459). Decides whole-manuscript vs chunked given a model's window. || `ansiStrip.js` | Streaming ANSI / control-byte stripper. || `hfToken.js` | HuggingFace token resolution (settings > env > CLI). || `hfErrors.js` | Parse huggingface_hub gated-access errors: `isGatedRepoError(text)` classifies a failure as gated (403/restricted), `extractGatedRepo(text)` → `owner/name` (or null) for the UI's license deep-link. Shared by the image runner and MIDI transcription (LoRA trainer keeps its own regex to also match bare 401). Pure. |diff --git a/server/lib/contextBudget.js b/server/lib/contextBudget.jsindex 0e852044f9..b234121cd0 100644--- a/server/lib/contextBudget.js+++ b/server/lib/contextBudget.js@@ -37,6 +37,10 @@ export const FALLBACK_CONTEXT_WINDOW = 8_192;/** chars/4 token estimate. Conservative (real tokenizers pack denser). */export const estimateTokens = (text) => Math.ceil(String(text ?? '').length / CHARS_PER_TOKEN);+/** Same heuristic for a char *count* (e.g. a run's stored `promptLength`) —+ * keeps every token-estimation site on one formula. */+export const estimateTokensFromChars = (chars) => Math.ceil((chars || 0) / CHARS_PER_TOKEN);+// Token cost of the separator `sectionsCorpus` inserts between packed sections// (mirrors its `\n\n---\n\n` join). The packer budgets for it so a chunk packed// to the token limit doesn't overflow `usableChars` by the separators and getdiff --git a/server/lib/index.js b/server/lib/index.jsindex 5750b0cc60..e97d27e6cd 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -196,6 +196,7 @@ export * from './issueLength.js';export * from './mediaItemKey.js';export * from './modelPricing.js';export * from './navManifest.js';+export * from './usageRange.js';export * from './personaTraitBlend.js';export * from './pipelineIssueOrder.js';export * from './postAdaptive.js';diff --git a/server/lib/modelPricing.js b/server/lib/modelPricing.jsindex c80a40165c..c5b04cd934 100644--- a/server/lib/modelPricing.js+++ b/server/lib/modelPricing.js@@ -58,11 +58,19 @@ const EXACT_RATES = {'gemini-2.5-flash-lite': [0.1, 0.4],};+// Exact keys sorted longest-first for the substring pass in+// resolveModelRates — a suffixed/prefixed variant of a known id+// (`gpt-5.6-terra-2026-06-01`, `global.anthropic.claude-opus-4-8`) resolves to+// its base rates without needing a hand-written regex per model, and+// longest-first makes `gpt-5.5-pro` win over `gpt-5.5`. (Keys are all+// lowercase, so matching against a lowercased id needs no re-mapping.)+const EXACT_KEYS_BY_LENGTH = Object.keys(EXACT_RATES).sort((a, b) => b.length - a.length);+/*** Ordered family rules — first regex that matches the model id wins. Covers- * CLI shorthand (`opus`, `sonnet`), versioned ids the exact table doesn't- * list, Bedrock-prefixed ids, and the `*-configured-default` sentinels (the- * sentinel strings contain their provider family name).+ * CLI shorthand (`opus`, `sonnet`), family names the exact table doesn't+ * list, and the `*-configured-default` sentinels (the sentinel strings+ * contain their provider family name).*/const FAMILY_RULES = [{ test: /fable|mythos/i, rateModel: 'claude-fable-5' },@@ -70,21 +78,11 @@ const FAMILY_RULES = [{ test: /sonnet[-.]?5/i, rateModel: 'claude-sonnet-5' },{ test: /sonnet/i, rateModel: 'claude-sonnet-4-5' },{ test: /haiku/i, rateModel: 'claude-haiku-4-5' },- { test: /gpt-5\.6-sol/i, rateModel: 'gpt-5.6-sol' },- { test: /gpt-5\.6-terra/i, rateModel: 'gpt-5.6-terra' },- { test: /gpt-5\.6-luna/i, rateModel: 'gpt-5.6-luna' },{ test: /codex/i, rateModel: 'gpt-5.3-codex' },- { test: /gpt-5\.5-pro/i, rateModel: 'gpt-5.5-pro' },- { test: /gpt-5\.4-mini/i, rateModel: 'gpt-5.4-mini' },- { test: /gpt-5\.4-nano/i, rateModel: 'gpt-5.4-nano' },{ test: /gpt/i, rateModel: 'gpt-5.4' },{ test: /grok-build/i, rateModel: 'grok-build-0.1' },- { test: /grok-4\.(3|20)/i, rateModel: 'grok-4.3' },+ { test: /grok-4\.20/i, rateModel: 'grok-4.3' },{ test: /grok/i, rateModel: 'grok-4.5' },- { test: /gemini-3\.5-flash/i, rateModel: 'gemini-3.5-flash' },- { test: /gemini-2\.5-pro/i, rateModel: 'gemini-2.5-pro' },- { test: /gemini-2\.5-flash-lite/i, rateModel: 'gemini-2.5-flash-lite' },- { test: /gemini-2\.5-flash/i, rateModel: 'gemini-2.5-flash' },{ test: /gemini|antigravity/i, rateModel: 'gemini-3.1-pro-preview' },];@@ -119,6 +117,11 @@ export function resolveModelRates(providerId, model) {return { ...toRates(id), matched: 'exact' };}if (id) {+ const lower = id.toLowerCase();+ const embedded = EXACT_KEYS_BY_LENGTH.find((key) => lower.includes(key));+ if (embedded) {+ return { ...toRates(embedded), matched: 'family' };+ }for (const rule of FAMILY_RULES) {if (rule.test.test(id)) {return { ...toRates(rule.rateModel), matched: 'family' };@@ -134,7 +137,11 @@ export function resolveModelRates(providerId, model) {return { ...FALLBACK_RATES, matched: 'fallback' };}-const LOCALHOST_ENDPOINT = /^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(:|\/|$)/i;+// Mirrors promptRunner.js's LOCAL_ENDPOINT_RE (scheme optional, unbracketed+// ::1 accepted) so the concurrency gate and the cost report agree on what+// "local" means. Duplicated rather than imported because modelPricing must+// stay a leaf module — promptRunner pulls in the whole runner/provider graph.+const LOCALHOST_ENDPOINT = /^(https?:\/\/)?(localhost|127\.0\.0\.1|0\.0\.0\.0|\[?::1\]?)(:|\/|$)/i;const FREE_ID = /ollama|lmstudio|lm-studio/i;/**@@ -151,7 +158,7 @@ export function isFreeProvider(providerOrId) {const p = providerOrId;if (p.ollamaBacked === true) return true;if (FREE_ID.test(p.id || '') || FREE_ID.test(p.command || '')) return true;- if (typeof p.endpoint === 'string' && LOCALHOST_ENDPOINT.test(p.endpoint)) return true;+ if (typeof p.endpoint === 'string' && LOCALHOST_ENDPOINT.test(p.endpoint.trim())) return true;return false;}diff --git a/server/lib/usageRange.js b/server/lib/usageRange.jsnew file mode 100644index 0000000000..55035b1e8e--- /dev/null+++ b/server/lib/usageRange.js@@ -0,0 +1,24 @@+/**+ * Date-range resolution for the /devtools/usage cost report — pure, shared by+ * the usage route and any future consumer (dashboard widget, voice tool,+ * scheduled report) that needs "period → inclusive YYYY-MM-DD range".+ */++const PERIOD_DAYS = { '7d': 7, '30d': 30, '90d': 90 };++/**+ * Resolve validated usage-query params to an inclusive { from, to } date range+ * (YYYY-MM-DD, null = unbounded). Explicit from/to win; otherwise a preset+ * period counting back from today (default 7d, matching the page's charts).+ * Dates use the UTC calendar day, consistent with usage.js's dailyActivity keys.+ * @param {{ period?: '7d'|'30d'|'90d'|'all', from?: string, to?: string }} query+ * @returns {{ from: string|null, to: string|null }}+ */+export function resolveUsageRange({ period, from, to } = {}) {+ if (from || to) return { from: from || null, to: to || null };+ if (period === 'all') return { from: null, to: null };+ const days = PERIOD_DAYS[period] || PERIOD_DAYS['7d'];+ const start = new Date();+ start.setDate(start.getDate() - (days - 1));+ return { from: start.toISOString().split('T')[0], to: null };+}diff --git a/server/lib/usageRange.test.js b/server/lib/usageRange.test.jsnew file mode 100644index 0000000000..3d8952da2e--- /dev/null+++ b/server/lib/usageRange.test.js@@ -0,0 +1,28 @@+import { describe, it, expect } from 'vitest';+import { resolveUsageRange } from './usageRange.js';++describe('resolveUsageRange', () => {+ it('counts period days back from today inclusive', () => {+ const { from, to } = resolveUsageRange({ period: '30d' });+ const expected = new Date();+ expected.setDate(expected.getDate() - 29);+ expect(from).toBe(expected.toISOString().split('T')[0]);+ expect(to).toBeNull();+ });++ it('defaults to 7d when nothing is given', () => {+ const { from } = resolveUsageRange();+ const expected = new Date();+ expected.setDate(expected.getDate() - 6);+ expect(from).toBe(expected.toISOString().split('T')[0]);+ });++ it('resolves period=all to an unbounded range', () => {+ expect(resolveUsageRange({ period: 'all' })).toEqual({ from: null, to: null });+ });++ it('lets explicit dates win over period', () => {+ expect(resolveUsageRange({ period: '90d', from: '2026-01-01' })).toEqual({ from: '2026-01-01', to: null });+ expect(resolveUsageRange({ from: '2026-01-01', to: '2026-02-01' })).toEqual({ from: '2026-01-01', to: '2026-02-01' });+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex ad3bf46143..7fac65161f 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -631,6 +631,16 @@ export const usageQuerySchema = z.object({to: isoDay.optional()}).refine((q) => !(q.from && q.to) || q.from <= q.to, { message: 'from must be on or before to' });+/** Body for POST /api/usage/messages — token counts persist forever, so+ * reject non-integer/negative garbage instead of coercing it into counters. */+export const usageMessagesSchema = z.object({+ providerId: z.string().min(1),+ model: z.string().nullish(),+ messageCount: z.number().int().nonnegative(),+ tokenCount: z.number().int().nonnegative().optional().default(0),+ inputTokenCount: z.number().int().nonnegative().optional().default(0)+});+/*** Validate data against a Zod schema, throwing on failure.* Returns parsed data on success, throws ServerError on failure.diff --git a/server/routes/usage.js b/server/routes/usage.jsindex 5375572067..bdb27c1d81 100644--- a/server/routes/usage.js+++ b/server/routes/usage.js@@ -4,26 +4,11 @@ import { getClaudeCodeUsage } from '../services/claudeCodeUsage.js';import { getProviderQuotas } from '../services/providerUsage.js';import { getAllProviders } from '../services/providers.js';import { asyncHandler } from '../lib/errorHandler.js';-import { validateRequest, usageQuerySchema } from '../lib/validation.js';+import { validateRequest, usageQuerySchema, usageMessagesSchema } from '../lib/validation.js';+import { resolveUsageRange } from '../lib/usageRange.js';const router = Router();-const PERIOD_DAYS = { '7d': 7, '30d': 30, '90d': 90 };--/**- * Resolve validated query params to an inclusive { from, to } date range- * (YYYY-MM-DD, null = unbounded). Explicit from/to win; otherwise a preset- * period counting back from today (default 7d, matching the page's charts).- */-export function resolveUsageRange({ period, from, to } = {}) {- if (from || to) return { from: from || null, to: to || null };- if (period === 'all') return { from: null, to: null };- const days = PERIOD_DAYS[period] || PERIOD_DAYS['7d'];- const start = new Date();- start.setDate(start.getDate() - (days - 1));- return { from: start.toISOString().split('T')[0], to: null };-}-// GET /api/usage - Usage summary + cost report. Accepts ?period=7d|30d|90d|all// or an explicit ?from/?to (YYYY-MM-DD, inclusive) for the report window.router.get('/', asyncHandler(async (req, res) => {@@ -67,8 +52,8 @@ router.post('/session', asyncHandler(async (req, res) => {// POST /api/usage/messages - Record messagesrouter.post('/messages', asyncHandler(async (req, res) => {- const { providerId, model, messageCount, tokenCount, inputTokenCount } = req.body;- await usage.recordMessages(providerId, model, messageCount, tokenCount, inputTokenCount || 0);+ const { providerId, model, messageCount, tokenCount, inputTokenCount } = validateRequest(usageMessagesSchema, req.body);+ await usage.recordMessages(providerId, model, messageCount, tokenCount, inputTokenCount);res.json({ success: true });}));diff --git a/server/routes/usage.test.js b/server/routes/usage.test.jsindex 4b95116193..49fcb5cc87 100644--- a/server/routes/usage.test.js+++ b/server/routes/usage.test.js@@ -27,7 +27,7 @@ vi.mock('../services/claudeCodeUsage.js', () => ({import * as usage from '../services/usage.js';import { getAllProviders } from '../services/providers.js';import { getProviderQuotas } from '../services/providerUsage.js';-import usageRoutes, { resolveUsageRange } from './usage.js';+import usageRoutes from './usage.js';const buildApp = () => {const app = express();@@ -99,18 +99,12 @@ describe('usage routes', () => {expect(getProviderQuotas).toHaveBeenCalledWith({ refresh: true });});- describe('resolveUsageRange', () => {- it('counts period days back from today inclusive', () => {- const { from, to } = resolveUsageRange({ period: '30d' });- const expected = new Date();- expected.setDate(expected.getDate() - 29);- expect(from).toBe(expected.toISOString().split('T')[0]);- expect(to).toBeNull();- });-- it('lets explicit dates win over period', () => {- expect(resolveUsageRange({ period: '90d', from: '2026-01-01' })).toEqual({ from: '2026-01-01', to: null });- });+ it('POST /api/usage/messages rejects negative or non-integer token counts', async () => {+ const res = await request(buildApp())+ .post('/api/usage/messages')+ .send({ providerId: 'p1', model: 'm', messageCount: 1, tokenCount: -5 });+ expect(res.status).toBe(400);+ expect(usage.recordMessages).not.toHaveBeenCalled();});it('GET /api/usage/raw returns the raw usage data', async () => {diff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.jsindex 45560f9ab3..1ee145bf96 100644--- a/server/services/agentRunTracking.js+++ b/server/services/agentRunTracking.js@@ -10,7 +10,7 @@ import { v4 as uuidv4 } from '../lib/uuid.js';import { recordSession, recordMessages } from './usage.js';import { bufferedSpawn } from '../lib/bufferedSpawn.js';import { atomicWrite, ensureDir, pathExists, readJSONFile, PATHS } from '../lib/fileUtils.js';-import { estimateTokens, CHARS_PER_TOKEN } from '../lib/contextBudget.js';+import { estimateTokens, estimateTokensFromChars } from '../lib/contextBudget.js';const RUNS_DIR = PATHS.runs;@@ -137,7 +137,7 @@ export async function completeAgentRun(runId, output, exitCode, duration, errorA// Record usage for successful CoS agent runs (token counts are estimated)if (exitCode === 0 && metadata.providerId && metadata.model) {const estimatedTokens = estimateTokens(output);- const inputTokens = Math.ceil((metadata.promptLength || 0) / CHARS_PER_TOKEN);+ const inputTokens = estimateTokensFromChars(metadata.promptLength);recordMessages(metadata.providerId, metadata.model, 1, estimatedTokens, inputTokens).catch(err => {console.error(`❌ Failed to record usage: ${err.message}`);});diff --git a/server/services/providerUsage.js b/server/services/providerUsage.jsindex 52885a9e29..0724fedbec 100644--- a/server/services/providerUsage.js+++ b/server/services/providerUsage.js@@ -4,6 +4,7 @@ import { join } from 'path';import { getAllProviders } from './providers.js';import { getClaudeCodeUsage } from './claudeCodeUsage.js';import { commandBasename, isClaudeCommand } from '../lib/providerModels.js';+import { isGrokCommand } from '../lib/grok.js';/*** Provider subscription-quota adapters for /devtools/usage — one card per@@ -22,15 +23,12 @@ import { commandBasename, isClaudeCommand } from '../lib/providerModels.js';* usage page — never at server boot — and none of them consume tokens (the* Claude `/usage` print-mode call is 0-token; the Codex adapter only reads* local session logs).+ *+ * No registry-level cache: the claude adapter already carries its own 60s+ * cache + single-flight inside claudeCodeUsage.js, and the codex adapter is a+ * bounded local-file tail read (1-2 leaf dirs on a typical layout).*/-const CACHE_TTL_MS = 60_000;--// family -> { data, at }-const cache = new Map();-// family -> Promise (single-flight)-const inflight = new Map();-// --- Codex: parse rate-limit telemetry out of local session logs -----------//// The Codex CLI has no queryable usage command, but every session appends@@ -115,23 +113,39 @@ export function mapCodexQuota(rateLimits, timestamp) {};}-/** Newest-first rollout log paths under <codexHome>/sessions (bounded scan). */+/**+ * Newest-first rollout log paths under <codexHome>/sessions. Codex lays+ * sessions out as `sessions/YYYY/MM/DD/rollout-<ISO-timestamp>-<uuid>.jsonl`,+ * so directory and file names both sort chronologically — walk them in+ * descending lexicographic order and stop as soon as the scan limit is hit+ * (typically 1-2 leaf dirs touched, zero stat calls).+ */async function listCodexRolloutFiles(codexHome) {const sessionsDir = join(codexHome, 'sessions');+ const newestFirstDirs = async (dir) =>+ (await readdir(dir, { withFileTypes: true }).catch(() => []))+ .filter((e) => e.isDirectory())+ .map((e) => e.name)+ .sort()+ .reverse();+const files = [];- const walk = async (dir) => {- const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);- for (const entry of entries) {- const p = join(dir, entry.name);- if (entry.isDirectory()) await walk(p);- else if (entry.name.startsWith('rollout-') && entry.name.endsWith('.jsonl')) files.push(p);+ for (const year of await newestFirstDirs(sessionsDir)) {+ for (const month of await newestFirstDirs(join(sessionsDir, year))) {+ for (const day of await newestFirstDirs(join(sessionsDir, year, month))) {+ const dayDir = join(sessionsDir, year, month, day);+ const names = (await readdir(dayDir).catch(() => []))+ .filter((n) => n.startsWith('rollout-') && n.endsWith('.jsonl'))+ .sort()+ .reverse();+ for (const name of names) {+ files.push(join(dayDir, name));+ if (files.length >= CODEX_SCAN_FILE_LIMIT) return files;+ }+ }}- };- await walk(sessionsDir);- const withTimes = await Promise.all(- files.map(async (f) => ({ f, mtime: (await stat(f).catch(() => null))?.mtimeMs || 0 }))- );- return withTimes.sort((a, b) => b.mtime - a.mtime).slice(0, CODEX_SCAN_FILE_LIMIT).map((e) => e.f);+ }+ return files;}async function readFileTail(file, bytes) {@@ -227,7 +241,7 @@ const FAMILIES = [{id: 'grok',label: 'Grok',- matches: (p) => commandBasename(p.command) === 'grok' || /grok/i.test(p.id || ''),+ matches: (p) => isGrokCommand(p.command) || /grok/i.test(p.id || ''),fetch: unsupported('grok', 'Grok', 'The Grok CLI and xAI API do not expose remaining-quota telemetry.')}];@@ -238,37 +252,22 @@ export function resolveEnabledFamilies(providers) {return FAMILIES.filter((family) => enabled.some((p) => family.matches(p)));}-async function fetchFamilyQuota(family, { refresh }) {- if (!refresh && cache.has(family.id) && Date.now() - cache.get(family.id).at < CACHE_TTL_MS) {- return cache.get(family.id).data;- }- if (inflight.has(family.id)) return inflight.get(family.id);-- const run = Promise.resolve(family.fetch({ refresh }))- .then((data) => {- cache.set(family.id, { data, at: Date.now() });- return data;- })- .catch((err) => ({- family: family.id,- label: family.label,- supported: true,- limits: [],- activity: [],- approximate: false,- fetchedAt: new Date().toISOString(),- error: err?.message || String(err)- }))- .finally(() => inflight.delete(family.id));-- inflight.set(family.id, run);- return run;-}+const fetchFamilyQuota = (family, { refresh }) =>+ Promise.resolve(family.fetch({ refresh })).catch((err) => ({+ family: family.id,+ label: family.label,+ supported: true,+ limits: [],+ activity: [],+ approximate: false,+ fetchedAt: new Date().toISOString(),+ error: err?.message || String(err)+ }));/*** Quota status for every enabled provider family. `refresh: true` bypasses- * the per-family 60s cache. Never rejects — per-family failures surface as- * `error` entries.+ * the claude adapter's 60s cache. Never rejects — per-family failures surface+ * as `error` entries.*/export async function getProviderQuotas({ refresh = false } = {}) {const providers = await getAllProviders();diff --git a/server/services/usage.js b/server/services/usage.jsindex e848ec081f..99756db389 100644--- a/server/services/usage.js+++ b/server/services/usage.js@@ -104,14 +104,14 @@ export async function recordSession(providerId, providerName, model) {// Track by providerif (!usageData.byProvider[providerId]) {- usageData.byProvider[providerId] = { name: providerName, sessions: 0, messages: 0, tokens: 0, tokensIn: 0, tokensOut: 0 };+ usageData.byProvider[providerId] = { name: providerName, sessions: 0, messages: 0, tokens: 0 };}usageData.byProvider[providerId].sessions++;// Track by modelif (model) {if (!usageData.byModel[model]) {- usageData.byModel[model] = { sessions: 0, messages: 0, tokens: 0, tokensIn: 0, tokensOut: 0 };+ usageData.byModel[model] = { sessions: 0, messages: 0, tokens: 0 };}usageData.byModel[model].sessions++;}@@ -148,40 +148,32 @@ export async function recordMessages(providerId, model, messageCount, outputTokeusageData.totalTokens.input += inputTokens;}- // Track by provider (legacy `tokens` stays output-only for old readers)+ // Track by provider / by model (the legacy all-time entries keep their+ // output-only `tokens` field for old readers — the in/out split lives only+ // in the day buckets, which is what the cost report aggregates)if (usageData.byProvider[providerId]) {- const p = usageData.byProvider[providerId];- p.messages += messageCount;- p.tokens = (p.tokens || 0) + outputTokens;- p.tokensIn = (p.tokensIn || 0) + inputTokens;- p.tokensOut = (p.tokensOut || 0) + outputTokens;+ usageData.byProvider[providerId].messages += messageCount;+ usageData.byProvider[providerId].tokens = (usageData.byProvider[providerId].tokens || 0) + outputTokens;}-- // Track by modelif (model && usageData.byModel[model]) {- const m = usageData.byModel[model];- m.messages += messageCount;- m.tokens = (m.tokens || 0) + outputTokens;- m.tokensIn = (m.tokensIn || 0) + inputTokens;- m.tokensOut = (m.tokensOut || 0) + outputTokens;+ usageData.byModel[model].messages += messageCount;+ usageData.byModel[model].tokens = (usageData.byModel[model].tokens || 0) + outputTokens;}// Track daily (a run can finish on a different day than it started — create// the day/provider buckets if missing rather than gating on existence)+ const bumpDayBucket = (bucket) => {+ bucket.messages += messageCount;+ bucket.tokensIn += inputTokens;+ bucket.tokensOut += outputTokens;+ };const day = todayBucket();day.messages = (day.messages || 0) + messageCount;day.tokens = (day.tokens || 0) + outputTokens;const providerName = usageData.byProvider[providerId]?.name;const providerDay = providerDayBucket(day, providerId, providerName);- providerDay.messages += messageCount;- providerDay.tokensIn += inputTokens;- providerDay.tokensOut += outputTokens;- if (model) {- const modelDay = modelDayBucket(providerDay, model);- modelDay.messages += messageCount;- modelDay.tokensIn += inputTokens;- modelDay.tokensOut += outputTokens;- }+ bumpDayBucket(providerDay);+ if (model) bumpDayBucket(modelDayBucket(providerDay, model));await saveUsage();}@@ -276,6 +268,11 @@ function findLongestStreak(dailyActivity) {const roundCents = (n) => Math.round(n * 100) / 100;+// The historical flat blended rate the all-time `estimatedCost` field has+// always used — kept so that field's meaning doesn't silently change for+// existing consumers. The accurate per-model number is `report.totals`.+const LEGACY_BLENDED_RATES = { inputPer1M: 3.0, outputPer1M: 15.0 };+/*** Aggregate the per-day per-provider per-model buckets over a date range into* a cost report. `from`/`to` are inclusive `YYYY-MM-DD` strings (null = open@@ -440,7 +437,7 @@ export function getUsageSummary({ from = null, to = null, providers = [] } = {})totalMessages: usageData.totalMessages,totalToolCalls: usageData.totalToolCalls,totalTokens: usageData.totalTokens,- estimatedCost: report.totals.estimatedCost,+ estimatedCost: roundCents(estimateCostUsd(usageData.totalTokens.input, usageData.totalTokens.output, LEGACY_BLENDED_RATES)),currentStreak,longestStreak,last7Days,diff --git a/server/services/usage.test.js b/server/services/usage.test.jsindex 7b7ad40ad4..f57e460027 100644--- a/server/services/usage.test.js+++ b/server/services/usage.test.js@@ -208,14 +208,13 @@ describe('usage.js — streak calculations', () => {expect(typeof today.label).toBe('string');});- it('estimatedCost is a number >= 0', async () => {+ it('estimatedCost keeps its all-time legacy-blended semantics ($3/$15 per 1M)', async () => {readJSONFile.mockResolvedValueOnce(makeUsage({}, {totalTokens: { input: 1_000_000, output: 500_000 }}));await loadUsage();const summary = getUsageSummary();- expect(typeof summary.estimatedCost).toBe('number');- expect(summary.estimatedCost).toBeGreaterThanOrEqual(0);+ expect(summary.estimatedCost).toBeCloseTo(10.5); // 1M×$3 + 0.5M×$15});});@@ -248,13 +247,15 @@ describe('usage.js — streak calculations', () => {const usage = getUsage();expect(usage.totalTokens).toEqual({ input: 1200, output: 400 });- expect(usage.byProvider['claude-code']).toMatchObject({ tokensIn: 1200, tokensOut: 400, tokens: 400 });- expect(usage.byModel.opus).toMatchObject({ tokensIn: 1200, tokensOut: 400 });+ // Legacy all-time entries keep their output-only `tokens` shape — the+ // in/out split lives only in the day buckets the report aggregates.+ expect(usage.byProvider['claude-code']).toMatchObject({ tokens: 400 });+ expect(usage.byModel.opus).toMatchObject({ tokens: 400 });const modelDay = usage.dailyActivity[daysAgo(0)].byProvider['claude-code'].byModel.opus;expect(modelDay).toMatchObject({ messages: 1, tokensIn: 1200, tokensOut: 400 });});- it('recordMessages tolerates legacy all-time entries without tokensIn/tokensOut', async () => {+ it('recordMessages accumulates onto legacy all-time entries without reshaping them', async () => {readJSONFile.mockResolvedValueOnce(makeUsage({}, {byProvider: { codex: { name: 'Codex', sessions: 5, messages: 5, tokens: 100 } },byModel: { 'gpt-5.3-codex': { sessions: 5, messages: 5, tokens: 100 } }@@ -263,8 +264,11 @@ describe('usage.js — streak calculations', () => {await recordMessages('codex', 'gpt-5.3-codex', 1, 50, 200);const usage = getUsage();- expect(usage.byProvider.codex).toMatchObject({ tokens: 150, tokensIn: 200, tokensOut: 50 });- expect(usage.byModel['gpt-5.3-codex']).toMatchObject({ tokens: 150, tokensIn: 200, tokensOut: 50 });+ expect(usage.byProvider.codex).toMatchObject({ messages: 6, tokens: 150 });+ expect(usage.byModel['gpt-5.3-codex']).toMatchObject({ messages: 6, tokens: 150 });+ // ...while the day bucket carries the full in/out split+ const modelDay = usage.dailyActivity[daysAgo(0)].byProvider.codex.byModel['gpt-5.3-codex'];+ expect(modelDay).toMatchObject({ tokensIn: 200, tokensOut: 50 });});});