Skip to content

Read only the session files that changed since the last scan - #12595

Closed
PapistProtocol wants to merge 4 commits into
omacom:quattrofrom
PapistProtocol:codex-usage-incremental-scan
Closed

PapistProtocol wants to merge 4 commits into
omacom:quattrofrom
PapistProtocol:codex-usage-incremental-scan

Conversation

@PapistProtocol

Copy link
Copy Markdown
Contributor

Fixes #12411.

omarchy-agent-usage-codex re-reads the whole history on every run: rg across all of ~/.pi/agent/sessions and ~/.omp/agent/sessions with no cutoff, plus a JSONL parse of every ~/.codex session file touched in the last 30 days. SCAN_REUSE_SECONDS = 20 means the aggregate cache only dedups concurrent collectors, so each widget refresh (triggeredOnStart: true, then every interval) pays for the walk again. On the reporter's machine that was ~5.9 GB rchar, one core at 98-99% for over three minutes, and a visibly laggy desktop.

Change

Session files are append-only, so a file whose mtime and size are unchanged cannot have grown a turn since it was last read. This adds a per-file cache (codex-files-<digest>.json, beside the existing codex-scan-<digest>.json) holding each file's totals as day -> model -> [input, output, cacheRead, cacheWrite, prompts]:

  • unchanged files are replayed from their record, changed and new files are read;
  • rg is handed the changed paths (in batches, for argument limits) instead of the session roots, so a file with no openai-codex message in it caches an empty record and is not searched again either;
  • the records carry no today, so unlike the aggregate cache they survive midnight and a clock move — only the file they describe can invalidate one;
  • --force ignores them and re-reads the history;
  • a file rg cannot open is left out of the cache rather than recorded as empty, since --json reports an unreadable file only on stderr and it would otherwise look identical to a file with no matches;
  • the opencode SQLite scan is untouched, and every cache failure still degrades to a direct scan.

Measurements

123 MB of synthetic history (150 native codex sessions, 60 pi sessions), on tmpfs — so this shows the parsing cost only, and the disk reads the real complaint is about do not appear at all:

run wall CPU
current, first scan 343 ms 0.36 s
current, refresh 340 ms 0.35 s
this branch, first scan 342 ms 0.35 s
this branch, refresh 78 ms 0.08 s

The printed record is identical between the two versions, on both the cold and the warm path (jq -S 'del(.updatedAt)' diff is empty).

Tests

test/shell.d/agent-usage-codex-scanner-test.sh keeps its existing 22 assertions and gains four, all failing against the current collector:

  • per-file records are written for the native and the pi session file;
  • with both session files made unreadable but unchanged in mtime and size, a refresh still reports the same totals — it can only have replayed them;
  • --force in that same state reports 0, so it really does re-read;
  • appending a turn to a cached session file is picked up.

./test/all: no new failures (the four it reports here — three omarchy-pkgs checkout assertions and the superseded-PTL-migration case — also fail on quattro in this environment).

The Codex collector walked the whole history on every run: rg over all of
~/.pi and ~/.omp, and a JSONL parse of every ~/.codex session touched in the
last 30 days. The local-stats cache only covers 20 seconds, so each widget
refresh paid for the walk again -- one core saturated for minutes and several
GB re-read on a large history, with the desktop lagging behind it.

Session files are append-only, so a file whose mtime and size are unchanged
cannot have grown a turn. Keep each file's totals in a per-file cache beside
the aggregate one, replay the unchanged files, and hand rg and the parser only
the rest. The records are day-keyed and hold no "today", so they stay true
across midnight; only the file they describe can invalidate one. --force still
re-reads everything, and a file rg cannot open is left out rather than cached
as empty.

On 123 MB of synthetic history (150 codex sessions, 60 pi sessions, tmpfs, so
the real disk saving does not show): a refresh drops from 0.35 s to 0.08 s of
CPU and 343 ms to 79 ms wall, and the record is byte-identical to the one the
full scan produces.

Fixes omacom#12411
@llstrk

llstrk commented Sep 21, 2026

Copy link
Copy Markdown

Cache validity misses failed searches and timezone changes

Reviewed c16c0505.

Verified: with the aggregate cache expired, an unchanged synthetic history produced identical usage records while the PR eliminated both native JSONL opens and Pi/OMP ripgrep invocations. Append, deletion, truncation, batching and forced-refresh controls also worked in isolated tests.

