Skip to content

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

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

MiniMax: recharge credits, usage dashboard, and quota utilization#1821
Yuxin-Qiao wants to merge 37 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 3, 2026, 2:12 PM ET / 18:12 UTC.

Summary
This PR adds MiniMax token-plan credit and usage-summary enrichment, dashboard/submenu UI, utilization history, Agent/browser/manual cookie handling, docs, screenshots, localization, tests, and package script output/stage overrides.

Reproducibility: yes. for the review findings: source inspection shows the API enrichment path calls a candidate chain that omits MiniMax Agent cookies and reads saved manual cookies without checking cookieSource; the package script deletion risk is also visible directly in the changed shell lines.

Review metrics: 2 noteworthy metrics.

  • Diff size: 99 files, +6097/-288. The branch spans provider fetching, menu UI, localization, docs, tests, screenshots, and packaging, so source-level review matters beyond green checks.
  • Release script touched: 1 package script changed. The package script change introduces deletion behavior that normal MiniMax parser/UI tests will not cover.

Merge readiness
Overall: 🧂 unranked krab
Proof: 🦞 diamond lobster
Patch quality: 🧂 unranked krab
Result: blocked by patch quality or review findings.

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

Rank-up moves:

  • [P2] Fix the MiniMax API enrichment candidate/source-order bugs and add focused resolver tests.
  • Guard or remove the package output/stage env overrides before any recursive delete.
  • [P2] Add MiniMax Agent cookie importer coverage for encrypted cookie rows or explicitly document and test the fallback behavior.

Risk before merge

  • [P1] API-token MiniMax users with a logged-in MiniMax Agent session but no manual or cached browser cookie still miss the advertised automatic credit and usage-summary enrichment.
  • [P1] A saved manual MiniMax cookie can still be used during API-token enrichment after the user switches the cookie source away from Manual, so stale web-session data can be attached to an API-token quota result.
  • [P1] The package script now allows environment-controlled final/stage paths to reach rm -rf, so a mis-set package environment can delete an arbitrary local path when packaging runs.

Maintainer options:

  1. Fix the blockers before merge (recommended)
    Repair the MiniMax API enrichment candidate chain, honor the selected cookie source, handle Agent cookie import reliably, and guard package deletion paths before landing.
  2. Split packaging changes out
    If the package output/stage overrides are not needed for the MiniMax feature, remove them from this branch and review that release-script behavior separately.
  3. Pause for owner review
    If maintainers want to accept the broader cookie-source or packaging behavior intentionally, pause automated repair and get explicit provider/release-script owner sign-off.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Repair the MiniMax API-enrichment candidate chain so it includes MiniMax Agent desktop cookies, honors `cookieSource` before using saved manual cookies, handles encrypted Agent cookie values or explicitly falls back, and validates/restricts `CODEXBAR_PACKAGE_OUTPUT` and `CODEXBAR_PACKAGE_STAGE` before any `rm -rf`; add focused resolver/importer/package tests and run `make check` plus MiniMax-focused Swift tests.

Next step before merge

  • The remaining blockers are narrow, source-confirmed, and repairable on the PR branch with focused tests; maintainer product review can happen after the branch is technically safe.

Security
Needs attention: The diff has concrete cookie-source and package-script safety concerns that should be fixed before merge.

Review findings

  • [P1] Honor the selected MiniMax cookie source — Sources/CodexBarCore/Providers/MiniMax/MiniMaxWebEnrichmentResolver.swift:45-48
  • [P1] Constrain package paths before deleting them — Scripts/package_app.sh:186-189
  • [P2] Try MiniMax Agent cookies for API enrichment — Sources/CodexBarCore/Providers/MiniMax/MiniMaxWebEnrichmentResolver.swift:34-38
Review details

Best possible solution:

Fix the remaining source-selection and packaging safeguards before merge, then land the MiniMax feature with focused resolver/importer/package tests and the existing live proof.

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

Yes for the review findings: source inspection shows the API enrichment path calls a candidate chain that omits MiniMax Agent cookies and reads saved manual cookies without checking cookieSource; the package script deletion risk is also visible directly in the changed shell lines.

Is this the best way to solve the issue?

No: the feature direction is useful, but the current implementation is not the narrowest maintainable solution until cookie-source precedence and package path deletion are made explicit and tested.

