Skip to content

The agent that grows with you

fix(desktop): forward --profile into the packaged desktop launch

brooklyn!8684bf3ddc24
diff --git a/apps/desktop/electron/launch-profile.test.ts b/apps/desktop/electron/launch-profile.test.ts
new file mode 100644
index 00000000000..c7180107c2e
--- /dev/null
+++ b/apps/desktop/electron/launch-profile.test.ts
@@ -0,0 +1,94 @@
+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'
+
+import { serveBackendArgs } from './backend-command'
+import { createDesktopProfilePreferences } from './desktop-profile'
+import { applyLaunchProfileOverride, parseLaunchProfile } from './launch-profile'
+
+function withStoredProfile(profile: string, run: (target: string) => void) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'launch-profile-'))
+ const target = path.join(root, 'active-profile.json')
+ const preferences = createDesktopProfilePreferences(target)
+
+ try {
+ preferences.remember(profile)
+ preferences.setDefault({ connectionId: null, profile })
+ run(target)
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+}
+
+test('parses both --profile spellings and ignores a missing flag', () => {
+ assert.equal(parseLaunchProfile(['Hermes.exe', '--profile', 'desktop']), 'desktop')
+ assert.equal(parseLaunchProfile(['Hermes.exe', '--profile=desktop']), 'desktop')
+ assert.equal(parseLaunchProfile(['open', '-a', 'Hermes', '--args', '--profile', 'work']), 'work')
+ assert.equal(parseLaunchProfile(['Hermes.exe', '--local']), null)
+ assert.equal(parseLaunchProfile(['Hermes.exe']), null)
+})
+
+test('normalizes a launch profile the same way the CLI does', () => {
+ assert.equal(parseLaunchProfile(['Hermes.exe', '--profile', ' Desktop ']), 'desktop')
+ assert.equal(parseLaunchProfile(['Hermes.exe', '--profile=Work']), 'work')
+ assert.equal(parseLaunchProfile(['Hermes.exe', '--profile', 'default']), 'default')
+ assert.equal(parseLaunchProfile(['Hermes.exe', '--profile']), null)
+ assert.equal(parseLaunchProfile(['Hermes.exe', '--profile=']), null)
+ assert.equal(parseLaunchProfile(['Hermes.exe', '--profile', 'my profile']), null)
+ assert.equal(parseLaunchProfile(['Hermes.exe', '--profile', '-desktop']), null)
+})
+
+test('a launch --profile is persisted before the backend reads active-profile.json', () => {
+ withStoredProfile('stored', target => {
+ const preferences = createDesktopProfilePreferences(target)
+
+ const launched = applyLaunchProfileOverride(['Hermes.exe', '--profile', 'desktop'], name => {
+ preferences.remember(name)
+ })
+
+ const restarted = createDesktopProfilePreferences(target)
+
+ assert.equal(launched, 'desktop')
+ assert.equal(restarted.readActive(), 'desktop')
+ assert.deepEqual(restarted.getDefault(), { connectionId: null, profile: 'stored' })
+ assert.deepEqual(serveBackendArgs(restarted.readActive() ?? undefined).slice(0, 2), ['--profile', 'desktop'])
+ })
+})
+
+test('--profile=<name> persists the same profile the space spelling does', () => {
+ withStoredProfile('stored', target => {
+ const preferences = createDesktopProfilePreferences(target)
+
+ applyLaunchProfileOverride(['Hermes.exe', '--ozone-platform=wayland', '--profile=desktop'], name => {
+ preferences.remember(name)
+ })
+
+ assert.equal(createDesktopProfilePreferences(target).readActive(), 'desktop')
+ })
+})
+
+test('a missing or invalid flag does not change the stored profile', () => {
+ for (const argv of [
+ ['Hermes.exe'],
+ ['Hermes.exe', '--local'],
+ ['Hermes.exe', '--profile'],
+ ['Hermes.exe', '--profile', 'Not a name'],
+ ['Hermes.exe', '--profile=../desktop']
+ ]) {
+ withStoredProfile('stored', target => {
+ const before = fs.readFileSync(target, 'utf8')
+ let persisted = false
+
+ const launched = applyLaunchProfileOverride(argv, () => {
+ persisted = true
+ })
+
+ assert.equal(launched, null)
+ assert.equal(persisted, false)
+ assert.equal(fs.readFileSync(target, 'utf8'), before)
+ })
+ }
+})
diff --git a/apps/desktop/electron/launch-profile.ts b/apps/desktop/electron/launch-profile.ts
new file mode 100644
index 00000000000..4a9be343fb5
--- /dev/null
+++ b/apps/desktop/electron/launch-profile.ts
@@ -0,0 +1,58 @@
+import { DESKTOP_PROFILE_NAME_RE } from './desktop-profile'
+
+/**
+ * Profile from `--profile <name>` or `--profile=<name>`.
+ *
+ * Missing, empty, and invalid values are null so a launch without a usable
+ * flag leaves the stored desktop profile alone. Names are trimmed and
+ * lowercased to match the CLI's `-p` / `--profile` normalization.
+ */
+export function parseLaunchProfile(argv: readonly string[]): string | null {
+ if (!Array.isArray(argv)) {
+ return null
+ }
+
+ for (let index = 0; index < argv.length; index++) {
+ const arg = argv[index]
+
+ if (typeof arg !== 'string') {
+ continue
+ }
+
+ if (arg === '--profile') {
+ return normalizeLaunchProfile(argv[index + 1])
+ }
+
+ if (arg.startsWith('--profile=')) {
+ return normalizeLaunchProfile(arg.slice('--profile='.length))
+ }
+ }
+
+ return null
+}
+
+function normalizeLaunchProfile(raw: unknown): string | null {
+ if (typeof raw !== 'string') {
+ return null
+ }
+
+ const name = raw.trim().toLowerCase()
+
+ return name && DESKTOP_PROFILE_NAME_RE.test(name) ? name : null
+}
+
+/**
+ * Persist a launch-time profile before startHermes reads active-profile.json.
+ * A missing or invalid flag does not call persist.
+ */
+export function applyLaunchProfileOverride(argv: readonly string[], persist: (name: string) => void): string | null {
+ const name = parseLaunchProfile(argv)
+
+ if (!name) {
+ return null
+ }
+
+ persist(name)
+
+ return name
+}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 8b0a79e8b19..4704a0a9c45 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -62,7 +62,7 @@ import {
processStartMarker,
REAP_PROBE_TIMEOUT_MS
} from './backend-claim'
-import { dashboardFallbackArgs } from './backend-command'
+import { dashboardFallbackArgs, serveBackendArgs } from './backend-command'
import { createBackendConnectionState } from './backend-connection-state'
import { BackendDialClaims } from './backend-dial-claim'
import type { HostBackendRecord } from './backend-discovery'
@@ -206,6 +206,7 @@ import {
resolveDesktopConnectionRequest,
resolveDesktopWindowLaunch
} from './desktop-profile'
+import { applyLaunchProfileOverride } from './launch-profile'
import { registryPrimaryBootRoute, resolveDesktopRemoteRoute, v1SshTerminalPoolKey } from './desktop-remote-route'
import {
buildPosixCleanupScript,
@@ -12791,18 +12792,15 @@ async function runHermesStart({ supervisorRecovery = false }: { supervisorRecove
}
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']
-
- // Pin the desktop's chosen profile via the global --profile flag. This is
- // deterministic (it wins over the sticky ~/.hermes/active_profile file) and
- // resolves HERMES_HOME the same way `hermes -p <name>` does on the CLI. An
- // unset preference keeps the legacy launch so existing installs are
- // unaffected. `activeProfile` is the SAME decision that pinned routing
- // above — never re-read here (#108417).
- if (activeProfile) {
- backendArgs.unshift('--profile', activeProfile)
- }
+ // Pin the desktop's chosen profile via the global --profile flag. A launch
+ // override is persisted into active-profile.json before startHermes, so
+ // Hermes.exe --profile <name> and hermes -p <name> desktop both land here.
+ // Null (no stored preference, no launch flag) keeps the legacy bare serve
+ // so the child still follows the sticky active_profile file.
+ // `activeProfile` is the SAME decision that pinned routing above — never
+ // re-read here (#108417). (--port 0: the OS assigns an ephemeral port; the
+ // child announces it on stdout.)
+ const backendArgs = serveBackendArgs(activeProfile || undefined)
const setup = await runPrimaryBackendStartup({
signal: localBackendLifecycle.signal,
@@ -18520,6 +18518,18 @@ if (!isPrimaryInstance) {
// routes into the running window and never touches backend machinery.
app.exit(0)
} else {
+ // Cold-start --profile must win over the stored preference before
+ // startHermes() reads active-profile.json. Only the instance that will
+ // boot writes: a second launch must not retarget the running app. A missing
+ // or invalid flag is a no-op, so the stored profile stays.
+ try {
+ applyLaunchProfileOverride(process.argv, name => {
+ writeActiveDesktopProfile(name)
+ })
+ } catch (error) {
+ console.error('[hermes] failed to persist --profile launch override:', error)
+ }
+
app.on('second-instance', (_event, argv) => {
const url = _extractDeepLink(argv)
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index 980877cb589..3007cd9c4d5 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -426,6 +426,9 @@ _startup_fast.ensure_project_root_on_path()
# HERMES_HOME set, and the flag stripped so argparse never sees it. Falls back
# to ~/.hermes/active_profile for the sticky default.
_PROFILE_NAME_RE = r"^[a-z0-9][a-z0-9_-]{0,63}$" # mirrors hermes_cli.profiles._PROFILE_ID_RE
+# Set only when -p/--profile was on argv. Sticky active_profile must not count:
+# `hermes desktop` with no flag must not overwrite Desktop's stored profile.
+_explicit_cli_profile: str | None = None
def _inside_mcp_add_args(argv: list, index: int) -> bool:
@@ -575,8 +578,19 @@ def _s6_supervised_gateway_run(argv: list) -> bool:
return _s6_running()
+def explicit_cli_profile() -> str | None:
+ """Profile named by a consumed ``-p``/``--profile`` flag, else None.
+
+ Sticky ``active_profile`` is not explicit. Desktop launch must not overwrite
+ its stored profile when the user omitted the flag.
+ """
+ return _explicit_cli_profile
+
+
def _apply_profile_override() -> None:
"""Pre-parse --profile/-p and set HERMES_HOME before imports."""
+ global _explicit_cli_profile
+ _explicit_cli_profile = None
argv = sys.argv[1:]
profile_name, consume, profile_index = _scan_profile_flag(argv)
@@ -622,6 +636,8 @@ def _apply_profile_override() -> None:
print(f"Warning: profile override failed ({exc}), using default", file=sys.stderr)
return
os.environ["HERMES_HOME"] = hermes_home
+ if consume > 0:
+ _explicit_cli_profile = profile_name
# Strip the flag from argv so argparse doesn't choke
if consume > 0 and profile_index is not None:
start = profile_index + 1 # +1 because argv is sys.argv[1:]
diff --git a/hermes_cli/main_desktop.py b/hermes_cli/main_desktop.py
index ed0944168a7..9c0d52c310c 100644
--- a/hermes_cli/main_desktop.py
+++ b/hermes_cli/main_desktop.py
@@ -1543,6 +1543,11 @@ def cmd_gui(args: argparse.Namespace):
launch_command.extend(config_electron_flags)
if getattr(args, "local", False):
launch_command.append("--local")
+ # Explicit -p/--profile only. A bare `hermes desktop` must not forward the
+ # sticky CLI profile — Electron would persist it over the stored desktop one.
+ from hermes_cli.main import explicit_cli_profile
+ if profile := explicit_cli_profile():
+ launch_command.extend(["--profile", profile])
if not source_mode:
desktop_launch_notice(f"→ Launching packaged Hermes Desktop: {' '.join(launch_command)}")
pass_fds: tuple[int, ...] = ()
diff --git a/tests/hermes_cli/test_desktop_profile_launch.py b/tests/hermes_cli/test_desktop_profile_launch.py
new file mode 100644
index 00000000000..88fa3bed248
--- /dev/null
+++ b/tests/hermes_cli/test_desktop_profile_launch.py
@@ -0,0 +1,138 @@
+"""hermes desktop forwards an explicit profile into the packaged Electron launch.
+
+Electron boots from active-profile.json. ``hermes -p <name> desktop`` used to
+set only the CLI HERMES_HOME, so the packaged app still started the stored
+profile. A launch with no ``-p`` / ``--profile`` must not invent a flag.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+from argparse import Namespace
+from pathlib import Path
+
+import pytest
+
+from hermes_cli import main as cli_main
+from hermes_cli import main_desktop
+
+
+def _ns(**kwargs):
+ defaults = dict(
+ skip_build=True,
+ build_only=False,
+ force_build=False,
+ source=False,
+ fake_boot=False,
+ ignore_existing=False,
+ hermes_root=None,
+ cwd=None,
+ setup_tcc_identity=False,
+ identity=None,
+ local=False,
+ )
+ defaults.update(kwargs)
+ return Namespace(**defaults)
+
+
+def _named_profiles(argv: list[str]) -> set[str]:
+ names: set[str] = set()
+ for index, arg in enumerate(argv):
+ if arg in {"-p", "--profile"} and index + 1 < len(argv):
+ names.add(argv[index + 1].strip().casefold())
+ elif arg.startswith("--profile="):
+ names.add(arg.split("=", 1)[1].strip().casefold())
+ names.discard("default")
+ return names
+
+
+def _packaged_exe(root: Path) -> Path:
+ desktop_dir = root / "apps" / "desktop"
+ if sys.platform == "darwin":
+ exe = desktop_dir / "release" / "mac-arm64" / "Hermes.app" / "Contents" / "MacOS" / "Hermes"
+ elif sys.platform == "win32":
+ exe = desktop_dir / "release" / "win-unpacked" / "Hermes.exe"
+ else:
+ exe = desktop_dir / "release" / "linux-unpacked" / "hermes"
+ exe.parent.mkdir(parents=True, exist_ok=True)
+ (exe.parent / "chrome-sandbox").write_text("", encoding="utf-8")
+ exe.parent.mkdir(parents=True, exist_ok=True)
+ exe.write_text("", encoding="utf-8")
+ return exe
+
+
+def _live_profile(root: Path, name: str) -> None:
+ profile = root / "profiles" / name
+ profile.mkdir(parents=True, exist_ok=True)
+ (profile / "config.yaml").write_text("{}\n", encoding="utf-8")
+
+
+def _launch_command(tmp_path, monkeypatch, argv: list[str], *, active_profile: str | None = None) -> list[str]:
+ hermes_root = tmp_path / ".hermes"
+ hermes_root.mkdir()
+ if active_profile and active_profile != "default":
+ _live_profile(hermes_root, active_profile)
+ (hermes_root / "active_profile").write_text(active_profile + "\n", encoding="utf-8")
+ for name in _named_profiles(argv):
+ _live_profile(hermes_root, name)
+
+ project = tmp_path / "hermes-agent"
+ (project / "apps" / "desktop").mkdir(parents=True)
+ (project / "apps" / "desktop" / "package.json").write_text("{}", encoding="utf-8")
+ exe = _packaged_exe(project)
+
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.delenv("HERMES_HOME", raising=False)
+ monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "xdg"))
+ monkeypatch.setenv("GNOME_KEYRING_CONTROL", "/run/user/1000/keyring")
+ for var in (
+ "HERMES_SUPERVISED_CHILD",
+ "HERMES_S6_SUPERVISED_CHILD",
+ "INVOCATION_ID",
+ "HERMES_GATEWAY_EXTERNAL_SUPERVISOR",
+ "KDE_SESSION_VERSION",
+ "KDE_FULL_SESSION",
+ ):
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setattr(sys, "argv", argv)
+ monkeypatch.setattr(cli_main, "PROJECT_ROOT", project)
+ monkeypatch.setattr(main_desktop, "_desktop_exe_integrity_error", lambda _path: None)
+
+ cli_main._apply_profile_override()
+
+ calls: list[list[str]] = []
+
+ def _run(cmd, **_kwargs):
+ calls.append(list(cmd))
+ return subprocess.CompletedProcess(cmd, 0)
+
+ monkeypatch.setattr(subprocess, "run", _run)
+ with pytest.raises(SystemExit) as exc:
+ cli_main.cmd_gui(_ns())
+ assert exc.value.code == 0
+ launches = [cmd for cmd in calls if cmd and cmd[0] == str(exe)]
+ assert len(launches) == 1
+ return launches[0]
+
+
+def test_dash_p_desktop_appends_profile_to_packaged_launch(tmp_path, monkeypatch):
+ launched = _launch_command(tmp_path, monkeypatch, ["hermes", "-p", "desktop", "desktop"])
+
+ assert launched[-2:] == ["--profile", "desktop"]
+
+
+def test_profile_equals_spelling_is_forwarded(tmp_path, monkeypatch):
+ launched = _launch_command(tmp_path, monkeypatch, ["hermes", "desktop", "--profile=work"])
+
+ assert launched[-2:] == ["--profile", "work"]
+
+
+def test_missing_flag_does_not_forward_sticky_profile(tmp_path, monkeypatch):
+ launched = _launch_command(
+ tmp_path, monkeypatch, ["hermes", "desktop"], active_profile="coder"
+ )
+
+ assert "--profile" not in launched
+ assert os.environ.get("HERMES_HOME", "").endswith(f"{os.sep}profiles{os.sep}coder")