From bf0cf81ddc25fda77a43e52ef1617fa526b661da Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 9 Nov 2026 02:02:16 -0800 Subject: [PATCH] fix(claude): isolate independent launches from parent session environments --- .../claude-command-process.test.ts | 19 ++++ .../claude-accounts/claude-command-process.ts | 11 +- .../claude-child-process-environment.test.ts | 35 +++--- .../claude-child-process-environment.ts | 20 +--- src/main/claude/claude-naming-invocation.ts | 3 +- .../claude/claude-stream-json-connection.ts | 3 +- .../claude-structured-child-env.test.ts | 42 ++++++-- .../launch/claude-structured-child-env.ts | 16 +-- .../pty-subprocess/shell-launch-plan.ts | 2 +- .../pty-subprocess/spawn-environment.ts | 6 +- src/main/ipc/pty/host-env/pi-agent.ts | 7 +- src/main/ipc/pty/host-env/spawn-env-keys.ts | 10 -- ...ged-data-account-spawn-environment.test.ts | 101 +++++++++++++++++- src/main/ipc/pty/spawn-options-assembly.ts | 14 ++- .../local-pty/local-pty-spawn-environment.ts | 6 ++ .../launch/structured-agent-launch-support.ts | 7 +- .../structured-chat-naming-runtime.test.ts | 26 +++++ .../commit-message-agent-environment.test.ts | 39 ++++++- .../commit-message-agent-environment.ts | 11 +- .../startup/claude-parent-session-env.ts | 57 ++++++++++ 20 files changed, 345 insertions(+), 90 deletions(-) create mode 100644 src/shared/agent-launch/startup/claude-parent-session-env.ts diff --git a/src/main/claude-accounts/claude-command-process.test.ts b/src/main/claude-accounts/claude-command-process.test.ts index 90924a65aaa..f2a55104048 100644 --- a/src/main/claude-accounts/claude-command-process.test.ts +++ b/src/main/claude-accounts/claude-command-process.test.ts @@ -34,12 +34,31 @@ import { runClaudeCommandProcess } from './claude-command-process' const originalPlatform = process.platform afterEach(() => { + vi.unstubAllEnvs() spawned.specs.length = 0 spawned.stdins.length = 0 Object.defineProperty(process, 'platform', { value: originalPlatform }) }) describe('runClaudeCommandProcess', () => { + it('uses the selected account without the launching Claude session identity', async () => { + vi.stubEnv('CLAUDE_CODE_MESSAGING_SOCKET', 'parent-socket') + vi.stubEnv('CLAUDE_CODE_MESSAGING_TOKEN', 'parent-token') + vi.stubEnv('CLAUDE_AGENT_SDK_VERSION', 'parent-sdk') + vi.stubEnv('CLAUDE_CODE_HTTP_PROXY', 'http://user-proxy') + await runClaudeCommandProcess( + ['auth', 'status'], + { windowsPath: '/chosen/claude', linuxPath: null, wslDistro: null }, + 1000 + ) + const env = spawned.specs[0]?.env + expect(env?.CLAUDE_CODE_MESSAGING_SOCKET).toBeUndefined() + expect(env?.CLAUDE_CODE_MESSAGING_TOKEN).toBeUndefined() + expect(env?.CLAUDE_AGENT_SDK_VERSION).toBeUndefined() + expect(env?.CLAUDE_CODE_HTTP_PROXY).toBe('http://user-proxy') + expect(env?.CLAUDE_CONFIG_DIR).toBe('/chosen/claude') + }) + it('survives a pasted code that reaches Claude just as it exits (EPIPE)', async () => { Object.defineProperty(process, 'platform', { value: 'linux' }) const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) diff --git a/src/main/claude-accounts/claude-command-process.ts b/src/main/claude-accounts/claude-command-process.ts index 951f17ca1a3..d7ad9bbe74b 100644 --- a/src/main/claude-accounts/claude-command-process.ts +++ b/src/main/claude-accounts/claude-command-process.ts @@ -15,6 +15,7 @@ import { import { resolveWslExecutablePath } from '../wsl/execution/wsl-executable-path' import { buildWindowsCommandInvocation } from './windows-command-invocation' import { terminateClaudeProcess } from './claude-login-process-termination' +import { stripInheritedClaudeSessionEnv } from '../../shared/agent-launch/startup/claude-parent-session-env' const MAX_COMMAND_OUTPUT_CHARS = 4_000 const CLAUDE_AUTH_DENIED_PATTERN = @@ -248,12 +249,14 @@ function resolveClaudeInvocation( hostClaudeCommand: () => string, browser: string | undefined ): ClaudeSpawnConfig { + const inheritedEnv = { ...process.env } + stripInheritedClaudeSessionEnv(inheritedEnv) const spawnConfig = interactiveLogin ? { command: interactiveLogin.command, args: interactiveLogin.args, env: withCliRuntimeOnPath(hostClaudeCommand(), { - ...process.env, + ...inheritedEnv, ...claudeConfigDirEnv(configDir.windowsPath, browser) }), windowsVerbatimArguments: false @@ -267,14 +270,14 @@ function resolveClaudeInvocation( '-c', buildWslLoginShellCommand(wslClaudeCommand(configDir.linuxPath, args, browser)) ]), - env: process.env, + env: inheritedEnv, windowsVerbatimArguments: false } : process.platform === 'win32' ? { ...buildWindowsCommandInvocation(hostClaudeCommand(), args), env: withCliRuntimeOnPath(hostClaudeCommand(), { - ...process.env, + ...inheritedEnv, ...claudeConfigDirEnv(configDir.windowsPath, browser) }) } @@ -282,7 +285,7 @@ function resolveClaudeInvocation( command: hostClaudeCommand(), args, env: withCliRuntimeOnPath(hostClaudeCommand(), { - ...process.env, + ...inheritedEnv, ...claudeConfigDirEnv(configDir.windowsPath, browser) }), windowsVerbatimArguments: false diff --git a/src/main/claude/claude-child-process-environment.test.ts b/src/main/claude/claude-child-process-environment.test.ts index 665dc7d3df0..32314de6627 100644 --- a/src/main/claude/claude-child-process-environment.test.ts +++ b/src/main/claude/claude-child-process-environment.test.ts @@ -15,6 +15,19 @@ describe('Claude child process environment', () => { Anthropic_Custom_Headers: 'Authorization: inherited', claude_code_child_session: '1', CLAUDE_CODE_SESSION_ID: 'inherited-session', + ClaudeCode: '1', + Claude_Code_Bridge_Session_Id: 'inherited-bridge', + Claude_Code_Host_Session_Id: 'inherited-host', + Claude_Code_Session_Attended: '1', + Claude_Code_Messaging_Socket: 'parent-socket', + Claude_Code_Messaging_Token: 'parent-token', + Claude_Code_Execpath: 'parent-claude', + Claude_Code_Entrypoint: 'parent-client', + Claude_Code_Desktop_App_Version: 'parent-desktop', + Claude_Effort: 'parent-effort', + Claude_Pid: '123', + Claude_Agent_Sdk_Version: 'parent-sdk', + CLAUDE_CODE_HTTP_PROXY: 'http://configured-proxy', SAFE_VALUE: 'preserved' } } @@ -23,6 +36,7 @@ describe('Claude child process environment', () => { expect(env).toEqual({ ANTHROPIC_AUTH_TOKEN: 'configured-token', Claude_Code_Session_Id: 'configured-session', + CLAUDE_CODE_HTTP_PROXY: 'http://configured-proxy', SAFE_VALUE: 'preserved' }) }) @@ -35,27 +49,8 @@ describe('Claude child process environment', () => { PATH: 'C:\\launch' }) expect(buildClaudeChildProcessEnv(configured, { platform: 'linux', inheritedEnv })).toEqual({ - ...inheritedEnv, + Path: 'C:\\inherited', ...configured }) }) - - it('can strip child-session stamps reintroduced by a full SDK launch overlay', () => { - expect( - buildClaudeChildProcessEnv( - { - CLAUDE_CODE_CHILD_SESSION: 'configured-child-session', - CLAUDE_CODE_SESSION_ID: 'configured-session', - CLAUDE_CODE_BRIDGE_SESSION_ID: 'configured-bridge-session' - }, - { - scrubConfiguredChildSessionStamps: true, - inheritedEnv: { - CLAUDE_CODE_CHILD_SESSION: 'inherited-child-session', - SAFE_VALUE: 'preserved' - } - } - ) - ).toEqual({ SAFE_VALUE: 'preserved' }) - }) }) diff --git a/src/main/claude/claude-child-process-environment.ts b/src/main/claude/claude-child-process-environment.ts index 08c3d7fbe66..c24f8b0dbc0 100644 --- a/src/main/claude/claude-child-process-environment.ts +++ b/src/main/claude/claude-child-process-environment.ts @@ -1,15 +1,10 @@ import { CLAUDE_AUTH_ENV_VARS, applyClaudeEnvPatch } from '../claude-accounts/environment' +import { stripInheritedClaudeSessionEnv } from '../../shared/agent-launch/startup/claude-parent-session-env' import { LEGACY_NATIVE_CHAT_VISUALS_DIR_ENV, NATIVE_CHAT_SCRATCH_DIR_ENV } from '../native-chat/native-chat-visuals-delivery' -const CLAUDE_CHILD_SESSION_STAMP_ENV_KEYS = [ - 'CLAUDE_CODE_CHILD_SESSION', - 'CLAUDE_CODE_SESSION_ID', - 'CLAUDE_CODE_BRIDGE_SESSION_ID' -] as const - function cloneProcessEnv(source: NodeJS.ProcessEnv): Record { const env: Record = {} for (const [key, value] of Object.entries(source)) { @@ -35,19 +30,11 @@ function stripEnvKeys( return env } -function stripClaudeChildSessionStamps( - env: Record, - platform: NodeJS.Platform -): Record { - return stripEnvKeys(env, CLAUDE_CHILD_SESSION_STAMP_ENV_KEYS, platform) -} - export function buildClaudeChildProcessEnv( configuredEnv: Record = {}, options: { inheritedEnv?: NodeJS.ProcessEnv platform?: NodeJS.Platform - scrubConfiguredChildSessionStamps?: boolean } = {} ): Record { const inheritedEnv = options.inheritedEnv ?? process.env @@ -83,9 +70,6 @@ export function buildClaudeChildProcessEnv( platform ) } - if (options.scrubConfiguredChildSessionStamps) { - return stripClaudeChildSessionStamps({ ...env, ...configuredEnv }, platform) - } - stripClaudeChildSessionStamps(env, platform) + stripInheritedClaudeSessionEnv(env, { platform }) return { ...env, ...configuredEnv } } diff --git a/src/main/claude/claude-naming-invocation.ts b/src/main/claude/claude-naming-invocation.ts index c41e53f8e6d..365f37176ae 100644 --- a/src/main/claude/claude-naming-invocation.ts +++ b/src/main/claude/claude-naming-invocation.ts @@ -88,8 +88,7 @@ export function claudeNamingLaunchInputs(launch: ClaudeStructuredLaunch): Claude ...claudeConfigDirEnvPatch(launch.claudeConfigDir, { env: launch.env }) }, { - inheritedEnv: withoutInheritedClaudeConfigDir(process.env), - scrubConfiguredChildSessionStamps: true + inheritedEnv: withoutInheritedClaudeConfigDir(process.env) } ) for (const key of launch.envToDelete ?? []) { diff --git a/src/main/claude/claude-stream-json-connection.ts b/src/main/claude/claude-stream-json-connection.ts index d980a73b902..df808c208e2 100644 --- a/src/main/claude/claude-stream-json-connection.ts +++ b/src/main/claude/claude-stream-json-connection.ts @@ -112,8 +112,7 @@ export async function openClaudeStreamJsonConnection( const env = await withoutRejectedClaudeApiKey( withoutKeys( buildClaudeChildProcessEnv(launch.env, { - inheritedEnv: withoutInheritedClaudeConfigDir(process.env), - scrubConfiguredChildSessionStamps: true + inheritedEnv: withoutInheritedClaudeConfigDir(process.env) }), launch.envToDelete ?? [] ) diff --git a/src/main/claude/structured/launch/claude-structured-child-env.test.ts b/src/main/claude/structured/launch/claude-structured-child-env.test.ts index aff78f757a7..006cd0f2a6e 100644 --- a/src/main/claude/structured/launch/claude-structured-child-env.test.ts +++ b/src/main/claude/structured/launch/claude-structured-child-env.test.ts @@ -37,21 +37,45 @@ it('names Orca as the Claude client unless the launch environment sets one', () command: 'claude', prefixArgs: [], overlay: undefined, - inheritedEnv: { CLAUDE_CODE_ENTRYPOINT: 'cli' } + inheritedEnv: { + CLAUDE_CODE_ENTRYPOINT: 'cli', + CLAUDECODE: '1', + CLAUDE_CODE_MESSAGING_SOCKET: 'parent-socket', + CLAUDE_AGENT_SDK_VERSION: 'parent-sdk', + CLAUDE_EFFORT: 'parent-effort', + CLAUDE_CODE_HTTP_PROXY: 'http://user-proxy' + } } const options = { runtimeOnPath: false } - expect(claudeChildEnv(sources, undefined, options).CLAUDE_CODE_ENTRYPOINT).toBe('orca') - const overlay = { CLAUDE_CODE_ENTRYPOINT: 'custom' } - expect(claudeChildEnv({ ...sources, overlay }, undefined, options).CLAUDE_CODE_ENTRYPOINT).toBe( - 'custom' - ) + expect(claudeChildEnv(sources, undefined, options)).toEqual({ + CLAUDE_CODE_ENTRYPOINT: 'orca', + CLAUDE_CODE_HTTP_PROXY: 'http://user-proxy' + }) + const overlay = { CLAUDE_CODE_ENTRYPOINT: 'custom', CLAUDE_EFFORT: 'configured-effort' } + expect(claudeChildEnv({ ...sources, overlay }, undefined, options)).toEqual({ + ...overlay, + CLAUDE_CODE_HTTP_PROXY: 'http://user-proxy' + }) }) it('keeps a differently cased Windows launch value over the Orca default', () => { - const inherited = { Claude_Code_Entrypoint: 'cli', PATH: 'C:\\bin' } + const inherited = { + Claude_Code_Entrypoint: 'cli', + CLAUDE_CODE_MESSAGING_TOKEN: 'parent-token', + Claude_Agent_Sdk_Version: 'parent-sdk', + PATH: 'C:\\bin' + } expect( - withOrcaClaudeEntrypoint(inherited, { claude_code_entrypoint: 'company-client' }, 'win32') - ).toEqual({ PATH: 'C:\\bin', CLAUDE_CODE_ENTRYPOINT: 'company-client' }) + withOrcaClaudeEntrypoint( + inherited, + { claude_code_entrypoint: 'company-client', claude_agent_sdk_version: 'configured-sdk' }, + 'win32' + ) + ).toEqual({ + PATH: 'C:\\bin', + CLAUDE_CODE_ENTRYPOINT: 'company-client', + CLAUDE_AGENT_SDK_VERSION: 'configured-sdk' + }) expect(withOrcaClaudeEntrypoint(inherited, undefined, 'win32')).toEqual({ PATH: 'C:\\bin', CLAUDE_CODE_ENTRYPOINT: 'orca' diff --git a/src/main/claude/structured/launch/claude-structured-child-env.ts b/src/main/claude/structured/launch/claude-structured-child-env.ts index 7348c90c323..2e5bfe44a33 100644 --- a/src/main/claude/structured/launch/claude-structured-child-env.ts +++ b/src/main/claude/structured/launch/claude-structured-child-env.ts @@ -12,6 +12,7 @@ import { withCliRuntimeOnPath } from '../../../../shared/node-cli-command-resolu import { applyClaudeEnvPatch } from '../../../claude-accounts/environment' import { resolveClaudeCommand } from '../../../codex-cli/command' import { withoutInheritedClaudeConfigDir } from '../../claude-config-dir-pin' +import { stripInheritedClaudeSessionEnv } from '../../../../shared/agent-launch/startup/claude-parent-session-env' function cloneDefinedEnv(env: NodeJS.ProcessEnv | Record): Record { const next: Record = {} @@ -90,18 +91,11 @@ export function withOrcaClaudeEntrypoint( overlay: Record | undefined, platform: NodeJS.Platform ): Record { - // Windows env names are case-insensitive, so a differently cased twin is the same variable. - const isEntrypointKey = (key: string): boolean => - (platform === 'win32' ? key.toUpperCase() : key) === CLAUDE_ENTRYPOINT_ENV - const withoutEntrypoint = (source: Record): Record => - Object.fromEntries(Object.entries(source).filter(([key]) => !isEntrypointKey(key))) - const override = Object.entries(overlay ?? {}).find(([key]) => isEntrypointKey(key))?.[1] + const env = { ...inheritedEnv, ...overlay } + stripInheritedClaudeSessionEnv(env, { launchEnv: overlay, platform }) // The SDK reads only the exact name and otherwise adds its own default, which Windows would pick. - return { - ...withoutEntrypoint(inheritedEnv), - ...withoutEntrypoint(overlay ?? {}), - [CLAUDE_ENTRYPOINT_ENV]: override ?? 'orca' - } + env[CLAUDE_ENTRYPOINT_ENV] ??= 'orca' + return env } // Merge onto the shell environment to retain PATH and ambient Anthropic auth. diff --git a/src/main/daemon/pty-subprocess/shell-launch-plan.ts b/src/main/daemon/pty-subprocess/shell-launch-plan.ts index 6a4d647264d..bda3dd730ca 100644 --- a/src/main/daemon/pty-subprocess/shell-launch-plan.ts +++ b/src/main/daemon/pty-subprocess/shell-launch-plan.ts @@ -231,7 +231,7 @@ export function createPtyShellLaunchPlan( ) { addWslEnvKeys(env, [POWERLEVEL10K_WIZARD_DISABLE_ENV]) } - finalizeDaemonPtyEnvironment(env, opts.env) + finalizeDaemonPtyEnvironment(env, opts.env, opts.envToDelete) return { shellPath, diff --git a/src/main/daemon/pty-subprocess/spawn-environment.ts b/src/main/daemon/pty-subprocess/spawn-environment.ts index 324e96ea758..8170166e150 100644 --- a/src/main/daemon/pty-subprocess/spawn-environment.ts +++ b/src/main/daemon/pty-subprocess/spawn-environment.ts @@ -30,6 +30,7 @@ import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' import type { PtySubprocessOptions } from './pty-subprocess' import { REMOTE_VIEWER_CLIPBOARD_ENV } from '../../../shared/remote-viewer-clipboard-env' import { ORCAD_SERVER_LAUNCH_ENV_KEYS } from '../../../shared/orcad-server-launch-env' +import { stripInheritedClaudeSessionEnv } from '../../../shared/agent-launch/startup/claude-parent-session-env' const PANE_IDENTITY_ENV_KEYS = [ 'ORCA_PANE_KEY', @@ -186,6 +187,7 @@ export function createDaemonPtyEnvironment(opts: PtySubprocessOptions): Record stripLegacyTerminalShimEnv(env, process.platform) + stripInheritedClaudeSessionEnv(env, { launchEnv: opts.env, envToDelete: opts.envToDelete }) composeGuardedDaemonGitConfigEnv(env, opts.env, opts.launchAgent) deleteRequestedDaemonEnvKeys(env, opts.envToDelete) if (opts.env?.TERM) { @@ -227,8 +229,10 @@ export function rescrubDaemonPtyEnvironment( /** Shell preparation can restore ambient state, so pane isolation is enforced again here. */ export function finalizeDaemonPtyEnvironment( env: Record, - requestedEnv: Record | undefined + requestedEnv: Record | undefined, + envToDelete?: readonly string[] ): void { + stripInheritedClaudeSessionEnv(env, { launchEnv: requestedEnv, envToDelete }) expandWindowsPathEnvironmentVariables(env) collapseWindowsPathEnvKeys(env, requestedEnv) const requestedPath = requestedEnv diff --git a/src/main/ipc/pty/host-env/pi-agent.ts b/src/main/ipc/pty/host-env/pi-agent.ts index 5b2c7a24146..80984ce8f31 100644 --- a/src/main/ipc/pty/host-env/pi-agent.ts +++ b/src/main/ipc/pty/host-env/pi-agent.ts @@ -5,11 +5,8 @@ import { } from '../../../../shared/pi-agent-kind' import { readSessionShellStartupEnvVar } from '../../../pty/shell-startup/shell-startup-env' import { getAgentLaunchExecutableName } from '../../../../shared/agent-launch/startup/agent-command-line-intent' -import { - AGENT_HOOK_RUNTIME_ENV_KEYS, - CLAUDE_CHILD_SESSION_STAMP_ENV_KEYS, - ORCA_AGENT_SESSION_CALLER_ENV_KEYS -} from './spawn-env-keys' +import { AGENT_HOOK_RUNTIME_ENV_KEYS, ORCA_AGENT_SESSION_CALLER_ENV_KEYS } from './spawn-env-keys' +import { CLAUDE_CHILD_SESSION_STAMP_ENV_KEYS } from '../../../../shared/agent-launch/startup/claude-parent-session-env' export function readEnvWithProcessFallback( baseEnv: Record, diff --git a/src/main/ipc/pty/host-env/spawn-env-keys.ts b/src/main/ipc/pty/host-env/spawn-env-keys.ts index 53e60eccc0c..fc08440f1ed 100644 --- a/src/main/ipc/pty/host-env/spawn-env-keys.ts +++ b/src/main/ipc/pty/host-env/spawn-env-keys.ts @@ -26,16 +26,6 @@ export const AGENT_PANE_HOOK_ENV_KEYS = [ ...AGENT_HOOK_RUNTIME_ENV_KEYS ] as const -// Inherited Claude child stamps make an independent pane act as the launching session's child. -export const CLAUDE_CHILD_SESSION_STAMP_ENV_KEYS = [ - 'CLAUDECODE', - 'CLAUDE_CODE_CHILD_SESSION', - 'CLAUDE_CODE_SESSION_ID', - 'CLAUDE_CODE_BRIDGE_SESSION_ID', - 'CLAUDE_CODE_EXECPATH', - 'CLAUDE_CODE_ENTRYPOINT' -] as const - // Inherited structured-session IDs would make every pane claim the parent orchestration caller. export const ORCA_AGENT_SESSION_CALLER_ENV_KEYS = [ ORCA_AGENT_SESSION_ID_ENV, diff --git a/src/main/ipc/pty/managed-data-account-spawn-environment.test.ts b/src/main/ipc/pty/managed-data-account-spawn-environment.test.ts index ed13aa02de9..10e7aa9cbc1 100644 --- a/src/main/ipc/pty/managed-data-account-spawn-environment.test.ts +++ b/src/main/ipc/pty/managed-data-account-spawn-environment.test.ts @@ -2,7 +2,15 @@ import { randomUUID, createHash } from 'node:crypto' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { join } from 'node:path' import { tmpdir } from 'node:os' -import { createDaemonPtyEnvironment } from '../../daemon/pty-subprocess/spawn-environment' +import { + createDaemonPtyEnvironment, + finalizeDaemonPtyEnvironment +} from '../../daemon/pty-subprocess/spawn-environment' +import { + buildInheritedLocalPtyEnvironment, + enforceLocalPtySpawnEnvironmentOverrides +} from '../../providers/local-pty/local-pty-spawn-environment' +import { assemblePtySpawnEnvDeletions } from './spawn-options-assembly' import { applyManagedDataAccountEnvironment } from '../../managed-data-accounts/launch-environment' import { buildPtyIpcSpawnOptions } from './ipc/spawn-options' import { createPtyIpcSpawnState } from './ipc/spawn-state' @@ -41,6 +49,97 @@ beforeEach(() => { }) afterEach(() => vi.unstubAllEnvs()) +describe('independent pane Claude environments', () => { + it('canonicalizes explicit Windows stamps for old receivers and keeps caller deletions authoritative', () => { + const platform = process.platform + Object.defineProperty(process, 'platform', { value: 'win32' }) + try { + const explicit = { claude_code_messaging_socket: '', SAFE_VALUE: 'kept' } + const input = { + env: explicit, + callerEnvToDelete: undefined, + agentTeamsEnvToDelete: [], + isDaemonHostSpawn: true, + connectionId: null, + skipCodexHomeEnv: false, + stripInheritedOrcaCodexHome: false, + codexResumeHomeSelected: false, + settings: undefined + } + const kept = assemblePtySpawnEnvDeletions(input) + expect(kept.env).toEqual({ CLAUDE_CODE_MESSAGING_SOCKET: '', SAFE_VALUE: 'kept' }) + expect(kept.envToDelete).not.toContain('CLAUDE_CODE_MESSAGING_SOCKET') + expect(kept.envToDelete).toContain('CLAUDE_CODE_MESSAGING_TOKEN') + const deleted = assemblePtySpawnEnvDeletions({ + ...input, + callerEnvToDelete: ['Claude_Code_Messaging_Socket'] + }) + expect(deleted.env).toEqual({ SAFE_VALUE: 'kept' }) + expect(deleted.envToDelete).toContain('CLAUDE_CODE_MESSAGING_SOCKET') + expect(explicit).toEqual({ claude_code_messaging_socket: '', SAFE_VALUE: 'kept' }) + } finally { + Object.defineProperty(process, 'platform', { value: platform }) + } + }) + + it.each(['local', 'daemon'])( + '%s owns stamps only from the pane overlay through final preparation', + (provider) => { + const platform = process.platform + vi.stubEnv('CLAUDE_CODE_MESSAGING_SOCKET', 'parent-uppercase') + vi.stubEnv('claude_code_messaging_socket', 'parent-alias') + vi.stubEnv('CLAUDE_CODE_SESSION_ATTENDED', 'parent-attended') + vi.stubEnv('CLAUDE_CODE_HTTP_PROXY', 'http://user-proxy') + const build = (env: Record, envToDelete: string[] = []) => + provider === 'local' + ? buildInheritedLocalPtyEnvironment(env, envToDelete) + : createDaemonPtyEnvironment({ sessionId: 'pane', cols: 80, rows: 24, env, envToDelete }) + try { + Object.defineProperty(process, 'platform', { value: 'win32' }) + const inherited = build({}) + expect(inherited.CLAUDE_CODE_MESSAGING_SOCKET).toBeUndefined() + expect(inherited.claude_code_messaging_socket).toBeUndefined() + expect(inherited.CLAUDE_CODE_SESSION_ATTENDED).toBeUndefined() + expect(inherited.CLAUDE_CODE_HTTP_PROXY).toBe('http://user-proxy') + const explicit = { claude_code_messaging_socket: '' } + const child = build(explicit) + expect(child.CLAUDE_CODE_MESSAGING_SOCKET).toBe('') + expect(child.claude_code_messaging_socket).toBeUndefined() + child.Claude_Code_Messaging_Socket = 'late-parent' + child.CLAUDE_CODE_SESSION_ATTENDED = 'late-attended' + if (provider === 'local') { + enforceLocalPtySpawnEnvironmentOverrides({ cols: 80, rows: 24, env: explicit }, child) + } else { + finalizeDaemonPtyEnvironment(child, explicit) + } + expect(child.CLAUDE_CODE_MESSAGING_SOCKET).toBe('') + expect(child.Claude_Code_Messaging_Socket).toBeUndefined() + expect(child.CLAUDE_CODE_SESSION_ATTENDED).toBeUndefined() + const deletions = ['Claude_Code_Messaging_Socket'] + const deleted = build(explicit, deletions) + deleted.claude_code_messaging_socket = 'late-parent' + if (provider === 'local') { + enforceLocalPtySpawnEnvironmentOverrides( + { cols: 80, rows: 24, env: explicit, envToDelete: deletions }, + deleted + ) + } else { + finalizeDaemonPtyEnvironment(deleted, explicit, deletions) + } + expect(deleted.CLAUDE_CODE_MESSAGING_SOCKET).toBeUndefined() + expect(deleted.claude_code_messaging_socket).toBeUndefined() + expect(explicit.claude_code_messaging_socket).toBe('') + Object.defineProperty(process, 'platform', { value: 'linux' }) + const posix = build({}) + expect(posix.CLAUDE_CODE_MESSAGING_SOCKET).toBeUndefined() + expect(posix.claude_code_messaging_socket).toBe('parent-alias') + } finally { + Object.defineProperty(process, 'platform', { value: platform }) + } + } + ) +}) + function hash(value: string | undefined): string | undefined { return value === undefined ? undefined : createHash('sha256').update(value).digest('hex') } diff --git a/src/main/ipc/pty/spawn-options-assembly.ts b/src/main/ipc/pty/spawn-options-assembly.ts index 7ebebf80160..ba8e3d5b1a0 100644 --- a/src/main/ipc/pty/spawn-options-assembly.ts +++ b/src/main/ipc/pty/spawn-options-assembly.ts @@ -24,6 +24,10 @@ import { import { promoteAgentTeamsShimPath, deleteRequestedEnvKeys } from './host-env/path' import { resolveConfiguredTerminalShellArgs } from './configured-terminal-shell-args' import { ptySizes } from './delivery/visibility-state' +import { + canonicalClaudeSessionStampEnvKey, + stripInheritedClaudeSessionEnv +} from '../../../shared/agent-launch/startup/claude-parent-session-env' import { shouldSeedPreAttachPtySize } from './delivery/attached-pty-size' type TrustInput = Parameters[0] @@ -42,10 +46,16 @@ export function assemblePtySpawnEnvDeletions(input: { settings: GlobalSettings | undefined }): { env: Record | undefined; envToDelete: string[] } { // Apply isolation at the common environment boundary used by every provider. - const env = withCodexTerminalServerIsolationEnv(input.env, input.settings) + const isolated = withCodexTerminalServerIsolationEnv(input.env, input.settings) + const env = isolated ? { ...isolated } : undefined + if (env) { + stripInheritedClaudeSessionEnv(env, { launchEnv: isolated }) + } let envToDelete = mergePtyEnvDeletions( - input.callerEnvToDelete ?? [], + input.callerEnvToDelete?.map((key) => + canonicalClaudeSessionStampEnvKey(key, process.platform) + ) ?? [], // Persistent daemons and older SSH hosts must not resurrect a parent Pi's ownership. PI_PROCESS_OWNER_ENV_KEYS, input.agentTeamsEnvToDelete, diff --git a/src/main/providers/local-pty/local-pty-spawn-environment.ts b/src/main/providers/local-pty/local-pty-spawn-environment.ts index 7d6c3f5be40..248bb6a08a3 100644 --- a/src/main/providers/local-pty/local-pty-spawn-environment.ts +++ b/src/main/providers/local-pty/local-pty-spawn-environment.ts @@ -15,6 +15,7 @@ import { removeUnspecifiedPaneIdentityEnv } from './local-pty-launch-context' import type { LocalPtyLaunchPlan } from './local-pty-launch-plan' import type { LocalPtyProviderOptions } from './local-pty-provider-types' import type { PtySpawnOptions } from '../pty-provider-contract' +import { stripInheritedClaudeSessionEnv } from '../../../shared/agent-launch/startup/claude-parent-session-env' /** Pane ownership must be fresh even when Orca itself was launched inside an agent. */ export function buildLocalPtySpawnEnvironment(args: { @@ -74,6 +75,7 @@ export function buildInheritedLocalPtyEnvironment( removeAppImageRuntimeEnv(spawnEnv) removeChromiumDisabledSessionBus(spawnEnv) removeInheritedNoColor(spawnEnv) + stripInheritedClaudeSessionEnv(spawnEnv, { launchEnv: explicitEnv, envToDelete }) for (const key of envToDelete) { delete spawnEnv[key] } @@ -93,6 +95,10 @@ export function enforceLocalPtySpawnEnvironmentOverrides( finalEnv: Record ): void { stripPiProcessOwnerEnv(finalEnv) + stripInheritedClaudeSessionEnv(finalEnv, { + launchEnv: spawn.env, + envToDelete: spawn.envToDelete + }) for (const key of spawn.envToDelete ?? []) { delete finalEnv[key] } diff --git a/src/main/runtime/agent-session/launch/structured-agent-launch-support.ts b/src/main/runtime/agent-session/launch/structured-agent-launch-support.ts index 16e51d3da17..7af8cf7bee2 100644 --- a/src/main/runtime/agent-session/launch/structured-agent-launch-support.ts +++ b/src/main/runtime/agent-session/launch/structured-agent-launch-support.ts @@ -32,6 +32,7 @@ import type { AgentSessionAccountHome } from '../../../../shared/agent-session/l import { nativeChatShellEnvironmentPolicy } from '../../../../shared/native-chat/native-chat-shell-environment' import { getProfileUserDataPath } from '../../../orca-profiles/profile-storage-paths' import { structuredChatUnavailableOnPlatform } from '../../../../shared/agent-session/structured-chat-platform-support' +import { stripInheritedClaudeSessionEnv } from '../../../../shared/agent-launch/startup/claude-parent-session-env' export type LaunchEnvironmentSettings = Pick< GlobalSettings, @@ -101,8 +102,12 @@ export async function resolveHostStructuredAgentLaunchEnvironment( agent: string, settings: LaunchEnvironmentSettings ): Promise> { + const inherited = { ...(await resolveHostAgentBaseEnvironment(settings)) } + if (agent === 'claude') { + stripInheritedClaudeSessionEnv(inherited) + } return { - ...(await resolveHostAgentBaseEnvironment(settings)), + ...inherited, ...(isTuiAgent(agent) ? resolveTuiAgentLaunchEnv(agent, settings) : {}) } } diff --git a/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.test.ts b/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.test.ts index f4082664bd6..ff79443d87e 100644 --- a/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.test.ts +++ b/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.test.ts @@ -7,6 +7,8 @@ import { normalizeSourceControlAiSettings } from '../../../../shared/source-cont import { structuredChatNamingDeps } from './structured-chat-naming-runtime' import type { AgentJournalSnapshot } from '../../../../shared/agent-session/journal/agent-session-journal-types' import type * as TextGeneration from '../../../text-generation/commit-message-text-generation' +import * as shellEnvironment from '../environment/structured-agent-shell-environment' +import { resolveHostStructuredAgentLaunchEnvironment } from '../launch/structured-agent-launch-support' const mocks = vi.hoisted(() => ({ account: vi.fn((_provider: string, id: string) => ({ @@ -43,6 +45,7 @@ vi.mock('../../../managed-data-accounts/service', () => ({ })) const roots: string[] = [] afterEach(async () => { + vi.restoreAllMocks() installClaudeProfileRouter(undefined) await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) }) @@ -74,6 +77,29 @@ function rig() { } describe('structured chat naming runtime', () => { + it('resolves Claude naming inheritance before the deliberate agent launch environment', async () => { + const inherited = { + CLAUDE_CODE_MESSAGING_SOCKET: 'parent-socket', + CLAUDE_CODE_ENTRYPOINT: 'parent-client', + CLAUDE_EFFORT: 'parent-effort', + CLAUDE_CODE_HTTP_PROXY: 'http://user-proxy' + } + vi.spyOn(shellEnvironment, 'resolveHostAgentBaseEnvironment').mockResolvedValue(inherited) + const settings = getDefaultSettings('/isolated') + settings.agentDefaultEnv = { claude: { CLAUDE_EFFORT: 'chosen-effort' } } + const env = await resolveHostStructuredAgentLaunchEnvironment('claude', settings) + expect(env).toMatchObject({ + CLAUDE_EFFORT: 'chosen-effort', + CLAUDE_CODE_HTTP_PROXY: 'http://user-proxy' + }) + expect(env.CLAUDE_CODE_MESSAGING_SOCKET).toBeUndefined() + expect(env.CLAUDE_CODE_ENTRYPOINT).toBeUndefined() + expect( + (await resolveHostStructuredAgentLaunchEnvironment('codex', settings)).CLAUDE_EFFORT + ).toBe('parent-effort') + expect(inherited.CLAUDE_CODE_MESSAGING_SOCKET).toBe('parent-socket') + }) + it.each(['grok', 'antigravity'] as const)( 'codes %s native naming failures without exposing provider text', async (provider) => { diff --git a/src/main/text-generation/commit-message-agent-environment.test.ts b/src/main/text-generation/commit-message-agent-environment.test.ts index a3aba7e4e0d..6347cc3e11a 100644 --- a/src/main/text-generation/commit-message-agent-environment.test.ts +++ b/src/main/text-generation/commit-message-agent-environment.test.ts @@ -1,7 +1,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { prepareLocalCommitMessageAgentEnv } from './commit-message-agent-environment' import { ManagedCodexHomeTemporarilyUnavailableError } from '../codex-accounts/host-codex-managed-home-ownership' @@ -10,6 +10,7 @@ const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') const tempDirs: string[] = [] afterEach(() => { + vi.unstubAllEnvs() if (originalPlatform) { Object.defineProperty(process, 'platform', originalPlatform) } @@ -36,6 +37,42 @@ function makeHome(): string { } describe('prepareLocalCommitMessageAgentEnv', () => { + it('isolates Claude generation inheritance before account overrides, including resolver fallbacks', async () => { + vi.stubEnv('CLAUDE_CODE_MESSAGING_SOCKET', 'parent-socket') + vi.stubEnv('CLAUDE_AGENT_SDK_VERSION', 'parent-sdk') + vi.stubEnv('CLAUDE_CODE_HTTP_PROXY', 'http://user-proxy') + for (const resolvers of [undefined, {}]) { + const result = await prepareLocalCommitMessageAgentEnv('claude', resolvers) + if (!result.ok) { + throw new Error(result.error) + } + expect(result.env?.CLAUDE_CODE_MESSAGING_SOCKET).toBeUndefined() + expect(result.env?.CLAUDE_AGENT_SDK_VERSION).toBeUndefined() + expect(result.env?.CLAUDE_CODE_HTTP_PROXY).toBe('http://user-proxy') + } + const configured = await prepareLocalCommitMessageAgentEnv('claude', { + resolveBaseEnvironment: async () => ({ + CLAUDE_CODE_MESSAGING_SOCKET: 'shell-parent', + CLAUDE_EFFORT: 'shell-effort', + CLAUDE_CODE_HTTP_PROXY: 'http://shell-proxy' + }), + prepareForClaudeLaunch: async () => ({ + configDir: '/chosen/claude', + envPatch: { CLAUDE_EFFORT: 'chosen-effort', ANTHROPIC_AUTH_TOKEN: 'chosen-token' }, + provenance: 'profile:test' + }) + }) + expect(configured).toEqual({ + ok: true, + env: { + CLAUDE_CODE_HTTP_PROXY: 'http://shell-proxy', + CLAUDE_EFFORT: 'chosen-effort', + ANTHROPIC_AUTH_TOKEN: 'chosen-token' + } + }) + expect(await prepareLocalCommitMessageAgentEnv('custom', undefined)).toEqual({ ok: true }) + }) + it('hydrates OpenCode config dir from shell startup files for headless generation', async () => { const home = makeHome() delete process.env.OPENCODE_CONFIG_DIR diff --git a/src/main/text-generation/commit-message-agent-environment.ts b/src/main/text-generation/commit-message-agent-environment.ts index 64eb32a97a0..1874ba7c076 100644 --- a/src/main/text-generation/commit-message-agent-environment.ts +++ b/src/main/text-generation/commit-message-agent-environment.ts @@ -2,6 +2,7 @@ import type { ClaudeRuntimeAuthPreparation } from '../claude-accounts/runtime-au import { applyClaudeEnvPatch } from '../claude-accounts/environment' import { readShellStartupEnvVar } from '../pty/shell-startup/shell-startup-env' import { parseWslUncPath } from '../../shared/wsl-paths' +import { stripInheritedClaudeSessionEnv } from '../../shared/agent-launch/startup/claude-parent-session-env' export type CommitMessageAgentEnvironmentResolvers = { prepareForCodexLaunch?: ( @@ -114,10 +115,16 @@ export async function prepareLocalCommitMessageAgentEnv( if (shellConfigEnv) { return shellConfigEnv } - if (!resolvers) { + if (!resolvers && agentId !== 'claude') { return { ok: true } } const base = hostBase ?? cloneProcessEnv() + if (agentId === 'claude') { + stripInheritedClaudeSessionEnv(base) + } + if (!resolvers) { + return { ok: true, env: base } + } try { if (agentId === 'codex' && resolvers.prepareForCodexLaunch) { @@ -158,5 +165,5 @@ export async function prepareLocalCommitMessageAgentEnv( } } - return hostBase ? { ok: true, env: hostBase } : { ok: true } + return hostBase || agentId === 'claude' ? { ok: true, env: base } : { ok: true } } diff --git a/src/shared/agent-launch/startup/claude-parent-session-env.ts b/src/shared/agent-launch/startup/claude-parent-session-env.ts new file mode 100644 index 00000000000..309f9f8a3cb --- /dev/null +++ b/src/shared/agent-launch/startup/claude-parent-session-env.ts @@ -0,0 +1,57 @@ +// A launching Claude's identity and messaging access do not belong to independent processes. +export const CLAUDE_CHILD_SESSION_STAMP_ENV_KEYS = [ + 'CLAUDECODE', + 'CLAUDE_CODE_CHILD_SESSION', + 'CLAUDE_CODE_SESSION_ID', + 'CLAUDE_CODE_BRIDGE_SESSION_ID', + 'CLAUDE_CODE_HOST_SESSION_ID', + 'CLAUDE_CODE_SESSION_ATTENDED', + 'CLAUDE_CODE_MESSAGING_SOCKET', + 'CLAUDE_CODE_MESSAGING_TOKEN', + 'CLAUDE_CODE_EXECPATH', + 'CLAUDE_CODE_ENTRYPOINT', + 'CLAUDE_CODE_DESKTOP_APP_VERSION', + 'CLAUDE_EFFORT', + 'CLAUDE_PID', + 'CLAUDE_AGENT_SDK_VERSION' +] as const + +const stampKeys = new Set(CLAUDE_CHILD_SESSION_STAMP_ENV_KEYS) + +export function canonicalClaudeSessionStampEnvKey(key: string, platform: NodeJS.Platform): string { + const normalized = platform === 'win32' ? key.toUpperCase() : key + return stampKeys.has(normalized) ? normalized : key +} + +/** The separate launch overlay, never the merged environment, owns any deliberate session values. */ +export function stripInheritedClaudeSessionEnv( + env: NodeJS.ProcessEnv, + { + launchEnv, + envToDelete = [], + platform = process.platform + }: { + launchEnv?: NodeJS.ProcessEnv + envToDelete?: readonly string[] + platform?: NodeJS.Platform + } = {} +): void { + const explicit = Object.entries(launchEnv ?? {}) + for (const key of Object.keys(env)) { + if (stampKeys.has(canonicalClaudeSessionStampEnvKey(key, platform))) { + delete env[key] + } + } + for (const [key, value] of explicit) { + const canonical = canonicalClaudeSessionStampEnvKey(key, platform) + if (value !== undefined && stampKeys.has(canonical)) { + env[canonical] = value + } + } + for (const key of envToDelete) { + const canonical = canonicalClaudeSessionStampEnvKey(key, platform) + if (stampKeys.has(canonical)) { + delete env[canonical] + } + } +}