Skip to content

feat(auth): add provider pool and multi-account management - #1270

Open
yansigit wants to merge 37 commits into
1jehuang:masterfrom
yansigit:feat/provider-pool-account-management-upstream
Open

yansigit wants to merge 37 commits into
1jehuang:masterfrom
yansigit:feat/provider-pool-account-management-upstream

Conversation

@yansigit

@yansigit yansigit commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds a provider-scoped account pool for authenticated providers, with durable metadata, safe account selection, quota-aware ranking, cooldowns, leases, failover, and account-management UI/CLI flows.

Closes #1238
Closes #1239
Refs #1130

Categorized changes

  • Storage and security: metadata-only managed account records, native credential separation, migration-safe persistence, no plaintext credential backups, and cross-process locking.
  • Routing and reliability: active-account overrides, quota/history scoring, cooldown persistence, leases, concurrent update safety, request-local failover, and retry-after handling.
  • Provider integrations: OpenAI/Codex, Cursor, and Antigravity account discovery, switching, usage, and quota presentation.
  • User experience: account center, shorthand switching, picker flows, diagnostics, and explicit quota capability semantics.

Validation

  • Rebased on current upstream/master and zero commits behind it.
  • scripts/dev_cargo.sh check -p jcode --bin jcode passed from the final rebased branch.
  • Focused provider-pool, account picker, quota, lease, and credential migration coverage is included in the branch.
  • The published fork branch and PR head now point to the same verified commit.

Scope notes

#1130 describes a broader Anthropic streaming failover report. This PR shares the account-first cooldown, lease, retry-after, and request-local failover foundation, but references rather than closes that issue because not every Anthropic-specific streaming behavior is claimed here.

@greptile-apps

greptile-apps Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 0/5

[Critical impact] Adds multi-account management and credential storage to auth system.

Do not merge yet: credential persistence, account identity, account-choice controls, API-key routing, and retry selection have blocking correctness issues, and three earlier issues remain partially addressed.

Findings

  1. P1 Separate homes share credentials ▶
  2. P1 Disabled account rotation still runs ▶
  3. P1 API-key requests change login ▶
  4. P1 Healthy accounts go untried ▶
  5. P1 Imported account labels collide ▶
  6. P1 Old credentials return ▶
  7. P1 Restore rotated credentials ▶
  8. P1 Make credential writes atomic ▶
  9. P1 Handle streamed failures ▶
  10. P2 Missing quotas get invented ▶
  11. P2 Quota follows the wrong account ▶
  12. P2 Retries share a busy account ▶
  13. P2 Cursor recovery command fails ▶
  14. P2 Long labels block failover ▶
Fix with agent prompt
### Issue 1
crates/jcode-storage/src/lib.rs:566
Production uses the same native service and raw key for every `JCODE_HOME`; only tests add the home to the key. Saving Cursor or Antigravity credentials in an isolated home can overwrite the normal home's credentials. Removing an imported account can also delete credentials another home still uses. Scope production keys to the resolved home.

### Issue 2
crates/jcode-provider-openai-runtime/src/openai_provider_impl.rs:721-728
OpenAI stream rotation and Antigravity runtime failover can try another account after an auth or quota error even when `same_provider_account_failover` is disabled. Antigravity also reads all saved accounts instead of honoring `AccountPool` exclusions. Apply the existing setting and allowed-account selection before retrying so requests respect the user's account choices.

### Issue 3
crates/jcode-provider-openai-runtime/src/openai_provider_impl.rs:88-99
After an API-key auth or quota error, `try_rotate_openai_account` can load saved OAuth credentials without checking `credential_mode_snapshot()`. It replaces the shared credentials, and the next attempt chooses its endpoint from those credentials. An explicitly selected `openai-api` request can therefore move to ChatGPT/Codex under another login. Keep API-key mode pinned during retries.

### Issue 4
crates/jcode-provider-openai-runtime/src/openai_provider_impl.rs:78-81
`attempted_accounts` starts empty, and each rotation checks only the first preferred candidate. With saved order A, B, C and no usable quota snapshot, failures can produce A → B → A. Both rotations are spent without trying healthy C. Seed the set with the starting account and choose the first untried account from the full candidate list.

### Issue 5
crates/jcode-base/src/auth/provider_pool.rs:1110-1114
Aliases `Work Email` and `Work-Email` both become `cursor-Work-Email`. `upsert_account` accepts both accounts because it checks IDs, but loading and switching find the first account by label. The second account cannot be selected; importing it as active selects the first account's credentials. Make labels unique within each provider.

### Issue 6
crates/jcode-base/src/auth/cursor.rs:326-329
If the native store becomes temporarily unavailable after an earlier save, `save_api_key` writes the new key to `cursor.env` but leaves the old native value untouched. When native reads work again, `load_api_key` prefers that old value. Antigravity uses the same save/load order, so an old refresh token can return too. Track which store holds the latest value instead of always preferring native storage.

