Skip to content

MiniMax: recharge credits, usage dashboard, and quota utilization#1821

Closed
Yuxin-Qiao wants to merge 57 commits into
steipete:mainfrom
Yuxin-Qiao:feat/minimax-token-plan-credit
Closed

MiniMax: recharge credits, usage dashboard, and quota utilization#1821
Yuxin-Qiao wants to merge 57 commits into
steipete:mainfrom
Yuxin-Qiao:feat/minimax-token-plan-credit

Conversation

@Yuxin-Qiao

@Yuxin-Qiao Yuxin-Qiao commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

Summary

Token Plan recharge credit balance

  • MiniMax Coding Plan / Token Plan remains APIs do not expose the console recharge-credit balance (积分余额). CodexBar now fetches it from GET /backend/account/token_plan_credit on www.minimaxi.com / www.minimax.io when a web session cookie is available.
  • Web-session refreshes always attempt the credit fetch after quota/billing enrichment (even when billing history is disabled).
  • API-token refreshes now enrich through MiniMaxWebEnrichmentResolver, trying candidates in order: manual/env cookie → MiniMax Agent desktop cookies → cached browser cookies → live browser import.
  • Chrome Keychain suppression is bypassed on user-initiated refresh (⌘R) so browser-only users can approve access once and then cache the session for background refreshes.
  • Credit enrichment is best-effort for auth/transport/parser failures but propagates cancellation like the other MiniMax optional enrichments.
  • MINIMAX_HOST selects the matching www.* credit host for MiniMax-owned domains; custom proxy hosts route through the override path. Use MINIMAX_TOKEN_PLAN_CREDIT_URL for a full custom credit URL.
  • Global→CN API retry stays fetch-scoped only; env-only CLI probes no longer persist region: cn into config.
  • Diagnostics export includes pointsBalance; menu rendering reuses the existing MiniMax points balance cost row.

Console usage-summary dashboard

  • Fetch and parse MiniMax 30-day usage summary (usage_summary) alongside quota/credit enrichment when a web cookie is available.
  • Main menu card: inline 6 KPI grid (today cost, 30d cost, latest-hour tokens, 7d tokens, cache hit, 30d tokens) plus a cost trend sparkline when pay-as-you-go pricing is available.
  • Token usage details submenu: 7d/30d trend chart, daily spend estimates, model breakdown, and window spend KPIs (hidden when the same summary KPIs already appear on the main card).
  • Subscription Utilization submenu for MiniMax: Session / Weekly quota history chart (same component as Codex/Claude), recording 5h + weekly lanes automatically.
  • Menu bar reset-time mode shows the nearest MiniMax quota reset (5h window) instead of the weekly reset when both are present.
  • KPI formatting: token counts to 2 decimal places, reset countdowns to minutes, localized pricing disclaimer strings.

Web session enrichment (no MiniMax Code required)

  • MiniMax Agent / MiniMax Code (if installed): reads ~/Library/Application Support/MiniMax/Cookies automatically — no Chrome Keychain prompt.
  • Browser-only users: stay logged into platform.minimaxi.com / www.minimaxi.com in Chrome, then press ⌘R once and approve the Keychain prompt if macOS asks for Chrome safe-storage access.
  • Manual fallback: paste DevTools Cookie: header into Preferences → Providers → MiniMax, or set MINIMAX_COOKIE.
  • Docs updated in docs/minimax.md with the full source priority and capture steps.

Follow-up fixes in this branch

  • Menu Usage Dashboard opens platform.*.com/console/usage (not the Coding Plan page). Settings Open Token Plan still opens the Coding Plan page.
  • 5h reset countdown ignores implausible remains_time values and falls back to end_time.
  • MINIMAX_HOST custom proxies also route usage_summary enrichment; MiniMax-owned host overrides still map to the matching www.* summary host.
  • Usage-summary cost projection bills cache_read_token separately from input_token.
  • Optional usage-summary auth failures no longer discard a valid API-token quota result when an auxiliary cookie is stale.
  • Fix timezone-flaky menu-card credit expiry assertion (MenuCardModelTests) that failed CI on UTC runners.

Review follow-up

Round 1 (30cf613a / ClawSweeper)

  • P2 (Codex) Remove provider-wide region persistence; keep fallback region fetch-scoped
  • P2 Route credit lookups from MINIMAX_HOST / resolved region instead of always using global www.minimax.io
  • P1 Live cookie-session proof with redacted diagnose / usage output (below)
  • P3 Gate live test on non-negative balance; optional MINIMAX_LIVE_TEST_EXPECTED_BALANCE for exact asserts
  • Fall back to MINIMAX_COOKIE / env when manual cookie settings are empty
  • P3 (ClawSweeper) Remove stale region-persistence release note