Failed ripgrep results persist after the underlying error clears

After the collector's readability check, a controlled permission change caused real rg to exit 2. Permissions were restored without changing file size or mtime:

13-token transcript            Baseline     PR
Transient read denial          0            0
Healthy refresh afterward      13           0
Forced refresh                 13           13

The PR cached the failed read as an empty file record and skipped searching it on later normal refreshes. Partial-output and interrupted-process fixtures also persisted incomplete totals.

Impact: transient search failures can cause lasting automatic-refresh undercounts. Manual --force repairs them; transcripts and billing are unaffected.

Suggested change: do not persist new file records from batches whose ripgrep exit status is neither 0 nor 1. Keep successful no-match caching, and test recovery without changing the transcript's size/mtime.

Cached dates retain the old timezone

Two unchanged near-midnight transcripts totaled 39 tokens:

Scan in UTC -> change timezone to America/Los_Angeles -> refresh

                       Baseline              PR
Date bucket            Previous local day    Still today (39 tokens)
Forced rescan          --                    Reassigns local date

The PR retained the old date buckets until forced to rescan.

Impact: timezone changes can leave today's totals and daily charts stale after the aggregate cache expires. Verified: ordinary midnight rollover in a stable timezone passed.

Suggested change: include effective timezone in cache validity, or retain timestamps sufficient to recompute local dates.

Optional test improvement: retain a populated cache before the append assertion. A mutation disabling size/mtime invalidation still passed because an earlier test had cleared those records. Verified: the actual implementation passed independent intact-cache tests.


Review information

Test scope: synthetic histories, real scanner/ripgrep, controlled RPC and failures, baseline/force controls. No user transcripts, real-account calls or multi-gigabyte disk benchmark.

Community review: Independent automated community review, unaffiliated with the Omarchy team, intended to help prepare PRs for their review.

Automated AI review: Astra ran initial experiments; independent Fable 5.1 and Astra reviewers added coverage and diagnostic controls. Both completed reports and material evidence were read before synthesis.

omarchybot and others added 3 commits October 1, 2026 12:34
rg exits 2 when it could not search a file and names the file only on stderr, so a batch that failed was cached as empty records and the files in it stayed uncounted until they changed. Count that batch for the run, but cache none of it.

The per-file records are bucketed by local day, so a record written in one timezone puts turns on the wrong day in another. Store the timezone with the cache and discard it when it differs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nst a full cache

A line that stops the read, such as a bare null, used to keep the usage counted before it; the per-file reader threw the whole file's totals away. Keep them and mark the record uncacheable instead.

The append test ran after a --force pass that could not read either file, so the cache was empty and the appended file was read from scratch whether or not invalidation worked. Re-cache both files before appending.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Codex Medium <[email protected]>
@omarchybot omarchybot added the verified Omarchy Triage has verified that this issue is ready for final review label Oct 1, 2026
@omarchybot

Copy link
Copy Markdown
Collaborator

Reviewed and verified on a disposable Omarchy worker. The fix works. I pushed three commits to the branch: a merge of quattro, and fixes for the two cache problems @llstrk found plus one more from review.

Reproduction. I built a synthetic history of 120 native Codex sessions and 60 pi sessions (42 MB), ran the collector once, expired the aggregate scan cache, and ran it again with nothing changed. On quattro the second run reopened all 120 native session files and walked both pi roots with rg again. On this branch it opened none of them and never started rg, and the totals matched. So the per-file cache removes the repeated reads #12411 describes.

Pushed to the branch:

  • 1cf6e87e4 merges quattro, which had started conflicting in test/shell.d/agent-usage-codex-scanner-test.sh after Read Codex limits without waiting on account/read #13733. Both test blocks are kept.
  • e72cabc39 stops caching the per-file records from an rg batch that exits with anything other than 0 or 1. rg reports a file it could not search only on stderr, so a passing failure was saved as an empty record and the file stayed uncounted until it changed. It also stores the timezone with the cache and drops the cache when the timezone changes, because records are bucketed by local day. These are the two problems @llstrk reported above. Each has a test that fails without its fix.
  • 7b91e0794 keeps the usage read from a native session file before a line that stops the read, such as a bare null. The per-file reader was discarding the whole file's totals, where quattro kept them. The partial record is still not cached. This commit also repairs the append test: the --force run before it left the cache empty, so the test passed even with mtime/size invalidation removed. It now re-caches both files first, and fails if invalidation is removed.