### Issue 7
crates/jcode-provider-openai-runtime/src/openai_provider_impl.rs:undefined-98
When a stream rotates after an authentication or quota failure, this replaces the shared runtime credentials but leaves the selected account label unchanged. Nothing restores the original credentials when the stream ends, so later requests and prewarms can use the alternate account while the UI and usage reporting still identify the original account.

### Issue 8
crates/jcode-base/src/auth/provider_pool.rs:undefined-521
Credential values are written to native storage before the metadata file is published, with no rollback if metadata publication fails. For example, a disk-full or permission error while updating an existing account can leave the old metadata pointing at newly replaced credentials; a new account can instead leave orphaned secrets. Stage or reconcile both stores so a failed save cannot partially update an account.

### Issue 9
crates/jcode-base/src/provider/dispatch.rs:44-51
The wrapper forwards `Some(Err(_))` without invoking account or provider failover, while Cursor starts its network operation only after returning an event stream. Cursor transport, authentication, and quota failures therefore bypass the new same-provider failover path, and the user receives the original error without trying another pooled account.

### Issue 10
crates/jcode-base/src/usage/cursor.rs:243-248
A monthly-only `planUsage` response containing spend and limit produces identical Monthly, Auto, and API windows because `percent_from_object` applies `pair(object)` to the monthly object for all three scopes. The fallback parser also fills absent scopes from generic percentages elsewhere in the response. These values are saved as account quota observations. This is non-blocking, but users see Auto/API usage the provider did not report, and later account comparisons use those invented observations. Read each window only from its own fields and leave missing quota unknown.

### Issue 11
crates/jcode-base/src/usage/provider_fetch.rs:482-485
Antigravity reads the active label after the network request. Switching from account A to B while polling waits therefore saves quota fetched with A's credentials under B. The executed switch succeeded and replaced B's 900-milli remaining quota with A's 100-milli response. This is non-blocking, but it misreports B's capacity and gives later account ranking the wrong data. Capture the account before fetching and use its account-specific credentials and label throughout.

### Issue 12
crates/jcode-provider-antigravity-runtime/src/lib.rs:112-119
Antigravity's runtime failover sends an alternate-account request without acquiring its `AccountLease`. After a primary HTTP 429, the executed retry used an alternate whose lease was still held by another process. This is non-blocking, but concurrent processes can send retries through an account that shared failover would skip, defeating the pool's busy-account admission behavior. Acquire and hold an `AccountLease` for each alternate attempt.

### Issue 13
crates/jcode-base/src/usage/model.rs:364
Cursor guidance emits `/account switch <label>`, but that shorthand only searches Claude and OpenAI accounts. Following it returns “No Anthropic or OpenAI account” instead of switching. This is non-blocking, but it makes the suggested recovery step unusable. Emit `/account cursor switch <label>`, which the new provider-specific path supports.

```suggestion
            Self::Cursor => format!("/account cursor switch {}", label),
```

### Issue 14
crates/jcode-base/src/auth/provider_pool.rs:107-110
`lease_path_component` doubles every label byte, and imported labels have no length limit. On a filesystem with a 255-byte filename limit, a 120-character Cursor alias produces an oversized lock filename. Opening it fails, so shared failover treats the account as already leased and skips it. This is non-blocking for ordinary labels, but long aliases never work as alternates. Use a bounded hash for the filename.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

T-Rex evidence

Evidence from the check

  • Compiles revision-specific application source and runs separate-process persistence checks with an isolated file-backed backend, making the reproduction repeatable without Cargo builds.

Evidence from the check

  • Contains the generated Rust used for the base standalone save/read comparison, showing the exact executed control code.

Evidence from the check

  • Contains the generated Rust with production managed-account persistence code and the controlled credential backend, showing the exact executed reproduction.

Command output from the check

  • Captures the rustc command compiling storage source from the specified base revision and exit zero, establishing successful control compilation.

Command output from the check

  • Captures the rustc command linking the base persistence harness and exit zero, establishing successful control executable creation.

Command output from the check

  • Captures the rustc command compiling head storage source with the keyring-core backend substitution and exit zero, documenting the precise execution boundary.

Command output from the check

  • Captures the rustc command linking the head persistence harness and exit zero, establishing successful reproduction executable creation.

Command output from the check

  • Runs saves and reads in separate processes under two homes at the specified base revision, showing that each home retains its own tokens.

Command output from the check

  • Runs standalone and managed-account saves, reads, and removal across two homes at head, showing cross-home token overwrite and credential deletion.

Command output from the check

  • Captures numbered application and keyring source excerpts plus a clean diff for the relevant tracked files, showing the missing production home namespace and unchanged reviewed source.

