Skip to content
4 changes: 4 additions & 0 deletions src/cli/handlers/orchestration/worker-start-agent-view.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { AgentLaunchResult } from '../../../shared/agent-launch/contracts/agent-launch-intent'
import { renderOrchestrationArgv, type OrchestrationAgentView } from './agent-view'
import type { WorkerStartReceipt } from './worker-output'

Expand All @@ -8,6 +9,7 @@ type LaunchChoice = {
}

export type WorkerStartAgentReceipt = WorkerStartReceipt & {
account?: AgentLaunchResult['account']
runId?: string
mode?: { mode?: string; preferred?: string; detail: string }
launch?: { requested?: LaunchChoice; effective?: LaunchChoice }
Expand All @@ -27,6 +29,7 @@ export function isUnobservedTurnStart(value: WorkerStartAgentReceipt): boolean {
}

type WorkerStartFields = {
account?: AgentLaunchResult['account']
dispatchId: string
taskId: string
runId?: string
Expand Down Expand Up @@ -57,6 +60,7 @@ export const WORKER_START_VIEW: OrchestrationAgentView<WorkerStartAgentReceipt,
const residual = (value.residualResources ?? []).map(describeEffect)
const unobserved = isUnobservedTurnStart(value)
return {
account: value.account,
dispatchId: value.dispatchId,
taskId: value.taskId,
runId: value.runId ?? value.run?.id,
Expand Down
1 change: 1 addition & 0 deletions src/cli/orchestration-session-caller-cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -500,6 +500,7 @@ describe('the orchestration envelope', () => {

expect(envelope.orchestrationCompatibilityEvidence).toEqual({
terminalHandle: 'term_inherited_pane',
claudeConfigDir: '',
agentSessionId: SESSION
})
})
Expand Down
8 changes: 4 additions & 4 deletions src/cli/runtime/orchestration-compatibility-envelope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ export function createOrchestrationCompatibilityEnvelope(
}
}

/** The chat an agent launch came from, so the host can show the launched agent there.
* Only a same-host session can be named: host-stamped (WSL) environments send nothing. */
/** Same-host pane or chat evidence; foreign host homes must not select this host's accounts. */
export function createAgentLaunchCallerEvidence(
env: NodeJS.ProcessEnv
): RuntimeOrchestrationEnvelope['orchestrationCompatibilityEvidence'] {
const agentSessionId = readInjectedAgentSessionId(env)
if (!agentSessionId || readOrchestrationCompatibilityEvidence(env)?.host) {
const evidence = readOrchestrationCompatibilityEvidence(env)
if (evidence?.host) {
return undefined
}
return { agentSessionId }
return agentSessionId ? { ...evidence, agentSessionId } : evidence
}
167 changes: 167 additions & 0 deletions src/main/claude-accounts/claude-launch-inheritance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
import type { AgentLaunchAccountReceipt } from '../../shared/agent-launch/contracts/agent-launch-intent'
import { AsyncLocalStorage } from 'node:async_hooks'
import { basename, dirname } from 'node:path'
import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path'
import type { OrchestrationCompatibilityEvidence } from '../../shared/orchestration-compatibility-evidence'
import type { RpcContext } from '../runtime/rpc/core'
import { getClaudeProfileRouter } from './claude-profile-installed-router'
import { claudeProfileLaunchPointer } from './claude-profile-paths'
import type { ClaudeProfileRouter } from './claude-profile-router'
import type { ClaudeRuntimeAuthPreparation } from './runtime-auth/runtime-auth-types'

type ClaudeLaunchAccount = {
router: ClaudeProfileRouter
preparation: ClaudeRuntimeAuthPreparation
receipt: AgentLaunchAccountReceipt
used: boolean
}

// Bind concurrent launches without changing the UI account selection.
const launches = new AsyncLocalStorage<ClaudeLaunchAccount>()

export function inheritedClaudeLaunchPreparation(
router: Pick<ClaudeProfileRouter, 'selectedProfile'>
): ClaudeRuntimeAuthPreparation | undefined {
const launch = launches.getStore()
if (launch?.router !== router) {
return undefined
}
launch.used = true
return launch.preparation
}

export function claudeLaunchAccountReceipt(): AgentLaunchAccountReceipt | undefined {
const launch = launches.getStore()
return launch?.used ? launch.receipt : undefined
}

function accountForHome(router: ClaudeProfileRouter, home: string): string | null | undefined {
const same = (other: string) =>
normalizeRuntimePathForComparison(home) === normalizeRuntimePathForComparison(other)
if (!home || same(router.systemDefaultHome())) {
return null
}
const id = basename(dirname(home))
const account = router.savedAccount(id)
if (account && account.managedAuthRuntime !== 'wsl' && same(router.accountHome(id))) {
return id
}
return undefined
}

async function callerAccount(
router: ClaudeProfileRouter,
context: RpcContext,
evidence: OrchestrationCompatibilityEvidence | undefined
): Promise<string | null | undefined> {
if (!evidence?.terminalHandle || evidence.host || typeof evidence.claudeConfigDir !== 'string') {
return undefined
}
try {
const terminal = await context.runtime.showTerminal(evidence.terminalHandle)
if (
!terminal.connected ||
terminal.agentIdentity !== 'claude' ||
!(await context.runtime.isTerminalRunningAgent(evidence.terminalHandle)) ||
(evidence.paneKey && evidence.paneKey !== `${terminal.tabId}:${terminal.leafId}`)
) {
return undefined
}
return accountForHome(router, evidence.claudeConfigDir)
} catch {
return undefined
}
}

export async function withInheritedClaudeLaunchAccount<T>(
context: RpcContext,
method: string,
params: unknown,
evidence: OrchestrationCompatibilityEvidence | undefined,
run: () => T | Promise<T>
): Promise<T> {
if (
context.caller?.kind !== 'local-cli' ||
![
'agent.launch',
'agent.launchReplay',
'orchestration.workerStart',
'worktree.create'
].includes(method) ||
typeof params !== 'object' ||
params === null ||
!('agent' in params) ||
params.agent !== 'claude' ||
('accountEnv' in params && params.accountEnv !== undefined) ||
('reuseTerminal' in params && params.reuseTerminal !== undefined) ||
('on' in params && params.on !== undefined)
) {
return run()
}
const router = getClaudeProfileRouter()
if (!router) {
return run()
}
if ('target' in params && typeof params.target === 'object' && params.target !== null) {
const target = params.target
if (
'kind' in target &&
target.kind === 'existing' &&
'worktree' in target &&
typeof target.worktree === 'string'
) {
const workspace = await context.runtime.showTerminalWorkspaceLaunchScope(target.worktree)
if (workspace.connectionId) {
return run()
}
}
if (
'create' in target &&
typeof target.create === 'object' &&
target.create !== null &&
'repoHostId' in target.create &&
target.create.repoHostId &&
target.create.repoHostId !== 'local'
) {
return run()
}
}
const inherited = await callerAccount(router, context, evidence)
const selected = inherited === undefined ? router.preparation() : undefined
const id =
inherited ??
(inherited === null
? null
: selected?.provenance.startsWith('profile:')
? selected.provenance.slice('profile:'.length)
: null)
const home = id === null ? router.systemDefaultHome() : await router.prepareAccount(id)
const pointer = claudeProfileLaunchPointer(router.pointerPath, id, home)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const launch: ClaudeLaunchAccount = {
router,
used: false,
receipt: {
id,
email: id === null ? null : (router.savedAccount(id)?.email ?? null),
source: inherited === undefined ? 'selected' : 'caller'
},
preparation: {
configDir: home,
runtime: 'host',
wslDistro: null,
wslLinuxConfigDir: null,
provenance: id === null ? 'system' : `profile:${id}`,
envPatch: {
ORCA_CLAUDE_PROFILE_POINTER: pointer,
CLAUDE_CONFIG_DIR: id === null ? (router.userConfigDir() ?? '') : home,
ORCA_CLAUDE_INJECTED_CONFIG_DIR: id === null ? '' : home
}
}
}
return launches.run(launch, async () => {
const result = await run()
return launch.used && typeof result === 'object' && result !== null && !('account' in result)
? { ...result, account: launch.receipt }
: result
})
}
23 changes: 22 additions & 1 deletion src/main/claude-accounts/claude-profile-paths.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { lstatSync, mkdirSync, readFileSync, realpathSync } from 'node:fs'
import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync } from 'node:fs'
import * as hostPath from 'node:path'
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
import {
Expand Down Expand Up @@ -248,3 +248,24 @@ export function readUserClaudeConfigDirAsSet(env: NodeJS.ProcessEnv): string | u
export function resolveClaudeDefaultHome(userHome: string, userConfigDir?: string): string {
return userConfigDir ?? join(userHome, '.claude')
}

export function writeClaudeProfilePointer(pointer: string, home: string): void {
if (!existsSync(pointer) || readFileSync(pointer, 'utf8') !== home) {
mkdirSync(dirname(pointer), { recursive: true, mode: 0o700 })
writeFileAtomically(pointer, home, { mode: 0o600 })
}
}

/** A fixed pointer keeps later account switches from redirecting the child's shell wrapper. */
export function claudeProfileLaunchPointer(
pointer: string,
accountId: string | null,
home: string
): string {
const fixed = join(
dirname(pointer),
accountId === null ? 'launch-system-default' : `launch-account-${accountId}`
)
writeClaudeProfilePointer(fixed, accountId === null ? '' : home)
return fixed
}
5 changes: 5 additions & 0 deletions src/main/claude-accounts/claude-profile-routed-home.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { inheritedClaudeLaunchPreparation } from './claude-launch-inheritance'
import { lstat } from 'node:fs/promises'
import type { ClaudeProfileRouter } from './claude-profile-router'
import {
Expand All @@ -15,6 +16,10 @@ export async function claudeRoutedHomeAsync(
>,
availability: 'checked' | 'identity' = 'checked'
): Promise<string | null> {
const inherited = inheritedClaudeLaunchPreparation(router)
if (inherited) {
return inherited.provenance === 'system' ? null : inherited.configDir
}
const profile = router.selectedProfile()
if (!profile) {
return null
Expand Down
55 changes: 33 additions & 22 deletions src/main/claude-accounts/claude-profile-router.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { inheritedClaudeLaunchPreparation } from './claude-launch-inheritance'
import { claudeAccountUsagePreparation } from './claude-account-usage-preparation'
import { claudeProfileSelectionHomes } from './claude-profile-selection-homes'
import { prepareClaudeProfileForLaunch } from './claude-profile-launch-preparation'
import { getClaudeAgentViewService } from '../claude/agent-view/agent-view-service'
import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'
import { existsSync, rmSync } from 'node:fs'
import { homedir } from 'node:os'
import { dirname, join } from 'node:path'
import { join } from 'node:path'
import { isAgentStatusHooksEnabledForAgent } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting'
import {
CLAUDE_INJECTED_CONFIG_DIR_ENV,
Expand All @@ -16,9 +17,9 @@ import { claudeProfileMissing } from './claude-profile-launch-errors'
import type { GlobalSettings } from '../../shared/global-settings-types'
import type { ClaudeManagedAccount } from '../../shared/managed-account-types'
import { probeRecentClaudeCliVersion } from '../claude/claude-hook-event-versions'
import { writeFileAtomically } from '../codex-accounts/fs-utils'
import { resolveClaudeCommand } from '../codex-cli/command'
import {
writeClaudeProfilePointer,
describeClaudeProfile,
type ClaudeProfileDescriptor,
readUserClaudeConfigDir,
Expand Down Expand Up @@ -132,6 +133,10 @@ export class ClaudeProfileRouter {
/** Never fall back from a missing folder: that would run the wrong account. `identity` names
* the selected route before its folder exists; launches and reads still check availability. */
routedHome(availability: 'checked' | 'identity' = 'checked'): string | null {
const inherited = inheritedClaudeLaunchPreparation(this)
if (inherited) {
return inherited.provenance === 'system' ? null : inherited.configDir
}
const home = this.routedProfile()?.home ?? null
if (availability === 'checked' && home !== null && !isDirectory(home)) {
throw claudeProfileMissing()
Expand All @@ -157,11 +162,7 @@ export class ClaudeProfileRouter {
return false
}
const home = this.routedProfile()?.home ?? ''
// Avoid rewriting the pointer on every launch.
if (!existsSync(this.pointerPath) || readFileSync(this.pointerPath, 'utf8') !== home) {
mkdirSync(dirname(this.pointerPath), { recursive: true, mode: 0o700 })
writeFileAtomically(this.pointerPath, home, { mode: 0o600 })
}
writeClaudeProfilePointer(this.pointerPath, home)
return true
}

Expand All @@ -173,6 +174,10 @@ export class ClaudeProfileRouter {

/** Initial setup must succeed; later refreshes may time out without blocking launch. */
async prepareLaunch(): Promise<ClaudeRuntimeAuthPreparation> {
const inherited = inheritedClaudeLaunchPreparation(this)
if (inherited) {
return inherited
}
const selected = this.selectedProfile()
// Only fallback routing needs the shell env; account setup waits for it separately.
if (!selected || !this.accountLogin(selected.accountId)) {
Expand Down Expand Up @@ -261,11 +266,13 @@ export class ClaudeProfileRouter {

launchEnv(): ClaudeEnvPatch {
const home = this.routedHome()
return {
[CLAUDE_PROFILE_POINTER_ENV]: this.pointerPath,
// Preserve the user's inherited CLAUDE_CONFIG_DIR for System default.
...(home ? { CLAUDE_CONFIG_DIR: home, [CLAUDE_INJECTED_CONFIG_DIR_ENV]: home } : {})
}
return (
inheritedClaudeLaunchPreparation(this)?.envPatch ?? {
[CLAUDE_PROFILE_POINTER_ENV]: this.pointerPath,
// Preserve the user's inherited CLAUDE_CONFIG_DIR for System default.
...(home ? { CLAUDE_CONFIG_DIR: home, [CLAUDE_INJECTED_CONFIG_DIR_ENV]: home } : {})
}
)
}

/** A broken account selection must not prevent opening a terminal. */
Expand Down Expand Up @@ -298,16 +305,19 @@ export class ClaudeProfileRouter {
}

preparation(): ClaudeRuntimeAuthPreparation {
const inherited = inheritedClaudeLaunchPreparation(this)
const profile = this.routedProfile()
const home = this.routedHome()
return {
configDir: home ?? this.systemDefaultHome(),
runtime: 'host',
wslDistro: null,
wslLinuxConfigDir: null,
envPatch: this.launchEnv(),
provenance: home ? `profile:${profile?.accountId}` : 'system'
}
return (
inherited ?? {
configDir: home ?? this.systemDefaultHome(),
runtime: 'host',
wslDistro: null,
wslLinuxConfigDir: null,
envPatch: this.launchEnv(),
provenance: home ? `profile:${profile?.accountId}` : 'system'
}
)
}

/** Compare pre-routing terminals against the selection; null means no account is selected. */
Expand All @@ -324,7 +334,8 @@ export class ClaudeProfileRouter {
}

routesToAccount(): boolean {
return this.routedProfile() !== null
const inherited = inheritedClaudeLaunchPreparation(this)
return inherited ? inherited.provenance !== 'system' : this.routedProfile() !== null
}

/** Read usage from the same login the account would launch with. */
Expand Down
Loading