Skip to content

feat(rate-limits): add hardened Z.AI Coding Plan usage - #18556

Closed
sjennings wants to merge 1 commit into
stablyai:mainfrom
sjennings:feat/zai-coding-plan-monitoring
Closed

sjennings wants to merge 1 commit into
stablyai:mainfrom
sjennings:feat/zai-coding-plan-monitoring

Conversation

@sjennings

Copy link
Copy Markdown

What Changed

  • Adds first-class Z.AI GLM Coding Plan quota monitoring through Orca’s shared rate-limit pipeline.
  • Reads only the explicit zai-coding-plan API-key record from OpenCode auth.json and sends one read-only quota request to the configured global or China origin.
  • Displays Z.AI after Claude and Codex in the footer with 5-hour and weekly windows, compact/detailed modes, visibility controls, localized recovery guidance, and a one-shot default-on migration.
  • Adds mixed-version, credential-safety, parser, stale/backoff, service-isolation, persistence, renderer, and Electron E2E coverage.

Why

GLM Coding Plan users currently need to leave Orca to check quota. This reuses the existing usage roster while preserving OpenCode credential ownership and treating missing or unfamiliar quota data as unknown rather than falsely showing 0%.

Linked Issue

Fixes #18506

Visual Proof

Validated by the deterministic Electron status-bar E2E at normal, compact, and icon-only widths, and with a signed local macOS build manually tested by the requester. The E2E asserts the visible Z.AI row, 5-hour and weekly windows, compact meter, icon badge, keyboard focus, and visibility toggle.

Testing

  • I manually tested these changes locally on macOS

  • Automated tests added/updated

  • pnpm tc — passed on current upstream main

  • 222 focused tests — passed on current upstream main

  • pnpm run check:code-quality:changed — feature branch passed with 0 findings before rebasing; after rebasing, the repo-wide baseline comparison reports one unrelated pre-existing finding in mobile/src/session/use-mobile-session-terminal-create-actions.test.ts

  • Electron status-bar E2E — 2/2 passed

  • pnpm build:mac — signed arm64 and x64 DMG/ZIP artifacts produced

Review

  • Independent plan-compliance and adversarial security/UX reviews found no critical/high issues.
  • Keys remain main-process-only; there are no auth-file writes, inference calls, region probes, environment-key fallbacks, or secret-bearing errors.
  • RateLimitState additions are optional for old-host compatibility.
  • Z.AI visibility is credential/snapshot based and deliberately not PATH gated.

Parallel implementation

PR #18507 addresses the same issue. This PR is an independently developed, hardened alternative with explicit OpenCode credential ownership, a strict global/CN origin allowlist, no in-app key-entry/account surface, stale/backoff integration, additive old-host compatibility, one-shot migration behavior, and broader regression coverage. Maintainers may prefer or combine either approach.

Agent skill upstream boundary

  • Not applicable; this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Z.AI’s official usage plugin uses the monitor endpoint, but it is not a documented stable public REST contract. Parsing is isolated and fails unknown instead of displaying false zero usage.
  • OpenCode credentials are read on the execution host; no unbounded WSL/UNC or remote credential scans are performed.

Checklist

  • This PR is focused on Z.AI quota monitoring
  • I explained what changed and why
  • Visual behavior validated through deterministic Electron E2E and a local macOS build
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, mobile, and backwards-compatibility impact considered
  • Typecheck, focused tests, pre-commit lint/format, and macOS build pass

@coderabbitai

coderabbitai Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds Z.AI Coding Plan usage tracking through OpenCode’s auth.json credentials and Z.AI quota monitor endpoint. Extends rate-limit state, compatibility handling, status-bar visibility, provider rendering, settings migration, localization, documentation, and automated coverage. Refactors shared OpenCode authentication loading and UI hydration helpers.

Merge Risk: 🔵 Low · up to b1857