Evidence from the check

  • The authored runner selects the requested runtime revisions, invokes serial Cargo probes, captures their output, and restores temporary source edits; completion of its latest run is unverified.

Evidence from the check

  • The authored Rust probe exercises real provider streams with isolated credentials and records structured HTTP responses; completed endpoint observations are still needed.

Command output from the check

  • A command captured the initial authored runner and Rust probe with command, working directory, and exit code; the separately saved runner contains subsequent corrections.

Command output from the check

  • The base-runtime probe command exited 101 on an unresolved usage-type import before making an HTTP request; this blocker does not disprove the candidate.

Command output from the check

  • Executed Git commands captured the requested runtime diff and account-policy source with command metadata; the retry paths appear to omit the required policy checks.

▶ candidate9-01-before.webm

  • The flow T-Rex ran, recorded end to end.

Before: Candidate9 01

  • What the screen looked like at this point in the check.

▶ candidate9-02-after.webm

  • The flow T-Rex ran, recorded end to end.

After: Candidate9 02

  • What the screen looked like at this point in the check.

Evidence from the check

  • The generated Rust test creates isolated synthetic accounts and captures real loopback HTTP traffic; its current-thread runtime must be corrected before rotation can be conclusively validated.

Evidence from the check

  • The Python runner builds and tests clean base and head worktrees sequentially, captures source hashes and temporary instrumentation, and restores its changes; it makes the attempted comparison reproducible.

Command output from the check

  • The base revision received synthetic HTTP 403 Forbidden responses and surfaced the API error without a ChatGPT request; this establishes the observed baseline.

Command output from the check

  • The head revision received the same synthetic HTTP 403 Forbidden responses but its usage probe panicked before an OAuth retry; the candidate remains inconclusive.

Command output from the check

  • The captured runner output records waiting for existing compilers and executing both revision tests with their results; it documents the actual attempt rather than a predicted outcome.

Evidence from the check

  • The executed Python driver installs each original implementation temporarily, runs the same harness sequentially, captures command output, and restores the source.

Evidence from the check

  • The executed Rust test saves three synthetic accounts and sends real provider requests to a loopback endpoint, demonstrating the automatic sequence and a successful C control.

Command output from the check

  • The base implementation was executed against the synthetic endpoint and captured A returning 401 Unauthorized followed by the direct C control returning 200 OK.

Command output from the check

  • The head implementation was executed against the same endpoint and captured A → B → A returning 401 Unauthorized while the direct C control returned 200 OK, confirming the missed working account.

Evidence from the check

  • The base implementation is preserved with its temporary harness include, identifying the underlying source used for the before capture.

Evidence from the check

  • The head implementation is preserved with its temporary harness include, identifying the underlying source used for the confirmed A → B → A capture.

Command output from the check

  • Executed Git source extraction and comparison captured the selection logic and verified that the tested provider source was restored byte-for-byte.

Evidence from the check

  • Compiles revision-specific application source and runs separate-process persistence checks with an isolated file-backed backend, making the reproduction repeatable without Cargo builds.

Evidence from the check

  • Contains the generated Rust used for the base standalone save/read comparison, showing the exact executed control code.

Evidence from the check

  • Contains the generated Rust with production managed-account persistence code and the controlled credential backend, showing the exact executed reproduction.

Command output from the check

  • Captures the rustc command compiling storage source from the specified base revision and exit zero, establishing successful control compilation.

Command output from the check

  • Captures the rustc command linking the base persistence harness and exit zero, establishing successful control executable creation.

Command output from the check

  • Captures the rustc command compiling head storage source with the keyring-core backend substitution and exit zero, documenting the precise execution boundary.

Command output from the check

  • Captures the rustc command linking the head persistence harness and exit zero, establishing successful reproduction executable creation.

Command output from the check

  • Runs saves and reads in separate processes under two homes at the specified base revision, showing that each home retains its own tokens.

Command output from the check

  • Runs standalone and managed-account saves, reads, and removal across two homes at head, showing cross-home token overwrite and credential deletion.

Command output from the check

  • Captures numbered application and keyring source excerpts plus a clean diff for the relevant tracked files, showing the missing production home namespace and unchanged reviewed source.

Evidence from the check

  • The authored runner selects the requested runtime revisions, invokes serial Cargo probes, captures their output, and restores temporary source edits; completion of its latest run is unverified.

Evidence from the check

  • The authored Rust probe exercises real provider streams with isolated credentials and records structured HTTP responses; completed endpoint observations are still needed.

Command output from the check

  • A command captured the initial authored runner and Rust probe with command, working directory, and exit code; the separately saved runner contains subsequent corrections.

Command output from the check

  • The base-runtime probe command exited 101 on an unresolved usage-type import before making an HTTP request; this blocker does not disprove the candidate.

Command output from the check

  • Executed Git commands captured the requested runtime diff and account-policy source with command metadata; the retry paths appear to omit the required policy checks.