Full review comments:

  • [P1] Honor the selected MiniMax cookie source — Sources/CodexBarCore/Providers/MiniMax/MiniMaxWebEnrichmentResolver.swift:45-48
    explicitCandidates adds a saved manual cookie whenever the header is non-empty, even if the user has switched MiniMax cookie source back to Auto or Off. In the API-token enrichment path this stale manual cookie is tried before the selected cached/browser source, so a disabled cookie can attach another web session's credits or usage summary to the API quota result.
    Confidence: 0.93
  • [P1] Constrain package paths before deleting them — Scripts/package_app.sh:186-189
    These new environment overrides feed APP_STAGE and APP_FINAL, but the script later runs rm -rf on both paths without checking that they are inside an expected package/build directory and not a dangerous user path. A mis-set package environment can therefore delete arbitrary local directories during packaging; validate or remove the overrides before the delete/move steps.
    Confidence: 0.88
  • [P2] Try MiniMax Agent cookies for API enrichment — Sources/CodexBarCore/Providers/MiniMax/MiniMaxWebEnrichmentResolver.swift:34-38
    The API-token enrichment candidate chain only includes explicit and cached/browser cookies, while the MiniMax Agent desktop import is only added by the separate web-session candidate chain. API-key users with a logged-in MiniMax Agent session but no manual/cached browser cookie still get quota but miss the advertised automatic credits and usage-summary enrichment.
    Confidence: 0.91
  • [P2] Read encrypted MiniMax Agent cookie values — Sources/CodexBarCore/Providers/MiniMax/MiniMaxDesktopCookieImporter.swift:57-60
    The desktop cookie importer selects only the plaintext value column and drops rows whose value is empty. Chromium/Electron cookie stores often place secure cookie contents in encrypted_value, so logged-in Agent installs can be treated as having no usable _token and the new Agent-cookie path silently fails.
    Confidence: 0.76

Overall correctness: patch is incorrect
Overall confidence: 0.9

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 61ff93208255.

Label changes

Label changes:

  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦞 diamond lobster and patch quality is 🧂 unranked krab.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🧂 unranked krab, so this older rating label is no longer current.

Label justifications:

  • P2: This is a substantial provider improvement PR with limited blast radius, but it still has merge-blocking correctness and safety issues.
  • merge-risk: 🚨 compatibility: The PR changes MiniMax cookie-source behavior and package output/stage handling in ways that can break existing user or release workflows.
  • merge-risk: 🚨 auth-provider: The API-token enrichment path can still use the wrong MiniMax web-session source or omit the advertised Agent source.
  • merge-risk: 🚨 security-boundary: The patch touches cookies and local packaging deletion paths, and current source inspection shows concrete boundary/safety defects.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦞 diamond lobster and patch quality is 🧂 unranked krab.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): The PR body includes after-fix menu screenshots and redacted live CLI/endpoint output showing MiniMax credits and usage-summary data from a live Plus account.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes after-fix menu screenshots and redacted live CLI/endpoint output showing MiniMax credits and usage-summary data from a live Plus account.
Evidence reviewed

Security concerns:

  • [medium] Disabled manual cookie can still enrich API-token results — Sources/CodexBarCore/Providers/MiniMax/MiniMaxWebEnrichmentResolver.swift:45
    Ignoring cookieSource lets a saved but unselected manual MiniMax cookie participate in API-token enrichment, which can mix web-session credit or usage data from the wrong account into the selected API-token result.
    Confidence: 0.93
  • [high] Package env paths reach rm -rf without containment — Scripts/package_app.sh:186
    CODEXBAR_PACKAGE_OUTPUT and CODEXBAR_PACKAGE_STAGE can redirect paths that the script later deletes recursively, so package runs need a guard against empty, root, home, or otherwise unsafe paths.
    Confidence: 0.88

Acceptance criteria:

  • [P1] swift test --filter MiniMaxWebEnrichmentResolverTests.
  • [P1] swift test --filter MiniMaxProviderTests.
  • [P1] swift test --filter MiniMaxDesktopCookieImporterTests.
  • [P1] make check.

What I checked:

