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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(routes): move 118 no-await handlers to the threadpool, gate the rest
rubenluetke10-beepb0da9f203743
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex d045e2fd69..6c167a8a43 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -400,6 +400,14 @@ jobs:# fails only when a file GAINS one. Mirrors pre-push.run: python scripts/ci/check_silent_exception_handlers.py+ - name: Blocking-route gate (no new async route without an await)+ # Static + stdlib-only: an `async def` handler that never awaits runs+ # its disk I/O ON the shared event loop and blocks every WebSocket,+ # route and brain turn behind it (measured 8.19 s behind one such+ # route, 2026-08-28). Per-file ratchet - fails only when a file GAINS+ # one; the fix is dropping `async` so FastAPI uses the threadpool.+ run: python scripts/ci/check_async_routes.py+- name: WebGL-context gate (every 3D surface gives its context back)# Static + stdlib-only: a browser allows ~16 live WebGL contexts and# kills the OLDEST to make room, and three.js `dispose()` never returnsdiff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex 9d2e04c0a5..13d9cc92df 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -1332,13 +1332,13 @@ class RecapEdit(BaseModel):# REST ## --------------------------------------------------------------------------- #@router.get("/state", summary="Agentic-IDE workspace state")-async def get_state() -> dict:+def get_state() -> dict:"""The open workspace, its terminals, and whether focus mode is on."""return get_registry().state()@router.get("/panes", summary="Every coding session running in any open workspace")-async def get_panes() -> dict:+def get_panes() -> dict:"""One row per pane, across ALL open workspaces — not just the front one.``/state`` describes the workspace being drawn. This answers the other@@ -1364,7 +1364,7 @@ async def get_panes() -> dict:@router.get("/state/brief", summary="Agentic-IDE workspace state, briefly")-async def get_state_brief() -> dict:+def get_state_brief() -> dict:"""The workspace as a language model needs it to steer the panes.Pane names, agents, status, idleness, and one recap line each — never@@ -1878,7 +1878,7 @@ def _unwrap_file_uri(value: str) -> str:response_model=WorkspacesResponse,summary="Open Agentic-IDE workspaces",)-async def get_workspaces() -> WorkspacesResponse:+def get_workspaces() -> WorkspacesResponse:"""Every open workspace, in tab order, with the front one marked.Several can be open at once — a workspace is a folder plus its running@@ -2155,7 +2155,7 @@ async def resume_workspace(request: Request) -> dict:response_model=InterruptedResponse,summary="Coding sessions that were interrupted and never restarted",)-async def get_interrupted() -> InterruptedResponse:+def get_interrupted() -> InterruptedResponse:"""Which panes came back holding a conversation and have been told nothing since.The state a restart leaves behind. Resuming reconnects each pane to the@@ -2217,7 +2217,7 @@ async def continue_interrupted(req: ContinueInterruptedRequest) -> ContinueInterresponse_model=PaneNotificationsResponse,summary="Terminals that finished, asked something, or stopped",)-async def get_notifications() -> PaneNotificationsResponse:+def get_notifications() -> PaneNotificationsResponse:"""What the bell in the Agentic-IDE header is showing.Newest first, across EVERY open workspace — a pane in a background tab is@@ -2241,7 +2241,7 @@ async def get_notifications() -> PaneNotificationsResponse:response_model=NotificationsChangedResponse,summary="Mark terminal notifications as read",)-async def read_notifications(req: ReadNotificationsRequest) -> NotificationsChangedResponse:+def read_notifications(req: ReadNotificationsRequest) -> NotificationsChangedResponse:"""Clear the unread count, for the given entries or for all of them.The entries stay in the list — this only stops the bell from counting them.@@ -2258,7 +2258,7 @@ async def read_notifications(req: ReadNotificationsRequest) -> NotificationsChanresponse_model=NotificationsChangedResponse,summary="Discard every terminal notification",)-async def clear_notifications() -> NotificationsChangedResponse:+def clear_notifications() -> NotificationsChangedResponse:"""Throw the whole list away.Nothing about a pane changes: an entry is a note that something happened,@@ -2275,7 +2275,7 @@ async def clear_notifications() -> NotificationsChangedResponse:response_model=NotificationsChangedResponse,summary="Discard one terminal notification",)-async def clear_notification(notification_id: str) -> NotificationsChangedResponse:+def clear_notification(notification_id: str) -> NotificationsChangedResponse:"""Throw one entry away. An id that is not in the list is a quiet no-op.Not a 404: the entry may have gone with its workspace between the client@@ -2369,7 +2369,7 @@ async def set_mode(request: Request, req: ModeRequest) -> dict:@router.put("/surface-context", summary="Report the visible Agentic-IDE terminal")-async def set_surface_context(req: SurfaceContextRequest) -> dict:+def set_surface_context(req: SurfaceContextRequest) -> dict:"""Keep deictic voice/chat references aligned with the visible pane.The state is ephemeral and active-workspace scoped. Grid view clears it,@@ -2767,7 +2767,7 @@ async def close_terminal(request: Request, name: str, workspace_id: str | None =@router.get("/recaps", response_model=RecapsResponse, summary="What every terminal is doing")-async def get_recaps(workspace_id: str | None = None) -> RecapsResponse:+def get_recaps(workspace_id: str | None = None) -> RecapsResponse:"""A short recap per pane — the header line and its hover tooltip.Separate from ``/state`` because the two change at completely different@@ -2804,7 +2804,7 @@ async def get_recaps(workspace_id: str | None = None) -> RecapsResponse:response_model=ActivityResponse,summary="Whether each pane's agent is still working",)-async def get_activity(workspace_id: str | None = None) -> ActivityResponse:+def get_activity(workspace_id: str | None = None) -> ActivityResponse:"""The status badge's own read — every pane's activity, and nothing else.Split from ``/recaps`` for the same reason ``/recaps`` is split from@@ -2895,7 +2895,7 @@ def _pane_for_recap(name: str, workspace_id: str | None) -> tuple[Terminal, Sessresponse_model=TerminalRecap,summary="Write a terminal's recap yourself",)-async def set_terminal_recap(+def set_terminal_recap(name: str, payload: RecapEdit, workspace_id: str | None = None) -> TerminalRecap:"""Replace what the header of terminal ``name`` says with your own words.@@ -2922,7 +2922,7 @@ async def set_terminal_recap(response_model=TerminalRecap,summary="Drop a hand-written recap",)-async def clear_terminal_recap(name: str, workspace_id: str | None = None) -> TerminalRecap:+def clear_terminal_recap(name: str, workspace_id: str | None = None) -> TerminalRecap:"""Hand terminal ``name`` back to the automatic recap.Also clears the back-off, so a pane whose summaries were failing an hour ago@@ -2964,7 +2964,7 @@ async def refresh_terminal_recap(name: str, workspace_id: str | None = None) ->response_model=LastPrompt,summary="The exact prompt a terminal was last sent",)-async def get_last_prompt(name: str, workspace_id: str | None = None) -> LastPrompt:+def get_last_prompt(name: str, workspace_id: str | None = None) -> LastPrompt:"""What terminal ``name`` was last told to do, word for word.This is the proof half of a delivery. Jarvis composes a brief, types it@@ -3039,7 +3039,7 @@ def _terminal_or_http_error(name: str) -> tuple[Session, Terminal]:@router.get("/terminals/{name}/report", summary="What one terminal is doing")-async def terminal_report(name: str, lines: int = 40) -> dict:+def terminal_report(name: str, lines: int = 40) -> dict:"""Status plus the recent readable output of the terminal called ``name``."""try:return get_registry().report(name, lines)@@ -3239,7 +3239,7 @@ def _picks_now(term: Any, read_result: Any) -> dict[str, str]:summary="Interrupt what one terminal's agent is doing (Escape)",openapi_extra={"x-jarvis-dangerous": True},)-async def terminal_interrupt(name: str, workspace: str | None = None) -> dict:+def terminal_interrupt(name: str, workspace: str | None = None) -> dict:"""Press Escape in the pane — the chat stage's Stop button.The coding CLIs stop their current turn on Escape (Claude Code says so in@@ -4580,7 +4580,7 @@ def _writer_options() -> list[PromptWriterOption]:response_model=PromptWriterState,summary="Who writes Agentic-IDE task briefs",)-async def prompt_writer_state() -> PromptWriterState:+def prompt_writer_state() -> PromptWriterState:"""Report the configured brief writer and every option, with live state."""return PromptWriterState(prompt_writer=_current_prompt_writer(), options=_writer_options())@@ -4590,7 +4590,7 @@ async def prompt_writer_state() -> PromptWriterState:response_model=PromptWriterState,summary="Choose who writes Agentic-IDE task briefs",)-async def set_prompt_writer(payload: PromptWriterRequest) -> PromptWriterState:+def set_prompt_writer(payload: PromptWriterRequest) -> PromptWriterState:"""Persist the brief writer.Refuses a provider this install does not offer, and refuses one whose CLI isdiff --git a/jarvis/ui/web/cli_routes.py b/jarvis/ui/web/cli_routes.pyindex 78a96dc058..50e69de8ca 100644--- a/jarvis/ui/web/cli_routes.py+++ b/jarvis/ui/web/cli_routes.py@@ -368,7 +368,7 @@ def _publish_safe(bus: Any, event: Any) -> None:@router.get("", response_model=ListClisResponse)-async def list_clis(request: Request) -> ListClisResponse:+def list_clis(request: Request) -> ListClisResponse:import timereg = _require_registry(request)@@ -401,7 +401,7 @@ async def list_clis(request: Request) -> ListClisResponse:@router.get("/{name}", response_model=CliDetail)-async def get_cli(name: str, request: Request) -> CliDetail:+def get_cli(name: str, request: Request) -> CliDetail:import timereg = _require_registry(request)@@ -464,7 +464,7 @@ async def check_cli(name: str, request: Request) -> CheckResponse:@router.get("/{name}/usage", response_model=UsageListResponse)-async def list_usage(+def list_usage(name: str,request: Request,page: int = Query(1, ge=1, le=10_000),@@ -513,7 +513,7 @@ async def list_usage(@router.get("/{name}/usage/stats", response_model=UsageStatsResponse)-async def usage_stats(+def usage_stats(name: str, request: Request, since_ms: int | None = Query(None, ge=0)) -> UsageStatsResponse:reg = _require_registry(request)@@ -533,7 +533,7 @@ async def usage_stats(@router.post("/{name}/spawn-external", response_model=SpawnExternalResponse)-async def spawn_external(+def spawn_external(name: str,request: Request,body: SpawnExternalRequest,@@ -667,7 +667,7 @@ def _start_install_job(reg: Any, spec: CliSpec, name: str, method: str) -> Any:@router.post("/{name}/install", response_model=InstallStartResponse)-async def install_cli(+def install_cli(name: str,request: Request,body: InstallRequest,@@ -693,7 +693,7 @@ async def install_cli(@router.delete("/{name}/install/{job_id}")-async def cancel_install(name: str, job_id: str, request: Request) -> dict[str, bool]:+def cancel_install(name: str, job_id: str, request: Request) -> dict[str, bool]:reg = _require_registry(request)ok = reg.installer().cancel(job_id)return {"ok": ok}@@ -872,7 +872,7 @@ async def register_custom(payload: CustomCliPayload, request: Request) -> CliDet@router.delete("/custom/{name}")-async def unregister_custom(name: str, request: Request) -> dict[str, Any]:+def unregister_custom(name: str, request: Request) -> dict[str, Any]:reg = _require_registry(request)ok = reg.catalog().remove_custom(name)if not ok:@@ -881,7 +881,7 @@ async def unregister_custom(name: str, request: Request) -> dict[str, Any]:@router.delete("/{name}/usage")-async def clear_usage(name: str, request: Request) -> dict[str, int]:+def clear_usage(name: str, request: Request) -> dict[str, int]:reg = _require_registry(request)if reg.catalog().get(name) is None:raise HTTPException(status_code=404, detail=f"CLI '{name}' not in catalog")diff --git a/jarvis/ui/web/control_routes.py b/jarvis/ui/web/control_routes.pyindex 9a56492924..4eac595a0b 100644--- a/jarvis/ui/web/control_routes.py+++ b/jarvis/ui/web/control_routes.py@@ -175,13 +175,13 @@ class SetKeyBody(BaseModel):@router.get("/auth/probe", dependencies=[Depends(require_control_key)])-async def auth_probe() -> dict[str, Any]:+def auth_probe() -> dict[str, Any]:"""200 iff the Bearer key is valid (cheap check for CLIs / agents)."""return {"ok": True}@router.get("/allowlist", dependencies=[Depends(require_control_key)])-async def get_allowlist() -> dict[str, Any]:+def get_allowlist() -> dict[str, Any]:"""Machine-readable list of mutable settings so an agent can validate arequest before sending it (instead of parsing Python source)."""return {"specs": [spec.model_dump() for spec in SelfModRegistry.list_all()]}@@ -193,7 +193,7 @@ async def get_allowlist() -> dict[str, Any]:@router.get("/config", dependencies=[Depends(require_control_key)])-async def get_config(path: str, request: Request) -> dict[str, Any]:+def get_config(path: str, request: Request) -> dict[str, Any]:if SelfModRegistry.is_forbidden(path):raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,@@ -239,13 +239,13 @@ def _apply_config_write(@router.put("/config", dependencies=[Depends(require_control_key)], openapi_extra={"x-jarvis-dangerous": True})-async def put_config(body: ConfigWriteBody, request: Request) -> dict[str, Any]:+def put_config(body: ConfigWriteBody, request: Request) -> dict[str, Any]:store = _pending_store(request)return _apply_config_write(store, body.path, body.value, body.reason)@router.post("/config/confirm", dependencies=[Depends(require_control_key)])-async def confirm_config(body: PendingIdBody, request: Request) -> dict[str, Any]:+def confirm_config(body: PendingIdBody, request: Request) -> dict[str, Any]:store = _pending_store(request)try:mutation_id = UUID(body.pending_id)@@ -267,7 +267,7 @@ async def confirm_config(body: PendingIdBody, request: Request) -> dict[str, Any@router.post("/config/reject", dependencies=[Depends(require_control_key)])-async def reject_config(body: PendingIdBody, request: Request) -> dict[str, Any]:+def reject_config(body: PendingIdBody, request: Request) -> dict[str, Any]:store = _pending_store(request)try:mutation_id = UUID(body.pending_id)@@ -283,7 +283,7 @@ async def reject_config(body: PendingIdBody, request: Request) -> dict[str, Any]@router.put("/language", dependencies=[Depends(require_control_key)])-async def put_language(body: LanguageBody, request: Request) -> dict[str, Any]:+def put_language(body: LanguageBody, request: Request) -> dict[str, Any]:"""Switch the language. A concrete code (de/en/es) sets BOTH the replylanguage (what Jarvis speaks) AND the interface language (what the usersees) so the whole experience switches; "auto" only affects replies (it@@ -307,7 +307,7 @@ async def put_language(body: LanguageBody, request: Request) -> dict[str, Any]:@router.get("/providers", dependencies=[Depends(require_control_key)])-async def get_providers() -> dict[str, Any]:+def get_providers() -> dict[str, Any]:from jarvis.brain.app_control import build_settings_snapshotreturn build_settings_snapshot(_running_cfg())@@ -341,7 +341,7 @@ def _secret_preview(value: str | None) -> str | None:@router.get("/secrets", dependencies=[Depends(require_control_key)])-async def list_secrets() -> dict[str, Any]:+def list_secrets() -> dict[str, Any]:items = []for key in sorted(ALLOWED_SECRET_KEYS):value = cfg_mod.get_secret(key)@@ -380,7 +380,7 @@ async def delete_secret_value(key: str, request: Request) -> dict[str, Any]:@router.get("/api-key", dependencies=[Depends(require_control_key_or_session)])-async def get_api_key(request: Request) -> dict[str, Any]:+def get_api_key(request: Request) -> dict[str, Any]:key = control_key.get_control_key()# Audit every reveal without logging either credential.client = getattr(request, "client", None)@@ -393,7 +393,7 @@ async def get_api_key(request: Request) -> dict[str, Any]:dependencies=[Depends(require_control_key_or_session)],openapi_extra={"x-jarvis-dangerous": True},)-async def rotate_api_key(body: RotateBody) -> dict[str, Any]:+def rotate_api_key(body: RotateBody) -> dict[str, Any]:if not body.confirm:raise HTTPException(status_code=400,@@ -412,7 +412,7 @@ async def rotate_api_key(body: RotateBody) -> dict[str, Any]:dependencies=[Depends(require_control_key_or_session)],openapi_extra={"x-jarvis-dangerous": True},)-async def set_api_key(body: SetKeyBody, request: Request) -> dict[str, Any]:+def set_api_key(body: SetKeyBody, request: Request) -> dict[str, Any]:"""Replace the control key with a user-chosen value.The caller already typed the value, so the response returns only thediff --git a/jarvis/ui/web/local_models_routes.py b/jarvis/ui/web/local_models_routes.pyindex 11a6d5c127..a3c0e8b79b 100644--- a/jarvis/ui/web/local_models_routes.py+++ b/jarvis/ui/web/local_models_routes.py@@ -490,7 +490,7 @@ async def get_roles(provider_id: str, request: Request) -> RolesResponse:@router.put("/roles/{role}", response_model=RoleSetResponse)-async def set_role(+def set_role(provider_id: str, role: str, body: RoleSetBody, request: Request) -> RoleSetResponse:"""Assign ``model`` to a role through the config writers; ``""`` = discovery."""@@ -595,7 +595,7 @@ def _options_response(name: str, opts: OllamaModelOptions | None) -> ModelOption@router.get("/models/{name:path}/options", response_model=ModelOptionsResponse)-async def get_model_options(provider_id: str, name: str, request: Request) -> ModelOptionsResponse:+def get_model_options(provider_id: str, name: str, request: Request) -> ModelOptionsResponse:"""The per-model profile as configured (empty when none)."""_require_pull_capable(provider_id)_key, opts = _options_for(_resolve_cfg(request), name)@@ -603,7 +603,7 @@ async def get_model_options(provider_id: str, name: str, request: Request) -> Mo@router.put("/models/{name:path}/options", response_model=ModelOptionsResponse)-async def put_model_options(+def put_model_options(provider_id: str, name: str, body: OllamaModelOptionsBody, request: Request) -> ModelOptionsResponse:"""Replace the profile of ``name`` with ``body`` (whole set; nothing set = clear)."""@@ -635,7 +635,7 @@ async def put_model_options(@router.delete("/models/{name:path}/options", response_model=ModelOptionsResponse)-async def delete_model_options(+def delete_model_options(provider_id: str, name: str, request: Request) -> ModelOptionsResponse:"""Reset: drop the profile so Ollama's defaults apply again."""@@ -752,13 +752,13 @@ def _require_hf(request: Request) -> None:@router.get("/hf/enabled", response_model=HfEnabledResponse)-async def get_hf_enabled(provider_id: str, request: Request) -> HfEnabledResponse:+def get_hf_enabled(provider_id: str, request: Request) -> HfEnabledResponse:_require_pull_capable(provider_id)return HfEnabledResponse(enabled=cfg_mod.ollama_hf_enabled(_resolve_cfg(request)))@router.put("/hf/enabled", response_model=HfEnabledResponse)-async def put_hf_enabled(+def put_hf_enabled(provider_id: str, body: HfEnabledBody, request: Request) -> HfEnabledResponse:"""Switch Hugging Face browsing on or off (``[brain.providers.ollama].hf_enabled``)."""@@ -903,7 +903,7 @@ class IdleReleaseResponse(BaseModel):@router.get("/runtime/idle-release", response_model=IdleReleaseResponse)-async def get_idle_release(provider_id: str, request: Request) -> IdleReleaseResponse:+def get_idle_release(provider_id: str, request: Request) -> IdleReleaseResponse:"""How long the local voice stack may sit idle before it releases memory."""_require_pull_capable(provider_id)voice = getattr(_resolve_cfg(request), "voice", None)@@ -911,7 +911,7 @@ async def get_idle_release(provider_id: str, request: Request) -> IdleReleaseRes@router.put("/runtime/idle-release", response_model=IdleReleaseResponse)-async def put_idle_release(+def put_idle_release(provider_id: str, body: IdleReleaseBody, request: Request) -> IdleReleaseResponse:"""Persist the idle window; the supervisor reads it on its next tick."""@@ -942,7 +942,7 @@ class AutostartBody(BaseModel):@router.get("/runtime/autostart", response_model=AutostartResponse)-async def get_autostart(provider_id: str, request: Request) -> AutostartResponse:+def get_autostart(provider_id: str, request: Request) -> AutostartResponse:"""Whether the local server starts with Jarvis, and whether that would fire."""_require_pull_capable(provider_id)from jarvis.core.config import ollama_autostart@@ -955,7 +955,7 @@ async def get_autostart(provider_id: str, request: Request) -> AutostartResponse@router.put("/runtime/autostart", response_model=AutostartResponse)-async def put_autostart(+def put_autostart(provider_id: str, body: AutostartBody, request: Request) -> AutostartResponse:"""Switch local models on or off — persisted AND applied to what runs now.@@ -1083,7 +1083,7 @@ async def get_overview(@router.get("/server/env-guide", response_model=EnvGuideResponse)-async def get_server_env_guide(+def get_server_env_guide(provider_id: str,os: str = Query(default="", description="windows | macos | linux; empty = this OS"),) -> EnvGuideResponse:diff --git a/jarvis/ui/web/onboarding_routes.py b/jarvis/ui/web/onboarding_routes.pyindex 0819afd69f..76309e063b 100644--- a/jarvis/ui/web/onboarding_routes.py+++ b/jarvis/ui/web/onboarding_routes.py@@ -48,7 +48,7 @@ def _safe_state_payload() -> dict:@router.get("/state")-async def get_state(response: Response) -> dict:+def get_state(response: Response) -> dict:# Same no-cache guarantee the fast-boot handler gives: the gate must never# act on a cached completed/incomplete verdict.response.headers["cache-control"] = "no-store, max-age=0"@@ -56,18 +56,18 @@ async def get_state(response: Response) -> dict:@router.get("/terms")-async def get_terms() -> dict:+def get_terms() -> dict:return {"version": CURRENT_TERMS_VERSION, "text": read_terms_text()}@router.post("/step")-async def post_step(body: StepBody) -> dict:+def post_step(body: StepBody) -> dict:st.set_onboarding_step(body.step, skipped=body.skipped, path=_path())return {"ok": True}@router.post("/accept-terms")-async def post_accept_terms() -> dict:+def post_accept_terms() -> dict:st.accept_terms(CURRENT_TERMS_VERSION, path=_path())return {"ok": True, "version": CURRENT_TERMS_VERSION}@@ -93,7 +93,7 @@ def _schedule_app_shutdown(request: Request) -> None:@router.post("/decline-terms")-async def post_decline_terms(request: Request) -> dict:+def post_decline_terms(request: Request) -> dict:"""Declining the Terms quits the app (design 2026-07-09).The install one-liner never asks anything, so the Terms gate on first@@ -112,7 +112,7 @@ async def post_decline_terms(request: Request) -> dict:@router.post("/acknowledge-wake-word")-async def post_ack_wake_word() -> dict:+def post_ack_wake_word() -> dict:st.acknowledge_wake_word(_path())return {"ok": True}@@ -144,7 +144,7 @@ def _schedule_fresh_restart(request: Request) -> bool:@router.post("/complete")-async def post_complete(request: Request) -> dict:+def post_complete(request: Request) -> dict:require_interactive_desktop_action(request, action="restart", require_origin=True)diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.pyindex cd110d122e..8c2bac3a49 100644--- a/jarvis/ui/web/settings_routes.py+++ b/jarvis/ui/web/settings_routes.py@@ -130,7 +130,7 @@ def _require_brain(request: Request):@router.get("/reply-language")-async def get_reply_language(request: Request) -> dict[str, object]:+def get_reply_language(request: Request) -> dict[str, object]:brain = _require_brain(request)return {"language": getattr(brain, "reply_language", "auto"),@@ -139,7 +139,7 @@ async def get_reply_language(request: Request) -> dict[str, object]:@router.put("/reply-language")-async def put_reply_language(body: ReplyLanguageBody, request: Request) -> dict[str, object]:+def put_reply_language(body: ReplyLanguageBody, request: Request) -> dict[str, object]:brain = _require_brain(request)# The BrainManager owns validation (single source of truth). An unknown@@ -456,7 +456,7 @@ def _resolve_cfg(request: Request):@router.get("/team-proxy")-async def get_team_proxy(request: Request) -> dict[str, object]:+def get_team_proxy(request: Request) -> dict[str, object]:from jarvis.core import config as cfg_modconf = _resolve_cfg(request) or cfg_mod.load_config()@@ -471,7 +471,7 @@ async def get_team_proxy(request: Request) -> dict[str, object]:@router.put("/team-proxy")-async def put_team_proxy(body: TeamProxyBody, request: Request) -> dict[str, object]:+def put_team_proxy(body: TeamProxyBody, request: Request) -> dict[str, object]:url = (body.url or "").strip()if body.enabled and not url:raise HTTPException(status_code=400, detail="Team mode requires a proxy url.")@@ -536,7 +536,7 @@ def _current_ui_language(request: Request) -> str:@router.get("/ui-language")-async def get_ui_language(request: Request) -> dict[str, object]:+def get_ui_language(request: Request) -> dict[str, object]:return {"language": _current_ui_language(request), "options": list(_UI_LANGUAGES)}@@ -618,7 +618,7 @@ def _current_ui_theme(request: Request) -> str:@router.get("/appearance")-async def get_appearance(request: Request) -> dict[str, object]:+def get_appearance(request: Request) -> dict[str, object]:"""The app's colour theme, plus the values this build accepts."""return {"theme": _current_ui_theme(request), "options": list(_UI_THEMES)}@@ -738,7 +738,7 @@ def _background_player_available() -> bool:@router.get("/music")-async def get_music_settings(request: Request) -> dict[str, object]:+def get_music_settings(request: Request) -> dict[str, object]:"""Preferred music service + where YouTube Music plays, with the acceptedvalues, which connectors are connected, and whether the background playercan run on this host."""@@ -754,7 +754,7 @@ async def get_music_settings(request: Request) -> dict[str, object]:@router.put("/music")-async def put_music_settings(body: MusicSettingsBody, request: Request) -> dict[str, object]:+def put_music_settings(body: MusicSettingsBody, request: Request) -> dict[str, object]:"""Change the preferred music service and/or where YouTube Music plays."""preferred_now, playback_now = _current_music(request)preferred = preferred_now@@ -857,12 +857,12 @@ def _current_stt_language(request: Request) -> str:@router.get("/stt-language")-async def get_stt_language(request: Request) -> dict[str, object]:+def get_stt_language(request: Request) -> dict[str, object]:return {"language": _current_stt_language(request), "options": list(_STT_LANGUAGES)}@router.put("/stt-language")-async def put_stt_language(body: SttLanguageBody, request: Request) -> dict[str, object]:+def put_stt_language(body: SttLanguageBody, request: Request) -> dict[str, object]:lang = (body.language or "").strip().lower()if lang not in _STT_LANGUAGES:raise HTTPException(@@ -1000,7 +1000,7 @@ class WakeLanguageBody(BaseModel):@router.get("/wake-language")-async def get_wake_language(request: Request) -> dict[str, object]:+def get_wake_language(request: Request) -> dict[str, object]:from jarvis.speech.wake_model_fetch import resolve_wake_languagecfg = _config(request)@@ -1018,7 +1018,7 @@ async def get_wake_language(request: Request) -> dict[str, object]:@router.put("/wake-language")-async def put_wake_language(body: WakeLanguageBody, request: Request) -> dict[str, object]:+def put_wake_language(body: WakeLanguageBody, request: Request) -> dict[str, object]:lang = (body.language or "").strip().lower()if lang not in _WAKE_LANGUAGES:raise HTTPException(@@ -1213,7 +1213,7 @@ def _run_local_speech_install() -> None:@router.post("/wake-word/enable-local-speech")-async def enable_local_speech(request: Request) -> dict[str, object]:+def enable_local_speech(request: Request) -> dict[str, object]:"""Install faster-whisper plus its wake model so any wake word works.Idempotent and non-blocking: returns immediately with a ``state`` the UI@@ -1245,7 +1245,7 @@ async def enable_local_speech(request: Request) -> dict[str, object]:@router.get("/wake-word/enable-local-speech/status")-async def enable_local_speech_status(request: Request) -> dict[str, object]:+def enable_local_speech_status(request: Request) -> dict[str, object]:"""Report the local-speech install progress + whether the pack is present."""available = _local_speech_ready()with _local_speech_install_lock:@@ -1293,7 +1293,7 @@ async def enable_local_speech_status(request: Request) -> dict[str, object]:@router.get("/wake-word")-async def get_wake_word(request: Request) -> dict[str, object]:+def get_wake_word(request: Request) -> dict[str, object]:from jarvis.core.config import WakeWordConfigfrom jarvis.speech.wake_constants import INSTANT_WAKE_PHRASES, WAKE_ENGINES@@ -1469,7 +1469,7 @@ class WakeActivationBody(BaseModel):@router.post("/wake-word/activation")-async def set_wake_activation(body: WakeActivationBody, request: Request) -> dict[str, object]:+def set_wake_activation(body: WakeActivationBody, request: Request) -> dict[str, object]:"""Turn the always-on wake word ON/OFF — the "how do you activate Jarvis"master switch (product rule 2026-07-04).@@ -1782,7 +1782,7 @@ class KeybindBody(BaseModel):@router.get("/keybinds")-async def get_keybinds(request: Request) -> dict[str, object]:+def get_keybinds(request: Request) -> dict[str, object]:from jarvis.core.config import TriggerConfigfrom jarvis.core.config_writer import KEYBIND_TOML_KEYfrom jarvis.trigger.hotkey import mouse_hotkeys_available@@ -1818,7 +1818,7 @@ async def get_keybinds(request: Request) -> dict[str, object]:@router.put("/keybinds")-async def put_keybind(body: KeybindBody, request: Request) -> dict[str, object]:+def put_keybind(body: KeybindBody, request: Request) -> dict[str, object]:from jarvis.core.config_writer import KEYBIND_ACTIONS, KEYBIND_TOML_KEYfrom jarvis.trigger.hotkey import (MOUSE_BUTTON_TOKENS,@@ -1968,7 +1968,7 @@ async def put_keybind(body: KeybindBody, request: Request) -> dict[str, object]:@router.get("/assistant-name")-async def get_assistant_name(request: Request) -> dict[str, object]:+def get_assistant_name(request: Request) -> dict[str, object]:"""The assistant's resolved name. Read-only: the name derives from the wakephrase (set via PUT /api/settings/wake-word), there is no separate control."""from jarvis.brain.assistant_name import DEFAULT_ASSISTANT_NAME, resolve_assistant_name@@ -2116,7 +2116,7 @@ class OverlayStyleBody(BaseModel):@router.get("/overlay-style")-async def get_overlay_style(request: Request) -> dict[str, object]:+def get_overlay_style(request: Request) -> dict[str, object]:"""Current on-screen overlay style + the selectable options."""cfg = _config(request)ui = getattr(cfg, "ui", None)@@ -2233,13 +2233,13 @@ def _system_prompt_payload() -> dict[str, object]:@router.get("/system-prompt")-async def get_system_prompt() -> dict[str, object]:+def get_system_prompt() -> dict[str, object]:"""Current effective system prompt + the packaged default (for reset)."""return _system_prompt_payload()@router.put("/system-prompt")-async def put_system_prompt(body: SystemPromptBody) -> dict[str, object]:+def put_system_prompt(body: SystemPromptBody) -> dict[str, object]:"""Save a custom system prompt. Applies on the next turn (no restart)."""from jarvis.brain import persona_loader@@ -2257,7 +2257,7 @@ async def put_system_prompt(body: SystemPromptBody) -> dict[str, object]:@router.delete("/system-prompt")-async def delete_system_prompt() -> dict[str, object]:+def delete_system_prompt() -> dict[str, object]:"""Reset to the packaged default by removing the custom override."""from jarvis.brain import persona_loader@@ -2296,13 +2296,13 @@ def _agent_instructions_payload(request: Request) -> dict[str, object]:@router.get("/agent-instructions")-async def get_agent_instructions(request: Request) -> dict[str, object]:+def get_agent_instructions(request: Request) -> dict[str, object]:"""Current agent instructions + the dynamic filename + a starter template."""return _agent_instructions_payload(request)@router.put("/agent-instructions")-async def put_agent_instructions(+def put_agent_instructions(body: AgentInstructionsBody, request: Request) -> dict[str, object]:"""Save the user's standing instructions. Applies on the next turn (no restart)."""@@ -2322,7 +2322,7 @@ async def put_agent_instructions(@router.delete("/agent-instructions")-async def delete_agent_instructions(request: Request) -> dict[str, object]:+def delete_agent_instructions(request: Request) -> dict[str, object]:"""Clear the user's standing instructions by deleting the file."""from jarvis.brain import agent_instructions@@ -2459,7 +2459,7 @@ async def restart_app(request: Request, force: bool = False) -> dict[str, object@router.get("/input-isolation", summary="Can other apps type into this window?")-async def get_input_isolation() -> dict[str, object]:+def get_input_isolation() -> dict[str, object]:"""Report whether outside input software can reach this app's window.Third-party dictation and speech-to-text tools, text expanders, clipboard@@ -2592,7 +2592,7 @@ class BoolToggleBody(BaseModel):@router.get("/bar-persistent")-async def get_bar_persistent(request: Request) -> dict[str, object]:+def get_bar_persistent(request: Request) -> dict[str, object]:cfg = _config(request)ui = getattr(cfg, "ui", None)return {"enabled": bool(getattr(ui, "bar_persistent", True))}@@ -2644,7 +2644,7 @@ async def put_bar_persistent(body: BoolToggleBody, request: Request) -> dict[str@router.get("/bar-follow-cursor")-async def get_bar_follow_cursor(request: Request) -> dict[str, object]:+def get_bar_follow_cursor(request: Request) -> dict[str, object]:cfg = _config(request)ui = getattr(cfg, "ui", None)return {"enabled": bool(getattr(ui, "bar_follow_cursor_monitor", True))}@@ -2711,7 +2711,7 @@ class BarSizeBody(BaseModel):@router.get("/bar-size")-async def get_bar_size(request: Request) -> dict[str, object]:+def get_bar_size(request: Request) -> dict[str, object]:cfg = _config(request)ui = getattr(cfg, "ui", None)return {@@ -2768,7 +2768,7 @@ async def put_bar_size(body: BarSizeBody, request: Request) -> dict[str, object]@router.get("/mute-music")-async def get_mute_music(request: Request) -> dict[str, object]:+def get_mute_music(request: Request) -> dict[str, object]:cfg = _config(request)duck = getattr(cfg, "ducking", None)return {"enabled": bool(getattr(duck, "enabled", False))}@@ -2806,14 +2806,14 @@ async def put_mute_music(body: BoolToggleBody, request: Request) -> dict[str, ob@router.get("/sound-effects")-async def get_sound_effects(request: Request) -> dict[str, object]:+def get_sound_effects(request: Request) -> dict[str, object]:cfg = _config(request)ui = getattr(cfg, "ui", None)return {"enabled": bool(getattr(ui, "sound_effects", True))}@router.put("/sound-effects")-async def put_sound_effects(body: BoolToggleBody, request: Request) -> dict[str, object]:+def put_sound_effects(body: BoolToggleBody, request: Request) -> dict[str, object]:"""Global earcon master switch. Persists to [ui] sound_effects and applieslive: the in-memory UI config is the same object the speech pipeline readsbefore every earcon, so the next tone honors the new value with no restart.@@ -2854,14 +2854,14 @@ async def put_sound_effects(body: BoolToggleBody, request: Request) -> dict[str,@router.get("/browser-login")-async def get_browser_login(request: Request) -> dict[str, object]:+def get_browser_login(request: Request) -> dict[str, object]:cfg = _config(request)ui = getattr(cfg, "ui", None)return {"enabled": bool(getattr(ui, "require_browser_login", False))}@router.put("/browser-login")-async def put_browser_login(+def put_browser_login(body: BoolToggleBody, request: Request, response: Response) -> dict[str, object]:"""Toggle the browser lock live and persist it to ``[ui]``.@@ -3208,7 +3208,7 @@ def _current_silence_window_ms(request: Request) -> int:@router.get("/silence-window")-async def get_silence_window(request: Request) -> dict[str, object]:+def get_silence_window(request: Request) -> dict[str, object]:ms = _current_silence_window_ms(request)return {"ms": ms,@@ -3223,7 +3223,7 @@ async def get_silence_window(request: Request) -> dict[str, object]:@router.put("/silence-window")-async def put_silence_window(body: SilenceWindowBody, request: Request) -> dict[str, object]:+def put_silence_window(body: SilenceWindowBody, request: Request) -> dict[str, object]:ms = _normalise_silence_window_ms(body.ms)# Best-effort in-memory cfg update so a later cfg read agrees pre-restart.@@ -3302,7 +3302,7 @@ def _current_tts_volume(request: Request) -> float:@router.get("/tts-volume")-async def get_tts_volume(request: Request) -> dict[str, object]:+def get_tts_volume(request: Request) -> dict[str, object]:return {"volume": _current_tts_volume(request),"default": _TTS_VOLUME_DEFAULT,@@ -3312,7 +3312,7 @@ async def get_tts_volume(request: Request) -> dict[str, object]:@router.put("/tts-volume")-async def put_tts_volume(body: TtsVolumeBody, request: Request) -> dict[str, object]:+def put_tts_volume(body: TtsVolumeBody, request: Request) -> dict[str, object]:volume = float(body.volume) # already range-validated by the Pydantic Field# Best-effort in-memory cfg update so a later cfg read agrees pre-restart.diff --git a/jarvis/ui/web/skills_routes.py b/jarvis/ui/web/skills_routes.pyindex 9e515f9a5f..181f4d685f 100644--- a/jarvis/ui/web/skills_routes.py+++ b/jarvis/ui/web/skills_routes.py@@ -346,7 +346,7 @@ class SkillQueryBody(BaseModel):# ----------------------------------------------------------------------@router.get("")-async def list_skills(request: Request) -> dict[str, Any]:+def list_skills(request: Request) -> dict[str, Any]:from jarvis.skills import prefsreg = _require_registry(request)@@ -358,7 +358,7 @@ async def list_skills(request: Request) -> dict[str, Any]:@router.get("/brief")-async def list_skills_brief(request: Request) -> dict[str, Any]:+def list_skills_brief(request: Request) -> dict[str, Any]:"""The lean listing the brain reads by voice ("which skills do I have").``GET /api/skills`` serialises triggers, resources, origin receipts and@@ -585,7 +585,7 @@ async def refine_skill_draft(@router.post("/creator/validate")-async def validate_skill_draft(+def validate_skill_draft(body: SkillCreatorValidateBody,request: Request,) -> dict[str, Any]:@@ -1106,7 +1106,7 @@ async def upload_skill(# NB: registered BEFORE ``/{name}`` so a ``PUT /order`` is not captured by the# ``PUT /{name}`` path-param route (which would treat "order" as a skill name).@router.put("/order")-async def reorder_skills(body: SkillOrderBody, request: Request) -> dict[str, Any]:+def reorder_skills(body: SkillOrderBody, request: Request) -> dict[str, Any]:"""Persist the user's custom skill order (list view only)."""from jarvis.skills import prefs@@ -1133,7 +1133,7 @@ class MatchTestRequest(BaseModel):@router.post("/match-test", openapi_extra={"x-jarvis-readonly": True})-async def match_test(request: Request, body: MatchTestRequest) -> dict[str, Any]:+def match_test(request: Request, body: MatchTestRequest) -> dict[str, Any]:"""Dry-run the skill matcher against an utterance and explain the verdict.This is the affordance whose absence made the whole problem invisible: the@@ -1289,7 +1289,7 @@ async def match_test(request: Request, body: MatchTestRequest) -> dict[str, Any]@router.get("/lint", openapi_extra={"x-jarvis-readonly": True})-async def lint_skills(request: Request) -> dict[str, Any]:+def lint_skills(request: Request) -> dict[str, Any]:"""Report which installed skills can never be FOUND.Different question from ``validate``: that one asks whether a SKILL.md@@ -1321,7 +1321,7 @@ async def lint_skills(request: Request) -> dict[str, Any]:@router.get("/match-log", openapi_extra={"x-jarvis-readonly": True})-async def match_log_recent(+def match_log_recent(request: Request,limit: int = 50,skill: str = "",@@ -1370,7 +1370,7 @@ async def match_log_recent(@router.get("/{name}")-async def get_skill(name: str, request: Request) -> dict[str, Any]:+def get_skill(name: str, request: Request) -> dict[str, Any]:reg = _require_registry(request)try:skill = reg.get(name)@@ -1429,7 +1429,7 @@ def _delete_user_skill(reg: Any, name: str) -> None:# NB: registered BEFORE ``/{name}`` so a ``POST /bulk-delete`` is never captured# by a path-param route that would treat "bulk-delete" as a skill name.@router.post("/bulk-delete")-async def bulk_delete_skills(+def bulk_delete_skills(body: SkillBulkDeleteBody, request: Request) -> dict[str, Any]:"""Delete several user skills in one batch.@@ -1457,7 +1457,7 @@ async def bulk_delete_skills(@router.delete("/{name}")-async def delete_skill(name: str, request: Request) -> dict[str, Any]:+def delete_skill(name: str, request: Request) -> dict[str, Any]:"""Delete a user skill (folder) and prune its prefs.Built-ins are refused (409) — they would be re-copied on the next start.@@ -1469,7 +1469,7 @@ async def delete_skill(name: str, request: Request) -> dict[str, Any]:@router.put("/{name}")-async def update_skill(+def update_skill(name: str,body: SkillUpdateBody,request: Request,@@ -1508,12 +1508,12 @@ async def update_skill(@router.post("/{name}/enable")-async def enable_skill(name: str, request: Request) -> dict[str, Any]:+def enable_skill(name: str, request: Request) -> dict[str, Any]:return _flip_state(request, name, SkillLifecycleState.ACTIVE)@router.post("/{name}/disable")-async def disable_skill(name: str, request: Request) -> dict[str, Any]:+def disable_skill(name: str, request: Request) -> dict[str, Any]:return _flip_state(request, name, SkillLifecycleState.DISABLED)@@ -1582,7 +1582,7 @@ async def get_skill_link_health(name: str, request: Request) -> dict[str, Any]:@router.get("/{name}/resources/{kind}/{filename:path}")-async def get_skill_resource(+def get_skill_resource(name: str, kind: str, filename: str, request: Request) -> PlainTextResponse:"""Returns the content of a bundled resource file (text-only, UTF-8).@@ -1913,7 +1913,7 @@ async def install_from_catalog(@router.get("/catalog/meta")-async def catalog_meta(request: Request) -> dict[str, Any]:+def catalog_meta(request: Request) -> dict[str, Any]:"""Meta info for the frontend: which categories, languages, and trust levelsexist in the current catalog. Fills the dropdowns in the SkillFinder dialogdynamically, so they don't drift out of sync with the JSON.diff --git a/jarvis/ui/web/workspace_clis_routes.py b/jarvis/ui/web/workspace_clis_routes.pyindex 37e90ca31c..904ab16986 100644--- a/jarvis/ui/web/workspace_clis_routes.py+++ b/jarvis/ui/web/workspace_clis_routes.py@@ -122,7 +122,7 @@ def _bad_request(exc: custom_clis.CustomCliError) -> HTTPException:@router.get("", response_model=CustomCliListResponse, summary="List your own CLIs")-async def list_clis() -> CustomCliListResponse:+def list_clis() -> CustomCliListResponse:"""Every CLI the user added, plus the limits the form has to respect."""return CustomCliListResponse(clis=[_model(entry) for entry in custom_clis.list_custom_clis()]@@ -135,7 +135,7 @@ async def list_clis() -> CustomCliListResponse:summary="Add a CLI of your own",openapi_extra={"x-jarvis-dangerous": True},)-async def create_cli(req: CreateCustomCliRequest) -> CustomCliModel:+def create_cli(req: CreateCustomCliRequest) -> CustomCliModel:"""Store a new CLI and offer it everywhere a terminal can be opened."""try:entry = custom_clis.create_custom_cli(@@ -156,7 +156,7 @@ async def create_cli(req: CreateCustomCliRequest) -> CustomCliModel:summary="Change one of your CLIs",openapi_extra={"x-jarvis-dangerous": True},)-async def update_cli(cli_id: str, req: UpdateCustomCliRequest) -> CustomCliModel:+def update_cli(cli_id: str, req: UpdateCustomCliRequest) -> CustomCliModel:"""Edit a stored CLI. Panes already running it keep the command they startedwith — a live process cannot be re-launched under it."""try:@@ -177,7 +177,7 @@ async def update_cli(cli_id: str, req: UpdateCustomCliRequest) -> CustomCliModelsummary="Remove one of your CLIs",openapi_extra={"x-jarvis-dangerous": True},)-async def delete_cli(cli_id: str) -> dict[str, Any]:+def delete_cli(cli_id: str) -> dict[str, Any]:"""Forget a CLI and its logo. Open panes running it are left alone."""try:entry = custom_clis.delete_custom_cli(cli_id)@@ -219,7 +219,7 @@ async def upload_logo(summary="Remove a CLI's logo",openapi_extra={"x-jarvis-dangerous": True},)-async def remove_logo(cli_id: str) -> CustomCliModel:+def remove_logo(cli_id: str) -> CustomCliModel:"""Drop the logo; the picker falls back to the monogram it draws without one."""try:entry = custom_clis.clear_logo(cli_id)@@ -229,7 +229,7 @@ async def remove_logo(cli_id: str) -> CustomCliModel:@router.get("/{cli_id}/logo", summary="A CLI's logo")-async def get_logo(cli_id: str) -> FileResponse:+def get_logo(cli_id: str) -> FileResponse:"""Serve the stored image.Two headers earn their place. ``Content-Security-Policy: sandbox`` becausediff --git a/scripts/ci/async-routes-baseline.json b/scripts/ci/async-routes-baseline.jsonnew file mode 100644index 0000000000..b0e3d39038--- /dev/null+++ b/scripts/ci/async-routes-baseline.json@@ -0,0 +1,38 @@+{+ "_comment": "Per-file count of async-def route handlers whose body never awaits - each one runs its disk I/O on the shared event loop. Generated by scripts/ci/check_async_routes.py --update. These numbers may go DOWN freely; an increase is a gate failure.",+ "total": 96,+ "files": {+ "jarvis/ui/web/agent_chat_routes.py": 4,+ "jarvis/ui/web/chats_routes.py": 4,+ "jarvis/ui/web/commands_routes.py": 2,+ "jarvis/ui/web/computer_use_routes.py": 5,+ "jarvis/ui/web/diagnostics_routes.py": 3,+ "jarvis/ui/web/dictation_routes.py": 3,+ "jarvis/ui/web/downloads_routes.py": 1,+ "jarvis/ui/web/feedback_routes.py": 1,+ "jarvis/ui/web/frontier_routes.py": 2,+ "jarvis/ui/web/local_models_assistant_routes.py": 1,+ "jarvis/ui/web/marketplace_publish_routes.py": 3,+ "jarvis/ui/web/marketplace_routes.py": 4,+ "jarvis/ui/web/mcp_routes.py": 5,+ "jarvis/ui/web/outputs_routes.py": 5,+ "jarvis/ui/web/preview_routes.py": 1,+ "jarvis/ui/web/profile_routes.py": 7,+ "jarvis/ui/web/provider_routes.py": 6,+ "jarvis/ui/web/screen_context_routes.py": 6,+ "jarvis/ui/web/self_mod_routes.py": 4,+ "jarvis/ui/web/sessions_routes.py": 5,+ "jarvis/ui/web/setup_routes.py": 2,+ "jarvis/ui/web/starter_plan_routes.py": 3,+ "jarvis/ui/web/sub_agents_routes.py": 2,+ "jarvis/ui/web/tasks_routes.py": 1,+ "jarvis/ui/web/telephony_routes.py": 7,+ "jarvis/ui/web/tool_model_routes.py": 1,+ "jarvis/ui/web/tools_routes.py": 1,+ "jarvis/ui/web/update_routes.py": 1,+ "jarvis/ui/web/voice_call_routes.py": 3,+ "jarvis/ui/web/wiki_routes.py": 1,+ "jarvis/ui/web/workflows_routes.py": 1,+ "jarvis/ui/web/workspace_routes.py": 1+ }+}diff --git a/scripts/ci/check_async_routes.py b/scripts/ci/check_async_routes.pynew file mode 100644index 0000000000..2f80d8c403--- /dev/null+++ b/scripts/ci/check_async_routes.py@@ -0,0 +1,208 @@+"""Blocking-route ratchet: no new ``async def`` handler without an ``await``.++FastAPI runs an ``async def`` handler ON the asyncio event loop; a plain+``def`` handler goes to the anyio threadpool. An ``async def`` body that never+awaits therefore runs its SQLite reads, directory walks and subprocess calls+on the one thread that answers every WebSocket, HTTP route and brain turn —+"every section loads slowly" was almost never the section, it was whichever+such route happened to be busy (measured 2026-08-28: ``/api/health`` 1.9 ms+alone, 8.19 s behind one blocking route; 285 such handlers existed on+2026-09-01, up from 234 four days earlier — they multiply faster than they+get fixed, hence this gate).++A handler is counted when:++* it is ``async def`` and decorated with a router verb+ (``get/post/put/patch/delete/head/options/websocket/api_route``), and+* its own body (nested functions excluded) contains no ``await``,+ ``async for``, ``async with``, or ``yield``.++The fix is almost always to drop ``async`` — FastAPI then runs it in the+threadpool. The backlog is grandfathered per file (baseline JSON beside this+script); a file may never GAIN one.++Usage::++ python scripts/ci/check_async_routes.py # gate+ python scripts/ci/check_async_routes.py --report # worst files+ python scripts/ci/check_async_routes.py --update # re-baseline (lower only)++Static analysis only — it never imports the app. Covered by+``tests/unit/ui/web/test_check_async_routes.py``.+"""++from __future__ import annotations++import argparse+import ast+import json+import sys+from pathlib import Path++_REPO = Path(__file__).resolve().parents[2]+_BASELINE = Path(__file__).resolve().parent / "async-routes-baseline.json"++#: Where route handlers live. Deliberately narrow: this gate is about the web+#: surface whose event loop is shared with voice and every other request.+_GLOB = "jarvis/ui/web/*_routes.py"++_ROUTE_VERBS = {+ "get",+ "post",+ "put",+ "patch",+ "delete",+ "head",+ "options",+ "websocket",+ "api_route",+}+++class UnparseableSource(RuntimeError):+ """A scanned file could not be parsed, so its count cannot be trusted."""+++def _decorator_verb(node: ast.expr) -> str:+ """The attribute name a decorator call ends in (``router.get`` -> ``get``)."""+ if isinstance(node, ast.Call):+ node = node.func+ if isinstance(node, ast.Attribute):+ return node.attr.lower()+ return ""+++def _is_route_handler(fn: ast.AsyncFunctionDef) -> bool:+ return any(_decorator_verb(dec) in _ROUTE_VERBS for dec in fn.decorator_list)+++def _body_awaits(fn: ast.AsyncFunctionDef) -> bool:+ """Does the handler's OWN body await / async-iterate / yield?++ Nested function definitions are skipped: an ``await`` inside a helper+ closure does not put the handler itself on the threadpool.+ """+ todo: list[ast.AST] = list(fn.body)+ while todo:+ node = todo.pop()+ if isinstance(node, ast.Await | ast.AsyncFor | ast.AsyncWith | ast.Yield | ast.YieldFrom):+ return True+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda):+ continue+ todo.extend(ast.iter_child_nodes(node))+ return False+++def blocking_routes(path: Path) -> list[tuple[int, str]]:+ """``(line, name)`` of every async route handler with no await in *path*."""+ source = path.read_text(encoding="utf-8-sig", errors="ignore")+ try:+ tree = ast.parse(source)+ except SyntaxError as exc:+ raise UnparseableSource(f"{path.relative_to(_REPO)} cannot be parsed ({exc}).") from exc+ return [+ (node.lineno, node.name)+ for node in ast.walk(tree)+ if isinstance(node, ast.AsyncFunctionDef)+ and _is_route_handler(node)+ and not _body_awaits(node)+ ]+++def scan() -> dict[str, int]:+ """Per-file count of blocking async routes, keyed by repo-relative path."""+ counts: dict[str, int] = {}+ for path in sorted(_REPO.glob(_GLOB)):+ found = blocking_routes(path)+ if found:+ counts[path.relative_to(_REPO).as_posix()] = len(found)+ return counts+++def load_baseline() -> dict[str, int]:+ if not _BASELINE.exists():+ return {}+ return json.loads(_BASELINE.read_text(encoding="utf-8"))["files"]+++def save_baseline(counts: dict[str, int]) -> None:+ payload = {+ "_comment": (+ "Per-file count of async-def route handlers whose body never "+ "awaits - each one runs its disk I/O on the shared event loop. "+ "Generated by scripts/ci/check_async_routes.py --update. These "+ "numbers may go DOWN freely; an increase is a gate failure."+ ),+ "total": sum(counts.values()),+ "files": dict(sorted(counts.items())),+ }+ _BASELINE.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")+++def regressions(current: dict[str, int], baseline: dict[str, int]) -> dict[str, tuple[int, int]]:+ """Files that gained blocking routes, mapped to ``(baseline, current)``."""+ out: dict[str, tuple[int, int]] = {}+ for path, count in sorted(current.items()):+ was = baseline.get(path, 0)+ if count > was:+ out[path] = (was, count)+ return out+++def main() -> int:+ parser = argparse.ArgumentParser(description="Blocking-route ratchet.")+ parser.add_argument("--report", action="store_true", help="show the worst files, exit 0")+ parser.add_argument("--update", action="store_true", help="rewrite the baseline")+ parser.add_argument(+ "--allow-increase",+ action="store_true",+ help="with --update: permit a higher count (say why in the commit)",+ )+ args = parser.parse_args()++ current = scan()+ total = sum(current.values())++ if args.report:+ print(f"{total} blocking async routes across {len(current)} files.\n")+ for path, count in sorted(current.items(), key=lambda kv: -kv[1])[:25]:+ print(f" {count:4d} {path}")+ return 0++ baseline = load_baseline()++ if args.update:+ if baseline and not args.allow_increase:+ bad = regressions(current, baseline)+ if bad:+ print(f"Refusing to raise the baseline for {len(bad)} file(s):\n")+ for path, (was, now) in list(bad.items())[:20]:+ print(f" {path}: {was} -> {now}")+ print("\nDrop the handler's `async`, or pass --allow-increase deliberately.")+ return 1+ save_baseline(current)+ print(f"Baseline written: {total} blocking async routes across {len(current)} files.")+ return 0++ if not baseline:+ print("No baseline yet. Run with --update to create one.")+ return 1++ bad = regressions(current, baseline)+ if not bad:+ print(f"OK: no file gained a blocking async route (total {total}).")+ return 0++ print("New async routes that never await - their I/O blocks every other request:\n")+ for path, (was, now) in list(bad.items())[:20]:+ print(f" {path}: {was} -> {now}")+ print(+ "\nFix: drop the `async` - FastAPI runs a plain `def` handler in the "+ "anyio threadpool, off the shared event loop. Keep `async` only for a "+ "body that actually awaits.",+ )+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/unit/ui/web/test_assistant_name_route.py b/tests/unit/ui/web/test_assistant_name_route.pyindex 3764ac8749..b03380b469 100644--- a/tests/unit/ui/web/test_assistant_name_route.py+++ b/tests/unit/ui/web/test_assistant_name_route.py@@ -5,6 +5,9 @@ is populated. Resolving the name from a missing config would answer theneutral "Assistant" fallback, which the frontend persists into itslocalStorage name cache — freezing the wrong brand on every surface until asuccessful re-fetch. The route answers 503 instead, so the seed hook retries.++The handler is a plain ``def`` (threadpool route — it never awaits), so these+tests call it directly."""from __future__ import annotations@@ -20,17 +23,17 @@ def _request_with_config(cfg: object) -> SimpleNamespace:return SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(config=cfg, cfg=None)))-async def test_warmup_without_config_answers_503_not_a_fake_name() -> None:+def test_warmup_without_config_answers_503_not_a_fake_name() -> None:with pytest.raises(HTTPException) as excinfo:- await get_assistant_name(_request_with_config(None)) # type: ignore[arg-type]+ get_assistant_name(_request_with_config(None)) # type: ignore[arg-type]assert excinfo.value.status_code == 503-async def test_resolves_name_from_wake_phrase_when_config_present() -> None:+def test_resolves_name_from_wake_phrase_when_config_present() -> None:# Arbitrary pinned brand (never the host's live wake-word config).cfg = SimpleNamespace(trigger=SimpleNamespace(wake_word=SimpleNamespace(phrase="Hey Nova")))- payload = await get_assistant_name(_request_with_config(cfg)) # type: ignore[arg-type]+ payload = get_assistant_name(_request_with_config(cfg)) # type: ignore[arg-type]assert payload["resolved"] == "Nova"assert payload["default"] == "Assistant"diff --git a/tests/unit/ui/web/test_check_async_routes.py b/tests/unit/ui/web/test_check_async_routes.pynew file mode 100644index 0000000000..097501ef90--- /dev/null+++ b/tests/unit/ui/web/test_check_async_routes.py@@ -0,0 +1,71 @@+"""The blocking-route ratchet: what counts, what does not, how it ratchets."""++from __future__ import annotations++import importlib.util+import sys+from pathlib import Path++_GATE = Path(__file__).resolve().parents[4] / "scripts" / "ci" / "check_async_routes.py"+_spec = importlib.util.spec_from_file_location("check_async_routes", _GATE)+assert _spec is not None and _spec.loader is not None+gate = importlib.util.module_from_spec(_spec)+sys.modules.setdefault("check_async_routes", gate)+_spec.loader.exec_module(gate)+++def _routes(tmp_path: Path, source: str) -> list[tuple[int, str]]:+ path = tmp_path / "x_routes.py"+ path.write_text(source, encoding="utf-8")+ return gate.blocking_routes(path)+++def test_an_async_route_with_no_await_is_counted(tmp_path: Path) -> None:+ found = _routes(+ tmp_path,+ "@router.get('/a')\nasync def a():\n return open('f').read()\n",+ )+ assert [name for _line, name in found] == ["a"]+++def test_awaiting_async_iterating_and_streaming_routes_pass(tmp_path: Path) -> None:+ source = (+ "@router.get('/a')\nasync def a():\n await x()\n"+ "@router.websocket('/w')\nasync def w(ws):\n async for m in ws:\n pass\n"+ "@router.get('/s')\nasync def s():\n yield b''\n"+ "@router.post('/c')\nasync def c():\n async with x():\n pass\n"+ )+ assert _routes(tmp_path, source) == []+++def test_a_plain_def_route_is_not_this_gates_business(tmp_path: Path) -> None:+ assert _routes(tmp_path, "@router.get('/a')\ndef a():\n return 1\n") == []+++def test_an_undecorated_async_helper_is_not_counted(tmp_path: Path) -> None:+ assert _routes(tmp_path, "async def helper():\n return 1\n") == []+++def test_an_await_inside_a_nested_helper_does_not_excuse_the_handler(+ tmp_path: Path,+) -> None:+ source = (+ "@router.get('/a')\n"+ "async def a():\n"+ " async def inner():\n"+ " await x()\n"+ " return 1\n"+ )+ assert [name for _line, name in _routes(tmp_path, source)] == ["a"]+++def test_the_ratchet_flags_growth_and_tolerates_shrinkage() -> None:+ baseline = {"a.py": 3, "b.py": 1}+ current = {"a.py": 4, "b.py": 0, "c.py": 1}+ assert gate.regressions(current, baseline) == {"a.py": (3, 4), "c.py": (0, 1)}+ assert gate.regressions({"a.py": 2}, baseline) == {}+++def test_the_live_tree_is_within_its_baseline() -> None:+ """The real gate, run as a test: no file may exceed its recorded count."""+ assert gate.regressions(gate.scan(), gate.load_baseline()) == {}