Skip to content

Improve China Kimi/GLM routes: Coding Plan 5h, Kimi Monthly, clearer labels#2351

Open
Leehow wants to merge 4 commits into
steipete:mainfrom
Leehow:local/cn-route-ux
Open

Improve China Kimi/GLM routes: Coding Plan 5h, Kimi Monthly, clearer labels#2351
Leehow wants to merge 4 commits into
steipete:mainfrom
Leehow:local/cn-route-ux

Conversation

@Leehow

@Leehow Leehow commented Jul 20, 2026

Copy link
Copy Markdown

Summary

Helps users (especially China-region accounts) map the right product endpoints and see the quotas that actually matter:

  • Kimi Code vs Moonshot open platform: clearer names, settings copy, and docs so China open-platform balance (api.moonshot.cn) is not confused with Kimi Code subscription (api.kimi.com).
  • Kimi Monthly enrichment: Code API / CLI usage only returns weekly + rate limits; Monthly still needs a web kimi-auth session. Best-effort enrichment via env/manual cookie, Kimi Desktop Cookies DB, then browser import.
  • GLM / BigModel Coding Plan: auto-discover local keys (~/.coding-relay/glm-api-key, env aliases), parse level, show 5-hour TOKENS_LIMIT as primary, keep MCP TIME_LIMIT as an extra lane (not mislabeled as monthly coding quota).
  • Reset times (absolute style): date-only (Today / Tomorrow / month-day), no clock time.
  • Small packaging/build notes: optional CODEXBAR_SKIP_WIDGET=1 when full Xcode is unavailable; @Entry → manual EnvironmentKey for Command Line Tools builds.

Motivation

China users often hold:

Product Host What they care about
Kimi Code api.kimi.com Weekly + rate + Monthly membership
Moonshot open platform api.moonshot.cn Balance
GLM Coding Plan open.bigmodel.cn 5-hour token window

CodexBar already had the right APIs for several of these, but discovery, labeling, and window mapping made it easy to miss Monthly (Kimi) or to think GLM was broken when the key lived only in a local relay file.

Test plan

  • codexbar usage --provider kimi with Kimi Code CLI + signed-in Kimi Desktop → primary/secondary + Monthly (+ Code 7-day when present)
  • codexbar usage --provider zai with ~/.coding-relay/glm-api-key + region=bigmodel-cn → primary 5-hour, MCP in extras, plan max/level
  • Absolute reset style renders date-only (no hour:minute)
  • Manual UI pass: Settings → Providers for Kimi Code / Moonshot / z.ai / GLM labels and key fields
  • Full Xcode package + widget build (optional; CODEXBAR_SKIP_WIDGET=1 used in CLT-only environments)

Notes for reviewers

  • Local key paths are read-only discovery (same spirit as other file-based credential readers). Config/env still win first.
  • No secrets or machine-specific config are included.
  • Happy to split into smaller PRs if preferred (Kimi-only / Zai-only / reset display).

haoli added 4 commits July 19, 2026 22:36
Rename provider labels and settings copy so China routes map to the
correct product (moonshot.cn / bigmodel.cn), and allow packaging without
the widget when full Xcode is unavailable.
… keys.

Enrich Code CLI/API usage with GetSubscriptionStats via kimi-desktop
kimi-auth, format absolute reset times as dates only, and accept common
BigModel API key env aliases with a required key field in settings.
Discover ~/.coding-relay/glm-api-key, parse plan level, map TOKENS_LIMIT
5h to the main bar, and park MCP TIME_LIMIT as an extra lane so Coding
Plan is not misread as multi-window monthly quota.
Expand provider docs in English so China Coding Plan keys, local key files,
and Kimi Desktop membership enrichment are discoverable for contributors.

@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

let snapshot = try await KimiUsageFetcher.fetchCodeAPIUsage(
apiKey: apiKey,
baseURL: baseURL,
transport: self.transport)

P2 Badge Pass the manual Kimi cookie into API enrichment

