The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: native-http profile scope follows audio and OAuth work onto worker threads
Teknium7e62d683a626
diff --git a/hermes_cli/web_routers/audio.py b/hermes_cli/web_routers/audio.pyindex f651b8a3bf8..90df06f39fe 100644--- a/hermes_cli/web_routers/audio.py+++ b/hermes_cli/web_routers/audio.py@@ -72,7 +72,10 @@ async def _run_config_scoped(profile: Optional[str], fn):with _config_profile_scope(profile):return fn()- return await asyncio.get_running_loop().run_in_executor(None, _scoped)+ # to_thread copies the request context: a secondary-profile native ticket's implicit+ # scope (native_profile_scope's home override) must reach the worker, which+ # run_in_executor drops, silently resolving the LAUNCH profile's config and keys.+ return await asyncio.to_thread(_scoped)def _audio_extension_for_mime(mime_type: str) -> str:@@ -246,13 +249,11 @@ async def get_elevenlabs_voices(profile: Optional[str] = None):)try:- loop = asyncio.get_running_loop()-def _fetch() -> Dict[str, Any]:with urllib.request.urlopen(request, timeout=10) as response:return _read_dashboard_json_response(response)- payload = await loop.run_in_executor(None, _fetch)+ payload = await asyncio.to_thread(_fetch)except urllib.error.HTTPError as exc:# An auth failure (bad/expired/scoped key) is a persistent, user-fixable# state and the desktop polls this on every settings open/focus, so@@ -375,7 +376,7 @@ async def tts_lease(payload: TTSLeaseRequest, profile: Optional[str] = None):return release_tts_lease(lease)try:- result = await asyncio.get_running_loop().run_in_executor(None, _apply)+ result = await asyncio.to_thread(_apply)except HTTPException:raiseexcept Exception as exc:@@ -503,7 +504,7 @@ async def stt_lease(payload: STTLeaseRequest, profile: Optional[str] = None):return release_stt_lease(lease)try:- result = await asyncio.get_running_loop().run_in_executor(None, _apply)+ result = await asyncio.to_thread(_apply)except HTTPException:raiseexcept Exception as exc:@@ -558,7 +559,7 @@ async def speak_stream_ws(ws: "WebSocket") -> None:return streamer, cap, cfgtry:- streamer, cap, cfg = await loop.run_in_executor(None, _resolve)+ streamer, cap, cfg = await asyncio.to_thread(_resolve)except Exception:_log.exception("speak-stream provider resolution failed")streamer, cap, cfg = None, 0, {}diff --git a/hermes_cli/web_routers/oauth.py b/hermes_cli/web_routers/oauth.pyindex 0434d7964b0..82414b9f713 100644--- a/hermes_cli/web_routers/oauth.py+++ b/hermes_cli/web_routers/oauth.py@@ -6,6 +6,7 @@ Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch oimport asyncioimport contextlib+import contextvarsimport loggingimport osimport secrets@@ -118,7 +119,11 @@ def _start_poller(target, sid: str, prefix: str = "oauth-poll") -> None:from hermes_cli.observability.shared_metrics_setup import settle_oauth_setupsettle_oauth_setup(sess)- threading.Thread(target=run, daemon=True, name=f"{prefix}-{sid[:6]}").start()+ # The poller saves credentials under ``_profile_scope(sess['profile'])``; an implicit+ # selector (None) must resolve in the REQUEST's home (a secondary-profile native ticket's+ # override), so the thread runs in a copy of the starting request's context.+ context = contextvars.copy_context()+ threading.Thread(target=context.run, args=(run,), daemon=True, name=f"{prefix}-{sid[:6]}").start()def _track_oauth_setup(flow, session_id: str) -> None:@@ -159,7 +164,7 @@ async def _httpx_call(fn: Callable[[Any], Any], timeout: float = 15.0, **client_) as client:return fn(client)- return await asyncio.get_running_loop().run_in_executor(None, _call)+ return await asyncio.to_thread(_call)# OpenAI Codex device-code worker. Codex's own deviceauth/usercode (returns@@ -826,7 +831,7 @@ async def start_oauth_login(provider_id: str, request: Request, profile: Optiona_log.exception("oauth/start %s failed", provider_id)raise HTTPException(status_code=500, detail=str(e))if flow is not None:- await asyncio.get_running_loop().run_in_executor(None, _track_oauth_setup, flow, body["session_id"])+ await asyncio.to_thread(_track_oauth_setup, flow, body["session_id"])return body@@ -839,7 +844,7 @@ async def _begin_oauth_setup_metric(provider_id: str, profile: Optional[str]):home = _resolve_profile_dir(profile_name) if profile_name else Noneif not collection_enabled(home):return None- return await asyncio.get_running_loop().run_in_executor(None, begin_oauth_setup, provider_id, home)+ return await asyncio.to_thread(begin_oauth_setup, provider_id, home)except Exception:return None@@ -853,7 +858,7 @@ async def _end_oauth_setup_metric(flow, exc: Exception) -> None:# provider not answering in time.status = exc.status_code if isinstance(exc, HTTPException) else Nonefailure = {401: "auth", 403: "auth", 504: "network"}.get(status) or setup_failure_class(exc)- await asyncio.get_running_loop().run_in_executor(None, finish_provider_setup, flow, "failed", failure)+ await asyncio.to_thread(finish_provider_setup, flow, "failed", failure)@router.post("/api/providers/oauth/{provider_id}/submit")@@ -911,5 +916,5 @@ async def cancel_oauth_session(session_id: str, request: Request, profile: Optioreturn {"ok": False, "message": "session not found"}# Recorded now, not when the poller next wakes: a Nous/xAI poll can block for the code's lifetime.from hermes_cli.observability.shared_metrics_setup import settle_oauth_setup- await asyncio.get_running_loop().run_in_executor(None, settle_oauth_setup, sess)+ await asyncio.to_thread(settle_oauth_setup, sess)return {"ok": True, "session_id": session_id}diff --git a/tests/hermes_cli/test_native_profile_scope_threads.py b/tests/hermes_cli/test_native_profile_scope_threads.pynew file mode 100644index 00000000000..9817a70cecc--- /dev/null+++ b/tests/hermes_cli/test_native_profile_scope_threads.py@@ -0,0 +1,45 @@+"""A secondary-profile native ticket's implicit scope must reach the audio worker thread."""+import asyncio++from hermes_constants import get_hermes_home, reset_hermes_home_override, set_hermes_home_override+++def test_config_scoped_worker_keeps_the_request_home_override(tmp_path):+ from hermes_cli.web_routers.audio import _run_config_scoped++ secondary = tmp_path / "profiles" / "secondary"+ secondary.mkdir(parents=True)++ async def run():+ # What native_profile_scope does for a ticket bound to a non-launch served profile.+ token = set_hermes_home_override(str(secondary))+ try:+ return await _run_config_scoped(None, get_hermes_home)+ finally:+ reset_hermes_home_override(token)++ assert asyncio.run(run()) == secondary+++def test_oauth_poller_thread_keeps_the_request_home_override(tmp_path):+ import threading++ from hermes_cli.web_routers import oauth++ secondary = tmp_path / "profiles" / "secondary"+ secondary.mkdir(parents=True)+ seen, done = {}, threading.Event()+ sid, _sess = oauth._new_oauth_session("fixture", "device_code", profile=None)++ def poller(_sid):+ seen["home"] = get_hermes_home()+ done.set()++ token = set_hermes_home_override(str(secondary))+ try:+ oauth._start_poller(poller, sid)+ finally:+ reset_hermes_home_override(token)+ assert done.wait(5)+ oauth._drop_oauth_session(sid)+ assert seen["home"] == secondary