Skip to content

fix(claude-auth): make the CLI's scoped Keychain item the single credential owner - #17796

Closed
brennanb2025 wants to merge 40 commits into
mainfrom
brennanb2025/claude-cred-13165
Closed

brennanb2025 wants to merge 40 commits into
mainfrom
brennanb2025/claude-cred-13165

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #13165 — "frequent claude code login for multi account setup".

What was wrong

Claude's refresh tokens are single-use. Replaying a spent one makes the server revoke the whole token family, which signs the user out of that account everywhere.

Orca was replaying them. On macOS the Claude CLI derives its Keychain service name from the config dir it is launched with, so each isolated account has its own item. Orca kept a second copy in its own account-id-keyed service and reconciled the two at every launch. That reconciliation has to answer questions it cannot: which copy is newer, whether the CLI rotated since we last looked, whether a credential blob belongs to this account at all. Guess wrong and you write a stale token over a fresh one.

Linux and Windows never had the second copy — one file location, nothing to reconcile — and produced none of the defects this bridge did.

What this does

Makes the CLI's config-dir-scoped Keychain item the single owner of a managed account's credential on macOS, and deletes the bridge. The launch path now performs no credential I/O at all.

Removed:

  • the launch-path write and its adoption loop
  • the freshness, identity and foreign-login guards that existed only to referee two copies
  • the switch-away read-back for isolated accounts, which could persist a blob from the shared runtime into the account being left
  • usage-preview staging, whose finally delete would have signed the user out on every panel open once the scoped item became the live store

Added:

  • one composed read — scoped Keychain item, falling back to the same-home .credentials.json, behind a shared present | absent | unavailable result. A transient Keychain failure never reaches the file, because that file is a durable-outage fallback that can hold an already-rotated token; serving it because the Keychain was briefly locked is how a spent token gets replayed.
  • a durable stale-fallback marker, written before the clear is attempted. A crash between the Keychain write and the fallback clear then fails closed on the next start instead of serving the token we just replaced.
  • a copy-forward migration that never deletes the source and never overwrites a destination present in either medium, with per-account completion markers so one account's failure cannot strand another.
  • a CI ratchet on which modules may persist credential bytes at all.

Scope

Isolated macOS accounts only. WSL keeps its file lane; the pre-isolation shared-~/.claude path is untouched.

Two follow-ups, deliberately not bundled:

  1. Identity status. This PR flips every account to an isolated per-account home, and a per-account home is somewhere a foreign login can hide — sign in as the wrong identity at a prompt and the account is mislabeled until you notice. This PR removes the old detection along with the bridge; the replacement reports match | foreign | unknown on the account summary as an optional wire field. No data loss in the meantime, and re-running sign-in recovers, but it is a real gap this PR opens and the follow-up closes it.
  2. Deleting the unreachable legacy branches. The settings loader normalizes managedAuthRuntime: undefined → 'host' before the runtime sees an account, so the legacy branches are dead. They are the fallback path if anything here is wrong, so they go last.

Testing

Every guard has an ablation: the named test goes red when the guard is removed, and green when it is restored. Verified for the launch write, the transient-Keychain guard, the stale-fallback guard, the isolated-lane read-back guard, the migration lane check, the per-account marker, the marker's fail-closed read, and the persistence ratchet.

Two tests in the first draft passed with their guard removed — one asserted a mock that was never wired in, the other never set up the live PTY its path required. Both were rewritten against real state.

Still outstanding: live validation with two real accounts.

Merge Sim and others added 18 commits August 31, 2026 19:44
Mirrors the CODEX_HOME spawn-time mechanism: ORCA_CLAUDE_CONFIG_DIR joins the
positive overlay allowlist and each shell wrapper re-exports CLAUDE_CONFIG_DIR
after user rc files, so a hand-typed claude inherits the selected account.

WIP recovered from an interrupted worker; per-account home creation and the
shared-store migration are not implemented yet.
Mirrors codexHome: relay panes are remote-owned, so they keep the host's own
CLAUDE_CONFIG_DIR rather than Orca's managed one.
The wrapper guard permits each agent's per-account home export by name
(CODEX_HOME, MIMOCODE_HOME, OPENCODE_CONFIG_DIR); CLAUDE_CONFIG_DIR is the
same contract and joins them. Snapshots regenerated after verifying the only
content change is the Claude restore line.
@greptile-apps

greptile-apps Bot commented Sep 1, 2026 •

Copy link
Copy Markdown

Greptile Summary

The PR replaces shared Claude credential materialization with per-account runtime configuration and read-only usage checks.

  • Adds per-account Claude config routing across local shell and PTY startup paths.
  • Introduces migration and load-time normalization for existing managed accounts.
  • Adds config-scoped macOS Keychain bridging and safer credential-store observations.
  • Removes token-writing behavior from usage and rate-limit collection.

Confidence Score: 4/5

The PR is not yet safe to merge because an early Claude launch can still reach an isolated config before legacy credentials have migrated.

Load normalization marks legacy accounts as host-isolated, while migration remains asynchronous and launch preparation neither joins it nor verifies credential readiness before selecting the per-account config.

Files Needing Attention: src/main/claude-accounts/runtime-auth-service.ts, src/main/persistence/loading-store/normalize-loaded-global-settings.ts, src/main/claude-accounts/runtime-auth/runtime-auth-preparation.ts

Important Files Changed

Filename Overview
src/main/claude-accounts/runtime-auth-service.ts Coordinates launch preparation, macOS credential bridging, and asynchronous legacy migration; the previously reported startup ordering defect remains.
src/main/persistence/loading-store/normalize-loaded-global-settings.ts Backfills legacy Claude accounts to host isolation before the corresponding credential migration is guaranteed complete.
src/main/claude-accounts/legacy-shared-claude-auth-migration.ts Implements a guarded one-way migration from shared credentials into the uniquely matching managed account.
src/main/claude-accounts/runtime-auth/runtime-auth-preparation.ts Routes host-managed accounts to per-account config directories without a credential-readiness barrier.
src/main/claude-accounts/keychain.ts Adds config-scoped Keychain access and makes the pre-2.1 compatibility write non-blocking.
src/main/rate-limits/claude-managed-account-usage.ts Changes managed-account usage collection to avoid credential materialization and refresh side effects.

Sequence Diagram

sequenceDiagram
  participant Load as Settings loader
  participant Auth as Claude auth service
  participant Migration as Legacy migration
  participant Launch as PTY launch
  participant Claude as Claude CLI
  Load->>Load: Normalize legacy account to host
  Load->>Auth: Construct with normalized settings
  Auth-->>Migration: Start migration asynchronously
  Launch->>Auth: prepareForClaudeLaunch()
  Auth->>Launch: Return per-account config
  Launch->>Claude: Spawn with CLAUDE_CONFIG_DIR
  Migration-->>Auth: Copy shared credentials later
Loading

Reviews (2): Last reviewed commit: "Give the status bar copy for the expired..." | Re-trigger Greptile

void this.safeSyncForCurrentSelection()
// Sync the selected runtime first; migration must not race a cleanup and
// repopulate a managed account from a stale shared Keychain entry.
void this.safeSyncForCurrentSelection().finally(() => this.migrateLegacySharedAuth())

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 Migration races isolated launch

When an existing legacy account launches during startup, settings normalization has already marked it as an isolated host account while this fire-and-forget migration has not necessarily copied its credentials. Launch preparation therefore routes Claude to an empty per-account config directory, causing a valid saved login to appear signed out.

Knowledge Base Used: Restore safe WSL Codex account migration

@coderabbitai

coderabbitai Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The changes add per-account Claude authentication migration and stricter managed-path ownership checks. Runtime preparation and synchronization now support host and WSL isolation, managed-home provisioning, scoped macOS Keychain bridging, and safer filesystem reads. Shell wrappers restore Orca-managed Claude configuration directories. OAuth 401 responses now produce terminal token_expired failures without refresh or CLI fallback. New tracing, environment handling, normalization, and test coverage support these behaviors.

Merge Risk: 🟠 High · up to cc567

This PR changes Claude credential storage and process routing to isolate accounts and stop shared-store writes, but the current head still has risks where failed recovery or account switching can launch Claude with the wrong credentials, replay a rotated token, or overwrite newer authentication state. The fallback and synchronization paths should be fixed before merging.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.81% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 57 functions across 58 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the problem, solution, scope, linked issue, and testing in detail, but it omits several required template sections and checklist items. Add the required ELI5, What Changed, Why, Visual Proof, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections. For Visual Proof, write N/A with a reason if there is no visual or interaction change. Complete the…
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The implementation directly addresses #13165 by preventing stale shared credential overwrites, isolating managed accounts, migrating existing credentials, and preserving safe fallback behavior when Ke…
Out of Scope Changes check ✅ Passed The production and test changes support the linked issue objectives. Rate-limit handling, filesystem observation, migration, environment restoration, Keychain behavior, and renderer messaging are all …
Title check ✅ Passed The title clearly identifies the main change: making the CLI's scoped macOS Keychain item the single credential owner for Claude authentication.
Full details: Linked Issues check

Explanation

The implementation directly addresses #13165 by preventing stale shared credential overwrites, isolating managed accounts, migrating existing credentials, and preserving safe fallback behavior when Keychain bridging fails.

Full details: Out of Scope Changes check

Explanation

The production and test changes support the linked issue objectives. Rate-limit handling, filesystem observation, migration, environment restoration, Keychain behavior, and renderer messaging are all related to safe per-account Claude authentication.

Full details: Description check

Resolution

Add the required ELI5, What Changed, Why, Visual Proof, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections. For Visual Proof, write N/A with a reason if there is no visual or interaction change. Complete the testing checklist and list the platforms tested. State whether the outstanding live validation with two real accounts is complete or remains a known limitation.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 14

🧹 Nitpick comments (3)
src/main/claude-accounts/managed-auth-path.ts (1)

194-194: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Restrict allowMissing to a missing target only.

At Line 194 allowMissing also accepts an existing non-regular file. If .credentials.json exists as a directory, isOwnedChildFile returns true and writeClaudeManagedAuthFile then fails inside writeFileAtomically with a rename error instead of the explicit ownership error. Keep the isFile() requirement for existing targets, and use allowMissing only in the catch branch that already handles definitive absence.

♻️ Proposed predicate tightening
-      const fileStat = lstatSync(filePath)
-      if (fileStat.isSymbolicLink() || (!fileStat.isFile() && !allowMissing)) {
-        return false
-      }
+      const fileStat = lstatSync(filePath)
+      if (fileStat.isSymbolicLink() || !fileStat.isFile()) {
+        return false
+      }
src/main/claude-accounts/runtime-auth/runtime-auth-managed-credentials.ts (1)

109-118: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Share one WSL ownership probe script between the two validators.

claude-managed-auth-storage.ts Lines 258-259 add test ! -L "$candidate" and test ! -L "$candidate_real/.orca-managed-claude-auth" to its probe. This copy at Lines 109-118 keeps the older script without those guards, so the two ownership validators now disagree about symlinked candidates. readlink -f plus the final case still enforces canonical containment here, so this is a consistency gap and not a proven bypass. Extract the script into one shared builder so future guards apply to both call sites.

src/main/claude-accounts/runtime-auth/runtime-auth-readback.ts (1)

117-117: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove or correct the unreachable shared-Keychain branch. normalizeLoadedGlobalSettings converts every undefined managedAuthRuntime to 'host', and readback matches against these normalized settings. Therefore, line 117 cannot call writeActiveClaudeKeychainCredentialsForRuntime for loaded accounts.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 81571db0-bbee-41da-a082-a1ed9ef389d5

📥 Commits

Reviewing files that changed from the base of the PR and between 69120d5 and 770549b.

📒 Files selected for processing (51)
  • src/main/__fixtures__/shell-wrapper-snapshots/daemon-zsh-zshenv.txt
  • src/main/__fixtures__/shell-wrapper-snapshots/local-bash-rcfile.txt
  • src/main/__fixtures__/shell-wrapper-snapshots/local-zsh-zshenv.txt
  • src/main/claude-accounts/claude-managed-auth-storage.ts
  • src/main/claude-accounts/environment.ts
  • src/main/claude-accounts/keychain.test.ts
  • src/main/claude-accounts/keychain.ts
  • src/main/claude-accounts/legacy-shared-claude-auth-migration.test.ts
  • src/main/claude-accounts/legacy-shared-claude-auth-migration.ts
  • src/main/claude-accounts/managed-auth-path.ts
  • src/main/claude-accounts/runtime-auth-service-keychain-snapshots.test.ts
  • src/main/claude-accounts/runtime-auth-service-launch-refresh.test.ts
  • src/main/claude-accounts/runtime-auth-service-materialization.test.ts
  • src/main/claude-accounts/runtime-auth-service-test-harness.ts
  • src/main/claude-accounts/runtime-auth-service.ts
  • src/main/claude-accounts/runtime-auth/runtime-auth-file-storage.test.ts
  • src/main/claude-accounts/runtime-auth/runtime-auth-file-storage.ts
  • src/main/claude-accounts/runtime-auth/runtime-auth-managed-credentials.ts
  • src/main/claude-accounts/runtime-auth/runtime-auth-preparation.ts
  • src/main/claude-accounts/runtime-auth/runtime-auth-readback.ts
  • src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts
  • src/main/claude-accounts/runtime-paths.ts
  • src/main/codex/codex-home-paths.ts
  • src/main/codex/codex-path-observation.ts
  • src/main/codex/config-toml-trust.ts
  • src/main/daemon/daemon-zsh-shell-ready-wrapper-spec.ts
  • src/main/ipc/pty/ipc/spawn-env.ts
  • src/main/ipc/pty/ipc/spawn-preflight.ts
  • src/main/ipc/pty/runtime/spawn-preflight.ts
  • src/main/persistence/loading-store/normalize-loaded-global-settings.test.ts
  • src/main/persistence/loading-store/normalize-loaded-global-settings.ts
  • src/main/powershell-osc133-bootstrap.ts
  • src/main/providers/local-pty-shell-ready-bash-rcfile.ts
  • src/main/providers/local-pty-shell-ready-wrapper-fileset.ts
  • src/main/providers/local-pty-windows-spawn-environment.ts
  • src/main/rate-limits/claude-fetcher-cli-fallback.test.ts
  • src/main/rate-limits/claude-fetcher-managed-account-usage.test.ts
  • src/main/rate-limits/claude-fetcher-test-harness.ts
  • src/main/rate-limits/claude-managed-account-credentials.ts
  • src/main/rate-limits/claude-managed-account-usage.ts
  • src/main/rate-limits/claude-managed-usage-panel.ts
  • src/main/rate-limits/claude-oauth-credentials.ts
  • src/main/rate-limits/claude-oauth-recovery.ts
  • src/main/rate-limits/claude-usage-error-classification.test.ts
  • src/main/rate-limits/claude-usage-error-classification.ts
  • src/main/shell-startup-features.ts
  • src/main/shell-wrapper-generated-file-snapshot.test.ts
  • src/main/zsh-startup-wrapper-builder.ts
  • src/relay/pty-shell-overlay-wrappers.ts
  • src/shared/filesystem-observation.ts
  • src/shared/rate-limit-types.ts
💤 Files with no reviewable changes (1)
  • src/main/rate-limits/claude-managed-usage-panel.ts

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

Comment on lines +28 to +32
if (activeAccount?.managedAuthRuntime === 'host') {
this.clearLastWrittenRuntimeState()
this.lastSyncedAccountId = activeAccount.id
return
}

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -euo pipefail
rg -n -C6 'readBackRefreshedTokens' --type=ts src/main
echo '--- tests covering switch to host account ---'
rg -n -C8 "managedAuthRuntime: 'host'" --type=ts -g '**/*.test.ts' src/main/claude-accounts

Repository: stablyai/orca

Length of output: 35970


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- repository guidance ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -maxdepth 2 -type f -name '*.md' -print

echo '--- current diff ---'
git diff -- src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts

echo '--- sync flow ---'
cat -n src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts | sed -n '1,100p'
cat -n src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts | sed -n '200,245p'

echo '--- read-back implementation ---'
cat -n src/main/claude-accounts/runtime-auth/runtime-auth-readback.ts | sed -n '1,110p'

Repository: stablyai/orca

Length of output: 15665


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- remaining sync flow ---'
cat -n src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts | sed -n '90,210p'
cat -n src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts | sed -n '218,285p'

echo '--- read-back persistence and candidate source ---'
cat -n src/main/claude-accounts/runtime-auth/runtime-auth-readback.ts | sed -n '90,180p'
rg -n -C8 'readRuntimeCredentialCandidatesForReadBack|findManagedAccountForRuntimeCredentials|clearLastWrittenRuntimeState|lastWrittenCredentialsJson' src/main/claude-accounts/runtime-auth --type=ts

echo '--- applicable repository convention ---'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/repo-wide.md

Repository: stablyai/orca

Length of output: 50369


Preserve the outgoing read-back before returning for a host account.

doSyncForCurrentSelection returns before the account-switch block invokes readBackRefreshedTokens. A refresh written by Claude to shared ~/.claude/.credentials.json therefore is not persisted to the previous account’s managed store. The sync code documents that refresh tokens are single-use and that stale materialization can produce invalid_grant. Switching back may replay the consumed token and invalidate the token family. Move the return after the outgoing read-back and skip only incoming materialization.

Comment on lines +62 to +64
env.CLAUDE_CONFIG_DIR = claudeConfigWslInfo.linuxPath
env.ORCA_CLAUDE_CONFIG_DIR = claudeConfigWslInfo.linuxPath
addWslEnvKeys(env, ['CLAUDE_CONFIG_DIR', 'ORCA_CLAUDE_CONFIG_DIR'])

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:

#!/bin/bash
set -euo pipefail
rg -n -C 12 'finalizeWindowsLocalPtySpawnEnvironment|launchWslDistro|CLAUDE_CONFIG_DIR|resolveWindowsShellLaunchArgs' src/main

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail
printf '%s\n' '--- repository conventions ---'
find /tmp/coderabbit-repo-knowledge/stablyai/orca-89dc44e4 -maxdepth 2 -type f -name '*.md' -print
printf '%s\n' '--- changed file ---'
cat -n src/main/providers/local-pty-windows-spawn-environment.ts | sed -n '1,150p'
printf '%s\n' '--- WSL path definition ---'
cat -n src/main/wsl.ts | sed -n '1,120p'
printf '%s\n' '--- direct launch and plan definitions ---'
rg -n -C 8 'plan\.launchWslDistro|launchWslDistro|parseWslPath|addWslEnvKeys|CODEX_HOME' src/main/providers src/main/wsl.ts

Repository: stablyai/orca

Length of output: 271


🏁 Script executed:

#!/bin/bash
set -euo pipefail
printf '%s\n' '--- changed file ---'
cat -n src/main/providers/local-pty-windows-spawn-environment.ts | sed -n '1,150p'
printf '%s\n' '--- WSL path definition ---'
cat -n src/main/wsl.ts | sed -n '1,120p'
printf '%s\n' '--- direct launch and plan references ---'
rg -n -C 8 'plan\.launchWslDistro|launchWslDistro|parseWslPath|addWslEnvKeys|CODEX_HOME' src/main/providers src/main/wsl.ts

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail
printf '%s\n' '--- launch-plan construction ---'
cat -n src/main/providers/local-pty-launch-plan.ts | sed -n '107,245p'
printf '%s\n' '--- Claude config environment producers ---'
rg -n -C 10 'CLAUDE_CONFIG_DIR|ORCA_CLAUDE_CONFIG_DIR|claudeConfigDir|configDir' src/main/providers src/main/claude src/main/pty \
  -g '*.ts' | head -n 500

Repository: stablyai/orca

Length of output: 29784


🏁 Script executed:

#!/bin/bash
set -euo pipefail
printf '%s\n' '--- Claude environment assignments ---'
rg -n -C 6 'envPatch.*CLAUDE_CONFIG_DIR|CLAUDE_CONFIG_DIR.*envPatch|CLAUDE_CONFIG_DIR\s*=' src/main -g '*.ts' | head -n 400
printf '%s\n' '--- WSL default contract ---'
rg -n -C 10 'function getDefaultWslDistro|export function getDefaultWslDistro|getDefaultWslDistro' src/main/wsl.ts src/main -g '*.ts' | head -n 240
printf '%s\n' '--- launch-plan finalizer ---'
rg -n -C 12 'function finalizeLocalPtyLaunchPlan|launchWslDistro:' src/main/providers/local-pty-launch-plan.ts

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail
printf '%s\n' '--- change diff ---'
git diff --unified=20 69120d54029471d4a1b292a7211b046bd40a361d 770549bdef5d674d578506724fad2416ba36dcbd -- src/main/providers/local-pty-windows-spawn-environment.ts
printf '%s\n' '--- focused tests and test references ---'
rg -n -C 12 'finalizeWindowsLocalPtySpawnEnvironment|CLAUDE_CONFIG_DIR|CODEX_HOME|launchWslDistro' src/main/providers/*test.ts src/main/providers/*test.tsx 2>/dev/null | head -n 500

Repository: stablyai/orca

Length of output: 29910


Route Claude WSL launches to the config directory's distro.

When CLAUDE_CONFIG_DIR is a WSL UNC path and plan.launchWslDistro is unset, this branch converts the path but does not update plan.shellArgs. wsl.exe can therefore use a different default distro. Mirror the CODEX_HOME routing block.

Comment on lines +63 to +64
env.ORCA_CLAUDE_CONFIG_DIR = claudeConfigWslInfo.linuxPath
addWslEnvKeys(env, ['CLAUDE_CONFIG_DIR', 'ORCA_CLAUDE_CONFIG_DIR'])

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

Do not infer managed ownership from a raw Claude config path.

applyClaudeEnvPatch deliberately leaves ORCA_CLAUDE_CONFIG_DIR unset when an explicit CLAUDE_CONFIG_DIR already exists. These branches create the Orca marker for any path. The overlay selector then enables the wrapper, and the zsh wrapper restores that value after startup files run. A user's intentional CLAUDE_CONFIG_DIR override can therefore be replaced on Windows or WSL. Preserve a managed-origin signal instead of deriving it from CLAUDE_CONFIG_DIR.

Also applies to: 67-68, 81-83

options?: ClaudeOAuthCredentialReadOptions
): Promise<ClaudeOAuthCredentialReadResult> {
const keychain = await readFromKeychain(options?.keychainConfigDir)
const decision = startSpan('claude.credentials.read', {

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

Start the span before the keychain read.

startSpan records its start timestamp when called. The current call occurs after await readFromKeychain(...), so the claude.credentials.read duration excludes the primary keychain read. Create the span before the keychain read, then set the keychain attributes after the read.

const decision = startSpan('claude.credentials.read', {
attributes: {
store: options?.keychainConfigDir ? 'scoped-keychain' : 'default-keychain',
keychain_available: !keychain.keychainUnavailable,

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

Report non-macOS keychain availability correctly.

readFromKeychain returns an empty result on non-darwin platforms without setting keychainUnavailable. This expression therefore records keychain_available: true on Linux and Windows, although no Keychain read occurred. Set this attribute to false, or use an explicit not-applicable value, when process.platform !== 'darwin'.

@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

Two issues need attention before merge: the legacy-auth migration refuses to adopt legacy-owned dirs that every other credential write path does adopt, and the IPC spawn preflight reads ctx.launchCommand before it is ever assigned, so Claude auth env is applied to non-Claude command panes.

Reviewed changes

This PR stops materializing Claude credentials into the shared ~/.claude/Keychain store and isolates auth per managed account, mirroring the Codex isolation architecture. Substantive changes:

  • Read-only usage reads — prepareForRateLimitFetch and the inactive-account fetcher no longer materialize or refresh tokens; a 401 now classifies as terminal token_expired and the CLI owns refresh.
  • Per-account CLAUDE_CONFIG_DIR isolation — host-managed accounts route panes to their owned auth dir, provisioning shared bulk state (settings.json, CLAUDE.md, projects, plugins) by link/copy, with ORCA_CLAUDE_CONFIG_DIR restore wired through zsh/bash/powershell wrappers.
  • macOS Keychain bridge — managed credentials are bridged into the config-scoped Keychain item the CLI reads, with refuse-to-route fallback when the bridge fails.
  • Versioned legacy migration — a one-way per-account-claude-auth-migration-v1.json marker copies shared credentials into the matching active account, and settings load backfills managedAuthRuntime: undefined → host.
  • Ownership hardening — symlink rejection, marker-content checks, and a three-state present | absent | indeterminate filesystem observation contract extracted to src/shared/filesystem-observation.ts.

The isolation and read-only halves are coherent and well tested; the concerns below are two places where the implementation diverges from its own invariants.

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

if (options.activeAccountId && account.id !== options.activeAccountId) {
return 'ambiguous'
}
if (!resolveOwnedClaudeManagedAuthPath(account.id, account.managedAuthPath)) {

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.

This ownership gate omits adoptLegacyMarker, so it rejects exactly the directories this migration exists to move. Every other credential write path — ClaudeManagedAuthStorage.assertOwned (claude-managed-auth-storage.ts:161), ClaudeRuntimeAuthManagedCredentials.getOwnedManagedAuthPath (runtime-auth-managed-credentials.ts:149), resolveClaudeManagedCredentialsLocation (claude-managed-account-credentials.ts:37), and getPreparation (runtime-auth-preparation.ts:88) — passes { adoptLegacyMarker: true }. A pre-marker legacy account therefore returns unavailable here, never stamps the marker, and retries every startup while its shared credentials stay stranded in ~/.claude; at launch the account is already normalized to host and routes to an empty managed dir, signing the user out. The test suite masks this by mocking resolveOwnedClaudeManagedAuthPath to return the path unconditionally (legacy-shared-claude-auth-migration.test.ts:11-13).

Technical details
# Migration ownership gate must adopt legacy markers

## Affected sites
- src/main/claude-accounts/legacy-shared-claude-auth-migration.ts:77 — `resolveOwnedClaudeManagedAuthPath(account.id, account.managedAuthPath)` without `{ adoptLegacyMarker: true }`, unlike all other callers of the write path.

## Required outcome
- The migration accepts any managed dir that `writeManagedCredentials` would accept, so a legacy account with a markerless-but-canonical `auth` dir migrates instead of looping on `unavailable`.

## Suggested approach
- Pass `{ adoptLegacyMarker: true }` to match `ClaudeRuntimeAuthManagedCredentials.getOwnedManagedAuthPath`, and add a migration test that exercises the real `resolveOwnedClaudeManagedAuthPath` (not the mock) with a markerless dir to prove it migrates.

ctx.claudeAuth =
!ctx.preAdoptedStablePane &&
!args.connectionId &&
(ctx.isClaudeLaunch || !ctx.launchCommand) &&

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.

ctx.launchCommand is still undefined here, so !ctx.launchCommand is always true in the IPC spawn path. It is only assigned later, in assemblePtyIpcSpawnCodexEnv (spawn-env-codex.ts:53), which runs from assemblePtyIpcSpawnEnv after preparePtyIpcSpawnPreflight returns (spawn-run.ts:39-40). The runtime path (runtime/spawn-preflight.ts:131-143) assigns ctx.launchCommand = codexResumeLaunch.command before its equivalent check, so the two paths diverge: IPC now prepares Claude auth for every local pane spawn — including non-Claude command panes (e.g. Codex launches) — while runtime restricts it to Claude launches and plain shells. For those command panes stripAuthEnv is then applied and the hasClaudeAuthEnvConflict throw in assemblePtyIpcSpawnEnv (spawn-env.ts:25) can reject the pane with a "This Claude launch defines explicit Anthropic auth…" error even though it is not a Claude launch.

Technical details
# IPC spawn preflight reads launchCommand before it exists

## Affected sites
- src/main/ipc/pty/ipc/spawn-preflight.ts:228 — `(ctx.isClaudeLaunch || !ctx.launchCommand)` evaluated against an unset `ctx.launchCommand`.
- src/main/ipc/pty/ipc/spawn-run.ts:39-40 — `preparePtyIpcSpawnPreflight` runs before `assemblePtyIpcSpawnEnv` (which populates `ctx.launchCommand`).

## Required outcome
- The IPC path must not prepare Claude auth for panes that launch a non-Claude command; its condition must be equivalent to the runtime path's (`ctx.isClaudeLaunch || !ctx.launchCommand` where `launchCommand` is the resolved launch command).

## Suggested approach
- Resolve the codex-resume launch command before the Claude-auth block in `preparePtyIpcSpawnPreflight`, or gate the block on a preflight-computable predicate (e.g. `ctx.isClaudeLaunch || !args.command` after confirming `args.command` is empty for plain shells) so IPC and runtime agree.

Step 1 makes an expired stored token report token_expired instead of Orca
refreshing it, but neither status-bar switch handled the new kind, so the
type-aware lint failed exhaustiveness. The adjacent 'Refreshing sign-in' copy
would also have been wrong: Orca no longer refreshes, the CLI does.

Also drops two redundant `Promise<unknown> | unknown` unions, where unknown
already absorbs the promise arm.

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

🧹 Nitpick comments (1)
src/renderer/src/components/status-bar/usage-error-copy.ts (1)

102-102: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use intent-named IDs for the new translations.

The new token_expired strings use hash-based IDs. Rename both IDs to intent-named keys and update the matching locale entries. Keep existing hash-based IDs unchanged.

Based on learnings: config/i18n-translation-source.md requires intent-named IDs for newly added TypeScript/TSX strings; existing hash-based IDs are grandfathered.

Also applies to: 172-172

Source: Learnings


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: b3b7708d-1111-4716-8d9e-45b8fb35b3fb

📥 Commits

Reviewing files that changed from the base of the PR and between 770549b and c424d40.

📒 Files selected for processing (3)
  • src/main/claude-accounts/legacy-shared-claude-auth-migration.ts
  • src/renderer/src/components/status-bar/usage-error-copy.ts
  • src/renderer/src/i18n/locales/en.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/claude-accounts/legacy-shared-claude-auth-migration.ts

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

@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 c424d40. The new commit correctly closes the token_expired exhaustiveness gap in both status-bar switches and narrows two redundant Promise<unknown> | unknown unions.

Reviewed changes

  • Added token_expired handling to the Claude status-bar label and message switches, with matching en.json copy (Sign-in expired / Run Claude to refresh it).
  • Narrowed readLegacyOauthAccount/readOauthAccount to () => unknown — unknown already absorbs the promise arm, and the await call sites are unaffected.

The two IMPORTANT findings from the prior review (the migration ownership gate and the IPC spawn-preflight launchCommand ordering) remain open and are unchanged by this commit, so approval is still withheld.

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

Merge Sim added 3 commits September 1, 2026 21:19
The scoped Keychain mock keys managed config dirs by path, so tests seeding the
shared field left the bridge re-reading whatever the previous launch wrote — the
foreign credential never reached the code under test and the identity assertions
passed without exercising the guard.

Splits the macOS bridge cases into their own file; the combined file crossed the
800-line ceiling.

Claude-Session: https://claude.ai/code/session_012E63B2jhajtUbArQHhZjVQ
A managed pane that could not reach its config-scoped Keychain item was rerouted
at the user's personal config dir, so the session silently ran as a different
account and spent that account's quota. Write the managed credentials into the
isolated home's own credentials file instead — the medium the CLI already falls
back to — and keep the pane on its account. The system lane now applies only
when no managed credential can be read at all, where it is still surfaced.

Claude-Session: https://claude.ai/code/session_012E63B2jhajtUbArQHhZjVQ
The file fallback treated every Keychain error alike, so a locked or
prompt-blocked Keychain wrote the credential to disk when the user only needed
to unlock. Classify recoverable failures and report the degraded state for them,
keeping the fallback for a Keychain that is structurally unavailable. The CLI's
own storage layer draws the same distinction.

The two fallback tests asserted a credentials file that setup had already
created, so neither observed a write; they now clear it first.

Claude-Session: https://claude.ai/code/session_012E63B2jhajtUbArQHhZjVQ

@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

🧹 Nitpick comments (1)
src/renderer/src/components/status-bar/usage-error-copy.ts (1)

103-103: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use intent-named localization IDs for the new strings.

The two new managed-Keychain-unavailable translations use hash-like IDs. Rename them to intent-named IDs and update the corresponding locale resources.

Based on learnings: “For newly added user-facing strings in stablyai/orca TypeScript and TSX files, follow config/i18n-translation-source.md: use intent-named localization IDs with named interpolation placeholders.”

Also applies to: 176-176

Source: Learnings


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 8e033e17-7758-4b15-be04-6de02055b45f

📥 Commits

Reviewing files that changed from the base of the PR and between 459f952 and dd36819.

📒 Files selected for processing (17)
  • src/main/claude-accounts/claude-account-service-account-selection.test.ts
  • src/main/claude-accounts/claude-managed-auth-storage.ts
  • src/main/claude-accounts/runtime-auth-service-keychain-snapshots.test.ts
  • src/main/claude-accounts/runtime-auth-service-managed-keychain-bridge.test.ts
  • src/main/claude-accounts/runtime-auth-service-test-harness.ts
  • src/main/claude-accounts/runtime-auth-service.ts
  • src/main/claude-accounts/runtime-auth/runtime-auth-credential-identity.ts
  • src/main/claude-accounts/runtime-auth/runtime-auth-managed-credentials.ts
  • src/main/claude-accounts/runtime-auth/runtime-auth-readback.ts
  • src/main/claude-accounts/runtime-auth/runtime-auth-runtime-state.ts
  • src/main/claude-accounts/runtime-auth/runtime-auth-types.ts
  • src/main/rate-limits/claude-usage-result.test.ts
  • src/main/rate-limits/claude-usage-result.ts
  • src/renderer/src/components/status-bar/tooltip.test.ts
  • src/renderer/src/components/status-bar/usage-error-copy.ts
  • src/renderer/src/i18n/locales/en.json
  • src/shared/rate-limit-types.ts
💤 Files with no reviewable changes (1)
  • src/main/claude-accounts/runtime-auth-service-keychain-snapshots.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/shared/rate-limit-types.ts
  • src/renderer/src/i18n/locales/en.json

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

Comment on lines +154 to +155
return this.managedKeychainUnavailable?.accountId === selectedId
? this.managedKeychainUnavailable.preparation

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 | 🟠 Major | ⚡ Quick win

Scope the cached fallback to the failed host target.

A host Keychain bridge failure stores a fallback by accountId only. If the same host-managed account is selected for a WSL target, getPreparation() creates a WSL preparation, but Lines 154-155 replace it with the cached host fallback. The rate-limit read then uses host runtime paths instead of the target WSL paths.

Key the cache by target/runtime, or apply it only when the current preparation is the failed managed host preparation. Add a host-failure then WSL-fetch regression test.

case 'managed-keychain-unavailable':
return translate(
'auto.components.status.bar.tooltip.9195af66c1',
'Claude could not load the selected managed sign-in. This session is using your personal Claude sign-in.'

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

Do not claim that a personal sign-in is active.

When managed credential materialization fails, prepareForClaudeLaunch selects the system configuration. That path does not prove that the system store contains a personal Claude sign-in. If the system store is empty or unreadable, this message is false. Describe the system-configuration fallback, or pass verified personal-credential availability to the renderer.

Proposed wording
-          'Claude could not load the selected managed sign-in. This session is using your personal Claude sign-in.'
+          'Claude could not load the selected managed sign-in. Claude is using the system configuration.'
📝 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
'Claude could not load the selected managed sign-in. This session is using your personal Claude sign-in.'
'Claude could not load the selected managed sign-in. Claude is using the system configuration.'

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/claude-accounts/runtime-auth-service.ts (1)

32-32: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Serialize legacy migration with runtime mutations.

migrateLegacySharedAuth() runs from finally, but it does not enter serializeMutation(). The constructor returns while migration can still call writeManagedCredentials. A later launch or account switch can synchronize runtime credentials at the same time. A stale migration write can then overwrite a newer managed credential.

Queue the migration on serializeMutation() or add an equivalent version check.

Proposed fix
-    void this.safeSyncForCurrentSelection().finally(() => this.migrateLegacySharedAuth())
+    void this.safeSyncForCurrentSelection().finally(() =>
+      this.serializeMutation(() => this.migrateLegacySharedAuth())
+    )

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: f92e5d38-1cea-4ae6-867f-abf979376e3b

📥 Commits

Reviewing files that changed from the base of the PR and between dd36819 and cc567b2.

📒 Files selected for processing (4)
  • src/main/claude-accounts/keychain.ts
  • src/main/claude-accounts/runtime-auth-service-managed-keychain-bridge.test.ts
  • src/main/claude-accounts/runtime-auth-service-test-harness.ts
  • src/main/claude-accounts/runtime-auth-service.ts

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

Comment on lines +135 to +146
isTransientKeychainError: (error: unknown) => {
const message = String((error as { message?: unknown })?.message ?? error).toLowerCase()
return (
message.includes('locked') ||
message.includes('interaction is not allowed') ||
message.includes('no user interaction') ||
message.includes('user canceled') ||
message.includes('user cancelled') ||
message.includes('name or passphrase') ||
message.includes('timed out')
)
},

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

Mirror isTransientKeychainError input handling in the mock.

src/main/claude-accounts/keychain.ts checks both stderr and message. This mock checks only message. An stderr-only Keychain failure cannot exercise the transient path, so the no-plaintext regression test can miss the real runtime error shape.

Read both fields and add an stderr-only test case.

Comment on lines +111 to +121
} catch (bridgeError) {
console.warn('[claude-runtime-auth] Failed to bridge macOS managed Claude Keychain')
// Degrade the medium before the identity: the CLI reads the config dir's own
// credentials file when the Keychain is unusable, so keep the pane on its account.
// A locked or prompt-blocked Keychain is recoverable, so never spill a plaintext
// credential for it; report the degraded state and let the user unlock instead.
try {
if (
!isTransientKeychainError(bridgeError) &&
(await this.materializeManagedCredentialsFile(selected))
) {

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Keep the stale-readback guard until Keychain repair succeeds.

The re-authentication guard is cleared before the managed-to-scoped Keychain write completes. If that write fails, this catch returns with the guard already cleared. After Keychain recovery, the next launch can import the stale scoped credential before repairing it. This can replay a rotated refresh token.

Clear the guard only after the managed-to-scoped write succeeds, or restore it when the write fails.

Proposed fix
-        if (skipScopedReadBack) {
-          this.skipNextReadBackForAccountId = null
-        }
+        // Keep the marker until the managed-to-scoped write succeeds.

         ...

         if (managed && this.isValidCredentialsJsonObject(managed)) {
           await writeActiveClaudeKeychainCredentials(managed, preparation.configDir)
+          if (skipScopedReadBack) {
+            this.skipNextReadBackForAccountId = null
+          }
         }

Two ways the isolated lane could still hand a consumed refresh token to the CLI.

A pane that never reached its managed home kept `managed:<id>` provenance while
running on the personal login, so the account picker, the bridge and the usage
lane all reported the wrong account indefinitely, and the bridge wrote the
account's credential into a Keychain item no reader reads. That state is now
distinct, surfaced, and the bridge is gated on the pane actually routing at the
managed home rather than on a provenance prefix.

The managed to scoped write also ran unguarded, so an unprovable identity — a
torn `.claude.json` is enough — meant refusing the CLI's fresh rotation and then
overwriting it with the stale copy. It now refuses to overwrite a fresher scoped
credential.

Claude-Session: https://claude.ai/code/session_012E63B2jhajtUbArQHhZjVQ

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No critical issues — one minor suggestion inline.

Reviewed changes

  • Scoped Keychain cleanup on removal — ClaudeManagedAuthStorage.remove now deletes the config-scoped Keychain item via the trusted resolved path, best-effort so a stale item can't block account removal.
  • Identity + freshness guard on bridge read-back — the macOS bridge only adopts a rotated scoped credential after proving it belongs to the selected account against the managed config dir's own .claude.json and that it can replace the managed credential.
  • Medium-degradation fallback — on bridge failure the service now materializes .credentials.json into the managed home and keeps routing to the account, falling back to the system lane (and caching that degraded state) only when materialization also fails.
  • Degraded-state surfacing — a new managed-keychain-unavailable failure kind, provenance constant, and status-bar copy tell the user they're on the personal sign-in lane.

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

deferredByLiveClaudeSession?: boolean
retryAtMs?: number
}): UsageRateLimitMetadata {
const failureKind =

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.

The provenance check overrides failureKind unconditionally, so it both replaces a more specific failure the caller already classified (e.g. token_expired or network via makeClaudeUsageClassificationError) and stamps a successful result — where input.failureKind is undefined — with managed-keychain-unavailable whenever the fallback lane happens to succeed. Gate the override on the provenance only when no specific failureKind was passed, so a real failure (or a clean success) isn't mislabeled as a keychain problem.

When the Keychain write fails durably the CLI persists its rotations to the
config dir's own credentials file, so that file is a live credential source and
not just somewhere to seed. Orca only ever wrote it, so once the Keychain came
back the stale copy was re-imposed and the next reader replayed a token the CLI
had already spent — losing the account this path exists to protect.

The bridge now treats both stores in the managed home as read-back candidates
under the same identity and freshness guards, and drops the outage copy once its
rotation has been adopted, so one live store remains.

Claude-Session: https://claude.ai/code/session_012E63B2jhajtUbArQHhZjVQ

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

Reviewed changes (delta since dd36819)

  • Gated the plaintext file fallback on non-transient Keychain failure — a new isTransientKeychainError helper recognizes locked / prompt-blocked / cancelled / timeout Keychain errors, and prepareForClaudeLaunch now skips materializeManagedCredentialsFile for those, so a recoverable Keychain state never spills the credential to disk and instead routes to the system lane with system:managed-keychain-unavailable.

No new issues found in this delta. Approval remains withheld only because the previously-flagged items are still open: the two IMPORTANT findings (migration adoptLegacyMarker gate, IPC launchCommand ordering) and the failureKind-override nitpick in metadataForClaudeUsageAttempt.

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

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

Reviewed changes (delta since cc567b2)

  • Corrected the failed-managed-route provenance — getPreparation now tracks managedRoutingFailed and emits system:managed-auth-unowned (instead of a false managed:<id>) when the home is unowned or provisioning fails, and the macOS bridge is additionally gated on envPatch.CLAUDE_CONFIG_DIR === configDir so a pane routed at the system dir is never bridged.
  • Read back the outage credentials file — the bridge read-back now considers both the scoped Keychain item and the managed home's .credentials.json as credential sources, adopts the freshest rotation that proves account identity, drops the outage copy once consumed, and refuses to overwrite a fresher unproven scoped credential.

No new issues found in this delta. Approval remains withheld only because the previously-flagged items are still open: the two IMPORTANT findings (migration adoptLegacyMarker gate, IPC launchCommand ordering) and the failureKind-override nitpick in metadataForClaudeUsageAttempt.

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

Merge Sim added 2 commits September 2, 2026 02:53
…able one

The refusal added for the scoped store did not cover the home's credentials
file, and went vacuously false when the scoped item was empty — the exact state
a Keychain outage leaves behind, with the CLI's rotation in the file. Recovery
then seeded the empty item with the pre-outage copy, which the CLI reads first,
so it shadowed the live file and the next refresh replayed a spent token.

The same refusal also swallowed the foreign-login revert, because a fresh login
by another identity is always the fresher credential. Refusing to overwrite it
left every pane on the account running someone else's identity. The two causes
are now separated by whether the home's identity record actually proves a
different account: provable means revert, unreadable means hold off.

Two assertions in this file pinned the flat harness field the bridge stopped
reading, so a real regression stayed green; both now assert the keyed channel.

Claude-Session: https://claude.ai/code/session_012E63B2jhajtUbArQHhZjVQ
Reverting a foreign login put the account's credential back but left the home's
identity record naming the other account, and nothing here ever repairs it — the
CLI only rewrites that record at login, not on refresh. Two launches later the
account's own rotation read as foreign, which disabled both freshness refusals
and wrote the credential it had already replaced back over it. That is this
issue's own failure, produced by the fix for it.

The revert now restores the record from the account's stored copy, and holds off
when the record is unreadable rather than discarding what else the CLI keeps in
it.

Identity is also no longer read from the credential blob: real blobs carry no
identity fields, so that arm could only ever fire for test fixtures — and the
test it satisfied asserted behaviour production cannot produce. It now uses a
production-shaped blob and proves the revert through the record.

Claude-Session: https://claude.ai/code/session_012E63B2jhajtUbArQHhZjVQ

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No critical issues — one minor suggestion inline.

Reviewed changes (delta since b09a262)

  • Split "provably foreign" from "unreadable" — runtimeIdentityIsProvablyForeign now consults both the candidate's own credential blob and the managed home's .claude.json record, so a foreign in-pane login is reverted while a torn identity record still holds off.
  • Extended the read-back guard to the file store — unadoptedFresher and a new wouldShadowLiveFile now weigh the outage .credentials.json candidate alongside the scoped Keychain item, so an empty scoped item is no longer seeded with the pre-outage copy that would shadow the CLI's live rotation.
  • Repaired two harness assertions — they pinned the flat scopedKeychainCredentials field the bridge no longer reads; both now assert the keyed per-config-dir channel, and two new tests pin the outage-shadowing and foreign-login-revert behaviors.

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No critical issues — one minor suggestion inline.

Reviewed changes (delta since c1bf80f)

  • Repaired the identity record a revert invalidates — after reverting a foreign login, repairRuntimeIdentityRecord restores the managed home's .claude.json oauthAccount from the account's stored copy, so the account's own next rotation is no longer mistaken for the foreign login it just undid. It holds off (returns false) when the record is torn or unreadable rather than discarding what else the CLI keeps there.
  • Dropped blob-based identity — runtimeIdentityIsProvablyForeign now derives foreignness only from the home's identity record, since production credential blobs carry no identity fields; foreignLogin became a record-only check.
  • Re-shaped the foreign-login test — the test now uses production-shaped blobs and proves the revert through the home record, plus a new test pinning that a rotation following the revert is kept.

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

Undoing a foreign in-pane login meant rewriting the CLI's own identity record,
which Orca does not own. That write was lock-free and non-atomic against a file
holding project entries, MCP servers and history; it also manufactured a record
that would vouch for the foreign session's next rotation, and any later
restoration of the foreign record re-armed the clobber it was meant to prevent.

A login the home's record proves belongs to another account is now refused in
both directions and surfaced, so no file Orca does not own is touched. The
account is repaired by signing back in, which is the only party that can.

Tools that do write an agent's config write their own store as its owner, with
tmp-then-rename and a same-or-newer check; none rewrites another program's
identity record.

Claude-Session: https://claude.ai/code/session_012E63B2jhajtUbArQHhZjVQ

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No critical issues — one test-integrity suggestion and a stale-comment nit inline.

Reviewed changes

Single commit replacing the foreign-login revert with a report-only path:

  • Refused both write directions on a foreign login — refuseManagedWrite in runtime-auth-service.ts now folds foreignLogin into the guard, and repairRuntimeIdentityRecord (the read-modify-write of the CLI's own .claude.json) is deleted, so the home's keychain/file stores and identity record stay byte-identical.
  • Surfaced the state — a new managed:foreign-login provenance/failure kind with status-bar copy, tracked by a managedForeignLoginAccountId flag that clears once the home record names the account again.

This is a defensible correctness improvement: the prior revert rewrote the CLI's identity record, which Orca does not own. The two IMPORTANT findings from the initial review (the migration adoptLegacyMarker gate and the IPC ctx.launchCommand ordering) remain open and unchanged.

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

setScopedKeychainCredentialsForManagedPath(managedAuthPath, rotatedCredentials)
await service.prepareForClaudeLaunch()

expect(testState.scopedKeychainCredentialsByConfigDir.get(realpathSync(managedAuthPath))).toBe(

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.

This renamed test claims to pin "adopts this account rotation", but asserts scopedKeychainCredentialsByConfigDir — a value the test itself seeds at line 209 — which stays rotatedCredentials whether or not the managed store absorbs the rotation. When adoption is broken, unadoptedFresher turns true and the service simply skips the scoped write, so the assertion still passes. Assert the managed store instead, e.g. expect(readManagedCredentialsForTest('account-1', managedAuthPath)).toBe(rotatedCredentials). The line 189 comment ("is reverted") is also stale now that the commit reports rather than reverts.

}

// Why: an unreadable identity record and one naming another account demand opposite responses —
// hold off when we cannot tell, revert when we can. Only the home's record can prove this;

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.

The "revert when we can" arm of this comment no longer matches the behavior: refuseManagedWrite now includes foreignLogin, and the caller reports managed:foreign-login while leaving both stores alone instead of reverting. Update it to "report when we can" so the contract description stays accurate.

Merge Sim added 2 commits September 2, 2026 20:21
Orca kept its own account-keyed copy of each managed Claude credential and
reconciled it onto the store the CLI owns at every launch. That reconciliation
has to answer questions it cannot: which of two copies is newer, whether the
CLI rotated since we last looked, whether a blob in the shared runtime belongs
to this account. Guessing wrong replays a spent single-use refresh token, and
the server revokes the whole token family - the repeated logouts in #13165.

On macOS the CLI derives a Keychain service from the config dir it is launched
with. Since each managed account already gets its own config dir, that item is
per-account and is the store the CLI actually reads. So make it the owner and
delete the second copy, which is how every other platform already worked.

Removed: the launch-path bridge and its adoption loop, the freshness, identity
and foreign-login guards that existed only to referee two copies, the
switch-away read-back for isolated accounts, and the usage-preview staging
whose `finally` delete would have signed users out on every panel open once the
scoped item became live. The launch path now performs no credential I/O.

Added:
- one composed read (Keychain primary, same-home file fallback) with a shared
  present/absent/unavailable result. A transient Keychain failure never reaches
  the file, because that file can hold an already-rotated token.
- a durable stale-fallback marker written before the clear, so a crash between
  the Keychain write and the fallback clear fails closed instead of serving a
  spent token after restart.
- a copy-forward migration that never deletes the source and never overwrites a
  destination present in either medium, with per-account completion markers.
- a CI ratchet on which modules may persist credential bytes at all. Five
  hand-written versions of that census were each incomplete because they were
  keyed on function names; this one is keyed on the module boundary.

Scope is the isolated macOS lane only. WSL keeps its file lane and the legacy
shared-~/.claude path is untouched.

Every guard has an ablation test: removing it turns a named test red.
…red-13165-single-store

# Conflicts:
#	src/main/persistence/loading-store/normalize-loaded-global-settings.test.ts

@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 this delta — the single-owner migration is clean and well-tested. One cleanup observation below; approval remains withheld only because the two IMPORTANT findings from the initial review are still open.

Reviewed changes

  • Removed the launch-time macOS Keychain bridge — prepareForClaudeLaunch no longer reads back, adopts, or refuses scoped-keychain rotations at spawn. ClaudeRuntimeAuthService now runs a startupMigrations chain (safeSyncForCurrentSelection → migrateLegacySharedAuth → migrateToScopedStore), and both prepareForClaudeLaunch/prepareForRateLimitFetch await whenStartupMigrationsComplete() first, so no reader can observe a not-yet-copied account as signed out.
  • Made the CLI's scoped Keychain item the single credential owner — new per-account-claude-store-migration.ts copies the legacy id-keyed credential into the config-dir-scoped item once (per-account completedAccountIds marker, source never deleted, destination-wins checked immediately before the write).
  • Added a three-state credential read — claude-credential-read-result.ts (present|absent|unavailable) with readComposedClaudeCredentials implementing the CLI's keychain-primary/file-fallback contract, a transient-keychain guard that never spills to the file, and a stale-fallback refusal.
  • Added a fail-closed stale-fallback marker — claude-stale-fallback-marker.ts writes the marker before clearing the fallback file so a crash between the two never re-serves a spent token across restart.
  • Neutered the stage/delete Fable-preview path — withClaudeManagedPreviewKeychainCredentials is now a no-op passthrough, removing the finally-delete that signed users out each time the usage panel opened.
  • Added a persistence-boundary ratchet — claude-credential-persistence-ratchet.test.ts confines credential writes to an explicit allow-listed module set.

ℹ️ Bridge removal orphans the managed-foreign-login / managed-keychain-unavailable surface

The delta that deleted the bridge also removed the only producers of the managed:foreign-login and system:managed-keychain-unavailable provenances (managedForeignLoginAccountId and managedKeychainUnavailable in runtime-auth-service.ts are gone), but the consumers were left behind: the two constants, their metadataForClaudeUsageAttempt mapping branches, the two UsageRateLimitFailureKind values, the status-bar switch arms, and the en.json copy. Nothing can emit those states anymore, so that mapping, that error copy, and tooltip.test.ts's managed-keychain-unavailable case are dead weight — and writeClaudeManagedCredentialsJson/readClaudeManagedCredentialsJson (claude-managed-account-credentials.ts:53,96) now have no callers. Not blocking; a follow-up cleanup keeps the dead provenance from reading as a live state a future reader chases.

Technical details
# Remove orphaned foreign-login / keychain-unavailable provenance

## Affected sites
- src/main/claude-accounts/runtime-auth/runtime-auth-types.ts:4,6 — now-unproduced constants
- src/main/rate-limits/claude-usage-result.ts:82-87 — dead mapping branches
- src/shared/rate-limit-types.ts:28,30 — dead failure kinds
- src/renderer/src/components/status-bar/usage-error-copy.ts — dead switch arms
- src/renderer/src/i18n/locales/en.json — orphaned copy
- src/main/rate-limits/claude-managed-account-credentials.ts:53,96 — dead exports

## Required outcome
- No dead failure kinds, copy, or exports that claim a state the app can no longer produce.

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

Deleting the launch-path bridge removed the only writers of
`system:managed-keychain-unavailable` and `managed:foreign-login`, so both
provenances and the failure kinds, copy and tests hanging off them were dead.

One of them was also actively wrong: the managed-keychain-unavailable tooltip
told the user "This session is using your personal Claude sign-in", which
described the system-lane fallback preparation that no longer exists. A pane
now stays on its own account and a locked Keychain surfaces as the CLI's own
sign-in prompt.

Foreign-login detection returns on its own surface (an identity status on the
account summary) rather than as a usage failure kind, so the failure kind goes
rather than sitting dormant waiting to be re-wired. No translations existed for
either string, so nothing is lost by removing them from en.json.

Also drops `runtimeIdentityIsProvablyForeign`, which lost its last caller with
the bridge. Its replacement has to report three states rather than a boolean -
an unreadable identity record must read as unknown, never as a mismatch - so it
is a rewrite, not a revival.
@brennanb2025 brennanb2025 changed the title fix(claude-auth): stop materializing Claude credentials into the shared store; isolate per account fix(claude-auth): make the CLI's scoped Keychain item the single credential owner Sep 3, 2026

@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 this delta — a clean dead-code removal that finalizes the single-owner model.

Reviewed changes

  • Dropped the two unreachable error states — removed the managed-keychain-unavailable and managed-foreign-login failure kinds, their provenance constants (runtime-auth-types.ts), the metadataForClaudeUsageAttempt mapping branches (claude-usage-result.ts), the status-bar switch arms, en.json strings, and the stale tooltip.test.ts case. Nothing emits those provenances after the bridge removal, so the copy is gone rather than left to read as a live state.
  • Removed the orphaned foreign-login predicate — runtimeIdentityIsProvablyForeign lost its last caller with the bridge and is dropped rather than left dormant; the commit notes its three-state replacement returns on the account-summary surface.
  • Pinned the surviving mapping with a pass-through test — claude-usage-result.test.ts now asserts the caller's failureKind survives a non-degraded (managed:*) preparation, closing the earlier failureKind-override concern for the only remaining degraded provenance.

The two IMPORTANT findings from the initial review remain open and unchanged by this commit: the migration ownership gate still omits { adoptLegacyMarker: true } (legacy-shared-claude-auth-migration.ts:50,88), and the IPC spawn preflight still reads ctx.launchCommand before it is assigned (spawn-preflight.ts:228). Approval stays withheld on those.

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Closing as superseded: a merged PR already covers this change. Merged #24434 (8fdad2a, re-landed as #26801 8b2a5e4) gives each Claude account its own config dir and deletes Orca's credential copying/replay, the same root cause (#13165). 15 PR files deleted by

(Stale-PR cleanup 2026-10-20, approved by Brennan. Reopen if something here is still missing on main.)

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] frequent claude code login for multi account setup

1 participant