Skip to content

The agent that grows with you

fix(desktop): profile backend env drops the launch profile's dotenv names

brooklyn!d17f5191ccec
diff --git a/apps/desktop/electron/backend-env.test.ts b/apps/desktop/electron/backend-env.test.ts
index 74571692f22..36fcda19924 100644
--- a/apps/desktop/electron/backend-env.test.ts
+++ b/apps/desktop/electron/backend-env.test.ts
@@ -1,4 +1,6 @@
import assert from 'node:assert/strict'
+import fs from 'node:fs'
+import os from 'node:os'
import path from 'node:path'
import { test } from 'vitest'
@@ -10,7 +12,8 @@ import {
hermesManagedNodePathEntries,
normalizeHermesHomeRoot,
pathEnvKey,
- POSIX_SANE_PATH_ENTRIES
+ POSIX_SANE_PATH_ENTRIES,
+ profileBackendParentEnv
} from './backend-env'
test('desktop backend PATH adds Hermes-managed bins and missing POSIX sane entries', () => {
@@ -205,3 +208,120 @@ test('Windows PATH casing and delimiter are preserved without POSIX sane entries
test('appendUniquePathEntries drops empty entries and keeps first occurrence', () => {
assert.equal(appendUniquePathEntries([':/a::/b', ['/a', '/c']], { delimiter: ':' }), '/a:/b:/c')
})
+
+// `hermes desktop` loads its launch profile's .env/.op.env into os.environ and
+// hands that env to Electron; these cover what a profile backend inherits (#68367).
+function withHermesRoot(files: Record<string, string>, run: (root: string) => void) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-profile-env-'))
+
+ try {
+ for (const [rel, contents] of Object.entries(files)) {
+ fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true })
+ fs.writeFileSync(path.join(root, rel), contents)
+ }
+
+ run(root)
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+}
+
+const ROOT_SCOPE_FILES = {
+ '.env': '\uFEFFTLON_SHIP_URL=https://moon.invalid\nexport TLON_SHIP_CODE = "root-code" # moon\nPATH=/root/bin\n',
+ '.op.env': 'OP_SERVICE_ACCOUNT_TOKEN=root-op\n',
+ 'profiles/urbot/.env': 'ANTHROPIC_API_KEY=urbot-key\n'
+}
+
+const ROOT_LAUNCHED_ENV = {
+ HOME: '/Users/test',
+ PATH: '/usr/bin:/bin',
+ TLON_SHIP_URL: 'https://moon.invalid',
+ TLON_SHIP_CODE: 'root-code',
+ OP_SERVICE_ACCOUNT_TOKEN: 'root-op',
+ OPENROUTER_API_KEY: 'shell-key'
+}
+
+test('a named profile backend does not inherit secrets the root .env/.op.env loaded into Desktop', () => {
+ withHermesRoot(ROOT_SCOPE_FILES, root => {
+ const env = profileBackendParentEnv({
+ hermesHome: root,
+ profile: 'urbot',
+ currentEnv: ROOT_LAUNCHED_ENV,
+ platform: 'linux'
+ })
+
+ // Shell exports the root dotenv never declared, and OS names, still reach the child.
+ assert.deepEqual(env, { HOME: '/Users/test', PATH: '/usr/bin:/bin', OPENROUTER_API_KEY: 'shell-key' })
+ })
+})
+
+test('the launch profile backend inherits the Desktop env unchanged', () => {
+ withHermesRoot(ROOT_SCOPE_FILES, root => {
+ for (const profile of ['default', null, undefined]) {
+ assert.deepEqual(
+ profileBackendParentEnv({ hermesHome: root, profile, currentEnv: ROOT_LAUNCHED_ENV, platform: 'linux' }),
+ ROOT_LAUNCHED_ENV
+ )
+ }
+ })
+})
+
+test('a primary backend without an explicit profile follows the sticky active_profile', () => {
+ withHermesRoot({ ...ROOT_SCOPE_FILES, active_profile: 'urbot\n' }, root => {
+ const env = profileBackendParentEnv({ hermesHome: root, profile: null, currentEnv: ROOT_LAUNCHED_ENV })
+
+ assert.equal(env.TLON_SHIP_CODE, undefined)
+ assert.equal(env.OP_SERVICE_ACCOUNT_TOKEN, undefined)
+ assert.equal(env.OPENROUTER_API_KEY, 'shell-key')
+ })
+})
+
+test('Desktop launched from a named profile keeps that profile out of the default backend', () => {
+ withHermesRoot(
+ {
+ '.env': 'OPENAI_API_KEY=root-key\n',
+ 'profiles/work/.env': 'TLON_SHIP_CODE=work-code\nOP_SERVICE_ACCOUNT_TOKEN=work-op\n'
+ },
+ root => {
+ const currentEnv = {
+ HERMES_HOME: path.join(root, 'profiles', 'work'),
+ TLON_SHIP_CODE: 'work-code',
+ OP_SERVICE_ACCOUNT_TOKEN: 'work-op',
+ OPENAI_API_KEY: 'shell-key'
+ }
+
+ assert.deepEqual(profileBackendParentEnv({ hermesHome: root, profile: 'default', currentEnv }), {
+ HERMES_HOME: currentEnv.HERMES_HOME,
+ OPENAI_API_KEY: 'shell-key'
+ })
+ assert.deepEqual(profileBackendParentEnv({ hermesHome: root, profile: 'work', currentEnv }), currentEnv)
+ }
+ )
+})
+
+test('Windows matches profile homes and dotenv names case-insensitively', () => {
+ const root = 'C:\\Users\\test\\AppData\\Local\\hermes'
+ const files = { [`${root}\\.env`]: 'TELEGRAM_BOT_TOKEN=root-token\r\n' }
+
+ const fsModule = {
+ readFileSync: file => {
+ if (!(file in files)) {
+ throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' })
+ }
+
+ return files[file]
+ }
+ }
+
+ const currentEnv = {
+ HERMES_HOME: 'c:\\users\\test\\appdata\\local\\HERMES',
+ Path: 'C:\\Windows',
+ Telegram_Bot_Token: 'root-token'
+ }
+
+ const scoped = (profile: string) =>
+ profileBackendParentEnv({ hermesHome: root, profile, currentEnv, platform: 'win32', fsModule })
+
+ assert.deepEqual(scoped('default'), currentEnv)
+ assert.deepEqual(scoped('urbot'), { HERMES_HOME: currentEnv.HERMES_HOME, Path: 'C:\\Windows' })
+})
diff --git a/apps/desktop/electron/backend-env.ts b/apps/desktop/electron/backend-env.ts
index f3fd8c81975..2ed1d67e9a0 100644
--- a/apps/desktop/electron/backend-env.ts
+++ b/apps/desktop/electron/backend-env.ts
@@ -1,3 +1,4 @@
+import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
@@ -104,6 +105,22 @@ function buildDesktopBackendPath({
return appendUniquePathEntries([hermesNodeDirs, venvBin, currentPath, saneEntries], { delimiter })
}
+function resolveHermesHomePath(hermesHome, { pathModule, homedir = os.homedir() }: any) {
+ // fish (and any shell when the value is quoted) hands a literal `~` through; path.resolve()
+ // would pin it under cwd and the Python backend inherits that absolute path via HERMES_HOME.
+ let raw = String(hermesHome)
+
+ if (raw === '~' || raw.startsWith('~/') || (pathModule === path.win32 && raw.startsWith('~\\'))) {
+ raw = pathModule.join(homedir, raw.slice(1))
+ }
+
+ return pathModule.resolve(raw)
+}
+
+function isProfileHome(resolved, pathModule) {
+ return pathModule.basename(pathModule.dirname(resolved)).toLowerCase() === 'profiles'
+}
+
function normalizeHermesHomeRoot(
hermesHome,
{ pathModule = pathModuleForPlatform(process.platform), homedir = os.homedir() }: any = {}
@@ -112,22 +129,104 @@ function normalizeHermesHomeRoot(
return hermesHome
}
- // fish (and any shell when the value is quoted) hands a literal `~` through; path.resolve()
- // would pin it under cwd and the Python backend inherits that absolute path via HERMES_HOME.
- let raw = String(hermesHome)
+ const resolved = resolveHermesHomePath(hermesHome, { pathModule, homedir })
- if (raw === '~' || raw.startsWith('~/') || (pathModule === path.win32 && raw.startsWith('~\\'))) {
- raw = pathModule.join(homedir, raw.slice(1))
+ return isProfileHome(resolved, pathModule) ? pathModule.dirname(pathModule.dirname(resolved)) : resolved
+}
+
+// OS/interpreter names a dotenv may redeclare that no child can run without.
+const PROCESS_ENV_NAMES = new Set([
+ 'APPDATA',
+ 'COMSPEC',
+ 'HERMES_HOME',
+ 'HOME',
+ 'LANG',
+ 'LC_ALL',
+ 'LOCALAPPDATA',
+ 'PATH',
+ 'PWD',
+ 'PYTHONPATH',
+ 'SHELL',
+ 'SSL_CERT_FILE',
+ 'SYSTEMROOT',
+ 'TEMP',
+ 'TMP',
+ 'TMPDIR',
+ 'TZ',
+ 'USER',
+ 'USERPROFILE',
+ 'VIRTUAL_ENV'
+])
+
+function dotenvKeyNames(contents = '') {
+ return String(contents)
+ .replace(/^\uFEFF/, '')
+ .split(/\r?\n/)
+ .flatMap(line => line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/)?.slice(1, 2) ?? [])
+}
+
+function readTextOrEmpty(fsModule, file) {
+ try {
+ return String(fsModule.readFileSync(file, 'utf8'))
+ } catch {
+ return ''
+ }
+}
+
+/**
+ * Parent env for a local `hermes serve` child of `profile` (#68367).
+ *
+ * `hermes desktop` loads its launch profile's `.env`/`.op.env` into os.environ
+ * before exec'ing Electron, so `process.env` carries that profile's platform
+ * credentials. A child for ANOTHER profile would inherit them ahead of its own
+ * dotenv (`.op.env` is even skipped once OP_SERVICE_ACCOUNT_TOKEN is set) and,
+ * e.g., connect the same Tlon ship as the default gateway. Drop every name the
+ * launch profile's dotenv declares, as `_profile_action_environment` does for
+ * dashboard actions; the child reloads its own scope. The launch profile's own
+ * backend keeps the env unchanged, and shell exports the launch dotenv never
+ * declared pass through everywhere.
+ *
+ * `profile` null/empty means no `--profile` flag: the child follows the sticky
+ * `active_profile` like a bare `hermes serve` (`_apply_profile_override`).
+ */
+function profileBackendParentEnv({
+ hermesHome,
+ profile,
+ currentEnv = process.env,
+ platform = process.platform,
+ fsModule = fs,
+ pathModule = pathModuleForPlatform(platform)
+}: any = {}) {
+ const env = { ...(currentEnv || {}) }
+
+ if (!hermesHome) {
+ return env
}
- const resolved = pathModule.resolve(raw)
- const parent = pathModule.dirname(resolved)
+ const fold = platform === 'win32' ? (value: string) => value.toUpperCase() : (value: string) => value
+ const inheritedHome = currentEnv?.HERMES_HOME ? resolveHermesHomePath(currentEnv.HERMES_HOME, { pathModule }) : null
+ const launchHome = inheritedHome && isProfileHome(inheritedHome, pathModule) ? inheritedHome : hermesHome
+ const name = profile || readTextOrEmpty(fsModule, pathModule.join(hermesHome, 'active_profile')).trim()
+ const targetHome = !name || name === 'default' ? hermesHome : pathModule.join(hermesHome, 'profiles', name)
+
+ if (fold(pathModule.resolve(launchHome)) === fold(pathModule.resolve(targetHome))) {
+ return env
+ }
- if (pathModule.basename(parent).toLowerCase() === 'profiles') {
- return pathModule.dirname(parent)
+ const launchOwned = new Set(
+ ['.env', '.op.env']
+ .flatMap(file => dotenvKeyNames(readTextOrEmpty(fsModule, pathModule.join(launchHome, file))))
+ .filter(key => !PROCESS_ENV_NAMES.has(key.toUpperCase()))
+ .map(fold)
+ )
+
+ for (const key of Object.keys(env)) {
+ if (launchOwned.has(fold(key))) {
+ delete env[key]
+ }
}
- return resolved
+ return env
}
function buildDesktopBackendEnv({
@@ -169,5 +268,6 @@ export {
hermesManagedNodePathEntries,
normalizeHermesHomeRoot,
pathEnvKey,
- POSIX_SANE_PATH_ENTRIES
+ POSIX_SANE_PATH_ENTRIES,
+ profileBackendParentEnv
}