omarchy icon indicating copy to clipboard operation
omarchy copied to clipboard

Agents bar widget: Claude collector shows 'Waiting for auth' with Vertex/Bedrock auth; no Gemini collector

Open Leonslost opened this issue 3 months ago • 2 comments

What happened

The Agents bar widget (omarchy.agents) misreports Claude's auth status when Claude Code is authenticated through Google Vertex AI (ANTHROPIC_VERTEX_PROJECT_ID set) instead of the standard claude login OAuth flow. The panel's hero card shows "Waiting for auth" with the help text "Run claude auth login to restore authoritative usage," even though Claude Code is actively running and working normally.

Separately, the widget also has no collector for the Gemini CLI at all, so Gemini never appears in the panel/switcher even when it's installed, authenticated, and in active use alongside Claude and Codex.

Root cause (traced in source)

/usr/share/omarchy/bin/omarchy-agent-usage-claude's oauth_login() only ever reads an access token from ~/.claude/.credentials.json (claudeAiOauth.accessToken). When Claude Code is authenticated via Vertex (or presumably Bedrock), that file is never created — there's no OAuth login step — so access_token is always "", collect_limits() takes the early-return branch, and the record is written with "usageStatusText": "Waiting for auth" regardless of whether Claude Code is actually working.

The local stats (today's tokens, model breakdown, weekly chart) are unaffected because those come from scanning ~/.claude/projects/*.jsonl transcripts directly (hasLocalStats: true), independent of the auth method. So the panel ends up in a confusing half-working state: usage numbers accrue correctly, but the hero card permanently shows an auth warning with an incorrect remedy ("run claude auth login" does nothing useful — there's no OAuth session to restore).

Separately, /usr/share/omarchy/shell/plugins/agents/manifest.json and bin/ only define collectors for claude, codex, and fireworks — there is no omarchy-agent-usage-gemini. This appears to be a missing feature rather than a bug, but is filed alongside since it compounds the confusion (a user with two working CLIs, Claude and Gemini, only ever sees one in the widget, and the one they do see shows a false auth error).

Expected behavior

  • When ~/.claude/.credentials.json is absent but Claude Code has recent local transcript activity (hasLocalStats / totalPrompts > 0) and/or ANTHROPIC_VERTEX_PROJECT_ID / CLAUDE_CODE_USE_VERTEX / CLAUDE_CODE_USE_BEDROCK env vars are set, the widget should not claim the user needs to run claude auth login. At minimum it should distinguish "OAuth session not applicable (non-OAuth auth backend, limits unavailable)" from "OAuth session lapsed, please re-auth."
  • Gemini CLI usage should be collectible the same way claude/codex are, following the record contract described in the plugin's README (a bin/omarchy-agent-usage-gemini collector).

Steps to reproduce

  1. Authenticate Claude Code via Google Vertex AI (ANTHROPIC_VERTEX_PROJECT_ID set, no claude login OAuth session, so ~/.claude/.credentials.json does not exist).
  2. Use Claude Code normally — transcripts accrue under ~/.claude/projects.
  3. Open the Agents bar panel.
  4. Observe: hero card shows "Waiting for auth" / "Run claude auth login to restore authoritative usage" even while Claude Code is being used in the same moment, and token counts are visibly incrementing.
  5. Separately: have the Gemini CLI installed and authenticated/in use — it never appears as a subscription tab/switch entry in the panel, because no collector exists for it.

System details

  • Omarchy version: 4.0.0-1
  • Kernel: Linux 7.1.8-arch1-3
  • Hardware: HP OMEN Transcend Gaming Laptop 14-fb0xxx
  • GPU: Intel Arc Graphics (Meteor Lake-P) + NVIDIA GeForce RTX 4070 Max-Q
  • omarchy debug command not present in this version (omarchy commands --all has no debug entry), so no diagnostic log/URL is attached.

Sample record written by the collector

