Skip to content

fix(opencode-go): show OpenCode Go usage for OpenCode 2 Console sign-ins - #52034

Merged
nwparker merged 1 commit into
stablyai:mainfrom
luisgonzaleznf:luisgonzaleznf/opencode-go-console-login
Nov 28, 2026
Merged

nwparker merged 1 commit into
stablyai:mainfrom
luisgonzaleznf:luisgonzaleznf/opencode-go-console-login

Conversation

@luisgonzaleznf

@luisgonzaleznf luisgonzaleznf commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

OpenCode 2 moved where it keeps your login. When you sign in with /connect, OpenCode 2 saves an OpenCode Console sign-in in its database instead of an "OpenCode Go key". Orca only knew how to find the old key, so it found nothing, decided you weren't set up, and hid the OpenCode Go row in the Usage popover. Now Orca also reads that sign-in, the same way OpenCode itself shows Go usage, and the row comes back. People who only use Zen (no Go plan) still see nothing new.

What Changed

Before: on OpenCode 2 with only a /connect Console sign-in, every OpenCode Go credential tier came up empty, fetchOpenCodeGoUsage returned unavailable, and the OpenCode Go row was hidden.

After: the row shows Go usage (rolling, weekly, monthly) for the signed-in org.

Mechanism:

  • New last-resort tier, opencode-console-login. Orca reads the credential row with integration_id = 'opencode' (OAuth access token or a service-account key, scoped by metadata.orgID) and calls GET https://opencode.ai/zen/go/v1/usage with Authorization: Bearer <token> and x-opencode-org-id: <orgID>, which is what OpenCode's own usage panel sends.
    • It only applies when nothing else is configured. The Settings override, a /connect Go key in any OpenCode database, OPENCODE_AUTH_CONTENT / auth.json, and OPENCODE_API_KEY all win over it, in the same order as before. A configured session cookie also keeps its own answer over an unproven sign-in.
    • It uses the first opencode row in OpenCode's order (active DESC, time_created DESC, id DESC), which is the active account, so an account the user switched away from is never picked over it. Legacy rows with no active flag still count. The row needs a string org ID and a metadata.server of opencode.ai (or the console.opencode.ai alias), so a token from another console is never sent to opencode.ai. Expired OAuth tokens are skipped: Orca never refreshes them, because that would write OpenCode's database.
  • Zen-only accounts stay hidden and don't get polled. Most OpenCode 2 users have a Console sign-in, with or without Go. Until an org returns Go usage, every non-OK answer looks exactly like having no credential (unavailable / missing-credentials). A 403 or EntitlementError for a Console org counts as "no Go here". That org is then left alone by automated polls for 6 hours (1 hour after any other failure, such as a timeout or 5xx). A user refresh (force) asks again right away. Once an org has shown Go in this process, errors show the same way they do for keys, and a 401 asks the user to run /connect again.
  • Credential read moved off the main thread. The OpenCode database lookup now runs in the existing foreign SQLite reader worker as a new openCodeGoCredential lane (readers/opencode-go-credential.ts, with a zod-validated result in opencode-go-credential-result.ts). This removes the four main-thread SQLite uses in opencode-go-api-key-source.ts, and the main-blocking-sqlite baseline is pruned to match. A worker timeout or crash maps to unreadable, never missing, so the fix(opencode-go): don't fall back to OPENCODE_API_KEY when the credential database is unreadable #24605 behaviour (withhold OPENCODE_API_KEY when the DB can't be read) is kept.

Why

The Go usage endpoint already accepts the Console token, and that is how OpenCode 2 renders Go usage itself, so this needs no new endpoint or cookie flow. Putting the sign-in last, and hiding it until its org proves Go, means a Zen-only sign-in can never hide a working Go key or add a visible change for Zen users. The backoff stops Orca from asking a Zen-only org for Go usage on every 15-minute poll. OpenCode itself only checks when its usage panel opens. Reusing the reader worker gives the lookup the deadline and crash handling the Cursor profile read already has, where a second synchronous SQLite open would have broken the main-thread ratchet.