Evidence from the check

  • The generated Rust test creates isolated synthetic accounts and captures real loopback HTTP traffic; its current-thread runtime must be corrected before rotation can be conclusively validated.

Evidence from the check

  • The Python runner builds and tests clean base and head worktrees sequentially, captures source hashes and temporary instrumentation, and restores its changes; it makes the attempted comparison reproducible.

Command output from the check

  • The base revision received synthetic HTTP 403 Forbidden responses and surfaced the API error without a ChatGPT request; this establishes the observed baseline.

Command output from the check

  • The head revision received the same synthetic HTTP 403 Forbidden responses but its usage probe panicked before an OAuth retry; the candidate remains inconclusive.

Command output from the check

  • The captured runner output records waiting for existing compilers and executing both revision tests with their results; it documents the actual attempt rather than a predicted outcome.

Evidence from the check

  • The executed Python driver installs each original implementation temporarily, runs the same harness sequentially, captures command output, and restores the source.

Evidence from the check

  • The executed Rust test saves three synthetic accounts and sends real provider requests to a loopback endpoint, demonstrating the automatic sequence and a successful C control.

Command output from the check

  • The base implementation was executed against the synthetic endpoint and captured A returning 401 Unauthorized followed by the direct C control returning 200 OK.

Command output from the check

  • The head implementation was executed against the same endpoint and captured A → B → A returning 401 Unauthorized while the direct C control returned 200 OK, confirming the missed working account.

Evidence from the check

  • The base implementation is preserved with its temporary harness include, identifying the underlying source used for the before capture.

Evidence from the check

  • The head implementation is preserved with its temporary harness include, identifying the underlying source used for the confirmed A → B → A capture.

Command output from the check

  • Executed Git source extraction and comparison captured the selection logic and verified that the tested provider source was restored byte-for-byte.

View artifacts

Summary

Adds provider-scoped account storage and management for Cursor and Antigravity, plus quota-aware selection and account failover.

  • Cursor and Antigravity accounts can be stored and managed separately.
  • Account views show provider usage and per-model quota snapshots.
  • Requests can retry on another eligible Cursor or Antigravity account.
  • OpenAI requests can rotate across accounts when an account runs out.
  • The account center lets users browse and switch managed accounts.
  • Build and platform-specific cleanup leaves user-visible behavior unchanged.

T-Rex validation blocked

  • Disabled rotation and excluded-account behavior: HTTP execution did not complete after an unresolved CursorUsageSemantics import; the subsequent retry had no observed completion.
  • API-key routing during rotation: the head reached a usage-probe panic because the test's current-thread Tokio runtime did not support block_in_place; the OAuth retry could not be observed.
  • Long-alias failover: harness compilation failed on a missing copied test file, incompatible cached dependency variants, and missing imports.

Reviews (3) · Last reviewed commit: "fix(storage): import Mutex once on Windo..." · Reviewed by Greptile

return None;
}
};
*credentials.write().await = next;

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.

P1 Restore rotated credentials

When a stream rotates after an authentication or quota failure, this replaces the shared runtime credentials but leaves the selected account label unchanged. Nothing restores the original credentials when the stream ends, so later requests and prewarms can use the alternate account while the UI and usage reporting still identify the original account.

Knowledge Base Used:

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-provider-openai-runtime/src/openai_provider_impl.rs
Line: 58

Comment:
**Restore rotated credentials**

When a stream rotates after an authentication or quota failure, this replaces the shared runtime credentials but leaves the selected account label unchanged. Nothing restores the original credentials when the stream ends, so later requests and prewarms can use the alternate account while the UI and usage reporting still identify the original account.