{
  "id": "claude",
  "name": "Claude Code",
  "ready": true,
  "hasLocalStats": true,
  "usageStatusText": "Waiting for auth",
  "authHelpText": "Run `claude auth login` to restore authoritative usage.",
  "limits": [],
  "todayTotalTokens": 569684,
  "todayPrompts": 12,
  "todaySessions": 2
}

Leonslost avatar Aug 15 '26 14:08 Leonslost

For anyone hitting this in the meantime: a local, user-scoped workaround that blanks the false auth warning on the Claude card until this is fixed properly.

It's a small script watched via inotify that patches ~/.local/state/omarchy/agents/usage/claude.json right after omarchy-agent-usage-claude (re)writes it — clearing usageStatusText/authHelpText only when hasLocalStats is true and ~/.claude/.credentials.json doesn't exist (i.e. only in the no-OAuth-session case this issue is about; a real lapsed OAuth session is left alone). Autostarted via Hyprland's autostart.lua so it survives reboots, and it stands down automatically if a real OAuth login ever appears.

~/.local/bin/omarchy-claude-authcard-patch:

#!/bin/bash
STATE_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/agents/usage"
RECORD="$STATE_DIR/claude.json"
CREDS="$(eval echo "${CLAUDE_CONFIG_DIR:-$HOME/.claude}")/.credentials.json"

patch() {
  [[ -f $RECORD ]] || return 0
  [[ -f $CREDS ]] && return 0

  local current patched tmp
  current=$(cat "$RECORD")
  patched=$(jq 'if .hasLocalStats and (.usageStatusText // "") != "" then .usageStatusText = "" | .authHelpText = "" else . end' <<<"$current" 2>/dev/null)
  [[ -z $patched || $patched == "$current" ]] && return 0

  tmp=$(mktemp "$STATE_DIR/.claude.XXXXXX")
  printf '%s\n' "$patched" >"$tmp"
  mv "$tmp" "$RECORD"
}

mkdir -p "$STATE_DIR"
patch
while inotifywait -qq -e close_write -e moved_to "$STATE_DIR" >/dev/null 2>&1; do
  patch
done

Added to ~/.config/hypr/autostart.lua:

o.launch_on_start("omarchy-claude-authcard-patch")

Obviously just a mitigation, not a substitute for the collector actually recognizing non-OAuth auth backends.

Leonslost avatar Aug 15 '26 15:08 Leonslost

For the second half of this issue (no Gemini collector): here's a working one, in case it's useful to anyone before this is fixed upstream.

It follows the record contract the shipped collectors print, so the panel picks it up with no changes to the plugin — Main.qml discovers records by globbing the usage directory, and providerEnabled() defaults to true for ids it doesn't know.

Data source. Gemini CLI writes per-message token counts to its own transcripts at ~/.gemini/tmp/<project>/chats/session-*.jsonl:

{"type":"gemini","model":"gemini-3.5-flash","timestamp":"...","tokens":{"input":13229,"output":21,"cached":0,"thoughts":390,"tool":0,"total":13640}}

total = input + output + thoughts, with cached a subset of input. Mapped onto the record's four-way split: thoughts bill as output, and cached input is reported as a cache read rather than counted twice.

Two transcript details worth flagging for anyone writing their own version:

  • Lines come in three shapes — a header, plain message objects, and {"$set": {...}} deltas whose messages key replaces the entire history. The replacement repeats messages already streamed, so it dedups by message id or a resumed session double-counts.
  • Timestamps are UTC (Z); day bucketing has to convert to local time or "today" lands on the wrong row for anyone west of Greenwich.

No limits. Gemini CLI publishes no quota endpoint — no usage subcommand, nothing local — so limits is empty and only the stats sections render. That combination (a real status, no auth remedy) turns out to hit a separate renderer bug, filed as #8445.

Install. The collector alone isn't enough: omarchy-agent-usage-update globs "$OMARCHY_PATH"/bin/omarchy-agent-usage-*, so a user-supplied collector never runs on the widget's refresh timer. A systemd user timer writes the record independently — the panel reads whatever lands in the directory, whoever wrote it.