Linked Issue

Fixes #24818

Refs #38232, which covered part of this (falling back to the opencode OAuth access token). This PR also sends the org header, uses the active account, checks the token's server, skips expired tokens, accepts service-account keys, backs off Zen-only orgs, and reads the database off the main thread.

Visual Proof

N/A: no screenshot was captured. To get the "after" state you need a live OpenCode Console sign-in on an org that has a Go plan, and we had no such account for a disposable, background-launched build. The only visible change is that the existing OpenCode Go row in the Usage popover appears with its normal layout. Nothing about the row itself changed. The tests below cover the behaviour against a real OpenCode 2.4 credential schema.

Testing

  • src/main/foreign-sqlite-readers/readers/opencode-go-credential.test.ts runs the reader against a real temp SQLite file with OpenCode 2.4's credential DDL and fake tokens. It covers:

    • Found: an active Console OAuth sign-in (an older inactive row is ignored), and a service-account key.
    • A Go key wins over the sign-in.
    • Missing: no org, a foreign server, an expired token, an external sign-in, and other integrations.
  • src/main/rate-limits/providers/opencode-go/opencode-go-usage-source-selection.test.ts drives fetchOpenCodeGoUsage through the real reader (in-process worker) and a real OpenCode database via OPENCODE_DB, with XDG_DATA_HOME isolated. It covers:

    • Usage for the signed-in org when there is no Go key.
    • auth.json, OPENCODE_API_KEY and a session cookie all winning over the sign-in.
    • The row stays hidden until the org returns Go usage, then shows errors until Go is refused.
    • OPENCODE_API_KEY is withheld when the worker crashes.
    • A refused org isn't asked again on automated polls until the recheck interval, but is asked on a user refresh.
  • Run against main's source selection, the new selection tests fail (4 of 7 at the time of review): there is no Console tier and no backoff. All pass on this branch: vitest run src/main/foreign-sqlite-readers src/main/rate-limits/providers/opencode-go src/main/rate-limits/service gives 6 files and 35 tests passing.

  • The contributor checked end to end against a real OpenCode 2.4.2 database. The resolver picked the opencode-console-login tier with an org, the request carried x-opencode-org-id, and the live endpoint returned 200 with rolling, weekly and monthly windows.

  • Static gates on the touched files are clean: oxlint anti-slop and code-quality native plugins (--deny-warnings), ast-grep, check-changed-code-quality, oxfmt, check-main-blocking-api-ratchet (sqlite 718), and check-main-blocking-helper-ratchet.

  • Platforms: tested on macOS. Linux and Windows share the code path (no platform branches), and WSL UNC databases are still skipped as before.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

  • Every added test fails without this change and avoids the test anti-patterns

Performance

This is a net reduction in main-thread work on the rate-limit poll path. That path runs on a 15-minute default poll plus user refreshes, so it is not a hot path. The credential lookup is now one worker read per OpenCode database instead of four synchronous SQLite calls on main. Benchmark (node 24, synthetic WAL opencode.db with a writer held open, N=30 runs, numbers are p50/max):

rows old main-thread sync new main-thread sync (spawn) new async round trip event-loop max delay
2,000 0.079 / 0.338 ms 0.175 / 0.697 ms 13.4 / 28.9 ms (off main) 1.5 / 6.7 ms
50,000 0.071 / 0.278 ms 0.196 / 1.726 ms 14.9 / 43.5 ms (off main) 1.6 / 10.9 ms

