Skip to content

The agent that grows with you

fix(cli,desktop): hide every console-subsystem child spawn on Windows

Brooklyn Nicholsonb9b1328b7d73
diff --git a/apps/desktop/src/app/shell/system-resources-statusbar.test.tsx b/apps/desktop/src/app/shell/system-resources-statusbar.test.tsx
new file mode 100644
index 00000000000..e6d8d801135
--- /dev/null
+++ b/apps/desktop/src/app/shell/system-resources-statusbar.test.tsx
@@ -0,0 +1,99 @@
+import { act, renderHook, waitFor } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { $localModelsEnabled } from '@/store/local-models-flag'
+import { $statusbarHiddenIds, STATUSBAR_HIDDEN_BY_DEFAULT } from '@/store/statusbar-prefs'
+
+// The poll fires getLocalHardware() every 5s while the item is shown; the
+// backend spawns nvidia-smi per poll, so a hidden window must stop polling
+// entirely and resume on visibilitychange (#120262).
+const { getLocalHardware } = vi.hoisted(() => ({
+ getLocalHardware: vi.fn().mockResolvedValue({
+ gpu_name: 'NVIDIA Test GPU',
+ gpu_util_percent: 10,
+ vram_total_bytes: 8 << 30,
+ vram_used_bytes: 1 << 30,
+ vram_usable_bytes: 6 << 30,
+ ram_total_bytes: 32 << 30,
+ ram_available_bytes: 16 << 30,
+ uma: false
+ })
+}))
+
+vi.mock('@/hermes', () => ({ getLocalHardware }))
+
+import { useSystemResourcesStatusbarItem } from './system-resources-statusbar'
+
+describe('system-resources statusbar polling', () => {
+ afterEach(() => {
+ getLocalHardware.mockClear()
+ vi.restoreAllMocks()
+ $statusbarHiddenIds.set([...STATUSBAR_HIDDEN_BY_DEFAULT])
+ $localModelsEnabled.set(true)
+ })
+
+ async function renderShown() {
+ $localModelsEnabled.set(true)
+ $statusbarHiddenIds.set([])
+
+ const { unmount } = renderHook(() => useSystemResourcesStatusbarItem())
+
+ // Mount poll, plus nothing scheduled while the window is visible-but-idle
+ // beyond the immediate one (POLL_MS is 5s; the fake timers below avoid it).
+ await waitFor(() => expect(getLocalHardware).toHaveBeenCalled())
+
+ return { unmount }
+ }
+
+ it('does not poll while the document is hidden', async () => {
+ vi.spyOn(document, 'hidden', 'get').mockReturnValue(true)
+
+ // Mounted while hidden: the mount poll bails out, so no call is expected —
+ // give the effect a tick and assert the spawn never happened.
+ $localModelsEnabled.set(true)
+ $statusbarHiddenIds.set([])
+ const { unmount } = renderHook(() => useSystemResourcesStatusbarItem())
+ await act(async () => {})
+
+ expect(getLocalHardware).not.toHaveBeenCalled()
+
+ // Even the visibilitychange resume path must stay quiet while hidden.
+ await act(async () => {
+ document.dispatchEvent(new Event('visibilitychange'))
+ })
+
+ expect(getLocalHardware).not.toHaveBeenCalled()
+ unmount()
+ })
+
+ it('resumes polling when the window becomes visible again', async () => {
+ vi.spyOn(document, 'hidden', 'get').mockReturnValue(true)
+
+ $localModelsEnabled.set(true)
+ $statusbarHiddenIds.set([])
+ const { unmount } = renderHook(() => useSystemResourcesStatusbarItem())
+ await act(async () => {})
+ expect(getLocalHardware).not.toHaveBeenCalled()
+
+ vi.spyOn(document, 'hidden', 'get').mockReturnValue(false)
+ await act(async () => {
+ document.dispatchEvent(new Event('visibilitychange'))
+ })
+
+ await waitFor(() => expect(getLocalHardware).toHaveBeenCalledTimes(1))
+ unmount()
+ })
+
+ it('stops polling and removes the listener on unmount', async () => {
+ const { unmount } = await renderShown()
+ getLocalHardware.mockClear()
+
+ unmount()
+
+ await act(async () => {
+ document.dispatchEvent(new Event('visibilitychange'))
+ })
+
+ expect(getLocalHardware).not.toHaveBeenCalled()
+ })
+})
diff --git a/apps/desktop/src/app/shell/system-resources-statusbar.tsx b/apps/desktop/src/app/shell/system-resources-statusbar.tsx
index b4de1621069..e021a883e37 100644
--- a/apps/desktop/src/app/shell/system-resources-statusbar.tsx
+++ b/apps/desktop/src/app/shell/system-resources-statusbar.tsx
@@ -67,6 +67,12 @@ export function useSystemResourcesStatusbarItem(): StatusbarItem {
let timer: number | null = null
const poll = async () => {
+ // Hidden window = nobody watching; resume on visibilitychange instead of
+ // burning a backend spawn per 5s tick in the background (#120262).
+ if (typeof document !== 'undefined' && document.hidden) {
+ return
+ }
+
try {
const next = await getLocalHardware()
@@ -84,11 +90,29 @@ export function useSystemResourcesStatusbarItem(): StatusbarItem {
}
}
+ const onVisibilityChange = () => {
+ if (typeof document !== 'undefined' && !document.hidden && !cancelled) {
+ if (timer !== null) {
+ window.clearTimeout(timer)
+ timer = null
+ }
+ void poll()
+ }
+ }
+
+ if (typeof document !== 'undefined') {
+ document.addEventListener('visibilitychange', onVisibilityChange)
+ }
+
void poll()
return () => {
cancelled = true
+ if (typeof document !== 'undefined') {
+ document.removeEventListener('visibilitychange', onVisibilityChange)
+ }
+
if (timer !== null) {
window.clearTimeout(timer)
}
diff --git a/hermes_cli/_subprocess_compat.py b/hermes_cli/_subprocess_compat.py
index 5f671e8a0c0..645dbf2f54e 100644
--- a/hermes_cli/_subprocess_compat.py
+++ b/hermes_cli/_subprocess_compat.py
@@ -343,6 +343,7 @@ def _user_safe_directories(base_env: "Mapping[str, str]") -> list[str]:
["git", "config", scope, "-z", "--get-all", "safe.directory"],
capture_output=True, text=True, encoding="utf-8", errors="replace",
timeout=5, stdin=subprocess.DEVNULL, env=env, check=False,
+ creationflags=windows_hide_flags(),
)
except (OSError, subprocess.SubprocessError):
continue
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 4765be78549..b99488bee70 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -2118,9 +2118,13 @@ def _windows_scheduled_task_state(task_name: str) -> str | None:
powershell = shutil.which("powershell") or shutil.which("pwsh")
if powershell is None:
return None
+ # pythonw/console-less backend startup reaches this probe; powershell.exe is a
+ # console-subsystem binary and would flash a window per spawn (#117781).
+ from hermes_cli._subprocess_compat import windows_hide_flags
result = subprocess.run(
[powershell, "-NoProfile", "-NonInteractive", "-Command", ps_cmd],
capture_output=True, text=True, encoding="utf-8", errors="ignore", timeout=10,
+ creationflags=windows_hide_flags(),
)
if result.returncode != 0:
return None
diff --git a/hermes_cli/gitlock.py b/hermes_cli/gitlock.py
index ddcaba5f36d..815d23cacc0 100644
--- a/hermes_cli/gitlock.py
+++ b/hermes_cli/gitlock.py
@@ -12,6 +12,8 @@ import time
from pathlib import Path
from typing import Callable, Iterable, List, Optional
+from hermes_cli._subprocess_compat import windows_hide_flags
+
logger = logging.getLogger(__name__)
# Files younger than this are presumed live (a fetch may be in flight) and are never removed. Lock
@@ -33,12 +35,15 @@ def _git_proc_running() -> bool:
A failed probe logs and returns False; the age floor in the sweep still applies.
"""
try:
+ # One shared spawn for both probes: the argv is the platform fork, the
+ # hide-flags wiring is common, so a console-less parent (pythonw backend)
+ # never flashes a console for either (#117781).
+ argv = (["tasklist", "/FI", "IMAGENAME eq git.exe", "/FO", "CSV"]
+ if os.name == "nt" else ["pgrep", "-x", "git"])
+ proc = subprocess.run(argv, capture_output=True, text=True, encoding="utf-8", errors="replace",
+ timeout=10, creationflags=windows_hide_flags())
if os.name == "nt":
- proc = subprocess.run(["tasklist", "/FI", "IMAGENAME eq git.exe", "/FO", "CSV"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10)
return "git.exe" in proc.stdout.lower()
- proc = subprocess.run(["pgrep", "-x", "git"], capture_output=True, text=True, encoding="utf-8", errors="replace",
- timeout=10)
return proc.returncode == 0
except Exception:
logger.debug("git process probe failed; assuming no git running", exc_info=True)
@@ -148,6 +153,7 @@ def _git_stdout_lines(repo_root: Path, args: List[str]) -> List[str]:
result = subprocess.run(
["git", *args], cwd=str(repo_root),
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
+ creationflags=windows_hide_flags(),
)
if result.returncode != 0:
return []
@@ -176,6 +182,7 @@ def _batch_missing_parents(repo_root: Path, candidates: List[str]) -> set[str]:
input=request.encode(),
capture_output=True,
timeout=30,
+ creationflags=windows_hide_flags(),
)
if result.returncode != 0:
return set()
@@ -213,6 +220,7 @@ def _batch_missing_parents(repo_root: Path, candidates: List[str]) -> set[str]:
input=("\n".join(sorted(parents)) + "\n").encode(),
capture_output=True,
timeout=10,
+ creationflags=windows_hide_flags(),
)
if check.returncode != 0:
return set()
@@ -293,6 +301,7 @@ def repair_broken_shallow_boundaries(repo_root: Path) -> int:
probe = subprocess.run(
["git", "rev-list", "--count", "--all", "--reflog"],
cwd=str(repo_root), capture_output=True, timeout=10,
+ creationflags=windows_hide_flags(),
)
if probe.returncode == 0:
return 0
@@ -386,6 +395,7 @@ def prune_stale_shallow_grafts(repo_root: Path) -> int:
subprocess.run(
["git", "reflog", "expire", "--expire=now", ref],
cwd=str(repo_root), capture_output=True, timeout=10,
+ creationflags=windows_hide_flags(),
)
_write_shallow(shallow_path, "\n".join(sorted(keep)) + "\n", suffix=".hermes-prune")
# Fail-safe: if any reachable walk now crosses a boundary we wrongly
@@ -451,6 +461,10 @@ def fetch_full_commit_graph(repo_root: Path, *extra_refspecs: str, **run_kwargs)
"""
shallow_path = _shallow_file_path(repo_root)
shallow = shallow_path is not None
+ # Callers already inject creationflags via _no_prompt_git_kwargs(); OR the
+ # hide flag into the shared kwargs instead of passing the keyword twice
+ # (TypeError: got multiple values) — the config probes below inherit it.
+ run_kwargs["creationflags"] = run_kwargs.get("creationflags", 0) | windows_hide_flags()
fetch_filter = _partial_clone_filter(repo_root, **run_kwargs)
converts = fetch_filter is None and shallow and bool(_batch_missing_parents(
repo_root, shallow_path.read_text(encoding="utf-8-sig").split()))
diff --git a/hermes_cli/local_runtime/bootstrap.py b/hermes_cli/local_runtime/bootstrap.py
index f3b4fff3059..e12347d0f74 100644
--- a/hermes_cli/local_runtime/bootstrap.py
+++ b/hermes_cli/local_runtime/bootstrap.py
@@ -11,7 +11,6 @@ from contextlib import contextmanager, suppress
import logging
import os
import signal
-import subprocess
import time
from pathlib import Path
@@ -27,17 +26,11 @@ def _detect_gpu_vendor() -> str | None:
"""Best-effort GPU vendor for backend selection. NVIDIA via nvidia-smi resolved by the hardware
probe's PATH-independent ladder (a stripped service PATH must not demote an NVIDIA box to
vulkan/cpu); anything else defers to select_backend's fallback ladder."""
- from hermes_cli.local_runtime.hardware import _nvidia_smi_path
+ from hermes_cli.local_runtime.hardware import _cached_nvidia_gpu_query
- smi = _nvidia_smi_path()
- if smi is None:
- return None
- with suppress(OSError, subprocess.TimeoutExpired):
- out = subprocess.run(
- [smi, "--query-gpu=name", "--format=csv,noheader"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10)
- if out.returncode == 0 and out.stdout.strip():
- return "nvidia " + out.stdout.strip().splitlines()[0]
+ query = _cached_nvidia_gpu_query()
+ if query is not None and query.get("gpu_name"):
+ return "nvidia " + query["gpu_name"]
return None
diff --git a/hermes_cli/local_runtime/hardware.py b/hermes_cli/local_runtime/hardware.py
index 332c1d54fdd..7f2e62c534e 100644
--- a/hermes_cli/local_runtime/hardware.py
+++ b/hermes_cli/local_runtime/hardware.py
@@ -200,23 +200,65 @@ def _nvidia_smi_path() -> str | None:
def _nvidia_vram() -> tuple[int, int, str, int | None] | None:
- """(total bytes, free bytes, name, optional packed PCI ID) from the same nvidia-smi query, or None."""
+ """(total bytes, free bytes, name, optional packed PCI ID) from the shared nvidia-smi query, or None."""
+ query = _cached_nvidia_gpu_query()
+ if query is None:
+ return None
+ return query["total_bytes"], query["free_bytes"], query["gpu_name"], query.get("gpu_pci_id")
+
+
+_gpu_query_cache: "tuple[float, dict | None] | None" = None
+# The statusbar polls /api/local-models/hardware every 5s and the endpoint needs
+# name/util/vram; the budget probe needs total/free. One shared query (with a TTL
+# shorter than the poll) serves both, so one poll = one nvidia-smi spawn (#120262)
+# instead of two, and the spawn carries CREATE_NO_WINDOW so a console-less backend
+# never flashes a window (#101895).
+_GPU_QUERY_TTL_S = 4.0
+
+
+def _cached_nvidia_gpu_query(ttl_s: float = _GPU_QUERY_TTL_S) -> "dict | None":
+ """One nvidia-smi read shared by the budget probe and the hardware endpoint.
+
+ Returns ``dict(gpu_name=, total_bytes=, free_bytes=, used_bytes=, gpu_util_percent=,
+ gpu_pci_id=)`` or None when nvidia-smi is absent, fails, or is not an NVIDIA card.
+ Cached for ``ttl_s`` (failures too — a missing smi must not spawn per poll).
+ """
+ global _gpu_query_cache
+ now = time.monotonic()
+ if _gpu_query_cache is not None and now - _gpu_query_cache[0] < ttl_s:
+ return _gpu_query_cache[1]
+
exe = _nvidia_smi_path()
if exe is None:
+ _gpu_query_cache = (now, None)
return None
+
+ from hermes_cli._subprocess_compat import windows_hide_flags
with suppress(OSError, ValueError, subprocess.TimeoutExpired):
out = subprocess.run(
- [exe, "--query-gpu=memory.total,memory.free,name,pci.device_id",
+ [exe, "--query-gpu=memory.total,memory.free,name,pci.device_id,memory.used,utilization.gpu",
"--format=csv,noheader,nounits"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10)
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
+ creationflags=windows_hide_flags())
if out.returncode != 0 or not out.stdout.strip():
+ _gpu_query_cache = (now, None)
return None
- total_mib, free_mib, name, raw_id = next(
+ total_mib, free_mib, name, raw_id, used_mib, util = next(
csv.reader(out.stdout.strip().splitlines(), skipinitialspace=True))
pci_id = None
with suppress(ValueError): # N/A or unsupported identity must not lose memory data.
pci_id = int(raw_id, 16)
- return int(total_mib) << 20, int(free_mib) << 20, name.strip(), pci_id
+ data = {
+ "gpu_name": name.strip(),
+ "total_bytes": int(total_mib) << 20,
+ "free_bytes": int(free_mib) << 20,
+ "used_bytes": int(used_mib) << 20,
+ "gpu_util_percent": int(util),
+ "gpu_pci_id": pci_id,
+ }
+ _gpu_query_cache = (now, data)
+ return data
+ _gpu_query_cache = (now, None)
return None
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 20a665821ef..41a05002b66 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -206,7 +206,10 @@ def _no_prompt_git_kwargs() -> dict:
env = dict(os.environ)
env["GIT_TERMINAL_PROMPT"] = "0"
env["GCM_INTERACTIVE"] = "Never"
- return {"stdin": subprocess.DEVNULL, "env": env}
+ # Every network git spawn (fetch/pull/shallow heal) runs under a console-less
+ # desktop backend on Windows; hide the per-spawn console (#117781).
+ from hermes_cli._subprocess_compat import windows_hide_flags
+ return {"stdin": subprocess.DEVNULL, "env": env, "creationflags": windows_hide_flags()}
_UPDATE_CRITICAL_FILES = (
@@ -264,12 +267,20 @@ def _record_snapshot_stage(args, snapshot_id) -> None:
def _git_run(git_cmd, args, cwd=None, *, check=False, network=False):
"""Run git capturing utf-8 text (default cwd: checkout); ``network=True`` disables the
- terminal prompt so an HTTP 401 fails fast instead of hanging, and bounds the wait."""
+ terminal prompt so an HTTP 401 fails fast instead of hanging, and bounds the wait.
+
+ Every spawn carries ``windows_hide_flags()``: the updater's git children run under the
+ console-less desktop backend, and a bare spawn flashes a console window each (#117781)."""
+ from hermes_cli._subprocess_compat import windows_hide_flags
+ # ``_no_prompt_git_kwargs()`` already carries the hide flags for network
+ # calls, so layer them instead of passing the keyword twice.
+ spawn_kwargs = {"timeout": NETWORK_GIT_TIMEOUT_SECONDS, **_no_prompt_git_kwargs()} if network else {}
+ spawn_kwargs.setdefault("creationflags", windows_hide_flags())
try:
return subprocess.run(
git_cmd + args, cwd=_m().PROJECT_ROOT if cwd is None else cwd, capture_output=True,
text=True, encoding="utf-8", errors="replace", check=check,
- **({"timeout": NETWORK_GIT_TIMEOUT_SECONDS, **_no_prompt_git_kwargs()} if network else {}))
+ **spawn_kwargs)
except subprocess.TimeoutExpired as exc:
# subprocess.run already killed the child; the checkout stays consistent because
# fetch writes to tmp_pack_* and only renames on success. Report as a failed run
diff --git a/hermes_cli/update_cmd_check.py b/hermes_cli/update_cmd_check.py
index 31c70539169..8ded5b4cd1d 100644
--- a/hermes_cli/update_cmd_check.py
+++ b/hermes_cli/update_cmd_check.py
@@ -14,8 +14,13 @@ from typing import Any
def _git(git_cmd: list[str], root: Path, args: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]:
+ from hermes_cli._subprocess_compat import windows_hide_flags
+ # Callers pass **_no_prompt_git_kwargs() which already carries creationflags;
+ # OR the hide flag into the shared kwargs instead of passing the keyword twice.
+ kwargs["creationflags"] = kwargs.get("creationflags", 0) | windows_hide_flags()
return subprocess.run(
- git_cmd + args, cwd=root, capture_output=True, text=True, encoding="utf-8", errors="replace", **kwargs,
+ git_cmd + args, cwd=root, capture_output=True, text=True, encoding="utf-8", errors="replace",
+ **kwargs,
)
diff --git a/hermes_cli/update_cmd_git.py b/hermes_cli/update_cmd_git.py
index eddb579c7cd..bbc330bb523 100644
--- a/hermes_cli/update_cmd_git.py
+++ b/hermes_cli/update_cmd_git.py
@@ -13,12 +13,18 @@ from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Optional
+from hermes_cli._subprocess_compat import windows_hide_flags
+
logger = logging.getLogger("hermes_cli.update_cmd") # log-record parity with the origin module
_ORPHAN_RESCUE_REFS_TO_KEEP = 10
_ORPHAN_RESCUE_REF_MAX_AGE_DAYS = 30
-_GIT_TEXT_KW = dict(capture_output=True, text=True, encoding="utf-8", errors="replace")
+# creationflags is folded in here so every ``**_GIT_TEXT_KW`` spawn (rev-parse label,
+# fork-bomb probe, EOL churn normalization) hides its console under the console-less
+# desktop backend (#117781).
+_GIT_TEXT_KW = dict(capture_output=True, text=True, encoding="utf-8", errors="replace",
+ creationflags=windows_hide_flags())
_BAR = "=" * 68
_UPSTREAM_ADD_CMD = "git remote add upstream https://github.com/NousResearch/hermes-agent.git"
@@ -32,7 +38,8 @@ def _git_run(git_cmd, args, cwd=None, *, check=False):
"""Run ``git_cmd + args`` and return the CompletedProcess.
The updater's git runner: capture all output and decode as UTF-8 regardless of the
- Windows ANSI code page (#52649). ``check=True`` raises on non-zero exit.
+ Windows ANSI code page (#52649). ``check=True`` raises on non-zero exit. The spawn
+ always hides its console window (#117781).
"""
return subprocess.run(
git_cmd + list(args),
@@ -40,6 +47,7 @@ def _git_run(git_cmd, args, cwd=None, *, check=False):
capture_output=True,
text=True, encoding="utf-8", errors="replace",
check=check,
+ creationflags=windows_hide_flags(),
)
@@ -596,4 +604,5 @@ def _normalize_managed_eol(git_cmd, repo_root):
if _eol_only(): # still dirty: pinning would only surface churn we failed to clear
return
print(f"→ Normalized line-ending churn ({len(eol_only)} file(s))")
- subprocess.run(git_cmd + ["config", "core.autocrlf", "false"], cwd=repo_root, capture_output=True, check=False)
+ subprocess.run(git_cmd + ["config", "core.autocrlf", "false"], cwd=repo_root, capture_output=True, check=False,
+ creationflags=windows_hide_flags())
diff --git a/hermes_cli/web_routers/local_models.py b/hermes_cli/web_routers/local_models.py
index 344bd38e705..ace7abce3e0 100644
--- a/hermes_cli/web_routers/local_models.py
+++ b/hermes_cli/web_routers/local_models.py
@@ -16,7 +16,6 @@ import logging
import os
import re
import shutil
-import subprocess
import threading
import time
import urllib.parse
@@ -525,16 +524,18 @@ def local_models_status():
# ── hardware: what this machine can do ───────────────────────
def _nvidia_smi_facts() -> dict:
- """GPU identity + live utilization (NVIDIA only; other vendors degrade to {} and the UI hides those readouts)."""
- smi_exe = hardware._nvidia_smi_path()
- if not smi_exe:
- return {}
- smi = subprocess.run([smi_exe, "--query-gpu=name,utilization.gpu,memory.used", "--format=csv,noheader,nounits"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5)
- if smi.returncode != 0 or not smi.stdout.strip():
+ """GPU identity + live utilization (NVIDIA only; other vendors degrade to {} and the UI hides those readouts).
+
+ Reads the shared cached query: one nvidia-smi spawn per poll window, hidden on Windows,
+ instead of a second bare one per request (#101895, #120262)."""
+ query = hardware._cached_nvidia_gpu_query()
+ if query is None:
return {}
- name, util, used_mib = (x.strip() for x in smi.stdout.strip().splitlines()[0].split(","))
- return dict(gpu_name=name, gpu_util_percent=int(util), vram_used_bytes=int(used_mib) << 20)
+ return dict(
+ gpu_name=query["gpu_name"],
+ gpu_util_percent=query["gpu_util_percent"],
+ vram_used_bytes=query["used_bytes"],
+ )
@router.get("/api/local-models/hardware")
diff --git a/tests/hermes_cli/test_local_n1x_pci_identity.py b/tests/hermes_cli/test_local_n1x_pci_identity.py
index 645fd6308af..d6d009dacda 100644
--- a/tests/hermes_cli/test_local_n1x_pci_identity.py
+++ b/tests/hermes_cli/test_local_n1x_pci_identity.py
@@ -41,15 +41,17 @@ def test_pci_identity_controls_recommendations_without_changing_memory(
monkeypatch, pci_id, name, matches):
calls = []
monkeypatch.setattr(hardware, "_nvidia_smi_path", lambda: "nvidia-smi")
+ # Shared cached query: reset so each parametrized case makes its own spawn.
+ monkeypatch.setattr(hardware, "_gpu_query_cache", None)
monkeypatch.setattr(hardware, "_ram_bytes", lambda: (64 << 30, 22 << 30))
monkeypatch.setattr(hardware, "_device_pool_view", lambda: (48 << 30, True))
def run(argv, **kwargs):
calls.append(argv)
- assert argv[1] == "--query-gpu=memory.total,memory.free,name,pci.device_id"
+ assert argv[1] == "--query-gpu=memory.total,memory.free,name,pci.device_id,memory.used,utilization.gpu"
# A second adapter must not supply identity for the first adapter's budget.
- output = (f'32704, 31423, "{name}", {pci_id}\n'
- '32704, 31423, NVIDIA RTX Spark N1X, 0x2E0310DE\n')
+ output = (f'32704, 31423, "{name}", {pci_id}, 2048, 7\n'
+ '32704, 31423, NVIDIA RTX Spark N1X, 0x2E0310DE, 2048, 7\n')
return SimpleNamespace(returncode=0, stdout=output)
monkeypatch.setattr(hardware.subprocess, "run", run)
@@ -80,14 +82,15 @@ def test_pci_identity_controls_recommendations_without_changing_memory(
def test_unavailable_pci_id_preserves_memory_and_name_fallback(monkeypatch, integrated):
calls = []
monkeypatch.setattr(hardware, "_nvidia_smi_path", lambda: "nvidia-smi")
+ monkeypatch.setattr(hardware, "_gpu_query_cache", None)
monkeypatch.setattr(hardware, "_ram_bytes", lambda: (64 << 30, 22 << 30))
monkeypatch.setattr(hardware, "_device_pool_view", lambda: (48 << 30, integrated))
name = "NVIDIA RTX Spark N1X"
def run(argv, **kwargs):
calls.append(argv)
- assert argv[1] == "--query-gpu=memory.total,memory.free,name,pci.device_id"
- return SimpleNamespace(returncode=0, stdout=f"32704, 31423, {name}, N/A\n")
+ assert argv[1] == "--query-gpu=memory.total,memory.free,name,pci.device_id,memory.used,utilization.gpu"
+ return SimpleNamespace(returncode=0, stdout=f"32704, 31423, {name}, N/A, 2048, 7\n")
monkeypatch.setattr(hardware.subprocess, "run", run)
budget = hardware.probe_budget(planning=True)
diff --git a/tests/hermes_cli/test_unified_pool_quirk.py b/tests/hermes_cli/test_unified_pool_quirk.py
index 08c09f04e43..439dc4c73e2 100644
--- a/tests/hermes_cli/test_unified_pool_quirk.py
+++ b/tests/hermes_cli/test_unified_pool_quirk.py
@@ -31,6 +31,9 @@ UMA_RAM = 48 * GIB
def _no_cache(monkeypatch):
monkeypatch.setattr(hw, "_pool_probe_cache", None)
+ # One shared cached nvidia-smi query (see _cached_nvidia_gpu_query): a stale
+ # TTL entry from a previous test would suppress this test's own spawn.
+ monkeypatch.setattr(hw, "_gpu_query_cache", None)
# ── _unified_pool_bytes: the classification gate ─────────────
@@ -198,13 +201,15 @@ def test_memory_probe_carries_identity_without_another_process(monkeypatch):
calls = []
name = "NVIDIA RTX Spark N1X (5120-core Blackwell RTX GPU)"
monkeypatch.setattr(hw, "_nvidia_smi_path", lambda: "nvidia-smi")
+ monkeypatch.setattr(hw, "_gpu_query_cache", None)
monkeypatch.setattr(hw, "_ram_bytes", lambda: (64 * GIB, 22 * GIB))
monkeypatch.setattr(hw, "_device_pool_view", lambda: (UMA_POOL, True))
def run(argv, **kwargs):
calls.append(argv)
assert argv[0] == "nvidia-smi"
- output = f"32704, 31423, {name}, 0x2E0310DE\n"
+ # Column order matches _cached_nvidia_gpu_query: total, free, name, pci, used, util.
+ output = f"32704, 31423, {name}, 0x2E0310DE, 2048, 7\n"
return SimpleNamespace(returncode=0, stdout=output)
monkeypatch.setattr(hw.subprocess, "run", run)
diff --git a/tests/test_windows_subprocess_no_window_flags.py b/tests/test_windows_subprocess_no_window_flags.py
index 4579735dc7d..60e0f19b9c7 100644
--- a/tests/test_windows_subprocess_no_window_flags.py
+++ b/tests/test_windows_subprocess_no_window_flags.py
@@ -33,7 +33,11 @@ def _spawns(captured, *needles):
return [
(cmd, kwargs)
for cmd, kwargs in captured
- if cmd and all(n in cmd for n in needles)
+ if cmd
+ and all(
+ any(needle in str(part) for part in (cmd if isinstance(cmd, (list, tuple)) else [cmd]))
+ for needle in needles
+ )
]
@@ -372,3 +376,247 @@ def test_suppress_platform_ver_console_stubs_syscmd_ver(monkeypatch):
# Idempotent + never raises on repeat calls.
_subprocess_compat.suppress_platform_ver_console()
assert platform._syscmd_ver() == ("", "", "")
+
+
+# ── #117781 desktop-startup helper spawns (console-less pythonw backend) ────
+#
+# The desktop backend runs under pythonw.exe (no console). Every helper it
+# spawns (git.exe, tasklist.exe, powershell.exe) without CREATE_NO_WINDOW gets
+# a brand-new VISIBLE console — one flash per spawn at startup, during the
+# update pipeline, and on the scheduled-task probe. These tests assert the
+# WIRING (the site threads windows_hide_flags() into creationflags), so the
+# helper is stubbed to a known constant and the tests run on every platform.
+
+
+def test_gitlock_git_spawns_hide_console_window(monkeypatch, tmp_path):
+ """gitlock read-only git probes never flash: stdout-lines queries, the
+ cat-file batch pair, the rev-list repair probe and the tag fetch."""
+ from hermes_cli import gitlock
+
+ captured = []
+
+ def fake_run(cmd, **kwargs):
+ captured.append((list(cmd), kwargs))
+ cmd_str = " ".join(cmd)
+ if "rev-list" in cmd_str:
+ return _Completed(stdout="", returncode=1)
+ if "cat-file" in cmd_str and "--batch-check" in cmd_str:
+ return _Completed(stdout="", returncode=0)
+ if "cat-file" in cmd_str:
+ return _Completed(stdout="", returncode=1)
+ return _Completed(stdout="deadbeef\n", returncode=0)
+
+ monkeypatch.setattr(gitlock, "windows_hide_flags", lambda: _CREATE_NO_WINDOW)
+ monkeypatch.setattr(gitlock.subprocess, "run", fake_run)
+
+ assert gitlock._git_stdout_lines(tmp_path, ["rev-parse", "--git-path", "shallow"]) == ["deadbeef"]
+ assert gitlock._batch_missing_parents(tmp_path, ["abc123"]) == set()
+ gitlock.repair_broken_shallow_boundaries(tmp_path)
+
+ spawns = _spawns(captured, "git")
+ assert spawns, "expected git spawns"
+ for cmd, kwargs in spawns:
+ assert kwargs.get("creationflags") == _CREATE_NO_WINDOW, cmd
+
+
+def test_gitlock_tasklist_probe_hides_console_window(monkeypatch):
+ """The stale-lock tasklist guard flashes on its own under pythonw."""
+ from hermes_cli import gitlock
+
+ captured = []
+
+ def fake_run(cmd, **kwargs):
+ captured.append((list(cmd), kwargs))
+ return _Completed(stdout="\"git.exe\",\"1234\",\"Console\",\"1\",\"10,000 K\"\n", returncode=0)
+
+ monkeypatch.setattr(gitlock, "windows_hide_flags", lambda: _CREATE_NO_WINDOW)
+ monkeypatch.setattr(gitlock.subprocess, "run", fake_run)
+ monkeypatch.setattr(gitlock.os, "name", "nt")
+
+ assert gitlock._git_proc_running() is True
+ spawns = _spawns(captured, "tasklist")
+ assert len(spawns) == 1, captured
+ assert spawns[0][1]["creationflags"] == _CREATE_NO_WINDOW
+
+
+def test_gitlock_tag_fetch_hides_console_window(monkeypatch, tmp_path):
+ """The full-commit-graph fetch (update pipeline) hides its window."""
+ from hermes_cli import gitlock
+
+ captured = []
+
+ def fake_run(cmd, **kwargs):
+ captured.append((list(cmd), kwargs))
+ if "cat-file" in " ".join(cmd):
+ return _Completed(stdout="", returncode=1)
+ return _Completed(stdout="8192, 4096, deadbeef\n", returncode=0)
+
+ monkeypatch.setattr(gitlock, "windows_hide_flags", lambda: _CREATE_NO_WINDOW)
+ monkeypatch.setattr(gitlock, "_shallow_file_path", lambda root: None)
+ monkeypatch.setattr(gitlock, "_partial_clone_filter", lambda root, **kw: None)
+ monkeypatch.setattr(gitlock.subprocess, "run", fake_run)
+
+ assert gitlock.fetch_full_commit_graph(tmp_path) is False # not shallow
+ spawns = _spawns(captured, "fetch")
+ assert len(spawns) == 1, captured
+ assert spawns[0][1]["creationflags"] == _CREATE_NO_WINDOW
+
+
+def test_gateway_scheduled_task_state_hides_powershell_window(monkeypatch):
+ """Task Scheduler COM probe spawns powershell.exe during backend startup."""
+ from hermes_cli import gateway
+
+ captured = []
+
+ def fake_run(cmd, **kwargs):
+ captured.append((list(cmd), kwargs))
+ return _Completed(stdout="Ready\n", returncode=0)
+
+ _patch_hide_flags(monkeypatch)
+ monkeypatch.setattr(gateway, "is_windows", lambda: True)
+ monkeypatch.setattr(gateway.subprocess, "run", fake_run)
+ monkeypatch.setattr(gateway.shutil, "which", lambda name: r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.EXE")
+
+ assert gateway._windows_scheduled_task_state("hermes-gateway") == "Ready"
+ assert len(captured) == 1, captured
+ cmd, kwargs = captured[0]
+ assert cmd[0].lower().endswith("powershell.exe"), cmd
+ assert kwargs["creationflags"] == _CREATE_NO_WINDOW
+
+
+def test_update_git_run_hides_console_window(monkeypatch, tmp_path):
+ """The central update git runner (26 call sites) hides its window."""
+ from hermes_cli import update_cmd
+
+ captured = []
+
+ def fake_run(cmd, **kwargs):
+ captured.append((list(cmd), kwargs))
+ return _Completed(stdout="ok\n", returncode=0)
+
+ _patch_hide_flags(monkeypatch)
+ monkeypatch.setattr(update_cmd, "_m", lambda: SimpleNamespace(PROJECT_ROOT=tmp_path))
+ monkeypatch.setattr(update_cmd.subprocess, "run", fake_run)
+
+ update_cmd._git_run(["git"], ["rev-parse", "HEAD"], tmp_path)
+ update_cmd._git_run(["git"], ["fetch", "origin", "main"], tmp_path, network=True)
+ assert len(captured) == 2, captured
+ for cmd, kwargs in captured:
+ assert kwargs.get("creationflags") == _CREATE_NO_WINDOW, cmd
+
+
+def test_no_prompt_git_kwargs_hide_console_window(monkeypatch):
+ """Network git kwargs (fetch/pull behind them) carry the hide flags too,
+ so the upstream-sync fetch/pull spawns never flash."""
+ from hermes_cli import update_cmd
+
+ _patch_hide_flags(monkeypatch)
+ kwargs = update_cmd._no_prompt_git_kwargs()
+ assert kwargs["creationflags"] == _CREATE_NO_WINDOW
+ assert kwargs["stdin"] == subprocess.DEVNULL
+
+
+def test_update_git_plumbing_spawns_hide_console_window(monkeypatch, tmp_path):
+ """rev-parse label, fork-bomb probe and EOL-normalization git spawns."""
+ from hermes_cli import update_cmd_git
+
+ captured = []
+
+ def fake_run(cmd, **kwargs):
+ captured.append((list(cmd), kwargs))
+ return _Completed(stdout="main\nabc123\n", returncode=0)
+
+ monkeypatch.setattr(update_cmd_git, "windows_hide_flags", lambda: _CREATE_NO_WINDOW)
+ monkeypatch.setattr(update_cmd_git, "_GIT_TEXT_KW",
+ dict(capture_output=True, text=True, encoding="utf-8", errors="replace",
+ creationflags=_CREATE_NO_WINDOW))
+ monkeypatch.setattr(update_cmd_git.subprocess, "run", fake_run)
+
+ assert update_cmd_git._probe_fork_bomb(["git"]) is False
+ label = update_cmd_git._branch_head_label(["git"], cwd=tmp_path)
+ assert label is not None and "abc" in label
+
+ assert captured, "expected git spawns"
+ for cmd, kwargs in captured:
+ assert kwargs.get("creationflags") == _CREATE_NO_WINDOW, cmd
+
+
[email protected]_safe_directory
+def test_safe_directory_git_config_probes_hide_console_window(monkeypatch):
+ """safe.directory replay (two git config children per internal git call)
+ never flashes."""
+ from hermes_cli import _subprocess_compat
+
+ captured = []
+
+ def fake_run(cmd, **kwargs):
+ captured.append((list(cmd), kwargs))
+ return _Completed(stdout="", returncode=1)
+
+ _subprocess_compat._safe_directory_cache.clear()
+ monkeypatch.setattr(_subprocess_compat, "windows_hide_flags", lambda: _CREATE_NO_WINDOW)
+ monkeypatch.setattr(_subprocess_compat.subprocess, "run", fake_run)
+
+ assert _subprocess_compat._user_safe_directories({}) == []
+ spawns = _spawns(captured, "git", "config")
+ assert len(spawns) == 2, captured
+ for cmd, kwargs in spawns:
+ assert kwargs.get("creationflags") == _CREATE_NO_WINDOW, cmd
+
+
+# ── #101895 nvidia-smi statusbar / hardware probes ──────────────────────────
+#
+# The desktop GPU statusbar polls /api/local-models/hardware every 5s. Before
+# the consolidation that endpoint spawned console-subsystem nvidia-smi twice
+# per poll (VRAM budget in hardware._nvidia_vram, then name/util in the
+# router) from a windowless backend — two console flashes per poll. Everything
+# now funnels through one cached, hidden spawn.
+
+
+def test_cached_nvidia_gpu_query_hides_console_window_and_caches(monkeypatch):
+ """One hidden nvidia-smi spawn serves the budget probe, the endpoint and
+ the vendor detector within the TTL; the second caller must not spawn."""
+ from hermes_cli.local_runtime import bootstrap, hardware
+ from hermes_cli.web_routers import local_models
+
+ captured = []
+
+ def fake_run(cmd, **kwargs):
+ captured.append((list(cmd), kwargs))
+ return _Completed(stdout="8192, 4096, NVIDIA GeForce RTX 4060 Ti, 0x250410DE, 4096, 12\n", returncode=0)
+
+ monkeypatch.setattr(hardware, "_gpu_query_cache", None)
+ monkeypatch.setattr(hardware, "_nvidia_smi_path", lambda: r"C:\Windows\System32\nvidia-smi.exe")
+ _patch_hide_flags(monkeypatch)
+ monkeypatch.setattr(hardware.subprocess, "run", fake_run)
+
+ vram = hardware._nvidia_vram()
+ assert vram == (8192 << 20, 4096 << 20, "NVIDIA GeForce RTX 4060 Ti", 0x250410DE)
+ facts = local_models._nvidia_smi_facts()
+ assert facts == dict(gpu_name="NVIDIA GeForce RTX 4060 Ti", gpu_util_percent=12, vram_used_bytes=4096 << 20)
+ vendor = bootstrap._detect_gpu_vendor()
+ assert vendor == "nvidia NVIDIA GeForce RTX 4060 Ti"
+
+ spawns = _spawns(captured, "nvidia-smi")
+ assert len(spawns) == 1, captured # one poll window, one spawn
+ assert spawns[0][1]["creationflags"] == _CREATE_NO_WINDOW
+ assert spawns[0][1]["capture_output"] is True
+
+
+def test_cached_nvidia_gpu_query_failure_is_cached(monkeypatch):
+ """A missing/failed smi must not re-spawn per poll either."""
+ from hermes_cli.local_runtime import hardware
+
+ captured = []
+
+ def fake_run(cmd, **kwargs):
+ captured.append((list(cmd), kwargs))
+ return _Completed(stdout="", returncode=1)
+
+ monkeypatch.setattr(hardware, "_gpu_query_cache", None)
+ monkeypatch.setattr(hardware, "_nvidia_smi_path", lambda: r"C:\Windows\System32\nvidia-smi.exe")
+ monkeypatch.setattr(hardware.subprocess, "run", fake_run)
+
+ assert hardware._nvidia_vram() is None
+ assert hardware._cached_nvidia_gpu_query() is None # TTL hit, no second spawn
+ assert len(captured) == 1, captured