Likely related people:

  • Peter Steinberger: Recent current-main commits touch MiniMax provider registration, billing summaries, region retry behavior, provider cookie settings, and package script behavior. (role: recent area contributor; confidence: high; commits: 7ffad6b5a4bf, af202b462bdf, bdb213f0199f; files: Sources/CodexBarCore/Providers/MiniMax/MiniMaxUsageFetcher.swift, Sources/CodexBarCore/Providers/MiniMax/MiniMaxProviderDescriptor.swift, Sources/CodexBar/Providers/MiniMax/MiniMaxSettingsStore.swift)
  • XWind: Current-main MiniMax token-plan quota and API fallback behavior appears to date through several XWind commits in the central fetcher path. (role: MiniMax token-plan contributor; confidence: medium; commits: 20d2ebe991c1, bfff3dfe494a, 65a41cbee9b3; files: Sources/CodexBarCore/Providers/MiniMax/MiniMaxUsageFetcher.swift)
  • Yuxin-Qiao: The PR author also has prior merged current-main MiniMax token-plan display history, so they are relevant beyond proposing this branch. (role: recent MiniMax contributor; confidence: medium; commits: d00c6c0f523d; files: Sources/CodexBarCore/Providers/MiniMax/MiniMaxUsageFetcher.swift)
  • pickaxe: Recent package_app.sh history includes signing-path containment and stale build product fixes, which are adjacent to the package deletion/path override risk in this PR. (role: packaging adjacent contributor; confidence: medium; commits: cb934ffe57e1, 5bfba2b5079f; files: Scripts/package_app.sh)
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.

@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.

Rebase onto latest PR fixes, add expiry UX with validated cache reuse on API enrichment, and prebuild MiniMax merged-menu content after open to cut first-switch latency.

Co-authored-by: Cursor <cursoragent@cursor.com>
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Jul 3, 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: 21857510e4

