Skip to content

The agent that grows with you

fix(tts): keep local voices warm for tts.keep_warm_seconds after the last lease drops

brooklyn!80e30634a512
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index cb95e732aeb..7e1bed1cd19 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -1052,6 +1052,10 @@ DEFAULT_CONFIG = {
# "edge" (free) | "elevenlabs" (premium) | "openai" | "xai" | "minimax" | "mistral" |
# "gemini" | "deepinfra" | "neutts" (local) | "kittentts" (local) | "piper" (local)
"provider": "edge",
+ # Seconds a local engine (Piper, KittenTTS) stays loaded after the last speech toggle
+ # turns off, so a quick re-activation (wake word, voice-chat restart) skips the reload.
+ # 0 unloads immediately.
+ "keep_warm_seconds": 60,
"streaming": {
# Shortest first sentence (chars) spoken on its own by streaming TTS; shorter openers
# ride with the next sentence. 20 suits English; CJK voice setups use ~6.
diff --git a/tests/hermes_cli/test_web_server_tts_lease.py b/tests/hermes_cli/test_web_server_tts_lease.py
index 04956f0757e..c5e55b80430 100644
--- a/tests/hermes_cli/test_web_server_tts_lease.py
+++ b/tests/hermes_cli/test_web_server_tts_lease.py
@@ -80,9 +80,16 @@ def test_active_acquires_and_warms(client, monkeypatch):
assert tts_tool_lifecycle.tts_lease_holders() == ["desktop:read-aloud"]
-def test_inactive_releases_and_unloads_when_last(client, monkeypatch):
+def _write_tts_config(home, tts):
+ import yaml
+
+ (home / "config.yaml").write_text(yaml.safe_dump({"tts": tts}), encoding="utf-8")
+
+
+def test_inactive_releases_and_unloads_when_last(client, monkeypatch, isolated_profiles):
from tools import tts_tool_lifecycle, tts_tool_local
+ _write_tts_config(isolated_profiles["default"], {"keep_warm_seconds": 0})
monkeypatch.setattr(tts_tool_lifecycle, "warm_tts_provider", lambda cfg=None, provider=None: {"action": "noop", "warmed": False, "provider": "piper"})
client.post("/api/audio/tts-lease", json={"lease": "desktop:read-aloud", "active": True})
client.post("/api/audio/tts-lease", json={"lease": "desktop:conversation:abc", "active": True})
@@ -99,6 +106,36 @@ def test_inactive_releases_and_unloads_when_last(client, monkeypatch):
assert tts_tool_local._piper_voice_cache == {}
+def test_last_release_keeps_model_warm_by_default(client, monkeypatch):
+ """#118037: with the shipped config the last release parks the unload instead of evicting now."""
+ from tools import tts_tool_lifecycle, tts_tool_local
+
+ monkeypatch.setattr(tts_tool_lifecycle, "warm_tts_provider", lambda cfg=None, provider=None: {"action": "loaded", "warmed": True, "provider": "piper"})
+ client.post("/api/audio/tts-lease", json={"lease": "desktop:conversation:abc", "active": True})
+ tts_tool_local._piper_voice_cache["voice"] = object()
+
+ last = client.post("/api/audio/tts-lease", json={"lease": "desktop:conversation:abc", "active": False}).json()
+ assert last["leases"] == 0
+ assert last["released"] == 0
+ assert len(tts_tool_local._piper_voice_cache) == 1
+
+
+def test_keep_warm_window_from_config_unloads_after_it_elapses(client, monkeypatch, isolated_profiles):
+ import time
+ from tools import tts_tool_lifecycle, tts_tool_local
+
+ _write_tts_config(isolated_profiles["default"], {"keep_warm_seconds": 0.1})
+ monkeypatch.setattr(tts_tool_lifecycle, "warm_tts_provider", lambda cfg=None, provider=None: {"action": "loaded", "warmed": True, "provider": "piper"})
+ client.post("/api/audio/tts-lease", json={"lease": "desktop:conversation:abc", "active": True})
+ tts_tool_local._piper_voice_cache["voice"] = object()
+ client.post("/api/audio/tts-lease", json={"lease": "desktop:conversation:abc", "active": False})
+
+ deadline = time.monotonic() + 5
+ while tts_tool_local._piper_voice_cache and time.monotonic() < deadline:
+ time.sleep(0.02)
+ assert tts_tool_local._piper_voice_cache == {}
+
+
def test_warm_failure_is_reported_not_an_http_error(client, monkeypatch):
from tools import tts_tool_lifecycle
diff --git a/tests/tools/test_tts_lifecycle_leases.py b/tests/tools/test_tts_lifecycle_leases.py
index 41a75c04da0..58deee6ef2d 100644
--- a/tests/tools/test_tts_lifecycle_leases.py
+++ b/tests/tools/test_tts_lifecycle_leases.py
@@ -4,7 +4,7 @@ Local engines load lazily on first synthesis, so the first spoken reply after
"read replies aloud" / voice conversation turns on pays the model load as dead
air. The toggles now hold *leases*: acquiring warms the configured provider
into the SAME cache slot synthesis reads; releasing the last lease unloads
-resident local models.
+resident local models once the keep-warm window passes (#118037).
"""
from __future__ import annotations
@@ -61,6 +61,39 @@ def fake_piper(monkeypatch, tmp_path):
return cfg
+class _FakeTimer:
+ def __init__(self, interval, function, args=None, kwargs=None):
+ self.interval, self.function, self.args = interval, function, tuple(args or ())
+ self.started = self.cancelled = False
+ self.daemon = False
+
+ def start(self):
+ self.started = True
+
+ def cancel(self):
+ self.cancelled = True
+
+ def fire(self):
+ self.function(*self.args)
+
+
+def timers(monkeypatch):
+ created: list = []
+
+ def _factory(*args, **kwargs):
+ timer = _FakeTimer(*args, **kwargs)
+ created.append(timer)
+ return timer
+
+ monkeypatch.setattr(tts_tool_lifecycle, "_make_keep_warm_timer", _factory, raising=False)
+ return created
+
+
+def _pending(timers):
+ return [t for t in timers if t.started and not t.cancelled]
+
+
# --------------------------------------------------------------------------
# warm_tts_provider: warm-up populates the exact slot synthesis reads
# --------------------------------------------------------------------------
@@ -180,7 +213,7 @@ def test_acquire_warms_and_counts(fake_piper):
assert tts_tool_lifecycle.tts_lease_holders() == ["desktop:read-aloud"]
-def test_last_release_unloads_but_earlier_release_does_not(fake_piper):
+def test_last_release_unloads_but_earlier_release_does_not(fake_piper, timers):
tts_tool_lifecycle.acquire_tts_lease("desktop:read-aloud")
tts_tool_lifecycle.acquire_tts_lease("tui:voice-tts")
assert len(tts_tool_local._piper_voice_cache) == 1
@@ -190,9 +223,12 @@ def test_last_release_unloads_but_earlier_release_does_not(fake_piper):
first = tts_tool_lifecycle.release_tts_lease("desktop:read-aloud")
assert first == {"leases": 1, "released": 0}
assert len(tts_tool_local._piper_voice_cache) == 1
+ assert _pending(timers) == []
last = tts_tool_lifecycle.release_tts_lease("tui:voice-tts")
- assert last == {"leases": 0, "released": 1}
+ assert last["leases"] == 0
+ [timer] = _pending(timers)
+ timer.fire()
assert tts_tool_local._piper_voice_cache == {}
@@ -242,7 +278,7 @@ def test_every_local_warmer_has_a_registered_cache():
# --------------------------------------------------------------------------
-def test_plugin_provider_warm_and_release_follow_the_lease(monkeypatch):
+def test_plugin_provider_warm_and_release_follow_the_lease(monkeypatch, timers):
from agent import tts_provider, tts_registry
calls: list = []
@@ -272,12 +308,14 @@ def test_plugin_provider_warm_and_release_follow_the_lease(monkeypatch):
tts_tool_lifecycle.release_tts_lease("desktop:read-aloud")
assert calls == ["warm", "warm"] # still one holder — no release yet
tts_tool_lifecycle.release_tts_lease("tui:voice-tts")
+ assert calls == ["warm", "warm"] # parked for the keep-warm window
+ _pending(timers)[0].fire()
assert calls == ["warm", "warm", "release"]
finally:
tts_registry._reset_for_tests()
-def test_command_provider_runs_warm_and_release_commands(monkeypatch):
+def test_command_provider_runs_warm_and_release_commands(monkeypatch, timers):
ran: list = []
done = threading.Event()
@@ -301,5 +339,70 @@ def test_command_provider_runs_warm_and_release_commands(monkeypatch):
assert done.wait(5)
done.clear()
tts_tool_lifecycle.release_tts_lease("desktop:read-aloud")
+ _pending(timers)[0].fire()
assert done.wait(5)
assert ran == ["curl -s localhost:5002/load?model='kokoro v1'", "curl -s localhost:5002/unload"]
+
+
+# --------------------------------------------------------------------------
+# Keep-warm window (#118037): the last release schedules the unload on a
+# cancellable timer instead of dropping the model inline, so a wake-word loop
+# that re-acquires within ``tts.keep_warm_seconds`` reuses the loaded voice.
+# --------------------------------------------------------------------------
+
+
+def test_last_release_keeps_model_warm_for_configured_window(fake_piper, timers):
+ fake_piper["keep_warm_seconds"] = 30
+ tts_tool_lifecycle.acquire_tts_lease("desktop:conversation")
+
+ result = tts_tool_lifecycle.release_tts_lease("desktop:conversation")
+
+ assert result == {"leases": 0, "released": 0}
+ assert len(tts_tool_local._piper_voice_cache) == 1
+ [timer] = _pending(timers)
+ assert timer.interval == fake_piper["keep_warm_seconds"]
+ assert timer.daemon is True # a parked unload never holds the process open
+
+ timer.fire()
+ assert tts_tool_local._piper_voice_cache == {}
+
+
+def test_reacquire_within_window_reuses_the_loaded_voice(fake_piper, timers):
+ tts_tool_lifecycle.acquire_tts_lease("desktop:conversation")
+ tts_tool_lifecycle.release_tts_lease("desktop:conversation")
+ [stale] = _pending(timers)
+
+ again = tts_tool_lifecycle.acquire_tts_lease("desktop:conversation")
+
+ assert again["action"] == "cached"
+ assert _FakePiperVoice.loads == 1
+ assert _pending(timers) == []
+ stale.fire() # a timer that already woke up before the cancel must not unload
+ assert len(tts_tool_local._piper_voice_cache) == 1
+
+
+def test_release_during_warm_up_still_unloads_after_the_window(fake_piper, timers, monkeypatch):
+ """A release that lands mid-load finds an empty cache; the voice must not stay resident forever."""
+ real_load = _FakePiperVoice.load.__func__
+
+ def _load_then_release(cls, model_path, use_cuda=False):
+ tts_tool_lifecycle.release_tts_lease("tui:voice-tts")
+ return real_load(cls, model_path, use_cuda)
+
+ monkeypatch.setattr(_FakePiperVoice, "load", classmethod(_load_then_release))
+ tts_tool_lifecycle.acquire_tts_lease("tui:voice-tts")
+
+ assert tts_tool_lifecycle.tts_lease_holders() == []
+ assert len(tts_tool_local._piper_voice_cache) == 1
+ [timer] = _pending(timers)
+ timer.fire()
+ assert tts_tool_local._piper_voice_cache == {}
+
+
+def test_zero_keep_warm_unloads_inline(fake_piper, timers):
+ fake_piper["keep_warm_seconds"] = 0
+ tts_tool_lifecycle.acquire_tts_lease("cli:voice-tts")
+
+ assert tts_tool_lifecycle.release_tts_lease("cli:voice-tts") == {"leases": 0, "released": 1}
+ assert tts_tool_local._piper_voice_cache == {}
+ assert _pending(timers) == []
diff --git a/tools/tts_tool_lifecycle.py b/tools/tts_tool_lifecycle.py
index d454c0e0c4d..b5656f32345 100644
--- a/tools/tts_tool_lifecycle.py
+++ b/tools/tts_tool_lifecycle.py
@@ -2,9 +2,10 @@
Local engines load lazily on first synthesis (dead air on the first spoken reply) and then stay
resident. Every surface that flips speech output on holds a *lease* here (warming the configured
-engine); when the last lease is released the local model caches are dropped, so one surface's
-"off" can't unload a model another surface still needs. Cloud providers have nothing resident;
-warming only ensures the SDK imports. Origin seams (``_load_tts_config``, ``_get_provider``) are
+engine); when the last lease is released the local model caches are dropped after a keep-warm
+window (``tts.keep_warm_seconds``), so one surface's "off" can't unload a model another surface
+still needs and a wake-word loop that re-acquires within the window reuses the loaded model.
+Cloud providers have nothing resident; warming only ensures the SDK imports. Origin seams (``_load_tts_config``, ``_get_provider``) are
resolved through :func:`_origin` per call.
"""
@@ -15,6 +16,7 @@ import threading
import time
from typing import Any, Callable, Dict, List, Optional
+from agent.memory_provider import ctx_bound
from tools import tts_command_provider
from tools.tts_command_provider import (
BUILTIN_TTS_PROVIDERS, _get_command_tts_timeout, _get_named_provider_config,
@@ -30,6 +32,12 @@ logger = logging.getLogger("tools.tts_tool")
_tts_lease_lock = threading.Lock()
_tts_leases: set = set()
+# Pending keep-warm unload; the generation lets a timer that already woke up see it was superseded.
+_DEFAULT_KEEP_WARM_SECONDS = 60.0
+_make_keep_warm_timer = threading.Timer # test seam
+_keep_warm_timer: Optional[threading.Timer] = None
+_keep_warm_generation = 0
+
def _local_tts_warmers() -> Dict[str, Callable[[Dict[str, Any]], Any]]:
"""Provider name → loader populating that engine's cache slot (same key synthesis uses)."""
@@ -140,22 +148,74 @@ def release_tts_provider(provider: Optional[str] = None) -> Dict[str, Any]:
return {"released": released}
+def _keep_warm_seconds() -> float:
+ """``tts.keep_warm_seconds``, read per call so each profile's config applies; ``0`` = unload now."""
+ raw = _origin()._load_tts_config().get("keep_warm_seconds", _DEFAULT_KEEP_WARM_SECONDS)
+ try:
+ return max(0.0, float(raw))
+ except (TypeError, ValueError):
+ return _DEFAULT_KEEP_WARM_SECONDS
+
+
+def _cancel_keep_warm_locked() -> None:
+ global _keep_warm_timer, _keep_warm_generation
+ _keep_warm_generation += 1
+ if _keep_warm_timer is not None:
+ _keep_warm_timer.cancel()
+ _keep_warm_timer = None
+
+
+def _schedule_release_locked() -> int:
+ """No holders left: (re)start the keep-warm window, or unload inline when it is 0.
+ Returns the count released inline."""
+ global _keep_warm_timer
+ _cancel_keep_warm_locked()
+ delay = _keep_warm_seconds()
+ if delay <= 0:
+ return release_tts_provider()["released"]
+ # ctx_bound: the unload reads config/secrets under the releasing caller's profile scope.
+ timer = _make_keep_warm_timer(
+ delay, ctx_bound(_release_after_keep_warm), args=(_keep_warm_generation,))
+ timer.daemon = True
+ _keep_warm_timer = timer
+ timer.start()
+ return 0
+
+
+def _release_after_keep_warm(generation: int) -> None:
+ global _keep_warm_timer
+ with _tts_lease_lock:
+ if generation != _keep_warm_generation or _tts_leases:
+ return
+ _keep_warm_timer = None
+ release_tts_provider()
+
+
def acquire_tts_lease(lease: str, tts_config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""Register ``lease`` (e.g. ``"desktop:read-aloud"``) and warm the provider. Re-acquiring is
- idempotent but still re-warms (cheap on a cache hit; heals a cache cleared elsewhere)."""
+ idempotent but still re-warms (cheap on a cache hit; heals a cache cleared elsewhere). An
+ acquire inside the keep-warm window cancels the pending unload."""
with _tts_lease_lock:
+ _cancel_keep_warm_locked()
_tts_leases.add(lease)
holders = len(_tts_leases)
- return {**warm_tts_provider(tts_config), "leases": holders}
+ result = warm_tts_provider(tts_config)
+ with _tts_lease_lock:
+ # Every holder released while the load ran: the window starts now that the model is resident.
+ if not _tts_leases:
+ _schedule_release_locked()
+ return {**result, "leases": holders}
def release_tts_lease(lease: str) -> Dict[str, Any]:
- """Drop ``lease``; the last one out unloads resident local models. A never-acquired lease is a
- no-op (still reports the holder count) so surfaces can call this unconditionally."""
+ """Drop ``lease``; the last one out unloads resident local models once the keep-warm window
+ passes with no new acquire. A never-acquired lease is a no-op (still reports the holder count)
+ so surfaces can call this unconditionally. ``released`` counts models unloaded inline."""
with _tts_lease_lock:
+ held = lease in _tts_leases
_tts_leases.discard(lease)
holders = len(_tts_leases)
- released = release_tts_provider()["released"] if holders == 0 else 0
+ released = _schedule_release_locked() if held and holders == 0 else 0
return {"leases": holders, "released": released}
@@ -167,4 +227,5 @@ def tts_lease_holders() -> List[str]:
def _reset_tts_leases_for_tests() -> None:
with _tts_lease_lock:
+ _cancel_keep_warm_locked()
_tts_leases.clear()
diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md
index 2dec21b039b..cf74aaa66f0 100644
--- a/website/docs/user-guide/configuration.md
+++ b/website/docs/user-guide/configuration.md
@@ -2115,6 +2115,7 @@ Legitimately slow work is not penalized: streaming responses, tool heartbeats (e
tts:
provider: "edge" # "edge" | "elevenlabs" | "openai" | "minimax" | "mistral" | "gemini" | "xai" | "neutts" | "kittentts" | "piper" | "deepinfra"
speed: 1.0 # Global speed multiplier (fallback for all providers)
+ keep_warm_seconds: 60 # Keep a local engine loaded this long after the last speech toggle turns off (0 = unload at once)
edge:
voice: "en-US-AriaNeural" # 322 voices, 74 languages
speed: 1.0 # Speed multiplier (converted to rate percentage, e.g. 1.5 → +50%)
diff --git a/website/docs/user-guide/features/tts.md b/website/docs/user-guide/features/tts.md
index af3cf9f324c..b321aed0626 100644
--- a/website/docs/user-guide/features/tts.md
+++ b/website/docs/user-guide/features/tts.md
@@ -271,7 +271,7 @@ Local engines (Piper, KittenTTS) load their model lazily, so without help the *f
- **Desktop** — **Read replies aloud** is a desktop-local preference, independent of the gateway's `voice.auto_tts` setting in Settings → Voice. It migrates the shared value once, then later gateway configuration changes do not override the desktop toggle. If local storage is full or unavailable, the choice still lasts for this window; persistence across a reload remains best-effort. Turning on **Read replies aloud**, or starting a **voice conversation**, pre-loads the configured engine in the background right away. Turning both off again unloads the resident model (a Piper voice is tens of MB; KittenTTS up to ~80MB) so it isn't parked in RAM for nothing.
- **CLI / TUI** — `/voice tts` (and `/voice on` when `voice.auto_tts` is set) do the same; `/voice off` releases.
-Each toggle holds a *lease* on the engine; the model is only unloaded when the last lease across surfaces is released, so switching off read-aloud in one Desktop window never pulls the voice out from under a conversation running in another. For cloud providers there is no model to hold — the toggle only makes sure a lazily-installed SDK (edge-tts, ElevenLabs, Mistral) is present. Warm-up is best-effort: if the engine can't load, the toggle still succeeds and the first reply falls back to loading on demand as before.
+Each toggle holds a *lease* on the engine; the model is only unloaded when the last lease across surfaces is released, so switching off read-aloud in one Desktop window never pulls the voice out from under a conversation running in another. The unload waits `tts.keep_warm_seconds` (default `60`) after the last release, and any toggle turning speech back on within that window keeps the loaded model, so a wake-word loop or a quickly restarted voice conversation doesn't reload the voice each time. Set it to `0` to unload immediately. For cloud providers there is no model to hold — the toggle only makes sure a lazily-installed SDK (edge-tts, ElevenLabs, Mistral) is present. Warm-up is best-effort: if the engine can't load, the toggle still succeeds and the first reply falls back to loading on demand as before.
The Desktop calls `POST /api/audio/tts-lease` with `{"lease": "<name>", "active": true|false}`; other frontends can use the same endpoint.