Skip to content

feat(mimo): opt-in local tracker fallback for MiMo card#1284

Open
LeoLin990405 wants to merge 1 commit into
steipete:mainfrom
LeoLin990405:fix/mimo-local-tracker-fallback
Open

feat(mimo): opt-in local tracker fallback for MiMo card#1284
LeoLin990405 wants to merge 1 commit into
steipete:mainfrom
LeoLin990405:fix/mimo-local-tracker-fallback

Conversation

@LeoLin990405
Copy link
Copy Markdown
Contributor

Summary

  • Add an implicit opt-in local fallback so the MiMo card surfaces meaningful data (lifetime/weekly token sums + progress bar) when the platform.xiaomimimo.com SSO cookie path is unavailable, instead of stuck on Xiaomi MiMo login required.
  • MiMoWebFetchStrategy.fetch() wraps existing cookie logic in try/catch and falls back to MiMoLocalUsageFallback.snapshot() only when ~/.codexbar/mimo-local-usage.json exists (zero behavior change for users who do not opt in).
  • Suppress the "Balance updates in near-real time / Daily billing finalizes at 07:00 UTC" footer when sourceLabel == "local" since neither applies to local accounting.
  • Ship Scripts/mimo-usage.py (Python 3, no external deps) as a sample tracker — scans ~/.claude-envs/mimo/.claude/projects/**/*.jsonl for any Claude Code wrapper pointed at MiMo (e.g. cc-mimo with ANTHROPIC_BASE_URL=https://token-plan-sgp.xiaomimimo.com/anthropic) and aggregates input_tokens / output_tokens / cache_read_input_tokens per today / week / all_time window.
  • Documented under docs/mimo.md → "Local fallback (opt-in)".

Why

The MiMo provider currently only reaches platform.xiaomimimo.com via SSO cookies, which break in common macOS scenarios:

  • Chrome session cookies (api-platform_serviceToken etc.) clear on Chrome relaunch (they're session-level: expires=0 in Chrome SQLite).
  • Disable Keychain access / TCC blocks reading Chrome Safe Storage to decrypt the cookie value.
  • The user drives MiMo inference only through a wrapper and never logs into platform from a browser.

When this happens the MiMo card shows Xiaomi MiMo login required indefinitely with no escape hatch — tp--prefixed inference API keys (token-plan-sgp.xiaomimimo.com/anthropic) cannot query platform quota; they are two independent auth systems per Xiaomi's own docs.

The local fallback is implicit opt-in: it activates only when the cache file exists. Users without a local wrapper / tracker see no change; current behavior preserved exactly.

Tests

  • Added MiMoLocalUsageFallbackTests covering:
    • cache file missing → snapshot() returns nil → fallback skipped
    • cache file malformed JSON → returns nil → fallback skipped
    • normal parse with progress bar (today/week/lifetime/sessions in planCode + tokenUsed/tokenLimit/tokenPercent for the progress bar)
    • idle-week edge case (week=0, allTime>0 → progress bar empty with lifetime as baseline)

Validation

  • swift build --target CodexBarCore passes locally.
  • swift build --target CodexBar passes locally.
  • Local swift test --filter MiMoLocalUsageFallbackTests is blocked before reaching the new tests by the local Command Line Tools environment (KeyboardShortcuts #Preview macro plugins are unavailable without full Xcode); CI should be the test signal.

Scope

No changes to OAuth/cookie paths, provider selection ordering, settings UI, Package.swift, or non-MiMo providers. Behavior is identical to current main when ~/.codexbar/mimo-local-usage.json does not exist.

@clawsweeper
Copy link
Copy Markdown

clawsweeper Bot commented Jun 3, 2026

Codex review: needs real behavior proof before merge. Reviewed June 4, 2026, 3:06 AM ET / 07:06 UTC.

Summary
Review failed before ClawSweeper could summarize the requested change.

Reproducibility: unclear. The review failed before ClawSweeper could establish a reproduction path.

Review metrics: none identified.

Merge readiness
Overall: 🌊 off-meta tidepool
Proof: 🌊 off-meta tidepool
Patch quality: 🌊 off-meta tidepool
Result: rating does not apply to this item.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Risk before merge

  • [P1] No close action taken because the review did not complete.

Maintainer options:

  1. Decide the mitigation before merge
    Retry the Codex review after fixing the execution failure.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Next step before merge

  • [P1] Review did not complete, so no work-lane recommendation was made.
Review details

Best possible solution:

Retry the Codex review after fixing the execution failure.

Do we have a high-confidence way to reproduce the issue?

Unclear. The review failed before ClawSweeper could establish a reproduction path.

Is this the best way to solve the issue?

Unclear. Retry the review first so ClawSweeper can evaluate the actual issue and fix direction.

AGENTS.md: unclear because the file could not be read completely.

Codex review notes: model gpt-5.5, reasoning high; reviewed against 65e39f4dcb3a.

Label changes

Label changes:

  • add rating: 🌊 off-meta tidepool: Overall readiness is 🌊 off-meta tidepool; proof is 🌊 off-meta tidepool and patch quality is 🌊 off-meta tidepool.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🌊 off-meta tidepool, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status no longer selects a status label.
  • remove P2: Current review triage priority is none.

Label justifications:

  • rating: 🌊 off-meta tidepool: Overall readiness is 🌊 off-meta tidepool; proof is 🌊 off-meta tidepool and patch quality is 🌊 off-meta tidepool.
Evidence reviewed

What I checked:

  • failure reason: timeout.
  • codex failure detail: Codex review failed for this PR: spawnSync codex ETIMEDOUT.
  • codex stdout: Per-item Codex failure; continuing with the rest of the shard.

Likely related people:

  • unknown: Codex failed before it could trace repository history. (role: review did not complete; confidence: low)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0bcd990d4c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +91 to +94
if Self.shouldFallbackToLocal(error: error),
let local = MiMoLocalUsageFallback.snapshot()
{
return self.makeResult(usage: local.toUsageSnapshot(), sourceLabel: "local")
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Let the local cache make MiMo fetching available

When MiMo is in auto mode with no cached/importable browser session, isAvailable() returns false, and ProviderFetchPipeline.fetch skips fetch() entirely before this fallback branch can run. That means the documented opt-in path for users with only ~/.codexbar/mimo-local-usage.json and no platform cookies still ends in noAvailableStrategy instead of showing local usage; the strategy needs to report available when the local cache exists or expose a separate local strategy.

Useful? React with 👍 / 👎.

Comment on lines +38 to +41
let weekInput = Self.intValue(week["input"])
let weekOutput = Self.intValue(week["output"])
let weekCacheRead = Self.intValue(week["cache_read"])
let weekTotal = weekInput + weekOutput + weekCacheRead
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Include cache-creation tokens in local totals

For sessions that contain cache_creation_input_tokens, the tracker writes cache_create into each window, but the fallback snapshot only sums input/output/cache_read for today/week/all-time. Those cache-creation tokens are billable local activity and are displayed by the script summary, so omitting them here underreports the MiMo card totals and progress for any cached-prompt session that creates cache entries.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 3, 2026
The MiMo provider only reaches platform.xiaomimimo.com via SSO cookies, which
break in common scenarios: Chrome session cookies clear on Chrome relaunch,
macOS keychain access to Chrome Safe Storage is blocked, the user has no SSO
login on this machine, etc. When this happens the MiMo card surfaces
"Xiaomi MiMo login required" indefinitely with no escape hatch (tp-prefixed
inference API keys for token-plan-sgp.xiaomimimo.com cannot query platform
quota — two independent auth systems).

This PR adds an implicit opt-in local fallback. When the platform fetch fails
with missingCookie / invalidCookie / loginRequired / invalidCredentials, the
MiMo strategy reads `~/.codexbar/mimo-local-usage.json` (populated by
`Scripts/mimo-usage.py` which scans `~/.claude-envs/mimo/.claude/projects/**/
*.jsonl` for any local Claude Code wrapper pointed at MiMo) and returns a
snapshot wrapped as `sourceLabel: "local"`.

- New `MiMoLocalUsageFallback.swift` reads the JSON cache and constructs a
  `MiMoUsageSnapshot` with today/week/lifetime token sums in `planCode` and a
  progress bar showing weekly tokens vs lifetime baseline.
- `MiMoWebFetchStrategy.fetch()` wraps the existing logic in try/catch and
  invokes the fallback only when the cache file exists (zero behavior change
  for users who do not opt in).
- `MenuCardView.usageNotes(input:)` suppresses the "Balance updates in
  near-real time / Daily billing finalizes at 07:00 UTC" footer when
  sourceLabel is "local" since neither applies to local accounting.
- `Scripts/mimo-usage.py` ships the sample tracker (Python 3, no external
  deps). Setup is documented in `docs/mimo.md` "Local fallback (opt-in)".
- New `MiMoLocalUsageFallbackTests` cover missing/malformed cache, normal
  parse with progress bar, and idle-week surfacing lifetime baseline.

## Tests
- `swift test --filter MiMoLocalUsageFallbackTests`

## Validation
- `swift build --target CodexBarCore` passes locally.
- `swift build --target CodexBar` passes locally.
- Local `swift test` is blocked before reaching these tests by the local
  Command Line Tools environment (`KeyboardShortcuts` `#Preview` macro
  plugins are unavailable without full Xcode); CI should be the test signal.

## Scope
No changes to OAuth/cookie paths, provider ordering, settings UI, package
targets, or non-MiMo providers. Behavior is identical to current main when
`~/.codexbar/mimo-local-usage.json` does not exist.
@LeoLin990405 LeoLin990405 force-pushed the fix/mimo-local-tracker-fallback branch from 0bcd990 to f923238 Compare June 3, 2026 06:14
@LeoLin990405
Copy link
Copy Markdown
Contributor Author

Pushed an amend: MiMoWebFetchStrategy.isAvailable(_:) now also returns true when MiMoLocalUsageFallback.snapshot() is non-nil. Without this, the multi-account provider switcher (the popover that lists each provider's status) reports No available fetch strategy for mimo whenever cookies are absent even though the fallback would happily serve the menu card on the next refresh. Test coverage stays the same since MiMoLocalUsageFallbackTests already pins snapshot() returning non-nil under valid cache and nil under missing/malformed cache.

@clawsweeper clawsweeper Bot added the P2 Normal priority bug or improvement with limited blast radius. label Jun 3, 2026
@LeoLin990405
Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The previous review marker references commit 0bcd990d from before the amend. The branch HEAD is now f923238a which adds an isAvailable(_:) change so the provider switcher no longer reports No available fetch strategy for mimo when only the local fallback is configured.

Real-behavior proof (after installing Scripts/mimo-usage.py and running it once to populate ~/.codexbar/mimo-local-usage.json against a cc-mimo style wrapper):

$ codexbar usage --provider mimo
== Xiaomi MiMo (local) ==
Credits: 100% left [============]
Resets 0 / 20,875,221 Credits
Plan: 20.9M Total · 1296 Sessions

$ codexbar usage --provider mimo --json | jq '.[0].source'
"local"

The (local) source label, the Local Tracker (1296 Sessions) plan label in the menu loginMethod row, and the lifetime baseline as progress denominator are exactly the contract the new MiMoLocalUsageFallback.snapshot() is supposed to produce, matching the assertions in MiMoLocalUsageFallbackTests.

Menu screenshot will be attached in a follow-up comment from the PR author (gh CLI doesn't support image upload).

Zero behavior change for users without ~/.codexbar/mimo-local-usage.json — the fallback file simply does not exist, snapshot() returns nil, isAvailable falls back to the original cookie/browser-session check, and fetch() does not invoke the fallback path. Same external behavior as main.

@clawsweeper
Copy link
Copy Markdown

clawsweeper Bot commented Jun 4, 2026

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal priority bug or improvement with limited blast radius. rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant