diff --git a/docs-site/src/content/docs/es/reference/management-api.md b/docs-site/src/content/docs/es/reference/management-api.md
index 830a877507d..1e942f2fbb0 100644
--- a/docs-site/src/content/docs/es/reference/management-api.md
+++ b/docs-site/src/content/docs/es/reference/management-api.md
@@ -394,6 +394,22 @@ Las solicitudes PUT válidas a `/api/selected-models` y `/api/model-presets` dev
La visibilidad/selección exitosa escribe a `/api/disabled-models`, `/api/model-visibility`, `/api/selected-models` y `/api/model-presets` para informar los resultados de seguimiento en `catalogRefresh` y `clientIntegrations` cuando se ejecuta esa ruta de actualización. HTTP 200 y `ok: true` confirman la selección guardar; no garantizan todos los catálogos de clientes actualizados. Inspeccione `clientIntegrations[]` para `ok: false`, `client`, opcional Aparte `profileId`, y el rechazo `reason`; los detalles de recuperación también pueden incluir `refusalReason`, `snapshotPath` y `residual`. La página Modelos mantiene la selección guardada y muestra una advertencia de actualización del cliente por separado. Inspeccione las integraciones y resuelva el problema notificado antes de volver a intentar `ocx sync`. Los campos de resultado que faltan de un servidor antiguo no establecen una recuperación exitosa.
+
+
+### Medidor en vivo (`GET /v1/usage/live`)
+
+Un endpoint de solo lectura del plano de datos informa de la solicitud completada más reciente: velocidad de salida, acierto de caché y ocupación del contexto. Un cliente, como un userscript de Codex de escritorio, puede consultarlo para mostrar esas cifras junto al compositor. Se admite exactamente igual que `/v1/models`: sin credencial en un enlace loopback, con una clave de datos (`x-opencodex-api-key`, `Authorization: Bearer` o `x-api-key`) en otro caso, y nunca con el token de administración. El origen de la página de Codex de escritorio `app://-` puede leer solo esta ruta (y su preflight); las demás rutas del plano de datos conservan sus reglas de origen.
+
+Consulta: `client=codex|claude|other` limita el resultado a una familia de clientes y `conversation=` a una conversación. El filtro de conversación acepta el id original, el resumen registrado o un enlace `codex://threads/`, y la respuesta nunca lo repite. El cuerpo es `{ "latest": Meter | null, "byClient": { "codex"?: Meter, "claude"?: Meter, "other"?: Meter }, "generatedAt": }`. Un `Meter` contiene `speed { value, reason }`, `outputTokens`, `generationMs`, `cache { readTokens, inputTokens, percent, reason }`, `context { usedTokens, limitTokens, percent, reason }`, `model`, `provider`, `client` y `timestamp`: solo números, nombres de modelo y proveedor y códigos de motivo. Las revisiones automáticas de aprobación (`codex-auto-review`) nunca se informan.
+
+Un valor es `null` (se muestra como `--`) en lugar de una estimación cuando no se puede medir:
+
+| Valor | `null` cuando |
+| --- | --- |
+| `speed` | La solicitud falló, se canceló o terminó incompleta; el uso falta o es estimado; faltan los tokens de salida; la ventana de generación no se registró, dura menos de 1 s o es incoherente. La velocidad es tokens de salida entre la ventana de generación, nunca el tiempo total. |
+| `cache.percent` | El uso falta o es estimado, falta el recuento de entrada o la lectura de caché solo existe en el cable. |
+| `context.percent` | El uso falta o es estimado, o la ventana de contexto del modelo no está en el catálogo persistido de Codex (`context.reason` es `limit_unknown`). |
+
### Cuentas OAuth, claves de proveedor y claves de plano de datos
diff --git a/docs-site/src/content/docs/reference/management-api.md b/docs-site/src/content/docs/reference/management-api.md
index 53f32c3e469..23031f7e632 100644
--- a/docs-site/src/content/docs/reference/management-api.md
+++ b/docs-site/src/content/docs/reference/management-api.md
@@ -672,6 +672,20 @@ The Models page keeps the saved selection and shows a separate client-refresh wa
Inspect Integrations and resolve the reported issue before retrying `ocx sync`. Missing
outcome fields from an older server do not establish successful recovery.
+### Live meter (`GET /v1/usage/live`)
+
+A read-only data-plane endpoint reports the newest completed request: output speed, cache hit and context fill. A client such as a Codex desktop userscript can poll it to show those numbers next to the composer. It is admitted exactly like `/v1/models`: no credential on a loopback bind, a data key (`x-opencodex-api-key`, `Authorization: Bearer` or `x-api-key`) otherwise, and never the admin token. The Codex desktop page origin `app://-` may read this one route (and its preflight); every other data-plane route keeps its existing origin rules.
+
+Query: `client=codex|claude|other` narrows the result to one client family, and `conversation=` to one conversation. The conversation filter accepts the raw id, the logged digest or a `codex://threads/` link, and the response never echoes it. The body is `{ "latest": Meter | null, "byClient": { "codex"?: Meter, "claude"?: Meter, "other"?: Meter }, "generatedAt": }`. A `Meter` carries `speed { value, reason }`, `outputTokens`, `generationMs`, `cache { readTokens, inputTokens, percent, reason }`, `context { usedTokens, limitTokens, percent, reason }`, `model`, `provider`, `client` and `timestamp`: numbers, model and provider names and reason codes only. Automatic approval reviews (`codex-auto-review`) are never reported.
+
+A value is `null` (shown as `--`) instead of a guess when it cannot be measured:
+
+| Value | `null` when |
+| --- | --- |
+| `speed` | The request failed, was cancelled or ended incomplete; usage is missing or estimated; output tokens are missing; the generation window is not recorded, shorter than 1 s or inconsistent. Speed is output tokens over the generation window, never wall time. |
+| `cache.percent` | Usage is missing or estimated, the input count is missing or the cache read is wire-only. |
+| `context.percent` | Usage is missing or estimated, or the model's context window is not in the persisted Codex catalog (`context.reason` is `limit_unknown`). |
+
### OAuth accounts, provider keys, and data-plane keys
OAuth account rows always include `plan`: a validated upstream subscription label or `null`
diff --git a/docs-site/src/content/docs/zh-cn/reference/management-api.md b/docs-site/src/content/docs/zh-cn/reference/management-api.md
index 73c78e12265..2dcba3021f5 100644
--- a/docs-site/src/content/docs/zh-cn/reference/management-api.md
+++ b/docs-site/src/content/docs/zh-cn/reference/management-api.md
@@ -227,6 +227,20 @@ Aside 配置档的变更在这种情况下仍会保存一件事:确认之后
可靠的初始模型列表尚未确认时,有效的 `PUT /api/selected-models` 和 `PUT /api/model-presets` 请求也会返回 HTTP 409 和代码 `initial_model_selection_pending`。请使用 `GET /api/models` 等方式刷新模型列表,成功后再重试。
+### 实时指标(`GET /v1/usage/live`)
+
+只读的数据平面端点,返回最近一次已完成请求的输出速度、缓存命中率和上下文占用,例如供 Codex 桌面端用户脚本在输入框旁显示。准入与 `/v1/models` 完全相同:回环绑定无需凭据,否则需要数据密钥(`x-opencodex-api-key`、`Authorization: Bearer` 或 `x-api-key`),永远不接受管理令牌。Codex 桌面端页面来源 `app://-` 仅可读取这一条路由(及其预检),其他数据平面路由的来源规则不变。
+
+查询参数:`client=codex|claude|other` 限定客户端类别,`conversation=` 限定单个会话;会话过滤接受原始 id、日志中的摘要或 `codex://threads/` 链接,响应不会回显它。响应体为 `{ "latest": Meter | null, "byClient": { "codex"?: Meter, "claude"?: Meter, "other"?: Meter }, "generatedAt": <毫秒> }`。`Meter` 含 `speed { value, reason }`、`outputTokens`、`generationMs`、`cache { readTokens, inputTokens, percent, reason }`、`context { usedTokens, limitTokens, percent, reason }`、`model`、`provider`、`client`、`timestamp`,只有数字、模型与 provider 名称和原因码。自动审批审查(`codex-auto-review`)不会被报告。
+
+无法测量时对应值为 `null`(显示为 `--`),绝不猜测:
+
+| 值 | 为 `null` 的情况 |
+| --- | --- |
+| `speed` | 请求失败、被取消或未完整结束;用量缺失或为估算值;缺少输出 token;生成窗口未记录、短于 1 秒或不一致。速度是输出 token 除以生成窗口,而不是墙钟时间。 |
+| `cache.percent` | 用量缺失或为估算值、缺少输入数,或缓存读取仅存在于线路层。 |
+| `context.percent` | 用量缺失或为估算值,或该模型的上下文窗口不在已持久化的 Codex 目录中(`context.reason` 为 `limit_unknown`)。 |
+
### OAuth 账户、provider 密钥和数据平面密钥
| 方法和路径 | 用途 | 典型错误 |
diff --git a/docs-site/src/content/docs/zh-tw/reference/management-api.md b/docs-site/src/content/docs/zh-tw/reference/management-api.md
index c2405560e68..371fb4d2eef 100644
--- a/docs-site/src/content/docs/zh-tw/reference/management-api.md
+++ b/docs-site/src/content/docs/zh-tw/reference/management-api.md
@@ -230,6 +230,20 @@ Aside 設定檔的變更在這種情況下仍會儲存一件事:確認之後
尚未確認可靠的初始模型清單時,有效的 `PUT /api/selected-models` 和 `PUT /api/model-presets` 請求也會回傳 HTTP 409 和代碼 `initial_model_selection_pending`。請使用 `GET /api/models` 等方式更新模型清單,成功後再重試。
+### 即時指標(`GET /v1/usage/live`)
+
+唯讀的資料平面端點,回傳最近一次已完成請求的輸出速度、快取命中率與上下文占用,例如供 Codex 桌面端使用者腳本在輸入框旁顯示。存取許可與 `/v1/models` 完全相同:回送綁定不需憑證,否則需要資料金鑰(`x-opencodex-api-key`、`Authorization: Bearer` 或 `x-api-key`),永遠不接受管理權杖。Codex 桌面端頁面來源 `app://-` 僅可讀取這一條路由(及其預檢),其他資料平面路由的來源規則不變。
+
+查詢參數:`client=codex|claude|other` 限定用戶端類別,`conversation=` 限定單一對話;對話過濾接受原始 id、日誌中的摘要或 `codex://threads/` 連結,回應不會回顯它。回應本體為 `{ "latest": Meter | null, "byClient": { "codex"?: Meter, "claude"?: Meter, "other"?: Meter }, "generatedAt": <毫秒> }`。`Meter` 含 `speed { value, reason }`、`outputTokens`、`generationMs`、`cache { readTokens, inputTokens, percent, reason }`、`context { usedTokens, limitTokens, percent, reason }`、`model`、`provider`、`client`、`timestamp`,只有數字、模型與供應商名稱和原因碼。自動核准審查(`codex-auto-review`)不會被回報。
+
+無法量測時對應值為 `null`(顯示為 `--`),絕不猜測:
+
+| 值 | 為 `null` 的情況 |
+| --- | --- |
+| `speed` | 請求失敗、被取消或未完整結束;用量缺失或為估算值;缺少輸出 token;生成視窗未記錄、短於 1 秒或不一致。速度是輸出 token 除以生成視窗,而不是牆鐘時間。 |
+| `cache.percent` | 用量缺失或為估算值、缺少輸入數,或快取讀取僅存在於線路層。 |
+| `context.percent` | 用量缺失或為估算值,或該模型的上下文視窗不在已持久化的 Codex 目錄中(`context.reason` 為 `limit_unknown`)。 |
+
### OAuth 帳號、供應商金鑰與 data-plane 金鑰
| 方法與路徑 | 用途 | 主要錯誤 |
diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json
index 05605249cbe..fce0f1ecba4 100644
--- a/scripts/test-layout/layout.json
+++ b/scripts/test-layout/layout.json
@@ -23,7 +23,7 @@
"anthropic2-discovery-ownership.test.ts": "oauth",
"codex-shim-runtime-preflight.test.ts": "codex-integration",
"cli-anthropic2-account.test.ts": "cli", "anthropic2-catalog.test.ts": "codex-integration", "provider-anthropic-instance-quota.test.ts": "providers", "anthropic2-management.test.ts": "server",
- "management-sidecar-anthropic-instance.test.ts": "server", "anthropic2-usage-attribution.test.ts": "usage", "vision-anthropic-instance-sidecar.test.ts": "vision", "web-search-anthropic-instance.test.ts": "web-search",
+ "management-sidecar-anthropic-instance.test.ts": "server", "anthropic2-usage-attribution.test.ts": "usage", "live-meter.test.ts": "usage", "vision-anthropic-instance-sidecar.test.ts": "vision", "web-search-anthropic-instance.test.ts": "web-search",
"provider-anthropic-instance.test.ts": "providers", "config-anthropic-instance-pool.test.ts": "config", "oauth-anthropic-instance-registration.test.ts": "oauth", "oauth-anthropic-instance-refresh.test.ts": "oauth",
"model-costs-pricing-cache.test.ts": "server", "model-costs-prompt-length-pricing.test.ts": "server", "cli-models-prompt-length-pricing.test.ts": "cli", "usage-prompt-length-pricing.test.ts": "usage",
"claude-picker-upload.test.ts": "claude-integration", "claude-picker-linger.test.ts": "claude-integration", "messages-native-scope.test.ts": "claude-integration", "catalog-auto-review-row.test.ts": "codex-integration",
@@ -1049,7 +1049,7 @@
"history-paginated-transition-destinations.test.ts": "codex-integration",
"hub-gated-local-clients.test.ts": "cli",
"hub-invite.test.ts": "cli", "hub-disable.test.ts": "cli",
- "hub-usage.test.ts": "server",
+ "hub-usage.test.ts": "server", "live-meter-handler.test.ts": "server",
"hyperbolic-provider.test.ts": "providers",
"identity-neutralize.test.ts": "adapters",
"identity-subagent.test.ts": "adapters",
diff --git a/src/server/auth-cors.ts b/src/server/auth-cors.ts
index 7ea7487797e..49046566dfc 100644
--- a/src/server/auth-cors.ts
+++ b/src/server/auth-cors.ts
@@ -704,6 +704,8 @@ export const AUTH_MATRIX: readonly ApiAuthMatrixRow[] = [
{ endpoint: "/v1/hub-state", bearer: "accepted", dedicated: "accepted", xApiKey: "accepted" },
// Usage additionally requires a configured key identity; unscoped environment keys are refused.
{ endpoint: "/v1/usage", bearer: "rejected", dedicated: "accepted", xApiKey: "rejected" },
+ // The live meter reads the in-process request log only (numbers and model names), admitted like /v1/models.
+ { endpoint: "/v1/usage/live", bearer: "accepted", dedicated: "accepted", xApiKey: "accepted" },
];
/** Whether `token` is the environment-provided management secret. */
diff --git a/src/server/index.ts b/src/server/index.ts
index 6d2f25b2ee4..7350c366d34 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -413,6 +413,8 @@ function startServerWithSpendLedgerOwner(port: number | undefined, deps: StartSe
if (path === "/v1/audio/transcriptions") return req.method === "POST";
if (path === "/v1/audio/transcriptions/stream") return req.headers.get("upgrade")?.toLowerCase() === "websocket";
if (path === "/v1/alpha/search") return req.method === "POST";
+ // Live meter (#8735): GET-only numbers from the local request log; Codex++ reads it here.
+ if (path === "/v1/usage/live") return req.method === "GET";
if (contextEndpoint(path)) return req.method === "POST";
if (path === "/v1/images/generations" || path === "/v1/images/edits") {
return req.method === "POST";
diff --git a/src/server/index/serve-options.ts b/src/server/index/serve-options.ts
index b943aab586d..b44cdb10626 100644
--- a/src/server/index/serve-options.ts
+++ b/src/server/index/serve-options.ts
@@ -405,6 +405,10 @@ export function createServeOptions(ctx: ServeOptionsContext) {
if (readyzPath !== undefined) {
return withCors(formatErrorResponse(404, "not_found", messagesUnknownEndpointMessage(req)), req, policy);
}
+ if (url.pathname === "/v1/usage/live") {
+ const preflight = (await import("../live-meter-handler")).liveMeterPreflight(req, policy);
+ if (preflight) return preflight;
+ }
// The exact Ollama-compatible paths are data-plane routes and take data-plane CORS.
const managementPreflight = url.pathname.startsWith("/api/") && !isOllamaNativePath(url.pathname);
const allowed = managementPreflight
@@ -795,6 +799,12 @@ export function createServeOptions(ctx: ServeOptionsContext) {
);
}
+ if (url.pathname === "/v1/usage/live" && req.method === "GET") {
+ // Same admission as the model routes; the module adds only the Codex desktop origin for this read.
+ const { handleLiveMeterData } = await import("../live-meter-handler");
+ return handleLiveMeterData(req, policy);
+ }
+
if (url.pathname === "/v1/usage" && req.method === "GET") {
const { handleHubUsage } = await import("../hub-usage");
return handleHubUsage(req, config, policy);
diff --git a/src/server/live-meter-handler.ts b/src/server/live-meter-handler.ts
new file mode 100644
index 00000000000..0cf90079fa3
--- /dev/null
+++ b/src/server/live-meter-handler.ts
@@ -0,0 +1,125 @@
+/**
+ * Read-only live meter: generation speed, cache hit and context fill of the newest completed
+ * request, overall and per client family, served on the data-plane route `GET /v1/usage/live`.
+ * It is admitted like the proxy's own model requests, so the Codex desktop renderer (Codex++
+ * userscript) can read it without the admin token. The projection is `src/usage/live-meter.ts`.
+ *
+ * The body carries numbers, model and provider names and reason codes only. A `conversation`
+ * filter narrows the rows but is never echoed, and neither is any stored conversation digest.
+ */
+import { readCatalog, readCodexCatalogPath } from "../codex/catalog";
+import { liveMeterFromEntry, selectLiveMeterEntries, type LiveMeter, type MeterClientFamily } from "../usage/live-meter";
+import {
+ corsHeaders, isAllowedRequestOrigin, isApiAuthRequired, isLoopbackRequestHost, resolveApiAuth, withCors,
+ type RequestPolicyView,
+} from "./auth-cors";
+import { formatErrorResponse } from "../bridge/errors";
+import { matchesLogConversationId } from "./request-log-conversation";
+import { getRequestLogEntries, type RequestLogEntry } from "./request-log";
+import { statSync } from "node:fs";
+
+/** The Codex desktop renderer's page origin; it may read this one route and nothing else. */
+export const LIVE_METER_APP_ORIGIN = "app://-";
+
+export interface LiveMeterBody {
+ latest: LiveMeter | null;
+ byClient: Partial>;
+ generatedAt: number;
+}
+
+export interface LiveMeterDeps {
+ entries?: () => readonly RequestLogEntry[];
+ contextLimit?: (model: string) => number | null;
+ now?: () => number;
+}
+
+const FAMILIES: readonly MeterClientFamily[] = ["codex", "claude", "other"];
+
+let catalogCache: { path: string; mtimeMs: number; size: number; limits: Map } | null = null;
+
+/** Window of the model as the persisted Codex catalog states it, re-read only when the file changes. */
+export function catalogContextLimit(model: string, catalogPath: string = readCodexCatalogPath()): number | null {
+ let stat;
+ try { stat = statSync(catalogPath); } catch { return null; }
+ if (!catalogCache || catalogCache.path !== catalogPath || catalogCache.mtimeMs !== stat.mtimeMs || catalogCache.size !== stat.size) {
+ const limits = new Map();
+ for (const row of readCatalog(catalogPath)?.models ?? []) {
+ const window = row.context_window;
+ if (typeof row.slug === "string" && typeof window === "number" && Number.isFinite(window) && window > 0) {
+ limits.set(row.slug, window);
+ }
+ }
+ catalogCache = { path: catalogPath, mtimeMs: stat.mtimeMs, size: stat.size, limits };
+ }
+ return catalogCache.limits.get(model) ?? null;
+}
+
+export function resetLiveMeterCatalogCacheForTests(): void { catalogCache = null; }
+
+export type LiveMeterResult = { status: 200; body: LiveMeterBody } | { status: 400; code: string; message: string };
+
+export function buildLiveMeter(params: URLSearchParams, deps: LiveMeterDeps = {}): LiveMeterResult {
+ const bad = (message: string): LiveMeterResult => ({ status: 400, code: "live_meter_query_invalid", message });
+ for (const key of params.keys()) {
+ if ((key !== "client" && key !== "conversation") || params.getAll(key).length !== 1) return bad("Unknown or repeated option");
+ }
+ const client = params.get("client");
+ if (client !== null && !(FAMILIES as readonly string[]).includes(client)) return bad("client must be codex, claude or other");
+ const conversation = params.get("conversation");
+ if (conversation !== null && !conversation.trim()) return bad("conversation must not be empty");
+ const limitOf = deps.contextLimit ?? ((model: string) => catalogContextLimit(model));
+ const selection = selectLiveMeterEntries(
+ (deps.entries ?? getRequestLogEntries)(),
+ conversation === null ? undefined : entry => matchesLogConversationId(entry.conversationId, conversation),
+ );
+ const project = (entry: RequestLogEntry): LiveMeter => liveMeterFromEntry(entry, entry.model ? limitOf(entry.model) : null);
+ const byClient: LiveMeterBody["byClient"] = {};
+ for (const family of FAMILIES) {
+ const entry = selection.byFamily[family];
+ if (entry) byClient[family] = project(entry);
+ }
+ const filtered = client === null ? selection.overall : selection.byFamily[client as MeterClientFamily] ?? null;
+ return { status: 200, body: {
+ latest: filtered ? project(filtered) : null,
+ byClient: client === null ? byClient : (byClient[client as MeterClientFamily] ? { [client]: byClient[client as MeterClientFamily] } : {}),
+ generatedAt: (deps.now ?? Date.now)(),
+ } };
+}
+
+export function liveMeterResponse(params: URLSearchParams, deps?: LiveMeterDeps): Response {
+ const result = buildLiveMeter(params, deps);
+ const headers = { "cache-control": "no-store" };
+ return result.status === 200
+ ? Response.json(result.body, { headers })
+ : Response.json({ error: { type: "invalid_request_error", code: result.code, message: result.message } }, { status: 400, headers });
+}
+
+/** `GET /v1/usage/live`: same admission as the proxy's model requests; never the admin token. */
+export async function handleLiveMeterData(req: Request, config: RequestPolicyView, deps?: LiveMeterDeps): Promise {
+ const appRenderer = req.headers.get("Origin") === LIVE_METER_APP_ORIGIN;
+ const reply = (response: Response, admittedOrigin = false): Response => {
+ const out = withCors(response, req, config);
+ if (admittedOrigin) out.headers.set("Access-Control-Allow-Origin", LIVE_METER_APP_ORIGIN);
+ return out;
+ };
+ if (!resolveApiAuth(req, config)) return reply(formatErrorResponse(401, "authentication_error", "opencodex API key required"));
+ // The renderer is not loopback-by-origin; the loopback Host gate still binds it when no key is required.
+ const originOk = appRenderer
+ ? isApiAuthRequired(config) || isLoopbackRequestHost(req.headers.get("Host"))
+ : isAllowedRequestOrigin(req, config);
+ if (!originOk) return reply(formatErrorResponse(403, "origin_rejected", "cross-origin data-plane request blocked"));
+ return reply(liveMeterResponse(new URL(req.url).searchParams, deps), appRenderer);
+}
+
+/**
+ * Preflight for the renderer's cross-origin read of `/v1/usage/live` (a key header makes it non-simple).
+ * `null` for every other origin, so the data-plane preflight policy is untouched.
+ */
+export function liveMeterPreflight(req: Request, config: RequestPolicyView): Response | null {
+ if (req.headers.get("Origin") !== LIVE_METER_APP_ORIGIN) return null;
+ if (!isApiAuthRequired(config) && !isLoopbackRequestHost(req.headers.get("Host"))) return null;
+ const headers = corsHeaders(req, config);
+ headers["Access-Control-Allow-Origin"] = LIVE_METER_APP_ORIGIN;
+ headers["Access-Control-Allow-Methods"] = "GET, OPTIONS";
+ return new Response(null, { status: 204, headers });
+}
diff --git a/src/usage/live-meter.ts b/src/usage/live-meter.ts
new file mode 100644
index 00000000000..e26fc5fc3fe
--- /dev/null
+++ b/src/usage/live-meter.ts
@@ -0,0 +1,138 @@
+/**
+ * Live meter: generation speed, cache hit and context fill for ONE completed request row.
+ *
+ * Pure projection of a `RequestLogEntry`. Speed divides the upstream-reported output tokens
+ * by the recorded generation window (`genStartMs` .. `lastOutputMs`, request-log-generation-window.ts),
+ * never by wall time or first visible text. Anything that cannot be measured is `null` plus a
+ * closed reason code; nothing is estimated or guessed. Carries numbers, model and provider
+ * names only: no prompt text, account labels or identifiers.
+ *
+ * Ported from the Codex++ userscript reader (codexpp-andrew-extensions/meter/core.mjs); the
+ * reason vocabulary is the same.
+ */
+import type { RequestLogEntry } from "../server/request-log";
+
+export type MeterSpeedReason =
+ | "no_matching_request" | "request_aborted" | "request_incomplete" | "request_failed"
+ | "usage_missing" | "tokens_estimated" | "output_missing" | "generation_timing_missing"
+ | "generation_window_too_short" | "invalid_generation_window";
+
+export type MeterPercentReason = "usage_missing" | "tokens_estimated" | "input_missing" | "limit_unknown";
+
+export interface LiveMeter {
+ speed: { value: number | null; reason: MeterSpeedReason | null };
+ outputTokens: number | null;
+ generationMs: number | null;
+ cache: { readTokens: number | null; inputTokens: number | null; percent: number | null; reason: MeterPercentReason | null };
+ context: { usedTokens: number | null; limitTokens: number | null; percent: number | null; reason: MeterPercentReason | null };
+ model: string | null;
+ provider: string | null;
+ client: string | null;
+ timestamp: number | null;
+}
+
+/** Rows that are not a conversation turn (automatic approval reviews) never become the meter. */
+export function isConversationMeterRow(entry: Pick): boolean {
+ return typeof entry.model === "string" && entry.model !== "codex-auto-review";
+}
+
+const count = (value: unknown): number | null =>
+ typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
+
+function speed(entry: RequestLogEntry): LiveMeter["speed"] {
+ const none = (reason: MeterSpeedReason) => ({ value: null, reason });
+ if (entry.closeReason === "client_cancel" || entry.status === 499) return none("request_aborted");
+ if (entry.terminalStatus === "failed" || entry.terminalStatus === "incomplete"
+ || entry.closeReason === "body_stall" || entry.closeReason === "body_overflow") return none("request_incomplete");
+ if (!(entry.status >= 200 && entry.status < 400)) return none("request_failed");
+ if (!entry.usage || entry.usageStatus === "unsupported") return none("usage_missing");
+ if (entry.usageStatus === "estimated" || entry.usage.estimated === true) return none("tokens_estimated");
+ const tokens = entry.usage.outputTokens;
+ if (!(Number.isFinite(tokens) && tokens > 0)) return none("output_missing");
+ const start = entry.genStartMs;
+ const end = entry.lastOutputMs;
+ if (!(typeof start === "number" && Number.isFinite(start) && start >= 0 && typeof end === "number" && Number.isFinite(end))) {
+ return none("generation_timing_missing");
+ }
+ const window = end - start;
+ if (window < 1000) return none(window > 0 ? "generation_window_too_short" : "invalid_generation_window");
+ if (Number.isFinite(entry.durationMs) && end > entry.durationMs + 10) return none("invalid_generation_window");
+ return { value: (tokens * 1000) / window, reason: null };
+}
+
+/**
+ * `contextLimitTokens` is the model's window as the catalog knows it, supplied by the caller
+ * (a pure projection cannot look it up). `null` when unknown: the percentage is then `null`.
+ */
+export function liveMeterFromEntry(entry: RequestLogEntry, contextLimitTokens: number | null): LiveMeter {
+ const s = speed(entry);
+ const reported = !!entry.usage && entry.usageStatus !== "unsupported"
+ && entry.usageStatus !== "estimated" && entry.usage.estimated !== true;
+ const usageReason: MeterPercentReason | null = !entry.usage || entry.usageStatus === "unsupported"
+ ? "usage_missing" : reported ? null : "tokens_estimated";
+ const usage = reported ? entry.usage : undefined;
+ const inputTokens = count(usage?.inputTokens);
+ const outputTokens = count(usage?.outputTokens);
+ const readTokens = count(usage?.cacheReadInputTokens ?? usage?.cachedInputTokens);
+ // `cacheReadInputTokens` is the read subset of `inputTokens`; a synthesized provenance is wire-only.
+ const cacheKnown = readTokens !== null && inputTokens !== null && inputTokens > 0
+ && entry.cacheProvenance !== "synthesized" && readTokens <= inputTokens;
+ const used = count(usage?.contextTotalTokens)
+ ?? (inputTokens !== null && outputTokens !== null ? inputTokens + outputTokens : null);
+ const limit = contextLimitTokens !== null && Number.isFinite(contextLimitTokens) && contextLimitTokens > 0
+ ? contextLimitTokens : null;
+ return {
+ speed: s,
+ outputTokens,
+ generationMs: s.value !== null ? (entry.lastOutputMs as number) - (entry.genStartMs as number) : null,
+ cache: {
+ readTokens, inputTokens,
+ percent: cacheKnown ? (100 * readTokens) / inputTokens : null,
+ reason: cacheKnown ? null : usageReason ?? "input_missing",
+ },
+ context: {
+ usedTokens: used, limitTokens: limit,
+ percent: used !== null && limit !== null ? Math.min(100, (100 * used) / limit) : null,
+ reason: used === null ? usageReason ?? "input_missing" : limit === null ? "limit_unknown" : null,
+ },
+ model: entry.model ?? null,
+ provider: entry.provider ?? null,
+ client: entry.client ?? null,
+ timestamp: Number.isFinite(entry.timestamp) ? entry.timestamp : null,
+ };
+}
+
+export type MeterClientFamily = "codex" | "claude" | "other";
+
+/** Family of a recorded client label; unknown or absent rows count only toward the overall meter. */
+export function meterClientFamily(client: string | undefined): MeterClientFamily | null {
+ if (!client || client === "unknown") return null;
+ if (client.startsWith("codex_")) return "codex";
+ if (client.startsWith("claude_")) return "claude";
+ return "other";
+}
+
+export interface LiveMeterSelection {
+ overall: RequestLogEntry | null;
+ byFamily: Partial>;
+}
+
+/**
+ * Newest completed conversation row overall and per client family. The store is append-ordered
+ * but combo and retried rows can finish out of order, so recency is by `timestamp`.
+ * `matches` narrows to one conversation when the caller supplied one.
+ */
+export function selectLiveMeterEntries(
+ entries: readonly RequestLogEntry[],
+ matches: (entry: RequestLogEntry) => boolean = () => true,
+): LiveMeterSelection {
+ const out: LiveMeterSelection = { overall: null, byFamily: {} };
+ const newer = (a: RequestLogEntry | null | undefined, b: RequestLogEntry) => !a || b.timestamp >= a.timestamp;
+ for (const entry of entries) {
+ if (!isConversationMeterRow(entry) || !matches(entry)) continue;
+ if (newer(out.overall, entry)) out.overall = entry;
+ const family = meterClientFamily(entry.client);
+ if (family && newer(out.byFamily[family], entry)) out.byFamily[family] = entry;
+ }
+ return out;
+}
diff --git a/structure/runtime.md b/structure/runtime.md
index 6598dab83f1..b2967808b9a 100644
--- a/structure/runtime.md
+++ b/structure/runtime.md
@@ -213,7 +213,7 @@ Enabled startup retains separate fresh ownership decisions. Explicit `sync` and
`startServer` composes up to four sockets in one synchronous startup transaction: the public data listener, optional unauthenticated data-loopback and hub-management listeners, and the optional `hub-link` listener, which opens only for a recorded link and persists its concrete `127.0.0.1:`. HTTP Responses/Messages apply the [caller header contract](data-planes/inbound-compat.md#http-caller-conversation-identity) before turn admission and dispatch. Linked-machine data uses the [connection-bound relay contract](remote-link.md#connection-bound-relay-authentication); client-local credentials and routing policy remain unchanged.
The data-loopback socket serves a fixed data-plane allowlist: Responses and its compact sibling,
-the native search relay, the standalone Images POSTs, keyed file/stream transcription, `GET /v1/models`, the realtime voice shapes,
+the native search relay, the standalone Images POSTs, keyed file/stream transcription, `GET /v1/models`, `GET /v1/usage/live`, the realtime voice shapes,
and the Anthropic and OpenAI chat wires the host's own local clients speak — `POST /v1/messages`,
`POST /v1/messages/count_tokens`, and `POST /v1/chat/completions`. It never serves `/api/*`,
`/healthz`, `/readyz`, or GUI routes, so local management discovery has to use an authenticated
diff --git a/structure/usage-client-attribution.md b/structure/usage-client-attribution.md
index 42da962df1c..e10ef43c328 100644
--- a/structure/usage-client-attribution.md
+++ b/structure/usage-client-attribution.md
@@ -202,3 +202,7 @@ and the request-log hydration keep only `p` plus six lowercase hex digits and dr
Per-account summaries still key on `accountLogLabel` and ignore the tag
(`tests/usage/request-log-anthropic-account-tag.test.ts`).
Remote Link rows may carry an optional `link` object (transport, continuation, hashed thread and turn refs) while the link WebSocket feature is on; it is validated in `src/usage/link-log-fields.ts` and spread into the row, the persisted entry and hydration, and described in `structure/remote-link.md`.
+
+## Live meter
+
+The client families (`codex_*`, `claude_*`, other) also scope the live meter. `src/server/live-meter-handler.ts` serves `GET /v1/usage/live`, the newest completed conversation row projected by `src/usage/live-meter.ts` (output tokens over the recorded generation window, cache read over input, context used over the persisted Codex catalog's `context_window`, cached by catalog mtime). Any measurement that is missing, estimated, failed or under 1 s is `null` with a reason code, never a guess; the body is numbers, model/provider names and reason codes only, and a `conversation` filter is never echoed. Admission is `resolveApiAuth` (the `/v1/models` set, never the admin token), and Origin `app://-` (the Codex desktop renderer) is additionally allowed for this GET and its preflight only, behind the same loopback Host gate; `isAllowedRequestOrigin` and every other route are unchanged. The unauthenticated data-loopback listener admits it as GET only, because that socket is where the Codex++ footer dials on a host whose public listener binds a non-loopback address. The route reads the in-process request log, so it adds no management route, CLI verb or ledger read. Covered by `tests/server/live-meter-handler.test.ts` and the `AUTH_MATRIX` row.
diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json
index ebfabf37355..1784de80f63 100644
--- a/tests/fixtures/test-layout-expected.json
+++ b/tests/fixtures/test-layout-expected.json
@@ -180,7 +180,7 @@
"anthropic2-discovery-ownership.test.ts": "oauth",
"codex-shim-runtime-preflight.test.ts": "codex-integration",
"cli-anthropic2-account.test.ts": "cli", "anthropic2-catalog.test.ts": "codex-integration", "provider-anthropic-instance-quota.test.ts": "providers", "anthropic2-management.test.ts": "server",
- "management-sidecar-anthropic-instance.test.ts": "server", "anthropic2-usage-attribution.test.ts": "usage", "vision-anthropic-instance-sidecar.test.ts": "vision", "web-search-anthropic-instance.test.ts": "web-search",
+ "management-sidecar-anthropic-instance.test.ts": "server", "anthropic2-usage-attribution.test.ts": "usage", "live-meter.test.ts": "usage", "vision-anthropic-instance-sidecar.test.ts": "vision", "web-search-anthropic-instance.test.ts": "web-search",
"provider-anthropic-instance.test.ts": "providers", "config-anthropic-instance-pool.test.ts": "config", "oauth-anthropic-instance-registration.test.ts": "oauth", "oauth-anthropic-instance-refresh.test.ts": "oauth",
"claude-picker-upload.test.ts": "claude-integration", "claude-picker-linger.test.ts": "claude-integration",
"model-costs-pricing-cache.test.ts": "server",
@@ -954,7 +954,7 @@
"history-ocx-compaction-recovery.test.ts": "codex-integration",
"history-paginated-openai-compat.test.ts": "codex-integration",
"history-paginated-transition-destinations.test.ts": "codex-integration", "hub-gated-local-clients.test.ts": "cli",
- "hub-invite.test.ts": "cli", "hub-disable.test.ts": "cli", "hub-usage.test.ts": "server",
+ "hub-invite.test.ts": "cli", "hub-disable.test.ts": "cli", "hub-usage.test.ts": "server", "live-meter-handler.test.ts": "server",
"hyperbolic-provider.test.ts": "providers", "identity-neutralize.test.ts": "adapters",
"identity-subagent.test.ts": "adapters", "init-backup-cleanup.test.ts": "service",
"init-eof.test.ts": "service", "initial-model-selection.test.ts": "providers",
diff --git a/tests/server/api-key-attribution.test.ts b/tests/server/api-key-attribution.test.ts
index 81e330a51a2..ac1116b820d 100644
--- a/tests/server/api-key-attribution.test.ts
+++ b/tests/server/api-key-attribution.test.ts
@@ -738,7 +738,7 @@ describe("AUTH_MATRIX is true of the running server", () => {
// from routing and the assertions below would be testing the method guard rather
// than admission. /v1/catalog joined this set in #809.
const isGet = row.endpoint === "/v1/models" || row.endpoint === "/v1/catalog"
- || row.endpoint === "/v1/hub-state" || row.endpoint === "/v1/usage";
+ || row.endpoint === "/v1/hub-state" || row.endpoint === "/v1/usage" || row.endpoint === "/v1/usage/live";
const live = row.endpoint === "/v1/live" || row.endpoint === "/v1/realtime/calls";
const audio = row.endpoint === "/v1/audio/transcriptions" || live ? new FormData() : null;
if (audio) {
diff --git a/tests/server/live-meter-handler.test.ts b/tests/server/live-meter-handler.test.ts
new file mode 100644
index 00000000000..f731b40c1d4
--- /dev/null
+++ b/tests/server/live-meter-handler.test.ts
@@ -0,0 +1,205 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { buildLiveMeter, catalogContextLimit, handleLiveMeterData, liveMeterPreflight, resetLiveMeterCatalogCacheForTests } from "../../src/server/live-meter-handler";
+import { isAllowedRequestOrigin } from "../../src/server/auth-cors";
+import { normalizeLogConversationId } from "../../src/server/request-log-conversation";
+import { clearRequestLogsForTests, getRequestLogEntries, type RequestLogEntry } from "../../src/server/request-log";
+import { getDefaultConfig, saveConfig } from "../../src/config";
+import { startServer } from "../../src/server";
+import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home";
+import { BACKGROUND_WORK_TEARDOWN_TIMEOUT_MS, removeTreeAfterBackgroundWork } from "../helpers/remove-tree";
+
+const CONVERSATION = "thread-raw-id-7f3a";
+const DIGEST = normalizeLogConversationId(CONVERSATION)!;
+
+const row = (o: Partial = {}): RequestLogEntry => ({
+ requestId: "r", timestamp: 100, model: "gpt-6-astra", provider: "native", client: "codex_desktop", status: 200,
+ durationMs: 10000, genStartMs: 2000, lastOutputMs: 8000, usageStatus: "reported",
+ usage: { inputTokens: 1000, outputTokens: 600, cacheReadInputTokens: 750 }, ...o,
+} as RequestLogEntry);
+
+const entries = [
+ row({ timestamp: 100, conversationId: DIGEST }),
+ row({ timestamp: 200, client: "claude_code", model: "claude-x", conversationId: "someone-else" }),
+ row({ timestamp: 300, client: "codex_cli", model: "codex-auto-review" }),
+ row({ timestamp: 150, client: "codex_cli", conversationId: DIGEST, usage: { inputTokens: 10, outputTokens: 5 } }),
+];
+const deps = { entries: () => entries, contextLimit: (m: string) => (m === "gpt-6-astra" ? 872000 : null), now: () => 42 };
+
+describe("live meter body", () => {
+ test("latest overall and per family, auto-review rows never selected", () => {
+ const r = buildLiveMeter(new URLSearchParams(), deps);
+ expect(r.status).toBe(200);
+ if (r.status !== 200) return;
+ expect(r.body.generatedAt).toBe(42);
+ expect(r.body.latest?.client).toBe("claude_code");
+ expect(Object.keys(r.body.byClient).sort()).toEqual(["claude", "codex"]);
+ expect(r.body.byClient.codex?.timestamp).toBe(150);
+ expect(r.body.byClient.claude?.context).toMatchObject({ limitTokens: null, reason: "limit_unknown" });
+ });
+
+ test("client filter narrows latest and byClient", () => {
+ const r = buildLiveMeter(new URLSearchParams("client=codex"), deps);
+ expect(r.status === 200 && r.body.latest?.timestamp).toBe(150);
+ expect(r.status === 200 && Object.keys(r.body.byClient)).toEqual(["codex"]);
+ const none = buildLiveMeter(new URLSearchParams("client=other"), deps);
+ expect(none.status === 200 && none.body).toEqual({ latest: null, byClient: {}, generatedAt: 42 });
+ });
+
+ test("conversation filter accepts raw id, digest and thread link, and echoes none of them", () => {
+ for (const q of [CONVERSATION, DIGEST, `codex://threads/${CONVERSATION}`]) {
+ const r = buildLiveMeter(new URLSearchParams({ conversation: q }), deps);
+ expect(r.status === 200 && r.body.latest?.timestamp).toBe(150);
+ const text = JSON.stringify(r);
+ expect(text).not.toContain(CONVERSATION);
+ expect(text).not.toContain(DIGEST);
+ }
+ const miss = buildLiveMeter(new URLSearchParams({ conversation: "unknown" }), deps);
+ expect(miss.status === 200 && miss.body.latest).toBeNull();
+ });
+
+ test("bad queries are 400 with a code, not an empty meter", () => {
+ for (const q of ["client=gemini", "conversation=", "client=codex&client=claude", "x=1"]) {
+ expect(buildLiveMeter(new URLSearchParams(q), deps)).toMatchObject({ status: 400, code: "live_meter_query_invalid" });
+ }
+ });
+
+ test("no request yet means a null latest, not a zeroed meter", () => {
+ const r = buildLiveMeter(new URLSearchParams(), { ...deps, entries: () => [] });
+ expect(r.status === 200 && r.body.latest).toBeNull();
+ });
+});
+
+describe("catalog context limit", () => {
+ let dir: string | undefined;
+ afterEach(() => {
+ if (dir) rmSync(dir, { recursive: true, force: true });
+ dir = undefined;
+ resetLiveMeterCatalogCacheForTests();
+ });
+
+ test("maps client-facing slug to context_window and re-reads only when the file changes", () => {
+ dir = mkdtempSync(join(tmpdir(), "ocx-live-meter-"));
+ const path = join(dir, "opencodex-catalog.json");
+ const catalog = (window: number) => JSON.stringify({ models: [
+ { slug: "gpt-6-astra", context_window: window, max_context_window: 872000 },
+ { slug: "google-vertex/gemini-4-argon", context_window: 1000000 },
+ { slug: "no-window" },
+ ] });
+ writeFileSync(path, catalog(872000));
+ expect(catalogContextLimit("gpt-6-astra", path)).toBe(872000);
+ expect(catalogContextLimit("google-vertex/gemini-4-argon", path)).toBe(1000000);
+ expect(catalogContextLimit("no-window", path)).toBeNull();
+ expect(catalogContextLimit("missing", path)).toBeNull();
+ writeFileSync(path, catalog(400000));
+ const later = new Date(Date.now() + 5000);
+ utimesSync(path, later, later);
+ expect(catalogContextLimit("gpt-6-astra", path)).toBe(400000);
+ rmSync(path);
+ expect(catalogContextLimit("gpt-6-astra", path)).toBeNull();
+ });
+});
+
+describe("data-plane admission and CORS", () => {
+ const key = { id: "k", name: "k", key: "ocx_data_livemeterkey", createdAt: "2026-01-01" };
+ const loopback = { hostname: "127.0.0.1", corsAllowOrigins: [], apiKeys: [] };
+ const remote = { hostname: "0.0.0.0", corsAllowOrigins: [], apiKeys: [key] };
+ const get = (url: string, headers: Record = {}) => new Request(url, { headers });
+
+ test("loopback needs no key and answers the Codex desktop origin with that exact origin", async () => {
+ const res = await handleLiveMeterData(get("http://127.0.0.1:1/v1/usage/live", { origin: "app://-", host: "127.0.0.1:1" }), loopback, deps);
+ expect(res.status).toBe(200);
+ expect(res.headers.get("access-control-allow-origin")).toBe("app://-");
+ expect(res.headers.get("cache-control")).toBe("no-store");
+ expect((await res.json()).latest.client).toBe("claude_code");
+ });
+
+ test("loopback still refuses a rebinding Host and any other foreign origin", async () => {
+ const rebound = await handleLiveMeterData(get("http://evil.test/v1/usage/live", { origin: "app://-", host: "evil.test" }), loopback, deps);
+ expect(rebound.status).toBe(403);
+ const foreign = await handleLiveMeterData(get("http://127.0.0.1:1/v1/usage/live", { origin: "https://evil.test", host: "127.0.0.1:1" }), loopback, deps);
+ expect(foreign.status).toBe(403);
+ expect(foreign.headers.get("access-control-allow-origin")).not.toBe("https://evil.test");
+ });
+
+ test("a non-loopback bind without a data key is rejected, with a key it is served", async () => {
+ const anon = await handleLiveMeterData(get("http://10.0.0.2:1/v1/usage/live", { origin: "app://-" }), remote, deps);
+ expect(anon.status).toBe(401);
+ expect(anon.headers.get("access-control-allow-origin")).not.toBe("app://-");
+ const wrong = await handleLiveMeterData(get("http://10.0.0.2:1/v1/usage/live", { "x-opencodex-api-key": "nope" }), remote, deps);
+ expect(wrong.status).toBe(401);
+ for (const headers of [{ "x-opencodex-api-key": key.key }, { authorization: `Bearer ${key.key}` }, { "x-api-key": key.key }]) {
+ const ok = await handleLiveMeterData(get("http://10.0.0.2:1/v1/usage/live", { origin: "app://-", ...headers }), remote, deps);
+ expect(ok.status).toBe(200);
+ expect(ok.headers.get("access-control-allow-origin")).toBe("app://-");
+ }
+ });
+
+ test("the app origin is not admitted anywhere else: the data-plane origin policy is unchanged", () => {
+ expect(isAllowedRequestOrigin(get("http://127.0.0.1:1/v1/models", { origin: "app://-", host: "127.0.0.1:1" }), loopback)).toBe(false);
+ });
+
+ test("preflight answers only the Codex desktop origin, with GET only and the exact origin", () => {
+ const pre = (headers: Record, config = loopback) => liveMeterPreflight(new Request("http://127.0.0.1:1/v1/usage/live", { method: "OPTIONS", headers }), config);
+ const ok = pre({ origin: "app://-", host: "127.0.0.1:1", "access-control-request-headers": "x-opencodex-api-key" });
+ expect(ok?.status).toBe(204);
+ expect(ok?.headers.get("access-control-allow-origin")).toBe("app://-");
+ expect(ok?.headers.get("access-control-allow-methods")).toBe("GET, OPTIONS");
+ expect(ok?.headers.get("access-control-allow-headers")).toContain("X-OpenCodex-API-Key");
+ expect(pre({ origin: "https://evil.test", host: "127.0.0.1:1" })).toBeNull();
+ expect(pre({ host: "127.0.0.1:1" })).toBeNull();
+ expect(pre({ origin: "app://-", host: "evil.test" })).toBeNull();
+ });
+});
+
+describe("running server", () => {
+ const envKeys = ["OPENCODEX_HOME", "OPENCODEX_API_AUTH_TOKEN", "OPENCODEX_ADMIN_AUTH_TOKEN"] as const;
+ let saved: Record;
+ let home: string;
+ let codex: IsolatedCodexHome;
+ let server: ReturnType | undefined;
+
+ beforeEach(() => {
+ saved = Object.fromEntries(envKeys.map(k => [k, process.env[k]]));
+ home = mkdtempSync(join(tmpdir(), "ocx-live-meter-server-"));
+ codex = installIsolatedCodexHome();
+ process.env.OPENCODEX_HOME = home;
+ delete process.env.OPENCODEX_API_AUTH_TOKEN;
+ saveConfig({ ...getDefaultConfig(), port: 0, hostname: "127.0.0.1", providers: {} });
+ clearRequestLogsForTests();
+ });
+ afterEach(async () => {
+ await server?.stop(true);
+ server = undefined;
+ clearRequestLogsForTests();
+ for (const k of envKeys) { if (saved[k] === undefined) delete process.env[k]; else process.env[k] = saved[k]; }
+ codex.restore();
+ await removeTreeAfterBackgroundWork(home);
+ }, BACKGROUND_WORK_TEARDOWN_TIMEOUT_MS);
+
+ test("the route, its preflight and the rest of the data plane behave as specified for app://-", async () => {
+ server = startServer(0);
+ getRequestLogEntries().push(row({ timestamp: Date.now(), model: "unlisted-model" }));
+ const base = server.url;
+ const app = { origin: "app://-" };
+ const res = await fetch(new URL("/v1/usage/live", base), { headers: app });
+ expect(res.status).toBe(200);
+ expect(res.headers.get("access-control-allow-origin")).toBe("app://-");
+ const body = await res.json();
+ expect(body.latest).toMatchObject({ model: "unlisted-model", speed: { value: 100, reason: null }, context: { reason: "limit_unknown" } });
+ expect(body.byClient.codex.model).toBe("unlisted-model");
+
+ const pre = await fetch(new URL("/v1/usage/live", base), { method: "OPTIONS", headers: { ...app, "access-control-request-method": "GET" } });
+ expect(pre.status).toBe(204);
+ expect(pre.headers.get("access-control-allow-origin")).toBe("app://-");
+
+ const models = await fetch(new URL("/v1/models", base), { headers: app });
+ expect(models.status).toBe(403);
+ const otherPre = await fetch(new URL("/v1/models", base), { method: "OPTIONS", headers: { ...app, "access-control-request-method": "GET" } });
+ expect(otherPre.status).toBe(403);
+ const postRes = await fetch(new URL("/v1/usage/live", base), { method: "POST", headers: app });
+ expect(postRes.status).not.toBe(200);
+ }, 60000);
+});
diff --git a/tests/server/loopback-listener-admission.test.ts b/tests/server/loopback-listener-admission.test.ts
index ea3075085f7..a03e9c07f68 100644
--- a/tests/server/loopback-listener-admission.test.ts
+++ b/tests/server/loopback-listener-admission.test.ts
@@ -118,6 +118,12 @@ describe("local client inference wires on the loopback listener (#4236)", () =>
);
});
+ test("the live meter is a GET-only read on the loopback listener", () => {
+ // The Codex++ footer reads `http://127.0.0.1:/v1/usage/live`. On a hub whose public
+ // listener binds a tailnet address that is this socket, and the route 404ed here.
+ expect(source).toContain('if (path === "/v1/usage/live") return req.method === "GET";');
+ });
+
test("no /api route joins the allowlist", () => {
// Management discovery is the other destination contract (authenticated ingress). A
// reviewer condition on #4236: `/api/*` must never appear on this listener.
diff --git a/tests/usage/live-meter.test.ts b/tests/usage/live-meter.test.ts
new file mode 100644
index 00000000000..7832c4d397d
--- /dev/null
+++ b/tests/usage/live-meter.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, test } from "bun:test";
+import { liveMeterFromEntry, selectLiveMeterEntries } from "../../src/usage/live-meter";
+import type { RequestLogEntry } from "../../src/server/request-log";
+
+const row = (o: Partial = {}): RequestLogEntry => ({
+ requestId: "r", timestamp: 1, model: "fixture", provider: "p", status: 200, durationMs: 10000,
+ genStartMs: 2000, lastOutputMs: 8000, firstOutputMs: 7000, usageStatus: "reported",
+ usage: { inputTokens: 1000, outputTokens: 600, reasoningOutputTokens: 200 }, ...o,
+} as RequestLogEntry);
+
+describe("live meter speed", () => {
+ test("output tokens over the generation window, reasoning counted once", () => {
+ const m = liveMeterFromEntry(row(), null);
+ expect(m.speed).toEqual({ value: 100, reason: null });
+ expect(m.generationMs).toBe(6000);
+ expect(m.outputTokens).toBe(600);
+ });
+ test("queue time, wall clock and first visible text do not enter the denominator", () => {
+ const a = liveMeterFromEntry(row(), null).speed.value;
+ expect(liveMeterFromEntry(row({ timestamp: 3_600_000, durationMs: 90000, firstOutputMs: 7900 }), null).speed.value).toBe(a);
+ expect(liveMeterFromEntry(row({ genStartMs: 62000, lastOutputMs: 68000, durationMs: 100000 }), null).speed.value).toBe(a);
+ });
+ test("missing window never falls back to duration or first output", () => {
+ for (const d of [{ genStartMs: undefined }, { lastOutputMs: undefined }, { genStartMs: NaN }]) {
+ expect(liveMeterFromEntry(row(d), null).speed).toEqual({ value: null, reason: "generation_timing_missing" });
+ }
+ });
+ test("tiny or invalid windows are not printed as a rate", () => {
+ expect(liveMeterFromEntry(row({ genStartMs: 7950 }), null).speed.reason).toBe("generation_window_too_short");
+ expect(liveMeterFromEntry(row({ genStartMs: 9000 }), null).speed.reason).toBe("invalid_generation_window");
+ expect(liveMeterFromEntry(row({ genStartMs: -1 }), null).speed.reason).toBe("generation_timing_missing");
+ expect(liveMeterFromEntry(row({ lastOutputMs: 10050 }), null).speed.reason).toBe("invalid_generation_window");
+ });
+ test("failed, truncated, cancelled and estimated requests stay unavailable with their reason", () => {
+ const cases: Array<[Partial, string]> = [
+ [{ status: 502 }, "request_failed"], [{ terminalStatus: "incomplete" }, "request_incomplete"],
+ [{ terminalStatus: "failed" }, "request_incomplete"], [{ closeReason: "client_cancel" }, "request_aborted"],
+ [{ status: 499 }, "request_aborted"], [{ closeReason: "body_stall" }, "request_incomplete"],
+ [{ closeReason: "body_overflow" }, "request_incomplete"], [{ usageStatus: "estimated" }, "tokens_estimated"],
+ [{ usage: { inputTokens: 1, outputTokens: 5, estimated: true } }, "tokens_estimated"],
+ [{ usage: undefined }, "usage_missing"], [{ usageStatus: "unsupported" }, "usage_missing"],
+ [{ usage: { inputTokens: 1, outputTokens: 0 } }, "output_missing"],
+ ];
+ for (const [delta, reason] of cases) {
+ const m = liveMeterFromEntry(row(delta), null);
+ expect(m.speed.value).toBeNull();
+ expect(m.speed.reason).toBe(reason as never);
+ }
+ });
+});
+
+describe("live meter cache and context", () => {
+ test("cache percent is cache-read over input, explicit zero stays a measurement", () => {
+ const hit = liveMeterFromEntry(row({ usage: { inputTokens: 1000, outputTokens: 5, cacheReadInputTokens: 870 } }), null);
+ expect(hit.cache).toEqual({ readTokens: 870, inputTokens: 1000, percent: 87, reason: null });
+ expect(liveMeterFromEntry(row({ usage: { inputTokens: 1000, outputTokens: 5, cacheReadInputTokens: 0 } }), null).cache.percent).toBe(0);
+ expect(liveMeterFromEntry(row({ usage: { inputTokens: 1000, outputTokens: 5, cachedInputTokens: 500 } }), null).cache.percent).toBe(50);
+ });
+ test("cache is null, never guessed, when unreported, estimated or synthesized", () => {
+ expect(liveMeterFromEntry(row(), null).cache).toMatchObject({ percent: null, readTokens: null });
+ expect(liveMeterFromEntry(row({ usageStatus: "estimated", usage: { inputTokens: 10, outputTokens: 1, cacheReadInputTokens: 5 } }), null).cache)
+ .toMatchObject({ percent: null, reason: "tokens_estimated" });
+ expect(liveMeterFromEntry(row({ cacheProvenance: "synthesized", usage: { inputTokens: 10, outputTokens: 1, cacheReadInputTokens: 5 } }), null).cache.percent).toBeNull();
+ });
+ test("context used is input plus output, or the absolute context total when the provider gives one", () => {
+ const m = liveMeterFromEntry(row({ usage: { inputTokens: 380_000, outputTokens: 900 } }), 1_000_000);
+ expect(m.context).toEqual({ usedTokens: 380_900, limitTokens: 1_000_000, percent: 38.09, reason: null });
+ const abs = liveMeterFromEntry(row({ usage: { inputTokens: 10, outputTokens: 5, contextTotalTokens: 200 } }), 1000);
+ expect(abs.context.usedTokens).toBe(200);
+ });
+ test("an unknown or invalid limit leaves the percentage null but keeps the used count", () => {
+ for (const limit of [null, 0, -5, NaN]) {
+ const m = liveMeterFromEntry(row(), limit);
+ expect(m.context).toMatchObject({ usedTokens: 1600, limitTokens: null, percent: null, reason: "limit_unknown" });
+ }
+ });
+ test("estimated usage reports no context used", () => {
+ expect(liveMeterFromEntry(row({ usageStatus: "estimated" }), 1000).context)
+ .toMatchObject({ usedTokens: null, percent: null, reason: "tokens_estimated" });
+ });
+ test("the payload carries only numbers, model, provider and client", () => {
+ const m = liveMeterFromEntry(row({ client: "codex_desktop", accountLogLabel: "main", conversationId: "a".repeat(32) }), 1000);
+ expect(Object.keys(m).sort()).toEqual(["cache", "client", "context", "generationMs", "model", "outputTokens", "provider", "speed", "timestamp"]);
+ expect(JSON.stringify(m)).not.toContain("main");
+ });
+});
+
+describe("live meter selection", () => {
+ test("newest overall and per family; auto-review rows never win", () => {
+ const rows = [
+ row({ requestId: "a", timestamp: 10, client: "codex_desktop" }),
+ row({ requestId: "b", timestamp: 20, client: "claude_code" }),
+ row({ requestId: "c", timestamp: 30, client: "codex_cli", model: "codex-auto-review" }),
+ row({ requestId: "d", timestamp: 15, client: "codex_cli" }),
+ row({ requestId: "e", timestamp: 40, client: "unknown" }),
+ ];
+ const sel = selectLiveMeterEntries(rows);
+ expect(sel.overall?.requestId).toBe("e");
+ expect(sel.byFamily.codex?.requestId).toBe("d");
+ expect(sel.byFamily.claude?.requestId).toBe("b");
+ expect(sel.byFamily.other).toBeUndefined();
+ });
+ test("a conversation matcher narrows the candidates", () => {
+ const rows = [row({ requestId: "a", timestamp: 10, conversationId: "x" }), row({ requestId: "b", timestamp: 20, conversationId: "y" })];
+ expect(selectLiveMeterEntries(rows, e => e.conversationId === "x").overall?.requestId).toBe("a");
+ expect(selectLiveMeterEntries(rows, () => false).overall).toBeNull();
+ });
+});