Round 2 (@chatgpt-codex-connector)

  • P2 Honor MINIMAX_HOST overrides for usage-summary enrichment
  • P2 Bill cache reads in addition to input tokens in usage-summary cost projection
  • P2 Keep optional usage-summary failures from failing API-token quota fetch

Motivation

Users with recharge credits (for example 20,000 points in the MiniMax console) saw quota data via API key but providerCostPresent: false in diagnostics and no balance in the menu. The balance lives on a separate cookie-authenticated endpoint discovered from the platform web bundle.

The console also exposes a separate usage-summary API with token/cost trends, cache-hit stats, and model breakdowns that CodexBar previously did not fetch or render. This PR adds that enrichment plus Codex-style quota utilization history without duplicating KPI blocks between the main card and submenus.

UI evidence (live Plus account, 2026-07-02)

Main card inline dashboard + credits

MiniMax main card inline dashboard

Shows 5h / Weekly quota rows, 6 KPI grid, cost trend, top-model line, pricing disclaimer, and 20,000 recharge credits with expiry.

Menu card usage notes (Settings preview)

MiniMax menu card usage notes

Subscription Utilization (Session / Weekly history)

MiniMax subscription utilization

Codex-style quota utilization chart with Session/Weekly lanes; footer shows reset time + used %.

Token usage details submenu

MiniMax token usage details

7d/30d segmented trend, daily spend, per-model token/cost rows, and window spend KPIs.

Test plan

  • make check
  • swift test --filter MiniMax
  • swift test --filter MiniMaxTokenPlanCreditTests
  • swift test --filter MiniMaxUsageSummary
  • swift test --filter MiniMaxResetDescriptionTests
  • swift test --filter MenuBarMiniMaxResetTimeDisplayTests
  • swift test --filter UsageStorePlanUtilizationTests
  • swift test --filter MiniMaxDesktopCookieImporterTests
  • swift test --filter MiniMaxWebEnrichmentResolverTests
  • TZ=UTC swift test --filter 'minimax token plan model shows weekly quota'
  • Parser coverage for remaining_credits, balance_breakdown.total_balance, and total_credits - used_credits
  • Web + API enrichment paths via ProviderHTTPTransportStub
  • Host-override credit + usage-summary routing + cookie env fallback
  • Dashboard URL opens console/usage
  • Cache-read pricing bills separately from input ($0.33 for 1M input + 500k cache reads on M2.7)
  • API-token quota survives stale auxiliary cookie during optional usage-summary enrichment
  • ./Scripts/compile_and_run.sh — menu card, Usage Dashboard link, and both submenus verified locally

Behavior proof

API-only account (no web session): built PR CLI on this branch

.build/release/CodexBarCLI diagnose --provider minimax --format json --pretty

source: api, quota present, pointsBalance omitted (expected; web cookie required).

API key + web session cookie (MiniMax Agent desktop or browser/manual): built PR CLI on this branch, 2026-07-02

{
  "source": "api",
  "planName": "Plus",
  "pointsBalance": 20000,
  "usageSummaryPresent": true,
  "providerCost": {
    "period": "MiniMax points balance",
    "used": 20000
  }
}

Commands:

# MiniMax Agent installed: automatic via desktop cookie store
# Browser-only: log into platform.minimaxi.com, then ⌘R in the MiniMax menu card
.build/release/CodexBarCLI diagnose --provider minimax --format json --pretty
.build/release/CodexBarCLI usage --provider minimax --format json

Direct endpoint sanity check (same session cookie, redacted): GET https://www.minimaxi.com/backend/account/token_plan_creditremaining_credits: 20000, base_resp.status_code: 0.

Notes for reviewers

  • Bearer API key alone still cannot read token_plan_credit (console returns not login); a web _token cookie is required for the balance.
  • MiniMax Agent desktop cookies are preferred when present; browser-only users need one user-initiated refresh (⌘R) to pass Chrome Keychain gating.
  • Optional overrides: MINIMAX_TOKEN_PLAN_CREDIT_URL, plus existing MINIMAX_HOST / remains / coding-plan overrides.
  • Menu Usage Dashboard and Settings Open Token Plan intentionally open different console pages.
  • Docs: docs/minimax.md
  • Screenshots also committed under docs/screenshots/minimax-usage/ for stable PR references.

MiniMax API remains responses omit the console recharge-credit balance.
Fetch it from token_plan_credit when a browser session cookie is available,
including API-token refreshes that also have cached or manual cookies.

Co-authored-by: Cursor <cursoragent@cursor.com>
@clawsweeper

clawsweeper Bot commented Jul 1, 2026

Copy link
Copy Markdown

Codex review: needs changes before merge. Reviewed July 5, 2026, 3:10 PM ET / 19:10 UTC.

Summary
The branch adds MiniMax web-session recharge-credit and usage-summary enrichment, menu/dashboard UI, utilization history, docs/screenshots, and package output-path validation.

