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(youtube-music): the background player answers while loading, and a play never waits three minutes

rubenluetke10-beep8de0eda1fd22
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 8518954bb3..27fe43c7cd 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -11608,3 +11608,39 @@ ran, not that the USER'S REQUEST happened. Any tool whose output is
instructions for the model (``run-skill``, ``answer_instruction`` lookups,
mission directives) is a hand-off, and every reader that turns results into a
completion claim — prompts and canned lines alike — must classify it as such.
+
+## BUG-166: "play some music" takes three minutes and the player window never appears — the host sat in pywebview's loaded gate and the parent counted naps, not time (HIGH, FIXED 2026-08-22)
+
+**Symptom (maintainer, 2026-08-22 20:01–20:05).** "Play nice music with
+YouTube Music" — the tool call ran for **199.6 s**; the answer then said the
+player "should be showing you throwback tracks"; no player window was visible.
+Ten minutes later the window was found minimized on the taskbar with YouTube's
+cookie-consent page in it.
+
+**Cause (two defects, one symptom).** (1) ``music_player_host`` reads the page
+with pywebview ``evaluate_js``, which is gated on the window's ``loaded``
+event and blocks up to 20 s when a navigation has not reported back; after
+the session's second ``load`` that event stayed clear, so EVERY ``state`` read
+blocked, and because the host's command loop is sequential the ``show`` behind
+them blocked too — the window was never restored. (2) ``_play_in_player``
+bounded its confirm loop by counting its 0.5 s naps, not by the clock: 18
+reads × (0.5 s nap + 10 s transport timeout) + one 10 s ``show`` = 199 s.
+
+**Fix (2026-08-22).** Host: ``state`` answers ``{"loading": true, …}`` after a
+bounded wait (``_page_loaded``, 1 s) instead of entering the gate; the page
+commands fail fast with "still loading"; ``show`` additionally un-minimizes and
+raises the window through Win32 by its title when pywebview's ``restore`` /
+``show`` leave it iconic (``_force_foreground``, a quiet no-op off Windows).
+Client: ``MusicPlayer.state()`` / ``show()`` take a per-call ``timeout``.
+Plugin: the confirm loop runs on a wall-clock deadline, reads with a 3 s bound
+(``_call_with_timeout`` also accepts players without the kwarg), skips
+``loading`` snapshots, and still brings the window forward at the end. Tests:
+``tests/unit/platform/test_music_player_host.py`` (new),
+``test_state_and_show_take_a_per_call_timeout``,
+``test_play_confirm_is_bounded_by_wall_clock_when_the_player_is_slow``,
+``test_play_keeps_polling_while_the_host_says_loading``.
+
+**Lesson.** A loop that bounds itself by counting sleeps is unbounded the
+moment the work between sleeps can block; bound by the clock, and bound every
+blocking read inside it tighter than the loop. A sequential command channel
+must never run a call that can block for longer than its own client's timeout.
diff --git a/jarvis/platform/music_player.py b/jarvis/platform/music_player.py
index b1b216aec3..08f7ba6f53 100644
--- a/jarvis/platform/music_player.py
+++ b/jarvis/platform/music_player.py
@@ -278,8 +278,10 @@ class MusicPlayer:
def load(self, url: str) -> bool:
return bool(self.request("load", url=url))
- def state(self) -> dict[str, Any]:
- result = self.request("state")
+ def state(self, *, timeout: float = _REQUEST_TIMEOUT_S) -> dict[str, Any]:
+ """The page state; ``timeout`` bounds the wait for a host that is busy
+ (a confirm loop polls this and must not inherit a 10 s wait per read)."""
+ result = self.request("state", timeout=timeout)
return result if isinstance(result, dict) else {}
def play(self) -> bool:
@@ -300,8 +302,8 @@ class MusicPlayer:
def set_volume(self, level: int) -> bool:
return bool(self.request("volume", level=int(level)))
- def show(self) -> bool:
- return bool(self.request("show"))
+ def show(self, *, timeout: float = _REQUEST_TIMEOUT_S) -> bool:
+ return bool(self.request("show", timeout=timeout))
def hide(self) -> bool:
return bool(self.request("hide"))
diff --git a/jarvis/platform/music_player_host.py b/jarvis/platform/music_player_host.py
index c07a5361fd..e4fa58ba0e 100644
--- a/jarvis/platform/music_player_host.py
+++ b/jarvis/platform/music_player_host.py
@@ -142,6 +142,79 @@ def _serve(window: Any) -> None:
# down so webview.start() returns and the process ends.
+#: How long a page-reading command waits for the current navigation to finish
+#: before answering "still loading". pywebview gates ``evaluate_js`` on its
+#: ``loaded`` event and blocks up to 20 s when a navigation has not reported
+#: back (live 2026-08-22 20:01:52: the second ``load`` of the session left
+#: ``loaded`` clear, every ``state`` then sat 20 s in the gate while the parent
+#: gave up at 10 s, and one play request took 199 s — 18 reads plus the
+#: ``show`` queued behind them). The command loop is sequential, so one blocked
+#: read holds every later command hostage; a short bounded wait keeps the loop
+#: answering and lets the parent decide what to do with a page that is still
+#: turning.
+_LOADED_WAIT_S = 1.0
+
+_LOADING_STATE: dict[str, Any] = {
+ "loading": True,
+ "ready": False,
+ "has_video": False,
+ "paused": None,
+ "ended": None,
+ "position": None,
+ "duration": None,
+ "volume": None,
+ "consent": False,
+ "signed_in": False,
+ "url": "",
+ "title": "",
+ "artist": "",
+ "album": "",
+}
+
+
+def _page_loaded(window: Any, wait_s: float | None = None) -> bool:
+ """True when the window's page has finished loading (bounded wait)."""
+ if wait_s is None:
+ wait_s = _LOADED_WAIT_S
+ loaded = getattr(getattr(window, "events", None), "loaded", None)
+ if loaded is None:
+ return True # a backend without the event has no gate to wait on
+ try:
+ if loaded.is_set():
+ return True
+ return bool(loaded.wait(wait_s))
+ except Exception as exc: # noqa: BLE001 — an odd event object must not block a command
+ _log(f"loaded probe skipped: {exc}")
+ return True
+
+
+def _force_foreground(window: Any) -> None:
+ """Windows fallback: un-minimize and raise the player window by its title.
+
+ pywebview's ``restore``/``show`` normally do this; when they do not (the
+ window stayed iconic on 2026-08-22 while the parent reported it shown),
+ the Win32 calls are the ground truth. Capability-gated: a quiet no-op
+ anywhere ``ctypes.windll`` does not exist.
+ """
+ if sys.platform != "win32":
+ return
+ try:
+ import ctypes
+
+ user32 = ctypes.windll.user32 # type: ignore[attr-defined]
+ title = str(getattr(window, "title", "") or "")
+ if not title:
+ return
+ handle = user32.FindWindowW(None, title)
+ if not handle:
+ return
+ if user32.IsIconic(handle):
+ user32.ShowWindow(handle, 9) # SW_RESTORE
+ user32.SetForegroundWindow(handle)
+ except Exception as exc: # noqa: BLE001 — a foreground nudge is best-effort
+ _log(f"foreground nudge skipped: {exc}")
+
+
def _dispatch(window: Any, cmd: str, msg: dict[str, Any]) -> Any:
if cmd == "load":
window.load_url(str(msg.get("url") or "about:blank"))
@@ -154,6 +227,7 @@ def _dispatch(window: Any, cmd: str, msg: dict[str, Any]) -> Any:
except Exception as exc: # noqa: BLE001 — not every backend has restore
_log(f"restore skipped: {exc}")
window.show()
+ _force_foreground(window)
return True
if cmd == "hide":
# Minimize, never hide: WebView2 does not start media in a window that
@@ -167,11 +241,20 @@ def _dispatch(window: Any, cmd: str, msg: dict[str, Any]) -> Any:
window.hide()
return True
if cmd == "state":
+ if not _page_loaded(window):
+ # Answer NOW with "still loading" instead of sitting in pywebview's
+ # 20 s gate: the parent polls again, and the next command is not
+ # stuck behind this one.
+ return dict(_LOADING_STATE)
raw = window.evaluate_js(_STATE_JS)
return json.loads(raw) if isinstance(raw, str) else raw
if cmd == "volume":
+ if not _page_loaded(window):
+ raise RuntimeError("the player page is still loading")
return window.evaluate_js(_volume_js(int(msg.get("level") or 0)))
if cmd in _JS:
+ if not _page_loaded(window):
+ raise RuntimeError("the player page is still loading")
return window.evaluate_js(_JS[cmd])
if cmd == "quit":
return True
diff --git a/jarvis/plugins/tool/youtube_music_rest.py b/jarvis/plugins/tool/youtube_music_rest.py
index fcc6b09992..c94669eac5 100644
--- a/jarvis/plugins/tool/youtube_music_rest.py
+++ b/jarvis/plugins/tool/youtube_music_rest.py
@@ -37,6 +37,7 @@ from __future__ import annotations
import asyncio
import html
import logging
+import time
from collections.abc import Awaitable, Callable
from typing import Any
@@ -101,6 +102,13 @@ _PRESS_PLAY_NOTE = (
# know. A page load plus buffering takes four to five seconds (measured
# 2026-08-18: position starts advancing ~4.5 s after load).
_PLAYER_CONFIRM_TIMEOUT_S = 9.0
+#: Per-read bound while confirming playback in the background player. The
+#: host answers "loading" at once when the page is still turning, so a read
+#: that takes longer than this is a stuck host, not a slow page — give up on
+#: that read and poll again rather than inherit the 10 s transport default.
+_PLAYER_READ_TIMEOUT_S = 3.0
+#: Bound for bringing the player window forward at the end of a confirm.
+_PLAYER_SHOW_TIMEOUT_S = 5.0
# Music category on YouTube. Songs on YouTube Music are videos in it.
_MUSIC_CATEGORY_ID = "10"
@@ -128,6 +136,22 @@ def playlist_url(playlist_id: str, first_video_id: str | None = None) -> str:
return f"{_MUSIC}/watch?list={playlist_id}"
+def _call_with_timeout(fn: Callable[..., Any], timeout: float) -> Any:
+ """Call a player command with a per-call ``timeout`` when it accepts one.
+
+ The shipped :class:`jarvis.platform.music_player.MusicPlayer` takes
+ ``timeout=``; a custom or test player may not, and then the plain call is
+ the right one — the bound is a nicety, never a contract the caller breaks
+ on.
+ """
+ try:
+ return fn(timeout=timeout)
+ except TypeError as exc:
+ if "timeout" not in str(exc):
+ raise
+ return fn()
+
+
def _default_token_provider() -> str | None:
from jarvis.marketplace.token_store import TokenStore
@@ -445,19 +469,29 @@ class YouTubeMusicRestTool:
out: dict[str, Any] = {"ok": True, "url": url, "sink": "background_player"}
if started:
out["started"] = started
- elapsed = 0.0
+ # Wall-clock deadline, not a count of sleeps: live 2026-08-22 20:01:52
+ # every state read sat out its full 10 s in the host, the loop counted
+ # only its 0.5 s naps, and one play request took 199 s. Each read is
+ # also bounded tighter than the default so a busy host costs seconds,
+ # not the whole turn.
+ deadline = time.monotonic() + self._player_confirm_timeout_s
last: dict[str, Any] = {}
nudged = False
- while elapsed < self._player_confirm_timeout_s:
+ while time.monotonic() < deadline:
await asyncio.sleep(_CONFIRM_STEP_S)
- elapsed += _CONFIRM_STEP_S
try:
- last = await asyncio.to_thread(player.state)
+ last = await asyncio.to_thread(
+ _call_with_timeout, player.state, _PLAYER_READ_TIMEOUT_S
+ )
except Exception as exc: # noqa: BLE001 — a blink while the page turns
log.debug("background player state during confirm: %s", exc)
continue
+ if last.get("loading"):
+ continue
if last.get("consent"):
- await asyncio.to_thread(player.show)
+ await asyncio.to_thread(
+ _call_with_timeout, player.show, _PLAYER_SHOW_TIMEOUT_S
+ )
out.update(playback_confirmed=False, needs_attention="consent", note=_CONSENT_NOTE)
return out
playing = last.get("has_video") and last.get("paused") is False
@@ -473,7 +507,7 @@ class YouTubeMusicRestTool:
except Exception as exc: # noqa: BLE001 — the nudge is best-effort
log.debug("background player nudge failed: %s", exc)
try:
- await asyncio.to_thread(player.show)
+ await asyncio.to_thread(_call_with_timeout, player.show, _PLAYER_SHOW_TIMEOUT_S)
except Exception as exc: # noqa: BLE001 — showing is best-effort
log.debug("background player show failed: %s", exc)
out.update(playback_confirmed=False, needs_attention="press_play", note=_PRESS_PLAY_NOTE)
diff --git a/tests/unit/platform/test_music_player.py b/tests/unit/platform/test_music_player.py
index 9c0c70be47..36ffc39a78 100644
--- a/tests/unit/platform/test_music_player.py
+++ b/tests/unit/platform/test_music_player.py
@@ -161,6 +161,35 @@ def test_host_error_and_timeout_surface_as_music_player_error():
player.stop()
+def test_state_and_show_take_a_per_call_timeout():
+ """A confirm loop polls ``state``; it must be able to bound each read
+ instead of inheriting the 10 s transport default (live 2026-08-22: 18
+ reads × 10 s = one 199 s play request)."""
+ host = FakeHost()
+ player = _player(host)
+ assert player.state(timeout=0.5)["has_video"] is True
+ assert player.show(timeout=0.5) is True
+
+ class SilentOnState(FakeHost):
+ def _serve(self) -> None:
+ for raw in self.stdin:
+ msg = json.loads(raw)
+ if msg.get("cmd") == "state":
+ continue # never answers
+ self.stdout.write(json.dumps({"id": msg["id"], "ok": True, "result": True}) + "\n")
+
+ silent = SilentOnState()
+ player = _player(silent)
+ started = time.monotonic()
+ try:
+ player.state(timeout=0.3)
+ except MusicPlayerError as exc:
+ assert "did not answer" in str(exc)
+ else: # pragma: no cover — a silent host must surface as a timeout
+ raise AssertionError("state() returned although the host never answered")
+ assert time.monotonic() - started < 2.0
+
+
def test_unavailable_host_makes_the_player_unavailable_with_its_reason():
host = FakeHost(unavailable="WebViewException: no GTK")
player = _player(host)
diff --git a/tests/unit/platform/test_music_player_host.py b/tests/unit/platform/test_music_player_host.py
new file mode 100644
index 0000000000..0fe2bef968
--- /dev/null
+++ b/tests/unit/platform/test_music_player_host.py
@@ -0,0 +1,121 @@
+"""The player host answers at once while its page is still loading.
+
+pywebview gates ``evaluate_js`` on the window's ``loaded`` event and blocks up
+to 20 s when a navigation has not reported back. The host's command loop is
+sequential, so one blocked ``state`` read holds every later command — including
+the ``show`` that would bring the window forward — hostage. Live 2026-08-22
+20:01:52: the second ``load`` of a session left ``loaded`` clear; eighteen
+``state`` reads each sat out the parent's 10 s timeout, the ``show`` behind them
+did too, and one "play some music" took 199 s while the player window stayed
+minimized. The host now answers "loading" after a short bounded wait and the
+Windows fallback un-minimizes the window by its title when pywebview's own
+``restore``/``show`` leave it iconic.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from types import SimpleNamespace
+
+from jarvis.platform import music_player_host as host
+
+
+class _Events:
+ def __init__(self, loaded: bool) -> None:
+ self.loaded = threading.Event()
+ if loaded:
+ self.loaded.set()
+
+
+class FakeWindow:
+ def __init__(self, *, loaded: bool = True, title: str = "Music") -> None:
+ self.events = _Events(loaded)
+ self.title = title
+ self.evaluated: list[str] = []
+ self.loaded_urls: list[str] = []
+ self.restored = 0
+ self.shown = 0
+ self.minimized = 0
+
+ def evaluate_js(self, script: str) -> str:
+ self.evaluated.append(script)
+ return '{"has_video": true, "paused": false, "position": 3.0, "consent": false}'
+
+ def load_url(self, url: str) -> None:
+ self.loaded_urls.append(url)
+
+ def restore(self) -> None:
+ self.restored += 1
+
+ def show(self) -> None:
+ self.shown += 1
+
+ def minimize(self) -> None:
+ self.minimized += 1
+
+
+def test_state_answers_loading_at_once_instead_of_waiting_in_the_gate(monkeypatch):
+ monkeypatch.setattr(host, "_LOADED_WAIT_S", 0.05)
+ window = FakeWindow(loaded=False)
+
+ started = time.monotonic()
+ state = host._dispatch(window, "state", {})
+ elapsed = time.monotonic() - started
+
+ assert state["loading"] is True and state["ready"] is False
+ assert state["has_video"] is False and state["consent"] is False
+ assert window.evaluated == [] # never touched the gate
+ assert elapsed < 1.0
+
+
+def test_state_reads_the_page_once_it_has_loaded():
+ window = FakeWindow(loaded=True)
+ state = host._dispatch(window, "state", {})
+ assert state["has_video"] is True and "loading" not in state
+ assert len(window.evaluated) == 1
+
+
+def test_state_waits_briefly_for_a_load_that_finishes_in_time(monkeypatch):
+ monkeypatch.setattr(host, "_LOADED_WAIT_S", 2.0)
+ window = FakeWindow(loaded=False)
+ threading.Timer(0.1, window.events.loaded.set).start()
+
+ state = host._dispatch(window, "state", {})
+
+ assert "loading" not in state and state["has_video"] is True
+
+
+def test_page_commands_fail_fast_while_loading_instead_of_blocking(monkeypatch):
+ monkeypatch.setattr(host, "_LOADED_WAIT_S", 0.05)
+ window = FakeWindow(loaded=False)
+ for cmd in ("play", "pause", "next", "volume"):
+ try:
+ host._dispatch(window, cmd, {"level": 30})
+ except RuntimeError as exc:
+ assert "still loading" in str(exc)
+ else: # pragma: no cover — the guard must raise
+ raise AssertionError(f"{cmd} did not fail fast")
+ assert window.evaluated == []
+
+
+def test_show_restores_then_shows_and_nudges_the_foreground(monkeypatch):
+ window = FakeWindow()
+ nudged: list[str] = []
+ monkeypatch.setattr(host, "_force_foreground", lambda w: nudged.append(w.title))
+
+ assert host._dispatch(window, "show", {}) is True
+ assert window.restored == 1 and window.shown == 1
+ assert nudged == ["Music"]
+
+
+def test_force_foreground_is_a_quiet_no_op_off_windows(monkeypatch):
+ monkeypatch.setattr(host.sys, "platform", "linux")
+ host._force_foreground(SimpleNamespace(title="Music")) # must not raise
+
+
+def test_a_window_without_the_loaded_event_is_read_directly():
+ window = FakeWindow(loaded=True)
+ del window.events # a backend that exposes no events at all
+ state = host._dispatch(window, "state", {})
+ assert state["has_video"] is True
diff --git a/tests/unit/plugins/tool/test_youtube_music_rest.py b/tests/unit/plugins/tool/test_youtube_music_rest.py
index 20fbb75b80..905c51fb2c 100644
--- a/tests/unit/plugins/tool/test_youtube_music_rest.py
+++ b/tests/unit/plugins/tool/test_youtube_music_rest.py
@@ -571,6 +571,61 @@ async def test_play_nudges_then_shows_the_player_when_it_stays_paused():
assert player.shown == 1
+async def test_play_confirm_is_bounded_by_wall_clock_when_the_player_is_slow():
+ """Live 2026-08-22 20:01:52: every state read sat out its transport timeout,
+ the loop counted only its naps, and one play took 199 s. The loop now runs
+ on a wall-clock deadline, so a slow host costs the deadline, not its
+ multiple — and the window is still brought forward at the end."""
+ import time as _time
+
+ class SlowPlayer(FakePlayer):
+ def state(self, **_kw):
+ _time.sleep(0.4) # a busy host: every read is slow
+ return {"loading": True}
+
+ player = SlowPlayer([], running=True)
+ tool = _tool(_search_handler, player=player, playback="background")
+ tool._player_confirm_timeout_s = 1.0
+
+ started = _time.monotonic()
+ out = await tool.play(query="karma police")
+ elapsed = _time.monotonic() - started
+
+ assert elapsed < 3.0, f"confirm loop ran {elapsed:.1f}s for a 1.0s deadline"
+ assert out["playback_confirmed"] is False and out["needs_attention"] == "press_play"
+ assert player.shown == 1
+
+
+async def test_play_keeps_polling_while_the_host_says_loading():
+ """The host answers "loading" instead of blocking; the loop waits it out
+ and confirms from the first real page state."""
+ player = FakePlayer([{"loading": True}, {"loading": True}, _page(position=2.5)])
+ tool = _tool(_search_handler, player=player, playback="background")
+ out = await tool.play(query="karma police")
+ assert out["playback_confirmed"] is True
+
+
+async def test_play_passes_a_per_call_timeout_to_a_player_that_takes_one():
+ """The shipped MusicPlayer accepts ``timeout=``; the confirm loop uses it
+ so one stuck read costs seconds, not the 10 s transport default."""
+ seen: list[float] = []
+
+ class TimeoutAwarePlayer(FakePlayer):
+ def state(self, *, timeout: float | None = None):
+ seen.append(timeout)
+ return super().state()
+
+ def show(self, *, timeout: float | None = None):
+ seen.append(timeout)
+ return super().show()
+
+ player = TimeoutAwarePlayer([{"url": "https://consent.youtube.com/m?x", "consent": True}])
+ tool = _tool(_search_handler, player=player, playback="background")
+ out = await tool.play(query="karma police")
+ assert out["needs_attention"] == "consent"
+ assert seen and all(isinstance(t, float) and 0 < t <= 10 for t in seen)
+
+
async def test_play_falls_back_to_the_browser_when_the_player_cannot_run():
player = FakePlayer(available=(False, "no display here"))
opener = Opener()