The event-loop baseline with no worker is 1.3 ms. No stall reaches 16 ms. The worker lane idles out after 30 s. A Console sign-in adds no requests beyond the one existing usage call, and Zen-only orgs are asked at most once every 6 hours by automated polls (previously they weren't asked at all, because there was no tier). There is no renderer or store change, so nothing scales with the number of tabs or worktrees. config/main-blocking-helper-baseline.txt raises foreign-sqlite-reader-spawn.ts from 5 to 6 for the existing worker-entry stat at spawn. This replaces the four main-thread SQLite uses removed above.

Risk

Level: Low

  • Only OpenCode Go usage changes, and only on OpenCode 2 when no other OpenCode Go credential is configured. Setups with a Settings override, a Go key, auth.json, OPENCODE_API_KEY or a session cookie resolve exactly as before.
  • If the sign-in's OAuth token has expired, the row stays hidden until OpenCode renews it (any OpenCode use does). If a first poll from an unproven org fails in transport, the row stays hidden for up to an hour, or until a manual refresh.
  • OpenCode's database is opened read-only with query_only. Nothing is written, and the token stays in the Authorization header (never logged, returned or sent in telemetry).
  • To back out, a plain revert works. The baseline rows revert with it.

Review

  • Security: the worker result is validated (printable ASCII token, [A-Za-z0-9_-] org) before it becomes header text. Tokens from non-opencode.ai consoles are ignored, and expired tokens are never refreshed.
  • SSH/remote: the same main-process code runs for every usage owner. Zen-only owners get the same missing-credentials result as before, so the "not set up on host" logic doesn't change.
  • Mobile: not affected.
  • Backwards compatibility: OpenCode 1 lookups, the Settings override and the env key are untouched.

Original fix by @luisgonzaleznf in #52034. Review follow-ups (Console tier after every Go key, session cookie precedence, Zen-only org backoff, separate resolution type) were squashed into this commit, and authorship is preserved.

Agent skill upstream boundary

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

Notes

Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • I stated the risk: what could break, for whom, and how to back it out
  • 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, and pnpm build pass (or CI will cover; local preferred)

@greptile-apps

greptile-apps Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Confidence Score: 4/5 · Exclude explicitly inactive Console credentials before merging.RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The changes affect the OpenCode Go usage workflow.

Exclude explicitly inactive Console credentials before merging.

Findings

  1. P1 Inactive account usage appears ▶

Summary

Adds OpenCode Go usage through OpenCode 2 Console sign-ins and moves credential reads into the existing SQLite worker.

  • OpenCode Go usage can come from an active OpenCode Console sign-in.
  • OpenCode credential reads run in a worker instead of the main thread.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Resolve Go credentials] --> B{Existing Go key?}
  B -->|Yes| C[Request Go usage with key]
  B -->|No| D[Read Console sign-in in worker]
  D --> E{Session cookie configured?}
  E -->|Yes| F[Keep cookie usage path]
  E -->|No| G{Org backoff active?}
  G -->|Yes| H[Keep Console account hidden]
  G -->|No or forced refresh| I[Request usage with token and org]
  I --> J{Go usage returned?}
  J -->|Yes| K[Show Go usage]
  J -->|No| L[Update org verdict and backoff]
Loading

Reviews (4) · Last reviewed commit: "fix(opencode-go): show OpenCode Go usage..." · Reviewed by Greptile

@coderabbitai

coderabbitai Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Walkthrough

The change moves OpenCode Go credential database reads to a SQLite worker and adds support for OpenCode Console credentials with organization IDs. The API-key source uses the worker results to distinguish Console logins from other database credentials. Usage requests include the organization ID when available. Console login results are reported as confirmed only after Go access is established. The usage flow also adds organization-level backoffs and forced refresh handling.

Severity of issue fixed: Medium

Merge Risk: Low · up to 66a29