Reproducibility: yes. for the PR blockers: source inspection at the current head shows the same failing guards/cache keys and Keychain path without needing live MiniMax credentials. I did not run live provider probes because repository policy avoids checks that can trigger Keychain prompts.

Review metrics: 3 noteworthy metrics.

  • Patch size: 103 files, +6924/-288. The PR spans provider auth, menu UI, package scripts, localization, docs, screenshots, and tests, so merge risk is not limited to one parser.
  • Blocking findings: 4 P2 findings still present. All four are concrete source-level regressions or user-visible failures that should be fixed before merge.
  • Security-sensitive surfaces: 2 touched areas. MiniMax desktop/web cookies and Keychain access are changed, and package output path validation is also modified.

Merge readiness
Overall: 🦐 gold shrimp
Proof: 🦞 diamond lobster
Patch quality: 🦐 gold shrimp
Result: needs maintainer review before merge.

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

Rank-up moves:

  • [P2] Fix the four review findings and add focused regression coverage for each.
  • [P2] Run make check or the focused MiniMax/menu test filters after the repair.

Risk before merge

  • [P1] Merging as-is can bypass the user's Keychain access opt-out when MiniMax Agent stores encrypted cookies.
  • [P1] MiniMax users can be left without an in-menu recovery path when usage-summary data is missing but a points balance is present.
  • [P1] The dashboard can show stale latest-token data when MiniMax daily_token_usage has advanced before date_model_usage catches up.
  • [P1] Merged menus can reuse an Overview-measured width for a provider menu with contextual actions and clip rows on first switch.

Maintainer options:

  1. Fix the remaining MiniMax blockers before merge (recommended)
    Repair the Keychain opt-out bypass, usage-summary recovery guard, daily-only latest-token fallback, and merged width cache key before this branch lands.
  2. Pause the feature until auth/session ownership reviews it
    If maintainers are not comfortable with the desktop-cookie and web-session enrichment path yet, hold this PR until the MiniMax auth/session contract is narrowed.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Fix the remaining PR 1821 blockers on the PR branch: honor KeychainAccessGate.isDisabled before MiniMax Agent encrypted-cookie decryption, show MiniMax web-session recovery when usageSummary is missing even if pointsBalance exists, prefer dailyTokenUsage.last when last_update_time's date lacks a date_model_usage row, and include overview/provider contextual-action state in merged menu width caching. Add focused regression tests for each repaired behavior and run make check or the relevant focused Swift test filters.

Next step before merge

  • [P2] The remaining action is a bounded mechanical repair on the PR branch, not a product decision.

Security
Needs attention: The diff still has a concrete Keychain boundary issue in the MiniMax Agent cookie importer.

Review findings

  • [P2] Honor the Keychain opt-out before Agent decryption — Sources/CodexBarCore/Providers/MiniMax/MiniMaxDesktopCookieImporter.swift:88
  • [P2] Show recovery when token usage is missing — Sources/CodexBar/StatusItemController+MiniMaxUsageSummarySection.swift:36-38
  • [P2] Prefer daily usage when the update-day row is absent — Sources/CodexBarCore/Providers/MiniMax/MiniMaxUsageSummary.swift:28-32
Review details

Best possible solution:

Land the MiniMax dashboard after the four mechanical blockers are fixed with focused regression coverage for Keychain gating, recovery actions, daily-only usage, and merged-menu width caching.

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

Yes for the PR blockers: source inspection at the current head shows the same failing guards/cache keys and Keychain path without needing live MiniMax credentials. I did not run live provider probes because repository policy avoids checks that can trigger Keychain prompts.

Is this the best way to solve the issue?

No: the feature direction is useful and well-proven, but the current implementation is not the narrowest safe merge until the four mechanical blockers are repaired. The safer path is to keep the enrichment feature but gate Keychain reads, show recovery correctly, prefer fresh daily data, and key width caching by menu context.