Some Z.AI users can lose the usage indicator or setup guidance after indeterminate quota responses or when connected to an older host. Resolve these visibility-state issues before relying on the feature rollout.

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (3 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR implements the core Z.AI status-bar provider, quota windows, endpoint access, visibility controls, and default-on migration for #18506. It does not implement the issue's proposed protected API-… Either implement the #18506 requirements for protected API-key storage, supported credential access, and planType, or update the issue's acceptance criteria to approve the OpenCode-owned credential design and add equivalent plan-tier suppor…
Out of Scope Changes check ⚠️ Warning Most changes support Z.AI quota monitoring. The pet-selection hydration extraction and normalization in ui-slice-hydration-actions.ts and ui-slice-hydration-values.ts are unrelated to the linked issue… Remove the pet-selection hydration refactor from this PR or move it to a separate pull request. Retain only changes required for Z.AI quota monitoring and its supporting tests.
Docstring Coverage ⚠️ Warning Docstring coverage is 29.82% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 57 functions across 50 files. (19 skipped… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: hardened Z.AI Coding Plan rate-limit support.
Description check ✅ Passed The description is detailed and covers the change, rationale, linked issue, testing, review notes, compatibility, and checklist. The ELI5 section is missing, and the Visual Proof section describes val…
Full details: Description check

Explanation

The description is detailed and covers the change, rationale, linked issue, testing, review notes, compatibility, and checklist. The ELI5 section is missing, and the Visual Proof section describes validation but does not show attached before-and-after evidence.

Full details: Linked Issues check

Explanation

The PR implements the core Z.AI status-bar provider, quota windows, endpoint access, visibility controls, and default-on migration for #18506. It does not implement the issue's proposed protected API-key field, does not support credentials outside OpenCode auth.json, and does not clearly expose the required planType value.

Resolution

Either implement the #18506 requirements for protected API-key storage, supported credential access, and planType, or update the issue's acceptance criteria to approve the OpenCode-owned credential design and add equivalent plan-tier support.

Full details: Out of Scope Changes check

Explanation

Most changes support Z.AI quota monitoring. The pet-selection hydration extraction and normalization in ui-slice-hydration-actions.ts and ui-slice-hydration-values.ts are unrelated to the linked issue and add separate scope.

Full details: Docstring Coverage

Explanation

Docstring coverage is 29.82% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 57 functions across 50 files. (19 skipped: 7 unsupported, 12 over the file limit.)

  • Fix all pre-merge checks with AI

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 8c2e7816-c0bc-44d8-8ee7-e515f44275bc

📥 Commits

Reviewing files that changed from the base of the PR and between 7106101 and b185777.

📒 Files selected for processing (69)
  • docs/site/content/docs/agents/usage-tracking.mdx
  • mobile/src/components/accounts-snapshot.ts
  • src/main/opencode/opencode-auth-store.test.ts
  • src/main/opencode/opencode-auth-store.ts
  • src/main/rate-limits/gemini-oauth-sources.ts
  • src/main/rate-limits/rate-limit-service-test-harness.ts
  • src/main/rate-limits/service-account-target-selection.test.ts
  • src/main/rate-limits/service-antigravity-usage.test.ts
  • src/main/rate-limits/service-inactive-account-previews.test.ts
  • src/main/rate-limits/service-live-claude-usage.test.ts
  • src/main/rate-limits/service-minimax-usage.test.ts
  • src/main/rate-limits/service-refresh-orchestration.test.ts
  • src/main/rate-limits/service-window-activation.test.ts
  • src/main/rate-limits/service-zai-usage.test.ts
  • src/main/rate-limits/service/service-configuration.ts
  • src/main/rate-limits/service/service-full-cycle-application.ts
  • src/main/rate-limits/service/service-full-cycle-preparation.ts
  • src/main/rate-limits/service/service-polling.ts
  • src/main/rate-limits/service/service-result-policy.ts
  • src/main/rate-limits/service/service-state.ts
  • src/main/rate-limits/service/service-types.ts
  • src/main/rate-limits/zai-auth-configured.test.ts
  • src/main/rate-limits/zai-auth-configured.ts
  • src/main/rate-limits/zai-credentials.test.ts
  • src/main/rate-limits/zai-credentials.ts
  • src/main/rate-limits/zai-fetcher.test.ts
  • src/main/rate-limits/zai-fetcher.ts
  • src/main/runtime/rpc/methods/client-ui-schemas.ts
  • src/main/runtime/rpc/methods/client-ui.test.ts
  • src/renderer/src/components/settings/appearance-status-bar-minimax-toggle-search.ts
  • src/renderer/src/components/settings/appearance-status-bar-search.test.ts
  • src/renderer/src/components/settings/appearance-status-bar-search.ts
  • src/renderer/src/components/settings/appearance-status-bar-zai-toggle-search.ts
  • src/renderer/src/components/status-bar/StatusBarProviderSegment.tsx
  • src/renderer/src/components/status-bar/StatusBarVisibilityMenu.tsx
  • src/renderer/src/components/status-bar/UsageRosterPanel.test.tsx
  • src/renderer/src/components/status-bar/icons.test.tsx
  • src/renderer/src/components/status-bar/icons.tsx
  • src/renderer/src/components/status-bar/provider-segment-letter-badge.test.tsx
  • src/renderer/src/components/status-bar/status-bar-agent-gating.test.ts
  • src/renderer/src/components/status-bar/status-bar-provider-visibility.test.ts
  • src/renderer/src/components/status-bar/status-bar-provider-visibility.ts
  • src/renderer/src/components/status-bar/tooltip.tsx
  • src/renderer/src/components/status-bar/usage-error-copy.test.ts
  • src/renderer/src/components/status-bar/usage-error-copy.ts
  • src/renderer/src/components/status-bar/usage-provider-settings-target.test.ts
  • src/renderer/src/components/status-bar/usage-provider-settings-target.ts
  • src/renderer/src/components/status-bar/usage-roster-order.test.ts
  • src/renderer/src/components/status-bar/usage-roster-order.ts
  • src/renderer/src/components/status-bar/use-status-bar-controller.ts
  • src/renderer/src/i18n/en-runtime-required.json
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/runtime/runtime-provider-accounts-client.test.ts
  • src/renderer/src/store/slices/rate-limits.test.ts
  • src/renderer/src/store/slices/rate-limits.ts
  • src/renderer/src/store/slices/ui-hydration-workspace-preferences.test.ts
  • src/renderer/src/store/slices/ui/status-bar-default-hydration.ts
  • src/renderer/src/store/slices/ui/ui-slice-hydration-actions.ts
  • src/renderer/src/store/slices/ui/ui-slice-hydration-values.ts
  • src/renderer/src/web/preload-api/web-rate-limits-api.ts
  • src/shared/persisted-ui-state-types.ts
  • src/shared/rate-limit-types.ts
  • src/shared/status-bar-defaults.ts
  • src/shared/ui-chrome-types.ts
  • tests/e2e/status-bar-caffeinate.spec.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

if (limits.usageMetadata?.failureKind === 'missing-credentials') {
return false
}
return limits.status !== 'unavailable'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Keep Z.AI discoverable when credential state is unknown.

Line 17 hides every unavailable result. An unavailable result without failureKind: 'missing-credentials' does not prove that the Coding Plan key is absent. This hides the provider for unfamiliar or indeterminate quota outcomes. Return true after the explicit missing-credentials check. Update src/main/rate-limits/zai-auth-configured.test.ts Line 42 to expect true.

Proposed fix
-  return limits.status !== 'unavailable'
+  return true
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return limits.status !== 'unavailable'
return true

isProviderSnapshotPending(providers.minimax) ||
isProviderSnapshotPending(providers.grok)
isProviderSnapshotPending(providers.grok) ||
isProviderSnapshotPending(providers.zai)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Gate the Z.AI pending check on Z.AI configuration.

An older host can omit the Z.AI snapshot while zaiAuthConfigured is false. Line 177 then treats the absent snapshot as pending. isUsageEmptyState returns false indefinitely and suppresses the setup CTA after all supported provider snapshots settle.

Match the Antigravity path. Require hasUsageProviderSettingsForProvider('zai', settings) before testing whether providers.zai is pending.

Proposed fix
+  const zaiSnapshotPending =
+    hasUsageProviderSettingsForProvider('zai', settings) &&
+    isProviderSnapshotPending(providers.zai)
   if (
     isProviderSnapshotPending(providers.claude) ||
     isProviderSnapshotPending(providers.codex) ||
     isProviderSnapshotPending(providers.gemini) ||
     isProviderSnapshotPending(providers.opencodeGo) ||
     isProviderSnapshotPending(providers.kimi) ||
     antigravitySnapshotPending ||
     isProviderSnapshotPending(providers.minimax) ||
     isProviderSnapshotPending(providers.grok) ||
-    isProviderSnapshotPending(providers.zai)
+    zaiSnapshotPending
   ) {

})
await flushMicrotasks()

subscriptionCallbacks?.onResponse({

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Require the compatibility test to establish the subscription and receive one snapshot.

If watchProviderAccounts does not call runtimeEnvironmentSubscribe, or if the callback receives no ready response, subscriptionCallbacks remains unset and the optional assertions at lines 301–302 still pass. Assert that the callback exists and that snapshots has one item before checking the omitted Z.AI fields.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No critical issues — two minor suggestions inline.

Reviewed changes

  • OpenCode auth-store extraction — pulled auth.json candidate discovery/parsing into a shared opencode-auth-store.ts with sanitized (path-free) read errors, and routed the existing Gemini readAuthJson through it while preserving its throw-on-error contract.
  • Z.AI fetcher + credential reader — new zai-fetcher.ts / zai-credentials.ts / zai-auth-configured.ts: reads only the zai-coding-plan record, strict two-host origin allowlist, raw-key Authorization, exact 5h/7d window parsing that fails "unknown" instead of 0%, and typed failureKind classification (401/403 → stale-token, 429 → rate-limited with Retry-After, 5xx → server, etc.).
  • Service wiring — zai added to the Promise.allSettled cycle, polling roster, stale/backoff policy, failure-streak tracking, and zaiAuthConfigured derived from the settled result (no duplicate auth probe).
  • Renderer + shared types — zai / zaiAuthConfigured as optional RateLimitState fields for old-host compatibility, roster ordering (Claude, Codex, Z.AI, …), visibility, letter badge, icon, error copy, i18n across all five catalogs, and a one-shot default-on migration inserting Z.AI after Codex.
  • Tests — mixed-version, credential-safety, parser, stale/backoff, service-isolation, persistence, renderer, and an Electron E2E across verbose/compact/icon-only modes plus visibility toggle.

The parsing is fail-closed, keys never reach the renderer or error strings, and the old-host wire compatibility is handled carefully. The two notes below are the only things that gave me pause.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

}

/** Durable `zaiAuthConfigured` signal: a nonempty Coding Plan key is on disk. */
export async function isZaiAuthConfigured(): Promise<boolean> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

isZaiAuthConfigured is exported and unit-tested but has no production caller — the service derives the durable flag from the settled fetch result via deriveZaiAuthConfigured instead. Its semantics also diverge from that live path: it returns false for an unreadable auth.json, whereas deriveZaiAuthConfigured returns true for the status: 'error' result such a failure produces. Two near-identically-named "is configured" functions with opposite edge-case behavior is a maintenance trap. Recommend removing isZaiAuthConfigured (and its test) or wiring it in explicitly if a store-level check is intended somewhere.

if (limits.usageMetadata?.failureKind === 'missing-credentials') {
return false
}
return limits.status !== 'unavailable'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

status !== 'unavailable' treats every error result as configured, including an auth-store read/parse failure (makeError(credentials.error, 'unknown')). That means a user who has never set up Z.AI but has a corrupt or unreadable ~/.opencode/auth.json gets a phantom Z.AI row in error state, and the recovery path shows the raw store error ("Failed to read OpenCode auth.json (EACCES)") since only stale-token/missing-credentials get the friendly copy. The keep-visible-on-transient-network-failure goal is right, but consider keying it on failureKind: unknown (store read failure) should read as unconfigured, while network/server/parse keep the row. Worth confirming this edge is intentional before merge.

@hongvincent

Copy link
Copy Markdown

Tested locally on macOS arm64 (Orca 1.4.194, ZCode v2 credentials).

Verified that querying the /api/monitor/usage/quota/limit endpoint with an active Z.AI OAuth token works as expected.

Filtering out TIME_LIMIT (which only tracks auxiliary web search/read counts) and focusing exclusively on TOKENS_LIMIT / CREDIT_LIMIT accurately reflects the active GLM Coding Plan token quota in Orca's status bar without falsely showing 100% usage.

Solid implementation and verified working on real hardware. Thanks for the work!

@nwparker

Copy link
Copy Markdown
Contributor

Thanks for the careful work here. Z.AI/GLM Coding Plan usage now ships on main via ZCode (#24674), so we're closing this as superseded. Feel free to open a new PR if reading OpenCode's zai key is still needed.

@nwparker nwparker closed this Oct 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Show Z.ai GLM Coding Plan quota in the status bar

3 participants