Skip to content

fix(rate-limits): read OpenCode Go usage with the Go API key - #22551

Merged
nwparker merged 6 commits into
mainfrom
nwparker/opencode-go-usage-api-key
Sep 24, 2026
Merged

nwparker merged 6 commits into
mainfrom
nwparker/opencode-go-usage-api-key

Conversation

@nwparker

@nwparker nwparker commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 15 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​585 $\color{#cf222e}{\Huge{\mathbf{−}}}$​56 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​529
Prod 28 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​661 $\color{#cf222e}{\Huge{\mathbf{−}}}$​24 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​637

ELI5

The OpenCode Go usage bar reads your usage by reusing a browser cookie. On 22 Sep OpenCode locked the page that cookie talks to behind a Black subscription, so everyone without Black lost the bar. OpenCode has a proper API for this that authenticates with the same key your Go inference already uses and needs no cookie. Orca now uses that key first, and keeps the cookie as a fallback so Black users are unaffected.

What Changed

Before: non-Black accounts see an empty or errored OpenCode Go bar.
After: usage is read with the Go API key. An account with no Go subscription gets a clear "No subscription" state instead of a generic refresh failure.

Key resolution order, cookie as the final fallback:

Tier Source macOS / Linux Windows
1 New setting opencodeGoApiKey (Settings → Accounts → OpenCode Go) encrypted in Orca state same
2 OPENCODE_API_KEY process env process env
3a OpenCode 1.x auth.json, entry opencode-go ~/.local/share/opencode/auth.json %USERPROFILE%\.local\share\opencode\auth.json
3b OpenCode 2.x credential table, integration_id='opencode-go', active DESC, time_created DESC ~/.local/share/opencode/opencode*.db (honours OPENCODE_DB) same shape under the user profile

New: opencode-go-api-key-source.ts, opencode-go-usage-api.ts, opencode-go-usage-source-selection.ts. The cookie fetcher is untouched.

Fallback policy: key first; on ok, done. On any key failure with a cookie configured, the cookie path runs and wins if it succeeds — that is what keeps Black/legacy accounts working, since their key 403s but their console session still has data. If both fail, the key's verdict is reported as the more specific answer.

Why

Fixes #22512. Distinct from #22257/#21462, which the reporter already had in v1.4.209.

Root cause confirmed in source — origin/dev commit fe51b0b19a "fix(console): restrict legacy access to Black (#50716)", 22 Sep 2026, breaks the cookie path two independent ways:

  • packages/console/app/src/context/auth.ts — getActor() now joins UserTable → BillingTable requiring isNotNull(BillingTable.subscriptionID); without Black it throw redirectToNewConsole() → 302 to /login, killing the /_server workspace lookup Orca depends on.
  • packages/console/app/src/routes/workspace/[id]/go/index.tsx — now begins throw redirect("/console/go") before any render.

Schema derived from origin/dev:packages/console/app/src/routes/zen/go/v1/usage.ts, not from the issue text:

GET https://opencode.ai/zen/go/v1/usage
Authorization: Bearer <key>            # ^Bearer (\S+)$; no cookie

200 {"usage":{"rolling":{"status":"ok"|"rate-limited","percent":<0-100>,"resetsAt":<ISO>},
              "weekly":{…},"monthly":{…}}}
401 {"type":"error","error":{"type":"AuthError",…}}
403 {"type":"error","error":{"type":"EntitlementError",…}}

Details the issue omitted: status has exactly two values; percent is pinned to 100 when rate-limited, so it alone is sufficient; all three windows are always present on a 200; window durations are not in the response (server-side ZEN_LIMITS), so Orca keeps its existing 5h/7d/30d assumptions. And the handler first calls proxyInference — an oc_sk_-prefixed key, or a legacy key on a migrated workspace, is forwarded upstream and the body is whatever the new console returns. So classification keys on the error name first and HTTP status second, and the success body is parsed defensively.

The issue's key-storage claim is only half right, and this matters. auth.json is OpenCode 1.x. On 2.x (v2.0.15, identical on v2.0.12) migration 20260805200742_import_legacy_credentials imports it into a SQLite credential table and it is never read again — a fresh OpenCode 2 install has no auth.json entry at all. Implementing only the documented tier would have missed every clean OpenCode 2 user, which is most of the people reporting OpenCode bugs right now.

Windows path: packages/util/src/global-roots.ts and packages/core/src/global.ts both resolve data as XDG_DATA_HOME || homedir()/.local/share with no Windows branch — so it is C:\Users\<name>\.local\share\opencode\, not %APPDATA%. Orca already had a matching resolver (opencode-data-directory.ts, pinned by scanner-windows-data-directory.test.ts); reused rather than duplicated.

OPENCODE_API_KEY is right for Go, not just Zen: v2.0.15:packages/core/models-dev/snapshot.txt gives opencode-go → env: ["OPENCODE_API_KEY"], api: "https://opencode.ai/zen/go/v1" — the same base as the usage endpoint.

Linked Issue

Fixes #22512

Visual Proof

N/A — capturing before/after needs a live OpenCode Go account, and per the brief I did not call the endpoint with real credentials. Staging it with a mocked response would be a screenshot of a fixture, not of the fix.

The behavioural proof is the source-derived schema above plus 25 new tests covering 200 / 401 / 403 / proxied-403 / malformed-body and every key tier.

Testing

Platforms: macOS; source verification against origin/dev (console server) and v2.0.15 / v2.0.12 (CLI, auth storage).

pnpm test src/main/rate-limits       → 50 files, 526 passed
  new: 7 key-resolution (all tiers, missing + malformed auth.json)
       8 API (200/401/403/proxied-403/malformed body/no-key-in-error)
       8 source-selection (each tier, both cookie-fallback directions)
       2 parser
pnpm tc                              → clean
pnpm run check:code-quality:changed  → 0 findings across 53 files
broader sweep (status bar, settings, persistence, shared, startup)
                                     → 1178 files, 12094 passed

Not verified: anything needing a live account — no real 200/401/403 was observed. The proxied response body for oc_sk_ keys comes from a handler not in this repo; the parser rejects anything that is not {usage:{rolling,weekly}} and reports a parse failure rather than guessing. Real ZEN_LIMITS window durations are server config; the 5h/7d/30d labels are pre-existing assumptions, not introduced here.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Secrets: the key uses the same PROTECTED_SECRET_SLOT safeStorage path as opencodeSessionCookie (encrypt on save, decrypt on load, retained blob cleared on clear), a type="password" input, and is deliberately not in the web/remote client settings allowlist. Never logged, never in an error message — network failures report error.name only, because the thrown message can embed the request URL — never in telemetry; the fetch-cycle config hash stores a SHA-256 digest. Fixtures use obvious placeholders.
  • A visibility bug would have hidden this fix: hasUsageProviderSettingsForProvider('opencode-go') gated solely on opencodeSessionCookie, so a key-only user would still have seen nothing. Added opencodeGoApiKeyConfigured to RateLimitState, set in main per fetch cycle — the key itself never crosses to the renderer — mirroring the existing minimaxApiKeyConfigured pattern.
  • SSH / WSL / remote: Orca reads the local credential store, never the SSH host's or the WSL distro's. Per docs/reference/ssh-execution-boundary.md the execution host owns what touches execution; a status-bar usage poll is an account-level property and the HTTPS request originates from the Orca host regardless. Pulling a bearer token off a remote host to use locally would move a secret across that boundary, which is strictly worse. This matches the existing cookie, which has always been an Orca-host setting. A user whose key lives only on a remote host can paste it into tier 1.
  • Wire compatibility (docs/reference/remote-wire-compatibility.md): no new opcode, no new RPC param. failureKind is absent from mobile's zod schema and ProviderRateLimitsSchema is .passthrough(), so 'no-subscription' reaches old mobile clients harmlessly; the new error string renders as text.
  • The SQLite tier is guarded by isWslUncPath so a synchronous read-only open can never hang main on a 9p/UNC share; every DB failure degrades to "no key here".

Checklist

  • This PR is small and focused
  • I explained what changed and why
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test pass locally

@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: e0add877-66f6-4995-84b0-24fff0fe2841

📥 Commits

Reviewing files that changed from the base of the PR and between 31cfa95 and 84bdd91.

📒 Files selected for processing (2)
  • src/shared/ghostty-import-preview.ts
  • src/shared/global-settings-types.ts

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


📝 Walkthrough

Walkthrough

The change adds encrypted OpenCode Go API-key settings and key discovery from settings, OpenCode storage, and the environment. The rate-limit path requests usage with a resolved key and can fall back to the existing cookie fetcher. It adds parsing and response handling for usage windows, unauthorized responses, and missing subscriptions. Rate-limit state and the settings and status-bar UI now include API-key configuration and no-subscription status.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🔵 Low · up to 84bdd

Windows test runs can fail on the path assertion, and the cookie guidance may discourage users from configuring an available fallback. Both are bounded fixes; neither establishes a broader usage outage.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning Issue #22512 requires key precedence of Orca settings, OPENCODE_API_KEY, then OpenCode saved credentials. The implementation resolves settings, auth.json, the credential database, and only then `O… Update resolveOpenCodeGoApiKey to check OPENCODE_API_KEY before auth.json and the credential database. Update the resolution tests and documentation to assert settings, environment, then saved credentials.
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 42 functions across 42 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary change: reading OpenCode Go usage with the Go API key. It is concise and specific.
Description check ✅ Passed The description follows the required template and covers the user impact, implementation, rationale, linked issue, visual proof, testing, security, compatibility, and checklist. It is sufficiently com…
Out of Scope Changes check ✅ Passed The changes stay within Issue #22512. They add OpenCode Go API-key storage and resolution, usage-endpoint access, no-subscription handling, cookie fallback, status-bar visibility, and related tests. T…
Full details: Linked Issues check

Explanation

Issue #22512 requires key precedence of Orca settings, OPENCODE_API_KEY, then OpenCode saved credentials. The implementation resolves settings, auth.json, the credential database, and only then OPENCODE_API_KEY. The API endpoint, no-subscription result, cookie fallback, protected setting, and automated tests are present. The required precedence remains incorrect.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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.

@andyranitzsch

Copy link
Copy Markdown

Confirming this on Windows 11, OpenCode Go (no Black subscription), Orca v1.4.207:

  • The endpoint already works with the key OpenCode saved: GET https://opencode.ai/zen/go/v1/usage with Authorization: Bearer <opencode-go key> from C:\Users\<user>\.local\share\opencode\auth.json returns 200 {"usage":{"rolling":...,"weekly":...,"monthly":...}}. No cookie involved.
  • So tier 3a's Windows path (%USERPROFILE%\.local\share\opencode\auth.json, not %APPDATA%) is correct as written.
  • +1 for keeping the cookie as a fallback only. The cookie path has needed repeated fresh pastes and is now dead for non-Black accounts anyway.

Happy to smoke-test a Windows dev build once this is mergeable.

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

Important

OPENCODE_API_KEY is the shared env var for both OpenCode Zen and OpenCode Go, so treating it as proof that Go is configured makes the default-on OpenCode Go meter appear (showing "No subscription") for a Zen-only user who happens to have it exported. One inline comment with the chain and a suggested lever.

Reviewed changes

  • New Go key resolution (opencode-go-api-key-source.ts) — resolves a key across four tiers (Orca setting, OPENCODE_API_KEY, OpenCode 1.x auth.json, OpenCode 2 credential DB) and reaches OpenCode's data directory through Orca's existing cross-platform resolver.
  • New keyed usage client (opencode-go-usage-api.ts) — GET /zen/go/v1/usage with Authorization: Bearer, 15s timeout, proxy guard on the default session, and failure classification keyed on the console's error name, with fixed error strings that never carry the key.
  • Key-first source selection (opencode-go-usage-source-selection.ts) — key path first, cookie path retained as a fallback for legacy/Black accounts, with per-verdict copy.
  • Service wiring — apiKey added to the Go config, a SHA-256 digest folded into the config-change hash, and opencodeGoApiKeyConfigured reported to the renderer in place of the key.
  • Encrypted persistence — new PROTECTED_SECRET_SLOT.opencodeGoApiKey on the same fail-closed encrypt/decrypt/clear path as the cookie, kept out of the web/remote settings allowlist.
  • Renderer — maskable settings field, visibility gated on the new flag, and a no-subscription status label/message branch.
  • Tests — 25 new tests spanning key tiers, API classification, source selection, visibility, and error copy.

I independently verified the upstream contracts this rests on: the GET /zen/go/v1/usage body shape and 401/403 error names, OpenCode 2's credential table (integration_id, JSON value of {type:"key",key}, active/time_created) and its legacy-import migration, and OpenCode 1.x auth.json ({"opencode-go":{"type":"api","key"}}). Those all match.

ℹ️ Nitpicks

  • classifyFailure ORs status === 403 ahead of the error name, so a 403 body carrying AuthError would read as "No subscription" even though the adjacent comment says the name is checked first. Low risk given the endpoint returns 401 for auth, but the ordering contradicts the stated rule.
  • resolveOpenCodeGoApiKey threads an injectable environment into the auth-file tier, but readOpenCodeCredentialDatabaseGoKey() reads process.env via listOpenCodeDatabases(), so an injected environment does not fully isolate the resolver. Tests pass only because they set the globals.

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

Comment on lines +65 to +70
if (outcome.kind === 'no-subscription') {
return emptyResult(
'This OpenCode account has no OpenCode Go subscription. Subscribe at opencode.ai to see Go usage.',
'error',
{ source: 'web', credentialSource, failureKind: 'no-subscription' }
)

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.

When the credential came from the shared OPENCODE_API_KEY env tier and there is no cookie, this branch turns a no-subscription verdict into a data-less status: "error" snapshot — and isProviderConfigured treats any non-unavailable status as configured, so the default-on opencode-go status item renders "No subscription" for a user who never opted into Go. A Go-specific credential (settings override or OpenCode's stored opencode-go key) should keep reporting the verdict; the shared env var should probably not claim the bar by itself.

Technical details
# Shared env var makes the default-on Go meter appear

## Affected sites
- `src/main/rate-limits/opencode-go-usage-source-selection.ts:65` — `no-subscription` is always surfaced as `status:'error'`.
- `src/main/rate-limits/opencode-go-api-key-source.ts:175` — tier 2 reads the generic `OPENCODE_API_KEY`.
- `src/renderer/src/components/status-bar/status-bar-provider-visibility.ts:59` — `isProviderConfigured` returns true for any non-`unavailable` status, including a data-less `error`.
- `src/shared/status-bar-defaults.ts:8` — `opencode-go` is a default-on item.

## Evidence
- models.dev declares `env:["OPENCODE_API_KEY"]` for both `opencode` (Zen) and `opencode-go`, and OpenCode's own provider resolution connects every provider whose declared env var is present. A Zen-only user with the var exported is therefore indistinguishable from a Go user at tier 2.
- The PR's Help text and `OPENCODE_API_KEY` tier read as if the var were Go-specific; it is not.

## Required outcome
- Catch the env tier by itself should not make a user who has no Go entitlement see a Go error meter, while a genuine Go credential should still surface "No subscription".

## Suggested approach (optional)
- In `apiFailureResult` (or its caller), when `credentialSource === 'environment'` and there is no cookie, return `emptyResult(..., 'unavailable', { failureKind: 'no-subscription' })` instead of `'error'` so the bar stays hidden; a real env-configured Go user still shows the bar via the `ok` snapshot from `isProviderConfigured`.

@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 new issues in the three new commits. This run is not an approval because the previously flagged shared-env-var concern is still open — the tier reorder narrows it but does not close it for an env-only account.

Reviewed changes

  • Go key precedence reordered (opencode-go-api-key-source.ts) — the OpenCode-stored /connect credential (auth.json, then the 2.x credential table) now outranks OPENCODE_API_KEY; only the Orca settings override sits above it. This fixes a both-Zen-and-Go account whose generic env key was shadowing its Go key, but an env-only account still resolves the shared tier.
  • Redirect-to-sign-in classified as unauthorized (opencode-go-usage-api.ts) — a 200 body that fails to parse while carrying content-type: text/html is now a rejected-key verdict rather than a parse failure, with a test covering the HTML page.
  • Cookie-path error reworded (opencode-go-usage-fetcher.ts) — the no-workspace message now points at adding an API key or running /connect; it only surfaces when no key was resolved, so the advice is accurate.
  • English catalog strings added (en.json) — the AccountsPane.opencodeGo.apiKey.* settings strings and the status.bar.tooltip.usage.noSubscription.label now resolve (verified all six paths parse and there is no duplicate opencodeGo key).

I ran the changed suites locally: src/main/rate-limits, src/renderer/src/components/status-bar, and src/renderer/src/i18n — 124 files, 1085 tests passed.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 564ceb8b-f07e-4b3c-864b-5bc1ab3c2e03

📥 Commits

Reviewing files that changed from the base of the PR and between 845db9e and cc7fef1.

📒 Files selected for processing (42)
  • src/main/persistence/applying-settings/settings-update.ts
  • src/main/persistence/leasing-ssh-ptys/secret-validation.ts
  • src/main/persistence/loading-store/loaded-state-parsing.ts
  • src/main/persistence/loading-store/state-serialization-secret-handling.ts
  • src/main/protected-secret-persistence.ts
  • src/main/rate-limits/opencode-go-api-key-source.test.ts
  • src/main/rate-limits/opencode-go-api-key-source.ts
  • src/main/rate-limits/opencode-go-status-parsing.test.ts
  • src/main/rate-limits/opencode-go-status-parsing.ts
  • src/main/rate-limits/opencode-go-usage-api.test.ts
  • src/main/rate-limits/opencode-go-usage-api.ts
  • src/main/rate-limits/opencode-go-usage-fetcher.test.ts
  • src/main/rate-limits/opencode-go-usage-fetcher.ts
  • src/main/rate-limits/opencode-go-usage-source-selection.test.ts
  • src/main/rate-limits/opencode-go-usage-source-selection.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/service-configuration.ts
  • src/main/rate-limits/service/service-full-cycle-preparation.ts
  • src/main/rate-limits/service/service-state.ts
  • src/main/rate-limits/service/service-types.ts
  • src/main/startup/main-process-account-services.ts
  • src/renderer/src/components/settings/AccountsPane.tsx
  • src/renderer/src/components/settings/accounts-pane-provider-setting-sections.tsx
  • src/renderer/src/components/settings/accounts-pane-types.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/usage-error-copy.test.ts
  • src/renderer/src/components/status-bar/usage-error-copy.ts
  • src/renderer/src/components/status-bar/use-status-bar-controller.ts
  • src/renderer/src/i18n/locales/en.json
  • src/shared/default-global-settings.ts
  • src/shared/global-settings-types.ts
  • src/shared/rate-limit-state-factory.ts
  • src/shared/rate-limit-types.test.ts
  • src/shared/rate-limit-types.ts

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

})

it('reads auth.json from XDG_DATA_HOME, which OpenCode uses on every platform', () => {
expect(getOpenCodeAuthFilePath({ XDG_DATA_HOME: '/data' })).toBe('/data/opencode/auth.json')

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

Build the expected path with join so the test passes on Windows.

getOpenCodeAuthFilePath uses node:path join. On Windows, join returns \data\opencode\auth.json. The literal '/data/opencode/auth.json' then fails. Line 74 already uses join.

Proposed fix
-    expect(getOpenCodeAuthFilePath({ XDG_DATA_HOME: '/data' })).toBe('/data/opencode/auth.json')
+    expect(getOpenCodeAuthFilePath({ XDG_DATA_HOME: '/data' })).toBe(
+      join('/data', 'opencode', 'auth.json')
+    )
📝 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
expect(getOpenCodeAuthFilePath({ XDG_DATA_HOME: '/data' })).toBe('/data/opencode/auth.json')
expect(getOpenCodeAuthFilePath({ XDG_DATA_HOME: '/data' })).toBe(
join('/data', 'opencode', 'auth.json')
)

"description": "Optional override. Orca otherwise uses the key OpenCode saved when you ran /connect, then OPENCODE_API_KEY.",
"label": "OpenCode Go API key",
"placeholder": "Leave blank to use the key saved by /connect or OPENCODE_API_KEY",
"help": "Used for OpenCode Go usage in the status bar. The session cookie below is only needed for legacy console (OpenCode Black) accounts."

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

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1,80p' src/main/rate-limits/opencode-go-usage-fetcher.ts
sed -n '86,132p' src/main/rate-limits/opencode-go-usage-source-selection.ts
rg -n -i 'black|legacy|console' src/main/rate-limits/opencode-go-usage-fetcher.ts src/main/rate-limits/opencode-go-usage-source-selection.ts src/renderer/src/components/settings/accounts-pane-provider-setting-sections.tsx

Repository: stablyai/orca

Length of output: 8320


🏁 Script executed:

sed -n '80,275p' src/main/rate-limits/opencode-go-usage-fetcher.ts
sed -n '1,155p' src/main/rate-limits/opencode-go-usage-source-selection.ts
sed -n '130,215p' src/renderer/src/components/settings/accounts-pane-provider-setting-sections.tsx
rg -n -i 'fetchOpenCodeGoRateLimits|console/api/go/status|zen/go/v1/usage|workspace/.*/go|OpenCode Black|legacy-console|legacy console' src README.md docs 2>/dev/null

Repository: stablyai/orca

Length of output: 21545


🏁 Script executed:

printf '%s\n' '--- fetcher ---'
sed -n '80,275p' src/main/rate-limits/opencode-go-usage-fetcher.ts
printf '%s\n' '--- selector ---'
sed -n '1,155p' src/main/rate-limits/opencode-go-usage-source-selection.ts
printf '%s\n' '--- settings ---'
sed -n '130,215p' src/renderer/src/components/settings/accounts-pane-provider-setting-sections.tsx
printf '%s\n' '--- references ---'
rg -n -i 'fetchOpenCodeGoRateLimits|console/api/go/status|zen/go/v1/usage|workspace/.*/go|OpenCode Black|legacy-console|legacy console' src README.md docs 2>/dev/null

Repository: stablyai/orca

Length of output: 21614


Clarify the OpenCode Go cookie fallback.

The cookie fallback is not restricted to OpenCode Black accounts. When no API key exists, or the keyed request fails, fetchOpenCodeGoUsage calls fetchOpenCodeGoRateLimits. That function uses the cookie to query /console/api/go/status and can return usage for any account whose response is accepted.

Suggested fix
-              "help": "Used for OpenCode Go usage in the status bar. The session cookie below is only needed for legacy console (OpenCode Black) accounts."
+              "help": "Used for OpenCode Go usage in the status bar. The session cookie can also be used as a fallback when no API key is available or the API key request fails. Legacy console (OpenCode Black) accounts use the cookie path."
📝 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
"help": "Used for OpenCode Go usage in the status bar. The session cookie below is only needed for legacy console (OpenCode Black) accounts."
"help": "Used for OpenCode Go usage in the status bar. The session cookie can also be used as a fallback when no API key is available or the API key request fails. Legacy console (OpenCode Black) accounts use the cookie path."

nwparker and others added 4 commits September 23, 2026 16:09
Since OpenCode's console migration (upstream fe51b0b19a, "fix(console):
restrict legacy access to Black"), an account with no Black subscription
is redirected from the legacy console to /console/login, so Orca's
cookie-based workspace lookup returns nothing and the Go bar stays empty.

Fetch usage from GET https://opencode.ai/zen/go/v1/usage instead, which
authenticates with `Authorization: Bearer <key>` and needs no console
session. The key resolves in order: Orca settings override,
OPENCODE_API_KEY, then whatever OpenCode itself stored on /connect --
auth.json for 1.x, the credential table for 2.x. The cookie path stays
as the fallback so Black/legacy accounts keep working.

A 403 EntitlementError now reads as "no OpenCode Go subscription" in the
status bar instead of a generic refresh failure (#22257's reporter was
misled by exactly that).
OpenCode applies the key saved on /connect after the environment, so the
stored key is the one its own Go requests use. OPENCODE_API_KEY is also
the Zen provider's variable, so ranking it first could read a key that
OpenCode itself is not using for Go.

Co-Authored-By: Claude <[email protected]>
…gn-in

A redirected usage request arrives as a 200 sign-in page because Electron
follows redirects; report it as a rejected key instead of a parse failure.
The cookie path's empty workspace lookup is what non-Black accounts now
hit after the console migration, so its message points at the API key
rather than only the workspace override.

Co-Authored-By: Claude <[email protected]>
@nwparker
nwparker force-pushed the nwparker/opencode-go-usage-api-key branch from cc7fef1 to 5d78723 Compare September 23, 2026 23:10
…rker

Verified on two real Windows hosts running OpenCode 1.18.16: the `credential`
table exists there too (empty, same columns), so its presence does not identify
a 2.x install. Neither host had an `auth.json` at all.

The resolution already probes both stores on every version, so only the comments
were wrong. Says so now, and records that a 2.x install which never ran the
legacy import has no `auth.json` either — which is why both tiers exist.
Adding `opencodeGoApiKey` pushed global-settings-types.ts one line past the
300-line ceiling, failing `oxlint` in CI. AGENTS.md forbids a max-lines
suppression, so split instead: the Ghostty import preview is a distinct concern
that never belonged in the settings-shape file.

Re-exported from the original module so no importer changes. 293 code lines now.
@nwparker
nwparker merged commit 5802b54 into main Sep 24, 2026
30 checks passed
@nwparker
nwparker deleted the nwparker/opencode-go-usage-api-key branch September 24, 2026 03:09
flosrn pushed a commit to flosrn/orca that referenced this pull request Sep 25, 2026
…i#22551)

* fix(rate-limits): read OpenCode Go usage with the account API key

Since OpenCode's console migration (upstream fe51b0b19a, "fix(console):
restrict legacy access to Black"), an account with no Black subscription
is redirected from the legacy console to /console/login, so Orca's
cookie-based workspace lookup returns nothing and the Go bar stays empty.

Fetch usage from GET https://opencode.ai/zen/go/v1/usage instead, which
authenticates with `Authorization: Bearer <key>` and needs no console
session. The key resolves in order: Orca settings override,
OPENCODE_API_KEY, then whatever OpenCode itself stored on /connect --
auth.json for 1.x, the credential table for 2.x. The cookie path stays
as the fallback so Black/legacy accounts keep working.

A 403 EntitlementError now reads as "no OpenCode Go subscription" in the
status bar instead of a generic refresh failure (stablyai#22257's reporter was
misled by exactly that).

* fix(rate-limits): prefer OpenCode's stored Go key over OPENCODE_API_KEY

OpenCode applies the key saved on /connect after the environment, so the
stored key is the one its own Go requests use. OPENCODE_API_KEY is also
the Zen provider's variable, so ranking it first could read a key that
OpenCode itself is not using for Go.

Co-Authored-By: Claude <[email protected]>

* fix(rate-limits): name the API key when OpenCode Go usage lands on sign-in

A redirected usage request arrives as a 200 sign-in page because Electron
follows redirects; report it as a rejected key instead of a parse failure.
The cookie path's empty workspace lookup is what non-Black accounts now
hit after the console migration, so its message points at the API key
rather than only the workspace override.

Co-Authored-By: Claude <[email protected]>

* chore(i18n): add the OpenCode Go API key strings to the English catalog

Co-Authored-By: Claude <[email protected]>

* docs(rate-limits): stop calling the credential table an OpenCode 2 marker

Verified on two real Windows hosts running OpenCode 1.18.16: the `credential`
table exists there too (empty, same columns), so its presence does not identify
a 2.x install. Neither host had an `auth.json` at all.

The resolution already probes both stores on every version, so only the comments
were wrong. Says so now, and records that a 2.x install which never ran the
legacy import has no `auth.json` either — which is why both tiers exist.

* refactor(shared): move GhosttyImportPreview out of global-settings-types

Adding `opencodeGoApiKey` pushed global-settings-types.ts one line past the
300-line ceiling, failing `oxlint` in CI. AGENTS.md forbids a max-lines
suppression, so split instead: the Ghostty import preview is a distinct concern
that never belonged in the settings-shape file.

Re-exported from the original module so no importer changes. 293 code lines now.

---------

Co-authored-by: Jinwoo-H <[email protected]>
Co-authored-by: Claude <[email protected]>
(cherry picked from commit 5802b54)
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.

[Bug]: OpenCode Go usage stops loading after OpenCode moved to the new Console

3 participants