install -Dm755 omarchy-agent-usage-gemini ~/.local/bin/omarchy-agent-usage-gemini
# ~/.config/systemd/user/omarchy-agent-usage-gemini.service
[Unit]
Description=Refresh the Gemini usage record for the Omarchy agents widget

[Service]
Type=oneshot
ExecStart=/bin/bash -c 'dir="${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/agents/usage"; mkdir -p "$dir"; tmp=$(mktemp "$dir/.gemini.XXXXXX"); if %h/.local/bin/omarchy-agent-usage-gemini >"$tmp" && [ -s "$tmp" ]; then mv "$tmp" "$dir/gemini.json"; else rm -f "$tmp"; exit 1; fi'
# ~/.config/systemd/user/omarchy-agent-usage-gemini.timer
[Unit]
Description=Refresh the Gemini usage record every 15 minutes

[Timer]
OnStartupSec=1min
OnUnitActiveSec=15min
Persistent=true

[Install]
WantedBy=timers.target
systemctl --user daemon-reload
systemctl --user enable --now omarchy-agent-usage-gemini.timer

The tab has no mark unless you also drop a gemini.svg into the plugin's assets/, which means cloning the plugin — the bar glyph stands in otherwise.

Known gaps. It reads Gemini CLI transcripts only, so it misses Gemini used through another agent — the shipped Claude collector deliberately picks up opencode sessions on an Anthropic provider, and Codex picks up pi and opencode sessions, but this does no equivalent reverse mapping. Also unaware of the syncMode aggregation.

omarchy-agent-usage-gemini
#!/usr/bin/python3
# omarchy:summary=Print the Gemini CLI usage record as JSON
# omarchy:args=[--force] [--limits-only]
# omarchy:hidden=true
"""Collect Gemini CLI usage into one display-ready JSON record.

Local stats come from the Gemini CLI's own session transcripts under
<gemini-dir>/tmp/<project>/chats/session-*.jsonl, which carry a per-message
token breakdown. Gemini CLI exposes no quota endpoint, so this reports local
stats only and leaves `limits` empty. The agents panel only ever reads the
JSON this prints.
"""

import argparse
import glob
import json
import os
import sys
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from pathlib import Path

AGENT_ID = "gemini"
AGENT_NAME = "Gemini CLI"
AUTH_HELP = "Run `gemini` and sign in to record usage."
RECENT_DAYS = 7


def gemini_dir():
    return Path(os.environ.get("GEMINI_DIR") or Path.home() / ".gemini")


def signed_in():
    """The panel's help card is for auth problems. Gemini's absent quota API is
    not one, so only speak up when there are genuinely no credentials on disk —
    otherwise a signed-in user reads a red card telling them to sign in."""
    root = gemini_dir()
    return any((root / name).exists()
               for name in ("oauth_creds.json", "google_accounts.json"))


def session_files():
    pattern = str(gemini_dir() / "tmp" / "*" / "chats" / "session-*.jsonl")
    return sorted(glob.glob(pattern))


def local_date(stamp):
    """'2026-08-26T04:35:07.670Z' -> local calendar date."""
    if not stamp:
        return None
    try:
        text = str(stamp).replace("Z", "+00:00")
        moment = datetime.fromisoformat(text)
    except ValueError:
        return None
    if moment.tzinfo is None:
        moment = moment.replace(tzinfo=timezone.utc)
    return moment.astimezone().date()


def split_tokens(tokens):
    """Gemini reports total = input + output + thoughts, with `cached` a
    subset of input. Map that onto the record's four-way split: thoughts bill
    as output, and cached input is reported as a cache read rather than
    counted twice."""
    def count(key):
        value = tokens.get(key)
        return value if isinstance(value, (int, float)) and value > 0 else 0

    cached = count("cached")
    total = count("total")
    if not total:
        total = count("input") + count("output") + count("thoughts")
    return {
        "inputTokens": max(0, count("input") - cached),
        "outputTokens": count("output") + count("thoughts"),
        "cacheReadInputTokens": cached,
        "cacheCreationInputTokens": 0,
        "total": total,
    }