Full review comments:

  • [P2] Honor the Keychain opt-out before Agent decryption — Sources/CodexBarCore/Providers/MiniMax/MiniMaxDesktopCookieImporter.swift:88
    Still unresolved from the prior review: encrypted MiniMax Agent cookies call derivedKeys() here, which reaches KeychainSecurity.copyMatching, even when KeychainAccessGate.isDisabled is true. Users who disabled Keychain access can still hit a SecItem read during availability/API enrichment, so skip Agent import or return no decryption keys while the gate is disabled.
    Confidence: 0.93
  • [P2] Show recovery when token usage is missing — Sources/CodexBar/StatusItemController+MiniMaxUsageSummarySection.swift:36-38
    Still unresolved from the prior review: this guard only adds recovery actions when both usageSummary and pointsBalance are nil. An API-key user can have pointsBalance from remains while the web usage-summary cookie is expired or unavailable, leaving the menu without Token usage details and without the re-import/login actions needed to repair the web session.
    Confidence: 0.91
  • [P2] Prefer daily usage when the update-day row is absent — Sources/CodexBarCore/Providers/MiniMax/MiniMaxUsageSummary.swift:28-32
    Still unresolved from the prior review: when last_update_time points to a newer daily_token_usage value but date_model_usage has not emitted that date yet, snapshotDay falls back to latestDay; then latestSnapshotTokens returns yesterday's positive total before it can use dailyTokenUsage.last. The main card can therefore show stale latest-token usage.
    Confidence: 0.9
  • [P2] Include overview state in the merged width cache — Sources/CodexBar/StatusItemController+MenuWidthCache.swift:12-17
    Still unresolved from the prior review: the merged width cache key ignores whether the width was measured from Overview or a provider menu. Opening Overview first can cache a width without the selected provider's contextual actions, then switching to that provider can reuse a too-small width and clip rows.
    Confidence: 0.89

Overall correctness: patch is incorrect
Overall confidence: 0.92

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 8e9a844dbd36.

Label changes

Label justifications:

  • P2: This is a substantial MiniMax provider improvement with limited blast radius, but four normal-priority merge blockers remain.
  • merge-risk: 🚨 auth-provider: The diff changes MiniMax cookie-session enrichment and recovery behavior, and one blocker hides recovery for stale or missing web usage data.
  • merge-risk: 🚨 security-boundary: The diff can still read Keychain-backed MiniMax Agent decryption material despite the user's Keychain access opt-out.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): The PR body includes live MiniMax UI screenshots and redacted CLI/endpoint output showing after-fix credit and usage-summary behavior, so contributor proof is sufficient even though source blockers remain.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes live MiniMax UI screenshots and redacted CLI/endpoint output showing after-fix credit and usage-summary behavior, so contributor proof is sufficient even though source blockers remain.
Evidence reviewed

Security concerns:

  • [medium] MiniMax Agent cookie import bypasses Keychain opt-out — Sources/CodexBarCore/Providers/MiniMax/MiniMaxDesktopCookieImporter.swift:88
    Encrypted desktop-cookie rows trigger KeychainSecurity.copyMatching through derivedKeys() without first checking KeychainAccessGate.isDisabled, so the user/admin Keychain access opt-out is not consistently enforced.
    Confidence: 0.93

Acceptance criteria:

  • [P1] swift test --filter MiniMaxDesktopCookieImporterTests.
  • [P1] swift test --filter MiniMaxUsageSummaryTests.
  • [P1] swift test --filter StatusMenu.
  • [P1] make check.

What I checked:

Likely related people:

  • Yuxin-Qiao: Authored prior merged MiniMax token-plan display work and is tied to the current MiniMax recharge/usage-dashboard surface. (role: recent MiniMax contributor; confidence: high; commits: d00c6c0f523d, 645ca833df31; files: Sources/CodexBarCore/Providers/MiniMax/MiniMaxUsageFetcher.swift, Sources/CodexBar/InlineUsageDashboardContent.swift)
  • steipete: Introduced the MiniMax provider and recently worked on merged menu width behavior, both central to the remaining blockers. (role: feature introducer and recent adjacent owner; confidence: high; commits: 17cdc54b26fa, 0e0102c30fe6; files: Sources/CodexBarCore/Providers/MiniMax/MiniMaxUsageFetcher.swift, Sources/CodexBar/StatusItemController+MenuWidthCache.swift)
  • XWind: Contributed the MiniMax token-plan quota path that this PR extends with recharge credit and usage-summary enrichment. (role: MiniMax token-plan area contributor; confidence: medium; commits: 65a41cbee9b3, 90368202df70; files: Sources/CodexBarCore/Providers/MiniMax/MiniMaxUsageFetcher.swift, Sources/CodexBarCore/Providers/MiniMax/MiniMaxUsageSnapshot.swift)
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.
Review history (11 earlier review cycles; latest 8 shown)
  • reviewed 2026-07-05T15:22:15.866Z sha 50bbe01 :: found issues before merge. :: [P1] Verify web sessions before merging API usage | [P2] Classify login-only summaries as expired credentials | [P2] Let longer hourly reset windows use their own cap | [P2] Use the sampled snapshot when gating MiniMax history | [P2] Anchor daily-only summaries without the machine year
  • reviewed 2026-07-05T15:53:14.797Z sha 048f9b6 :: needs changes before merge. :: [P1] Verify web sessions before accepting API enrichment | [P2] Map login-only summaries to invalid credentials | [P2] Check specific hourly windows before the generic hour cap | [P2] Gate MiniMax history on the sampled snapshot | [P2] Anchor daily-only summaries without the machine year | [P2] Prefer the dedicated credit endpoint balance
  • reviewed 2026-07-05T16:04:31.390Z sha 048f9b6 :: needs changes before merge. :: [P1] Verify web sessions before accepting API enrichment | [P2] Map login-only summaries to invalid credentials | [P2] Check specific hourly windows before the generic hour cap | [P2] Gate MiniMax history on the sampled snapshot | [P2] Anchor daily-only summaries without the machine year | [P2] Prefer the dedicated credit endpoint balance
  • reviewed 2026-07-05T16:23:50.436Z sha ec7ae80 :: needs changes before merge. :: [P1] Require account validation before accepting web enrichment | [P2] Map login-only summaries to invalid credentials | [P2] Check parsed hourly windows before the generic hour cap | [P2] Gate MiniMax history on the sampled snapshot | [P2] Anchor daily-only summaries without the machine year | [P2] Prefer the dedicated credit endpoint balance
  • reviewed 2026-07-05T16:40:19.461Z sha 7c3f534 :: needs changes before merge. :: [P2] Use the dedicated credit result after fetching it | [P2] Honor the Keychain opt-out for Agent cookies | [P2] Show recovery when token usage is missing | [P2] Prefer daily usage when model rows lag
  • reviewed 2026-07-05T16:50:49.688Z sha 93ede2a :: needs changes before merge. :: [P2] Use the dedicated credit result after fetching it | [P2] Honor the Keychain opt-out for Agent cookies | [P2] Show recovery when token usage is missing | [P2] Prefer daily usage when model rows lag | [P2] Remove the duplicate SwiftLint disable
  • reviewed 2026-07-05T17:17:27.197Z sha bfdcce8 :: needs changes before merge. :: [P2] Honor the Keychain opt-out before Agent decryption | [P2] Show recovery when token usage is missing | [P2] Prefer daily usage when the update-day row is absent | [P2] Include overview state in the merged width cache
  • reviewed 2026-07-05T17:23:43.779Z sha 5d1661d :: needs changes before merge. :: [P2] Honor the Keychain opt-out before Agent decryption | [P2] Show recovery when token usage is missing | [P2] Prefer daily usage when the update-day row is absent | [P2] Include overview state in the merged width cache

