Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(music): the review's four — no per-turn config parse, an honest request deadline, a player that always dies, a test-proof cache

Harald2fc741de7ac2
diff --git a/jarvis/core/music_service.py b/jarvis/core/music_service.py
index ed9ab717fe..1c8709673e 100644
--- a/jarvis/core/music_service.py
+++ b/jarvis/core/music_service.py
@@ -83,16 +83,60 @@ def connected_music_services(*, store: object | None = None) -> tuple[str, ...]:
log.debug("music connection probe failed: %s", exc)
return _connected_cache[1] if _connected_cache else ()
result = tuple(live)
- with _connected_lock:
- _connected_cache = (now + _CONNECTED_TTL_S, result)
+ if store is None: # an injected (test) store must never poison the process cache
+ with _connected_lock:
+ _connected_cache = (now + _CONNECTED_TTL_S, result)
return result
def forget_connected_music_services() -> None:
"""Drop the cached connection answer (a connect/disconnect just happened)."""
- global _connected_cache
+ global _connected_cache, _preferred_cache
with _connected_lock:
_connected_cache = None
+ _preferred_cache = None
+
+
+# The preferred service is read from jarvis.toml; a tool description is built
+# on every router turn, so the value is remembered for the same few seconds
+# rather than re-parsing the config each time. The Settings route drops it on
+# write (via forget_connected_music_services), so a change shows at once.
+_preferred_cache: tuple[float, str] | None = None
+
+
+def preferred_music_service() -> str:
+ """``[music] preferred_service`` — cached briefly; a config fault reads as
+ ``auto``. Never raises."""
+ global _preferred_cache
+ now = time.monotonic()
+ with _connected_lock:
+ if _preferred_cache is not None and _preferred_cache[0] > now:
+ return _preferred_cache[1]
+ try:
+ from jarvis.core.config import load_config
+
+ value = str(load_config().music.preferred_service or MUSIC_SERVICE_AUTO)
+ except Exception as exc: # noqa: BLE001 — a config fault means "no preference"
+ log.debug("preferred music service read failed: %s", exc)
+ value = MUSIC_SERVICE_AUTO
+ with _connected_lock:
+ _preferred_cache = (now + _CONNECTED_TTL_S, value)
+ return value
+
+
+def description_hint(service_id: str) -> str:
+ """The sentence a music tool appends to its description (see
+ :func:`preference_hint`), built from the cached preference and connection
+ state. Never raises — a description must not."""
+ try:
+ return preference_hint(
+ service_id,
+ preferred=preferred_music_service(),
+ connected=connected_music_services(),
+ )
+ except Exception as exc: # noqa: BLE001 — a fault means no hint, not no tool
+ log.debug("music description hint failed: %s", exc)
+ return ""
def service_label(service_id: str) -> str:
@@ -155,9 +199,11 @@ def preference_hint(service_id: str, *, preferred: str, connected: Iterable[str]
__all__ = [
"connected_music_services",
+ "description_hint",
"explicit_music_service",
"forget_connected_music_services",
"preference_hint",
+ "preferred_music_service",
"resolve_music_service",
"service_label",
]
diff --git a/jarvis/platform/music_player.py b/jarvis/platform/music_player.py
index e250272be9..b1b216aec3 100644
--- a/jarvis/platform/music_player.py
+++ b/jarvis/platform/music_player.py
@@ -26,6 +26,7 @@ import logging
import subprocess
import sys
import threading
+import time
from collections.abc import Callable
from pathlib import Path
from typing import Any
@@ -255,10 +256,15 @@ class MusicPlayer:
except Exception as exc: # noqa: BLE001 — pipe gone → the host is gone
self.stop()
raise MusicPlayerError(f"player went away: {exc}") from exc
- deadline = timeout
+ # One fixed deadline: the condition is shared and notified on EVERY
+ # reply, so a per-wait timeout would restart on unrelated traffic.
+ deadline = time.monotonic() + timeout
with self._cond:
while req_id not in self._replies:
- if not self._cond.wait(deadline):
+ remaining = deadline - time.monotonic()
+ if remaining <= 0 or not self._cond.wait(remaining):
+ if req_id in self._replies:
+ break
raise MusicPlayerError(f"player did not answer '{cmd}' in {timeout:.0f}s")
if not self._ready.is_set() and req_id not in self._replies:
raise MusicPlayerError("player exited")
diff --git a/jarvis/platform/music_player_host.py b/jarvis/platform/music_player_host.py
index a276fd472d..c07a5361fd 100644
--- a/jarvis/platform/music_player_host.py
+++ b/jarvis/platform/music_player_host.py
@@ -6,8 +6,9 @@ A pywebview window that starts MINIMIZED (a taskbar entry, no focus, no tab —
and unlike a truly hidden window, WebView2 does start media in it), keeps its
own persistent browser profile (so a YouTube Music login survives restarts),
and takes JSON-line commands on stdin — ``load`` a URL, ``show`` / ``hide`` the window, read the
-player ``state``, ``pause`` / ``play`` / ``next`` / ``previous`` / ``volume``
-— answering one JSON line per command on stdout. Playback therefore happens
+player ``state``, ``pause`` / ``play`` / ``toggle`` / ``next`` / ``previous`` /
+``volume`` — answering one JSON line per command on stdout. That closed list
+IS the protocol: no free-form script ever crosses the pipe. Playback therefore happens
in the background: no browser tab, no focus steal, one window that navigates
instead of piling up tabs.
@@ -168,8 +169,6 @@ def _dispatch(window: Any, cmd: str, msg: dict[str, Any]) -> Any:
if cmd == "state":
raw = window.evaluate_js(_STATE_JS)
return json.loads(raw) if isinstance(raw, str) else raw
- if cmd == "eval":
- return window.evaluate_js(str(msg.get("js") or ""))
if cmd == "volume":
return window.evaluate_js(_volume_js(int(msg.get("level") or 0)))
if cmd in _JS:
@@ -191,6 +190,14 @@ def main(argv: list[str] | None = None) -> int:
)
args = parser.parse_args(argv)
+ # The protocol is UTF-8 on both pipes whatever the console code page says
+ # (a title with an umlaut must survive the round trip on a cp1252 box).
+ for stream in (sys.stdin, sys.stdout, sys.stderr):
+ try:
+ stream.reconfigure(encoding="utf-8", errors="replace") # type: ignore[union-attr]
+ except Exception as exc: # noqa: BLE001 — a non-reconfigurable stream keeps its encoding
+ _log(f"stream reconfigure skipped: {exc}")
+
# Must be in the environment before the WebView2 runtime is created.
flag = "--autoplay-policy=no-user-gesture-required"
existing = os.environ.get("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS", "")
@@ -212,7 +219,7 @@ def main(argv: list[str] | None = None) -> int:
elif args.start == "offscreen":
extra["x"] = -32000
extra["y"] = -32000
- window = webview.create_window(
+ window: Any = webview.create_window(
args.title,
"about:blank",
width=1080,
@@ -221,6 +228,9 @@ def main(argv: list[str] | None = None) -> int:
confirm_close=False,
**extra,
)
+ if window is None: # pywebview returns None only when the GUI cannot be created
+ _emit({"event": "unavailable", "error": "no window could be created"})
+ return 2
quitting = {"flag": False}
@@ -238,12 +248,18 @@ def main(argv: list[str] | None = None) -> int:
window.events.closing += _on_closing
def _serve_then_quit() -> None:
- _serve(window)
- quitting["flag"] = True
+ # Whatever ends the command loop — EOF, quit, or a read fault — the
+ # window must go down, or the GUI loop would keep a ghost player alive.
try:
- window.destroy()
- except Exception as exc: # noqa: BLE001 — already gone is fine
- _log(f"destroy skipped: {exc}")
+ _serve(window)
+ except Exception as exc: # noqa: BLE001 — logged, and the finally still tears down
+ _log(f"serve loop ended with {type(exc).__name__}: {exc}")
+ finally:
+ quitting["flag"] = True
+ try:
+ window.destroy()
+ except Exception as exc: # noqa: BLE001 — already gone is fine
+ _log(f"destroy skipped: {exc}")
try:
# pywebview runs ``func`` on its own worker thread once the GUI loop is up.
diff --git a/jarvis/plugins/tool/spotify_rest.py b/jarvis/plugins/tool/spotify_rest.py
index 935b583d8c..a749ea12c8 100644
--- a/jarvis/plugins/tool/spotify_rest.py
+++ b/jarvis/plugins/tool/spotify_rest.py
@@ -85,19 +85,15 @@ async def _default_refresher(observed_access_token: str | None = None) -> bool:
def _preference_hint_for(service_id: str) -> str:
- """One sentence about ``[music] preferred_service`` for the tool description,
- empty when there is nothing to say. Never raises (a description must not)."""
+ """One sentence about ``[music] preferred_service`` for the tool
+ description — cached in ``jarvis.core.music_service`` so a router turn
+ never re-parses the config. Never raises (a description must not)."""
try:
- from jarvis.core.config import load_config
- from jarvis.core.music_service import connected_music_services, preference_hint
+ from jarvis.core.music_service import description_hint
- preferred = str(load_config().music.preferred_service)
- connected = connected_music_services()
- return preference_hint(service_id, preferred=preferred, connected=connected)
- except Exception: # noqa: BLE001 — a config/store fault means no hint, not no tool
+ return description_hint(service_id)
+ except Exception: # noqa: BLE001 — a fault means no hint, not no tool
return ""
-
-
def _artists(item: dict[str, Any]) -> str:
names = [a.get("name") for a in item.get("artists") or [] if a.get("name")]
return ", ".join(n for n in names if n)
diff --git a/jarvis/plugins/tool/youtube_music_rest.py b/jarvis/plugins/tool/youtube_music_rest.py
index c47fe5033c..f223191b69 100644
--- a/jarvis/plugins/tool/youtube_music_rest.py
+++ b/jarvis/plugins/tool/youtube_music_rest.py
@@ -166,19 +166,15 @@ def _default_playback_mode() -> str:
def _preference_hint_for(service_id: str) -> str:
- """One sentence about ``[music] preferred_service`` for a tool description,
- empty when there is nothing to say. Never raises (a description must not)."""
+ """One sentence about ``[music] preferred_service`` for the tool
+ description — cached in ``jarvis.core.music_service`` so a router turn
+ never re-parses the config. Never raises (a description must not)."""
try:
- from jarvis.core.config import load_config
- from jarvis.core.music_service import connected_music_services, preference_hint
+ from jarvis.core.music_service import description_hint
- preferred = str(load_config().music.preferred_service)
- connected = connected_music_services()
- return preference_hint(service_id, preferred=preferred, connected=connected)
- except Exception: # noqa: BLE001 — a config/store fault means no hint, not no tool
+ return description_hint(service_id)
+ except Exception: # noqa: BLE001 — a fault means no hint, not no tool
return ""
-
-
def _clean(text: Any) -> str:
return html.unescape(str(text or "")).strip()
diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.py
index 94ab519660..173642dd88 100644
--- a/jarvis/ui/web/settings_routes.py
+++ b/jarvis/ui/web/settings_routes.py
@@ -802,6 +802,14 @@ async def put_music_settings(body: MusicSettingsBody, request: Request) -> dict[
music.playback = playback # type: ignore[attr-defined]
except Exception as exc: # noqa: BLE001 — frozen model is not an error
log.debug("in-memory cfg.music update skipped: %s", exc)
+ try:
+ # The music tools remember the preference for a few seconds; a change
+ # here must show on the very next turn.
+ from jarvis.core.music_service import forget_connected_music_services
+
+ forget_connected_music_services()
+ except Exception as exc: # noqa: BLE001 — a cache miss is the worst case here
+ log.debug("music preference cache reset skipped: %s", exc)
return {
"ok": True,
diff --git a/tests/unit/core/test_music_service.py b/tests/unit/core/test_music_service.py
index d0ca4d30e7..3b8dd2d364 100644
--- a/tests/unit/core/test_music_service.py
+++ b/tests/unit/core/test_music_service.py
@@ -87,3 +87,24 @@ def test_music_config_defaults_and_sanitising():
assert MusicConfig(playback="Browser").playback == "browser"
assert set(MUSIC_SERVICES) == {"auto", "spotify", "youtube_music"}
assert set(MUSIC_PLAYBACK_MODES) == {"background", "browser"}
+
+
+def test_description_hint_reads_the_cached_preference(monkeypatch):
+ import jarvis.core.config as config_mod
+
+ calls = {"n": 0}
+
+ def fake_load_config():
+ calls["n"] += 1
+ return SimpleNamespace(music=SimpleNamespace(preferred_service="youtube_music"))
+
+ monkeypatch.setattr(config_mod, "load_config", fake_load_config)
+ monkeypatch.setattr(ms, "connected_music_services", lambda: ("spotify", "youtube_music"))
+ ms.forget_connected_music_services()
+ assert "prefers YouTube Music" in ms.description_hint("youtube_music")
+ assert "names Spotify explicitly" in ms.description_hint("spotify")
+ assert calls["n"] == 1 # one config read for both descriptions
+ ms.forget_connected_music_services()
+ ms.description_hint("spotify")
+ assert calls["n"] == 2 # a settings write drops the cache
+ ms.forget_connected_music_services()