Repository navigation
Conversation
Unlike Claude, Codex has no live per-turn push into Orca — every usage refresh goes through chatgpt.com (backend fetch, RPC app-server, or a PTY /status probe), all of which require reaching OpenAI's network. When all three fail, the usage bar went completely dark with no local fallback. Codex's own session log already records a token_count event with total_token_usage and model_context_window on every turn. Read the most recently modified session log's last token_count event as a last-resort, network-free usage signal — but only for genuine network/CLI failures, not for auth errors, which need to stay visible so the user knows to re-sign in.
Greptile SummaryThis PR adds a local session-log fallback to
Confidence Score: 5/5Safe to merge — the change is strictly additive, activates only on a non-auth network-error path, and leaves all existing behavior unchanged. The fallback is well-guarded: auth errors, aborted fetches, and non-error network results all bypass it. The session-log parser is purely functional with no side effects, errors are caught at every layer, and the abort-during-read race is explicitly tested. All 89 tests pass including the 21 pre-existing codex-fetcher tests. Files Needing Attention: No files require special attention.
|
| Filename | Overview |
|---|---|
| src/main/rate-limits/codex-fetcher.ts | Wraps fetchCodexRateLimitsViaNetwork with a thin session-log fallback; auth-error and abort guard conditions are correct and tested. |
| src/main/rate-limits/codex-session-log-usage.ts | New module that parses the last token_count event from a Codex session JSONL log; includes dependency-injected file discovery, stat, and read helpers for clean unit-testability. |
| src/main/rate-limits/codex-session-log-usage.test.ts | New test file with thorough coverage of parsing edge cases (last-event priority, fallback field, malformed JSON, zero/missing context window, clamping) and file-selection logic. |
| src/main/rate-limits/codex-fetcher.test.ts | Adds two integration tests: fallback engaging when all network paths fail, and fallback being skipped on abort; existing 21 tests patched to keep their null-mock default. |
| src/main/rate-limits/codex-fetcher-session-log-abort.test.ts | New test validating the race where abort fires while readLatestCodexSessionUsedPercent is in-flight; confirms the result is discarded and an abort error is returned. |
| src/shared/rate-limit-types.ts | One-line addition of 'session-log' to the UsageRateLimitSource union type. |
Reviews (3): Last reviewed commit: "fix(rate-limits): recheck abort signal a..." | Re-trigger Greptile
| export async function readLatestCodexSessionUsedPercent( | ||
| listFiles: () => Promise<string[]> = listCodexSessionFiles, | ||
| statFile: (filePath: string) => Promise<{ mtimeMs: number }> = getProcessedFileInfo, | ||
| readFileFn: (filePath: string) => Promise<string> = (filePath) => readFile(filePath, 'utf8') | ||
| ): Promise<number | null> { | ||
| try { | ||
| const files = await listFiles() | ||
| let latestPath: string | null = null | ||
| let latestMtimeMs = -Infinity | ||
| for (const filePath of files) { | ||
| try { | ||
| const info = await statFile(filePath) | ||
| if (info.mtimeMs > latestMtimeMs) { | ||
| latestMtimeMs = info.mtimeMs | ||
| latestPath = filePath | ||
| } | ||
| } catch { | ||
| // Missing/unreadable file — another session log may still qualify. | ||
| } | ||
| } | ||
| if (!latestPath) { | ||
| return null | ||
| } | ||
| const content = await readFileFn(latestPath) | ||
| return extractCodexSessionUsedPercentFromLog(content) | ||
| } catch { | ||
| return null | ||
| } | ||
| } |
There was a problem hiding this comment.
Full-file read for tail-of-file data
readFile(filePath, 'utf8') loads the entire session log into memory to then scan backward for the last token_count line. Session logs grow unboundedly with session length; a multi-hour session can produce logs well into the tens of megabytes, making this a non-trivial allocation on an already-stressed (network-down) path. Consider reading only the last N bytes (e.g. 64 KB) via a file handle and scanning that slice first, falling back to a full read only if no token_count is found — the last event is almost always near the end of the file.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
| if (result.status !== 'error' || options?.signal?.aborted || isCodexAuthError(result.error)) { | ||
| return result | ||
| } | ||
| // Why: Codex has no live per-turn push like Claude's statusline — when every network | ||
| // path (backend/RPC/PTY) fails for a non-auth reason, the local session log's last | ||
| // token_count event is the only usage signal left, so usage doesn't go completely | ||
| // dark on an internal network. | ||
| const usedPercent = await readLatestCodexSessionUsedPercent().catch(() => null) | ||
| if (usedPercent === null) { | ||
| return result | ||
| } | ||
| return { | ||
| ...result, | ||
| session: { | ||
| usedPercent, | ||
| windowMinutes: CODEX_SESSION_WINDOW_MINUTES, | ||
| resetsAt: null, | ||
| resetDescription: null | ||
| }, | ||
| status: 'ok', | ||
| error: null, | ||
| usageMetadata: { ...result.usageMetadata, source: 'session-log' } | ||
| } | ||
| } |
There was a problem hiding this comment.
Stale-window usage shown as current
The fallback sets windowMinutes: CODEX_SESSION_WINDOW_MINUTES (5 h) but has no way to know whether the 5-hour window that produced the logged token_count event has already rolled over. A user who hit 80 % in the previous window, let the window reset, then lost network connectivity will see "80 % used" in the bar when they are actually at 0 % in the new window. Because resetsAt: null is returned, no misleading countdown is shown, but the usage bar itself can be materially wrong — with no visual cue that the figure is from a different window. This is an inherent limitation of the local-log approach, but it is worth documenting (e.g. with a staleWindowRisk flag in usageMetadata) so the UI layer can optionally render the bar differently (e.g. with reduced opacity or a "last known" label).
📝 WalkthroughWalkthroughCodex rate-limit fetching now reads usage from the latest usable local session log when eligible network fetches fail. The parser scans JSONL entries for the latest valid 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
src/main/rate-limits/codex-session-log-usage.ts (2)
66-94: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winFall back to older session files when the newest yields no usable data.
readLatestCodexSessionUsedPercentonly extracts usage from the single most recently modified file. If that file has no validtoken_countevent yet (for example, a session log just created but not yet used), the function returnsnulleven though an older session log may hold a valid signal. Iterate files in descendingmtimeMsorder and try the next one when extraction returnsnull.♻️ Proposed refactor to try older files
- const files = await listFiles() - let latestPath: string | null = null - let latestMtimeMs = -Infinity - for (const filePath of files) { - try { - const info = await statFile(filePath) - if (info.mtimeMs > latestMtimeMs) { - latestMtimeMs = info.mtimeMs - latestPath = filePath - } - } catch { - // Missing/unreadable file — another session log may still qualify. - } - } - if (!latestPath) { - return null - } - const content = await readFileFn(latestPath) - return extractCodexSessionUsedPercentFromLog(content) + const files = await listFiles() + const candidates: { path: string; mtimeMs: number }[] = [] + for (const filePath of files) { + try { + const info = await statFile(filePath) + candidates.push({ path: filePath, mtimeMs: info.mtimeMs }) + } catch { + // Missing/unreadable file — another session log may still qualify. + } + } + candidates.sort((a, b) => b.mtimeMs - a.mtimeMs) + for (const { path } of candidates) { + try { + const content = await readFileFn(path) + const usedPercent = extractCodexSessionUsedPercentFromLog(content) + if (usedPercent !== null) { + return usedPercent + } + } catch { + // Unreadable file — try the next-newest candidate. + } + } + return null
66-94: 🚀 Performance & Scalability | 🔵 TrivialConsider the cost of repeated session-log scans during sustained outages.
readLatestCodexSessionUsedPercentwalks and stats every session file on each call. If Codex rate-limit polling retries periodically and the network stays down, this fallback runs on every poll cycle, repeating the directory walk and per-filestatcalls each time. Consider caching the last-known-good result briefly or debouncing this fallback so persistent outages do not repeat the full filesystem scan on every poll.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: ee83d21d-8cbc-4e69-99fc-809a3dd3f1d8
📒 Files selected for processing (5)
src/main/rate-limits/codex-fetcher.test.tssrc/main/rate-limits/codex-fetcher.tssrc/main/rate-limits/codex-session-log-usage.test.tssrc/main/rate-limits/codex-session-log-usage.tssrc/shared/rate-limit-types.ts
…eads readLatestCodexSessionUsedPercent only inspected the single most recently modified session file. A freshly created session log with no token_count event yet (or an unreadable file) made the fallback report nothing even though an older log still had a usable signal. Sort candidates by mtime and try each in order until one yields a value. Addresses CodeRabbit feedback on stablyai#11766.
…ck read readLatestCodexSessionUsedPercent() is awaited after the network paths exhaust; if the fetch aborts while that read is in flight, the wrapper returned a fabricated status: 'ok' from the local log instead of the aborted result, breaking the abort-safety pattern used everywhere else in this file. Caught by CodeRabbit review on stablyai#11766.
f041212 to
208bfca
Compare
|
Thanks @YuSoeun for the Codex session-log fallback work. We consolidated this with #11760 and #11662 in canonical issue #17518, covering provider RPC, PTY, and local-log fallback behavior. We will reimplement the matrix on current main; no contributor follow-up is requested. Closing this superseded branch while preserving your credit. |
Summary
/statusprobe), all of which require reaching OpenAI's network. When all three fail, the usage bar went completely dark with no local fallback (see the related Claude fix in fix(rate-limits): fall back to context_window for Claude usage on Vertex/proxy backends #11760 for the internal-network usage investigation this follows up on).token_countevent withtotal_token_usageandmodel_context_windowon every turn.fetchCodexRateLimitsnow reads the most recently modified session log's lasttoken_countevent as a last-resort, network-free usage signal when every network path returns a genuine error.okwould hide the one thing the user actually needs to act on.Testing
pnpm typecheck(targeted:tsc --noEmit -p config/tsconfig.node.json)pnpm lint(targeted oxlint + type-aware + native-plugins + max-lines-ratchet + reliability-gates on changed files)pnpm test(targeted: allsrc/main/rate-limits/codex-*.test.ts— 89 tests passing, including 21 pre-existing codex-fetcher tests unchanged and 2 new integration tests for the fallback)pnpm build— not run; native module rebuild requires Visual Studio Build Tools not available in this environment (unrelated to this change, which is TS-only)New coverage:
codex-session-log-usage.test.ts— puretoken_countparsing (last-event priority,last_token_usagefallback, malformed lines, missingmodel_context_window, clamping) and the file-selection wrapper via dependency injectioncodex-fetcher.test.ts— the fallback engaging when every network path exhausts tostatus: 'error', and not engaging when the fetch was abortedAI Review Report
Reviewed with Claude Code. Checked: cross-platform (pure JSON/string parsing, no OS-specific paths — reuses the existing
codex-usage/scanner.tsdirectory discovery which already handles Windows/WSL/macOS/Linux session locations), SSH/remote compatibility (session log discovery is unchanged, local-only by design since this is a local fallback), auth-error handling (verified via test that auth errors are never masked by the fallback — this was caught as a real bug during review: an early version applied the fallback to auth-error results too, which surfaced during testing as a live session on the dev machine getting silently marked "ok"), and regression safety (all pre-existing codex-fetcher and codex-fetcher-auth-errors tests pass unchanged).Security Audit
fetchCodexRateLimitsalready uses.nullrather than throwing.Notes
weeklystaysnullin the fallback result since the local session log has no 7-day window data — only the 5-hoursessionwindow is populated.