@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. P2 Normal priority bug or improvement with limited blast radius. labels Jul 1, 2026

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

Copy link
Copy Markdown

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: 88dfac6c95

ℹ️ 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".

usage = await MiniMaxUsageFetcher.attachingTokenPlanCreditIfAvailable(
to: usage,
context: fetchContext,
groupID: MiniMaxCookieHeader.override(from: cookieHeader)?.groupID)

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 Preserve MiniMax group IDs from cookie overrides

When the configured cookie value is a curl command whose group is only present as x-group-id or a GroupId URL parameter, resolveCookieHeader has already stripped the raw value down to just the Cookie header before this re-parse runs. That drops the group ID even though MiniMaxCookieHeader.override supports extracting it, so the token_plan_credit request omits x-group-id and can fetch no balance or the wrong group balance for multi-group accounts; carry the original MiniMaxCookieOverride through this path instead.

Useful? React with 👍 / 👎.

return MiniMaxCookieHeader.override(from: raw)?.cookieHeader
}
#if os(macOS)
return CookieHeaderCache.load(provider: .minimax)?.cookieHeader

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 Avoid merging cached cookies into unrelated API results

When a user has a MiniMax API key for one account but the cached browser cookie belongs to another, this automatic cache fallback supplies that cookie to the API strategy and the new enrichment attaches the cookie account's pointsBalance to the API-key quota. The cache entry is not compared with any account or group in the API response, so this can render and export a balance for a different account; require an explicit cookie for API enrichment or verify the account before merging.

Useful? React with 👍 / 👎.

