Skip to content

The agent that grows with you

fix(update): support uv default venv in desktop updates

KoNit-Kb6cc751e5ff5
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index b0d26919533..e8a9672895d 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -428,6 +428,7 @@ import {
import {
formatBlockerMessage,
formatProbeFailedMessage,
+ resolveVenvDir,
scanVenvBlockers,
stopSafeVenvBlockers
} from './venv-blocker-scan'
@@ -3458,9 +3459,10 @@ function repairMacUpdaterHelper(updater) {
// fresh entry points. On Windows this is the file the running backend
// `hermes.exe` holds open; on POSIX it's never mandatory-locked.
function venvHermesShimPath(updateRoot) {
+ const venvDir = resolveVenvDir(updateRoot)
return IS_WINDOWS
- ? path.join(updateRoot, 'venv', 'Scripts', 'hermes.exe')
- : path.join(updateRoot, 'venv', 'bin', 'hermes')
+ ? path.join(venvDir, 'Scripts', 'hermes.exe')
+ : path.join(venvDir, 'bin', 'hermes')
}
// Best-effort lock probe mirroring the Rust updater's is_locked(): a running
@@ -3506,7 +3508,7 @@ function killHermesOwnedVenvDaemons(updateRoot) {
return
}
- const scriptsDir = path.join(updateRoot, 'venv', 'Scripts')
+ const scriptsDir = path.join(resolveVenvDir(updateRoot), 'Scripts')
let holders = []
@@ -4079,7 +4081,7 @@ async function applyUpdates(opts: { stopSafeBlockers?: boolean } = {}) {
updaterArgs.push('--target-app', targetApp)
}
- const venvBin = path.join(updateRoot, 'venv', IS_WINDOWS ? 'Scripts' : 'bin')
+ const venvBin = path.join(resolveVenvDir(updateRoot), IS_WINDOWS ? 'Scripts' : 'bin')
// ── Pre-flight state.db integrity guard (#68474) ─────────────────
// Emergency backup and header verification before the update touches
@@ -4371,7 +4373,7 @@ async function handOffWindowsBootstrapRecovery(reason) {
? await resolveHealedBranch(updateRoot, configuredBranch || DEFAULT_UPDATE_BRANCH)
: configuredBranch || DEFAULT_UPDATE_BRANCH
- const venvBin = path.join(updateRoot, 'venv', IS_WINDOWS ? 'Scripts' : 'bin')
+ const venvBin = path.join(resolveVenvDir(updateRoot), IS_WINDOWS ? 'Scripts' : 'bin')
const venvHermes = path.join(venvBin, IS_WINDOWS ? 'hermes.exe' : 'hermes')
const venvPython = path.join(venvBin, IS_WINDOWS ? 'python.exe' : 'python')
@@ -4630,7 +4632,7 @@ async function applyUpdatesPosixHandoff(opts: any) {
...process.env,
HERMES_HOME,
HERMES_UPDATE_STARTED_AT: String(updateStartedAt),
- PATH: pathWithHermesManagedNode(path.join(updateRoot, 'venv', 'bin'))
+ PATH: pathWithHermesManagedNode(path.join(resolveVenvDir(updateRoot), 'bin'))
},
detached: true,
stdio: 'ignore'
diff --git a/apps/desktop/electron/updater-process.ts b/apps/desktop/electron/updater-process.ts
index 70af87a2880..7a575e93893 100644
--- a/apps/desktop/electron/updater-process.ts
+++ b/apps/desktop/electron/updater-process.ts
@@ -3,11 +3,12 @@ import { existsSync, statSync } from 'node:fs'
import path from 'node:path'
import { hiddenWindowsChildOptions } from './windows-child-options'
+import { resolveVenvDir } from './venv-blocker-scan'
/** File prerequisites only: dependency recovery must remain reachable through update. */
export function windowsUpdatePrerequisiteError(updateRoot: string): string | null {
const maintainedDir = path.join(updateRoot, 'scripts', 'desktop-update')
- const required = [path.join(updateRoot, 'venv', 'Scripts', 'python.exe')]
+ const required = [path.join(resolveVenvDir(updateRoot), 'Scripts', 'python.exe')]
// Pre-reorg flat scripts remain supported; damaged modern trees do not.
if (existsSync(maintainedDir)) {
diff --git a/apps/desktop/electron/venv-blocker-scan.test.ts b/apps/desktop/electron/venv-blocker-scan.test.ts
index bc62f788493..8641f061997 100644
--- a/apps/desktop/electron/venv-blocker-scan.test.ts
+++ b/apps/desktop/electron/venv-blocker-scan.test.ts
@@ -18,6 +18,7 @@ import {
formatBlockerMessage,
formatProbeFailedMessage,
parseVenvBlockerScanOutput,
+ resolveVenvDir,
resolveVenvPython,
scanVenvBlockers,
stopSafeVenvBlockers
@@ -44,6 +45,51 @@ describe('resolveVenvPython', () => {
}
})
+ it('resolves a uv-default .venv python when legacy venv is absent', () => {
+ const sandbox = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-vt-'))
+
+ try {
+ const scriptsDir = process.platform === 'win32' ? 'Scripts' : 'bin'
+ const pythonName = process.platform === 'win32' ? 'python.exe' : 'python3'
+ const dir = path.join(sandbox, '.venv', scriptsDir)
+ fs.mkdirSync(dir, { recursive: true })
+ const pyPath = path.join(dir, pythonName)
+ fs.writeFileSync(pyPath, '', { mode: 0o755 })
+ assert.equal(resolveVenvPython(sandbox), pyPath)
+ } finally {
+ fs.rmSync(sandbox, { recursive: true, force: true })
+ }
+ })
+
+ it('uses the Windows Scripts interpreter in a uv-default .venv', () => {
+ const sandbox = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-vt-'))
+ const platform = Object.getOwnPropertyDescriptor(process, 'platform')
+
+ try {
+ const dir = path.join(sandbox, '.venv', 'Scripts')
+ fs.mkdirSync(dir, { recursive: true })
+ const pyPath = path.join(dir, 'python.exe')
+ fs.writeFileSync(pyPath, '', { mode: 0o755 })
+ Object.defineProperty(process, 'platform', { value: 'win32' })
+ assert.equal(resolveVenvPython(sandbox), pyPath)
+ } finally {
+ if (platform) Object.defineProperty(process, 'platform', platform)
+ fs.rmSync(sandbox, { recursive: true, force: true })
+ }
+ })
+
+ it('keeps legacy venv precedence when both supported layouts exist', () => {
+ const sandbox = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-vt-'))
+
+ try {
+ fs.mkdirSync(path.join(sandbox, 'venv'), { recursive: true })
+ fs.mkdirSync(path.join(sandbox, '.venv'), { recursive: true })
+ assert.equal(resolveVenvDir(sandbox), path.join(sandbox, 'venv'))
+ } finally {
+ fs.rmSync(sandbox, { recursive: true, force: true })
+ }
+ })
+
it('returns null for non-existent venv', () => {
assert.equal(resolveVenvPython('/nonexistent'), null)
})
diff --git a/apps/desktop/electron/venv-blocker-scan.ts b/apps/desktop/electron/venv-blocker-scan.ts
index d891d750521..e0e9b3911a1 100644
--- a/apps/desktop/electron/venv-blocker-scan.ts
+++ b/apps/desktop/electron/venv-blocker-scan.ts
@@ -259,12 +259,29 @@ export async function scanVenvBlockers(
// Internal helpers (exported for testing)
// ---------------------------------------------------------------------------
-/** Resolve the venv python path. Returns null if the file does not exist. */
+/** Resolve the supported venv directory, preserving legacy ``venv`` precedence. */
+export function resolveVenvDir(updateRoot: string): string {
+ for (const name of ['venv', '.venv']) {
+ const candidate = path.join(updateRoot, name)
+
+ try {
+ if (fs.statSync(candidate).isDirectory()) {
+ return candidate
+ }
+ } catch {
+ // Try the other supported layout, then retain the legacy path for diagnostics.
+ }
+ }
+
+ return path.join(updateRoot, 'venv')
+}
+
+/** Resolve the venv python path. Returns null if the selected runtime is missing. */
export function resolveVenvPython(updateRoot: string): string | null {
const isWindows = process.platform === 'win32'
const pythonName = isWindows ? 'python.exe' : 'python3'
const scriptsDir = isWindows ? 'Scripts' : 'bin'
- const candidate = path.join(updateRoot, 'venv', scriptsDir, pythonName)
+ const candidate = path.join(resolveVenvDir(updateRoot), scriptsDir, pythonName)
try {
fs.accessSync(candidate)
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 3f777354c68..df18ca45741 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -18,7 +18,7 @@ from pathlib import Path
from hermes_cli.config import get_hermes_home # noqa: F401 (re-exported; patched via update_cmd)
from hermes_cli.update_cmd_common import _best_effort
-from hermes_constants import get_default_hermes_root, venv_python_path
+from hermes_constants import get_default_hermes_root, project_venv_dir, venv_python_path
# Re-exports: every split-module name stays reachable (and monkeypatchable) as update_cmd.<name>.
from hermes_cli.update_abort_recovery import ( # noqa: F401
@@ -613,8 +613,8 @@ def _repair_venv_on_current_checkout(
from hermes_cli.managed_uv import ensure_uv
repair_uv = ensure_uv()
# Venv gone entirely (repair interrupted after the old one was moved aside): recreate.
- venv_python_missing = not (
- venv_python_path(_m().PROJECT_ROOT / "venv", windows=_m()._is_windows())).exists()
+ venv_dir = project_venv_dir(_m().PROJECT_ROOT) or _m().PROJECT_ROOT / "venv"
+ venv_python_missing = not venv_python_path(venv_dir, windows=_m()._is_windows()).exists()
if venv_python_missing and repair_uv:
print("→ Recreating virtual environment...")
subprocess.run([repair_uv, "venv", "venv"], cwd=_m().PROJECT_ROOT, check=False)
@@ -655,7 +655,7 @@ def _pip_install_prefix(uv_bin) -> tuple[list[str], dict | None]:
# See #83914.
from hermes_cli.managed_uv import managed_python_env
env = managed_python_env()
- env["VIRTUAL_ENV"] = str(_m().PROJECT_ROOT / "venv")
+ env["VIRTUAL_ENV"] = str(project_venv_dir(_m().PROJECT_ROOT) or _m().PROJECT_ROOT / "venv")
return [uv_bin, "pip"], env
return [sys.executable, "-m", "pip"], None
diff --git a/hermes_cli/update_cmd_deps.py b/hermes_cli/update_cmd_deps.py
index b0c0c97d14d..a3d1b881704 100644
--- a/hermes_cli/update_cmd_deps.py
+++ b/hermes_cli/update_cmd_deps.py
@@ -12,7 +12,7 @@ import subprocess
import sys
from pathlib import Path
from typing import Optional
-from hermes_constants import venv_python_path
+from hermes_constants import project_venv_dir, venv_python_path
from hermes_cli._subprocess_compat import bounded_probe_run
# Log-record parity with the origin module.
@@ -85,7 +85,8 @@ def _critical_module_import_failures(
try:
interpreter = sys.executable
with suppress(Exception):
- venv_python = venv_python_path(Path(root) / "venv", windows=_m()._is_windows())
+ venv_dir = project_venv_dir(root) or Path(root) / "venv"
+ venv_python = venv_python_path(venv_dir, windows=_m()._is_windows())
if venv_python.exists():
interpreter = str(venv_python)
result = bounded_probe_run(
@@ -638,7 +639,7 @@ def _venv_core_imports_healthy() -> tuple[bool, str]:
imports, catching a half-updated venv that "Already up to date!" would otherwise never re-sync.
Returns ``(healthy, detail)``; never raises, unknown states report healthy."""
from hermes_cli.update_cmd import _m
- venv_dir = _m().PROJECT_ROOT / "venv"
+ venv_dir = project_venv_dir(_m().PROJECT_ROOT) or _m().PROJECT_ROOT / "venv"
venv_python = venv_python_path(venv_dir, windows=_m()._is_windows())
if not venv_python.exists():
# No venv: normal for a dev checkout (healthy), but on a MANAGED install (bootstrap
diff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.py
index 22fd48cf4ff..b213122c21f 100644
--- a/hermes_cli/update_cmd_windows.py
+++ b/hermes_cli/update_cmd_windows.py
@@ -146,7 +146,9 @@ def _detect_venv_python_processes(*, exclude_pids: set[int] | None = None) -> li
psutil = _psutil()
if not _m()._is_windows() or psutil is None:
return []
- venv_prefix = _lower_dir_prefix(_m().PROJECT_ROOT / "venv")
+ from hermes_constants import project_venv_dir
+ venv_dir = project_venv_dir(_m().PROJECT_ROOT) or _m().PROJECT_ROOT / "venv"
+ venv_prefix = _lower_dir_prefix(venv_dir)
root_prefix = _lower_dir_prefix(_m().PROJECT_ROOT)
skip = set(exclude_pids or set()) | _self_and_non_gateway_ancestor_pids(psutil)
matches: list[tuple[int, str, str]] = []
@@ -298,7 +300,9 @@ def _venv_launcher_ancestors(pids: list[int]) -> list[int]:
psutil = _psutil()
if not _m()._is_windows() or not pids or psutil is None:
return []
- venv_prefix = _lower_dir_prefix(_m().PROJECT_ROOT / "venv")
+ from hermes_constants import project_venv_dir
+ venv_dir = project_venv_dir(_m().PROJECT_ROOT) or _m().PROJECT_ROOT / "venv"
+ venv_prefix = _lower_dir_prefix(venv_dir)
skip = _self_and_non_gateway_ancestor_pids(psutil) | set(pids)
found: list[int] = []
for pid in pids:
diff --git a/hermes_cli/update_cmd_zip.py b/hermes_cli/update_cmd_zip.py
index 01a98c62336..f8f73072838 100644
--- a/hermes_cli/update_cmd_zip.py
+++ b/hermes_cli/update_cmd_zip.py
@@ -14,6 +14,7 @@ from pathlib import Path
from typing import Optional
from hermes_cli.update_cmd_common import _best_effort
+from hermes_constants import project_venv_dir
# Log-record parity with the origin module.
logger = logging.getLogger("hermes_cli.update_cmd")
@@ -333,7 +334,7 @@ def _reinstall_python_deps_after_zip(active_tool_dependencies) -> None:
# from unrelated software must not steer which interpreter uv resolves here.
from hermes_cli.managed_uv import managed_python_env
uv_env = managed_python_env()
- uv_env["VIRTUAL_ENV"] = str(_m().PROJECT_ROOT / "venv")
+ uv_env["VIRTUAL_ENV"] = str(project_venv_dir(_m().PROJECT_ROOT) or _m().PROJECT_ROOT / "venv")
if _m()._is_termux_env(uv_env):
uv_env.pop("PYTHONPATH", None)
uv_env.pop("PYTHONHOME", None)
diff --git a/scripts/desktop-update/windows.ps1 b/scripts/desktop-update/windows.ps1
index 5124b2123d2..56b508011ff 100644
--- a/scripts/desktop-update/windows.ps1
+++ b/scripts/desktop-update/windows.ps1
@@ -1185,6 +1185,16 @@ function Set-InstallRootCurrentDirectory([string]$Root) {
return $resolved
}
+function Resolve-HermesVenvDir([string]$Root) {
+ # Match hermes_constants.project_venv_dir(): installer-created venv wins,
+ # while uv-default .venv remains a supported source-install layout.
+ $legacy = Join-Path $Root "venv"
+ if (Test-Path -LiteralPath $legacy -PathType Container) { return $legacy }
+ $uvDefault = Join-Path $Root ".venv"
+ if (Test-Path -LiteralPath $uvDefault -PathType Container) { return $uvDefault }
+ return $legacy
+}
+
$finalCode = 1
$finalMsg = "update did not complete"
$script:TreeSafeToFinalize = $true
@@ -1465,6 +1475,8 @@ try {
exit $finalCode
}
+ $VenvDir = Resolve-HermesVenvDir $InstallRoot
+
# Exercise the production cwd setup and native launcher without updating.
if ($SelfTestWorkingDirectory) {
$expectedRoot = [System.IO.Path]::GetFullPath($InstallRoot)
@@ -1483,7 +1495,7 @@ try {
}
# Check only the interpreter here: dependency recovery belongs to update.
- $pythonExe = Join-Path $InstallRoot "venv\Scripts\python.exe"
+ $pythonExe = Join-Path $VenvDir "Scripts\python.exe"
if (-not (Test-Path -LiteralPath $pythonExe -PathType Leaf)) {
$finalCode = 3
$finalMsg = "Update aborted: $pythonExe is missing. Repair the installation and review antivirus quarantine before retrying."
@@ -1514,7 +1526,7 @@ try {
# -- 2. Wait for the venv shim to unlock (FAIL CLOSED) ------------------
Publish-UiProgress "Preparing Hermes files"
- $shim = Join-Path $InstallRoot "venv\Scripts\hermes.exe"
+ $shim = Join-Path $VenvDir "Scripts\hermes.exe"
if (Test-Path -LiteralPath $shim) {
$unlocked = $false
$deadline = (Get-Date).AddSeconds(20)
@@ -1577,7 +1589,7 @@ try {
#
# posix.sh is deliberately left alone: unlinking a running executable is
# legal there, so the equivalent call is harmless.
- $pythonExe = Join-Path $InstallRoot "venv\Scripts\python.exe"
+ $pythonExe = Join-Path $VenvDir "Scripts\python.exe"
if (-not (Test-Path -LiteralPath $pythonExe)) {
$finalCode = 3
$finalMsg = "Update aborted: $pythonExe is missing. The install needs repair (run the Hermes installer or `hermes doctor`)."
diff --git a/tests/hermes_cli/test_update_venv_health.py b/tests/hermes_cli/test_update_venv_health.py
index 77f0dc4ac12..5e034f907b0 100644
--- a/tests/hermes_cli/test_update_venv_health.py
+++ b/tests/hermes_cli/test_update_venv_health.py
@@ -119,6 +119,24 @@ def test_detect_venv_python_prefetches_only_cheap_process_fields(_winp, tmp_path
unrelated.cwd.assert_not_called()
[email protected](cli_main, "_is_windows", return_value=True)
+def test_detect_venv_python_matches_uv_default_dotvenv(_winp, tmp_path):
+ venv_py = str(tmp_path / ".venv" / "Scripts" / "python.exe")
+ holder = _proc(104, venv_py, "python.exe", [venv_py, "-m", "hermes_cli.main", "serve"])
+ me = MagicMock()
+ me.parents.return_value = []
+ fake_psutil = types.SimpleNamespace(
+ process_iter=lambda attrs: iter([holder]),
+ Process=lambda *a, **k: me,
+ )
+ (tmp_path / ".venv").mkdir()
+
+ with patch.object(cli_main, "PROJECT_ROOT", tmp_path), patch.dict(sys.modules, {"psutil": fake_psutil}):
+ matches = cli_main._detect_venv_python_processes()
+
+ assert [match[0] for match in matches] == [104]
+
+
@patch.object(cli_main, "_is_windows", return_value=True)
def test_detect_venv_python_keeps_external_interpreter_fallback(_winp, tmp_path):
external = _proc(
diff --git a/tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py b/tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py
index 679483a0c18..321be355544 100644
--- a/tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py
+++ b/tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py
@@ -113,6 +113,16 @@ def test_update_no_longer_invokes_the_hermes_exe_shim() -> None:
)
+def test_handoff_resolves_uv_default_dotvenv_before_building_python_and_shim_paths() -> None:
+ source = _read()
+
+ assert "function Resolve-HermesVenvDir" in source
+ assert 'Join-Path $Root ".venv"' in source
+ assert "$VenvDir = Resolve-HermesVenvDir $InstallRoot" in source
+ assert 'Join-Path $VenvDir "Scripts\\python.exe"' in source
+ assert 'Join-Path $VenvDir "Scripts\\hermes.exe"' in source
+
+
def test_desktop_relaunch_waits_for_an_in_place_rebuild() -> None:
source = _read()
relaunch = re.search(