Tests run on the worker: agent-usage-codex-scanner-test.sh 29/29, agent-usage-update-test.sh 7/7, agents-panel-test.sh 6/6. ./test/cli stops at vscode generated theme references current theme file. It stops at the same point on quattro, so this change didn't cause it, but the suite is not green, and the tests after that one did not run on either tree.

Second opinion: Codex Medium reviewed this over two rounds. It contributed the read-error regression and the vacuous append test. Its last round, on 7b91e0794, found nothing open. It also flagged three things I left alone, because none affects a real install:

Related: #12336 and #12803 work on the same cost. #12336 caches native Codex sessions only and leaves the pi/omp scan as it is. #12803 still reads every file on every scan. This PR is the only one of the three that stops all the repeated reads #12411 reports. Choosing among them is up to the maintainer.

Waiting on the maintainer. It is verified at 7b91e0794, but not marked ready while ./test/cli fails on quattro.

@greptile-apps

greptile-apps Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 3/5

[Medium risk] Refactors session file scanning to cache per-file totals.

The PR is not ready to merge because some Pi/OMP histories can produce incorrect cached usage totals.

Findings

  1. P1 Fallback dates become stale ▶
  2. P1 Ignored transcripts are now counted ▶
  3. P2 Replaced files retain stale totals ▶
  4. P2 Root runs fail this test ▶

Summary

The PR adds persistent per-file totals for native Codex and Pi/OMP sessions so refreshes can replay unchanged files instead of rereading their contents.

  • Changed Pi/OMP file selection can include previously ignored transcripts.
  • Scan-time fallback dates can become stale in persistent records.
  • The new forced-rescan test depends on running without root privileges.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Session paths] --> B[Stat each file]
  B --> C{Cached mtime and size match?}
  C -- Yes --> D[Replay day/model totals]
  C -- No --> E[Read native file or search Pi/OMP file]
  E --> F[Store per-file totals]
  D --> G[Aggregate usage]
  F --> G
Loading

Reviews (1) · Last reviewed commit: "Keep native usage read before a failed l..."

Comment on lines +271 to +272
day = local_day(entry.get("timestamp") or message.get("timestamp"))
record_usage(record, day, model_name(message.get("model")), input_tokens, output_tokens, cache_read, cache_write)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Fallback dates become stale If a Pi/OMP message has no usable timestamp, local_day assigns it the scan date. The new per-file cache keeps that date indefinitely, so after midnight the message remains attributed to yesterday even though a fresh scan would count it today. Its usage disappears from today's totals until the file changes.

Comment on lines +188 to +202
stale = []
for path in root.rglob("*"):
try:
event = json.loads(raw)
if event.get("type") != "match":
if not path.is_file():
continue
line = event.get("data", {}).get("lines", {}).get("text", "")
path = event.get("data", {}).get("path", {}).get("text", "pi-session")
entry = json.loads(line)
except Exception:
stat_result = path.stat()
except OSError:
continue
key = str(path)
record = reusable_record(cached_files, key, stat_result)
if record is not None:
scanned_files[key] = record
merge_file_record(key, record)
elif os.access(key, os.R_OK):
stale.append((key, stat_result))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Ignored transcripts are now counted If a sessions directory contains an ignored backup transcript, the new file walk passes it to ripgrep explicitly. The previous directory search skipped ignored files, but this search counts the backup alongside the original and caches the duplicate usage, inflating the reported totals.

record = cached_files.get(key)
if record is None:
return None
if record["mtime"] != stat_result.st_mtime or record["size"] != stat_result.st_size:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Replaced files retain stale totals If a session file is restored or replaced with different, same-sized content while retaining its modification time, this check reuses the old record. Because per-file records do not expire, the reported usage stays wrong until the file's size or modification time changes. Consider checking file identity as well.

Comment on lines +678 to +680
result=$(run_incremental --force)
[[ $(jq -r '.todayTotalTokens' <<<"$result") == "0" ]] ||
fail "Codex collector --force reuses per-file records" "$result"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Root runs fail this test If the shell suite runs as root, chmod 000 does not make these fixtures unreadable. A correct --force rescan can still count their 20 tokens, so the assertion fails despite correct behavior. Make the unreadability check independent of runner privileges, or skip this assertion for root.