let fetchContext = MiniMaxUsageFetcher.WebFetchContext(
cookie: cookie,
authorizationToken: nil,
region: region,

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 Use the region that actually served the API quota

For API-key users who leave the region at the default, fetchUsage(apiToken:region:) first tries global and then silently retries China when the global host rejects the key (see the existing retries china host when global rejects token coverage). If that China retry succeeds, this enrichment context still uses the original .global region, so the balance request goes to www.minimax.io instead of www.minimaxi.com and misses the cookie-authenticated credit balance for those existing China-region accounts.

Useful? React with 👍 / 👎.

Comment on lines +58 to +60
if let host = MiniMaxSettingsReader.hostOverride(environment: environment),
let hostURL = URL(string: "https://\(host)")?
.appendingPathComponent("backend/account/token_plan_credit")

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 Keep credit fetches on the web host under host overrides

When users set the documented general override such as MINIMAX_HOST=platform.minimaxi.com (or an API host), this branch rewrites the new credit endpoint to https://platform.minimaxi.com/backend/account/token_plan_credit. The endpoint added in this patch defaults to the www.minimaxi.com/www.minimax.io web hosts, so these valid existing host-override setups silently lose the recharge balance after the 404 is swallowed; either keep the default web host for this endpoint or require the specific MINIMAX_TOKEN_PLAN_CREDIT_URL override for proxies.

Useful? React with 👍 / 👎.

Propagate cancellation from token-plan credit enrichment, keep credit
fetches on www hosts under MINIMAX_HOST overrides, use the API region
that actually served quota, preserve curl group IDs, and only merge
explicit cookies into API refreshes. Fix released changelog structure and
expand regression tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
@Yuxin-Qiao

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Addressed the review items in 972cffa:

  1. CancellationattachingTokenPlanCreditIfAvailable now rethrows CancellationError / URLError.cancelled like subscription metadata enrichment.
  2. Changelog — removed the duplicate ### Fixed heading inside released 0.37.3; moved the misplaced Added bullets back under ### Added.
  3. Codex P2s — API enrichment now carries the full MiniMaxCookieOverride (curl x-group-id), uses fetchAPITokenUsage(...).resolvedRegion after global→China retry, skips cached browser cookies on the API path, and keeps credit fetches on www.* unless MINIMAX_TOKEN_PLAN_CREDIT_URL is set.

Proof: API-only diagnose from the built PR CLI is attached in the updated PR body. Full recharge-balance proof still needs an explicit MiniMax cookie on the contributor account (manual settings or MINIMAX_COOKIE); I can add a redacted menu/diagnose screenshot once that cookie is configured.

@clawsweeper

clawsweeper Bot commented Jul 1, 2026

Copy link
Copy Markdown

🦞🧹
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.

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

Copy link
Copy Markdown

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: 972cffac68

ℹ️ 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".

if let override = MiniMaxSettingsReader.tokenPlanCreditURL(environment: environment) {
return override
}
return region.tokenPlanCreditURL

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 Respect host override when choosing credit region

When MiniMax is configured only through the documented MINIMAX_HOST=platform.minimaxi.com env override and no persisted region, quota/billing requests resolve to the China host, but this fallback ignores that override and still sends the new credit lookup to region.tokenPlanCreditURL (defaulting to www.minimax.io). Fresh evidence after the prior host-override comment is that the updated resolver now avoids the platform host but still uses the global web host for China MINIMAX_HOST setups, so those existing env-based users silently lose pointsBalance unless they also know to set MINIMAX_TOKEN_PLAN_CREDIT_URL.

Useful? React with 👍 / 👎.

Co-authored-by: Cursor <cursoragent@cursor.com>
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. merge-risk: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. labels Jul 1, 2026
Yuxin-Qiao and others added 2 commits July 2, 2026 01:16
Co-authored-by: Cursor <cursoragent@cursor.com>
No code changes; prior macOS test shards were cancelled by cancel-in-progress from rapid pushes.

Co-authored-by: Cursor <cursoragent@cursor.com>

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

Copy link
Copy Markdown

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: 8d40b54e3c

ℹ️ 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".

let resolved = MiniMaxAPIRegion(rawValue: region),
self.settings.minimaxAPIRegion != resolved
else { return }
self.settings.minimaxAPIRegion = resolved

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 Avoid persisting detected MiniMax region across accounts

When a selected MiniMax token account only succeeds after the global→China retry, this writes .cn into the provider-wide setting. That setting is then reused for other MiniMax token accounts, and fetchAPITokenUsage does not try the global host when the preferred region is already .cn, so any configured global account can start failing on later refreshes until the user manually changes the shared region back. Keep the auto-detected region scoped to the current account/fetch, or only persist it when there are no token accounts to mix.

Useful? React with 👍 / 👎.

Route credit lookups from MINIMAX_HOST, fall back to env cookies when manual settings are empty, and relax the gated live balance assertion.

Co-authored-by: Cursor <cursoragent@cursor.com>
@Yuxin-Qiao

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Addressed the open findings in 227ed49:

  • P2 host routing: now selects for (and matching origin headers).
  • P1 live proof: redacted API+cookie / output added to the PR body (, ).
  • P3 live test: no longer hard-codes ; asserts non-negative balance with optional .
  • Cookie fallback: empty manual cookie settings now fall back to / env on both API and web paths.

@clawsweeper

clawsweeper Bot commented Jul 1, 2026

Copy link
Copy Markdown

🦞🧹
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.

Yuxin-Qiao and others added 2 commits July 2, 2026 01:55
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
@clawsweeper clawsweeper Bot added proof: sufficient Contributor real behavior proof is sufficient. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 1, 2026

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

Copy link
Copy Markdown

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: 6c49ef2925

ℹ️ 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 +340 to +344
var providerConfig = config.providerConfig(for: provider) ?? ProviderConfig(id: provider)
guard providerConfig.region != trimmed else { return }
providerConfig.region = trimmed
config.setProviderConfig(providerConfig)
try store.save(config)

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 Avoid persisting region from env-only CLI probes

When codexbar usage/diagnose is run with only a temporary MINIMAX_CODING_API_KEY in the environment and the global request falls back to China, this CLI updater creates or updates the persisted MiniMax provider config and saves region = cn. This separate CLI path means a one-shot env probe changes later app/CLI refreshes, and because fetchAPITokenUsage does not try global once the preferred region is .cn, a subsequent global key can fail until the user manually resets the setting; skip this updater for env-backed credentials or scope it to a stored MiniMax config.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. label Jul 1, 2026
@Yuxin-Qiao

Copy link
Copy Markdown
Contributor Author

@codex review
@clawsweeper re-review

Addressed the remaining MiniMax region findings in 30cf613a:

  • removed provider-wide persistence of the detected fallback region from app refresh, token-account refresh, CLI usage, and diagnose
  • kept resolvedRegion scoped to the current API fetch and its cookie credit enrichment
  • removed the persistence-only callback plumbing and test

This prevents env-only probes and mixed global/China credentials from changing later routing. SwiftFormat and git diff --check pass. Focused local Swift tests were attempted, but this environment blocks SwiftPM with nested sandbox-exec: sandbox_apply: Operation not permitted; GitHub CI is the authoritative run.

@clawsweeper

clawsweeper Bot commented Jul 2, 2026

Copy link
Copy Markdown

🦞🧹
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.

@clawsweeper clawsweeper Bot added proof: sufficient Contributor real behavior proof is sufficient. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. merge-risk: 🚨 auth-provider 🚨 Merging this PR could break OAuth, tokens, provider routing, model choice, or credentials. labels Jul 5, 2026
Co-authored-by: Cursor <cursoragent@cursor.com>
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. label Jul 5, 2026
Co-authored-by: Cursor <cursoragent@cursor.com>

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

Copy link
Copy Markdown

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: b2bc5da376

ℹ️ 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 +69 to +70
let resolvedBalance = self.pointsBalance ?? pointsBalance
let resolvedExpiry = self.pointsBalanceExpiresAt ?? expiresAt

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 Use the fetched MiniMax credit balance

When the remains response already contains pointsBalance but token_plan_credit returns a different remaining_credits, this helper keeps self.pointsBalance because of self.pointsBalance ?? pointsBalance, so the Credits card can continue showing the older/general balance while only the expiry metadata updates. Fresh evidence after the earlier guard fix is that the credit request now runs, but its balance is still discarded here whenever any balance was parsed earlier.

Useful? React with 👍 / 👎.

Comment thread Scripts/package_app.sh
Comment on lines +238 to +239
APP_FINAL="${CODEXBAR_PACKAGE_OUTPUT:-$ROOT/CodexBar.app}"
APP_STAGE="${CODEXBAR_PACKAGE_STAGE:-$ROOT/.build/package/CodexBar.app}"

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 Reject identical package stage and output paths

If a caller sets only CODEXBAR_PACKAGE_OUTPUT to the default stage path (or otherwise makes these two variables resolve to the same .app), the script builds into APP_STAGE and then the existing finalization step runs rm -rf "$APP_FINAL" before mv "$APP" "$APP_FINAL", deleting the just-built bundle and causing packaging to fail. The new validation should reject identical resolved paths or always stage in a separate temporary bundle.

Useful? React with 👍 / 👎.

Comment on lines +339 to +341
if provider == .minimax {
return MenuBarMetricWindowResolver.nearestResetWindow(snapshot: snapshot)
?? self.menuBarMetricWindow(for: provider, snapshot: snapshot)

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 Honor MiniMax reset-time metric preference

When MiniMax is in menu-bar reset-time mode and the user selected the weekly/secondary metric, this branch ignores that preference and always chooses the soonest reset across all MiniMax lanes; normal accounts with both 5-hour and weekly quotas therefore keep showing and scheduling refreshes for the 5-hour reset instead of the selected weekly reset. Keep the nearest-reset behavior to the automatic case or fall back to menuBarMetricWindow when a specific lane is selected.

Useful? React with 👍 / 👎.

Comment on lines +10 to +14
private static let webCookieHosts: Set<String> = [
"www.minimaxi.com",
"www.minimax.io",
"platform.minimaxi.com",
"platform.minimax.io",

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 Accept parent-domain MiniMax Agent cookies

If the MiniMax Agent stores its session cookie on the parent domain (.minimax.io or .minimaxi.com), which is valid for the www/platform endpoints and is already included by the browser-cookie importer, this allow-list drops it because only exact subdomains are accepted. In that common cookie shape the new Agent import path returns no usable session even though the cookie would be sent by the browser; include the parent domains while still excluding Agent-only hosts.

Useful? React with 👍 / 👎.

Yuxin-Qiao and others added 4 commits July 5, 2026 23:40
Keep MiniMax sampling helpers file-local, restore private plan utilization sampling, and split non-macOS API enrichment.

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
@clawsweeper clawsweeper Bot removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. proof: sufficient Contributor real behavior proof is sufficient. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jul 5, 2026
Yuxin-Qiao and others added 2 commits July 5, 2026 23:48
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>

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

Copy link
Copy Markdown

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: 048f9b6970

ℹ️ 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 +36 to +37
usage.usageSummary == nil,
usage.pointsBalance == nil,

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 Offer recovery when MiniMax token details are missing

When an API-key MiniMax refresh gets points_balance from token-plan remains but the web usage_summary cookie is expired or unavailable, this guard returns before adding the recovery items because pointsBalance is non-nil. That leaves the menu without Token usage details and without the re-import/login actions needed to repair the web session; gate on all required web data being present, or at least on usageSummary for this token-details recovery path, instead of requiring both fields to be nil.

Useful? React with 👍 / 👎.

Comment on lines +14 to +16
"version=\(self.menuSession.contentVersion)",
"providers=\(providers.map(\.rawValue).joined(separator: ","))",
"locale=\(self.menuLocalizationSignature())",

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 overview state in the merged width cache

When a merged menu is first opened on Overview, menuCardWidth is called with the overview descriptor, where the selected provider's contextual actions are intentionally omitted, but this cache key is reused later when switching to that provider with its full action section. If that provider has the widest action text, the cached width is too small and the first provider switch can render clipped/narrow rows; include the selected/overview descriptor state in the key or measure all providers with the same contextual-action mode before caching.

Useful? React with 👍 / 👎.

if let day = self.days.first(where: { $0.date == self.snapshotDateKey }) {
return day
}
return self.latestDay

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 Prefer daily MiniMax usage for a missing update day

When last_update_time points to the latest daily_token_usage value but date_model_usage has not yet emitted a row for that date, this fallback returns the previous model day. latestSnapshotTokens then uses that stale positive day total before it can fall back to dailyTokenUsage.last, so the main card shows yesterday's tokens as the latest usage; only fall back to latestDay when there is no daily value for the snapshot date.

Useful? React with 👍 / 👎.

KeychainNoUIQuery.apply(to: &query)

var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)

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 Honor the Keychain opt-out for MiniMax Agent cookies

When Keychain access is disabled (for example via Advanced settings or CODEXBAR_DISABLE_KEYCHAIN_ACCESS) and the MiniMax Agent cookie DB stores encrypted values, this path still reaches SecItemCopyMatching. Browser cookie imports are gated on KeychainAccessGate.isDisabled, so the new Agent importer bypasses the same opt-out during availability checks/API enrichment; return no decryption keys or skip the Agent import while the gate is disabled.

Useful? React with 👍 / 👎.

Yuxin-Qiao and others added 8 commits July 6, 2026 00:19
Co-authored-by: Cursor <cursoragent@cursor.com>
Verify credit group IDs before merging API web enrichment, map login-only
usage summaries to invalid credentials, anchor daily-only years from the
reference date, prefer dedicated credit balances, gate plan history on the
sampled snapshot, honor explicit reset-metric preferences, accept parent-
domain Agent cookies, and reject identical package output/stage paths.

Co-authored-by: Yuxin Qiao <Yuxin-Qiao@users.noreply.github.com>
Co-authored-by: Yuxin Qiao <Yuxin-Qiao@users.noreply.github.com>
Co-authored-by: Yuxin Qiao <Yuxin-Qiao@users.noreply.github.com>
Co-authored-by: Yuxin Qiao <Yuxin-Qiao@users.noreply.github.com>
Co-authored-by: Yuxin Qiao <Yuxin-Qiao@users.noreply.github.com>
Co-authored-by: Yuxin Qiao <Yuxin-Qiao@users.noreply.github.com>
Co-authored-by: Yuxin Qiao <Yuxin-Qiao@users.noreply.github.com>
@Yuxin-Qiao

Copy link
Copy Markdown
Contributor Author

Closing in favor of a 3-PR feature split for easier review:

  1. MiniMax: Token Plan recharge credits and web session enrichment #1981 — Token Plan recharge credits + web session enrichment
  2. MiniMax: usage summary dashboard UI #1982 — Usage summary dashboard UI (merge after MiniMax: Token Plan recharge credits and web session enrichment #1981)
  3. MiniMax: quota utilization history and reset-time display #1983 — Quota utilization history + reset-time display (merge after MiniMax: Token Plan recharge credits and web session enrichment #1981)

Original branch: feat/minimax-token-plan-credit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 auth-provider 🚨 Merging this PR could break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. P2 Normal priority bug or improvement with limited blast radius. proof: sufficient Contributor real behavior proof is sufficient. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants