Skip to content

feat: per-worktree Claude account binding (concurrent multi-account) - #6963

Closed
srs-adamr wants to merge 40 commits into
stablyai:mainfrom
srs-adamr:srs-adamr/feat-per-worktree-claude-account
Closed

srs-adamr wants to merge 40 commits into
stablyai:mainfrom
srs-adamr:srs-adamr/feat-per-worktree-claude-account

Conversation

@srs-adamr

@srs-adamr srs-adamr commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Lets each worktree bind to a specific Claude managed account, so multiple worktrees can run different Claude accounts concurrently, and a worktree's agents stay deterministically pinned to its account across spawn/despawn churn. Closes the per-project ask in #5203 / #5635 (concurrency is the superset). Tracking design discussion: #6921.

Today account selection is global per host (activeClaudeManagedAccountId), and the host launch path materializes the active account's creds into shared ~/.claude, which is structurally single-tenant. This PR adds an optional claudeAccountId on the worktree and, when set, has the launch reuse Orca's existing WSL-style CLAUDE_CONFIG_DIR injection on the host path instead of materializing — so assigned worktrees are isolated and concurrent. Purely additive: unassigned worktrees are byte-for-byte unchanged.

What's included:

  • Data model — claudeAccountId?: string | null on Worktree + WorktreeMeta (mirrors the workspaceStatus precedent end-to-end through persistence/IPC/store).
  • Launch — pty.ts resolves the worktree's pinned account fresh at every spawn and passes it as an override; getPreparation returns the injection shape ({ configDir: managedAuthPath, envPatch: { CLAUDE_CONFIG_DIR }, stripAuthEnv: true }) for host and WSL pinned accounts; doSyncForCurrentSelection early-returns for injected accounts (no materialization/read-back).
  • macOS — seeds only the config-dir-scoped Keychain service (Claude Code-credentials-<sha256(configDir)[:8]>) once per launch; never the shared legacy service.
  • Concurrency — injected launches are exempted from the global account-switch gate (they don't touch the shared runtime); the non-injected path keeps the gate exactly as-is.
  • UI — account selector in the create-worktree modal + an "Assign Account" submenu in the worktree context menu, both filtered by the worktree's runtime (host vs WSL/distro).

Screenshots

Create-worktree modal — new Account selector beside the Agent picker (hidden when no accounts exist; runtime-filtered host/WSL):

orca-pr-modal

Worktree context menu — new Assign Account submenu ("Inherit global" + managed accounts):

orca-pr-context-menu

Testing

  • pnpm typecheck — clean
  • pnpm build — clean
  • pnpm lint — the only failure is pre-existing verify:localization-catalog debt in EphemeralVmsPane.tsx (a file this PR does not touch); this PR's own new i18n keys pass.
  • pnpm test — 16 failures, all pre-existing on main (PR-comments, Linear-skill toast, sidebar-toolbar suites — all outside this PR's diff). Verified by running the full suite at the base commit: identical 16 failures there (16 failed / 23035 passed) vs this branch (16 failed / 23039 passed) → this PR adds zero new failures. Branch is rebased onto current upstream/main (v1.4.111-rc.2); our targeted suites are green (347 passed across claude-accounts, pty.test.ts, and the composer card).
  • Added/updated high-quality tests: new unit + integration tests for host & WSL injection, runtime/distro-mismatch fallback + warn, the macOS scoped-keychain seed, and the switch-block exemption (injected launch not blocked during a global switch; non-injected still blocked). The previously-broken pty.test.ts mock (getWorktreeMeta) is fixed.

AI Review Report

Reviewed with Claude (Opus) across the full diff. Main risks checked:

  • Additive/no-regression — verified unassigned worktrees take an identical code path; the switch-block change reduces to the exact original condition when !isInjectedClaudeLaunch. The override is threaded as a trailing optional param, leaving ~130 existing call sites untouched.
  • Cross-platform (macOS / Linux / Windows + WSL/SSH-remote) — explicitly confirmed: all Keychain operations are process.platform === 'darwin'-guarded (no-ops elsewhere); host vs WSL paths are cleanly separated via managedAuthRuntime/wslLinuxAuthPath; runtime filtering reuses the existing getWslDistroFromPath helper (no hardcoded path separators); SSH-remote spawns are correctly out of scope (no-op fallback, never a wrong-account launch). No Electron menu accelerators or shortcuts touched.
  • Refresh/rotation — confirmed Orca does no proactive refresh for injected accounts (doSyncForCurrentSelection early-returns), so token rotation ([Feature]: Make Orca's managed Claude (cloud subscription) auth survive token rotation — stop daily re-auth #6234) is preserved; multi-tenant (N worktrees → 1 account) refresh is CLI-owned per config dir, as it already is for the shared runtime today.

Flagged and addressed: an initial version left WSL bindings inert (host-only resolution) — fixed so WSL worktrees inject their account's wslLinuxAuthPath, with a runtime/distro-mismatch fallback + warn.

Security Audit

  • Credentials by reference, never by value — injection only ever puts a path (CLAUDE_CONFIG_DIR) in the child env and sets stripAuthEnv: true; no token/credential is ever placed in the environment or logged (the mismatch/seed warnings log account ids, not secrets).
  • Path jailing — injection requires getOwnedManagedAuthPath(account) (ownership-marker validated), so a pinned account can't point CLAUDE_CONFIG_DIR outside Orca's managed root.
  • IPC — the create/update-meta IPC surface carries only the claudeAccountId string; no credential material crosses IPC.
  • macOS Keychain — seeds only the scoped service for the account's own config dir; the shared legacy Claude Code-credentials service is never written from an injected launch (avoids cross-worktree clobber), and the seed is best-effort (degrades to Claude's own login prompt, never throws).
  • No new dependencies; no command execution added.

Follow-up needed: none blocking. See Notes for deferred scope.

Notes

  • Platform: macOS requires Claude Code 2.1+ (config-dir-scoped Keychain). Linux/Windows/WSL are file-based and need no Keychain step.
  • Deferred (intentional, documented): (1) a full per-CLAUDE_CONFIG_DIR refresh lock — not needed for this PR since Orca doesn't proactively refresh injected accounts (CLI-owned); (2) per-worktree usage/rate-limit display in the Accounts pane.
  • Binding home: stored on WorktreeMeta following the workspaceStatus precedent — happy to relocate if maintainers prefer a different home (raised in [Feature]: Per-worktree Claude account binding (concurrent multi-account + per-project defaults) #6921).

Open in Stage

ELI5

Each worktree can stick to its own Claude account instead of sharing one global pick. That means several worktrees can use different Claude logins at the same time, and agents keep using the right account even when they restart.

@ghost

ghost commented Jun 30, 2026 •

Copy link
Copy Markdown

Ready to review this PR? Stage has broken it down into 6 individual chapters for you:

Title
1 Define per-worktree Claude account data model
2 Implement account injection and runtime validation
3 Wire account injection through PTY spawn
4 Persist pinned account in worktree metadata
5 Add UI for worktree account selection
6 Wire account selection through creation flow
Open in Stage

Chapters generated by Stage for commit 30b3b50efb8d915db10a29a0b9a2d3e0aaa76ba3 on Jul 2, 2026 2:10am UTC.

@srs-adamr
srs-adamr force-pushed the srs-adamr/feat-per-worktree-claude-account branch from d6420c2 to 30f82ca Compare July 1, 2026 11:46
@srs-adamr
srs-adamr marked this pull request as ready for review July 2, 2026 00:34
@coderabbitai

coderabbitai Bot commented Jul 2, 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-worktree Claude account pinning across shared types, runtime auth preparation, PTY spawn gating, and worktree metadata persistence. Renderer flows now fetch compatible managed accounts, let users select or inherit the global account when creating worktrees or assigning them from the context menu, and pass the selected account through quick-create and worktree creation paths. Tests cover injected-account resolution, fallback behavior, spawn gating, and the new UI selector behavior.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise and accurately summarizes the main change: per-worktree Claude account binding with concurrency.
Description check ✅ Passed The description follows the required template and includes summary, screenshots, testing, AI review, security audit, and notes.

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

🧹 Nitpick comments (1)
src/renderer/src/components/NewWorkspaceComposerCard.test.tsx (1)

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

Consider adding coverage for the new Account selector.

Props are wired correctly for the default render, but no test exercises rendering the Select when claudeAccounts is non-empty, or verifies onClaudeAccountIdChange receives null when INHERIT_GLOBAL_CLAUDE_ACCOUNT_VALUE is selected vs. the account id otherwise.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 296a1bb5-1312-4bd5-b8fc-f7526e879ff1

📥 Commits

Reviewing files that changed from the base of the PR and between 0dfd56a and 30f82ca2f2aee6060b8fae2403699605e6c7fc33.

📒 Files selected for processing (26)
  • src/main/claude-accounts/runtime-auth-service.test.ts
  • src/main/claude-accounts/runtime-auth-service.ts
  • src/main/claude-accounts/runtime-selection.ts
  • src/main/index.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/ipc/worktree-metadata-merge.ts
  • src/main/ipc/worktree-remote.ts
  • src/main/ipc/worktrees.ts
  • src/main/window/attach-main-window-services.ts
  • src/renderer/src/components/NewWorkspaceComposerCard.test.tsx
  • src/renderer/src/components/NewWorkspaceComposerCard.tsx
  • src/renderer/src/components/NewWorkspaceComposerModal.tsx
  • src/renderer/src/components/sidebar/WorktreeContextMenu.tsx
  • src/renderer/src/hooks/useComposerState.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/lib/claude-account-runtime-filter.ts
  • src/renderer/src/lib/pending-worktree-creation.ts
  • src/renderer/src/lib/worktree-creation-flow.ts
  • src/renderer/src/store/slices/worktree-helpers.ts
  • src/renderer/src/store/slices/worktrees.ts
  • src/shared/types.ts

@srs-adamr

Copy link
Copy Markdown
Contributor Author

Addressed the automated review feedback in 02de27dc0:

  • Perf (main-process hot path): hasInjectedAccountOverride() reaches getOwnedManagedAuthPath(), which on Windows validates WSL-pinned accounts via a synchronous execFileSync('wsl.exe', …). Since that check runs on the PTY spawn gate, it's now memoized per account.id:managedAuthPath — only successful resolutions are cached, so a transiently-unavailable distro isn't sticky. (host/macOS/Linux never shelled out; they hit cheap sync fs.)
  • Stability: added .catch() to the claudeAccounts.list() fetch in NewWorkspaceComposerModal so an IPC rejection degrades to an empty list rather than an unhandled promise rejection.
  • Coverage: added tests for the Account selector in NewWorkspaceComposerCard.test.tsx — conditional render, controlled value display, and that onClaudeAccountIdChange emits the account id on select and null for "Inherit global".

typecheck, targeted vitest suites (claude-accounts, pty, composer card — all green), and lint on the touched files all pass locally.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

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

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

789-797: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Preserve default-WSL account matching when the target has no distro.

All callers pass the target through resolveWslDefaultTarget() first, so a launch with no distro becomes the concrete default distro. That makes a pinned WSL account stored with wslDistro: null / __default__ fail this comparison and fall back to global selection even though it represents the default WSL account.

🐛 Proposed fix
-    const runtimeMismatch =
+    const targetWslKey = getClaudeWslSelectionKey(normalizedTarget.wslDistro)
+    const defaultWslKey = getClaudeWslSelectionKey(getDefaultWslDistro())
+    const accountWslKey = getClaudeWslSelectionKey(account.wslDistro)
+    const wslDistroMatches =
+      accountWslKey === targetWslKey ||
+      (normalizedTarget.runtime === 'wsl' &&
+        targetWslKey === defaultWslKey &&
+        accountWslKey === getClaudeWslSelectionKey(null))
+    const runtimeMismatch =
       (normalizedTarget.runtime === 'host' && accountIsWsl) ||
-      (normalizedTarget.runtime === 'wsl' &&
-        (!accountIsWsl ||
-          getClaudeWslSelectionKey(account.wslDistro) !==
-            getClaudeWslSelectionKey(normalizedTarget.wslDistro)))
+      (normalizedTarget.runtime === 'wsl' && (!accountIsWsl || !wslDistroMatches))

845-850: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Do not overwrite refreshed injected Keychain credentials with stale managed credentials.

For macOS injected host launches, Claude can refresh the scoped Keychain service for account.managedAuthPath. The next launch always seeds that scoped service from managed storage, but this path never reads the scoped service back first; a rotated refresh token can be replaced with the stale managed copy and break subsequent auth.

Before writing, read the scoped service for account.managedAuthPath and persist/keep it when it matches this account and is fresher or has a non-older rotated refresh token, mirroring the existing read-back logic used for global runtime auth.

🧹 Nitpick comments (1)
src/renderer/src/components/NewWorkspaceComposerCard.test.tsx (1)

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

as never erases type safety for the fixture.

Casting the fixture as never bypasses structural checks against ClaudeManagedAccountSummary[] entirely, so future required-field additions to that type won't be caught here.

♻️ Suggested safer typing
-const claudeAccounts = [
-  { id: 'acct-alice', email: 'alice@example.com' },
-  { id: 'acct-bob', email: 'bob@example.com' }
-] as never
+const claudeAccounts = [
+  { id: 'acct-alice', email: 'alice@example.com' },
+  { id: 'acct-bob', email: 'bob@example.com' }
+] as unknown as ClaudeManagedAccountSummary[]

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 71715fcb-9f85-447a-b009-3eaac928fafb

📥 Commits

Reviewing files that changed from the base of the PR and between 30f82ca2f2aee6060b8fae2403699605e6c7fc33 and 02de27dc06db1dd12257e9a1eaef07b33d19fb8d.

📒 Files selected for processing (3)
  • src/main/claude-accounts/runtime-auth-service.ts
  • src/renderer/src/components/NewWorkspaceComposerCard.test.tsx
  • src/renderer/src/components/NewWorkspaceComposerModal.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/components/NewWorkspaceComposerModal.tsx

@srs-adamr

Copy link
Copy Markdown
Contributor Author

Addressed the second review pass in 30b3b50ef.

🟠 Default-WSL account matching (functional correctness) — verified real and fixed, plus a related bug found while tracing it:

  • resolveInjectedAccount now canonicalizes the WSL distro key, so a default-WSL account stored with wslDistro: null (__default__) matches a launch whose distro resolved to the concrete default (e.g. Ubuntu). getDefaultWslDistro() is process-lifetime cached and a no-op off Windows, so no hot-path cost.
  • While reproducing it I found resolveWslDefaultTarget was dropping overrideAccountId when it substituted the default distro — so a distro-less WSL launch silently lost its per-worktree pin. Fixed to preserve the other target fields. Regression test added covering both.

🟠 Injected Keychain re-seed clobber (macOS data integrity) — verified real and fixed. On macOS the seed reads the managed keychain (keyed by account.id) and writes the config-dir-scoped service (keyed by sha256(managedAuthPath)). Claude rotates only the scoped service, and injected accounts are CLI-owned (no read-back), so re-seeding the static managed copy on the next launch would clobber a rotated refresh token. seedInjectedHostAccountKeychain now bootstraps only on first launch — if valid creds already exist in the scoped service, Claude's copy is left in place. The scoped service for a per-account config dir only ever holds that account's creds, so an existence guard is sufficient (no full read-back needed). Regression test added.

🟡/🔵 Test hardening — the HTMLElement.prototype pointer/scroll polyfills are now restored in a finally so they can't leak into sibling tests, and the account fixture is typed as ClaudeManagedAccountSummary[] instead of as never.

typecheck + the full claude-accounts / pty / composer suites (364 tests) are green; lint clean on the touched files.

@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/main/claude-accounts/runtime-auth-service.test.ts (1)

3829-3854: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Forced non-null assertion on originalReadImpl risks a silent mock-restore no-op.

originalReadImpl is typed as possibly undefined (from getMockImplementation()), but the finally block restores it with readStrict.mockImplementation(originalReadImpl!). If no prior implementation was set for readActiveClaudeKeychainCredentialsStrict in this suite, this silently swaps the mock's implementation to undefined rather than genuinely restoring prior state — masking the intent and risking subtle isolation drift for later tests, similar to the mock-restore issues already hardened elsewhere in this PR (HTMLElement.prototype polyfills restored in finally).

♻️ Safer restore
     } finally {
-      readStrict.mockImplementation(originalReadImpl!)
+      if (originalReadImpl) {
+        readStrict.mockImplementation(originalReadImpl)
+      } else {
+        readStrict.mockReset()
+      }
     }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 3405120c-aae3-464c-9f36-1b64874798c4

📥 Commits

Reviewing files that changed from the base of the PR and between 02de27dc06db1dd12257e9a1eaef07b33d19fb8d and 30b3b50efb8d915db10a29a0b9a2d3e0aaa76ba3.

📒 Files selected for processing (3)
  • src/main/claude-accounts/runtime-auth-service.test.ts
  • src/main/claude-accounts/runtime-auth-service.ts
  • src/renderer/src/components/NewWorkspaceComposerCard.test.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/renderer/src/components/NewWorkspaceComposerCard.test.tsx
  • src/main/claude-accounts/runtime-auth-service.ts

@srs-adamr
srs-adamr force-pushed the srs-adamr/feat-per-worktree-claude-account branch 2 times, most recently from 2dfc5ab to 19fee23 Compare July 7, 2026 16:13
@srs-adamr
srs-adamr force-pushed the srs-adamr/feat-per-worktree-claude-account branch from 19fee23 to 13dd3ef Compare July 10, 2026 16:26
@AmethystLiang

Copy link
Copy Markdown
Contributor

this is a great feature and we'd love to get it in. It's a large one so give us some time to review it

@AmethystLiang
AmethystLiang requested review from AmethystLiang and removed request for brennanb2025 July 12, 2026 04:52
srs-adamr and others added 11 commits July 12, 2026 16:36
Wave 1 plumbing for per-worktree Claude account binding. Adds the
optional claudeAccountId field to Worktree and WorktreeMeta (following the
workspaceStatus precedent), surfaces it through the meta->Worktree merges
(git + folder paths), and threads it through createWorktree args. Persistence
(blind spread merge) and the renderer store (generic Partial<WorktreeMeta>
spread) carry the field with no further change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Resolve the worktree's claudeAccountId fresh at each Claude PTY spawn
(pty.ts) and pass it as an overrideAccountId on the selection target. In
getPreparation, a valid owned host override returns the WSL-shaped injection
({configDir, CLAUDE_CONFIG_DIR envPatch, stripAuthEnv}) instead of
materializing into shared ~/.claude, and doSyncForCurrentSelection
early-returns for injected accounts (mirroring the WSL path). A missing,
foreign, or WSL override is ignored, so unassigned worktrees keep today's
global behavior — purely additive.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude Code 2.1+ reads macOS Keychain credentials from a config-dir-scoped
service rather than the legacy unscoped one. An injected per-worktree host
account points CLAUDE_CONFIG_DIR at its own managedAuthPath, so before launch
we now seed ONLY that scoped service (reusing the existing scoped-only
writeActiveClaudeKeychainCredentials helper) from the account's managed
credentials. The legacy unscoped service is never touched here — that's the
shared global-selection singleton, and writing it from multiple worktrees
would race. No-op on Linux/Windows (keychain ops are darwin-only there) and
for unassigned worktrees, which keep today's behavior unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Threads the per-worktree claudeAccountId (Wave 1 data model) from the
quick-composer's submitQuick(agent, claudeAccountId) through
WorktreeCreationRequest and into the createWorktree store action's trailing
options bag (alongside automationProvenanceRequest, avoiding yet another
positional parameter on an already 24-deep signature). Purely additive:
existing callers omit the new param/field and see no behavior change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Adds a Claude account picker beside the Agent picker in the quick-create
modal, mirroring the quickAgent/onQuickAgentChange controlled-prop pattern.
Populated from claudeAccounts:list, default "Inherit global", filtered to
accounts compatible with the target repo's runtime (host vs WSL — keyed off
the repo's on-disk path via the new claude-account-runtime-filter helper,
shared with the upcoming context-menu surface). Hidden for folder-workspace
and SSH-remote targets, where the field either isn't forwarded yet or has no
local launch path to apply to.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Clones the "Move to Status" DropdownMenuSub into an "Assign Account" submenu
(plus "Inherit global") calling updateWorktreeMeta(id, { claudeAccountId }).
Fetches claudeAccounts:list only while the menu is open, mirroring the
existing selectMenuScopedMap gating so many closed sidebar rows don't each
fire an IPC call. Filtered by runtime (host vs WSL) via the
claude-account-runtime-filter helper added alongside the create-modal
selector; multi-select uses the first selected worktree's path as the
representative runtime, matching contextWorkspaceStatus's "use first" mixed-
value convention.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…n mismatch

resolveInjectedHostAccount only resolved HOST override accounts, so a
worktree pinned to a WSL account had no effect on WSL launches: the WSL
prep branch in getPreparation kept reading the global active account's
wslLinuxAuthPath instead of the worktree's override. Generalize the
resolver (now resolveInjectedAccount) to also resolve a WSL override
whose runtime/distro matches the launch, inject that account's
wslLinuxAuthPath (+ configDir/wslLinuxConfigDir/wslDistro, stripAuthEnv)
from getPreparation, and bypass materialization in
doSyncForCurrentSelection the same way the host path already does.

On a runtime/distro mismatch (e.g. a host-pinned account on a WSL
launch, or a WSL-pinned account for the wrong distro), fall back to the
global selection and emit a single console.warn instead of silently
ignoring the pin. seedInjectedHostAccountKeychain now explicitly skips
WSL accounts (they're isolated by their own Linux config dir and need
no Keychain seed), since the generalized resolver can return either
runtime.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Wave 1 added a store.getWorktreeMeta(worktreeId) call in pty.ts to resolve
the per-worktree claudeAccountId override at spawn time, but the store
mocks in pty.test.ts were never given that method, causing
"store.getWorktreeMeta is not a function" in 13 tests whenever a spawn
path passed a string worktreeId. Add getWorktreeMeta: vi.fn() (returning
undefined, i.e. no pinned account) to each affected store mock.
… global switch-block

doSyncForCurrentSelection already early-returns for injected (per-worktree-
pinned) accounts, so Orca does no proactive refresh/materialization for
them — the Claude CLI owns each injected config dir's own token refresh.
The only remaining gap was that a Claude launch in a pinned worktree could
still be blocked by isClaudeAuthSwitchInProgress() (live-pty-gate.ts), even
though it never reads/writes the shared ~/.claude runtime that gate
protects.

Add ClaudeRuntimeAuthService.hasInjectedAccountOverride(), a synchronous
wrapper around the existing resolveInjectedAccount() resolution (the same
one getPreparation() uses), so the PTY spawn gates in pty.ts can tell
whether an in-flight launch is injected *before* paying for the async
prepare/keychain work. Both gates in pty.ts (runtime.setPtyController's
spawn and the pty:spawn IPC handler) now skip the switch-block throw only
when the launch resolves a valid per-worktree override; the global-
selection (non-injected) path is unchanged.

This is explicitly NOT the per-config-dir refresh lock described in the
spec's Correctness model — that remains future work. It is the minimal
coordination fix needed so a global account switch cannot stall a
worktree that isn't using the shared runtime at all.
brennanb2025
brennanb2025 previously approved these changes Jul 13, 2026

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

Thanks for the thorough contribution. I reviewed and hardened the account-isolation lifecycle across local, SSH, WSL, renderer, restart, and reattach paths; added race, durability, retry, and performance regression coverage; and verified the integrated branch in Electron. The exact pushed head passed the full local validation, a clean three-lane review round, and all GitHub checks.

@brennanb2025
brennanb2025 dismissed their stale review July 13, 2026 08:10

Withdrawing approval pending maintainer discussion.

@srs-adamr

Copy link
Copy Markdown
Contributor Author

Hi @brennanb2025 — just checking in. Thanks again for the hardening pass you put into this. The branch has picked up merge conflicts against main as it's sat (currently 5 files: daemon/terminal-host.ts, daemon/types.ts, rate-limits/service.test.ts, store/slices/worktrees.ts, web/web-preload-api.ts). I'm happy to resolve them and bring the branch current whenever that's useful — or to hold off if you'd rather keep it steady while the review wraps up. Just let me know what's most helpful.

@yeodahui

Copy link
Copy Markdown

Hi! I have a similar work/personal account setup, but I mainly use Codex.

Once this PR lands, I’d be interested in working on two follow-ups:

  1. Add the same per-worktree account selection for Codex using CODEX_HOME.
  2. Let users set a default Claude or Codex account per project and host.

For account selection, I was thinking:

  • use the account selected when creating the workspace
  • otherwise use the project default for that host
  • otherwise fall back to the currently active account

Workspaces without an account preference would continue to work as they do today. I’d also make sure local, WSL, and remote account IDs don’t get mixed.

Would these be useful follow-up contributions?

@nwparker nwparker added the enhancement New feature or request label Jul 27, 2026
chambber added a commit to chambber/orca that referenced this pull request Jul 28, 2026
Applies srs-adamr's PR as an isolated diff against its own PR base
(rather than merging the branch wholesale, which would have pulled in
~70 unrelated upstream commits from main). Resolved two conflicts:
kept both new wsl-paths.ts helpers (non-overlapping additions), and
dropped an incidental updatePRBotAuthorOverride declaration that
belongs to an unrelated, not-yet-merged PR bot feature.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@matheus1lva

matheus1lva commented Jul 30, 2026 •

Copy link
Copy Markdown

Can we land this? I forked so i could add this feature for myself - very useful. cc @AmethystLiang @brennanb2025

@temperatio

Copy link
Copy Markdown

Any update on when this might land? I think many of us would really appreciate this feature, as it would be incredibly helpful for those of us who use different accounts for different projects.

@srs-adamr

srs-adamr commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Features really aren't shipping much anymore. The repo's been overrun. I'm gonna give up on this one. Appreciate the effort that went into looking at it.

Here's the data — trying to be as objective as I can.

Feature share vs fixes.

@theyv

theyv commented Sep 1, 2026

Copy link
Copy Markdown

+1, and a suggestion. Three Claude accounts on macOS here. I'm using a third-party wrapper (ccs) that does exactly what this PR does (per-account CLAUDE_CONFIG_DIR, shared agents/ and commands/ symlinked back), so the approach holds up in practice.

@codejunk1e

Copy link
Copy Markdown

This feature is needed ngl. Just here to mention this.

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

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants