The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): prevent venv scan timeout on busy Windows hosts
andyst-dev4d3e1e4d132b
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 0dfb816567a..bc8a5408b04 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -3810,7 +3810,7 @@ async function applyUpdates(opts: { stopSafeBlockers?: boolean } = {}) {}if (scanOutcome.kind === 'probe-failure') {- const message = formatProbeFailedMessage()+ const message = formatProbeFailedMessage(scanOutcome.error)rememberLog(`[updates] venv-blocker probe failed: ${scanOutcome.error}`)emitUpdateProgress({ stage: 'error', message, percent: null })diff --git a/apps/desktop/electron/venv-blocker-scan.test.ts b/apps/desktop/electron/venv-blocker-scan.test.tsindex 9eaa22c26c2..1b9c07a61c5 100644--- a/apps/desktop/electron/venv-blocker-scan.test.ts+++ b/apps/desktop/electron/venv-blocker-scan.test.ts@@ -75,6 +75,12 @@ describe('formatProbeFailedMessage', () => {assert.ok(msg.includes('hermes update'))assert.ok(msg.includes('retry'))})++ it('distinguishes a timeout from a confirmed blocker', () => {+ const msg = formatProbeFailedMessage('timed out after 60 seconds')+ assert.ok(msg.includes('timed out after 60 seconds'))+ assert.ok(msg.includes('no blocking process was confirmed'))+ })})// ---------------------------------------------------------------------------@@ -254,6 +260,15 @@ describe('scanVenvBlockers', () => {}) as any}+ function execTimeout(): any {+ return (async (...args: any[]) => {+ const e: any = new Error()+ e.killed = true+ e.signal = 'SIGTERM'+ throw e+ }) as any+ }+it('clear scan returns clear', async () => {assert.equal((await scanVenvBlockers('/r', execReturn(okJson), stubVenv)).kind, 'clear')})@@ -267,6 +282,14 @@ describe('scanVenvBlockers', () => {assert.equal(o.kind, 'probe-failure')})+ it('reports a timed-out subprocess explicitly', async () => {+ const o = await scanVenvBlockers('/r', execTimeout(), stubVenv)+ assert.deepEqual(o, {+ kind: 'probe-failure',+ error: 'timed out after 60 seconds'+ })+ })+it('missing venv python is probe-failure', async () => {const o = await scanVenvBlockers('/r', execReturn(okJson), () => null)assert.equal(o.kind, 'probe-failure')@@ -292,8 +315,7 @@ describe('scanVenvBlockers', () => {assert.ok(c.cmd.endsWith('python.exe'))assert.deepEqual(c.args, ['-m', 'hermes_cli._scan_venv_blockers'])assert.equal(c.cwd, '/update/root')- assert.equal(typeof c.timeout, 'number')- assert.ok(c.timeout > 0)+ assert.equal(c.timeout, 60_000)})})diff --git a/apps/desktop/electron/venv-blocker-scan.ts b/apps/desktop/electron/venv-blocker-scan.tsindex 0b687d3531e..d891d750521 100644--- a/apps/desktop/electron/venv-blocker-scan.ts+++ b/apps/desktop/electron/venv-blocker-scan.ts@@ -45,7 +45,10 @@ export type ScanOutcome =// Constants// ----------------------------------------------------------------------------const SCAN_TIMEOUT_MS = 15000+// A Windows process table can take longer than 15 seconds to inspect on busy+// hosts. Keep a watchdog for genuinely wedged probes, but leave enough headroom+// for the scanner's conservative fallback checks.+const SCAN_TIMEOUT_MS = 60000const SCAN_MODULE = 'hermes_cli._scan_venv_blockers'// ---------------------------------------------------------------------------@@ -204,7 +207,7 @@ export function parseVenvBlockerScanOutput(raw: string): ScanOutcome {/*** Run the venv-blocker scan subprocess. Async so the Electron main-process- * event loop is never blocked by the psutil process scan (up to 15s on a+ * event loop is never blocked by the psutil process scan (tens of seconds on a* loaded Windows box). Accepts optional overrides for testing (dependency* injection).*/@@ -233,6 +236,13 @@ export async function scanVenvBlockers(stdout = String((proc as any).stdout ?? '')} catch (err: any) {+ if (err?.killed === true) {+ return {+ kind: 'probe-failure',+ error: `timed out after ${SCAN_TIMEOUT_MS / 1000} seconds`+ }+ }+const diag = [`exit code ${err.status ?? err.code ?? -1}`]if (err.stderr) {@@ -298,10 +308,15 @@ export function formatBlockerMessage(result: VenvBlockerScanResult): string {/*** Build a probe-failure error message.*/-export function formatProbeFailedMessage(): string {+export function formatProbeFailedMessage(error?: string): string {+ const timeoutDetail = error?.startsWith('timed out after')+ ? `\n\nThe verification scan ${error}; no blocking process was confirmed.`+ : ''+return (- 'Update aborted: Desktop could not verify the Hermes installation is free.\n' +- '\n' ++ 'Update aborted: Desktop could not verify the Hermes installation is free.' ++ timeoutDetail ++ '\n\n' +'Close other Hermes windows and terminals, then retry. If the problem\n' +'persists, run `hermes update` in a terminal for detailed diagnostics.')diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex de2f6cb3728..5d88ad4e055 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -4997,7 +4997,12 @@ def _detect_venv_python_processes(matches: list[tuple[int, str, str]] = []try:- proc_iter = psutil.process_iter(["pid", "exe", "name", "cmdline", "cwd"])+ # On Windows, prefetching cmdline and cwd performs two expensive+ # per-process queries. A busy workstation can have 500+ processes, so+ # querying those fields for every unrelated process can exceed the+ # Desktop preflight watchdog. First collect only cheap identity fields;+ # fetch cmdline/cwd lazily for plausible Python/uv/Hermes candidates.+ proc_iter = psutil.process_iter(["pid", "exe", "name"])except Exception:return []for proc in proc_iter:@@ -5013,13 +5018,23 @@ def _detect_venv_python_processes(exe_norm = str(Path(exe).resolve()).lower()except (OSError, ValueError):exe_norm = str(exe).lower()- cmdline_raw = " ".join(info.get("cmdline") or [])- cmdline_low = cmdline_raw.lower()- cwd_low = str(info.get("cwd") or "").lower().rstrip(os.sep) + os.sep-# Primary match: the executable itself lives under this venv# (venv\Scripts\python(w).exe — the desktop backend / gateway case).is_holder = exe_norm.startswith(venv_prefix)+ name = str(info.get("name") or Path(exe).name)+ name_low = name.lower()++ if not is_holder and not (+ name_low.startswith(("python", "pypy"))+ or name_low in {"uv.exe", "uvx.exe", "hermes.exe"}+ ):+ continue++ try:+ cmdline_raw = " ".join(proc.cmdline() or [])+ except Exception:+ cmdline_raw = ""+ cmdline_low = cmdline_raw.lower()# Fallback: uv/base-interpreter trampolines run a python whose exe is# OUTSIDE the venv but which still imports from it and holds its .pyd# files. Catch those by what they're running: a cmdline that references@@ -5028,6 +5043,10 @@ def _detect_venv_python_processes(if not is_holder and venv_prefix in cmdline_low:is_holder = Trueif not is_holder and "hermes_cli.main" in cmdline_low:+ try:+ cwd_low = str(proc.cwd() or "").lower().rstrip(os.sep) + os.sep+ except Exception:+ cwd_low = os.sepif root_prefix in cmdline_low or cwd_low.startswith(root_prefix):is_holder = Trueif not is_holder:diff --git a/tests/hermes_cli/test_update_venv_health.py b/tests/hermes_cli/test_update_venv_health.pyindex aaa5f7b915a..f98b92f35e8 100644--- a/tests/hermes_cli/test_update_venv_health.py+++ b/tests/hermes_cli/test_update_venv_health.py@@ -54,9 +54,9 @@ def _proc(pid: int, exe: str, name: str, cmdline: list[str] | None = None, cwd:"pid": pid,"exe": exe,"name": name,- "cmdline": cmdline or [],- "cwd": cwd,}+ proc.cmdline.return_value = cmdline or []+ proc.cwd.return_value = cwdreturn proc@@ -86,6 +86,63 @@ def test_detect_venv_python_excludes_self_and_ancestors(_winp, tmp_path):assert cli_main._detect_venv_python_processes() == [][email protected](cli_main, "_is_windows", return_value=True)+def test_detect_venv_python_prefetches_only_cheap_process_fields(_winp, tmp_path):+ venv_py = str(tmp_path / "venv" / "Scripts" / "python.exe")+ holder = _proc(101, venv_py, "python.exe", [venv_py, "-m", "hermes_cli.main", "serve"])+ unrelated = _proc(102, r"C:\Program Files\Browser\browser.exe", "browser.exe")+ unrelated.cmdline.side_effect = AssertionError("unrelated cmdline must stay lazy")+ unrelated.cwd.side_effect = AssertionError("unrelated cwd must stay lazy")+ attrs_seen = []+ me = MagicMock()+ me.parents.return_value = []++ def process_iter(attrs):+ attrs_seen.append(attrs)+ return iter([unrelated, holder])++ fake_psutil = types.SimpleNamespace(+ process_iter=process_iter,+ Process=lambda *a, **k: me,+ )+ with patch.object(cli_main, "PROJECT_ROOT", tmp_path), patch.dict(+ sys.modules, {"psutil": fake_psutil}+ ):+ matches = cli_main._detect_venv_python_processes()++ assert attrs_seen == [["pid", "exe", "name"]]+ assert [match[0] for match in matches] == [101]+ holder.cmdline.assert_called_once_with()+ holder.cwd.assert_not_called()+ unrelated.cmdline.assert_not_called()+ unrelated.cwd.assert_not_called()++[email protected](cli_main, "_is_windows", return_value=True)+def test_detect_venv_python_keeps_external_interpreter_fallback(_winp, tmp_path):+ external = _proc(+ 103,+ r"C:\Python311\python.exe",+ "python.exe",+ ["python.exe", "-m", "hermes_cli.main", "serve"],+ str(tmp_path),+ )+ me = MagicMock()+ me.parents.return_value = []+ fake_psutil = types.SimpleNamespace(+ process_iter=lambda attrs: iter([external]),+ Process=lambda *a, **k: me,+ )+ 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] == [103]+ external.cmdline.assert_called_once_with()+ external.cwd.assert_called_once_with()++# ---------------------------------------------------------------------------