Skip to content

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

fix(boot): keep the event loop answerable through a cold-boot start storm

rubenluetke10-beepae47a80d24b1
diff --git a/docs/BUGS.md b/docs/BUGS.md
index f97b193070..1802245c5f 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -13196,3 +13196,95 @@ picker lived behind a "Change" button, two clicks from the row.
later, so it may be returned but never stored. And a control whose options
come from a filtered list needs an answer for the empty case: offering one
option is indistinguishable, to the person using it, from ignoring the click.
+
+## BUG-189: the desktop app hung in every section and sometimes did not paint at all for the first minutes after a cold Windows boot — the event loop was stopped for 15 s at a time behind an SDK import and a thread start (HIGH, FIXED 2026-08-27)
+
+**Symptom.** Windows booted at 09:57:21, Jarvis auto-started at 09:58:34.
+Every section hung, views did not render, clicks and keystrokes went
+nowhere, the machine felt stuck; the maintainer quit at 10:06 and relaunched,
+and the second boot was fine. The log of the first boot, side by side with
+the second: wake-word ready after 54.3 s (7.6 s), the German Vosk model
+loaded in 18.5 s (0.7 s), Vertex credentials in 26.6 s (2.1 s), the
+voice-ready watchdog fired at 45 s, 14 of 22 CLI probes were still running
+at the 44 s sweep ceiling, the mic capture thread starved (`Mic stall
+detected (6.4s without a frame)`, `5.0s of audio never reached the
+recording`), the WebView's own UI thread stalled for 3 s — and twice
+`Event loop STALLED for 15.0s — every WebSocket, HTTP route and brain turn
+is blocked behind this call`.
+
+**Root cause.** A cold OS boot (empty disk cache, Windows still starting
+its own autostart) met the app's own start storm: 22 CLI probes at once
+(up to 44 child processes), the agent chat's provider health sweep with a
+live one-token request per provider, Ollama plus a 9B model, three MCP
+servers, the wake models, Vertex ADC — and then the Agentic IDE resuming
+ten coding-CLI panes within two seconds (eight `claude.exe`, each reading a
+session transcript and starting its MCP servers), six more at 10:05. Under
+that load two things blocked the ONE thread that answers every click:
+
+1. `claude_api._ensure_client` ran `from anthropic import AsyncAnthropic` —
+ pydantic model generation for a few hundred types — synchronously inside
+ `complete()`, on the event loop, on a cold disk: 15 s. The same lazy
+ import sits in every OpenAI-shaped plugin, and `provider_registry._load`
+ (entry-point discovery that imports EVERY plugin) had the same shape in a
+ stall stack the day before. Reached from the agent chat's boot-time
+ health sweep and from the wiki extractor.
+2. A synchronous FastAPI route went through Starlette's
+ `run_in_threadpool` → `anyio.to_thread.run_sync` → `WorkerThread.start()`
+ → `Thread.start()` waits for the new thread to be scheduled: 15 s on a
+ starved box. anyio grows its pool on the calling thread — the loop —
+ exactly as CPython's default executor did before `loop_executor.py`
+ (2026-07-29), and its workers RETIRE after ten idle seconds, so the pool
+ was empty again by the time the user clicked.
+
+The second boot was warm: nothing to page in, no import to run, no thread
+to start — which is why "it works now" told nobody anything.
+
+**Fix.**
+
+* `jarvis/plugins/brain/{claude_api,openai,grok,openrouter,nvidia,ollama,local_openai}.py`
+ — `complete()` builds the client on a worker thread the first time
+ (`asyncio.to_thread(self._ensure_client)`); the SDK import and the
+ credential read never run on the loop.
+* `jarvis/brain/healthcheck.py` — `probe()` instantiates the provider off
+ the loop, which also moves the registry's plugin imports there.
+* `jarvis/core/loop_executor.py` — `keep_anyio_workers_alive()` stops
+ anyio's workers from retiring (guarded on the backend's shape; a no-op on
+ an unfamiliar anyio), `warm_anyio_worker_pool()` brings eight up at a
+ calm moment. `jarvis/ui/web/server.py` applies the keep-alive when the
+ app is built and warms the pool five seconds after voice reports ready
+ (or at the end of the deferred phase when voice is off).
+* `jarvis/clis/prober.py` — `probe_all` runs `PROBE_CONCURRENCY` (6) probes
+ at a time; the partial-result contract is unchanged.
+* `jarvis/agentic_ide/session.py` — a cold-start slot is held until the
+ pane paints its input line (`fleet_actions.wait_for_input_line`, the bare
+ observation without Claude Code's typing opt-out) or
+ `COLD_START_HOLD_MAX_S` (15 s), with `COLD_START_SETTLE_S` as the floor.
+ A fixed 1.2 s let eight resumes pile into two seconds.
+* `jarvis/ui/web/server.py` — the SPA index route decides between index
+ and holding page off the loop (it reads `index.html` and stats every
+ asset; it was in a stall stack on 2026-08-26).
+* Side find, same log: `jarvis/telemetry/recorder.py` serializes a string
+ `trace_id` instead of raising `'str' object has no attribute 'hex'` on
+ every dictation.
+
+**Regression tests.**
+`tests/unit/brain/test_healthcheck_off_loop.py`,
+`tests/unit/core/test_loop_executor_anyio.py`,
+`tests/unit/clis/test_prober_concurrency.py`,
+`tests/unit/agentic_ide/test_cold_start_gate.py::test_a_slot_is_held_until_the_pane_paints_its_input_line`,
+`::test_a_pane_that_never_paints_an_input_line_holds_its_slot_only_to_the_ceiling`,
+`tests/unit/telemetry/test_recorder_trace_id.py`.
+
+**Forensics.** `grep -n "Event loop STALLED" data/jarvis_desktop.log` and
+the stack under it name the blocking call; `wake-start=` in the "Warm-up
+Phase A" line is the boot-health number (3–8 s warm, 20–55 s means the box
+was starved); `Get-CimInstance Win32_OperatingSystem` `LastBootUpTime`
+tells whether it was a cold OS boot.
+
+**Lesson.** A lazy `import` inside an `async def` is a synchronous call on
+the event loop, and the first one in a process is not cheap. Every pool
+that grows by `Thread.start()` grows on the thread that asks — the asyncio
+executor was fixed once; anyio's was the same bug one layer over. And a
+gate that releases on a timer gates only what fits in the timer: the honest
+end of a cold start is the CLI's own input line.
+
diff --git a/jarvis/agentic_ide/fleet_actions.py b/jarvis/agentic_ide/fleet_actions.py
index 72e62b9004..4e4585bd42 100644
--- a/jarvis/agentic_ide/fleet_actions.py
+++ b/jarvis/agentic_ide/fleet_actions.py
@@ -35,6 +35,24 @@ def ready_for_prompt(term: Any) -> bool:
spec = workspace_agents.get_agent(getattr(term, "agent", ""))
if spec is not None and not spec.needs_input_line_wait:
return True
+ return input_line_visible(term, spec)
+
+
+def input_line_visible(term: Any, spec: Any | None = None) -> bool:
+ """Does the bottom of this pane's screen show the CLI's input line?
+
+ The bare observation, without :func:`ready_for_prompt`'s opt-out. A CLI
+ that safely accepts typed text before it has painted its composer is
+ still LOADING until the composer is there — and "has it finished loading"
+ is the question a cold-start slot asks, whatever the CLI's typing policy
+ (BUG-189). ``spec`` may be passed in to save the registry lookup.
+ """
+ if getattr(term, "status", "") != "live" or not getattr(term, "pty_id", None):
+ return False
+ if spec is None:
+ from jarvis.workspace import agents as workspace_agents
+
+ spec = workspace_agents.get_agent(getattr(term, "agent", ""))
transcript = getattr(term, "transcript", None)
if transcript is None:
return False
@@ -83,13 +101,34 @@ async def wait_for_prompt_ready(
timeout_s: float = READY_TIMEOUT_S,
) -> tuple[str, ...]:
"""Wait for newly mounted panes to display their real input line."""
+ return await _wait_for_panes(session, names, ready_for_prompt, timeout_s=timeout_s)
+
+
+async def wait_for_input_line(
+ session: Any,
+ names: Sequence[str],
+ *,
+ timeout_s: float = READY_TIMEOUT_S,
+) -> tuple[str, ...]:
+ """Wait for panes to paint their input line — loading done, whatever the
+ CLI's typing policy (see :func:`input_line_visible`)."""
+ return await _wait_for_panes(session, names, input_line_visible, timeout_s=timeout_s)
+
+
+async def _wait_for_panes(
+ session: Any,
+ names: Sequence[str],
+ predicate: Any,
+ *,
+ timeout_s: float,
+) -> tuple[str, ...]:
wanted = tuple(dict.fromkeys(name for name in names if name))
deadline = time.monotonic() + max(0.0, timeout_s)
while True:
ready = tuple(
name
for name in wanted
- if (term := session.find(name)) is not None and ready_for_prompt(term)
+ if (term := session.find(name)) is not None and predicate(term)
)
if len(ready) == len(wanted) or time.monotonic() >= deadline:
return ready
@@ -138,7 +177,9 @@ __all__ = [
"READY_POLL_S",
"READY_TIMEOUT_S",
"close_agent_terminals",
+ "input_line_visible",
"ready_for_prompt",
"terminals_closed_event",
+ "wait_for_input_line",
"wait_for_prompt_ready",
]
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index 179de07721..a4467fb172 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -67,7 +67,7 @@ import re
import shutil
import sys
import time
-from collections.abc import AsyncIterator
+from collections.abc import AsyncIterator, Awaitable, Callable
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
from pathlib import Path
@@ -385,7 +385,18 @@ COLD_START_LIMIT = max(2, (os.cpu_count() or 4) // 4)
# releasing the slot on spawn would let the whole grid pile into the same second
# regardless of the limit. Roughly the length of a CLI's own boot burst; long
# enough to stagger, short enough that nobody watches a spinner for it.
+#
+# That is the FLOOR. The slot is actually held until the pane shows its input
+# line — the moment the CLI has finished loading — or until COLD_START_HOLD_MAX_S,
+# whichever comes first. A fixed second was the whole gate on a machine that
+# had booted a minute earlier: eight resumed Claude Code panes went from
+# "spawned" to "loading" within two seconds of each other, each one reading a
+# session transcript and starting its MCP servers off a cold disk, and the app
+# stalled behind them (2026-08-27, BUG-189). The input line is the honest end
+# of a cold start; the ceiling keeps a CLI stopped on a login or trust screen
+# from holding everyone else's slot.
COLD_START_SETTLE_S = 1.2
+COLD_START_HOLD_MAX_S = 15.0
# How long the nudged window size is held before it is put back (see
# ``_nudge_repaint``). A PTY carries one size, not a queue of them: set twice
@@ -1735,6 +1746,11 @@ class Registry:
# limit; separate accounts get separate gates, and CLIs with no limit
# never touch this path.
self._agent_cold_starts: dict[tuple[str, str], asyncio.Semaphore] = {}
+ # The tasks holding a cold-start slot open until a pane's input line
+ # appears (see ``_cold_start_slot``). asyncio keeps only weak
+ # references to tasks; without this set a hold could be collected
+ # mid-wait and its slot never given back.
+ self._cold_start_holds: set[asyncio.Task[None]] = set()
# ---------------------------------------------------------------- state
@property
@@ -2636,7 +2652,9 @@ class Registry:
return None if term is None else (session, term)
@asynccontextmanager
- async def _cold_start_slot(self) -> AsyncIterator[None]:
+ async def _cold_start_slot(
+ self, ready: Callable[[], Awaitable[bool]] | None = None
+ ) -> AsyncIterator[None]:
"""Hold one of the few slots for starting an agent CLI.
Waiting here is what turns "open a workspace" from a burst that pins
@@ -2646,12 +2664,15 @@ class Registry:
an agent already running is never made to wait behind one that is
booting.
- The slot is released a moment AFTER the block, not at its end. What
- costs is the CLI loading itself and its servers, and by then ``spawn``
- has returned; releasing immediately would let the whole grid through in
- the same instant and the limit would gate nothing. A spawn that FAILED
- releases at once — nothing is loading, and a broken pane must not hold
- up the ones behind it.
+ The slot is released AFTER the block, not at its end. What costs is
+ the CLI loading itself and its servers, and by then ``spawn`` has
+ returned; releasing immediately would let the whole grid through in
+ the same instant and the limit would gate nothing. So the slot stays
+ taken for at least ``COLD_START_SETTLE_S``, and then until ``ready``
+ — the pane's input line, when the caller can name it — answers or
+ ``COLD_START_HOLD_MAX_S`` runs out. A spawn that FAILED releases at
+ once: nothing is loading, and a broken pane must not hold up the ones
+ behind it.
"""
gate = self._cold_start
if gate is None:
@@ -2665,10 +2686,63 @@ class Registry:
started = True
finally:
if started:
- asyncio.get_running_loop().call_later(COLD_START_SETTLE_S, gate.release)
+ self._hold_cold_start_slot(gate, ready)
else:
gate.release()
+ def _hold_cold_start_slot(
+ self, gate: asyncio.Semaphore, ready: Callable[[], Awaitable[bool]] | None
+ ) -> None:
+ """Give ``gate`` back once the started pane has finished loading.
+
+ Runs as a task of its own so the attach that started the pane returns
+ at once — the viewer connects to a booting CLI exactly as before; only
+ the NEXT cold start waits. Whatever happens in here, the slot comes
+ back: a readiness check that raises or is cancelled releases in the
+ ``finally``, and the ceiling bounds the wait for a CLI that never
+ shows an input line (login, trust prompt, an unknown future screen).
+ """
+
+ async def _hold() -> None:
+ try:
+ await asyncio.sleep(COLD_START_SETTLE_S)
+ remaining = COLD_START_HOLD_MAX_S - COLD_START_SETTLE_S
+ if ready is not None and remaining > 0:
+ try:
+ await asyncio.wait_for(ready(), timeout=remaining)
+ except TimeoutError:
+ # The ceiling IS the release. The pane's own readiness
+ # wait reports a CLI that never showed its input line.
+ pass
+ except Exception: # noqa: BLE001 — a probe that cannot read
+ # the screen must not keep a slot; log, release.
+ logger.debug(
+ "Agentic IDE: cold-start readiness check failed; "
+ "releasing the slot",
+ exc_info=True,
+ )
+ finally:
+ gate.release()
+
+ task = asyncio.get_running_loop().create_task(_hold(), name="cold-start-hold")
+ self._cold_start_holds.add(task)
+ task.add_done_callback(self._cold_start_holds.discard)
+
+ async def _prompt_ready(self, session: Session, term: Terminal) -> bool:
+ """Has this pane painted its input line yet? Waits, bounded.
+
+ The input line, not ``ready_for_prompt``: Claude Code opts out of the
+ typing wait because typing early is safe with it — but its composer
+ still appears only once it has loaded, and loading is what the slot
+ is for.
+ """
+ from . import fleet_actions
+
+ ready = await fleet_actions.wait_for_input_line(
+ session, [term.name], timeout_s=COLD_START_HOLD_MAX_S
+ )
+ return term.name in ready
+
async def _acquire_agent_cold_start(self, term: Terminal) -> asyncio.Semaphore | None:
"""Take this CLI/account's boot slot when its registry entry needs one.
@@ -3136,8 +3210,9 @@ class Registry:
agent_start_gate = await self._acquire_agent_cold_start(term)
spawn_succeeded = False
try:
- # One of a few starts at a time (see COLD_START_LIMIT).
- async with self._cold_start_slot():
+ # One of a few starts at a time (see COLD_START_LIMIT), and the
+ # slot stays taken until this pane's input line appears.
+ async with self._cold_start_slot(ready=lambda: self._prompt_ready(session, term)):
try:
pty_session = await manager.spawn(
shell_argv=argv,
diff --git a/jarvis/brain/healthcheck.py b/jarvis/brain/healthcheck.py
index 8d4a64d353..f6d90f1bfa 100644
--- a/jarvis/brain/healthcheck.py
+++ b/jarvis/brain/healthcheck.py
@@ -66,7 +66,13 @@ class BrainHealthChecker:
"""Calls the provider with a 1-token prompt and measures latency."""
start = time.perf_counter()
try:
- brain = self._registry.instantiate(provider, model=model)
+ # Off the loop. Instantiating means the registry's entry-point
+ # discovery — which IMPORTS every brain plugin the first time — and
+ # the plugin's constructor. On a cold disk that import ran for
+ # 15 s ON the event loop while a health sweep probed the providers
+ # at boot (2026-08-26 and 2026-08-27, BUG-189), and every WebSocket
+ # frame, HTTP route and brain turn stood still behind it.
+ brain = await asyncio.to_thread(self._registry.instantiate, provider, model=model)
except Exception as exc: # noqa: BLE001
duration_ms = (time.perf_counter() - start) * 1000.0
return HealthResult(
diff --git a/jarvis/clis/prober.py b/jarvis/clis/prober.py
index e4ca1318c5..0dcf4af1b5 100644
--- a/jarvis/clis/prober.py
+++ b/jarvis/clis/prober.py
@@ -45,6 +45,16 @@ KILL_WAIT_TIMEOUT_S = 2.0
# normal operation instead of acting as a backstop (see BUG: the 30s registry
# ceiling blanked all 22 CLIs on 2026-07-25).
PROBE_ALL_TIMEOUT_S = CHECK_TIMEOUT_S + AUTH_TIMEOUT_S + 2 * KILL_WAIT_TIMEOUT_S + 15.0
+# How many catalog probes run at once. Every probe is up to two child
+# processes (the binary check, then the auth check), and most of the catalog
+# is a Node or Python CLI that spends a second of CPU just printing its
+# version. All 22 at once on a machine that had booted a minute earlier meant
+# forty interpreter starts inside a second, while the wake-word models were
+# still loading off a cold disk — 14 probes were still running at the sweep
+# ceiling and the app's own event loop stalled behind the load (2026-08-27,
+# BUG-189). Six lanes keep a calm sweep under ten seconds and turn the
+# cold-boot burst into a queue.
+PROBE_CONCURRENCY = 6
class CliStatusProber:
@@ -82,7 +92,13 @@ class CliStatusProber:
"""
if not specs:
return {}
- tasks = [asyncio.ensure_future(self.probe(spec)) for spec in specs]
+ lanes = asyncio.Semaphore(PROBE_CONCURRENCY)
+
+ async def _gated(spec: CliSpec) -> CliStatus:
+ async with lanes:
+ return await self.probe(spec)
+
+ tasks = [asyncio.ensure_future(_gated(spec)) for spec in specs]
await asyncio.wait(tasks, timeout=PROBE_ALL_TIMEOUT_S)
out: dict[str, CliStatus] = {}
diff --git a/jarvis/core/loop_executor.py b/jarvis/core/loop_executor.py
index 7eedf40808..ad8a51bccc 100644
--- a/jarvis/core/loop_executor.py
+++ b/jarvis/core/loop_executor.py
@@ -38,6 +38,7 @@ running, and the app stays answerable.
from __future__ import annotations
+import asyncio
import logging
import os
import threading
@@ -121,10 +122,103 @@ def install_prewarmed_default_executor(loop, *, workers: int | None = None):
return pool
+# --------------------------------------------------------------- anyio's pool
+#
+# The asyncio executor above is not the only pool that grows on the loop.
+# Starlette runs every synchronous (``def``) route through
+# ``anyio.to_thread.run_sync``, and anyio's pool does exactly what CPython's
+# did: with no idle worker it calls ``Thread.start()`` on the calling thread —
+# the event loop. Worse, its workers RETIRE after ten idle seconds, so a quiet
+# minute empties the pool and the next click pays the start again. Measured
+# 2026-08-27 on a host that was still cold-booting (BUG-189)::
+#
+# starlette/concurrency.py:34 run_in_threadpool
+# anyio/to_thread.py:63 run_sync
+# anyio/_backends/_asyncio.py:2560 run_sync_in_worker_thread
+# threading.py:999 Thread.start
+# threading.py:655 wait <-- 15.0 s
+#
+# Two halves, same shape as above: workers that never retire, and a warm-up
+# that brings a few of them up at a moment nobody is waiting on.
+
+#: How long anyio keeps an idle worker once :func:`keep_anyio_workers_alive`
+#: ran — effectively for the life of the loop. anyio only prunes idle workers
+#: when it hands out the next job, and a pruned worker is a ``Thread.start()``
+#: on the loop later.
+ANYIO_KEEP_ALIVE_S = 10 * 365 * 24 * 3600
+
+#: How many anyio workers :func:`warm_anyio_worker_pool` brings up. Sync routes
+#: burst in handfuls (a section mounting asks for its settings, its lists and
+#: its status at once); eight resident threads cover a burst without a start.
+ANYIO_WARM_WORKERS = 8
+
+
+def keep_anyio_workers_alive() -> bool:
+ """Stop anyio's thread pool from shrinking between bursts.
+
+ Process-wide and idempotent. Returns ``False`` — touching nothing — when
+ anyio's backend does not look like the one this relies on, so an anyio
+ release that reshapes its pool degrades to the old behaviour, never to a
+ crash on boot.
+ """
+ try:
+ from anyio._backends._asyncio import WorkerThread
+ except Exception: # noqa: BLE001 — no such backend module: keep anyio's own policy
+ log.debug("anyio worker keep-alive not applied: backend module unavailable")
+ return False
+ if not isinstance(getattr(WorkerThread, "MAX_IDLE_TIME", None), int | float):
+ log.debug("anyio worker keep-alive not applied: WorkerThread has no MAX_IDLE_TIME")
+ return False
+ WorkerThread.MAX_IDLE_TIME = ANYIO_KEEP_ALIVE_S
+ return True
+
+
+async def warm_anyio_worker_pool(workers: int = ANYIO_WARM_WORKERS) -> int:
+ """Bring ``workers`` anyio threads up now, while nobody is clicking.
+
+ Each start still happens on the loop — anyio leaves no other way — which
+ is why this belongs at a calm moment AFTER boot (the voice pipeline
+ reporting ready), never on the boot path. The calls park on one shared
+ gate so anyio cannot serve them with a single worker; the gate opens once
+ every one of them is running. Returns how many workers actually arrived.
+ """
+ import anyio.to_thread
+
+ loop = asyncio.get_running_loop()
+ gate = threading.Event()
+ all_up = asyncio.Event()
+ lock = threading.Lock()
+ arrived = 0
+
+ def _park() -> None:
+ nonlocal arrived
+ with lock:
+ arrived += 1
+ complete = arrived >= workers
+ if complete:
+ loop.call_soon_threadsafe(all_up.set)
+ gate.wait(_PREWARM_TIMEOUT_S)
+
+ tasks = [asyncio.ensure_future(anyio.to_thread.run_sync(_park)) for _ in range(workers)]
+ try:
+ await asyncio.wait_for(all_up.wait(), timeout=_PREWARM_TIMEOUT_S)
+ except TimeoutError:
+ log.debug("anyio pool warm-up: only %d of %d workers arrived in time", arrived, workers)
+ finally:
+ gate.set()
+ await asyncio.gather(*tasks, return_exceptions=True)
+ log.debug("anyio worker pool warmed: %d thread(s) resident", arrived)
+ return arrived
+
+
__all__ = [
+ "ANYIO_KEEP_ALIVE_S",
+ "ANYIO_WARM_WORKERS",
"MAX_WORKERS",
"MIN_WORKERS",
"default_worker_count",
"install_prewarmed_default_executor",
+ "keep_anyio_workers_alive",
"prewarm",
+ "warm_anyio_worker_pool",
]
diff --git a/jarvis/plugins/brain/claude_api.py b/jarvis/plugins/brain/claude_api.py
index 930b4e38ff..dcd983dd62 100644
--- a/jarvis/plugins/brain/claude_api.py
+++ b/jarvis/plugins/brain/claude_api.py
@@ -4,6 +4,7 @@ Keyring/ENV: `anthropic_api_key` / `ANTHROPIC_API_KEY`.
"""
from __future__ import annotations
+import asyncio
from collections.abc import AsyncIterator
from typing import Any
@@ -44,7 +45,14 @@ class ClaudeAPIBrain:
return self._client
async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
- client = self._ensure_client()
+ client = self._client
+ if client is None:
+ # The first call imports the SDK (pydantic model generation for a
+ # few hundred types) and reads the credential store. Done ON the
+ # event loop, that import ran for 15 s on a cold disk and stopped
+ # every WebSocket, route and turn with it (2026-08-27, BUG-189) —
+ # so the one-time construction happens on a worker thread.
+ client = await asyncio.to_thread(self._ensure_client)
async for delta in stream_complete(client, self._model, req):
yield delta
diff --git a/jarvis/plugins/brain/grok.py b/jarvis/plugins/brain/grok.py
index b7aad0c531..02a18a2a20 100644
--- a/jarvis/plugins/brain/grok.py
+++ b/jarvis/plugins/brain/grok.py
@@ -1,6 +1,7 @@
"""xAI Grok brain over its OpenAI-compatible API."""
from __future__ import annotations
+import asyncio
from collections.abc import AsyncIterator
from typing import Any
@@ -49,7 +50,11 @@ class GrokBrain:
return self._client
async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
- client = self._ensure_client()
+ client = self._client
+ if client is None:
+ # First use imports the SDK — seconds on a cold disk, and never on
+ # the event loop (BUG-189; see claude_api.py for the measurement).
+ client = await asyncio.to_thread(self._ensure_client)
async for delta in stream_complete(
client,
self._model,
diff --git a/jarvis/plugins/brain/local_openai.py b/jarvis/plugins/brain/local_openai.py
index c941823272..4c2d776d46 100644
--- a/jarvis/plugins/brain/local_openai.py
+++ b/jarvis/plugins/brain/local_openai.py
@@ -28,6 +28,7 @@ looked at is the failure mode worth being conservative about.
from __future__ import annotations
+import asyncio
import logging
from collections.abc import AsyncIterator
from typing import Any
@@ -151,7 +152,11 @@ class LocalOpenAIBrain:
return self._model
async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
- client = self._ensure_client()
+ client = self._client
+ if client is None:
+ # First use imports the SDK — seconds on a cold disk, and never on
+ # the event loop (BUG-189; see claude_api.py for the measurement).
+ client = await asyncio.to_thread(self._ensure_client)
model = await self._resolve_model()
async for delta in stream_complete(
client, model, req, supports_vision=self.supports_vision
diff --git a/jarvis/plugins/brain/nvidia.py b/jarvis/plugins/brain/nvidia.py
index d0103b8c5e..bc3896a9b0 100644
--- a/jarvis/plugins/brain/nvidia.py
+++ b/jarvis/plugins/brain/nvidia.py
@@ -13,6 +13,7 @@ user actually has, and the model id comes from the user's pick (the live
"""
from __future__ import annotations
+import asyncio
from collections.abc import AsyncIterator
from typing import Any
@@ -80,7 +81,11 @@ class NvidiaBrain:
return self._client
async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
- client = self._ensure_client()
+ client = self._client
+ if client is None:
+ # First use imports the SDK — seconds on a cold disk, and never on
+ # the event loop (BUG-189; see claude_api.py for the measurement).
+ client = await asyncio.to_thread(self._ensure_client)
async for delta in stream_complete(client, self._model, req):
yield delta
diff --git a/jarvis/plugins/brain/ollama.py b/jarvis/plugins/brain/ollama.py
index adb8e3347a..388485eeb0 100644
--- a/jarvis/plugins/brain/ollama.py
+++ b/jarvis/plugins/brain/ollama.py
@@ -34,6 +34,7 @@ one raises an honest error instead of describing a screenshot blind.
from __future__ import annotations
+import asyncio
import logging
import os
from collections.abc import AsyncIterator
@@ -322,7 +323,11 @@ class OllamaBrain:
return caps is not None and "vision" in caps
async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
- client = self._ensure_client()
+ client = self._client
+ if client is None:
+ # First use imports the SDK — seconds on a cold disk, and never on
+ # the event loop (BUG-189; see claude_api.py for the measurement).
+ client = await asyncio.to_thread(self._ensure_client)
need_vision = _request_has_images(req)
model = await self._resolve_model(need_tools=bool(req.tools), need_vision=need_vision)
if need_vision and self._model and not await self._pinned_model_can_see(model):
diff --git a/jarvis/plugins/brain/openai.py b/jarvis/plugins/brain/openai.py
index b2858259c9..762391b0c1 100644
--- a/jarvis/plugins/brain/openai.py
+++ b/jarvis/plugins/brain/openai.py
@@ -1,6 +1,7 @@
"""OpenAI GPT Brain (direct API)."""
from __future__ import annotations
+import asyncio
from collections.abc import AsyncIterator
from typing import Any
@@ -35,7 +36,11 @@ class OpenAIBrain:
return self._client
async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
- client = self._ensure_client()
+ client = self._client
+ if client is None:
+ # First use imports the SDK — seconds on a cold disk, and never on
+ # the event loop (BUG-189; see claude_api.py for the measurement).
+ client = await asyncio.to_thread(self._ensure_client)
async for delta in stream_complete(client, self._model, req):
yield delta
diff --git a/jarvis/plugins/brain/openrouter.py b/jarvis/plugins/brain/openrouter.py
index 584133f954..cc8edad634 100644
--- a/jarvis/plugins/brain/openrouter.py
+++ b/jarvis/plugins/brain/openrouter.py
@@ -5,6 +5,7 @@ Model names are namespaced ("anthropic/claude-opus-4.7", "openai/gpt-5").
"""
from __future__ import annotations
+import asyncio
from collections.abc import AsyncIterator
from dataclasses import replace
from typing import Any
@@ -73,7 +74,11 @@ class OpenRouterBrain:
return self._client
async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
- client = self._ensure_client()
+ client = self._client
+ if client is None:
+ # First use imports the SDK — seconds on a cold disk, and never on
+ # the event loop (BUG-189; see claude_api.py for the measurement).
+ client = await asyncio.to_thread(self._ensure_client)
extra_body: dict[str, Any] | None = None
if getattr(req, "reasoning_effort", None) == "none":
# OpenRouter's unified ``reasoning`` parameter: ask the gateway to
diff --git a/jarvis/telemetry/recorder.py b/jarvis/telemetry/recorder.py
index 3a6dc1415a..27a34b15ed 100644
--- a/jarvis/telemetry/recorder.py
+++ b/jarvis/telemetry/recorder.py
@@ -118,9 +118,14 @@ class FlightRecorder:
def _serialize_event(self, event: Event) -> str:
data = dataclasses.asdict(event)
+ # The contract says UUID, but this is a wildcard observer of EVERY
+ # event, and a publisher that hands over a string trace id must cost
+ # telemetry one line, not the event: ``.hex`` on a str raised here on
+ # every dictation (2026-08-27) and the recorder dropped the event.
+ trace_id = event.trace_id
top: dict[str, Any] = {
"ts_ns": data.pop("timestamp_ns"),
- "trace_id": event.trace_id.hex,
+ "trace_id": trace_id.hex if isinstance(trace_id, UUID) else str(trace_id),
"event": type(event).__name__,
"layer": data.pop("source_layer", ""),
}
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 4a83c7be18..f2332565c5 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -647,10 +647,21 @@ class WebServer:
)
self._voice_ready = _voice_disabled
+ # Synchronous routes run on anyio's thread pool, which grows ON the
+ # loop and shrinks after ten idle seconds — a start that blocked the
+ # loop for 15 s on 2026-08-27 (BUG-189). Workers stay resident from
+ # here on; a handful is brought up once voice reports ready, below.
+ from jarvis.core.loop_executor import keep_anyio_workers_alive
+
+ keep_anyio_workers_alive()
+ self._anyio_pool_warmed = False
+
async def _track_voice_ready(event: VoiceBootStatus) -> None:
# A bus subscriber must never raise (AP-18); setting a plain
- # instance bool cannot fail.
+ # instance bool cannot fail, and the warm-up below only schedules.
self._voice_ready = bool(event.ready)
+ if event.ready:
+ self._schedule_anyio_pool_warm()
self.bus.subscribe(VoiceBootStatus, _track_voice_ready)
@@ -665,6 +676,37 @@ class WebServer:
return app
+ #: Breathing room between "voice is ready" and bringing anyio's workers
+ #: up. Ready is the end of the heavy boot work, not of the box's — the
+ #: wake models have just loaded and the frontend is still mounting.
+ _ANYIO_WARM_DELAY_S = 5.0
+
+ def _schedule_anyio_pool_warm(self) -> None:
+ """Bring a few anyio workers up, once, at the first calm moment.
+
+ Every start happens on the loop (anyio leaves no other way), so the
+ one place to pay for it is right after boot, before the first click —
+ never on the boot path itself (AP-26). Idempotent: the ready event
+ can arrive more than once (warm-up, then the watchdog).
+ """
+ if self._anyio_pool_warmed:
+ return
+ self._anyio_pool_warmed = True
+
+ async def _warm() -> None:
+ from jarvis.core.loop_executor import warm_anyio_worker_pool
+
+ try:
+ await asyncio.sleep(self._ANYIO_WARM_DELAY_S)
+ resident = await warm_anyio_worker_pool()
+ except Exception as exc: # noqa: BLE001 — a pool that grows lazily is
+ # yesterday's behaviour, not a boot failure
+ logger.opt(exception=exc).debug("anyio pool warm-up did not complete")
+ return
+ logger.info("anyio worker pool warmed: {} thread(s) resident", resident)
+
+ asyncio.create_task(_warm(), name="anyio-pool-warm")
+
async def _voice_ready_watchdog(self, deadline_s: float = 45.0) -> None:
"""Guarantee the UI never hangs on "starting up" forever.
@@ -2044,7 +2086,11 @@ class WebServer:
@app.get("/", include_in_schema=False, response_model=None)
async def _spa_root() -> FileResponse | HTMLResponse:
- return self._spa_index_response()
+ # Off the loop: deciding between the index and the holding page
+ # reads index.html and stats every asset it references. On a disk
+ # that is busy paging in a cold boot that took long enough to show
+ # up in a loop-stall stack (2026-08-26, BUG-189).
+ return await asyncio.to_thread(self._spa_index_response)
@app.get("/{full_path:path}", include_in_schema=False, response_model=None)
async def _spa_fallback(
@@ -2065,7 +2111,7 @@ class WebServer:
# success and never retries (sidebar-logo regression, 2026-07-18).
if PurePosixPath(full_path).suffix.lower() in ASSET_SUFFIXES:
return JSONResponse({"detail": "Not Found"}, status_code=404)
- return self._spa_index_response()
+ return await asyncio.to_thread(self._spa_index_response)
def _spa_index_response(self) -> FileResponse | HTMLResponse:
# An index.html whose own entry bundle is not on disk is worse than no
@@ -2439,6 +2485,10 @@ class WebServer:
self._voice_ready_watchdog_task = asyncio.create_task(
self._voice_ready_watchdog(), name="voice-ready-watchdog"
)
+ else:
+ # Voice is off, so no ready event will ever arrive to trigger
+ # this; the end of the deferred phase is the calm moment instead.
+ self._schedule_anyio_pool_warm()
# Phase-6 mission stack — MissionManager with a DB path derived from
# the config's memory data_dir (same folder as data/jarvis.db, its
diff --git a/tests/unit/agentic_ide/test_cold_start_gate.py b/tests/unit/agentic_ide/test_cold_start_gate.py
index 817e5d8498..d1e1c00621 100644
--- a/tests/unit/agentic_ide/test_cold_start_gate.py
+++ b/tests/unit/agentic_ide/test_cold_start_gate.py
@@ -84,6 +84,7 @@ async def test_a_full_workspace_starts_in_waves(
"""The whole grid connecting at once must not become one starting storm."""
monkeypatch.setattr(ide, "COLD_START_LIMIT", 3)
monkeypatch.setattr(ide, "COLD_START_SETTLE_S", 0.0)
+ monkeypatch.setattr(ide, "COLD_START_HOLD_MAX_S", 0.0)
pool.hold_s = 0.05
registry = ide.Registry(pty_manager=pool)
session = await registry.start(
@@ -101,6 +102,7 @@ async def test_codex_shared_store_starts_are_serial_until_the_input_line(
) -> None:
"""A process existing does not release Codex's account-scoped boot slot."""
monkeypatch.setattr(ide, "COLD_START_SETTLE_S", 0.0)
+ monkeypatch.setattr(ide, "COLD_START_HOLD_MAX_S", 0.0)
monkeypatch.setattr(fleet_actions, "READY_POLL_S", 0.01)
monkeypatch.setattr(fleet_actions, "READY_TIMEOUT_S", 1.0)
registry = ide.Registry(pty_manager=pool)
@@ -152,6 +154,7 @@ async def test_rejoining_a_running_agent_never_waits_for_a_starting_one(
"""
monkeypatch.setattr(ide, "COLD_START_LIMIT", 1)
monkeypatch.setattr(ide, "COLD_START_SETTLE_S", 0.0)
+ monkeypatch.setattr(ide, "COLD_START_HOLD_MAX_S", 0.0)
registry = ide.Registry(pty_manager=pool)
session = await registry.start(
str(tmp_path), [{"agent": "claude"}, {"agent": "claude"}]
@@ -207,3 +210,62 @@ async def test_a_failed_start_hands_its_slot_back_at_once(
registry.attach(term.key, 80, 24, sink, gone, workspace_id=session.id),
timeout=2.0,
)
+
+
+async def _wait_for_spawns(pool: CountingPtyManager, count: int) -> None:
+ for _ in range(200):
+ if len(pool.spawns) >= count:
+ return
+ await asyncio.sleep(0.01)
+
+
+async def test_a_slot_is_held_until_the_pane_paints_its_input_line(
+ pool: CountingPtyManager, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A process existing is not the end of a cold start; its input line is.
+
+ Eight resumed Claude Code panes went from spawned to loading within two
+ seconds of each other on a machine that had booted a minute earlier, and
+ the app stalled behind them (2026-08-27). Claude Code accepts typed text
+ before its composer is painted, so this is deliberately NOT the typing
+ wait — it is the composer itself.
+ """
+ monkeypatch.setattr(ide, "COLD_START_LIMIT", 1)
+ monkeypatch.setattr(ide, "COLD_START_SETTLE_S", 0.0)
+ monkeypatch.setattr(ide, "COLD_START_HOLD_MAX_S", 5.0)
+ monkeypatch.setattr(fleet_actions, "READY_POLL_S", 0.01)
+ registry = ide.Registry(pty_manager=pool)
+ session = await registry.start(str(tmp_path), [{"agent": "claude"}, {"agent": "claude"}])
+
+ mounting = asyncio.create_task(_attach_all(registry, session))
+ await _wait_for_spawns(pool, 1)
+ await asyncio.sleep(0.1)
+ assert len(pool.spawns) == 1, "the second pane started before the first had loaded"
+
+ first = next(term for term in session.terminals if term.status == "live")
+ await pool.emit(first.pty_id, "\x1b[2J\x1b[H❯ \x1b[?25h")
+ await _wait_for_spawns(pool, 2)
+ assert len(pool.spawns) == 2, "the next pane starts as soon as the first has painted"
+
+ second = next(term for term in session.terminals if term is not first)
+ await pool.emit(second.pty_id, "\x1b[2J\x1b[H❯ \x1b[?25h")
+ await asyncio.wait_for(mounting, timeout=2.0)
+
+
+async def test_a_pane_that_never_paints_an_input_line_holds_its_slot_only_to_the_ceiling(
+ pool: CountingPtyManager, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A CLI stopped on a login or trust screen must not strand the grid."""
+ monkeypatch.setattr(ide, "COLD_START_LIMIT", 1)
+ monkeypatch.setattr(ide, "COLD_START_SETTLE_S", 0.0)
+ monkeypatch.setattr(ide, "COLD_START_HOLD_MAX_S", 0.2)
+ monkeypatch.setattr(fleet_actions, "READY_POLL_S", 0.01)
+ registry = ide.Registry(pty_manager=pool)
+ session = await registry.start(str(tmp_path), [{"agent": "claude"}, {"agent": "claude"}])
+
+ started = asyncio.get_running_loop().time()
+ await asyncio.wait_for(_attach_all(registry, session), timeout=3.0)
+
+ assert len(pool.spawns) == 2
+ elapsed = asyncio.get_running_loop().time() - started
+ assert elapsed >= 0.15, "the second pane did not wait for the ceiling at all"
diff --git a/tests/unit/brain/test_healthcheck_off_loop.py b/tests/unit/brain/test_healthcheck_off_loop.py
new file mode 100644
index 0000000000..986e74e905
--- /dev/null
+++ b/tests/unit/brain/test_healthcheck_off_loop.py
@@ -0,0 +1,79 @@
+"""The probe's construction step runs off the event loop (BUG-189).
+
+Instantiating a provider is, on a cold process, the first import of its SDK —
+pydantic model generation for a few hundred types, plus the registry's
+entry-point discovery that imports every brain plugin. Done ON the loop, that
+ran for 15 s while the agent chat's health sweep probed every provider at boot
+(2026-08-27), and every WebSocket frame, route and brain turn stood still
+behind it. The checker hands the registry call to a worker thread; these pin
+that the loop thread is never the one constructing, and that a constructor
+that raises is still an honest, non-raising result.
+"""
+
+from __future__ import annotations
+
+import threading
+from collections.abc import AsyncIterator
+from typing import Any
+
+import pytest
+
+from jarvis.brain.healthcheck import BrainHealthChecker
+from jarvis.core.protocols import BrainDelta, BrainRequest
+
+
+class _InstantBrain:
+ name = "instant-brain"
+ context_window = 8192
+ supports_tools = False
+ supports_vision = False
+
+ def __init__(self, *, model: str) -> None:
+ self.model = model
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ yield BrainDelta(content="hi", finish_reason="stop")
+
+ def estimate_cost(self, req: BrainRequest) -> float: # pragma: no cover
+ return 0.0
+
+
+class _ThreadRecordingRegistry:
+ """Same ``instantiate`` signature as production; remembers who called."""
+
+ def __init__(self) -> None:
+ self.threads: list[int] = []
+
+ def instantiate(self, name: str, **kwargs: Any) -> Any:
+ self.threads.append(threading.get_ident())
+ return _InstantBrain(**kwargs)
+
+
+class _RefusingRegistry:
+ def instantiate(self, name: str, **kwargs: Any) -> Any:
+ raise RuntimeError("No Anthropic API key found.")
+
+
+async def test_construction_happens_off_the_loop_thread() -> None:
+ registry = _ThreadRecordingRegistry()
+ checker = BrainHealthChecker(registry) # type: ignore[arg-type]
+
+ result = await checker.probe("some-provider", "some-model")
+
+ assert result.ok is True
+ assert registry.threads, "the registry was never asked"
+ assert all(ident != threading.get_ident() for ident in registry.threads), (
+ "the provider was constructed on the event loop thread"
+ )
+
+
+async def test_a_constructor_that_raises_is_a_clean_failure_not_an_exception() -> None:
+ checker = BrainHealthChecker(_RefusingRegistry()) # type: ignore[arg-type]
+
+ result = await checker.probe("claude-api", "claude-haiku-4-5-20251001")
+
+ assert result.ok is False
+ assert result.error is not None
+ assert "No Anthropic API key" in result.error
diff --git a/tests/unit/clis/test_prober_concurrency.py b/tests/unit/clis/test_prober_concurrency.py
new file mode 100644
index 0000000000..2b0b1d71bd
--- /dev/null
+++ b/tests/unit/clis/test_prober_concurrency.py
@@ -0,0 +1,93 @@
+"""A catalog sweep runs a few probes at a time, not the whole catalog at once.
+
+Every probe is up to two child processes, and most of the catalog is a Node or
+Python CLI that spends a second of CPU printing its version. All 22 at once on
+a machine that had booted a minute earlier meant forty interpreter starts in a
+second while the wake-word models were still loading — 14 probes were still
+running at the sweep ceiling and the app stalled behind the load (2026-08-27,
+BUG-189). ``PROBE_CONCURRENCY`` lanes turn that burst into a queue; the
+partial-result contract of ``probe_all`` must survive the lanes unchanged.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from jarvis.clis import prober as prober_mod
+from jarvis.clis.prober import CliStatusProber
+from jarvis.clis.spec import AuthConfig, CliSpec, CliStatus, InstallMethods, RiskConfig
+
+
+def _spec(name: str) -> CliSpec:
+ return CliSpec(
+ name=name,
+ display_name=name.upper(),
+ description="d",
+ homepage="",
+ binary_name=name,
+ check_command=(name, "--version"),
+ version_parse_regex=r"(\d+)",
+ install=InstallMethods(manual_url="https://x"),
+ auth=AuthConfig(type="oauth_cli", status_command=(name, "auth", "status")),
+ risk=RiskConfig(default_tier="monitor"),
+ )
+
+
+class _CountingProber(CliStatusProber):
+ """Reports how many probes overlapped in time."""
+
+ def __init__(self, *, hanging: set[str] | None = None) -> None:
+ self.in_flight = 0
+ self.peak = 0
+ self._hanging = hanging or set()
+
+ async def probe(self, spec: CliSpec) -> CliStatus:
+ self.in_flight += 1
+ self.peak = max(self.peak, self.in_flight)
+ try:
+ if spec.name in self._hanging:
+ await asyncio.sleep(3600)
+ await asyncio.sleep(0.01)
+ return CliStatus(
+ installed=True,
+ version="1.2.3",
+ binary_path=f"/usr/bin/{spec.name}",
+ auth_status="connected",
+ )
+ finally:
+ self.in_flight -= 1
+
+
+async def test_a_sweep_never_exceeds_the_lane_count(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(prober_mod, "PROBE_CONCURRENCY", 3)
+ prober = _CountingProber()
+ specs = [_spec(f"cli{i}") for i in range(10)]
+
+ statuses = await asyncio.wait_for(prober.probe_all(specs), timeout=5.0)
+
+ assert len(statuses) == 10
+ assert all(status.installed for status in statuses.values()), "a probe lost its result"
+ assert prober.peak <= 3, f"{prober.peak} probes ran at once"
+ assert prober.peak >= 2, "the lanes were not used in parallel at all"
+
+
+async def test_a_probe_still_queued_at_the_ceiling_is_unknown_not_an_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Waiting for a lane that a wedged probe never gives back is not a fault."""
+ monkeypatch.setattr(prober_mod, "PROBE_CONCURRENCY", 1)
+ monkeypatch.setattr(prober_mod, "PROBE_ALL_TIMEOUT_S", 0.05)
+ prober = _CountingProber(hanging={"gcloud"})
+
+ statuses = await asyncio.wait_for(
+ prober.probe_all([_spec("gcloud"), _spec("gh")]), timeout=5.0
+ )
+
+ assert set(statuses) == {"gcloud", "gh"}
+ for name in ("gcloud", "gh"):
+ assert statuses[name].error is None, f"{name} was reported broken, not unfinished"
+ assert statuses[name].installed is False
diff --git a/tests/unit/core/test_loop_executor_anyio.py b/tests/unit/core/test_loop_executor_anyio.py
new file mode 100644
index 0000000000..4731d2a77c
--- /dev/null
+++ b/tests/unit/core/test_loop_executor_anyio.py
@@ -0,0 +1,52 @@
+"""anyio's thread pool must neither grow nor shrink under the loop (BUG-189).
+
+Starlette runs every synchronous route through ``anyio.to_thread.run_sync``;
+anyio starts a worker with ``Thread.start()`` on the calling thread — the event
+loop — whenever none is idle, and retires idle workers after ten seconds. On a
+host still cold-booting that start blocked the loop for 15 s (2026-08-27).
+Like ``test_loop_executor.py`` these assert the pool's SHAPE, not results.
+"""
+
+from __future__ import annotations
+
+import threading
+
+import anyio.to_thread
+import pytest
+from anyio._backends._asyncio import WorkerThread
+
+from jarvis.core.loop_executor import (
+ ANYIO_KEEP_ALIVE_S,
+ keep_anyio_workers_alive,
+ warm_anyio_worker_pool,
+)
+
+
+def test_keep_alive_makes_workers_resident(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A worker that retires is a ``Thread.start()`` on the loop later."""
+ monkeypatch.setattr(WorkerThread, "MAX_IDLE_TIME", 10)
+
+ assert keep_anyio_workers_alive() is True
+ assert WorkerThread.MAX_IDLE_TIME == ANYIO_KEEP_ALIVE_S
+
+
+def test_keep_alive_is_a_no_op_on_an_unfamiliar_backend(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A reshaped anyio must degrade to yesterday's pool, never to a boot crash."""
+ monkeypatch.delattr(WorkerThread, "MAX_IDLE_TIME", raising=True)
+
+ assert keep_anyio_workers_alive() is False
+ assert not hasattr(WorkerThread, "MAX_IDLE_TIME")
+
+
+async def test_warm_up_brings_up_distinct_workers_that_serve_the_next_call() -> None:
+ """Four parked calls need four threads — one worker cannot serve them all —
+ and once they are resident a real call starts nothing new."""
+ resident = await warm_anyio_worker_pool(4)
+ assert resident == 4
+
+ before = threading.active_count()
+ await anyio.to_thread.run_sync(lambda: None)
+ assert threading.active_count() == before, "the call had to start a thread"
diff --git a/tests/unit/telemetry/test_recorder_trace_id.py b/tests/unit/telemetry/test_recorder_trace_id.py
new file mode 100644
index 0000000000..93d6bb5d91
--- /dev/null
+++ b/tests/unit/telemetry/test_recorder_trace_id.py
@@ -0,0 +1,38 @@
+"""A publisher's string trace id costs telemetry one line, not the event.
+
+The recorder observes EVERY event on the bus. ``Event.trace_id`` is a UUID by
+contract, but one publisher handed over a plain string and ``.hex`` raised
+inside the wildcard subscriber on every dictation (2026-08-27) — logged as a
+failure, and the event never reached the flight-recorder file.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from jarvis.core.bus import EventBus
+from jarvis.core.events import DictationTranscribing
+from jarvis.telemetry import FlightRecorder
+
+
+async def test_a_string_trace_id_is_recorded_not_dropped(tmp_path) -> None:
+ bus = EventBus()
+ rec = FlightRecorder(tmp_path, flush_interval_s=0)
+ rec.attach(bus)
+
+ await bus.publish(
+ DictationTranscribing(source_layer="speech.dictation", trace_id="not-a-uuid") # type: ignore[arg-type]
+ )
+ await rec.flush()
+ await rec.close()
+
+ files = list(tmp_path.glob("*.jsonl"))
+ assert len(files) == 1
+ lines = files[0].read_text(encoding="utf-8").strip().splitlines()
+ assert len(lines) == 1, "the event was dropped"
+ record = json.loads(lines[0])
+ assert record["event"] == "DictationTranscribing"
+ assert record["trace_id"] == "not-a-uuid"