The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Port from cline/cline#12482 era: login-shell PATH resolution for GUI-launched desktop (cline/cline#12429)
Tekniumc13105a8c5ee
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 132200f9488..ccc5b8aa39e 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -260,6 +260,7 @@ import {SESSION_WINDOW_MIN_HEIGHT,SESSION_WINDOW_MIN_WIDTH} from './session-windows'+import { ensureLoginShellPath } from './shell-path'import { ensureSpawnHelperExecutable } from './spawn-helper-perms'import { createBootstrapCoordinator, sshConfigFingerprint } from './ssh-bootstrap-coordinator'import { collectSshConfigHosts, parseSshGOutput } from './ssh-config'@@ -10170,6 +10171,30 @@ async function startHermes() {await advanceBootProgress('backend.resolve', 'Resolving Hermes backend', 8)// Resolve for the desktop's primary profile so a per-profile remote// override on the active profile is honored (falls back to env / global).++ // Mutual exclusion with an in-app update (#50238). If this instance was+ // relaunched while the Tauri updater is still applying an update, spawning+ // a local backend now re-locks the venv shim and gets killed by the+ // updater's straggler cleanup — looping. Park until the update finishes (or+ // is detected stale), THEN start the backend. Local backends only; remote+ // connections returned above and never touch the install tree.+ await waitForUpdateToFinish()++ // GUI launches (Finder/Dock, desktop launchers) inherit a minimal PATH+ // that skips the user's shell profiles. Merge the login-shell PATH into+ // process.env BEFORE resolving the runtime or spawning the backend, so+ // both the Electron-side resolvers and the whole backend subtree (tool+ // availability checks, stdio MCP servers) can find Homebrew-, nvm-, and+ // ~/.local/bin-installed CLIs. Single-flight with the whenReady warmup;+ // failure-hardened — a broken shell profile never blocks boot.+ const loginShellPath = await ensureLoginShellPath()++ if (loginShellPath.applied) {+ rememberLog('[env] merged login-shell PATH into process.env for backend spawn')+ } else if (loginShellPath.reason && !['win32', 'unchanged'].includes(loginShellPath.reason)) {+ rememberLog(`[env] login-shell PATH resolution unavailable (${loginShellPath.reason}); keeping inherited PATH`)+ }+const token = crypto.randomBytes(32).toString('base64url')// --port 0: the OS assigns an ephemeral port; the child announces it on stdout.const backendArgs = ['serve', '--host', '127.0.0.1', '--port', '0']@@ -14698,6 +14723,10 @@ app.on('open-url', (event, url) => {})app.whenReady().then(() => {+ // Warm the login-shell PATH resolution immediately so it usually completes+ // before the backend start path awaits the same single-flight promise.+ void ensureLoginShellPath()+const systemCa = installWindowsSystemCaTrust(tls)if (systemCa.applied) {diff --git a/apps/desktop/electron/shell-path.test.ts b/apps/desktop/electron/shell-path.test.tsnew file mode 100644index 00000000000..e2767833140--- /dev/null+++ b/apps/desktop/electron/shell-path.test.ts@@ -0,0 +1,147 @@+import assert from 'node:assert/strict'++import { beforeEach, test } from 'vitest'++import {+ applyLoginShellPath,+ ensureLoginShellPath,+ extractSentinelPath,+ loginShellExecutable,+ mergeLoginShellPath,+ resetLoginShellPathForTests+} from './shell-path'++const START = '__HERMES_LOGIN_PATH_START__'+const END = '__HERMES_LOGIN_PATH_END__'++function fakeExecFile(outputsByFlags, { error = null, calls = [] }: any = {}) {+ return (file, args, _options, callback) => {+ calls.push({ file, args })+ const flags = args[0]+ const stdout = outputsByFlags[flags] ?? ''+ queueMicrotask(() => callback(error, stdout, ''))++ return { stdin: { end() {} } }+ }+}++beforeEach(() => {+ resetLoginShellPathForTests()+})++test('extractSentinelPath survives profile banner noise around the markers', () => {+ const stdout = `Welcome to my shell!\nmotd garbage\n${START}/opt/homebrew/bin:/usr/bin${END}trailing noise`+ assert.equal(extractSentinelPath(stdout), '/opt/homebrew/bin:/usr/bin')+})++test('extractSentinelPath uses the last start marker (echoed command lines cannot poison it)', () => {+ const stdout = `${START}poisoned-echo${END}\n${START}/real/path${END}`+ assert.equal(extractSentinelPath(stdout), '/real/path')+})++test('extractSentinelPath returns null when markers are missing or empty', () => {+ assert.equal(extractSentinelPath('no markers here'), null)+ assert.equal(extractSentinelPath(`${START}${END}`), null)+ assert.equal(extractSentinelPath(`${START}/half/open`), null)+})++test('mergeLoginShellPath puts login entries first and appends current-only entries', () => {+ const merged = mergeLoginShellPath(+ '/opt/homebrew/bin:/Users/u/.local/bin:/usr/bin:/bin',+ '/usr/bin:/bin:/launcher/only',+ { delimiter: ':' }+ )++ assert.equal(merged, '/opt/homebrew/bin:/Users/u/.local/bin:/usr/bin:/bin:/launcher/only')+})++test('loginShellExecutable honors $SHELL and falls back per platform', () => {+ assert.equal(loginShellExecutable({ SHELL: '/usr/local/bin/fish' }, 'darwin'), '/usr/local/bin/fish')+ assert.equal(loginShellExecutable({}, 'darwin'), '/bin/zsh')+ assert.equal(loginShellExecutable({}, 'linux'), '/bin/bash')+})++test('applyLoginShellPath merges the captured login PATH into the env', async () => {+ const env: any = { SHELL: '/bin/zsh', PATH: '/usr/bin:/bin' }+ const calls: any[] = []+ const execFileFn = fakeExecFile({ '-ilc': `${START}/opt/homebrew/bin:/Users/u/.cargo/bin:/usr/bin${END}` }, { calls })++ const result = await applyLoginShellPath({ env, platform: 'darwin', execFileFn })++ assert.equal(result.applied, true)+ assert.equal(env.PATH, '/opt/homebrew/bin:/Users/u/.cargo/bin:/usr/bin:/bin')+ assert.equal(calls.length, 1)+ assert.equal(calls[0].file, '/bin/zsh')+ assert.equal(calls[0].args[0], '-ilc')+})++test('applyLoginShellPath falls back to -lc when -ilc yields no sentinel (bash 3.2 swallow)', async () => {+ const env: any = { SHELL: '/bin/bash', PATH: '/usr/bin' }+ const calls: any[] = []+ const execFileFn = fakeExecFile({ '-ilc': 'swallowed', '-lc': `${START}/opt/homebrew/bin:/usr/bin${END}` }, { calls })++ const result = await applyLoginShellPath({ env, platform: 'darwin', execFileFn })++ assert.equal(result.applied, true)+ assert.deepEqual(+ calls.map(call => call.args[0]),+ ['-ilc', '-lc']+ )+ assert.equal(env.PATH, '/opt/homebrew/bin:/usr/bin')+})++test('applyLoginShellPath leaves the env untouched when resolution fails', async () => {+ const env: any = { SHELL: '/bin/zsh', PATH: '/usr/bin:/bin' }+ const execFileFn = fakeExecFile({}, { error: new Error('boom') })++ const result = await applyLoginShellPath({ env, platform: 'darwin', execFileFn })++ assert.equal(result.applied, false)+ assert.equal(result.reason, 'unresolved')+ assert.equal(env.PATH, '/usr/bin:/bin')+})++test('applyLoginShellPath reports unchanged when the login PATH adds nothing new', async () => {+ const env: any = { SHELL: '/bin/zsh', PATH: '/opt/homebrew/bin:/usr/bin' }+ const execFileFn = fakeExecFile({ '-ilc': `${START}/opt/homebrew/bin:/usr/bin${END}` })++ const result = await applyLoginShellPath({ env, platform: 'darwin', execFileFn })++ assert.equal(result.applied, false)+ assert.equal(result.reason, 'unchanged')+ assert.equal(env.PATH, '/opt/homebrew/bin:/usr/bin')+})++test('applyLoginShellPath is a no-op on Windows', async () => {+ const env: any = { Path: 'C:\\Windows\\System32' }+ const result = await applyLoginShellPath({ env, platform: 'win32' })++ assert.equal(result.applied, false)+ assert.equal(result.reason, 'win32')+ assert.equal(env.Path, 'C:\\Windows\\System32')+})++test('ensureLoginShellPath is single-flight — concurrent callers share one shell probe', async () => {+ const env: any = { SHELL: '/bin/zsh', PATH: '/usr/bin' }+ const calls: any[] = []+ const execFileFn = fakeExecFile({ '-ilc': `${START}/opt/homebrew/bin:/usr/bin${END}` }, { calls })++ const [first, second] = await Promise.all([+ ensureLoginShellPath({ env, platform: 'darwin', execFileFn }),+ ensureLoginShellPath({ env, platform: 'darwin', execFileFn })+ ])++ assert.equal(first.applied, true)+ assert.equal(second.applied, true)+ assert.equal(calls.length, 1)+ assert.equal(env.PATH, '/opt/homebrew/bin:/usr/bin')+})++test('ensureLoginShellPath never rejects', async () => {+ const execFileFn = () => {+ throw new Error('spawn EACCES')+ }++ const result = await ensureLoginShellPath({ env: { SHELL: '/bin/zsh' }, platform: 'darwin', execFileFn })+ assert.equal(result.applied, false)+})diff --git a/apps/desktop/electron/shell-path.ts b/apps/desktop/electron/shell-path.tsnew file mode 100644index 00000000000..54923df0740--- /dev/null+++ b/apps/desktop/electron/shell-path.ts@@ -0,0 +1,187 @@+import { execFile } from 'node:child_process'++import { appendUniquePathEntries, delimiterForPlatform, pathEnvKey } from './backend-env'++// Login-shell PATH resolution for GUI launches.+//+// A desktop app launched from Finder/Dock (macOS launchd) or a desktop+// environment's launcher (Linux) inherits a minimal PATH such as+// /usr/bin:/bin:/usr/sbin:/sbin — none of the user's shell profiles ever run.+// backend-env.ts papers over the common cases with a static sane-entry list+// (Homebrew, /usr/local), but anything only a profile adds — ~/.local/bin,+// nvm/pyenv/asdf shims, ~/.cargo/bin, nix profiles — stays invisible to the+// backend process. That breaks tool availability checks (shutil.which), stdio+// MCP server spawns, and the Electron-side binary resolvers.+//+// Fix (same approach as VS Code's shell-environment resolution; ported from+// cline/cline#12429): run the user's shell once as an interactive login shell,+// capture $PATH between sentinel markers so profile banners can't corrupt the+// value, and merge it into process.env — login-shell entries first (so+// /opt/homebrew/bin wins), current-only entries appended (so dirs injected by+// the launching environment aren't lost).+//+// Failure hardening: a broken/slow shell profile must never brick app startup.+// Every attempt is bounded by a timeout, stdin is closed immediately, and any+// failure leaves PATH untouched.++const PATH_START = '__HERMES_LOGIN_PATH_START__'+const PATH_END = '__HERMES_LOGIN_PATH_END__'+const PROBE_COMMAND = "printf '%s' \"" + PATH_START + '${PATH}' + PATH_END + '"'+const ATTEMPT_TIMEOUT_MS = 5000++function loginShellExecutable(env: any = process.env, platform = process.platform) {+ const shell = typeof env?.SHELL === 'string' ? env.SHELL.trim() : ''++ if (shell) {+ return shell+ }++ // macOS Catalina+ defaults to zsh; most Linux distros default to bash.+ return platform === 'darwin' ? '/bin/zsh' : '/bin/bash'+}++// Extract $PATH from between the sentinel markers. Uses the LAST start marker+// so a profile that echoes the environment (or the command line itself) can't+// poison the capture with an earlier partial match.+function extractSentinelPath(stdout) {+ const text = String(stdout || '')+ const start = text.lastIndexOf(PATH_START)++ if (start === -1) {+ return null+ }++ const valueStart = start + PATH_START.length+ const end = text.indexOf(PATH_END, valueStart)++ if (end === -1) {+ return null+ }++ return text.slice(valueStart, end).trim() || null+}++// Login-shell entries first (Homebrew/version-manager dirs win), then any+// current-only entries appended, duplicates and empties dropped.+function mergeLoginShellPath(loginPath, currentPath, { delimiter = ':' }: any = {}) {+ return appendUniquePathEntries([loginPath, currentPath], { delimiter })+}++function runProbe(shell, flags, execFileFn, timeoutMs): Promise<string | null> {+ return new Promise(resolve => {+ let settled = false++ const finish = value => {+ if (!settled) {+ settled = true+ resolve(value)+ }+ }++ try {+ const child = execFileFn(+ shell,+ [...flags, PROBE_COMMAND],+ { encoding: 'utf8', timeout: timeoutMs, windowsHide: true },+ (_error, stdout) => {+ // A profile script may exit nonzero after the sentinel already+ // printed — trust the sentinel, not the exit code.+ finish(extractSentinelPath(stdout))+ }+ )++ // Interactive shells with a broken rc can block reading stdin.+ child?.stdin?.end?.()+ } catch {+ finish(null)+ }+ })+}++async function captureLoginShellPath({+ env = process.env,+ platform = process.platform,+ execFileFn = execFile,+ timeoutMs = ATTEMPT_TIMEOUT_MS+}: any = {}) {+ if (platform === 'win32') {+ // GUI apps on Windows inherit the user PATH from the registry env block;+ // the launchd-minimal-PATH problem is POSIX-only.+ return null+ }++ const shell = loginShellExecutable(env, platform)++ // -l sources ~/.zprofile / ~/.profile (where `brew shellenv` lives); -i+ // sources ~/.zshrc / ~/.bashrc (where nvm/pyenv-style managers live). Some+ // shells swallow combined -ilc with a non-tty stdin (macOS system bash 3.2+ // — see tests/tools/test_find_shell.py), so fall back to a plain login+ // shell before giving up.+ for (const flags of [['-ilc'], ['-lc']]) {+ const captured = await runProbe(shell, flags, execFileFn, timeoutMs)++ if (captured) {+ return captured+ }+ }++ return null+}++async function applyLoginShellPath({+ env = process.env,+ platform = process.platform,+ execFileFn = execFile,+ timeoutMs = ATTEMPT_TIMEOUT_MS+}: any = {}) {+ if (platform === 'win32') {+ return { applied: false, reason: 'win32' }+ }++ const loginPath = await captureLoginShellPath({ env, platform, execFileFn, timeoutMs })++ if (!loginPath) {+ return { applied: false, reason: 'unresolved' }+ }++ const key = pathEnvKey(env, platform)+ const delimiter = delimiterForPlatform(platform)+ const merged = mergeLoginShellPath(loginPath, env?.[key] || '', { delimiter })++ if (!merged || merged === env?.[key]) {+ return { applied: false, reason: 'unchanged', path: merged }+ }++ env[key] = merged++ return { applied: true, path: merged }+}++// Single-flight: the warmup at app start and the await before the backend+// spawn share one resolution. Never rejects.+let _ensurePromise: Promise<any> | null = null++function ensureLoginShellPath(options: any = {}) {+ if (!_ensurePromise) {+ _ensurePromise = applyLoginShellPath(options).catch(error => ({+ applied: false,+ reason: String(error?.message || error)+ }))+ }++ return _ensurePromise+}++function resetLoginShellPathForTests() {+ _ensurePromise = null+}++export {+ applyLoginShellPath,+ captureLoginShellPath,+ ensureLoginShellPath,+ extractSentinelPath,+ loginShellExecutable,+ mergeLoginShellPath,+ resetLoginShellPathForTests+}