The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): move _profile_scope and config I/O off the event loop in async handlers
Royalaid52c9aee3bfde
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex 5cbeff3b32a..1bfcaa36eda 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -2318,36 +2318,42 @@ async def upload_chat_image(payload: ChatImageUpload, profile: Optional[str] = N``HERMES_HOME/images/`` — the same directory ``clipboard.paste`` /``image.attach`` already use."""- data, mime_type, ext = _decode_chat_image_upload(payload)- with _profile_scope(profile) as scoped_home:- home = scoped_home or get_hermes_home()- img_dir = Path(home) / "images"- try:- img_dir.mkdir(parents=True, exist_ok=True)- except PermissionError:- raise HTTPException(status_code=403, detail="Image directory is not writable")- except OSError as exc:- raise HTTPException(status_code=500, detail=f"Could not create image directory: {exc}")+ def _run():+ data, mime_type, ext = _decode_chat_image_upload(payload)+ with _profile_scope(profile) as scoped_home:+ home = scoped_home or get_hermes_home()+ img_dir = Path(home) / "images"+ try:+ img_dir.mkdir(parents=True, exist_ok=True)+ except PermissionError:+ raise HTTPException(status_code=403, detail="Image directory is not writable")+ except OSError as exc:+ raise HTTPException(status_code=500, detail=f"Could not create image directory: {exc}")- stem = Path(_sanitize_chat_image_filename(payload.filename)).stem or "pasted-image"- stem = re.sub(r"[^A-Za-z0-9_.-]+", "_", stem).strip("._-") or "pasted-image"- ts = datetime.now().strftime("%Y%m%d_%H%M%S")- target = img_dir / f"dashboard_{ts}_{secrets.token_hex(4)}_{stem}{ext}"+ stem = Path(_sanitize_chat_image_filename(payload.filename)).stem or "pasted-image"+ stem = re.sub(r"[^A-Za-z0-9_.-]+", "_", stem).strip("._-") or "pasted-image"+ ts = datetime.now().strftime("%Y%m%d_%H%M%S")+ target = img_dir / f"dashboard_{ts}_{secrets.token_hex(4)}_{stem}{ext}"- try:- target.write_bytes(data)- except PermissionError:- raise HTTPException(status_code=403, detail="Image directory is not writable")- except OSError as exc:- raise HTTPException(status_code=500, detail=f"Could not write image: {exc}")+ try:+ target.write_bytes(data)+ except PermissionError:+ raise HTTPException(status_code=403, detail="Image directory is not writable")+ except OSError as exc:+ raise HTTPException(status_code=500, detail=f"Could not write image: {exc}")- return {- "ok": True,- "path": str(target),- "name": target.name,- "bytes": len(data),- "mime_type": mime_type,- }+ return {+ "ok": True,+ "path": str(target),+ "name": target.name,+ "bytes": len(data),+ "mime_type": mime_type,+ }++ # _profile_scope acquires _SKILLS_PROFILE_LOCK and the body does file I/O —+ # keep both off the event loop (asyncio.to_thread copies the contextvar+ # context, so the profile override stays scoped to the worker thread).+ return await asyncio.to_thread(_run)@app.get("/api/files")@@ -3535,11 +3541,16 @@ async def get_learning_graph(profile: Optional[str] = None):Profile-scoped view of learned, non-base skills plus memory chunks, withgraph links derived from skill relations and memory-skill overlap."""- try:+ def _run():from agent.learning_graph import build_learning_graphwith _profile_scope(profile):return build_learning_graph()++ try:+ # _profile_scope takes _SKILLS_PROFILE_LOCK and the graph build reads+ # skills/memories from disk — keep it off the event loop.+ return await asyncio.to_thread(_run)except Exception:_log.exception("GET /api/learning/graph failed")raise HTTPException(status_code=500, detail="Failed to build learning graph")@@ -3550,8 +3561,11 @@ async def get_learning_node(id: str, profile: Optional[str] = None):"""Current content of a journey node (skill SKILL.md or memory chunk), for an edit prefill."""from agent.learning_mutations import node_detail- with _profile_scope(profile):- res = node_detail(id)+ def _run():+ with _profile_scope(profile):+ return node_detail(id)++ res = await asyncio.to_thread(_run)if not res.get("ok"):raise HTTPException(status_code=404, detail=res.get("message", "not found"))return res@@ -3562,8 +3576,11 @@ async def delete_learning_node(body: LearningNodeRef):"""Delete a journey node — skills are archived (restorable), memories removed."""from agent.learning_mutations import delete_node- with _profile_scope(body.profile):- res = delete_node(body.id)+ def _run():+ with _profile_scope(body.profile):+ return delete_node(body.id)++ res = await asyncio.to_thread(_run)if not res.get("ok"):raise HTTPException(status_code=400, detail=res.get("message", "delete failed"))return res@@ -3574,8 +3591,11 @@ async def update_learning_node(body: LearningNodeEdit):"""Rewrite a journey node's content (SKILL.md or memory chunk)."""from agent.learning_mutations import edit_node- with _profile_scope(body.profile):- res = edit_node(body.id, body.content)+ def _run():+ with _profile_scope(body.profile):+ return edit_node(body.id, body.content)++ res = await asyncio.to_thread(_run)if not res.get("ok"):raise HTTPException(status_code=400, detail=res.get("message", "edit failed"))return res@@ -3596,6 +3616,15 @@ def _safe_call(mod, fn_name: str, default):@app.get("/api/portal")async def get_portal_status():+ # load_config() + auth/subscription snapshots are disk reads — this is a+ # polled endpoint, so keep them off the event loop.+ def _run():+ return _get_portal_status_sync()++ return await asyncio.to_thread(_run)+++def _get_portal_status_sync():cfg = load_config() or {}auth: Dict[str, Any] = {}try:@@ -6127,8 +6156,16 @@ async def update_memory_provider_config(@app.get("/api/config")async def get_config(profile: Optional[str] = None):- with _profile_scope(profile):- config = _normalize_config_for_web(load_config())+ # _profile_scope blocks on the process-wide _SKILLS_PROFILE_LOCK and+ # load_config() reads from disk; on the event loop a slow lock-holder+ # froze the whole gateway for >1s (observed via the loop watchdog).+ # asyncio.to_thread copies the contextvar context, so the profile+ # override stays scoped to the worker thread.+ def _run():+ with _profile_scope(profile):+ return _normalize_config_for_web(load_config())++ config = await asyncio.to_thread(_run)# Strip internal keys that the frontend shouldn't see or send backreturn {k: v for k, v in config.items() if not k.startswith("_")}@@ -6914,7 +6951,7 @@ def _denormalize_config_from_web(config: Dict[str, Any]) -> Dict[str, Any]:@app.put("/api/config")async def update_config(body: ConfigUpdate, profile: Optional[str] = None):- try:+ def _run():with _profile_scope(body.profile or profile):# The dashboard form is schema-driven (see CONFIG_SCHEMA). Any root# key absent from the schema — most visibly ``custom_providers``, but@@ -6926,6 +6963,9 @@ async def update_config(body: ConfigUpdate, profile: Optional[str] = None):incoming = _denormalize_config_from_web(body.config)save_config(_deep_merge(existing, incoming))return {"ok": True}++ try:+ return await asyncio.to_thread(_run)except HTTPException:raiseexcept Exception:@@ -7042,6 +7082,12 @@ def _catalog_provider_env_metadata() -> dict:@app.get("/api/env")async def get_env_vars(profile: Optional[str] = None):+ # _profile_scope takes _SKILLS_PROFILE_LOCK and load_env()/catalog+ # discovery read from disk — keep the whole build off the event loop.+ return await asyncio.to_thread(_get_env_vars_sync, profile)+++def _get_env_vars_sync(profile: Optional[str] = None):with _profile_scope(profile):env_on_disk = load_env()channel_keys = _channel_managed_env_keys()@@ -7105,7 +7151,7 @@ async def get_env_vars(profile: Optional[str] = None):@app.put("/api/env")async def set_env_var(body: EnvVarUpdate, profile: Optional[str] = None):- try:+ def _run():with _profile_scope(body.profile or profile):# Unified credential lifecycle: writes .env AND reconciles any# config.yaml mirror still holding the previous value of this var@@ -7114,8 +7160,10 @@ async def set_env_var(body: EnvVarUpdate, profile: Optional[str] = None):# keeps authenticating with the old key (#62269).from hermes_cli.credential_lifecycle import save_provider_env_credential- result = save_provider_env_credential(body.key, body.value)- return result+ return save_provider_env_credential(body.key, body.value)++ try:+ return await asyncio.to_thread(_run)except ValueError as exc:# save_env_value raises ValueError for invalid names and for keys# on the denylist (LD_PRELOAD, PATH, PYTHONPATH, …). Surface the@@ -7572,7 +7620,7 @@ async def validate_provider_credential(body: EnvVarUpdate, request: Request):@app.delete("/api/env")async def remove_env_var(body: EnvVarDelete, profile: Optional[str] = None):- try:+ def _run():with _profile_scope(body.profile or profile):# Unified credential lifecycle: clears the .env entry AND every# mirror of the credential — env-seeded credential_pool entries in@@ -7582,7 +7630,10 @@ async def remove_env_var(body: EnvVarDelete, profile: Optional[str] = None):# manual pool entries for the same provider are preserved.from hermes_cli.credential_lifecycle import remove_provider_env_credential- result = remove_provider_env_credential(body.key)+ return remove_provider_env_credential(body.key)++ try:+ result = await asyncio.to_thread(_run)if not result.get("found"):raise HTTPException(status_code=404, detail=f"{body.key} not found in .env")return result@@ -7621,8 +7672,11 @@ async def reveal_env_var(_reveal_timestamps.append(now)# --- Reveal ---- with _profile_scope(body.profile or profile):- env_on_disk = load_env()+ def _run():+ with _profile_scope(body.profile or profile):+ return load_env()++ env_on_disk = await asyncio.to_thread(_run)value = env_on_disk.get(body.key)if value is None:raise HTTPException(status_code=404, detail=f"{body.key} not found in .env")@@ -9258,11 +9312,15 @@ async def apply_telegram_onboarding()effective_profile = body.profile or profile- try:++ def _apply():with _profile_scope(effective_profile):save_env_value("TELEGRAM_BOT_TOKEN", bot_token)save_env_value("TELEGRAM_ALLOWED_USERS", ",".join(allowed_user_ids))_write_platform_enabled("telegram", True)++ try:+ await asyncio.to_thread(_apply)except HTTPException:raiseexcept ValueError as exc:@@ -9302,27 +9360,30 @@ async def get_messaging_platforms(profile: Optional[str] = None):# load_env() honors the HERMES_HOME contextvar override; the gateway# status readers do NOT (they resolve process-level paths), so the# profile directory is passed explicitly for those (#71211).- with _profile_scope(profile) as scoped_dir:- env_on_disk = load_env()- runtime = (- read_runtime_status(path=scoped_dir / "gateway_state.json")- if scoped_dir is not None- else read_runtime_status()- )- return {- "env_path": str(get_env_path()),- "gateway_start_command": _gateway_display_command(profile, "start"),- "platforms": [- _messaging_platform_payload(- entry,- env_on_disk,- runtime,- scoped=scoped_dir is not None,- profile_home=scoped_dir,- )- for entry in _messaging_platform_catalog()- ]- }+ def _run():+ with _profile_scope(profile) as scoped_dir:+ env_on_disk = load_env()+ runtime = (+ read_runtime_status(path=scoped_dir / "gateway_state.json")+ if scoped_dir is not None+ else read_runtime_status()+ )+ return {+ "env_path": str(get_env_path()),+ "gateway_start_command": _gateway_display_command(profile, "start"),+ "platforms": [+ _messaging_platform_payload(+ entry,+ env_on_disk,+ runtime,+ scoped=scoped_dir is not None,+ profile_home=scoped_dir,+ )+ for entry in _messaging_platform_catalog()+ ]+ }++ return await asyncio.to_thread(_run)def _multiplex_port_binding_conflict(@@ -9401,7 +9462,8 @@ async def update_messaging_platform(raise HTTPException(status_code=409, detail=conflict)allowed_env = set(entry["env_vars"])- try:++ def _apply():with _profile_scope(body.profile or profile):for key in body.clear_env:if key not in allowed_env:@@ -9425,6 +9487,9 @@ async def update_messaging_platform(if body.enabled is not None:_write_platform_enabled(platform_id, body.enabled)+ try:+ await asyncio.to_thread(_apply)+# Audit trail for channel config mutations: names only, never values._log.info("Messaging platform updated: platform=%s profile=%s enabled=%s "@@ -9451,20 +9516,23 @@ async def test_messaging_platform(platform_id: str, profile: Optional[str] = Nonstatus_code=404, detail=f"Unknown messaging platform: {platform_id}")- with _profile_scope(profile) as scoped_dir:- env_on_disk = load_env()- runtime = (- read_runtime_status(path=scoped_dir / "gateway_state.json")- if scoped_dir is not None- else read_runtime_status()- )- payload = _messaging_platform_payload(- entry,- env_on_disk,- runtime,- scoped=scoped_dir is not None,- profile_home=scoped_dir,- )+ def _run():+ with _profile_scope(profile) as scoped_dir:+ env_on_disk = load_env()+ runtime = (+ read_runtime_status(path=scoped_dir / "gateway_state.json")+ if scoped_dir is not None+ else read_runtime_status()+ )+ return _messaging_platform_payload(+ entry,+ env_on_disk,+ runtime,+ scoped=scoped_dir is not None,+ profile_home=scoped_dir,+ )++ payload = await asyncio.to_thread(_run)if not payload["enabled"]:message = f"{entry['name']} is disabled. Enable it, then restart the gateway."return {"ok": False, "state": payload["state"], "message": message}@@ -9957,23 +10025,26 @@ async def list_oauth_providers(profile: Optional[str] = None):sync with the `hermes model` picker; _OAUTH_OVERRIDES supplies per-providerflow/status/cli metadata."""- with _profile_scope(profile):- providers = []- for p in _build_oauth_catalog():- status = _resolve_provider_status(p["id"], p.get("status_fn"))- disconnect_hint = _oauth_provider_disconnect_hint(p, status)- providers.append({- "id": p["id"],- "name": p["name"],- "flow": p["flow"],- "cli_command": p["cli_command"],- "docs_url": p["docs_url"],- "disconnect_hint": disconnect_hint,- "disconnect_command": _oauth_provider_disconnect_command(p),- "disconnectable": disconnect_hint is None,- "status": status,- })- return {"providers": providers}+ def _run():+ with _profile_scope(profile):+ providers = []+ for p in _build_oauth_catalog():+ status = _resolve_provider_status(p["id"], p.get("status_fn"))+ disconnect_hint = _oauth_provider_disconnect_hint(p, status)+ providers.append({+ "id": p["id"],+ "name": p["name"],+ "flow": p["flow"],+ "cli_command": p["cli_command"],+ "docs_url": p["docs_url"],+ "disconnect_hint": disconnect_hint,+ "disconnect_command": _oauth_provider_disconnect_command(p),+ "disconnectable": disconnect_hint is None,+ "status": status,+ })+ return {"providers": providers}++ return await asyncio.to_thread(_run)@app.delete("/api/providers/oauth/{provider_id}")@@ -9985,63 +10056,66 @@ async def disconnect_oauth_provider("""Disconnect an OAuth provider. Token-protected (matches /env/reveal)."""_require_token(request)- with _profile_scope(profile):- catalog_by_id = {p["id"]: p for p in _build_oauth_catalog()}- provider = catalog_by_id.get(provider_id)- if provider is None:- raise HTTPException(- status_code=400,- detail=f"Unknown provider: {provider_id}. "- f"Available: {', '.join(sorted(catalog_by_id))}",- )+ def _run():+ with _profile_scope(profile):+ catalog_by_id = {p["id"]: p for p in _build_oauth_catalog()}+ provider = catalog_by_id.get(provider_id)+ if provider is None:+ raise HTTPException(+ status_code=400,+ detail=f"Unknown provider: {provider_id}. "+ f"Available: {', '.join(sorted(catalog_by_id))}",+ )- disconnect_hint = _oauth_provider_disconnect_hint(provider, {})- if disconnect_hint:- raise HTTPException(- status_code=400,- detail=f"{provider['name']} cannot be disconnected automatically. {disconnect_hint}",- )+ disconnect_hint = _oauth_provider_disconnect_hint(provider, {})+ if disconnect_hint:+ raise HTTPException(+ status_code=400,+ detail=f"{provider['name']} cannot be disconnected automatically. {disconnect_hint}",+ )- status = _resolve_provider_status(provider_id, provider.get("status_fn"))- disconnect_hint = _oauth_provider_disconnect_hint(provider, status)- if disconnect_hint:- raise HTTPException(- status_code=400,- detail=f"{provider['name']} cannot be disconnected automatically. {disconnect_hint}",- )+ status = _resolve_provider_status(provider_id, provider.get("status_fn"))+ disconnect_hint = _oauth_provider_disconnect_hint(provider, status)+ if disconnect_hint:+ raise HTTPException(+ status_code=400,+ detail=f"{provider['name']} cannot be disconnected automatically. {disconnect_hint}",+ )++ # Anthropic clears only the Hermes-managed PKCE file and auth-store entry.+ # The separate claude-code catalog row is external/read-only and rejected+ # above so we never pretend to remove ~/.claude/* credentials owned by the CLI.+ if provider_id == "anthropic":+ cleared = False+ try:+ from agent.anthropic_adapter import _get_hermes_oauth_file+ oauth_file = _get_hermes_oauth_file()+ if oauth_file.exists():+ oauth_file.unlink()+ cleared = True+ except Exception:+ pass+ # Also clear the credential pool entry if present.+ try:+ from hermes_cli.auth import clear_provider_auth+ cleared = clear_provider_auth("anthropic") or cleared+ except Exception:+ pass+ _log.info("oauth/disconnect: %s", provider_id)+ return {"ok": bool(cleared), "provider": provider_id}- # Anthropic clears only the Hermes-managed PKCE file and auth-store entry.- # The separate claude-code catalog row is external/read-only and rejected- # above so we never pretend to remove ~/.claude/* credentials owned by the CLI.- if provider_id == "anthropic":- cleared = False- try:- from agent.anthropic_adapter import _get_hermes_oauth_file- oauth_file = _get_hermes_oauth_file()- if oauth_file.exists():- oauth_file.unlink()- cleared = True- except Exception:- pass- # Also clear the credential pool entry if present.try:- from hermes_cli.auth import clear_provider_auth- cleared = clear_provider_auth("anthropic") or cleared- except Exception:- pass- _log.info("oauth/disconnect: %s", provider_id)- return {"ok": bool(cleared), "provider": provider_id}+ from hermes_cli.auth import clear_provider_auth, invalidate_nous_auth_status_cache+ cleared = clear_provider_auth(provider_id)+ if provider_id == "nous":+ invalidate_nous_auth_status_cache()+ _log.info("oauth/disconnect: %s (cleared=%s)", provider_id, cleared)+ return {"ok": bool(cleared), "provider": provider_id}+ except Exception as e:+ _log.exception("disconnect %s failed", provider_id)+ raise HTTPException(status_code=500, detail=str(e))- try:- from hermes_cli.auth import clear_provider_auth, invalidate_nous_auth_status_cache- cleared = clear_provider_auth(provider_id)- if provider_id == "nous":- invalidate_nous_auth_status_cache()- _log.info("oauth/disconnect: %s (cleared=%s)", provider_id, cleared)- return {"ok": bool(cleared), "provider": provider_id}- except Exception as e:- _log.exception("disconnect %s failed", provider_id)- raise HTTPException(status_code=500, detail=str(e))+ return await asyncio.to_thread(_run)# ---------------------------------------------------------------------------@@ -12818,38 +12892,46 @@ async def remove_credential_pool_entry(provider: str, index: int):@app.get("/api/memory")async def get_memory_status():- cfg = load_config()- active = ""- mem = cfg.get("memory")- if isinstance(mem, dict):- active = _normalize_memory_provider_name(mem.get("provider"))+ # load_config(), file stats and provider discovery are disk reads — keep+ # them off the event loop.+ def _run():+ cfg = load_config()+ active = ""+ mem = cfg.get("memory")+ if isinstance(mem, dict):+ active = _normalize_memory_provider_name(mem.get("provider"))++ # Built-in memory file sizes (so the UI can show what a reset would erase).+ mem_dir = get_hermes_home() / "memories"+ files = {}+ for fname, key in (("MEMORY.md", "memory"), ("USER.md", "user")):+ path = mem_dir / fname+ files[key] = path.stat().st_size if path.exists() else 0- # Built-in memory file sizes (so the UI can show what a reset would erase).- mem_dir = get_hermes_home() / "memories"- files = {}- for fname, key in (("MEMORY.md", "memory"), ("USER.md", "user")):- path = mem_dir / fname- files[key] = path.stat().st_size if path.exists() else 0+ return {+ "active": active,+ "providers": _discover_memory_provider_statuses(),+ "builtin_files": files,+ }- return {- "active": active,- "providers": _discover_memory_provider_statuses(),- "builtin_files": files,- }+ return await asyncio.to_thread(_run)@app.put("/api/memory/provider")async def set_memory_provider(body: MemoryProviderSelect):provider = _normalize_memory_provider_name(body.provider)- _require_memory_provider_ready(provider)+ def _run():+ _require_memory_provider_ready(provider)- cfg = load_config()- if not isinstance(cfg.get("memory"), dict):- cfg["memory"] = {}- cfg["memory"]["provider"] = provider- save_config(cfg)- return {"ok": True, "active": provider}+ cfg = load_config()+ if not isinstance(cfg.get("memory"), dict):+ cfg["memory"] = {}+ cfg["memory"]["provider"] = provider+ save_config(cfg)+ return {"ok": True, "active": provider}++ return await asyncio.to_thread(_run)@app.post("/api/memory/reset")@@ -13083,44 +13165,47 @@ async def list_hooks():currently executable, plus the set of valid hook events so the createform can offer them."""- from hermes_cli.config import load_config as _load_config- from agent import shell_hooks-- try:- from hermes_cli.plugins import VALID_HOOKS- valid_events = sorted(VALID_HOOKS)- except Exception:- valid_events = []-- specs = []- try:- specs = shell_hooks.iter_configured_hooks(_load_config())- except Exception:- _log.exception("iter_configured_hooks failed")+ def _run():+ from hermes_cli.config import load_config as _load_config+ from agent import shell_hooks- out = []- for spec in specs:- entry = Nonetry:- entry = shell_hooks.allowlist_entry_for(spec.event, spec.command)+ from hermes_cli.plugins import VALID_HOOKS+ valid_events = sorted(VALID_HOOKS)except Exception:- pass- executable = False+ valid_events = []++ specs = []try:- executable = shell_hooks.script_is_executable(spec.command)+ specs = shell_hooks.iter_configured_hooks(_load_config())except Exception:- pass- out.append({- "event": spec.event,- "matcher": spec.matcher,- "command": spec.command,- "timeout": spec.timeout,- "allowed": entry is not None,- "approved_at": (entry or {}).get("approved_at"),- "executable": executable,- })+ _log.exception("iter_configured_hooks failed")- return {"hooks": out, "valid_events": valid_events}+ out = []+ for spec in specs:+ entry = None+ try:+ entry = shell_hooks.allowlist_entry_for(spec.event, spec.command)+ except Exception:+ pass+ executable = False+ try:+ executable = shell_hooks.script_is_executable(spec.command)+ except Exception:+ pass+ out.append({+ "event": spec.event,+ "matcher": spec.matcher,+ "command": spec.command,+ "timeout": spec.timeout,+ "allowed": entry is not None,+ "approved_at": (entry or {}).get("approved_at"),+ "executable": executable,+ })++ return {"hooks": out, "valid_events": valid_events}++ return await asyncio.to_thread(_run)@app.post("/api/ops/hooks")@@ -13151,33 +13236,36 @@ async def create_hook(body: HookCreate):except Exception:pass- cfg = load_config()- hooks_cfg = cfg.get("hooks")- if not isinstance(hooks_cfg, dict):- hooks_cfg = {}- cfg["hooks"] = hooks_cfg- entries = hooks_cfg.get(event)- if not isinstance(entries, list):- entries = []- hooks_cfg[event] = entries-- new_entry: Dict[str, Any] = {"command": command}- if body.matcher:- new_entry["matcher"] = body.matcher- if body.timeout is not None:- new_entry["timeout"] = int(body.timeout)- entries.append(new_entry)- save_config(cfg)+ def _run():+ cfg = load_config()+ hooks_cfg = cfg.get("hooks")+ if not isinstance(hooks_cfg, dict):+ hooks_cfg = {}+ cfg["hooks"] = hooks_cfg+ entries = hooks_cfg.get(event)+ if not isinstance(entries, list):+ entries = []+ hooks_cfg[event] = entries++ new_entry: Dict[str, Any] = {"command": command}+ if body.matcher:+ new_entry["matcher"] = body.matcher+ if body.timeout is not None:+ new_entry["timeout"] = int(body.timeout)+ entries.append(new_entry)+ save_config(cfg)- approved = False- if body.approve:- try:- shell_hooks._record_approval(event, command)- approved = True- except Exception:- _log.exception("hook consent record failed")+ approved = False+ if body.approve:+ try:+ shell_hooks._record_approval(event, command)+ approved = True+ except Exception:+ _log.exception("hook consent record failed")- return {"ok": True, "event": event, "command": command, "approved": approved}+ return {"ok": True, "event": event, "command": command, "approved": approved}++ return await asyncio.to_thread(_run)@app.delete("/api/ops/hooks")@@ -13190,27 +13278,31 @@ async def delete_hook(body: HookDelete):if not event or not command:raise HTTPException(status_code=400, detail="event and command are required")- cfg = load_config()- hooks_cfg = cfg.get("hooks")- removed = False- if isinstance(hooks_cfg, dict) and isinstance(hooks_cfg.get(event), list):- before = len(hooks_cfg[event])- hooks_cfg[event] = [- e for e in hooks_cfg[event]- if not (isinstance(e, dict) and e.get("command") == command)- ]- removed = len(hooks_cfg[event]) < before- if not hooks_cfg[event]:- del hooks_cfg[event]- if not hooks_cfg:- cfg.pop("hooks", None)- save_config(cfg)+ def _run():+ cfg = load_config()+ hooks_cfg = cfg.get("hooks")+ removed = False+ if isinstance(hooks_cfg, dict) and isinstance(hooks_cfg.get(event), list):+ before = len(hooks_cfg[event])+ hooks_cfg[event] = [+ e for e in hooks_cfg[event]+ if not (isinstance(e, dict) and e.get("command") == command)+ ]+ removed = len(hooks_cfg[event]) < before+ if not hooks_cfg[event]:+ del hooks_cfg[event]+ if not hooks_cfg:+ cfg.pop("hooks", None)+ save_config(cfg)- # Revoke consent regardless so a re-add re-prompts.- try:- shell_hooks.revoke(command)- except Exception:- pass+ # Revoke consent regardless so a re-add re-prompts.+ try:+ shell_hooks.revoke(command)+ except Exception:+ pass+ return removed++ removed = await asyncio.to_thread(_run)if not removed:raise HTTPException(status_code=404, detail="No matching hook found")@@ -14063,16 +14155,19 @@ async def get_config_raw(profile: Optional[str] = None):``config_path`` is machine-global and always reports the dashboardprocess's own profile, which is wrong under the global profile switcher."""- with _profile_scope(profile):- path = get_config_path()- if not path.exists():- return {"yaml": "", "path": str(path)}- return {"yaml": path.read_text(encoding="utf-8"), "path": str(path)}+ def _run():+ with _profile_scope(profile):+ path = get_config_path()+ if not path.exists():+ return {"yaml": "", "path": str(path)}+ return {"yaml": path.read_text(encoding="utf-8"), "path": str(path)}++ return await asyncio.to_thread(_run)@app.put("/api/config/raw")async def update_config_raw(body: RawConfigUpdate, profile: Optional[str] = None):- try:+ def _run():parsed = yaml.safe_load(body.yaml_text)if not isinstance(parsed, dict):raise HTTPException(status_code=400, detail="YAML must be a mapping")@@ -14081,6 +14176,9 @@ async def update_config_raw(body: RawConfigUpdate, profile: Optional[str] = None# merge omitted sections back from disk (#62723).save_config(parsed, merge_existing=False)return {"ok": True}++ try:+ return await asyncio.to_thread(_run)except yaml.YAMLError as e:raise HTTPException(status_code=400, detail=f"Invalid YAML: {e}")@@ -16557,36 +16655,42 @@ async def get_dashboard_themes():normalised definition under `definition`, so the client can applythem without a stub."""- config = load_config()- active = cfg_get(config, "dashboard", "theme", default="default")- user_themes = _discover_user_themes()- seen = set()- themes = []- for t in _BUILTIN_DASHBOARD_THEMES:- seen.add(t["name"])- themes.append(t)- for t in user_themes:- if t["name"] in seen:- continue- themes.append({- "name": t["name"],- "label": t["label"],- "description": t["description"],- "definition": t,- })- seen.add(t["name"])- return {"themes": themes, "active": active}+ def _run():+ config = load_config()+ active = cfg_get(config, "dashboard", "theme", default="default")+ user_themes = _discover_user_themes()+ seen = set()+ themes = []+ for t in _BUILTIN_DASHBOARD_THEMES:+ seen.add(t["name"])+ themes.append(t)+ for t in user_themes:+ if t["name"] in seen:+ continue+ themes.append({+ "name": t["name"],+ "label": t["label"],+ "description": t["description"],+ "definition": t,+ })+ seen.add(t["name"])+ return {"themes": themes, "active": active}++ return await asyncio.to_thread(_run)@app.put("/api/dashboard/theme")async def set_dashboard_theme(body: ThemeSetBody):"""Set the active dashboard theme (persists to config.yaml)."""- config = load_config()- if "dashboard" not in config:- config["dashboard"] = {}- config["dashboard"]["theme"] = body.name- save_config(config)- return {"ok": True, "theme": body.name}+ def _run():+ config = load_config()+ if "dashboard" not in config:+ config["dashboard"] = {}+ config["dashboard"]["theme"] = body.name+ save_config(config)+ return {"ok": True, "theme": body.name}++ return await asyncio.to_thread(_run)# Curated font-override ids. Kept in sync with FONT_CHOICES in@@ -16606,11 +16710,14 @@ _FONT_CHOICES = frozenset({@app.get("/api/dashboard/font")async def get_dashboard_font():"""Return the active font override (``"theme"`` = use the theme's font)."""- config = load_config()- font = cfg_get(config, "dashboard", "font", default=_FONT_DEFAULT_ID)- if font not in _FONT_CHOICES:- font = _FONT_DEFAULT_ID- return {"font": font}+ def _run():+ config = load_config()+ font = cfg_get(config, "dashboard", "font", default=_FONT_DEFAULT_ID)+ if font not in _FONT_CHOICES:+ font = _FONT_DEFAULT_ID+ return {"font": font}++ return await asyncio.to_thread(_run)@app.put("/api/dashboard/font")@@ -16623,12 +16730,16 @@ async def set_dashboard_font(body: FontSetBody):the picker."""font = body.font if body.font in _FONT_CHOICES else _FONT_DEFAULT_ID- config = load_config()- if "dashboard" not in config:- config["dashboard"] = {}- config["dashboard"]["font"] = font- save_config(config)- return {"ok": True, "font": font}++ def _run():+ config = load_config()+ if "dashboard" not in config:+ config["dashboard"] = {}+ config["dashboard"]["font"] = font+ save_config(config)+ return {"ok": True, "font": font}++ return await asyncio.to_thread(_run)# ---------------------------------------------------------------------------@@ -16797,20 +16908,24 @@ def _get_dashboard_plugins(force_rescan: bool = False) -> list:@app.get("/api/dashboard/plugins")async def get_dashboard_plugins():"""Return discovered dashboard plugins (excludes user-hidden and non-enabled ones)."""- plugins = _get_dashboard_plugins()- # Read user's hidden plugins list from config.- config = load_config()- hidden: list = cfg_get(config, "dashboard", "hidden_plugins", default=[]) or []- # Gate: only serve user plugins that are in plugins.enabled and not- # in plugins.disabled. This prevents the frontend from loading JS/CSS- # from plugins the user has not explicitly activated. (#46435)- try:- from hermes_cli.plugins_cmd import _get_enabled_set, _get_disabled_set- enabled_set = _get_enabled_set()- disabled_set = _get_disabled_set()- except Exception:- enabled_set = set()- disabled_set = set()+ def _run():+ plugins = _get_dashboard_plugins()+ # Read user's hidden plugins list from config.+ config = load_config()+ hidden: list = cfg_get(config, "dashboard", "hidden_plugins", default=[]) or []+ # Gate: only serve user plugins that are in plugins.enabled and not+ # in plugins.disabled. This prevents the frontend from loading JS/CSS+ # from plugins the user has not explicitly activated. (#46435)+ try:+ from hermes_cli.plugins_cmd import _get_enabled_set, _get_disabled_set+ enabled_set = _get_enabled_set()+ disabled_set = _get_disabled_set()+ except Exception:+ enabled_set = set()+ disabled_set = set()+ return plugins, hidden, enabled_set, disabled_set++ plugins, hidden, enabled_set, disabled_set = await asyncio.to_thread(_run)def _is_active(p: dict) -> bool:name = p.get("name", "")@@ -17172,22 +17287,25 @@ async def post_plugin_visibility(request: Request, name: str, body: _PluginVisib_require_token(request)name = _validate_plugin_name(name)- config = load_config()- if "dashboard" not in config or not isinstance(config.get("dashboard"), dict):- config["dashboard"] = {}- hidden_list: list = config["dashboard"].get("hidden_plugins") or []- if not isinstance(hidden_list, list):- hidden_list = []-- if body.hidden and name not in hidden_list:- hidden_list.append(name)- elif not body.hidden and name in hidden_list:- hidden_list.remove(name)-- config["dashboard"]["hidden_plugins"] = hidden_list- save_config(config)- _invalidate_plugins_hub_cache()- return {"ok": True, "name": name, "hidden": body.hidden}+ def _run():+ config = load_config()+ if "dashboard" not in config or not isinstance(config.get("dashboard"), dict):+ config["dashboard"] = {}+ hidden_list: list = config["dashboard"].get("hidden_plugins") or []+ if not isinstance(hidden_list, list):+ hidden_list = []++ if body.hidden and name not in hidden_list:+ hidden_list.append(name)+ elif not body.hidden and name in hidden_list:+ hidden_list.remove(name)++ config["dashboard"]["hidden_plugins"] = hidden_list+ save_config(config)+ _invalidate_plugins_hub_cache()+ return {"ok": True, "name": name, "hidden": body.hidden}++ return await asyncio.to_thread(_run)@app.get("/dashboard-plugins/{plugin_name}/{file_path:path}")diff --git a/tests/hermes_cli/test_web_server_config_offloop.py b/tests/hermes_cli/test_web_server_config_offloop.pynew file mode 100644index 00000000000..98a733ba6af--- /dev/null+++ b/tests/hermes_cli/test_web_server_config_offloop.py@@ -0,0 +1,104 @@+"""GET /api/config must not block the event loop on _SKILLS_PROFILE_LOCK.++Regression for a captured 1.044s gateway stall: the endpoint entered+``_profile_scope`` (which acquires the process-wide ``_SKILLS_PROFILE_LOCK``)+directly on the asyncio event loop, so any slow lock-holder in a worker+thread froze every request and WebSocket in the gateway. The handler now+runs the scope + ``load_config()`` in ``asyncio.to_thread``.+"""++import asyncio+import threading+import time++import pytest+++class TestGetConfigOffLoop:+ @pytest.fixture(autouse=True)+ def _home(self, _isolate_hermes_home):+ pass++ def test_get_config_returns_data(self):+ """The threaded path still returns the normalized, filtered config."""+ try:+ from starlette.testclient import TestClient+ except ImportError:+ pytest.skip("fastapi/starlette not installed")+ from hermes_cli.web_server import app, _SESSION_HEADER_NAME, _SESSION_TOKEN++ client = TestClient(app)+ client.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN+ resp = client.get("/api/config")+ assert resp.status_code == 200+ body = resp.json()+ assert isinstance(body, dict)+ assert not any(k.startswith("_") for k in body)++ def test_loop_stays_responsive_while_profile_lock_held(self):+ """Heartbeats on the request's event loop must keep ticking while+ another thread holds _SKILLS_PROFILE_LOCK and /api/config is in+ flight. Before the fix the handler blocked the loop for the full+ hold; now only the worker thread waits."""+ try:+ import httpx+ except ImportError:+ pytest.skip("httpx not installed")+ from hermes_cli import web_server++ hold_s = 1.0+ release = threading.Event()++ def _holder():+ with web_server._SKILLS_PROFILE_LOCK:+ release.wait(hold_s)++ async def _scenario():+ holder = threading.Thread(target=_holder)+ holder.start()+ # Give the holder time to actually take the lock.+ await asyncio.sleep(0.05)++ ticks = 0++ async def _heartbeat(stop: asyncio.Event):+ # Tick COUNT is the starvation signal, not max gap: when the+ # handler blocks the loop, this task never runs at all during+ # the request, so a gap-based assertion passes vacuously.+ nonlocal ticks+ while not stop.is_set():+ await asyncio.sleep(0.02)+ ticks += 1++ stop = asyncio.Event()+ hb = asyncio.create_task(_heartbeat(stop))+ # Let the heartbeat task actually start before the request.+ await asyncio.sleep(0)+ transport = httpx.ASGITransport(app=web_server.app)+ try:+ async with httpx.AsyncClient(+ transport=transport, base_url="http://testserver"+ ) as client:+ client.headers[web_server._SESSION_HEADER_NAME] = (+ web_server._SESSION_TOKEN+ )+ resp = await client.get("/api/config")+ finally:+ stop.set()+ release.set()+ await hb+ holder.join()++ assert resp.status_code == 200+ return ticks++ ticks = asyncio.run(_scenario())+ # The request waits out the ~1s lock hold in a worker thread while+ # the loop keeps ticking (~50 ticks at 20ms). Pre-fix, the handler+ # blocked the loop for the whole hold and the heartbeat got ~0+ # ticks. Threshold is generous so slow CI machines don't flake.+ assert ticks >= 10, (+ f"event loop heartbeat only ticked {ticks} time(s) while "+ "_SKILLS_PROFILE_LOCK was held — /api/config is blocking the "+ "loop again"+ )