**Knowledge Base Used:**
- [Authentication and account management](https://app.greptile.com/solo-systems/-/custom-context/knowledge-base/1jehuang/jcode/-/docs/authentication-and-account-management.md)
- [Provider selection and runtime adapters](https://app.greptile.com/solo-systems/-/custom-context/knowledge-base/1jehuang/jcode/-/docs/provider-selection-and-runtime-adapters.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

}

fn write_unlocked(provider: &str, file: &AccountFile) -> Result<()> {
let persisted = PersistedAccountFile::from_managed(provider, file)?;

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.

P1 Make credential writes atomic

Credential values are written to native storage before the metadata file is published, with no rollback if metadata publication fails. For example, a disk-full or permission error while updating an existing account can leave the old metadata pointing at newly replaced credentials; a new account can instead leave orphaned secrets. Stage or reconcile both stores so a failed save cannot partially update an account.

Knowledge Base Used: Authentication and account management

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-base/src/auth/provider_pool.rs
Line: 521

Comment:
**Make credential writes atomic**

Credential values are written to native storage before the metadata file is published, with no rollback if metadata publication fails. For example, a disk-full or permission error while updating an existing account can leave the old metadata pointing at newly replaced credentials; a new account can instead leave orphaned secrets. Stage or reconcile both stores so a failed save cannot partially update an account.

**Knowledge Base Used:** [Authentication and account management](https://app.greptile.com/solo-systems/-/custom-context/knowledge-base/1jehuang/jcode/-/docs/authentication-and-account-management.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +44 to +48
let item = self.inner.as_mut().poll_next(context);
if matches!(item, Poll::Ready(None)) {
self.account_lease = None;
}
item

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.

P1 Handle streamed failures

The wrapper forwards Some(Err(_)) without invoking account or provider failover, while Cursor starts its network operation only after returning an event stream. Cursor transport, authentication, and quota failures therefore bypass the new same-provider failover path, and the user receives the original error without trying another pooled account.

Knowledge Base Used:

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-base/src/provider/dispatch.rs
Line: 44-48

Comment:
**Handle streamed failures**

The wrapper forwards `Some(Err(_))` without invoking account or provider failover, while Cursor starts its network operation only after returning an event stream. Cursor transport, authentication, and quota failures therefore bypass the new same-provider failover path, and the user receives the original error without trying another pooled account.

**Knowledge Base Used:**
- [Model provider integration](https://app.greptile.com/solo-systems/-/custom-context/knowledge-base/1jehuang/jcode/-/docs/provider-integration.md)
- [Provider selection and runtime adapters](https://app.greptile.com/solo-systems/-/custom-context/knowledge-base/1jehuang/jcode/-/docs/provider-selection-and-runtime-adapters.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment thread src/cli/args.rs Resolved
@yansigit
yansigit force-pushed the feat/provider-pool-account-management-upstream branch from 0656752 to c84657c Compare September 16, 2026 01:53
@greptile-apps

greptile-apps Bot commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

Want your agent to iterate on Greptile's feedback? Try greploops.

@github-actions github-actions Bot added area: providers Model providers, API adapters, and provider authentication. area: tui Terminal user interface, rendering, and interactions. platform: windows Windows-specific behavior or compatibility. security Security hardening or security-sensitive changes. type: feature Adds a new user-facing capability. labels Sep 19, 2026
cursoragent and others added 5 commits October 12, 2026 22:01
…l-account-management-upstream

# Conflicts:
#	Cargo.lock
#	crates/jcode-base/src/auth/codex_tests.rs
#	crates/jcode-base/src/auth/cursor.rs
#	crates/jcode-base/src/provider/account_failover.rs
#	crates/jcode-base/src/provider/tests/catalog_subscription.rs
#	crates/jcode-base/src/usage.rs
#	crates/jcode-base/src/usage/provider_fetch.rs
#	crates/jcode-provider-core/src/retry_after.rs
#	crates/jcode-provider-cursor-runtime/src/agent_transport.rs
#	crates/jcode-provider-cursor-runtime/src/lib.rs
#	crates/jcode-provider-openai-runtime/src/lib.rs
#	crates/jcode-provider-openai-runtime/src/openai_provider_impl.rs

Co-authored-by: SB Yoon <[email protected]>
Refresh inactive Antigravity quotas on the selected account, restore OpenAI credentials and labels after a stream rotation, and lock account files on every platform. Cursor startup failures now return before the stream so same-provider failover can run, and pooled Cursor or Antigravity accounts can be removed.

Co-authored-by: SB Yoon <[email protected]>
Rustfmt the module and import order current stable rustfmt requires, keep the companion listener mutable only on Windows, and compile the niri Deserialize import only where those types exist. Upgrade quinn-proto to 0.11.19 so the current RustSec advisories clear.

Co-authored-by: SB Yoon <[email protected]>
Replace the newline write, the infallible lock match, and the nested device and capture checks that stable clippy denies.

Co-authored-by: SB Yoon <[email protected]>
The native credential helper imports Mutex on every platform, so the Windows-only import collided with it and the Windows build stopped.

Co-authored-by: SB Yoon <[email protected]>
if key.is_empty() || key.len() > 256 || key.chars().any(|ch| ch.is_control()) {
anyhow::bail!("invalid native credential key");
}
keyring::Entry::new(NATIVE_CREDENTIAL_SERVICE, key)

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.

P1 Separate homes share credentials

Production uses the same native service and raw key for every JCODE_HOME; only tests add the home to the key. Saving Cursor or Antigravity credentials in an isolated home can overwrite the normal home's credentials. Removing an imported account can also delete credentials another home still uses. Scope production keys to the resolved home.

Knowledge Base Used: Authentication and account management

Artifacts

Evidence from the check

  • Compiles revision-specific application source and runs separate-process persistence checks with an isolated file-backed backend, making the reproduction repeatable without Cargo builds.

Evidence from the check

  • Contains the generated Rust used for the base standalone save/read comparison, showing the exact executed control code.

Evidence from the check

  • Contains the generated Rust with production managed-account persistence code and the controlled credential backend, showing the exact executed reproduction.

Command output from the check

  • Captures the rustc command compiling storage source from the specified base revision and exit zero, establishing successful control compilation.

Command output from the check

  • Captures the rustc command linking the base persistence harness and exit zero, establishing successful control executable creation.

Command output from the check

  • Captures the rustc command compiling head storage source with the keyring-core backend substitution and exit zero, documenting the precise execution boundary.

Command output from the check

  • Captures the rustc command linking the head persistence harness and exit zero, establishing successful reproduction executable creation.

Command output from the check

  • Runs saves and reads in separate processes under two homes at the specified base revision, showing that each home retains its own tokens.

Command output from the check

  • Runs standalone and managed-account saves, reads, and removal across two homes at head, showing cross-home token overwrite and credential deletion.

Command output from the check

  • Captures numbered application and keyring source excerpts plus a clean diff for the relevant tracked files, showing the missing production home namespace and unchanged reviewed source.

View artifacts

T-Rex Ran code and verified through T-Rex

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-storage/src/lib.rs
Line: 566

Comment:
**Separate homes share credentials**

Production uses the same native service and raw key for every `JCODE_HOME`; only tests add the home to the key. Saving Cursor or Antigravity credentials in an isolated home can overwrite the normal home's credentials. Removing an imported account can also delete credentials another home still uses. Scope production keys to the resolved home.

**Knowledge Base Used:** [Authentication and account management](https://app.greptile.com/solo-systems/-/custom-context/knowledge-base/1jehuang/jcode/-/docs/authentication-and-account-management.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +721 to +728
if is_account_rotation_error(&error)
&& account_attempt < MAX_ACCOUNT_ROTATIONS
&& let Some(account) = try_rotate_openai_account(
&credentials,
&mut attempted_accounts,
&mut account_restore,
)
.await

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.

P1 Disabled account rotation still runs

OpenAI stream rotation and Antigravity runtime failover can try another account after an auth or quota error even when same_provider_account_failover is disabled. Antigravity also reads all saved accounts instead of honoring AccountPool exclusions. Apply the existing setting and allowed-account selection before retrying so requests respect the user's account choices.

Knowledge Base Used: Authentication and account management

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-provider-openai-runtime/src/openai_provider_impl.rs
Line: 721-728

Comment:
**Disabled account rotation still runs**

OpenAI stream rotation and Antigravity runtime failover can try another account after an auth or quota error even when `same_provider_account_failover` is disabled. Antigravity also reads all saved accounts instead of honoring `AccountPool` exclusions. Apply the existing setting and allowed-account selection before retrying so requests respect the user's account choices.

**Knowledge Base Used:** [Authentication and account management](https://app.greptile.com/solo-systems/-/custom-context/knowledge-base/1jehuang/jcode/-/docs/authentication-and-account-management.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +88 to +99
let next = match jcode_base::auth::codex::load_credentials_for_account(&candidate) {
Ok(next) => next,
Err(error) => {
jcode_base::logging::info(&format!(
"OpenAI stream account rotation could not load '{}': {}",
candidate, error
));
return None;
}
};
*credentials.write().await = next;
restore.note(&candidate);

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.

P1 API-key requests change login

After an API-key auth or quota error, try_rotate_openai_account can load saved OAuth credentials without checking credential_mode_snapshot(). It replaces the shared credentials, and the next attempt chooses its endpoint from those credentials. An explicitly selected openai-api request can therefore move to ChatGPT/Codex under another login. Keep API-key mode pinned during retries.

Knowledge Base Used: Provider selection and runtime adapters

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-provider-openai-runtime/src/openai_provider_impl.rs
Line: 88-99

Comment:
**API-key requests change login**

After an API-key auth or quota error, `try_rotate_openai_account` can load saved OAuth credentials without checking `credential_mode_snapshot()`. It replaces the shared credentials, and the next attempt chooses its endpoint from those credentials. An explicitly selected `openai-api` request can therefore move to ChatGPT/Codex under another login. Keep API-key mode pinned during retries.

**Knowledge Base Used:** [Provider selection and runtime adapters](https://app.greptile.com/solo-systems/-/custom-context/knowledge-base/1jehuang/jcode/-/docs/provider-selection-and-runtime-adapters.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +78 to +81
let current = jcode_base::auth::codex::active_account_label()?;
let candidate = jcode_base::provider::MultiProvider::preferred_openai_account_label()?;
if candidate == current || !attempted_accounts.insert(candidate.clone()) {
return None;

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.

P1 Healthy accounts go untried

attempted_accounts starts empty, and each rotation checks only the first preferred candidate. With saved order A, B, C and no usable quota snapshot, failures can produce A → B → A. Both rotations are spent without trying healthy C. Seed the set with the starting account and choose the first untried account from the full candidate list.

Artifacts

Evidence from the check

  • The executed Python driver installs each original implementation temporarily, runs the same harness sequentially, captures command output, and restores the source.

Evidence from the check

  • The executed Rust test saves three synthetic accounts and sends real provider requests to a loopback endpoint, demonstrating the automatic sequence and a successful C control.

Command output from the check

  • The base implementation was executed against the synthetic endpoint and captured A returning 401 Unauthorized followed by the direct C control returning 200 OK.

Command output from the check

  • The head implementation was executed against the same endpoint and captured A → B → A returning 401 Unauthorized while the direct C control returned 200 OK, confirming the missed working account.

Evidence from the check

  • The base implementation is preserved with its temporary harness include, identifying the underlying source used for the before capture.

Evidence from the check

  • The head implementation is preserved with its temporary harness include, identifying the underlying source used for the confirmed A → B → A capture.

Command output from the check

  • Executed Git source extraction and comparison captured the selection logic and verified that the tested provider source was restored byte-for-byte.

View artifacts

T-Rex Ran code and verified through T-Rex

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-provider-openai-runtime/src/openai_provider_impl.rs
Line: 78-81

Comment:
**Healthy accounts go untried**

`attempted_accounts` starts empty, and each rotation checks only the first preferred candidate. With saved order A, B, C and no usable quota snapshot, failures can produce A → B → A. Both rotations are spent without trying healthy C. Seed the set with the starting account and choose the first untried account from the full candidate list.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +1110 to +1114
let safe = safe.trim_matches('-');
if safe.is_empty() {
crate::auth::account_store::canonical_account_label(provider, index + 1)
} else {
format!("{provider}-{safe}")

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.

P1 Imported account labels collide

Aliases Work Email and Work-Email both become cursor-Work-Email. upsert_account accepts both accounts because it checks IDs, but loading and switching find the first account by label. The second account cannot be selected; importing it as active selects the first account's credentials. Make labels unique within each provider.

T-Rex Ran code and verified through T-Rex

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-base/src/auth/provider_pool.rs
Line: 1110-1114

Comment:
**Imported account labels collide**

Aliases `Work Email` and `Work-Email` both become `cursor-Work-Email`. `upsert_account` accepts both accounts because it checks IDs, but loading and switching find the first account by label. The second account cannot be selected; importing it as active selects the first account's credentials. Make labels unique within each provider.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +243 to +248
if let Some((used, limit)) = pair(object) {
return Some(((used / limit) * 100.0).clamp(0.0, MAX_PERCENT) as f32);
}
}
aliases.iter().find_map(|alias| {
let value = find_value(root, &[alias], 0);

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.

P2 Missing quotas get invented

A monthly-only planUsage response containing spend and limit produces identical Monthly, Auto, and API windows because percent_from_object applies pair(object) to the monthly object for all three scopes. The fallback parser also fills absent scopes from generic percentages elsewhere in the response. These values are saved as account quota observations. This is non-blocking, but users see Auto/API usage the provider did not report, and later account comparisons use those invented observations. Read each window only from its own fields and leave missing quota unknown.

T-Rex Ran code and verified through T-Rex

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-base/src/usage/cursor.rs
Line: 243-248

Comment:
**Missing quotas get invented**

A monthly-only `planUsage` response containing spend and limit produces identical Monthly, Auto, and API windows because `percent_from_object` applies `pair(object)` to the monthly object for all three scopes. The fallback parser also fills absent scopes from generic percentages elsewhere in the response. These values are saved as account quota observations. This is non-blocking, but users see Auto/API usage the provider did not report, and later account comparisons use those invented observations. Read each window only from its own fields and leave missing quota unknown.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +482 to +485
if let Some(account) = crate::auth::provider_pool::active_account("antigravity")
.ok()
.flatten()
{

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.

P2 Quota follows the wrong account

Antigravity reads the active label after the network request. Switching from account A to B while polling waits therefore saves quota fetched with A's credentials under B. The executed switch succeeded and replaced B's 900-milli remaining quota with A's 100-milli response. This is non-blocking, but it misreports B's capacity and gives later account ranking the wrong data. Capture the account before fetching and use its account-specific credentials and label throughout.

Knowledge Base Used: Authentication and account management

T-Rex Ran code and verified through T-Rex

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-base/src/usage/provider_fetch.rs
Line: 482-485

Comment:
**Quota follows the wrong account**

Antigravity reads the active label after the network request. Switching from account A to B while polling waits therefore saves quota fetched with A's credentials under B. The executed switch succeeded and replaced B's 900-milli remaining quota with A's 100-milli response. This is non-blocking, but it misreports B's capacity and gives later account ranking the wrong data. Capture the account before fetching and use its account-specific credentials and label throughout.

**Knowledge Base Used:** [Authentication and account management](https://app.greptile.com/solo-systems/-/custom-context/knowledge-base/1jehuang/jcode/-/docs/authentication-and-account-management.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +112 to +119
for account in alternatives {
jcode_base::auth::provider_pool::mark_account_cooldown(
"antigravity",
&original,
cooldown,
);
match self
.generate_content_for_account(

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.

P2 Retries share a busy account

Antigravity's runtime failover sends an alternate-account request without acquiring its AccountLease. After a primary HTTP 429, the executed retry used an alternate whose lease was still held by another process. This is non-blocking, but concurrent processes can send retries through an account that shared failover would skip, defeating the pool's busy-account admission behavior. Acquire and hold an AccountLease for each alternate attempt.

T-Rex Ran code and verified through T-Rex

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-provider-antigravity-runtime/src/lib.rs
Line: 112-119

Comment:
**Retries share a busy account**

Antigravity's runtime failover sends an alternate-account request without acquiring its `AccountLease`. After a primary HTTP 429, the executed retry used an alternate whose lease was still held by another process. This is non-blocking, but concurrent processes can send retries through an account that shared failover would skip, defeating the pool's busy-account admission behavior. Acquire and hold an `AccountLease` for each alternate attempt.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

match self {
Self::Anthropic => format!("/account switch {}", label),
Self::OpenAI => format!("/account openai switch {}", label),
Self::Cursor => format!("/account switch {}", label),

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.

P2 Cursor recovery command fails

Cursor guidance emits /account switch <label>, but that shorthand only searches Claude and OpenAI accounts. Following it returns “No Anthropic or OpenAI account” instead of switching. This is non-blocking, but it makes the suggested recovery step unusable. Emit /account cursor switch <label>, which the new provider-specific path supports.

Suggested change
Self::Cursor => format!("/account switch {}", label),
Self::Cursor => format!("/account cursor switch {}", label),

T-Rex Ran code and verified through T-Rex

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-base/src/usage/model.rs
Line: 364

Comment:
**Cursor recovery command fails**

Cursor guidance emits `/account switch <label>`, but that shorthand only searches Claude and OpenAI accounts. Following it returns “No Anthropic or OpenAI account” instead of switching. This is non-blocking, but it makes the suggested recovery step unusable. Emit `/account cursor switch <label>`, which the new provider-specific path supports.

```suggestion
            Self::Cursor => format!("/account cursor switch {}", label),
```

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +107 to +110
let path = directory.join(format!(
"{}-{}.lock",
lease_path_component(provider),
lease_path_component(label)

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.

P2 Long labels block failover

lease_path_component doubles every label byte, and imported labels have no length limit. On a filesystem with a 255-byte filename limit, a 120-character Cursor alias produces an oversized lock filename. Opening it fails, so shared failover treats the account as already leased and skips it. This is non-blocking for ordinary labels, but long aliases never work as alternates. Use a bounded hash for the filename.

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/jcode-base/src/auth/provider_pool.rs
Line: 107-110

Comment:
**Long labels block failover**

`lease_path_component` doubles every label byte, and imported labels have no length limit. On a filesystem with a 255-byte filename limit, a 120-character Cursor alias produces an oversized lock filename. Opening it fails, so shared failover treats the account as already leased and skips it. This is non-blocking for ordinary labels, but long aliases never work as alternates. Use a bounded hash for the filename.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

@greptile-apps

greptile-apps Bot commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Comments Outside Diff

These findings could not be posted inline.

  • P1 Security Upgrade the h2 dependency crates/jcode-provider-cursor-runtime/Cargo.toml:17 ▶

    The new Cursor HTTP/2 client resolves h2 to version 0.4.13, which is affected by RUSTSEC-2026-0258. A malicious or compromised HTTP/2 peer can send unbounded empty DATA frames that this version queues, causing unbounded memory growth and denial of service. Update the lockfile to h2 0.4.16 or newer.

    How this was verified: The locked Cursor transport reached the remote AgentService through h2 0.4.13 and consumed its peer response body.

  • P1 Switch accounts on server crates/jcode-tui/src/tui/app/auth_account_commands.rs:519 ▶

    A remote TUI request to switch a Cursor or Antigravity account falls through to the local executor instead of sending a server-side switch request. The client reports success after changing its local store, but the remote server’s provider, credentials, session, and catalog remain on the previous account. Route these providers through server-side account-switch requests or reject the unsupported remote action.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: providers Model providers, API adapters, and provider authentication. area: tui Terminal user interface, rendering, and interactions. platform: windows Windows-specific behavior or compatibility. security Security hardening or security-sensitive changes. type: feature Adds a new user-facing capability.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: expose Cursor account quota and usage semantics feat: secure provider credential storage and legacy migration

2 participants