Skip to content

The agent that grows with you

fix(voice): requirement checks answer from state, never install

ethernet398867326dbe
diff --git a/tests/hermes_cli/test_install_lock_timeout.py b/tests/hermes_cli/test_install_lock_timeout.py
new file mode 100644
index 00000000000..7b4ae1626af
--- /dev/null
+++ b/tests/hermes_cli/test_install_lock_timeout.py
@@ -0,0 +1,88 @@
+"""A backend binds even while another process holds the install lock.
+
+Regression: ``runtime_lock`` waited forever, and the lock is held across a whole dependency
+rebuild (tens of seconds on a bundle), so the second backend — the ``hermes-setup`` onboarding
+profile — never reached its port: the renderer gave up at 40 s and Electron killed it at 90 s
+while the holder ran a uv build it had started for a status probe. Deciding what a lost race
+means is the caller's job now: readers skip, explicit installs still wait.
+"""
+
+import json
+import os
+import subprocess
+import sys
+
+import pytest
+
+from hermes_cli.runtime_paths import install_state_dir, runtime_facts_path, site_packages
+
+_HOLDER = """
+import sys
+from pathlib import Path
+from hermes_cli.runtime_state import runtime_lock
+with runtime_lock(Path(sys.argv[1]), timeout=0):
+ print("locked", flush=True)
+ sys.stdin.readline()
+"""
+
+
+def install_tree(tmp_path, monkeypatch):
+ """A real committed generation, ready for ``activate_dependencies`` to select."""
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
+ environment = install_state_dir(repo) / "environments" / "gen1" / "venv"
+ site = site_packages(environment)
+ site.mkdir(parents=True)
+ (environment / "pyvenv.cfg").write_text("version = 3.14", encoding="utf-8")
+ (environment.parent / ".lease-managed").touch()
+ runtime_facts_path(repo).write_text(
+ json.dumps({"packages": {"venv": {"environment": str(environment)}}}), encoding="utf-8")
+ return repo, site
+
+
+def locked_install(install_tree):
+ """A live second process holding ``.install.lock``, the way a sibling backend does."""
+ repo, site = install_tree
+ holder = subprocess.Popen([sys.executable, "-c", _HOLDER, str(repo)], env=dict(os.environ),
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, text=True)
+ assert holder.stdout is not None and holder.stdin is not None
+ assert holder.stdout.readline().strip() == "locked"
+ try:
+ yield repo, site
+ finally:
+ holder.communicate("done\n", timeout=15)
+
+
+def test_runtime_lock_reports_a_lost_race(locked_install):
+ from hermes_cli.runtime_state import runtime_lock
+
+ repo, _site = locked_install
+ with runtime_lock(repo, timeout=0.2) as held:
+ assert held is False
+ # The blocked-install symptom: a bounded wait, then carry on — never the holder's rebuild.
+
+
+def test_boot_activation_proceeds_while_the_install_is_locked(locked_install, monkeypatch):
+ """The issue's symptom, inverted: the backend reaches its dependency environment and can bind
+ while a sibling holds the lock. Recovery belongs to whoever holds it, so it is skipped."""
+ import hermes_cli.runtime_paths as runtime_paths
+ import hermes_cli.runtime_state as runtime_state
+
+ repo, site = locked_install
+ real_lock = runtime_state.runtime_lock
+ monkeypatch.setattr(runtime_state, "runtime_lock",
+ lambda project, **kw: real_lock(project, timeout=0.2))
+ recovered: list = []
+ monkeypatch.setattr(runtime_state, "recover_publication", lambda project: recovered.append(project))
+
+ saved_path = sys.path[:]
+ try:
+ runtime_paths.activate_dependencies(repo)
+ assert str(site) in sys.path
+ finally:
+ sys.path[:] = saved_path
+ assert recovered == []
diff --git a/tests/pm/test_extras.py b/tests/pm/test_extras.py
index 8bc5c3ce700..bcf6a745b1a 100644
--- a/tests/pm/test_extras.py
+++ b/tests/pm/test_extras.py
@@ -87,6 +87,32 @@ def test_declared_extra_gates_match_dependency_selection():
)
+def test_faster_whisper_targets_are_gated(monkeypatch):
+ """The local-STT extra's anchor is faster-whisper, which has no win_arm64 or darwin-x64 build.
+
+ An extra whose anchor can never import there must be refused up front: without the gate,
+ ensure_import rebuilt the whole dependency environment and still failed the anchor — on every
+ status probe, forever. ``voice`` is deliberately NOT gated (its sounddevice/numpy are
+ installable on those targets; see the selection test above), so the lazy STT path asks for
+ ``stt-whisper``, the extra that carries only faster-whisper.
+ """
+ monkeypatch.setattr(extras, "_PLATFORM_GATES", None)
+ targets = {
+ "win32-arm64": {"sys_platform": "win32", "platform_system": "Windows",
+ "platform_machine": "ARM64", "os_name": "nt"},
+ "darwin-x64": {"sys_platform": "darwin", "platform_system": "Darwin",
+ "platform_machine": "x86_64", "os_name": "posix"},
+ "linux-x64": {"sys_platform": "linux", "platform_system": "Linux",
+ "platform_machine": "x86_64", "os_name": "posix"},
+ }
+ supported = {
+ target: extras.extra_supported("stt-whisper", environment=environment,
+ importable=lambda _: False)
+ for target, environment in targets.items()
+ }
+ assert supported == {"win32-arm64": False, "darwin-x64": False, "linux-x64": True}
+
+
@pytest.fixture
def synced(monkeypatch):
calls: list[list[str]] = []
diff --git a/tests/pm/test_uv_cache_seed.py b/tests/pm/test_uv_cache_seed.py
new file mode 100644
index 00000000000..2878917e2c6
--- /dev/null
+++ b/tests/pm/test_uv_cache_seed.py
@@ -0,0 +1,49 @@
+"""A failed uv-cache seed must not record completion.
+
+Regression: the seed copy ran inside ``except OSError: pass`` and wrote the ``.seeded`` marker
+unconditionally, so a copy that died half-way was permanent — no later install retried it, and
+every offline sync that needed a missing entry failed closed with "requested data wasn't found
+in the cache".
+"""
+
+import shutil
+
+import pytest
+
+from hermes_constants import get_default_hermes_root
+from pm import packages
+from pm import paths
+
+
+def payload_cache(tmp_path, monkeypatch):
+ """A sealed payload shipping ``uv-cache/`` beside its store, and a machine cache that is empty."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
+ payload = tmp_path / "payload"
+ entry = payload / "uv-cache" / "archive-v0" / "bucket"
+ entry.mkdir(parents=True)
+ (entry / "module.py").write_text("seeded = True\n", encoding="utf-8")
+ store = payload / "tools"
+ store.mkdir()
+ monkeypatch.setattr(paths, "store_root", lambda: store)
+ return get_default_hermes_root() / "cache" / "uv"
+
+
+def test_partial_seed_is_retried_on_the_next_install(payload_cache, monkeypatch):
+ real_copytree = shutil.copytree
+ attempts: list[int] = []
+
+ def flaky(*args, **kwargs):
+ """Fails the first copy only; shutil recurses through this same module attribute."""
+ attempts.append(1)
+ if len(attempts) == 1:
+ raise OSError("no space left on device")
+ return real_copytree(*args, **kwargs)
+
+ monkeypatch.setattr(shutil, "copytree", flaky)
+ packages.uv_cache_dir()
+ assert not (payload_cache / ".seeded").is_file(), "a failed seed recorded completion"
+
+ packages.uv_cache_dir()
+ assert (payload_cache / ".seeded").is_file()
+ assert (payload_cache / "archive-v0" / "bucket" / "module.py").read_text(encoding="utf-8") == "seeded = True\n"
diff --git a/tests/tools/test_stt_resolution_passive.py b/tests/tools/test_stt_resolution_passive.py
new file mode 100644
index 00000000000..e12bde025ba
--- /dev/null
+++ b/tests/tools/test_stt_resolution_passive.py
@@ -0,0 +1,38 @@
+"""STT provider RESOLUTION never installs; transcription still does.
+
+Regression: ``_detect_local_backend`` lazy-installed faster-whisper, and it sits in the provider
+resolution chain every status surface uses — ``wake.status`` (fired on every desktop
+gateway-open), ``/voice status`` and ``GET /api/audio/voice-config``. Each of those could start a
+full dependency rebuild, holding the per-install lock long enough to keep a sibling profile's
+backend off its port.
+"""
+
+import pytest
+
+from tools import transcription_tools
+
+
+def no_faster_whisper(monkeypatch):
+ """A machine without faster-whisper or a whisper CLI, recording install attempts."""
+ attempts: list[int] = []
+ monkeypatch.setattr(transcription_tools, "_HAS_FASTER_WHISPER", False)
+ monkeypatch.setattr(transcription_tools, "_has_local_command", lambda: False)
+ monkeypatch.setattr(transcription_tools, "_try_lazy_install_stt",
+ lambda: attempts.append(1) or False)
+ return transcription_tools, attempts
+
+
+def test_resolution_reports_unavailable_without_installing(no_faster_whisper):
+ tools, attempts = no_faster_whisper
+ assert tools._detect_local_backend() is None
+ assert tools._resolve_explicit_local() == "none"
+ assert attempts == []
+
+
+def test_transcription_is_what_installs(no_faster_whisper):
+ tools, attempts = no_faster_whisper
+ result = tools._transcribe_local("/tmp/absent.wav", "base")
+ assert attempts == [1], "the action path lost its on-demand install"
+ assert result["success"] is False
+ assert "faster-whisper not installed" in result["error"]
diff --git a/tests/tools/test_tts_requirements_passive.py b/tests/tools/test_tts_requirements_passive.py
new file mode 100644
index 00000000000..25d0efd140e
--- /dev/null
+++ b/tests/tools/test_tts_requirements_passive.py
@@ -0,0 +1,80 @@
+"""``check_tts_requirements`` is the ``text_to_speech`` tool's ``check_fn``: a PASSIVE probe.
+
+Regression: the edge / elevenlabs / mistral entries called the SDK importers, and those install
+their pm extra on import — so a tool listing (every turn, and on boot) could start a full
+dependency rebuild under the install lock. A provider whose SDK installs at first use still has
+to read as READY here, or the tool disappears from the schema for exactly the users the install
+exists for; the install itself belongs to synthesis.
+"""
+
+import pytest
+
+from tools import tts_tool
+
+
+def _lazy_installs(monkeypatch, allowed: bool) -> None:
+ """Stand in for ``security.allow_lazy_installs``.
+
+ The submodule must be fetched through ``import_module``: ``pm.ensure`` on the pm PACKAGE is the
+ ``ensure()`` function, so ``pm.ensure.lazy_installs_allowed`` is not the seam the production
+ import reads.
+ """
+ import importlib
+
+ monkeypatch.setattr(importlib.import_module("pm.ensure"), "lazy_installs_allowed", lambda: allowed)
+
+
+def _no_extra(monkeypatch) -> None:
+ """pm's availability answer: nothing installed. A real function in every revision, so the
+ check reaches its own logic instead of being stubbed out."""
+ import importlib
+
+ monkeypatch.setattr(importlib.import_module("pm.extras"), "available", lambda extra: False)
+
+
+def installs(monkeypatch):
+ """Records any install a requirement check attempts, and fails loudly on one."""
+ import pm
+
+ calls: list[str] = []
+
+ def fake_ensure(extra):
+ calls.append(extra)
+ raise AssertionError(f"a TTS requirement check installed {extra!r}")
+
+ monkeypatch.setattr(pm, "ensure_import", fake_ensure)
+ return calls
+
+
+def edge_without_sdk(monkeypatch):
+ """The default provider, with edge-tts absent and no NeuTTS fallback."""
+ monkeypatch.setattr(tts_tool, "_load_tts_config", lambda: {"provider": "edge"})
+ monkeypatch.setattr(tts_tool, "_resolve_command_provider_config", lambda *a, **k: None)
+ _no_extra(monkeypatch)
+ monkeypatch.setattr(tts_tool, "_check_neutts_available", lambda: False)
+
+
+def test_installable_sdk_reads_ready_without_installing(monkeypatch, installs, edge_without_sdk):
+ _lazy_installs(monkeypatch, True)
+ assert tts_tool.check_tts_requirements() is True
+ assert installs == []
+
+
+def test_missing_sdk_reports_unavailable_when_install_cannot_help(monkeypatch, installs, edge_without_sdk):
+ """Lazy installs off: nothing to be ready about, and still no install."""
+ _lazy_installs(monkeypatch, False)
+ assert tts_tool.check_tts_requirements() is False
+ assert installs == []
+
+
+def test_second_provider_needs_its_own_credential_before_first_use_counts(monkeypatch, installs):
+ """An install cannot conjure a key: elevenlabs without ELEVENLABS_API_KEY stays unavailable."""
+ monkeypatch.setattr(tts_tool, "_load_tts_config", lambda: {"provider": "elevenlabs"})
+ monkeypatch.setattr(tts_tool, "_resolve_command_provider_config", lambda *a, **k: None)
+ _no_extra(monkeypatch)
+ monkeypatch.setattr(tts_tool, "_resolve_provider_key", lambda *a, **k: "")
+ _lazy_installs(monkeypatch, True)
+ assert tts_tool.check_tts_requirements() is False
+ assert installs == []
diff --git a/tools/transcription_local.py b/tools/transcription_local.py
index 3ac2a67e88c..a5234d61819 100644
--- a/tools/transcription_local.py
+++ b/tools/transcription_local.py
@@ -56,20 +56,25 @@ def _normalize_local_model(model_name: Optional[str]) -> str:
def _try_lazy_install_stt() -> bool:
- """Lazy-install faster-whisper and re-check dynamically so it's usable without a restart."""
+ """Install faster-whisper and re-check dynamically so it's usable without a restart.
+
+ ACTION paths only (``_transcribe_local``). Nothing that merely *resolves* or *reports* a
+ provider may call this: the install takes the per-install lock for as long as a full extra-set
+ rebuild, and a status probe must never start one."""
try:
# pm installs are gated by security.allow_lazy_installs; never a blocking
# prompt mid-session. See #40490.
import pm
- pm.ensure_import("voice")
+ pm.ensure_import("stt-whisper")
if _ilu.find_spec("faster_whisper"):
return True
logger.warning("faster-whisper was installed but importlib still cannot find it (may require Python restart)")
except Exception as exc:
logger.warning(
"Lazy install of faster-whisper failed: %s. "
- "This is often a permission issue: the Hermes process user cannot "
- "write to the dependency environment. Run `hermes tools` as the "
+ "When the message names a restart, this process selected its dependency generation at "
+ "boot and a new one cannot take effect in-flight; otherwise the Hermes process user "
+ "may not be able to write to the dependency environment. Run `hermes tools` as the "
"Hermes installation owner and select Local Whisper under Speech-to-Text.",
exc)
return False
diff --git a/tools/transcription_tools.py b/tools/transcription_tools.py
index ff6df1b39a8..3ea993b3b7d 100644
--- a/tools/transcription_tools.py
+++ b/tools/transcription_tools.py
@@ -156,10 +156,16 @@ def _resolve_explicit_openai() -> str:
def _detect_local_backend() -> Optional[str]:
- """faster-whisper > local whisper CLI > lazy-installed faster-whisper; None when nothing local works."""
+ """faster-whisper > local whisper CLI; None when no local backend is installed.
+
+ Resolution only — it must never install. Asking a status probe to resolve the provider used
+ to run a full dependency sync here (``_try_lazy_install_stt`` → ``pm.ensure_import``) under
+ the per-install lock, so ``wake.status`` and ``/voice status`` could hold a sibling profile's
+ backend off its port for the length of a venv rebuild. A missing faster-whisper now reports
+ unavailable; the install happens on first transcription, in ``_transcribe_local``."""
if _HAS_FASTER_WHISPER:
return "local"
- return "local_command" if _has_local_command() else ("local" if _try_lazy_install_stt() else None)
+ return "local_command" if _has_local_command() else None
def _resolve_explicit_local() -> str:
diff --git a/tools/tts_tool.py b/tools/tts_tool.py
index 8e7154c5dae..2145c7e8978 100644
--- a/tools/tts_tool.py
+++ b/tools/tts_tool.py
@@ -490,28 +490,82 @@ def _xai_requirements() -> bool:
# Must mirror text_to_speech_tool dispatch: unrelated cloud credentials never make the Edge
# default usable, and an explicit provider is checked on its own.
+#
+# PASSIVE ONLY: every entry answers from availability/credentials and never installs. The SDK
+# importers (`_import_edge_tts`/`_import_elevenlabs`/`_import_mistral_client`) call
+# ``pm.ensure_import`` on import, so reaching them from here turned ``check_tts_requirements``
+# — the ``text_to_speech`` tool's ``check_fn`` — into an installer that ran during every tool
+# listing.
_BUILTIN_REQUIREMENTS: Dict[str, Callable[[], bool]] = {
- "edge": lambda: _importable(_import_edge_tts) or _check_neutts_available(),
- "elevenlabs": lambda: _importable(_import_elevenlabs) and bool(_resolve_provider_key("ELEVENLABS_API_KEY", "elevenlabs")),
+ "edge": lambda: _pm_extra_available("edge-tts") or _check_neutts_available(),
+ "elevenlabs": lambda: _pm_extra_available("tts-premium") and bool(_resolve_provider_key("ELEVENLABS_API_KEY", "elevenlabs")),
"openai": lambda: _package_installed("openai") and _has_openai_audio_backend(),
"deepinfra": lambda: _package_installed("openai") and bool(_resolve_provider_key("DEEPINFRA_API_KEY", "deepinfra")),
"minimax": _minimax_requirements,
"xai": _xai_requirements,
"gemini": lambda: bool(_resolve_provider_key("GEMINI_API_KEY", "gemini") or _resolve_provider_key("GOOGLE_API_KEY", "gemini")),
- "mistral": lambda: _importable(_import_mistral_client) and bool(_resolve_provider_key("MISTRAL_API_KEY", "mistral")),
+ "mistral": lambda: _pm_extra_available("mistral") and bool(_resolve_provider_key("MISTRAL_API_KEY", "mistral")),
"neutts": lambda: _check_neutts_available(),
"kittentts": lambda: _check_kittentts_available(),
"piper": lambda: _check_piper_available()}
+def _pm_extra_available(extra: str) -> bool:
+ """Whether the extra's anchor is importable, by pm's own answer for it.
+
+ Not ``find_spec`` on a hand-written module name: ``pm.extras`` owns the extra→anchor table and
+ counts a module already in ``sys.modules`` as installed, which is how every other feature in
+ the tree reports availability.
+ """
+ try:
+ from pm.extras import available
+ except Exception:
+ return False
+ return bool(available(extra))
+
+# Providers whose SDK pm installs on first use: provider -> the credential it needs REGARDLESS of
+# the install (an install cannot conjure a key; None = none). Extra names come from
+# ``_PM_FEATURE_ALIASES`` (upstream's ``tts.<provider>`` ids), so that table stays their one
+# source. The install belongs to synthesis (``_select_builtin_engine`` and the command/streaming
+# paths), never to a requirement check — so a missing-but-installable SDK counts as READY here.
+_SDK_ON_DEMAND: Dict[str, Optional[str]] = {
+ "edge": None,
+ "elevenlabs": "ELEVENLABS_API_KEY",
+ "mistral": "MISTRAL_API_KEY"}
+
+
+def _ready_after_first_use_install(provider: str) -> bool:
+ """True when the SDK is absent but pm may install it at first synthesis AND this machine
+ could actually get it (platform gate open) AND the provider's own credential is present.
+ Installs nothing itself."""
+ if provider not in _SDK_ON_DEMAND:
+ return False
+ feature = _PM_FEATURE_ALIASES.get(f"tts.{provider}")
+ if feature is None:
+ return False
+ key_env = _SDK_ON_DEMAND[provider]
+ if key_env and not _resolve_provider_key(key_env, provider):
+ return False
+ try:
+ from pm.ensure import lazy_installs_allowed
+ from pm.extras import extra_supported
+ except Exception:
+ return False
+ return extra_supported(feature) and bool(lazy_installs_allowed())
+
+
def check_tts_requirements() -> bool:
- """Return whether the explicitly resolved TTS provider can run."""
+ """Return whether the explicitly resolved TTS provider can run — now, or after the
+ first-use SDK install that synthesis performs. This is the ``text_to_speech`` tool's
+ ``check_fn``, so it runs on every tool listing and must never install."""
tts_config = _load_tts_config()
provider = _get_provider(tts_config)
if _resolve_command_provider_config(provider, tts_config) is not None:
return True
check = _BUILTIN_REQUIREMENTS.get(provider)
- return check() if check is not None else _plugin_provider_is_available(provider)
+ if check is not None:
+ return bool(check()) or _ready_after_first_use_install(provider)
+ return _plugin_provider_is_available(provider)
# --- Registry ---