def iter_messages(path):
    """Yield every message in one transcript.

    A transcript mixes three line shapes: a header, plain message objects, and
    {"$set": {...}} deltas whose `messages` key replaces the whole history. The
    replacement repeats messages already streamed, so callers dedup by id.
    """
    try:
        with open(path, "r", errors="replace") as handle:
            for line in handle:
                line = line.strip()
                if not line:
                    continue
                try:
                    entry = json.loads(line)
                except json.JSONDecodeError:
                    continue
                if not isinstance(entry, dict):
                    continue
                if "$set" in entry:
                    replacement = (entry.get("$set") or {}).get("messages")
                    if isinstance(replacement, list):
                        for message in replacement:
                            if isinstance(message, dict):
                                yield message
                    continue
                if entry.get("kind") and entry.get("sessionId"):
                    continue
                yield entry
    except OSError:
        return


def collect():
    today = datetime.now().astimezone().date()
    window = {today - timedelta(days=offset) for offset in range(RECENT_DAYS)}

    tokens_by_day = defaultdict(int)
    model_usage = defaultdict(lambda: defaultdict(int))
    today_tokens_by_model = defaultdict(int)
    active_dates = set()
    total_prompts = 0
    today_prompts = 0
    today_sessions = 0
    total_sessions = 0

    for path in session_files():
        total_sessions += 1
        seen = set()
        touched_today = False

        for index, message in enumerate(iter_messages(path)):
            key = message.get("id")
            key = key if key is not None else f"__pos{index}"
            if key in seen:
                continue
            seen.add(key)

            day = local_date(message.get("timestamp"))
            if day:
                active_dates.add(day)
                if day == today:
                    touched_today = True

            if message.get("type") == "user":
                total_prompts += 1
                if day == today:
                    today_prompts += 1

            tokens = message.get("tokens")
            if not isinstance(tokens, dict):
                continue

            split = split_tokens(tokens)
            total = split.pop("total")
            model = str(message.get("model") or "gemini")

            for field, value in split.items():
                model_usage[model][field] += value
            if day:
                tokens_by_day[day] += total
                if day == today:
                    today_tokens_by_model[model] += total

        if touched_today:
            today_sessions += 1

    recent_days = [
        {
            "date": (today - timedelta(days=offset)).isoformat(),
            "messageCount": tokens_by_day.get(today - timedelta(days=offset), 0),
        }
        for offset in reversed(range(RECENT_DAYS))
    ]

    return {
        "schemaVersion": 1,
        "id": AGENT_ID,
        "name": AGENT_NAME,
        "updatedAt": datetime.now(timezone.utc).astimezone().isoformat(),
        "ready": True,
        "hasLocalStats": True,
        "todayPrompts": today_prompts,
        "todaySessions": today_sessions,
        "todayTotalTokens": tokens_by_day.get(today, 0),
        "todayTokensByModel": dict(today_tokens_by_model),
        "recentDays": recent_days,
        "totalPrompts": total_prompts,
        "totalSessions": total_sessions,
        "activeDays": len(active_dates),
        "activeDates": sorted(day.isoformat() for day in active_dates),
        "modelUsage": {model: dict(fields) for model, fields in model_usage.items()},
        # Gemini CLI publishes no quota endpoint, so the panel gets stats only.
        "limits": [],
        "tierLabel": "",
        "usageStatusText": "Gemini limits unavailable",
        "authHelpText": "" if signed_in() else AUTH_HELP,
    }


def main():
    parser = argparse.ArgumentParser(add_help=False)
    # Accepted for parity with the shipped collectors. A scan of a handful of
    # transcripts is cheap enough that neither flag changes the work.
    parser.add_argument("--force", action="store_true")
    parser.add_argument("--limits-only", action="store_true")
    parser.parse_args()

    json.dump(collect(), sys.stdout, indent=2, sort_keys=True)
    sys.stdout.write("\n")


if __name__ == "__main__":
    main()

davo42002 avatar Aug 26 '26 18:08 davo42002