Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

fix(cli): show scan usage timestamps and account allowance (#1911)

Michael D'Angelo3c68266a11a2
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index 5b95ba43d..d86b2159b 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -385,6 +385,10 @@ Deep discovery retains its enforced deadline, with a default and maximum of
### Progress and cost
Use `onProgress` for scan progress and `onCost` for cost updates.
+Use `onUsageObservation` for the last reported token measurement time
+(`tokensUpdatedAt`) and account-wide allowance readings (`accountRateLimits`).
+Each reading includes its own `observedAt` timestamp and the percentage used in
+each reported window. A limit-only update can arrive before any token measurement.
Follow scans with `onWorkerEvent` and `onReconnect`. `onWorkerEvent` reports
persisted worker sessions discovered by the SDK's existing session tracker,
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index 84f5aa1de..d8d480380 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -1023,6 +1023,14 @@ work could not be measured, including in-flight turns or missing earlier attempt
The parent can continue after report completion, so final CLI tokens can exceed
the saved measurement window.
+During a scan, progress shows when Codex reported the displayed token and cost
+totals, in UTC. If the report has no timestamp, progress says so.
+In-flight requests may add tokens and cost after that time. When Codex supplies
+account allowance, progress shows the percentage used in each reported window
+and the time of that reading. On a short terminal, resize the window or press
+`d` to scroll through the full readings in Details. With ChatGPT authentication,
+progress also says when Codex has yet to report allowance.
+
`usage.accountRateLimits` saves the latest observed account-wide readings with
their own timestamps, window durations, and reset times. These are historical
observations, not a live allowance check or scan-only consumption. Empty readings
diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjs
index f840cc29e..53deeee0b 100644
--- a/sdk/typescript/scripts/package-dist-files.mjs
+++ b/sdk/typescript/scripts/package-dist-files.mjs
@@ -95,6 +95,7 @@ const distModules = [
"scan-history-renderer",
"scan-inputs",
"scan-logs",
+ "scan-usage-display",
"security-policy",
"security-policy-cli",
"security-policy-diff",
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index c0f3fa92d..c50b7a8cf 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -97,6 +97,7 @@ import {
ScanCostTracker,
type ScanCost,
type ScanSessionEvent,
+ type ScanUsageObservation,
type ScanWorkerEvent,
} from "./cost.js";
import type { ScanTokenUsage } from "./cost-model.js";
@@ -339,6 +340,8 @@ export interface ScanOptions extends ScanSettings {
onCost?: (cost: Readonly<ScanCost>, maxCostUsd?: number) => void;
/** Observed tokens, including models without a price estimate. */
onUsage?: (usage: Readonly<ScanTokenUsage>) => void;
+ /** The last reportable token total's measurement time and latest account limits from this scan's sessions. */
+ onUsageObservation?: (observation: ScanUsageObservation) => void;
onBudgetApproaching?: (
budget: ScanBudget,
) => number | undefined | Promise<number | undefined>;
@@ -587,6 +590,7 @@ type ScanObserverName =
| "onAuthentication"
| "onCost"
| "onUsage"
+ | "onUsageObservation"
| "onOutputArchived"
| "onOutputDirReady"
| "onScanRegistered"
@@ -2367,6 +2371,10 @@ export class CodexSecurity {
options.onUsage === undefined
? undefined
: (usage) => notifyObserver(options, "onUsage")(usage),
+ onUsageObservation:
+ options.onUsageObservation === undefined
+ ? undefined
+ : notifyObserver(options, "onUsageObservation"),
onActivity:
options.onActivity === undefined
? undefined
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 5a95ca55a..6059f4438 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -300,6 +300,13 @@ import {
type HistoryCommand,
} from "./scan-history-renderer.js";
import { ScanDashboard } from "./scan-dashboard.js";
+import {
+ ACCOUNT_LIMITS_UNAVAILABLE,
+ formatAccountLimits,
+ formatUsageFreshness,
+ isChatGptAuthentication,
+ USAGE_TIME_UNAVAILABLE,
+} from "./scan-usage-display.js";
import {
policyDisplayData,
runPolicyCommand,
@@ -5100,10 +5107,12 @@ export async function main(
componentName,
event,
options.showCost || settings.maxCostUsd !== undefined,
+ settings.auth,
);
if (line !== null) errorOutput.write(line);
}
- : (event) => dashboard?.recordComponentEvent(event),
+ : (event) =>
+ dashboard?.recordComponentEvent(event, settings.auth),
onDeduplicationStarted: () => {
if (dashboard !== null)
dashboard.showComponents("Combining duplicate findings");
@@ -9158,6 +9167,8 @@ async function executeScan(
let deepConsolidating = false;
let runningCost: Readonly<ScanCost> | null = null;
let runningUsage: Readonly<ScanTokenUsage> | null = null;
+ let usageFreshness: string | null = null;
+ let accountLimits: string | null = null;
let maxCostUsd = arguments_.maxCostUsd;
const showCost = arguments_.showCost === true || maxCostUsd !== undefined;
let phase: string | null = null;
@@ -9392,6 +9403,9 @@ async function executeScan(
input: scanInput,
onInterrupt,
});
+ dashboard.setChatGptAuth(
+ isChatGptAuthentication(selectedAuthentication, auth),
+ );
}
const scope = scanScope(arguments_);
const runningMessage = (): string => {
@@ -9426,6 +9440,11 @@ async function executeScan(
if (showCost && runningCost !== null) {
details.push(`Cost: ${formatScanCost(runningCost)}`);
}
+ if (tokens !== null)
+ details.push(usageFreshness ?? USAGE_TIME_UNAVAILABLE);
+ if (accountLimits !== null) details.push(diagnosticValue(accountLimits));
+ else if (isChatGptAuthentication(selectedAuthentication, auth))
+ details.push(ACCOUNT_LIMITS_UNAVAILABLE);
return details.length === 0 ? stage : `${stage} | ${details.join(" | ")}`;
};
if (dashboard === null) {
@@ -9463,6 +9482,22 @@ async function executeScan(
archiveExisting: arguments_.archiveExisting,
parentScanId: arguments_.parentScanId,
expectedPluginVersion: arguments_.expectedPluginVersion,
+ onUsageObservation: async (observation) => {
+ if (dashboard !== null) {
+ dashboard.setUsageObservation(observation);
+ return;
+ }
+ usageFreshness = formatUsageFreshness(observation);
+ accountLimits = formatAccountLimits(observation);
+ const priorUsage = runningUsage;
+ const priorCost = runningCost;
+ // Usage and cost callbacks render the same poll. Refresh here for a receipt alone.
+ await Promise.resolve();
+ if (runningUsage === priorUsage && runningCost === priorCost) {
+ progress?.stopTimer();
+ progress?.startTimer(runningMessage());
+ }
+ },
onUsage: async (usage) => {
runningUsage = usage;
if (dashboard !== null) {
@@ -9539,6 +9574,9 @@ async function executeScan(
},
onAuthentication: (authentication) => {
selectedAuthentication = authentication;
+ dashboard?.setChatGptAuth(
+ isChatGptAuthentication(authentication, auth),
+ );
const bedrock =
providerOptions.provider === "amazon-bedrock" ||
authentication.method === "aws_credentials";
@@ -10669,7 +10707,13 @@ function componentScanEventLine(
componentName: string,
event: ComponentScanEvent,
showCost: boolean,
+ requestedAuth?: ScanAuthMode,
): string | null {
+ if (event.type === "authentication") {
+ return isChatGptAuthentication(event.value, requestedAuth)
+ ? `codex-security: ${componentName} | ${ACCOUNT_LIMITS_UNAVAILABLE}\n`
+ : null;
+ }
if (event.type === "progress") {
const progress = event.value;
const count = scanProgressCount(progress);
@@ -10681,6 +10725,13 @@ function componentScanEventLine(
? null
: `codex-security: ${componentName} | Tokens: ${tokens}\n`;
}
+ if (event.type === "usage-observation") {
+ const details = [
+ formatUsageFreshness(event.value) ?? USAGE_TIME_UNAVAILABLE,
+ formatAccountLimits(event.value),
+ ].filter((detail) => detail !== null);
+ return `codex-security: ${componentName} | ${diagnosticValue(details.join(" | "))}\n`;
+ }
if (event.type !== "cost" || !showCost) return null;
return `codex-security: ${componentName} | Cost: ${formatScanCost(event.value)}\n`;
}
diff --git a/sdk/typescript/src/component-scan.ts b/sdk/typescript/src/component-scan.ts
index 774a71fe3..f6076d578 100644
--- a/sdk/typescript/src/component-scan.ts
+++ b/sdk/typescript/src/component-scan.ts
@@ -8,6 +8,7 @@ import {
scanAuthentication,
selectedScanEnvironment,
type CodexSecuritySurface,
+ type ScanAuthentication,
type ScanOptions,
} from "./api.js";
import {
@@ -22,7 +23,11 @@ import {
scanModelProvider,
type CodexSecurityConfig,
} from "./config.js";
-import type { ScanCost, ScanSessionEvent } from "./cost.js";
+import type {
+ ScanCost,
+ ScanSessionEvent,
+ ScanUsageObservation,
+} from "./cost.js";
import type { ScanTokenUsage } from "./cost-model.js";
import { readThreatModelPath } from "./artifact-export.js";
import { errorMessage } from "./errors.js";
@@ -81,11 +86,13 @@ export interface ComponentReceipt {
}
type ComponentScanUpdate =
+ | { type: "authentication"; value: ScanAuthentication }
| { type: "progress"; value: ScanProgress }
| { type: "activity"; value: ScanActivity }
| { type: "session"; value: ScanSessionEvent }
| { type: "cost"; value: Readonly<ScanCost> }
| { type: "usage"; value: Readonly<ScanTokenUsage> }
+ | { type: "usage-observation"; value: Readonly<ScanUsageObservation> }
| { type: "workers"; value: ScanWorkerStatus }
| { type: "warning"; value: string };
@@ -217,11 +224,15 @@ export async function runComponentScans(
options.onScanEvent === undefined
? {}
: {
+ onAuthentication: (value) =>
+ emit({ type: "authentication", value }),
onProgress: (value) => emit({ type: "progress", value }),
onActivity: (value) => emit({ type: "activity", value }),
onSessionEvent: (value) => emit({ type: "session", value }),
onCost: (value) => emit({ type: "cost", value }),
onUsage: (value) => emit({ type: "usage", value }),
+ onUsageObservation: (value) =>
+ emit({ type: "usage-observation", value }),
onWorkerStatus: (value) => emit({ type: "workers", value }),
onWarning: (value) => emit({ type: "warning", value }),
};
diff --git a/sdk/typescript/src/cost.ts b/sdk/typescript/src/cost.ts
index 5faa6723b..23300da9f 100644
--- a/sdk/typescript/src/cost.ts
+++ b/sdk/typescript/src/cost.ts
@@ -2,6 +2,8 @@ import { parseJson } from "./value.js";
import { open, readdir, stat } from "node:fs/promises";
import { join } from "node:path";
import { StringDecoder } from "node:string_decoder";
+import { isDeepStrictEqual } from "node:util";
+import { z } from "zod";
import { isRecord } from "./record.js";
import {
estimateScanCost,
@@ -27,6 +29,43 @@ import {
export { estimateScanCost, formatUsd, type ScanCost } from "./cost-model.js";
+export interface ScanAccountRateLimitWindow {
+ readonly usedPercent: number;
+ readonly windowMinutes: number | null;
+ /** Unix time in seconds. */
+ readonly resetsAt: number | null;
+}
+
+export interface ScanAccountRateLimit {
+ readonly limitId: string;
+ readonly observedAt: string;
+ readonly primary: ScanAccountRateLimitWindow | null;
+ readonly secondary: ScanAccountRateLimitWindow | null;
+}
+
+export interface ScanUsageObservation {
+ /** Latest native measurement in the last reportable total, or null when its time is unknown. */
+ readonly tokensUpdatedAt: string | null;
+ readonly accountRateLimits: readonly ScanAccountRateLimit[];
+}
+
+const rateLimitWindow = z
+ .object({
+ used_percent: z.number(),
+ window_minutes: z.number().int().nullish(),
+ resets_at: z.number().int().nullish(),
+ })
+ .transform((window): ScanAccountRateLimitWindow => ({
+ usedPercent: window.used_percent,
+ windowMinutes: window.window_minutes ?? null,
+ resetsAt: window.resets_at ?? null,
+ }));
+const rateLimitSnapshot = z.object({
+ limit_id: z.string().nullish(),
+ primary: rateLimitWindow.nullish(),
+ secondary: rateLimitWindow.nullish(),
+});
+
/** A persisted worker session discovered during this run. Contains no model text. */
export interface ScanWorkerEvent {
kind: "observed";
@@ -61,6 +100,7 @@ interface ScanCostTrackerOptions {
/** Incomplete costs are measured subtotals, usable for spending limits only. */
onCost?: (cost: Readonly<ScanCost>, complete: boolean) => void;
onUsage?: (usage: Readonly<ScanTokenUsage>) => void;
+ onUsageObservation?: (observation: ScanUsageObservation) => void;
onActivity?: (activity: ScanActivity) => void;
onProgress?: (progress: ScanProgress) => void;
onSessionEvent?: (event: ScanSessionEvent) => void;
@@ -76,7 +116,7 @@ interface ScanCostSnapshot {
const COST_POLL_INTERVAL_MS = 100;
const SESSION_READ_SIZE = 64 * 1_024;
-function createSessionUsage() {
+function createSessionUsage(observeUsage: boolean) {
return {
offset: 0,
decoder: new StringDecoder("utf8"),
@@ -89,6 +129,10 @@ function createSessionUsage() {
inheritedUsage: null as ScanTokenUsage | null,
replaying: false,
usage: null as ScanTokenUsage | null,
+ tokensUpdatedAt: null as string | null,
+ accountRateLimits: observeUsage
+ ? new Map<string, ScanAccountRateLimit>()
+ : null,
responseUsage: null as ScanTokenUsage | null,
responseIds: new Set<string>(),
calls: new Map<string, ScanActivity>(),
@@ -116,6 +160,7 @@ export class ScanCostTracker {
#snapshot: ScanCostSnapshot = { usage: null, cost: null };
#lastCost: string | null = null;
#lastUsage: string | null = null;
+ #lastObservation: ScanUsageObservation | null = null;
#highestFilesCompleted = 0;
#expectedFilesTotal: number | undefined;
@@ -142,6 +187,7 @@ export class ScanCostTracker {
this.#options.maxCostUsd === undefined &&
this.#options.onCost === undefined &&
this.#options.onUsage === undefined &&
+ this.#options.onUsageObservation === undefined &&
this.#options.onActivity === undefined &&
this.#options.onProgress === undefined &&
this.#options.onSessionEvent === undefined &&
@@ -203,6 +249,7 @@ export class ScanCostTracker {
async #readSessions(): Promise<void> {
if (this.#threadId === null) return;
+ const observeUsage = this.#options.onUsageObservation !== undefined;
const repository =
this.#options.onActivity === undefined
? undefined
@@ -213,7 +260,7 @@ export class ScanCostTracker {
)) {
let session = this.#sessions.get(path);
if (session === undefined) {
- session = createSessionUsage();
+ session = createSessionUsage(observeUsage);
this.#sessions.set(path, session);
}
try {
@@ -278,7 +325,7 @@ export class ScanCostTracker {
session.events === undefined
) {
// Replay only newly associated sessions, including their early events.
- session = createSessionUsage();
+ session = createSessionUsage(observeUsage);
session.events = [];
await readSessionUsage(path, session, repository);
this.#sessions.set(path, session);
@@ -334,6 +381,7 @@ export class ScanCostTracker {
}
usage = addTokenUsage(usage, value);
}
+ if (observeUsage) this.#reportUsageObservation(usages, complete);
if (!complete) this.#snapshot = { usage: null, cost: null };
if (usage === null) return;
const cost = estimateScanCost(this.#options.model, usage);
@@ -344,6 +392,54 @@ export class ScanCostTracker {
this.#reportCost(cost, complete);
}
+ #reportUsageObservation(
+ usages: ReadonlyMap<string, ScanTokenUsage | null>,
+ complete: boolean,
+ ): void {
+ const limits = new Map<string, ScanAccountRateLimit>();
+ const timed = new Set<string>();
+ let tokensUpdatedAt: string | null = null;
+ for (const session of this.#sessions.values()) {
+ const id = session.threadId;
+ if (id === null || !usages.has(id) || session.accountRateLimits === null)
+ continue;
+ for (const limit of session.accountRateLimits.values())
+ retainLatestRateLimit(limits, limit);
+ if (
+ session.tokensUpdatedAt !== null &&
+ isDeepStrictEqual(usages.get(id), session.usage)
+ ) {
+ timed.add(id);
+ if (session.tokensUpdatedAt > (tokensUpdatedAt ?? ""))
+ tokensUpdatedAt = session.tokensUpdatedAt;
+ }
+ }
+ if (!complete) {
+ // The display retains the last complete aggregate while a worker is unmeasured.
+ tokensUpdatedAt = this.#lastObservation?.tokensUpdatedAt ?? null;
+ } else if (
+ usages
+ .entries()
+ .some(([id, usage]) => (usage?.total_tokens ?? 0) > 0 && !timed.has(id))
+ ) {
+ // A newer SDK fallback can supersede its thread's timestamped rollout receipt.
+ tokensUpdatedAt = null;
+ }
+ if (
+ this.#lastObservation === null &&
+ tokensUpdatedAt === null &&
+ limits.size === 0
+ )
+ return;
+ const observation = {
+ tokensUpdatedAt,
+ accountRateLimits: [...limits.values()],
+ };
+ if (isDeepStrictEqual(observation, this.#lastObservation)) return;
+ this.#lastObservation = observation;
+ this.#options.onUsageObservation?.(observation);
+ }
+
#reportWorkerProgress(session: SessionUsage): void {
if (this.#options.onProgress === undefined || session.threadId === null) {
return;
@@ -536,6 +632,7 @@ function readSessionEvent(
session.usage === null ||
recorded.total_tokens >= session.usage.total_tokens
) {
+ observeUsageEvent(session, event["timestamp"], recorded);
session.usage = recorded;
}
return;
@@ -655,32 +752,69 @@ function readSessionEvent(
}
return;
}
- if (
- event["type"] !== "event_msg" ||
- payload["type"] !== "token_count" ||
- !isRecord(payload["info"])
- ) {
+ if (event["type"] !== "event_msg" || payload["type"] !== "token_count") {
return;
}
- const usage = tokenUsage(payload["info"]["total_token_usage"]);
- if (usage === null) return;
+ const usage = isRecord(payload["info"])
+ ? tokenUsage(payload["info"]["total_token_usage"])
+ : null;
const ownUsage =
- session.inheritedUsage === null
+ session.inheritedUsage === null || usage === null
? usage
: subtractTokenUsage(usage, session.inheritedUsage);
// Older runtimes only emit token_count. In newer rollouts these snapshots can
// lag compaction receipts, so do not replace a more complete native total.
- if (
+ const measured =
ownUsage !== null &&
(session.usage === null ||
ownUsage.total_tokens > session.usage.total_tokens ||
(session.responseUsage === null &&
- ownUsage.total_tokens === session.usage.total_tokens))
- ) {
- session.usage = ownUsage;
+ ownUsage.total_tokens === session.usage.total_tokens));
+ observeUsageEvent(
+ session,
+ event["timestamp"],
+ measured ? ownUsage : null,
+ payload["rate_limits"],
+ );
+ if (measured) session.usage = ownUsage;
+}
+
+function observeUsageEvent(
+ session: SessionUsage,
+ timestamp: unknown,
+ measured: ScanTokenUsage | null,
+ rateLimits?: unknown,
+): void {
+ if (session.accountRateLimits === null) return;
+ const time = sessionStartedAt(timestamp);
+ if (time === null) {
+ if (measured !== null && !isDeepStrictEqual(measured, session.usage))
+ session.tokensUpdatedAt = null;
+ return;
+ }
+ const observedAt = new Date(time).toISOString();
+ if (measured !== null && observedAt > (session.tokensUpdatedAt ?? ""))
+ session.tokensUpdatedAt = observedAt;
+ if (rateLimits == null) return;
+ const parsed = rateLimitSnapshot.safeParse(rateLimits);
+ if (parsed.success) {
+ retainLatestRateLimit(session.accountRateLimits, {
+ limitId: parsed.data.limit_id || "codex",
+ observedAt,
+ primary: parsed.data.primary ?? null,
+ secondary: parsed.data.secondary ?? null,
+ });
}
}
+function retainLatestRateLimit(
+ limits: Map<string, ScanAccountRateLimit>,
+ limit: ScanAccountRateLimit,
+): void {
+ if (limit.observedAt >= (limits.get(limit.limitId)?.observedAt ?? ""))
+ limits.set(limit.limitId, limit);
+}
+
function readSessionReasoning(
event: Readonly<Record<string, unknown>>,
payload: Readonly<Record<string, unknown>>,
diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts
index 78224a208..c8364acdb 100644
--- a/sdk/typescript/src/index.ts
+++ b/sdk/typescript/src/index.ts
@@ -88,7 +88,14 @@ export type {
ComponentPlanningOptions,
} from "./component-plan.js";
export { estimateScanCost } from "./cost.js";
-export type { ScanCost, ScanSessionEvent, ScanWorkerEvent } from "./cost.js";
+export type {
+ ScanAccountRateLimit,
+ ScanAccountRateLimitWindow,
+ ScanCost,
+ ScanSessionEvent,
+ ScanUsageObservation,
+ ScanWorkerEvent,
+} from "./cost.js";
export type { ScanTokenUsage } from "./cost-model.js";
export type { DeepScanProgress } from "./scan-progress.js";
export type { CustomValidationResult } from "./custom-validation.js";
diff --git a/sdk/typescript/src/scan-dashboard.ts b/sdk/typescript/src/scan-dashboard.ts
index ef6b6aff4..72b429925 100644
--- a/sdk/typescript/src/scan-dashboard.ts
+++ b/sdk/typescript/src/scan-dashboard.ts
@@ -5,14 +5,19 @@ import { pathToFileURL } from "node:url";
import stripAnsi from "strip-ansi";
import stringWidth from "string-width";
import { isRecord } from "./record.js";
-import type { ScanBudget } from "./api.js";
+import type { ScanAuthMode, ScanBudget } from "./api.js";
import type { ScanModelConfiguration } from "./config.js";
import type {
ComponentReceipt,
ComponentScanEvent,
ComponentScanResult,
} from "./component-scan.js";
-import { formatUsd, type ScanCost, type ScanSessionEvent } from "./cost.js";
+import {
+ formatUsd,
+ type ScanCost,
+ type ScanSessionEvent,
+ type ScanUsageObservation,
+} from "./cost.js";
import {
estimateScanCost,
formatScanCost,
@@ -22,6 +27,13 @@ import {
type ScanTokenUsage,
} from "./cost-model.js";
import type { ScanActivity } from "./scan-activity.js";
+import {
+ ACCOUNT_LIMITS_UNAVAILABLE,
+ USAGE_TIME_UNAVAILABLE,
+ formatAccountLimits,
+ formatUsageFreshness,
+ isChatGptAuthentication,
+} from "./scan-usage-display.js";
import type { ScanMode } from "./targets.js";
import {
scanPhaseLabel,
@@ -38,7 +50,7 @@ const DISABLE_ALTERNATE_SCROLL = "\u001B[?1007l";
const CURSOR_HOME = "\u001B[H";
const ERASE_LINE = "\u001B[2K";
const MAX_HISTORY_ENTRIES = 2_000;
-const FIXED_SCREEN_ROWS = 8;
+const FIXED_SCREEN_ROWS = 4; // Title, two dividers and elapsed time.
interface DashboardStream {
write(chunk: string, callback?: (error?: Error | null) => void): unknown;
@@ -152,6 +164,9 @@ export class ScanDashboard {
#publicationProgress: { completed: number; total: number } | null = null;
#cost: Readonly<ScanCost> | null = null;
#tokens: string | null = null;
+ #usageFreshness: string | null = null;
+ #accountLimits: string | null = null;
+ #chatGptAuth = false;
#budget: {
request: ScanBudget;
input: string;
@@ -491,7 +506,10 @@ export class ScanDashboard {
this.#refresh();
}
- public recordComponentEvent(event: ComponentScanEvent): void {
+ public recordComponentEvent(
+ event: ComponentScanEvent,
+ requestedAuth?: ScanAuthMode,
+ ): void {
const dashboard = this.#components.find(
({ receipt }) => receipt.id === event.componentId,
)?.dashboard;
@@ -504,6 +522,11 @@ export class ScanDashboard {
case "activity":
dashboard.record(event.value);
break;
+ case "authentication":
+ dashboard.setChatGptAuth(
+ isChatGptAuthentication(event.value, requestedAuth),
+ );
+ break;
case "session":
dashboard.recordDetails(event.value);
break;
@@ -513,6 +536,9 @@ export class ScanDashboard {
case "usage":
dashboard.setUsage(event.value);
break;
+ case "usage-observation":
+ dashboard.setUsageObservation(event.value);
+ break;
case "workers":
if (event.value.kind === "dispatch")
dashboard.setStage(scanPhaseLabel(event.value.phase));
@@ -563,6 +589,19 @@ export class ScanDashboard {
this.#refresh();
}
+ public setUsageObservation(
+ observation: Readonly<ScanUsageObservation>,
+ ): void {
+ this.#usageFreshness = formatUsageFreshness(observation);
+ this.#accountLimits = formatAccountLimits(observation);
+ this.#refresh();
+ }
+
+ public setChatGptAuth(enabled: boolean): void {
+ this.#chatGptAuth = enabled;
+ this.#refresh();
+ }
+
public requestBudgetIncrease(
request: ScanBudget,
): Promise<number | undefined> {
@@ -666,9 +705,12 @@ export class ScanDashboard {
}
public scroll(lines: number): void {
+ const { footer, details } = this.#usageLayout();
const maximum = Math.max(
0,
- this.#activityLines(this.#width()).length - this.#activityRows(),
+ this.#activityLines(this.#width()).length +
+ details.length -
+ this.#activityRows(footer.length),
);
this.#scrollOffset = Math.max(
0,
@@ -703,7 +745,9 @@ export class ScanDashboard {
const verification = this.#options.presentation === "verification";
const findingProgress = publication || verification;
const width = this.#width();
- const activityRows = this.#activityRows();
+ const { footer, details } = this.#usageLayout();
+ const availableRows = this.#availableActivityRows(footer.length);
+ const activityRows = Math.max(1, availableRows);
const divider = ` ${"─".repeat(Math.max(0, width - 4))}`;
const elapsed = Math.max(
0,
@@ -722,7 +766,8 @@ export class ScanDashboard {
: count.completed > 0
? `${formatCount(count.completed)} / ${formatCount(count.total)} reviewed`
: `${formatCount(count.total)} in scope`;
- const history = this.#activityLines(width);
+ let history = this.#activityLines(width);
+ if (details.length > 0) history = history.concat(details);
const maximumOffset = Math.max(0, history.length - activityRows);
this.#scrollOffset = Math.min(this.#scrollOffset, maximumOffset);
const first = Math.max(
@@ -755,9 +800,9 @@ export class ScanDashboard {
return this.#formatFrame([
` CODEX SECURITY · ${publication ? "PUBLISH · " : verification ? "VERIFY-FIX · " : ""}${basename(this.#options.repository)}${this.#options.componentName === undefined ? "" : ` · ${this.#options.componentName}`}${model === undefined ? "" : ` · ${model.model} (${model.reasoningEffort})`}${this.#view === "details" ? ` · DETAILS${this.#source === "all" ? "" : ` · ${typeof this.#source === "number" ? `worker ${this.#source}` : this.#source}`}` : ""}`,
- divider,
+ ...(availableRows > 0 ? [divider] : []),
...activity,
- divider,
+ ...(availableRows >= 0 ? [divider] : []),
...(findingProgress
? [
` STAGE ${this.#stage}`,
@@ -770,8 +815,7 @@ export class ScanDashboard {
` STAGE ${this.#stage}`,
` ${count?.label === "reviews" ? "REVIEWS" : "FILES "} ${files}`,
]),
- ...this.#tokenLines(),
- ...this.#costLines(),
+ ...footer,
...(this.#budget === null
? []
: [
@@ -973,28 +1017,67 @@ export class ScanDashboard {
return Math.max(1, Math.min(this.#stream.columns ?? 88, 160));
}
- #activityRows(): number {
- return Math.max(
- 1,
+ #activityRows(usageRows = this.#usageLayout().footer.length): number {
+ return Math.max(1, this.#availableActivityRows(usageRows));
+ }
+
+ #availableActivityRows(usageRows: number): number {
+ const findingProgress =
+ this.#options.presentation === "publication" ||
+ this.#options.presentation === "verification";
+ const stageRows = this.#options.mode === "deep" && !findingProgress ? 0 : 2;
+ return (
(this.#stream.rows ?? 24) -
- FIXED_SCREEN_ROWS -
- (this.#budget === null ? 0 : 2) -
- (this.#options.presentation === "publication" ||
- this.#options.presentation === "verification"
- ? 0
- : this.#tokenLines().length - 1 + this.#costLines().length - 1) +
- (this.#options.presentation === "publication" ||
- this.#options.presentation === "verification"
- ? 2
- : this.#options.mode === "deep"
- ? 2
- : 0),
+ FIXED_SCREEN_ROWS -
+ stageRows -
+ usageRows -
+ (this.#budget === null ? 0 : 2)
);
}
- #tokenLines(): string[] {
- const tokens = this.#tokens ?? "waiting for usage";
- return wrapActivity(" TOKENS ", tokens, this.#width());
+ #usageLayout(): { footer: string[]; details: DashboardActivityLine[] } {
+ if (
+ this.#options.presentation === "publication" ||
+ this.#options.presentation === "verification"
+ ) {
+ return { footer: [], details: [] };
+ }
+ const width = this.#width();
+ const limits =
+ this.#accountLimits ??
+ (this.#chatGptAuth ? ACCOUNT_LIMITS_UNAVAILABLE : null);
+ const lines = [
+ ...wrapActivity(
+ " TOKENS ",
+ this.#tokens ?? "waiting for usage",
+ width,
+ ),
+ ...this.#costLines(),
+ ...(this.#tokens === null
+ ? []
+ : wrapActivity(
+ " USAGE ",
+ this.#usageFreshness ?? USAGE_TIME_UNAVAILABLE,
+ width,
+ )),
+ ...(limits === null ? [] : wrapActivity(" LIMITS ", limits, width)),
+ ];
+ // Both dividers can give way, but one activity row must remain.
+ const capacity = Math.max(0, this.#availableActivityRows(0) + 1);
+ if (lines.length <= capacity) return { footer: lines, details: [] };
+ if (this.#view === "details") {
+ return {
+ footer: [],
+ details: lines.map((text) => ({ text, kind: "path" })),
+ };
+ }
+ const footer = lines.slice(0, capacity);
+ if (footer.length > 0)
+ footer[footer.length - 1] =
+ this.#options.input?.isTTY === true
+ ? " … Full readings in details"
+ : " … Resize for full readings";
+ return { footer, details: [] };
}
#costLines(): string[] {
diff --git a/sdk/typescript/src/scan-usage-display.ts b/sdk/typescript/src/scan-usage-display.ts
new file mode 100644
index 000000000..341e1e58a
--- /dev/null
+++ b/sdk/typescript/src/scan-usage-display.ts
@@ -0,0 +1,63 @@
+import type { ScanAuthentication, ScanAuthMode } from "./api.js";
+import type { ScanAccountRateLimit, ScanUsageObservation } from "./cost.js";
+
+export const ACCOUNT_LIMITS_UNAVAILABLE =
+ "ChatGPT allowance not reported by Codex";
+export const USAGE_TIME_UNAVAILABLE =
+ "Usage report time unavailable · in-flight usage may be missing";
+
+export function isChatGptAuthentication(
+ authentication: ScanAuthentication | null,
+ requested?: ScanAuthMode,
+): boolean {
+ return (
+ authentication?.method === "stored_credentials" &&
+ (authentication.credentialType ?? requested) === "chatgpt"
+ );
+}
+
+function receiptTime(timestamp: string): string {
+ return `${timestamp.slice(0, 10)} ${timestamp.slice(11, 19)} UTC`;
+}
+
+export function formatUsageFreshness(
+ observation: Readonly<ScanUsageObservation>,
+): string | null {
+ return observation.tokensUpdatedAt === null
+ ? null
+ : `Last usage report ${receiptTime(observation.tokensUpdatedAt)} · in-flight usage may be missing`;
+}
+
+function formatWindow(
+ window: ScanAccountRateLimit["primary"],
+ name: string,
+): string | null {
+ if (window === null) return null;
+ const minutes = window.windowMinutes;
+ let duration = name;
+ if (minutes !== null) {
+ if (minutes % 1440 === 0) duration = `${minutes / 1440}d`;
+ else if (minutes % 60 === 0) duration = `${minutes / 60}h`;
+ else duration = `${minutes}m`;
+ }
+ return `${duration} ${window.usedPercent}% used`;
+}
+
+export function formatAccountLimits(
+ observation: Readonly<ScanUsageObservation>,
+): string | null {
+ const readings = observation.accountRateLimits.flatMap((limit) => {
+ const windows = [
+ formatWindow(limit.primary, "primary"),
+ formatWindow(limit.secondary, "secondary"),
+ ].filter((window) => window !== null);
+ return windows.length === 0
+ ? []
+ : [
+ `${limit.limitId} ${windows.join(", ")} (as of ${receiptTime(limit.observedAt)})`,
+ ];
+ });
+ return readings.length === 0
+ ? null
+ : `Account allowance: ${readings.join(" | ")}`;
+}
diff --git a/sdk/typescript/tests-ts/cli-show-cost.test.ts b/sdk/typescript/tests-ts/cli-show-cost.test.ts
index 457b5b3d0..eb6e2249d 100644
--- a/sdk/typescript/tests-ts/cli-show-cost.test.ts
+++ b/sdk/typescript/tests-ts/cli-show-cost.test.ts
@@ -97,6 +97,50 @@ const observedUsage: ScanTokenUsage = {
total_tokens: 1280,
};
+test("headless scan reports account limits independently of token receipts", async () => {
+ const { stdout, stderr, runCli } = createCliTest(main);
+ const deps = dependencies();
+ deps.createSecurity = () =>
+ fakeSecurity(async (_repository, options = {}) => {
+ options.onAuthentication?.({
+ method: "stored_credentials",
+ credentialType: "chatgpt",
+ verified: false,
+ });
+ options.onScanStarted?.();
+ expect(stderr.text()).toContain("ChatGPT allowance not reported");
+ const accountRateLimits = [
+ {
+ limitId: "codex",
+ observedAt: "2026-01-01T14:02:00.000Z",
+ primary: null,
+ secondary: { usedPercent: 87, windowMinutes: 10080, resetsAt: null },
+ },
+ ];
+ await options.onUsageObservation?.({
+ tokensUpdatedAt: null,
+ accountRateLimits,
+ });
+ expect(stderr.text()).toContain("7d 87% used");
+ expect(stderr.text()).not.toContain("Last usage report");
+ options.onUsageObservation?.({
+ tokensUpdatedAt: "2026-01-01T14:03:00.000Z",
+ accountRateLimits,
+ });
+ await options.onUsage?.(observedUsage);
+ options.onScanStarted?.();
+ const progress = stderr.text().trim().split("\n").at(-1)!;
+ expect(progress).toContain("1,280 total");
+ expect(progress).toContain("14:03:00 UTC");
+ expect(progress).toContain("in-flight");
+ expect(progress).toContain("14:02:00 UTC");
+ expect(progress).not.toContain("$");
+ return result;
+ });
+ expect(await runCli(["scan", ".", "--headless", "--json"], deps)).toBe(0);
+ expect(JSON.parse(stdout.text())).toEqual(result.toJSON());
+});
+
test.each([
{ name: "headless", args: ["--headless"], tty: true, environment: {} },
{ name: "CI", args: [], tty: true, environment: { CI: "true" } },
@@ -120,7 +164,9 @@ test.each([
expect(stderr.text()).toContain("1,280 total");
expect(stderr.text()).not.toContain("REPORT");
options.onScanStarted?.();
- expect(stderr.text().trim().split("\n").at(-1)).toContain("1,280 total");
+ const progress = stderr.text().trim().split("\n").at(-1);
+ expect(progress).toContain("1,280 total");
+ expect(progress).toContain("Usage report time unavailable");
return unpriced;
});
expect(await runCli(["scan", ".", ...mode.args], deps)).toBe(0);
diff --git a/sdk/typescript/tests-ts/component-scan.test.ts b/sdk/typescript/tests-ts/component-scan.test.ts
index 9d563a5a4..ae44f296b 100644
--- a/sdk/typescript/tests-ts/component-scan.test.ts
+++ b/sdk/typescript/tests-ts/component-scan.test.ts
@@ -491,6 +491,10 @@ test("forwards scan events with their component identity without letting observe
createSecurity: client(async (repository, options) => {
expect(planned).toBe(true);
const target = scope(repository, options);
+ options.onAuthentication?.({
+ method: "stored_credentials",
+ verified: false,
+ });
options.onProgress?.({
phase: "discovery",
filesCompleted: 1,
@@ -517,6 +521,17 @@ test("forwards scan events with their component identity without letting observe
reasoning_output_tokens: 0,
total_tokens: 110,
});
+ options.onUsageObservation?.({
+ tokensUpdatedAt: null,
+ accountRateLimits: [
+ {
+ limitId: target,
+ observedAt: "2026-01-01T00:00:00Z",
+ primary: { usedPercent: 75, windowMinutes: 300, resetsAt: null },
+ secondary: null,
+ },
+ ],
+ });
options.onWorkerStatus?.({
kind: "dispatch",
phase: "validation",
@@ -537,17 +552,24 @@ test("forwards scan events with their component identity without letting observe
({ componentId }) => componentId === `component-${index + 1}`,
);
expect(received.map(({ type }) => type)).toEqual([
+ "authentication",
"progress",
"activity",
"session",
"cost",
"usage",
+ "usage-observation",
"workers",
"warning",
]);
- expect(received[1]).toMatchObject({
+ expect(received.find(({ type }) => type === "activity")).toMatchObject({
value: { description: component.paths.join(",") },
});
+ expect(
+ received.find(({ type }) => type === "usage-observation"),
+ ).toMatchObject({
+ value: { accountRateLimits: [{ limitId: component.paths.join(",") }] },
+ });
}
});
@@ -586,6 +608,17 @@ test.each([
}),
createSecurity: client(async (repository, options) => {
expect(typeof options.onProgress).toBe("function");
+ options.onAuthentication?.({
+ method: "stored_credentials",
+ credentialType: presentation === "ci" ? "api_key" : "chatgpt",
+ verified: false,
+ });
+ if (presentation !== "dashboard")
+ expect(
+ stderr
+ .text()
+ .includes("apps/api | ChatGPT allowance not reported"),
+ ).toBe(presentation === "headless");
options.onProgress?.({
phase: "validation",
filesCompleted: 2,
@@ -599,6 +632,10 @@ test.each([
reasoning_output_tokens: 0,
total_tokens: 120,
});
+ options.onUsageObservation?.({
+ tokensUpdatedAt: "2026-01-01T07:08:09Z",
+ accountRateLimits: [],
+ });
options.onCost?.({
model: "gpt-5.6",
inputTokens: 100,
@@ -636,6 +673,7 @@ test.each([
expect(stderr.text()).toContain(
"apps/api | Tokens: 90 uncached input, 10 cache reads, 0 cache writes, 20 output, 120 total",
);
+ expect(stderr.text()).toMatch(/apps\/api \| .*07:08:09 UTC/u);
}
expect(
[...signals.listeners.values()].every(
diff --git a/sdk/typescript/tests-ts/cost.test.ts b/sdk/typescript/tests-ts/cost.test.ts
index f69281ba0..12efd2c7d 100644
--- a/sdk/typescript/tests-ts/cost.test.ts
+++ b/sdk/typescript/tests-ts/cost.test.ts
@@ -10,6 +10,7 @@ import {
estimateScanCost,
ScanCostTracker,
type ScanSessionEvent,
+ type ScanUsageObservation,
type ScanWorkerEvent,
} from "../src/cost.js";
import type { ScanActivity } from "../src/scan-activity.js";
@@ -185,10 +186,20 @@ describe("scan cost", () => {
{},
{ parent: scanThreadId },
);
+ const rollout = ownershipRollout([]);
+ rollout.splice(2, 0, {
+ type: "event_msg",
+ timestamp: "2026-07-26T12:04:00Z",
+ payload: {
+ type: "token_count",
+ info: null,
+ rate_limits: { limit_id: "replayed" },
+ },
+ });
await writeFile(
path,
jsonLines([
- ...ownershipRollout([]),
+ ...rollout,
{
type: "event_msg",
timestamp: "2026-07-26T12:03:00Z",
@@ -200,12 +211,27 @@ describe("scan cost", () => {
},
]) + "\n",
);
+ const observations: ScanUsageObservation[] = [];
const tracker = new ScanCostTracker({
codexHome: home,
model: "gpt-6-astra",
+ onUsageObservation: (observation) => observations.push(observation),
});
tracker.start(scanThreadId);
expect((await tracker.stop()).usage).toEqual(ownedSdkUsage);
+ expect(observations).toEqual([
+ {
+ tokensUpdatedAt: "2026-07-26T12:02:00.250Z",
+ accountRateLimits: [
+ {
+ limitId: "codex",
+ observedAt: "2026-07-26T12:03:00.000Z",
+ primary: { usedPercent: 5, windowMinutes: null, resetsAt: null },
+ secondary: null,
+ },
+ ],
+ },
+ ]);
expect(readPythonRolloutUsage(BUNDLED_PLUGIN_ROOT, path)).toEqual({
usage: ownedPythonUsage,
warnings: [],
@@ -525,6 +551,69 @@ describe("scan cost", () => {
});
describe("live scan cost tracking", () => {
+ test("observes account limits and actual token measurement times from this scan", async () => {
+ const home = await codexHome();
+ const path = await writeSession(home, scanThreadId, {});
+ const unrelated = await writeSession(home, "unrelated", {});
+ const older = "2026-07-26T12:00:00.000Z";
+ const limitAt = "2026-07-26T12:01:00.000Z";
+ const tokensAt = "2026-07-26T12:02:00.000Z";
+ const later = "2026-07-26T12:03:00.000Z";
+ const limit = (timestamp: string, usedPercent: number) => ({
+ type: "event_msg",
+ timestamp,
+ payload: {
+ type: "token_count",
+ info: null,
+ rate_limits: {
+ limit_id: "codex",
+ secondary: { used_percent: usedPercent, window_minutes: 10_080 },
+ },
+ },
+ });
+ await appendFile(path, jsonLines([limit(limitAt, 12)]) + "\n");
+ await appendFile(unrelated, jsonLines([limit(later, 99)]) + "\n");
+ const observations: ScanUsageObservation[] = [];
+ const tracker = costTracker(home, {
+ onUsageObservation: (observation) => observations.push(observation),
+ });
+ tracker.start(scanThreadId);
+ const accountRateLimits = [
+ {
+ limitId: "codex",
+ observedAt: limitAt,
+ primary: null,
+ secondary: { usedPercent: 12, windowMinutes: 10_080, resetsAt: null },
+ },
+ ];
+ try {
+ expect((await tracker.refresh()).usage).toBeNull();
+ expect(observations).toEqual([
+ { tokensUpdatedAt: null, accountRateLimits },
+ ]);
+ const receipt = nativeUsageRecord(
+ scanThreadId,
+ "response",
+ ownedSdkUsage,
+ );
+ await appendFile(
+ path,
+ jsonLines([
+ { ...receipt, timestamp: tokensAt },
+ { ...receipt, timestamp: later },
+ limit(older, 3),
+ ]) + "\n",
+ );
+ expect((await tracker.refresh()).usage).toEqual(ownedSdkUsage);
+ await tracker.refresh();
+ expect(observations.slice(1)).toEqual([
+ { tokensUpdatedAt: tokensAt, accountRateLimits },
+ ]);
+ } finally {
+ await tracker.stop();
+ }
+ });
+
test("keeps receipt cache-write detail when an equal legacy counter omits it", async () => {
const home = await codexHome();
const usage = {
@@ -550,6 +639,71 @@ describe("live scan cost tracking", () => {
});
});
+ test("keeps freshness with the last reportable token total", async () => {
+ const home = await codexHome();
+ const parent = await writeSession(home, scanThreadId, {});
+ const first = "2026-07-26T10:01:00.000Z";
+ const second = "2026-07-26T10:02:00.000Z";
+ const third = "2026-07-26T10:03:00.000Z";
+ const measure = (
+ path: string,
+ timestamp: string | undefined,
+ input: number,
+ ) =>
+ appendFile(
+ path,
+ jsonLines([
+ {
+ ...legacyUsageRecord({ input_tokens: input, output_tokens: 0 }),
+ timestamp,
+ },
+ ]) + "\n",
+ );
+ await measure(parent, first, 10);
+ const times: Array<string | null> = [];
+ const tracker = costTracker(home, {
+ onUsageObservation: ({ tokensUpdatedAt }) => times.push(tokensUpdatedAt),
+ });
+ tracker.start(scanThreadId);
+ try {
+ expect((await tracker.refresh()).usage).toMatchObject({
+ total_tokens: 10,
+ });
+ const worker = await writeSession(
+ home,
+ "worker",
+ {},
+ { parent: scanThreadId },
+ );
+ await measure(parent, second, 20);
+ expect((await tracker.refresh()).usage).toBeNull();
+ expect(times).toEqual([first]);
+ await measure(worker, third, 7);
+ expect((await tracker.refresh()).usage).toMatchObject({
+ total_tokens: 27,
+ });
+ expect(times).toEqual([first, third]);
+ tracker.recordUsage({ input_tokens: 30, output_tokens: 0 });
+ expect((await tracker.refresh()).usage).toMatchObject({
+ total_tokens: 37,
+ });
+ expect(times).toEqual([first, third, null]);
+ await measure(parent, third, 30);
+ await tracker.refresh();
+ expect(times.at(-1)).toBe(third);
+ await measure(parent, undefined, 30);
+ await tracker.refresh();
+ expect(times.at(-1)).toBe(third);
+ await measure(parent, undefined, 31);
+ expect((await tracker.refresh()).usage).toMatchObject({
+ total_tokens: 38,
+ });
+ expect(times.at(-1)).toBeNull();
+ } finally {
+ await tracker.stop();
+ }
+ });
+
test("counts compaction receipts before stale counters and deduplicates responses", async () => {
const home = await codexHome();
const original = { ...ownedSdkUsage };
diff --git a/sdk/typescript/tests-ts/scan-dashboard.test.ts b/sdk/typescript/tests-ts/scan-dashboard.test.ts
index da263e1f0..3995d2f67 100644
--- a/sdk/typescript/tests-ts/scan-dashboard.test.ts
+++ b/sdk/typescript/tests-ts/scan-dashboard.test.ts
@@ -702,6 +702,156 @@ describe("live scan dashboard", () => {
dashboard.stop();
});
+ test("keeps the token and cost measurement time on later timer redraws", () => {
+ const stderr = capture(true);
+ const measured = "2026-07-29T12:34:56Z";
+ let now = Date.parse(measured);
+ let redraw: (() => void) | undefined;
+ const terminal = { ...stderr.stream, columns: 60, rows: 24 };
+ const dashboard = createDashboard(terminal, {
+ showCost: true,
+ clock: {
+ ...fakeClock(() => now),
+ setInterval(callback) {
+ redraw = callback;
+ return {} as NodeJS.Timeout;
+ },
+ },
+ });
+ dashboard.start();
+ dashboard.setUsageObservation({
+ tokensUpdatedAt: measured,
+ accountRateLimits: [],
+ });
+ expect(lastFrame(stderr)).not.toMatch(/^\s*USAGE\b/m);
+ dashboard.setCost(
+ fakeResult([], "complete", { input_tokens: 100, output_tokens: 1 }).cost!,
+ );
+ const before = lastFrame(stderr);
+ expect(before).toContain("12:34:56");
+ expect(before).toMatch(/COST\s+\$/);
+ expect(before).not.toMatch(/^\s*LIMITS\b/m);
+ now += 42 * 60_000;
+ redraw!();
+ const after = lastFrame(stderr);
+ expect(after.match(/12:34:56/g)).toHaveLength(1);
+ expect(after.replace(/\s+/gu, " ")).toContain("in-flight usage");
+ expect(after).toMatch(/TIME\s+42:00/);
+ expect(after.split("\n")).toHaveLength(24);
+ expect(after.split("\n").every((line) => stringWidth(line) <= 60)).toBe(
+ true,
+ );
+ terminal.columns = 80;
+ terminal.rows = 12;
+ dashboard.setUsageObservation({
+ tokensUpdatedAt: "2026-07-29T13:15:05Z",
+ accountRateLimits: [
+ {
+ limitId: "codex",
+ observedAt: "2026-07-29T13:15:07Z",
+ primary: { usedPercent: 73, windowMinutes: 300, resetsAt: null },
+ secondary: { usedPercent: 87, windowMinutes: 10_080, resetsAt: null },
+ },
+ ],
+ });
+ const resized = lastFrame(stderr);
+ expect(resized).toContain("13:15:05");
+ expect(resized).not.toContain("12:34:56");
+ expect(resized).toContain("5h 73% used, 7d 87% used");
+ expect(resized).toContain("13:15:07");
+ expect(resized).toContain("Ctrl+C to exit");
+ expect(resized.split("\n")).toHaveLength(12);
+ dashboard.stop();
+ });
+
+ test("keeps the clock and budget visible when allowance readings need several pages", async () => {
+ const stderr = capture(true);
+ const input = new DashboardTestInput();
+ const dashboard = createDashboard(
+ { ...stderr.stream, columns: 48, rows: 16 },
+ { maxCostUsd: 20, input },
+ );
+ const cost = fakeResult([], "complete", {
+ input_tokens: 100,
+ output_tokens: 2,
+ }).cost!;
+ const limits = Array.from({ length: 8 }, (_, index) => ({
+ limitId: `pool-${index + 1}`,
+ observedAt: "2026-07-29T12:35:00Z",
+ primary: { usedPercent: 11 + index, windowMinutes: 300, resetsAt: null },
+ secondary: null,
+ }));
+ dashboard.start();
+ try {
+ dashboard.setCost(cost);
+ dashboard.setUsageObservation({
+ tokensUpdatedAt: "2026-07-29T12:34:56Z",
+ accountRateLimits: limits,
+ });
+ expect(lastFrame(stderr).split("\n")).toHaveLength(16);
+ expect(lastFrame(stderr)).toContain("Full readings in details");
+ const budget = dashboard.requestBudgetIncrease({
+ maxCostUsd: 20,
+ cost,
+ signal: new AbortController().signal,
+ });
+ const prompt = lastFrame(stderr);
+ expect(prompt.split("\n")).toHaveLength(16);
+ expect(prompt).toContain("BUDGET");
+ expect(prompt.split("\n").at(-1)).toMatch(/TIME.*Enter to apply/);
+ input.emit("data", "\r");
+ await expect(budget).resolves.toBeUndefined();
+ input.emit("data", "d");
+ const pages = new Set<string>();
+ while (!pages.has(lastFrame(stderr))) {
+ const page = lastFrame(stderr);
+ expect(page.split("\n")).toHaveLength(16);
+ pages.add(page);
+ input.emit("data", "\u001B[5~");
+ }
+ const details = [...pages].join(" ").replace(/\s+/gu, " ");
+ for (const limit of limits) {
+ expect(details).toContain(limit.limitId);
+ expect(details).toContain(`${limit.primary.usedPercent}% used`);
+ }
+ } finally {
+ dashboard.stop();
+ }
+ });
+
+ test("shows ChatGPT account windows before any token measurement", () => {
+ const stderr = capture(true);
+ const dashboard = createDashboard(
+ { ...stderr.stream, columns: 60, rows: 24 },
+ { mode: "deep" },
+ );
+ dashboard.start();
+ expect(lastFrame(stderr)).not.toMatch(/^\s*LIMITS\b/m);
+ dashboard.setChatGptAuth(true);
+ expect(lastFrame(stderr).replace(/\s+/gu, " ")).toMatch(
+ /LIMITS .*?(?:unavailable|not reported)/i,
+ );
+ dashboard.setUsageObservation({
+ tokensUpdatedAt: null,
+ accountRateLimits: [
+ {
+ limitId: "codex",
+ observedAt: "2026-07-29T14:23:19Z",
+ primary: { usedPercent: 73, windowMinutes: 300, resetsAt: null },
+ secondary: null,
+ },
+ ],
+ });
+ const frame = lastFrame(stderr);
+ expect(frame).toMatch(/TOKENS\s+waiting for usage/);
+ expect(frame).not.toMatch(/^\s*(?:COST|USAGE)\b/m);
+ expect(frame).toContain("73%");
+ expect(frame).toContain("14:23:19");
+ expect(frame).not.toMatch(/unavailable|not reported/i);
+ expect(frame.split("\n")).toHaveLength(24);
+ dashboard.stop();
+ });
+
test("edits a higher total budget while continuing to show live cost", async () => {
const stderr = capture(true);
const input = new DashboardTestInput();
@@ -1245,6 +1395,18 @@ describe("live scan dashboard", () => {
output_tokens: 10,
}).cost!;
for (const [index, receipt] of receipts.slice(0, 2).entries()) {
+ dashboard.recordComponentEvent(
+ {
+ componentId: receipt.id,
+ type: "authentication",
+ value: {
+ method: "stored_credentials",
+ credentialType: index === 0 ? "chatgpt" : "api_key",
+ verified: false,
+ },
+ },
+ "auto",
+ );
dashboard.recordComponentEvent({
componentId: receipt.id,
type: "progress",
@@ -1302,8 +1464,18 @@ describe("live scan dashboard", () => {
expect(frame()).toContain("component scans only");
expect(frame()).toContain("before deduplication");
expect(frame().split("\n")).toHaveLength(20);
+ dashboard.recordComponentEvent({
+ componentId: receipts[0]!.id,
+ type: "usage-observation",
+ value: {
+ tokensUpdatedAt: "2026-07-29T12:34:56Z",
+ accountRateLimits: [],
+ },
+ });
input.emit("data", "\r");
expect(frame()).toContain("API only activity");
+ expect(frame()).toContain("12:34:56");
+ expect(frame()).toMatch(/ChatGPT allowance not reported/i);
expect(frame()).not.toContain("Web only activity");
expect(frame()).toContain("$1.00");
for (const chunk of ["\u001BO", "1;5P"]) {
@@ -1320,6 +1492,8 @@ describe("live scan dashboard", () => {
input.emit("data", "B\r");
expect(frame()).toContain("Web only activity");
expect(frame()).not.toContain("API only activity");
+ expect(frame()).not.toContain("12:34:56");
+ expect(frame()).not.toContain("ChatGPT allowance");
dashboard.updateComponent({
...receipts[0]!,
status: "completed",
@@ -1705,6 +1879,7 @@ describe("live scan dashboard", () => {
expect(frame).toContain("worker 1 · Reviewed source file 2");
expect(frame).toContain("worker 1 · Reviewed source file 6");
expect(frame).toContain("TOKENS");
+ expect(frame).toContain("Usage report time unavailable");
expect(frame).not.toContain("COST");
expect(frame).toContain("TIME");
});