An OpenCode 2 account that has been switched away from can still supply the credential for Go usage if it is the only Console sign-in stored. This shows usage for the wrong account, and the fix is a one-line query filter. The rest of the change looks sound, and the risk is limited.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "fix(opencode-go): show OpenCode Go usage for OpenCode 2 Console sign-ins" names the main change. The changeset adds a reader for the OpenCode 2 Console sign-in (the opencode credential ro…
Description check Passed The description follows the repository template and covers each required section: ELI5, What Changed, Why, Linked Issue (Fixes #24818), Visual Proof, Testing, Performance, Risk (Level: Low), AI Disclo…
Linked Issues check Passed [#24818] Objective: the user can view OpenCode Go usage after updating OpenCode Go, without relying only on the older Go key lookup. The issue gives no further acceptance criteria. The change addresse…
Out of Scope Changes check Passed The changes support the #24818 objective. Worker lane files (foreign-sqlite-reader-client, -dispatch, -protocol, -spawn) add the openCodeGoCredential request. opencode-go-credential-result.ts validate…
Full details: Title check

Explanation

The title "fix(opencode-go): show OpenCode Go usage for OpenCode 2 Console sign-ins" names the main change. The changeset adds a reader for the OpenCode 2 Console sign-in (the opencode credential row), wires it into usage-source selection as a last-resort tier, and adds the x-opencode-org-id header. The title is specific and matches the linked issue #24818. It does not mention the worker move or the baseline change, which is expected for a title.

Full details: Description check

Explanation

The description follows the repository template and covers each required section: ELI5, What Changed, Why, Linked Issue (Fixes #24818), Visual Proof, Testing, Performance, Risk (Level: Low), AI Disclosure, Review, and Checklist. It explains the root cause, the mechanism, the worker move, the fallback order, and the back-out path. The Visual Proof section says the screenshot is still to be attached, and one checklist item for screenshots is unchecked. The Performance section flags the baseline change for reviewer sign-off. Those gaps are minor and do not make the description incomplete.

Full details: Linked Issues check

Explanation

[#24818] Objective: the user can view OpenCode Go usage after updating OpenCode Go, without relying only on the older Go key lookup. The issue gives no further acceptance criteria. The change addresses the OpenCode 2 Console sign-in case. The reader in readers/opencode-go-credential.ts reads the active opencode credential (OAuth access token or service-account key) with metadata.orgID, after checking expiry and server. opencode-go-usage-api.ts sends the token with x-opencode-org-id. opencode-go-usage-source-selection.ts shows the row once Go usage is returned for that org. Existing Go key, auth.json, env key and cookie paths keep their order. Tests cover reader selection, rejection cases and the hide-until-proven state machine. Limits: validation was performed on macOS only. The issue reports Windows, but the requirement is not platform-specific. The screenshot is pending and is not a coding requirement. This verdict relies on the change summary and PR description; no repository inspection was performed.

Full details: Out of Scope Changes check

Explanation

The changes support the #24818 objective. Worker lane files (foreign-sqlite-reader-client, -dispatch, -protocol, -spawn) add the openCodeGoCredential request. opencode-go-credential-result.ts validates the worker result. opencode-go-api-key-source.ts moves the read off the main thread and adds the console-login tier. opencode-go-usage-api.ts adds the org header and the 403 classification for org requests. The source-selection module adds the proven-Go gating, backoff and force option. service-full-cycle-preparation.ts passes force through to that option. The baseline files remove the old SQLite allowance and raise the helper count by one with a note. The baseline change follows from the new worker call and needs reviewer sign-off under the ratchet rule. The credential-record parser now accepts only type api, and the callers no longer pass an expected type. This is a refactor inside the same resolver, and it supports the new tier. Its effect on OpenCode 1 callers was not traced in this assessment. The prompt-failure lane timeout changes from 2 seconds to 2,000 ms, an equivalent value. No unrelated change was identified from the summary.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@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

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d2022922-798e-4fed-aed6-710200d1bb4e
Commits

Reviewing files that changed from the base of the PR and between ef41c14 and 8f61901.

Files selected for processing: 12

  • config/main-blocking-helper-baseline.txt
  • config/main-blocking-sqlite-baseline.txt
  • src/main/foreign-sqlite-readers/foreign-sqlite-reader-client.ts
  • src/main/foreign-sqlite-readers/foreign-sqlite-reader-dispatch.ts
  • src/main/foreign-sqlite-readers/foreign-sqlite-reader-protocol.ts
  • src/main/foreign-sqlite-readers/foreign-sqlite-reader-spawn.ts
  • src/main/foreign-sqlite-readers/opencode-go-credential-result.ts
  • src/main/foreign-sqlite-readers/readers/opencode-go-credential.test.ts
  • src/main/foreign-sqlite-readers/readers/opencode-go-credential.ts
  • src/main/rate-limits/providers/opencode-go/opencode-go-api-key-source.ts
  • src/main/rate-limits/providers/opencode-go/opencode-go-usage-api.ts
  • src/main/rate-limits/providers/opencode-go/opencode-go-usage-source-selection.ts
Files with no reviewable changes: 1

  • config/main-blocking-sqlite-baseline.txt

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

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

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e78bfcdc-4661-41e8-8c92-2b9f5cd5762d
Commits

Reviewing files that changed from the base of the PR and between 8f61901 and c786e53.

Files selected for processing: 3

  • src/main/rate-limits/providers/opencode-go/opencode-go-api-key-source.ts
  • src/main/rate-limits/providers/opencode-go/opencode-go-usage-source-selection.test.ts
  • src/main/rate-limits/providers/opencode-go/opencode-go-usage-source-selection.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

OpenCode 2 stores a /connect Console sign-in as an `opencode` credential
(OAuth access token or service-account key, scoped by metadata.orgID)
instead of an OpenCode Go key, so Orca found no credential and hid the
OpenCode Go usage row.

Read the active Console sign-in as a last-resort tier, after every Go
key, auth.json and OPENCODE_API_KEY, and call the Go usage endpoint with
its token and the x-opencode-org-id header, the same way OpenCode does.
Only opencode.ai-issued, unexpired tokens are used, and Orca never
refreshes them. A configured session cookie still wins over an unproven
sign-in, and an org stays hidden until it returns Go usage, so Zen-only
accounts look exactly as before.

The OpenCode credential lookup moves off the main thread into the
foreign SQLite reader worker as a new openCodeGoCredential lane; a worker
timeout or crash maps to `unreadable`, preserving the stablyai#24605 behaviour.

Fixes stablyai#24818

Co-authored-by: Neil <[email protected]>
@nwparker
nwparker force-pushed the luisgonzaleznf/opencode-go-console-login branch from cf93604 to 66a2978 Compare November 28, 2026 23:28
const login = credentialValue(
db
.prepare(
`SELECT value FROM credential WHERE integration_id = ? ${CREDENTIAL_ORDER} LIMIT 1`

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 Inactive account usage appears

When the database contains only inactive opencode credentials, this query still selects one. Sorting by active does not exclude active = 0, and consoleCredential never checks that flag. Orca can therefore request and display Go usage for an account the user switched away from, contrary to the PR’s active-account requirement.

Exclude explicitly inactive rows and add an inactive-only test.

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

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 061ec150-ae80-418c-b5d8-fca1aa4faaed
Commits

Reviewing files that changed from the base of the PR and between cf93604 and 66a2978.

Files selected for processing: 7

  • src/main/foreign-sqlite-readers/readers/opencode-go-credential.test.ts
  • src/main/foreign-sqlite-readers/readers/opencode-go-credential.ts
  • src/main/rate-limits/providers/opencode-go/opencode-go-api-key-source.ts
  • src/main/rate-limits/providers/opencode-go/opencode-go-usage-api.ts
  • src/main/rate-limits/providers/opencode-go/opencode-go-usage-source-selection.test.ts
  • src/main/rate-limits/providers/opencode-go/opencode-go-usage-source-selection.ts
  • src/main/rate-limits/service/service-full-cycle-preparation.ts

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

const login = credentialValue(
db
.prepare(
`SELECT value FROM credential WHERE integration_id = ? ${CREDENTIAL_ORDER} LIMIT 1`

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.

Minor · Functional Correctness · Quick win

Exclude explicitly inactive Console credentials.

If the database contains only an opencode row with active=0, this query selects it. consoleCredential then accepts its token and organization. Orca can therefore request and display usage for an inactive account.

Exclude explicitly inactive rows. Preserve support for active rows and legacy rows with active IS NULL. The PR objective excludes fallback to inactive accounts.

@nwparker
nwparker merged commit 37276c8 into stablyai:main Nov 28, 2026
59 checks passed
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]: Can't view opencode go usage

2 participants