ℹ️ 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 +351 to +353
if let status = payload.baseResp?.statusCode, status != 0 {
let message = payload.baseResp?.statusMessage ?? "status_code \(status)"
throw MiniMaxUsageError.apiError(message)

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 Map usage-summary login errors to invalid credentials

When usage_summary returns HTTP 200 with base_resp.status_code like 1004/"not login" for an expired cookie, this throws apiError instead of invalidCredentials. attemptWebEnrichment only sets rejectedCredentials for invalidCredentials, so if the credit endpoint is unavailable or 404 the expired cached/explicit web session is reported as endpointsUnavailable and the cache/re-import path is not triggered; map login/cookie status messages here the same way the credit parser does.

Useful? React with 👍 / 👎.

var components = DateComponents()
components.calendar = Calendar.current
components.timeZone = TimeZone.current
components.year = Calendar.current.component(.year, from: Date())

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 fetch year for daily-only summaries

When MiniMax omits date_model_usage and only provides daily_token_usage, last_update_time is just month/day, but this fills the year from the machine clock. Around New Year, e.g. viewing a 12-31 summary on January 1, 2027, the synthesized trend bars are dated December 2027 instead of December 2026; choose the fetch/snapshot year or nearest non-future date. Fresh evidence is that the updated anchoring still derives the year from Date() here.

Useful? React with 👍 / 👎.

Comment on lines +241 to +246
case .minimax:
guard let snapshot = self.snapshots[provider] else { return false }
return !self.planUtilizationSeriesSamples(
provider: provider,
snapshot: snapshot,
capturedAt: snapshot.updatedAt).isEmpty

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 passed MiniMax snapshot for history recording

When multiple MiniMax token accounts are refreshed, recordFetchedTokenAccountPlanUtilizationHistory passes each non-selected account's snapshot into recordPlanUtilizationHistorySample, but this guard decides whether to persist by looking at the provider-wide self.snapshots[.minimax] instead. If the selected/current snapshot is nil or lacks MiniMax quota lanes, valid samples for the other account are dropped, so its Subscription Utilization history never persists; base this check on the already-computed sample/snapshot being recorded.

Useful? React with 👍 / 👎.

Comment on lines +58 to +60
SELECT host_key, name, value
FROM cookies
WHERE host_key LIKE '%minimax%'

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 Read encrypted MiniMax Agent cookie values

When the MiniMax Agent/Electron cookie DB stores secure cookies in the Chromium encrypted_value column with value empty, this query never retrieves those bytes and the import loop drops the row as an empty value. That makes the new desktop-session path miss _token/session cookies for logged-in Agent installs that use encrypted cookie storage; select and decrypt encrypted_value like the other Chromium cookie importers, or fall back to browser import instead of treating the desktop DB as empty.

Useful? React with 👍 / 👎.

cursoragent and others added 3 commits July 3, 2026 12:39
Complete it/tr/id/pl catalogs after the session recovery strings landed in
en, and mirror the same keys in zh-Hant.

Co-authored-by: Yuxin Qiao <Yuxin-Qiao@users.noreply.github.com>
Resolve CHANGELOG, menu usage-history cluster, and widget package reference conflicts while keeping MiniMax usage-summary sections.

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: 143ac2e193

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

static func apiEnrichmentCandidates(context: ProviderFetchContext) -> [Candidate] {
var candidates = self.explicitCandidates(context: context)
#if os(macOS)
candidates.append(contentsOf: self.cachedAndBrowserCandidates(context: context))

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 Try MiniMax Agent cookies during API enrichment

When an API-token refresh succeeds, MiniMaxAPIFetchStrategy only asks apiEnrichmentCandidates for optional web data, but this candidate chain skips MiniMaxDesktopCookieImporter.importSession() even though the cookie-first web chain includes it. For users with a valid API key and a logged-in MiniMax Agent session but no manual cookie/cached browser import, quota data loads while pointsBalance and usage-summary enrichment stay unavailable despite the new automatic Agent source; add the desktop candidate here before the cached/browser candidates.

Useful? React with 👍 / 👎.


extension StatusMenuTests {
@Test
func `merged menu prewarms MiniMax content before first switch`() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Remove the duplicate MiniMax prewarm test

This test method is also declared in Tests/CodexBarTests/StatusMenuInstantOpenTests.swift with the same backticked name and no parameters, so the macOS test target hits an invalid redeclaration error before any tests can run. Rename or keep only one copy so swift test/make check can compile the suite.

Useful? React with 👍 / 👎.

Comment on lines +45 to +48
if let settings = context.settings?.minimax,
let header = settings.manualCookieHeader?.trimmingCharacters(in: .whitespacesAndNewlines),
!header.isEmpty,
let override = MiniMaxCookieHeader.override(from: header)

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 MiniMax cookie source for API enrichment

When a user switches MiniMax cookies back to Auto/Off after pasting a manual cookie, this still adds the stored manual header as the first API-enrichment candidate; unlike the web fetch path, it does not require cookieSource == .manual. If that stale cookie is still valid for another account, the usage-summary/credit data from it is attached to the API-token quota and the loop stops before trying the cached/browser session the user selected.

Useful? React with 👍 / 👎.

enrichedSnapshot = snapshot
}

guard includeBillingHistory else { return enrichedSnapshot }

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 Continue credit enrichment when billing history is off

When includeBillingHistory is false, this new guard returns before the usage-summary and token_plan_credit enrichment calls below, so the updated no-billing path never fetches pointsBalance/expiry or summary data even though only the billing-history request was meant to be skipped. Keep the billing-history fetch conditional, but let the later web enrichments run for valid cookie sessions.

Useful? React with 👍 / 👎.

cursoragent and others added 2 commits July 3, 2026 17:18
- Remove duplicate merged-menu prewarm test from StatusMenuInstantOpenTests
- Bundle provider-switcher perf timings into a struct for SwiftLint
- Extract menuUpdateContext helper to shorten populateMenu body

Co-authored-by: Yuxin Qiao <Yuxin-Qiao@users.noreply.github.com>
Co-authored-by: Yuxin Qiao <Yuxin-Qiao@users.noreply.github.com>
@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: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. 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. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. proof: sufficient Contributor real behavior proof is sufficient. 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. merge-risk: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. labels Jul 3, 2026
cursoragent and others added 2 commits July 3, 2026 17:34
Co-authored-by: Yuxin Qiao <Yuxin-Qiao@users.noreply.github.com>
Billing history toggles account/amount fetches only; token-plan credit and
usage-summary enrichment should still run when includeBillingHistory is false.

Co-authored-by: Yuxin Qiao <Yuxin-Qiao@users.noreply.github.com>
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 3, 2026
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: 🚨 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. P2 Normal priority bug or improvement with limited blast radius. proof: sufficient Contributor real behavior proof is sufficient. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. 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