@omarchybot omarchybot removed the verified Omarchy Triage has verified that this issue is ready for final review label Oct 1, 2026
@dhh

dhh commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

Thank you! Brought in with your authorship in #14049.

@dhh dhh closed this Oct 2, 2026
dhh added a commit that referenced this pull request Oct 3, 2026
…ommunity PRs (#14049)

* Read Codex app-server replies from the raw fd (#13703)

* Resolve Codex through mise which instead of running the lazy launcher (#13109)

* Skip the Codex app-server probe when there are no credentials (#13106)

Adapted: credentials are checked in the home being probed rather than in
the CODEX_HOME environment variable, since each registered account is
probed in its own home, so a signed-out secondary account isn't hidden
behind the primary's login. A home without credentials reports "Waiting
for auth" like any other signed-out home. The credentials store setting is
read with tomllib, so a single-quoted value counts too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Show the Codex CLI's own error when its app-server dies (#8977)

Detect an app-server that exits or stops answering, and report the end of
its stderr instead of a bare RPC method name. Rebased onto the raw-fd
reply reader; the switch from "-a on-request" to "-a never" is left out,
keeping the current approval flags.

* Count pi sessions when HOME is a git checkout (#13209)

* Count only OpenAI-backed native sessions as Codex usage (#12032)

* Deduplicate Pi usage across forked sessions (#8602)

* Skip unchanged native Codex token snapshots (#10531)

* Count omp and pi profile sessions in the agent usage collectors (#9546)

`omp --profile=<name>` (and pi's equivalent) relocates the whole agent
tree under <base>/profiles/<name>/. The Claude and Codex collectors only
ever scanned <base>/agent/sessions, so a subscription driven entirely
through a profile was invisible to the agents panel: no tokens by day, no
tokens by model, no prompt or session counts.

Discover the profile roots alongside the default one. Sessions are keyed
by file path, so a profile adds sessions instead of double-counting the
default root, and a missing or unreadable profiles directory leaves the
existing behavior untouched.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014zFbJcDEEpV5BAmsH6kAB3

* Skip unrelated Codex session lines before JSON parsing (#12803)

Adapted: session_meta lines also pass the pre-filter, since the provider
filter from #12032 reads them to skip rollouts served by a non-OpenAI
provider.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Read only the Codex session files that changed since the last scan (#12595)

Native Codex rollouts keep per-file totals between runs, replayed while a
file's mtime and size are unchanged. Rebased onto the session_meta
provider filter, snapshot dedup, and line pre-filter, which now live in
the per-file reader. pi and omp sessions are left out of the per-file
cache: a forked pi session repeats its parent's messages, so they are
deduplicated across the whole tree on every scan.

* Count streamed Claude messages by their highest-output usage line (#10606)

Claude Code writes a streamed assistant response as several transcript
lines that share one message id, one per content block. Each line
carries a usage object. The first line's output_tokens is a placeholder,
often 1, and the last line has the real count. Input and cache fields
usually match across the lines.

The scanner dedupes by message id and keeps the first line it sees, so
it under-counts output tokens. On a machine with 2,577 transcripts it
reported 39.0M output tokens against 60.1M used, a 35% shortfall. Input
and both cache fields differed by under 0.01%.

Keep the line with the highest output count, with the last one scanned
winning a tie. The whole line is kept because a response can fall back
to another model mid-stream. Those lines are separate snapshots with
different cache figures and a different model, and taking a maximum per
field across them over-counts cache tokens and credits the wrong model.

The zero-usage check now runs before dedup, so a zero-usage first line
no longer claims a message id and hides a later line with real usage.

Co-authored-by: Claude Fable 5.1 <[email protected]>
Co-authored-by: GPT-6 Astra <[email protected]>

* Index Claude transcripts so the agents refresh reads only what was appended (#8313)

omarchy-agent-usage-claude re-parsed every line of every transcript under
~/.claude/projects on each refresh: no mtime cutoff, no memory of the last
pass. The agents widget is on by default and ticks every 15 minutes, so the
cost grew for the life of the machine. After one month here that was 803
files, 640 MB, 127k lines and 57k JSON parses per tick, about 1 core-second,
pushed through the page cache every quarter hour forever.

Keep a per-file index next to the scan cache: the unique usage records
already parsed out of each transcript and the byte offset they end at. A
file whose size and mtime match is not opened; a file that grew is read
from the stored offset; a file that shrank or was rewritten is read from
the start. --force drops the index and rescans from scratch.

The summary is built from the indexed records in the same directory order
the walk always used. That matters: when a resumed session carries earlier
messages, the same message id appears in two files with different usage,
and the first file visited wins. 91 ids differed on this machine; sorting
the walk moved one model's output total by 25k tokens. Output is now
byte-identical to the previous scan on a frozen copy of the corpus, cold,
warm, and after an append.

Warm refresh: 1.0 s -> 0.10 s of CPU, of which the scan itself is 70 ms;
the index for this corpus is 2.9 MB.

Adapted:
- Rebased onto #10606: the highest-output rule for streamed messages now
  lives where the index parses records, and decides between files too.
- The index records the timezone it was written in, and a change rereads
  every transcript, since its records hold local days.
- A file only counts as appended to when its inode and the hash of what
  was already read still match, so a transcript replaced by a larger one,
  or rewritten in place, is read from the start.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Label a Claude Team seat by its subscription, not its rate-limit tier (#11109)

The collector built the plan label from the OAuth rateLimitTier first, so a
Team premium seat, which runs on default_claude_max_5x, showed in the agents
panel as "Max 5x". Lead with subscriptionType and keep the multiplier as its
qualifier: Max still reads "Max 5x", a Team seat reads "Team 5x".

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Label the Claude plan from the profile the CLI refreshes (#7225)

Adapted: the profile is found the same way current_account_id() finds it,
now shared as profile_path(): ~/.claude.json for the default home, the
home's own .claude.json otherwise. The original fell back to ~/.claude.json
for any home without CLAUDE_CONFIG_DIR set, so a secondary account read the
primary's tier. The profile's tier also keeps the subscription in the label,
so a Team seat stays "Team" (#11109).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Call a lapsed Claude access token paused, not signed out (#8093)

* Refresh Claude usage after the clock moves backwards (#9956)

* Bound unreadable Claude transcript warnings (#12414)

* Count Claude usage from opencode v2 sessions (#13894)

* Reload agent usage records when an inotify watch fails to rearm (#10067)

* Reload agent usage records after each update run instead of on a timer

Rather than #10067's two-minute timer per record, reload every record when
the omarchy-agent-usage-update process exits, the moment its files can have
been replaced. A reload that finds a file unchanged keeps its record, so the
panel isn't stirred up by identical data. The grep test now runs the QML
functions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Show the agent status when the trouble line has no help text (#8497)

* Clear stale agent login guidance after a successful probe (#8892)

* Clear the Grok login hint after a successful probe

#8892 cleared the default login hint after a successful probe in the
Claude and Codex collectors; Grok's collector had the same stale hint.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Read Fireworks credentials from pi's auth.json (#7455)

The Fireworks collector skipped pi, Omarchy's default agent, when
walking its credential ladder, so a machine signed in to Fireworks only
through pi (/login fireworks) never showed the tab. Insert the key pi
stores in $PI_CODING_AGENT_DIR/auth.json (default ~/.pi/agent) between
the firectl auth.ini and the opencode fallback.

pi keys can be literals, $ENV_VAR/${ENV_VAR} references, or !command
shell lookups. The collector resolves the first two; command lookups
stay pi-only and are skipped rather than sent to the API verbatim.

* Call a lapsed Grok access token paused, not signed out

Grok's access token lives six hours and Grok mints a new one from its
refresh token whenever it starts, so a lapsed one is routine. Reporting
it as an expired sign-in made the panel offer Sign-in required several
times a day, sending people through grok login for nothing. With a
refresh token present it now reads as paused, like Claude's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Keep showing Grok's last limits while it sits idle

While Grok hasn't run, nothing on the machine has spent its allowance,
so with a refresh token on hand the last numbers still stand: they show
as current rather than dimmed under a status line. A weekly window that
reset in the meantime starts over at 0%, a whole number of weeks on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Ask for a Grok sign-in once its refresh token is past 30 days

A refresh token older than Grok's 30-day sign-in can't renew anything,
so the panel offers Sign-in required again instead of showing the last
limits as current. With nothing cached yet it says to start Grok, rather
than showing an empty section without a word.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Check both ends of what the Claude index read before resuming a transcript

A transcript rewritten in place could grow and change only after its
first kilobytes, and the index took it for an append. It now compares
the last kilobytes before the resume point too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Simplify the agent usage collectors

- Codex: pass the forced-scan choice down instead of a module global, make
  the per-file reader's cache arguments required, shrink the cache record
  check, and drop guards for shapes that can't occur: an empty launcher
  path, realpath raising, mise itself being a lazy launcher, multi-line
  `mise which` output, and probing without a temp file for stderr.
- Claude: decide an append by the digest of both ends of what was read
  alone; the inode and mtime checks it made redundant are gone.
- Snapshot: the device id falls back to the hostname, which always exists.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Share fixture setup in the agent usage scanner tests

Every fixture home lives under one scratch directory with a single cleanup
trap, instead of a trap rewritten with a longer list for each new home, and
the Codex test builds its signed-in homes with one helper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Treat a replaced Claude transcript as new even when its ends match

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Probe Codex without its error text when there's no temporary space

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: tossbaws <[email protected]>
Co-authored-by: surim0n <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: anonwurcod <[email protected]>
Co-authored-by: Kevin Rajan <[email protected]>
Co-authored-by: Nate Ashby <[email protected]>
Co-authored-by: Aris Gysel <[email protected]>
Co-authored-by: Brams <[email protected]>
Co-authored-by: This_Is_NPC <[email protected]>
Co-authored-by: sanjyay <[email protected]>
Co-authored-by: PapistProtocol <[email protected]>
Co-authored-by: steez <[email protected]>
Co-authored-by: GPT-6 Astra <[email protected]>
Co-authored-by: Ryan Yogan <[email protected]>
Co-authored-by: Oli Denton <[email protected]>
Co-authored-by: Igor Kramar <[email protected]>
Co-authored-by: Martin Eidensten <[email protected]>
Co-authored-by: Romain Perron <[email protected]>
Co-authored-by: Omarchy Contributor <[email protected]>
Co-authored-by: manuaudio <[email protected]>
Co-authored-by: Tyler South <[email protected]>
Co-authored-by: whathek <[email protected]>
Co-authored-by: Ty Richards <[email protected]>
sgruendel pushed a commit to sgruendel/omarchy that referenced this pull request Oct 3, 2026
…ommunity PRs (omacom#14049)

* Read Codex app-server replies from the raw fd (omacom#13703)

* Resolve Codex through mise which instead of running the lazy launcher (omacom#13109)

* Skip the Codex app-server probe when there are no credentials (omacom#13106)

Adapted: credentials are checked in the home being probed rather than in
the CODEX_HOME environment variable, since each registered account is
probed in its own home, so a signed-out secondary account isn't hidden
behind the primary's login. A home without credentials reports "Waiting
for auth" like any other signed-out home. The credentials store setting is
read with tomllib, so a single-quoted value counts too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Show the Codex CLI's own error when its app-server dies (omacom#8977)

Detect an app-server that exits or stops answering, and report the end of
its stderr instead of a bare RPC method name. Rebased onto the raw-fd
reply reader; the switch from "-a on-request" to "-a never" is left out,
keeping the current approval flags.

* Count pi sessions when HOME is a git checkout (omacom#13209)

* Count only OpenAI-backed native sessions as Codex usage (omacom#12032)

* Deduplicate Pi usage across forked sessions (omacom#8602)

* Skip unchanged native Codex token snapshots (omacom#10531)

* Count omp and pi profile sessions in the agent usage collectors (omacom#9546)

`omp --profile=<name>` (and pi's equivalent) relocates the whole agent
tree under <base>/profiles/<name>/. The Claude and Codex collectors only
ever scanned <base>/agent/sessions, so a subscription driven entirely
through a profile was invisible to the agents panel: no tokens by day, no
tokens by model, no prompt or session counts.

Discover the profile roots alongside the default one. Sessions are keyed
by file path, so a profile adds sessions instead of double-counting the
default root, and a missing or unreadable profiles directory leaves the
existing behavior untouched.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014zFbJcDEEpV5BAmsH6kAB3

* Skip unrelated Codex session lines before JSON parsing (omacom#12803)

Adapted: session_meta lines also pass the pre-filter, since the provider
filter from omacom#12032 reads them to skip rollouts served by a non-OpenAI
provider.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Read only the Codex session files that changed since the last scan (omacom#12595)

Native Codex rollouts keep per-file totals between runs, replayed while a
file's mtime and size are unchanged. Rebased onto the session_meta
provider filter, snapshot dedup, and line pre-filter, which now live in
the per-file reader. pi and omp sessions are left out of the per-file
cache: a forked pi session repeats its parent's messages, so they are
deduplicated across the whole tree on every scan.

* Count streamed Claude messages by their highest-output usage line (omacom#10606)

Claude Code writes a streamed assistant response as several transcript
lines that share one message id, one per content block. Each line
carries a usage object. The first line's output_tokens is a placeholder,
often 1, and the last line has the real count. Input and cache fields
usually match across the lines.

The scanner dedupes by message id and keeps the first line it sees, so
it under-counts output tokens. On a machine with 2,577 transcripts it
reported 39.0M output tokens against 60.1M used, a 35% shortfall. Input
and both cache fields differed by under 0.01%.

Keep the line with the highest output count, with the last one scanned
winning a tie. The whole line is kept because a response can fall back
to another model mid-stream. Those lines are separate snapshots with
different cache figures and a different model, and taking a maximum per
field across them over-counts cache tokens and credits the wrong model.

The zero-usage check now runs before dedup, so a zero-usage first line
no longer claims a message id and hides a later line with real usage.

Co-authored-by: Claude Fable 5.1 <[email protected]>
Co-authored-by: GPT-6 Astra <[email protected]>

* Index Claude transcripts so the agents refresh reads only what was appended (omacom#8313)

omarchy-agent-usage-claude re-parsed every line of every transcript under
~/.claude/projects on each refresh: no mtime cutoff, no memory of the last
pass. The agents widget is on by default and ticks every 15 minutes, so the
cost grew for the life of the machine. After one month here that was 803
files, 640 MB, 127k lines and 57k JSON parses per tick, about 1 core-second,
pushed through the page cache every quarter hour forever.

Keep a per-file index next to the scan cache: the unique usage records
already parsed out of each transcript and the byte offset they end at. A
file whose size and mtime match is not opened; a file that grew is read
from the stored offset; a file that shrank or was rewritten is read from
the start. --force drops the index and rescans from scratch.

The summary is built from the indexed records in the same directory order
the walk always used. That matters: when a resumed session carries earlier
messages, the same message id appears in two files with different usage,
and the first file visited wins. 91 ids differed on this machine; sorting
the walk moved one model's output total by 25k tokens. Output is now
byte-identical to the previous scan on a frozen copy of the corpus, cold,
warm, and after an append.

Warm refresh: 1.0 s -> 0.10 s of CPU, of which the scan itself is 70 ms;
the index for this corpus is 2.9 MB.

Adapted:
- Rebased onto omacom#10606: the highest-output rule for streamed messages now
  lives where the index parses records, and decides between files too.
- The index records the timezone it was written in, and a change rereads
  every transcript, since its records hold local days.
- A file only counts as appended to when its inode and the hash of what
  was already read still match, so a transcript replaced by a larger one,
  or rewritten in place, is read from the start.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Label a Claude Team seat by its subscription, not its rate-limit tier (omacom#11109)

The collector built the plan label from the OAuth rateLimitTier first, so a
Team premium seat, which runs on default_claude_max_5x, showed in the agents
panel as "Max 5x". Lead with subscriptionType and keep the multiplier as its
qualifier: Max still reads "Max 5x", a Team seat reads "Team 5x".

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Label the Claude plan from the profile the CLI refreshes (omacom#7225)

Adapted: the profile is found the same way current_account_id() finds it,
now shared as profile_path(): ~/.claude.json for the default home, the
home's own .claude.json otherwise. The original fell back to ~/.claude.json
for any home without CLAUDE_CONFIG_DIR set, so a secondary account read the
primary's tier. The profile's tier also keeps the subscription in the label,
so a Team seat stays "Team" (omacom#11109).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Call a lapsed Claude access token paused, not signed out (omacom#8093)

* Refresh Claude usage after the clock moves backwards (omacom#9956)

* Bound unreadable Claude transcript warnings (omacom#12414)

* Count Claude usage from opencode v2 sessions (omacom#13894)

* Reload agent usage records when an inotify watch fails to rearm (omacom#10067)

* Reload agent usage records after each update run instead of on a timer

Rather than omacom#10067's two-minute timer per record, reload every record when
the omarchy-agent-usage-update process exits, the moment its files can have
been replaced. A reload that finds a file unchanged keeps its record, so the
panel isn't stirred up by identical data. The grep test now runs the QML
functions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Show the agent status when the trouble line has no help text (omacom#8497)

* Clear stale agent login guidance after a successful probe (omacom#8892)

* Clear the Grok login hint after a successful probe

omacom#8892 cleared the default login hint after a successful probe in the
Claude and Codex collectors; Grok's collector had the same stale hint.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Read Fireworks credentials from pi's auth.json (omacom#7455)

The Fireworks collector skipped pi, Omarchy's default agent, when
walking its credential ladder, so a machine signed in to Fireworks only
through pi (/login fireworks) never showed the tab. Insert the key pi
stores in $PI_CODING_AGENT_DIR/auth.json (default ~/.pi/agent) between
the firectl auth.ini and the opencode fallback.

pi keys can be literals, $ENV_VAR/${ENV_VAR} references, or !command
shell lookups. The collector resolves the first two; command lookups
stay pi-only and are skipped rather than sent to the API verbatim.

* Call a lapsed Grok access token paused, not signed out

Grok's access token lives six hours and Grok mints a new one from its
refresh token whenever it starts, so a lapsed one is routine. Reporting
it as an expired sign-in made the panel offer Sign-in required several
times a day, sending people through grok login for nothing. With a
refresh token present it now reads as paused, like Claude's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Keep showing Grok's last limits while it sits idle

While Grok hasn't run, nothing on the machine has spent its allowance,
so with a refresh token on hand the last numbers still stand: they show
as current rather than dimmed under a status line. A weekly window that
reset in the meantime starts over at 0%, a whole number of weeks on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Ask for a Grok sign-in once its refresh token is past 30 days

A refresh token older than Grok's 30-day sign-in can't renew anything,
so the panel offers Sign-in required again instead of showing the last
limits as current. With nothing cached yet it says to start Grok, rather
than showing an empty section without a word.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Check both ends of what the Claude index read before resuming a transcript

A transcript rewritten in place could grow and change only after its
first kilobytes, and the index took it for an append. It now compares
the last kilobytes before the resume point too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Simplify the agent usage collectors

- Codex: pass the forced-scan choice down instead of a module global, make
  the per-file reader's cache arguments required, shrink the cache record
  check, and drop guards for shapes that can't occur: an empty launcher
  path, realpath raising, mise itself being a lazy launcher, multi-line
  `mise which` output, and probing without a temp file for stderr.
- Claude: decide an append by the digest of both ends of what was read
  alone; the inode and mtime checks it made redundant are gone.
- Snapshot: the device id falls back to the hostname, which always exists.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Share fixture setup in the agent usage scanner tests

Every fixture home lives under one scratch directory with a single cleanup
trap, instead of a trap rewritten with a longer list for each new home, and
the Codex test builds its signed-in homes with one helper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Treat a replaced Claude transcript as new even when its ends match

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Probe Codex without its error text when there's no temporary space

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: tossbaws <[email protected]>
Co-authored-by: surim0n <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: anonwurcod <[email protected]>
Co-authored-by: Kevin Rajan <[email protected]>
Co-authored-by: Nate Ashby <[email protected]>
Co-authored-by: Aris Gysel <[email protected]>
Co-authored-by: Brams <[email protected]>
Co-authored-by: This_Is_NPC <[email protected]>
Co-authored-by: sanjyay <[email protected]>
Co-authored-by: PapistProtocol <[email protected]>
Co-authored-by: steez <[email protected]>
Co-authored-by: GPT-6 Astra <[email protected]>
Co-authored-by: Ryan Yogan <[email protected]>
Co-authored-by: Oli Denton <[email protected]>
Co-authored-by: Igor Kramar <[email protected]>
Co-authored-by: Martin Eidensten <[email protected]>
Co-authored-by: Romain Perron <[email protected]>
Co-authored-by: Omarchy Contributor <[email protected]>
Co-authored-by: manuaudio <[email protected]>
Co-authored-by: Tyler South <[email protected]>
Co-authored-by: whathek <[email protected]>
Co-authored-by: Ty Richards <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Codex usage collector rereads GB of history and saturates CPU

4 participants