For an Auto/API user with a configured Kimi Code API key and a manually pasted kimi-auth cookie, this successful API strategy never supplies context.settings or context.env to the enrichment call. The new helper therefore only sees ProcessInfo environment, Desktop, or browser cookies, while the configured manual cookie is only read by KimiCookieHeader.resolveCookieOverride(context:); the API result is accepted and Monthly is omitted instead of being enriched. Pass the resolved manual token/context into fetchCodeAPIUsage so this advertised authentication path works.

ℹ️ 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 +41 to +47
for relative in self.localAPIKeyRelativePaths {
let url = homeDirectory.appendingPathComponent(relative)
guard FileManager.default.isReadableFile(atPath: url.path),
let raw = try? String(contentsOf: url, encoding: .utf8),
let token = self.cleaned(raw.split(separator: "\n").first.map(String.init))
else { continue }
return token

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 Keep BigModel file keys off the global endpoint

When a user has the newly supported ~/.coding-relay/glm-api-key (or either other BigModel path) but has not explicitly changed the region, this returns that key while the provider still defaults to ZaiAPIRegion.global, so the next refresh sends a BigModel credential as a Bearer token to https://api.z.ai. The settings copy explicitly says these keys are not interchangeable; infer/select the China endpoint for these files or require the China region before returning them to avoid leaking the credential to the wrong service.

Useful? React with 👍 / 👎.

Comment on lines +86 to +88
#if os(macOS)
if let token = try? KimiCookieImporter.importSession().authToken {
return token

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 Kimi cookie-source opt-out during enrichment

This browser import now runs after every successful Code API/CLI refresh whenever no process-level token or Desktop token is found, even when the provider's cookie source is set to Off or the user selected API source. Since the helper has no fetch context, it bypasses the guard used by KimiWebFetchStrategy and can trigger browser/Keychain access despite the user's opt-out; thread the cookie-source setting into enrichment and skip Desktop/browser discovery when it is off.

Useful? React with 👍 / 👎.

Comment on lines +40 to +44
// Chrome/Electron may hold a write lock; copy to a temp file first.
let tempURL = FileManager.default.temporaryDirectory
.appendingPathComponent("codexbar-kimi-desktop-cookies-\(UUID().uuidString).db")
do {
try FileManager.default.copyItem(at: dbURL, to: tempURL)

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 Copy SQLite WAL state before querying Desktop cookies

When Kimi Desktop has its Chromium Cookies database open in WAL mode, recent cookie writes live in Cookies-wal rather than the main Cookies file. Copying only the main database and opening the isolated copy can therefore return a stale token or no kimi-auth row, so Desktop-only users miss the new monthly enrichment. Use SQLite's backup API or copy the WAL/SHM sidecars consistently before opening the temporary database.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 Urgent regression or broken agent/channel workflow affecting real users now. 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. labels Jul 20, 2026
@clawsweeper

clawsweeper Bot commented Jul 20, 2026

Copy link
Copy Markdown

Codex review: needs real behavior proof before merge. Reviewed July 20, 2026, 12:19 AM ET / 04:19 UTC.

Summary
The branch clarifies Kimi Code, Moonshot open-platform, and z.ai/GLM labels; adds Kimi Desktop and local BigModel credential discovery; changes quota presentation; and expands provider documentation.

Reproducibility: no. live high-confidence reproduction was run in this read-only review, but the failures are source-reproducible: a discovered BigModel file key lacks a region guard, and Kimi enrichment lacks the cookie-source policy input.

Review metrics: 2 noteworthy metrics.

  • Changed surface: 24 files affected; 478 added, 85 removed. The PR combines UI copy, package behavior, provider credential resolution, session access, quota mapping, widgets, and docs, so provider-specific regression coverage is important.
  • New credential fallbacks: 6 environment aliases and 3 home-relative key paths. The expanded discovery matrix makes endpoint selection and user-consent behavior merge-critical.

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🦪 silver shellfish
Result: blocked until real behavior proof is added.

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

Rank-up moves:

  • [P1] Fix the BigModel region guard, Kimi cookie-source propagation, and WAL-consistent Desktop cookie read.
  • [P2] Add focused XCTest coverage for each fallback and opt-out path.
  • [P1] Attach redacted live CLI output or logs showing the China key route, Kimi Monthly enrichment, and cookie-source Off behavior; private tokens and account details must be removed.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The PR body contains checklist assertions but no attached terminal output, recording, screenshot, redacted logs, or linked artifact demonstrating the after-fix provider behavior; add redacted live proof after fixing the findings, then update the body for re-review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Risk before merge

  • [P1] A BigModel credential discovered from the new home-directory paths may be transmitted to the global z.ai service when the user has not explicitly selected the China region.
  • [P1] Users who set Kimi cookie source to Off can still trigger Desktop/browser session discovery during API or CLI quota enrichment, undermining the setting and potentially causing unwanted credential-store access.
  • [P1] Kimi Desktop sessions stored in a live WAL-mode Chromium database may not be found reliably, so the promised Monthly enrichment can silently fail.

Maintainer options:

  1. Repair credential routing and consent handling (recommended)
    Keep the feature, but prevent BigModel file credentials from reaching the global endpoint, honor cookie-source Off during every enrichment path, and make the Desktop SQLite read WAL-consistent before merge.
  2. Pause and split the provider changes
    If the routing and session-policy changes cannot be verified promptly, land the label/docs-only work separately and revisit credential discovery with focused tests and proof.

Next step before merge

  • [P1] The code defects are concrete, but an external contributor must also provide real after-fix behavior proof from their Kimi/GLM setup before this PR can merge.

Security
Needs attention: The PR adds credential and session-discovery paths with a concrete wrong-endpoint disclosure risk and a cookie-consent bypass.

Review findings

  • [P1] Keep BigModel file keys off the global endpoint — Sources/CodexBarCore/Providers/Zai/ZaiSettingsReader.swift:35
  • [P1] Honor cookie-source Off during Kimi enrichment — Sources/CodexBarCore/Providers/Kimi/KimiUsageFetcher.swift:48
  • [P2] Read a WAL-consistent Kimi Desktop cookie snapshot — Sources/CodexBarCore/Providers/Kimi/KimiDesktopAuthToken.swift:44-46
Review details

Best possible solution:

Preserve the useful provider labeling and quota work, but gate BigModel local-file discovery on the China region or atomically infer that region, thread the Kimi cookie-source policy through enrichment, use a WAL-consistent SQLite snapshot, add focused tests, and provide redacted live CLI/provider evidence after the fixes.

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

No live high-confidence reproduction was run in this read-only review, but the failures are source-reproducible: a discovered BigModel file key lacks a region guard, and Kimi enrichment lacks the cookie-source policy input.

Is this the best way to solve the issue?

No. The overall direction is useful, but automatic credential/session discovery must preserve endpoint routing and explicit cookie-source consent before it is a maintainable solution.

Full review comments:

  • [P1] Keep BigModel file keys off the global endpoint — Sources/CodexBarCore/Providers/Zai/ZaiSettingsReader.swift:35
    apiToken returns keys from BigModel-specific files regardless of the selected region, while the default region remains global. A user with only ~/.coding-relay/glm-api-key can therefore send that credential to api.z.ai; require the China region or infer it atomically with the file fallback before returning the key.
    Confidence: 0.99
  • [P1] Honor cookie-source Off during Kimi enrichment — Sources/CodexBarCore/Providers/Kimi/KimiUsageFetcher.swift:48
    This enrichment resolves Desktop and browser sessions after API/CLI usage without the configured cookie-source policy. That bypasses a user's explicit Off setting and can trigger unwanted session discovery; pass the policy through and skip Desktop/browser lookup when it is off.
    Confidence: 0.97
  • [P2] Read a WAL-consistent Kimi Desktop cookie snapshot — Sources/CodexBarCore/Providers/Kimi/KimiDesktopAuthToken.swift:44-46
    Copying only the main Chromium Cookies file loses cookie writes that are still in Cookies-wal while Kimi Desktop is running. Use SQLite backup or consistently include the WAL/SHM sidecars so Desktop-only users can reliably receive Monthly enrichment.
    Confidence: 0.96

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Label changes

Label changes:

  • add P1: The new default credential-discovery path can expose an existing user's provider credential to the wrong service endpoint.
  • add merge-risk: 🚨 compatibility: Existing users with BigModel relay key files and the default global region can experience a broken or unsafe provider refresh after upgrade.
  • add merge-risk: 🚨 auth-provider: The diff changes API-key selection and can route a BigModel key through the global z.ai request path.
  • add merge-risk: 🚨 security-boundary: It introduces automatic local credential and browser/Desktop session discovery that can bypass a configured cookie opt-out.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body contains checklist assertions but no attached terminal output, recording, screenshot, redacted logs, or linked artifact demonstrating the after-fix provider behavior; add redacted live proof after fixing the findings, then update the body for re-review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Label justifications:

  • P1: The new default credential-discovery path can expose an existing user's provider credential to the wrong service endpoint.
  • merge-risk: 🚨 auth-provider: The diff changes API-key selection and can route a BigModel key through the global z.ai request path.
  • merge-risk: 🚨 security-boundary: It introduces automatic local credential and browser/Desktop session discovery that can bypass a configured cookie opt-out.
  • merge-risk: 🚨 compatibility: Existing users with BigModel relay key files and the default global region can experience a broken or unsafe provider refresh after upgrade.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body contains checklist assertions but no attached terminal output, recording, screenshot, redacted logs, or linked artifact demonstrating the after-fix provider behavior; add redacted live proof after fixing the findings, then update the body for re-review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed

Security concerns:

  • [high] BigModel file keys can reach the global z.ai endpoint — Sources/CodexBarCore/Providers/Zai/ZaiSettingsReader.swift:35
    Local paths specifically intended for BigModel are returned without a selected-region check, so a provider refresh can transmit a China-region credential to the global service.
    Confidence: 0.99
  • [medium] Kimi enrichment bypasses the cookie-source setting — Sources/CodexBarCore/Providers/Kimi/KimiUsageFetcher.swift:48
    API/CLI enrichment invokes Desktop and browser token resolution without the provider's cookie-source policy, allowing session discovery after the user selected Off.
    Confidence: 0.97

What I checked:

  • BigModel local-key routing: The new token resolver searches BigModel-specific local paths after environment variables without receiving or checking the selected ZaiAPIRegion; the provider still defaults to the global endpoint, so a discovered BigModel credential can be sent to api.z.ai. (Sources/CodexBarCore/Providers/Zai/ZaiSettingsReader.swift:35, 56e6225afb98)
  • Cookie-source opt-out bypass: The new API/CLI usage enrichment resolves Desktop and browser cookies internally without fetch context or the configured Kimi cookie-source policy, unlike the existing web fetch strategy guard. (Sources/CodexBarCore/Providers/Kimi/KimiUsageFetcher.swift:48, 56e6225afb98)
  • Desktop SQLite snapshot is incomplete: The new Desktop token reader copies only the primary Chromium Cookies database before querying it; active WAL-mode cookie writes can remain in the Cookies-wal sidecar, making the newly added enrichment stale or unavailable. (Sources/CodexBarCore/Providers/Kimi/KimiDesktopAuthToken.swift:44, 56e6225afb98)
  • Repository policy applied: The repository AGENTS.md specifically requires provider data to remain siloed, asks cookie imports to default Chrome-only where possible to avoid prompts, and requires focused provider/parser tests rather than live account probes. Those policies reinforce the routing and opt-out findings. (AGENTS.md:1, f8636cb37eb0)
  • Existing review coverage: Three review comments on the current head identify the same concrete BigModel routing, cookie opt-out, and WAL snapshot problems; no later commit in the supplied PR context addresses them. (56e6225afb98)

Likely related people:

  • steipete: Repository ownership is the only reliable current-main ownership signal available in the supplied context; this PR changes shared provider credential and usage behavior across Kimi and z.ai/GLM. (role: likely follow-up owner; confidence: low; files: Sources/CodexBarCore/Providers/Zai/ZaiSettingsReader.swift, Sources/CodexBarCore/Providers/Kimi/KimiUsageFetcher.swift, Sources/CodexBarCore/Providers/Kimi/KimiDesktopAuthToken.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.

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. P1 Urgent regression or broken agent/channel workflow affecting real users now. 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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant