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: prevent desktop freezes during agent review fallback
rubenluetke10-beepf0ee1533f62f
diff --git a/jarvis/plugins/brain/antigravity.py b/jarvis/plugins/brain/antigravity.pyindex 68ade4cf39..ab594eb3cd 100644--- a/jarvis/plugins/brain/antigravity.py+++ b/jarvis/plugins/brain/antigravity.py@@ -14,6 +14,7 @@ Google ToS (hard): we only ever invoke the official binary. We never read thestored OAuth token to make our own HTTP request. The CLI is slow (the agentspins up per turn), so this is a deliberate, user-opted path — not the default."""+from __future__ import annotationsimport asyncio@@ -39,7 +40,7 @@ from jarvis.google_cli.isolated_home import (real_gemini_dir as _real_gemini_dir,)from jarvis.google_cli.isolated_home import redirect_home_env-from jarvis.google_cli.pty_runner import repair_agy_path, run_cli_over_pty+from jarvis.google_cli.pty_runner import repair_agy_pathfrom jarvis.google_cli.resolver import GoogleCli, resolve_google_clifrom .cli_prompt_context import (@@ -154,29 +155,18 @@ def _agy_effort(req: BrainRequest | None) -> str:def _build_argv(cli: GoogleCli, prompt: str, model: str, effort: str = _DEFAULT_AGY_EFFORT) -> list[str]:- """Build the headless argv for the resolved CLI — flags differ per binary.-- * ``agy`` (Antigravity CLI): ``--print <prompt> --model <id> --effort <level>``.- It has neither ``--approval-mode`` nor ``-o json`` (live ``agy --help``- 2026-06-20); output is plain text, which ``_parse_cli_answer`` handles via- its raw fallback. A read-only conversational answer needs no tool- permissions.-- ``--effort`` is NOT optional next to ``--model``: a newer agy aborts with- ``invalid model selection (--model "..." --effort ""): ... requires- --effort`` and writes that line to stdout, where a caller happily reads it- as the answer (live 2026-07-26 — the Agentic IDE composer shipped it as a- composed prompt). Sending the pair is what keeps the model choice usable- at all on current agy.- * ``gemini`` (Gemini CLI): read-only ``--approval-mode plan`` + ``--skip-trust``- (so the throwaway workdir is trusted and the sandbox policy is not loaded —- forensic 2026-06-20) + ``-o json``.+ """Build read-only JSON-output commands; the complete prompt travels on stdin.++ Antigravity print mode activates on piped input without ``--print``.+ Keeping input out of argv avoids both Windows and POSIX argument limits."""if cli.kind == "agy":return [*cli.argv_prefix,- "--print",- prompt,+ "--output-format",+ "json",+ "--mode",+ "plan","--model",model,"--effort",@@ -185,7 +175,7 @@ def _build_argv(return [*cli.argv_prefix,"-p",- prompt,+ "Follow the instructions supplied on stdin.","-m",model,"--approval-mode",@@ -256,8 +246,8 @@ class AntigravityBrain:def can_call_tools(self) -> bool:"""Runtime tool-calling capability (NOT the static ``supports_tools``).- Antigravity always drives the Google-subscription CLI (``agy`` over a PTY- or the Gemini CLI over a pipe) on a flattened prompt — it has no+ Antigravity drives the Google-subscription CLI (``agy`` or Gemini) over+ pipes with a flattened prompt — it has nochat-completions/function-calling path and drops every tool. The caller(``BrainManager``) uses this to delegate tool/Computer-Use turns to atool-capable provider instead of letting the CLI silently no-op."""@@ -279,20 +269,13 @@ class AntigravityBrain:prompt = self._render_prompt(req)argv = _build_argv(cli, prompt, self._model, _agy_effort(req))- # agy is a TUI tool: over a plain pipe it emits 0 bytes (the brain then- # sees "no answer"). It must be driven over a real pseudo-terminal. The- # Gemini CLI writes clean JSON to a pipe, so it keeps the fast path.- if cli.kind == "agy":- async for delta in self._complete_via_pty(argv, prompt):- yield delta- else:- async for delta in self._complete_via_pipe(argv, prompt):- yield delta+ async for delta in self._complete_via_pipe(argv, prompt):+ yield deltadef _build_child_env(self, *, harden_path: bool) -> dict[str, str]:"""Child env: drop API keys (subscription login wins), redirect HOME to an- isolated hook/mcp-free CLI home (the lag fix), and — for the agy/PTY case- on Windows — repair the PATH so agy's internal ``cmd.exe``/``npm`` spawns+ isolated hook/mcp-free CLI home (the lag fix), and on Windows repair PATH+ so agy's internal ``cmd.exe``/``npm`` spawnsresolve even from a degraded launch env."""env = {k: v for k, v in os.environ.items() if k not in _DROP_ENV}if harden_path and sys.platform == "win32":@@ -308,73 +291,13 @@ class AntigravityBrain:redirect_home_env(env, iso)return env- async def _complete_via_pty(- self, argv: list[str], prompt: str- ) -> AsyncIterator[BrainDelta]:- """Drive ``agy`` over a ConPTY/PTY (it has no usable pipe output)."""- workdir = tempfile.mkdtemp(prefix="jarvis-antigravity-brain-")- env = self._build_child_env(harden_path=True)- loop = asyncio.get_running_loop()- log.info(- "AntigravityBrain(agy/PTY): driving %s (model=%s, prompt=%d chars)",- argv[0], self._model, len(prompt),- )- t0 = time.monotonic()- fut = loop.run_in_executor(- None,- lambda: run_cli_over_pty(- tuple(argv), timeout_s=self._cli_timeout_s, cwd=workdir, env=env- ),- )- try:- while not fut.done():- done, _ = await asyncio.wait({fut}, timeout=3.0)- if not done:- # No-text progress tick keeps the caller's no-progress- # deadline alive through the slow agent spin-up.- yield BrainDelta(content="")- result = fut.result()- finally:- with suppress(OSError):- shutil.rmtree(workdir, ignore_errors=True)-- elapsed = time.monotonic() - t0- if result.error:- log.warning("AntigravityBrain(agy/PTY) unavailable: %s", result.error)- raise RuntimeError(- f"Antigravity (Google login) is unavailable: {result.error}"- )- if result.timed_out:- log.warning(- "AntigravityBrain(agy/PTY): no answer within %.0fs",- self._cli_timeout_s,- )- raise RuntimeError(- "Antigravity (Google login) did not answer within "- f"{self._cli_timeout_s:.0f}s."- )- if not result.text:- log.warning(- "AntigravityBrain(agy/PTY): empty answer after %.1fs rc=%s",- elapsed, result.exit_status,- )- raise RuntimeError("Antigravity (Google login) returned no answer.")- log.info(- "AntigravityBrain(agy) turn ok: %d chars in %.1fs",- len(result.text), elapsed,- )- yield BrainDelta(content=result.text)- yield BrainDelta(finish_reason="stop")-- async def _complete_via_pipe(- self, argv: list[str], prompt: str- ) -> AsyncIterator[BrainDelta]:- """Drive the Gemini CLI over pipes — it emits clean JSON on stdout."""+ async def _complete_via_pipe(self, argv: list[str], prompt: str) -> AsyncIterator[BrainDelta]:+ """Drive the official Google CLI with UTF-8 stdin and JSON stdout."""+ env = await asyncio.to_thread(self._build_child_env, harden_path=True)workdir = tempfile.mkdtemp(prefix="jarvis-antigravity-brain-")- env = self._build_child_env(harden_path=False)creationflags = NO_WINDOW_CREATIONFLAGS if sys.platform == "win32" else 0log.info(- "AntigravityBrain(gemini/pipe): spawning %s (model=%s, prompt=%d chars)",+ "AntigravityBrain(pipe): spawning %s (model=%s, prompt=%d chars)",argv[0],self._model,len(prompt),@@ -397,12 +320,9 @@ class AntigravityBrain:log.warning("AntigravityBrain: spawn failed: %s", exc)raise RuntimeError(f"Google CLI could not be launched: {exc}") from exc- # Close stdin empty — the whole prompt rides on ``-p``.- with suppress(Exception):- if proc.stdin is not None:- proc.stdin.close()-- comm_task = asyncio.create_task(proc.communicate())+ # communicate drains both output pipes while sending the full prompt;+ # the same deadline covers a child that never consumes its input.+ comm_task = asyncio.create_task(proc.communicate(input=prompt.encode("utf-8")))deadline = t0 + self._cli_timeout_sstdout_bytes = b""stderr_bytes = b""@@ -414,7 +334,11 @@ class AntigravityBrain:if sys.platform == "win32" and isinstance(pid, int) and pid > 0:with suppress(Exception):killer = await asyncio.create_subprocess_exec(- "taskkill", "/PID", str(pid), "/T", "/F",+ "taskkill",+ "/PID",+ str(pid),+ "/T",+ "/F",stdout=asyncio.subprocess.DEVNULL,stderr=asyncio.subprocess.DEVNULL,creationflags=creationflags,@@ -450,24 +374,37 @@ class AntigravityBrain:self._cli_timeout_s,)raise RuntimeError(- "Antigravity (Google login) did not answer within "- f"{self._cli_timeout_s:.0f}s."+ f"Antigravity (Google login) did not answer within {self._cli_timeout_s:.0f}s.") from excfinally:with suppress(OSError):shutil.rmtree(workdir, ignore_errors=True)- answer = _parse_cli_answer(stdout_bytes.decode("utf-8", errors="replace"))+ if proc.returncode:+ log.warning("AntigravityBrain: CLI exited with status %s", proc.returncode)+ raise RuntimeError(f"Google CLI failed with exit status {proc.returncode}.")+ decoded = stdout_bytes.decode("utf-8", errors="replace")+ try:+ envelope = json.loads(decoded)+ except ValueError:+ envelope = None # The parser below supports older plain-text CLI output.+ if isinstance(envelope, dict) and (+ envelope.get("error") or envelope.get("status") in {"ERROR", "CANCELED", "CANCELLED"}+ ):+ log.warning("AntigravityBrain: CLI reported a failed result")+ raise RuntimeError("Google CLI reported a failed result.")+ answer = _parse_cli_answer(decoded)elapsed = time.monotonic() - t0if not answer:detail = stderr_bytes.decode("utf-8", errors="replace").strip()[:300]log.warning("AntigravityBrain: empty answer after %.1fs rc=%s detail=%s",- elapsed, proc.returncode, detail[:200],+ elapsed,+ proc.returncode,+ detail[:200],)raise RuntimeError(- "Antigravity (Google login) returned no answer"- + (f": {detail}" if detail else ".")+ "Antigravity (Google login) returned no answer" + (f": {detail}" if detail else "."))log.info("AntigravityBrain turn ok: %d chars in %.1fs", len(answer), elapsed)diff --git a/jarvis/society/review.py b/jarvis/society/review.pyindex 43f0d4d18b..b0f4bfcf24 100644--- a/jarvis/society/review.py+++ b/jarvis/society/review.py@@ -41,7 +41,7 @@ async def _ask(runtime: Any, agent: Any, prompt: str) -> dict[str, Any] | None:from .chat_binding import pair_forprovider_name, model, _ = pair_for(runtime.config(), agent)- secret = get_jarvis_agent_secret(provider_name)+ secret = await asyncio.to_thread(get_jarvis_agent_secret, provider_name)with override_provider_secrets({provider_name: secret} if secret else {}):def candidates():@@ -68,7 +68,14 @@ async def _ask(runtime: Any, agent: Any, prompt: str) -> dict[str, Any] | None:log.info("society: fallback review provider unavailable", exc_info=True)seen = set()- for provider in candidates():+ providers = candidates()+ while True:+ # Provider construction may read catalogs, credentials and local+ # models. Never run that synchronous work on the desktop event loop.+ # next(..., None) also avoids propagating StopIteration into a Future.+ provider = await asyncio.to_thread(next, providers, None)+ if provider is None:+ breakidentity = (getattr(provider, "name", ""), str(getattr(provider, "_model", "")))if identity in seen:continuediff --git a/tests/unit/plugins/brain/test_antigravity_brain.py b/tests/unit/plugins/brain/test_antigravity_brain.pyindex 9d18c80cab..5cf0c741a5 100644--- a/tests/unit/plugins/brain/test_antigravity_brain.py+++ b/tests/unit/plugins/brain/test_antigravity_brain.py@@ -2,6 +2,7 @@The subprocess is faked; no real CLI or network is touched."""+from __future__ import annotationsimport asyncio@@ -84,7 +85,12 @@ def test_voice_mode_keeps_the_conversational_flattening():def test_cli_prompt_includes_standing_instructions_without_heavy_router_prompt():req = BrainRequest(- messages=(BrainMessage(role="user", content="Was ist das wertvollste Unternehmen?"),), # i18n-allow: simulated German user utterance, content under test+ messages=(+ BrainMessage(+ role="user",+ content="Was ist das wertvollste Unternehmen?", # i18n-allow+ ),+ ),system=_system_with_standing_instructions(),)@@ -125,8 +131,14 @@ def test_cli_prompt_puts_current_empty_state_after_stale_history():req = BrainRequest(messages=(BrainMessage(role="user", content="Wasketup"),- BrainMessage(role="assistant", content="schef, alles laeuft."), # i18n-allow: simulated German assistant reply, content under test- BrainMessage(role="user", content="Du musst das nicht mehr sagen."), # i18n-allow: simulated German user utterance, content under test+ BrainMessage(+ role="assistant",+ content="schef, alles laeuft.", # i18n-allow+ ),+ BrainMessage(+ role="user",+ content="Du musst das nicht mehr sagen.", # i18n-allow+ ),),system=_system_with_empty_standing_instructions(),)@@ -176,7 +188,8 @@ class _FakeProc:self._stdout = stdoutself._stderr = stderr- async def communicate(self) -> tuple[bytes, bytes]:+ async def communicate(self, input=None) -> tuple[bytes, bytes]: # noqa: A002 - subprocess API+ self.input = inputreturn self._stdout, self._stderrdef kill(self) -> None:@@ -189,7 +202,8 @@ class _FakeProc:@pytest.mark.asyncioasync def test_complete_yields_answer(monkeypatch):monkeypatch.setattr(- agmod, "resolve_google_cli",+ agmod,+ "resolve_google_cli",lambda: GoogleCli(kind="gemini", argv_prefix=["gemini"]),)@@ -228,7 +242,8 @@ async def test_argv_trusts_the_ephemeral_workdir(monkeypatch):sandbox policy is loaded."""monkeypatch.setattr(- agmod, "resolve_google_cli",+ agmod,+ "resolve_google_cli",lambda: GoogleCli(kind="gemini", argv_prefix=["gemini"]),)captured: dict[str, object] = {}@@ -253,7 +268,8 @@ async def test_complete_scrubs_api_key_env(monkeypatch):"""The child must not inherit GEMINI_API_KEY (so the subscription login wins)."""monkeypatch.setenv("GEMINI_API_KEY", "should-not-leak")monkeypatch.setattr(- agmod, "resolve_google_cli",+ agmod,+ "resolve_google_cli",lambda: GoogleCli(kind="gemini", argv_prefix=["gemini"]),)captured: dict[str, object] = {}@@ -271,16 +287,17 @@ async def test_complete_scrubs_api_key_env(monkeypatch):assert "GEMINI_API_KEY" not in env-def test_build_argv_agy_uses_print_and_model():- """agy 1.0.9 has --print/--model but NOT the gemini-CLI flags --approval-mode- / -o json / --skip-trust (forensic 2026-06-20, live `agy --help`)."""+def test_build_argv_agy_uses_stdin_and_read_only_json():+ """The current CLI reads stdin in print mode without a PTY."""from jarvis.plugins.brain.antigravity import _build_argvcli = GoogleCli(kind="agy", argv_prefix=["agy"])argv = _build_argv(cli, "hello", "gemini-3.1-pro-preview")assert argv[0] == "agy"- assert "--print" in argv- assert "hello" in argv+ assert "--print" not in argv+ assert "hello" not in argv+ assert argv[argv.index("--output-format") + 1] == "json"+ assert argv[argv.index("--mode") + 1] == "plan"assert "--model" in argvassert "gemini-3.1-pro-preview" in argvassert "--approval-mode" not in argv@@ -299,47 +316,40 @@ def test_build_argv_gemini_keeps_skip_trust():assert "plan" in argv-# ---- agy over ConPTY --------------------------------------------------------# agy is a TUI tool: a plain pipe yields 0 bytes (the brain then sees no answer).-# It must be driven over a pseudo-terminal via pty_runner.run_cli_over_pty.+# ---- agy with piped UTF-8 input -------------------------------------------def _agy_cli() -> GoogleCli:return GoogleCli(kind="agy", argv_prefix=["agy.exe"])-def _fake_pty_result(text: str = "", *, error: str | None = None, timed_out: bool = False):- from jarvis.google_cli.pty_runner import PtyRunResult-- return PtyRunResult(- text=text, raw=text, exit_status=0, timed_out=timed_out, error=error- )--@pytest.mark.asyncio-async def test_complete_agy_drives_pty_runner(monkeypatch):- """kind='agy' must go through the PTY runner, not create_subprocess_exec."""- monkeypatch.setattr(agmod, "resolve_google_cli", _agy_cli)- captured: dict[str, object] = {}-- def _fake_run(argv, *, timeout_s, cwd=None, env=None, **kw):- captured["argv"] = list(argv)- return _fake_pty_result("Servus von agy!")-- monkeypatch.setattr(agmod, "run_cli_over_pty", _fake_run)- # Guard: the pipe path must NOT be taken for agy.- async def _boom(*a, **k):- raise AssertionError("agy must not use create_subprocess_exec")[email protected]("kind", ["agy", "gemini"])+async def test_complete_sends_large_unicode_prompt_on_stdin(monkeypatch, kind):+ monkeypatch.setattr(+ agmod,+ "resolve_google_cli",+ lambda: GoogleCli(kind=kind, argv_prefix=[kind]),+ )+ captured = {}+ proc = _FakeProc(b'{"response": "ok"}')- monkeypatch.setattr(asyncio, "create_subprocess_exec", _boom)+ async def spawn(*argv, **kwargs):+ captured["argv"] = argv+ captured["cwd"] = kwargs["cwd"]+ return proc- brain = AntigravityBrain()- chunks = [d async for d in brain.complete(_req())]- texts = "".join(d.content for d in chunks if d.content)- assert "Servus von agy!" in texts+ monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)+ text = "Evidence: \U0001f600\u00e9\n" * 60000+ brain = AntigravityBrain(structured_prompts=True)+ request = _req(text)+ chunks = [d async for d in brain.complete(request)]+ assert "".join(d.content or "" for d in chunks) == "ok"+ assert proc.input.decode("utf-8") == brain._render_prompt(request)+ assert len(proc.input) > 743147+ assert sum(map(len, captured["argv"])) < 1000+ assert not await asyncio.to_thread(Path(captured["cwd"]).exists)assert any(d.finish_reason == "stop" for d in chunks)- assert captured["argv"][0] == "agy.exe"- assert "--print" in captured["argv"]@pytest.mark.asyncio@@ -349,11 +359,11 @@ async def test_complete_agy_drops_key_and_hardens_path(monkeypatch):monkeypatch.setattr(agmod, "resolve_google_cli", _agy_cli)captured: dict[str, object] = {}- def _fake_run(argv, *, timeout_s, cwd=None, env=None, **kw):- captured["env"] = env- return _fake_pty_result("ok")+ async def _fake_exec(*argv, **kwargs):+ captured["env"] = kwargs["env"]+ return _FakeProc(b'{"response": "ok"}')- monkeypatch.setattr(agmod, "run_cli_over_pty", _fake_run)+ monkeypatch.setattr(asyncio, "create_subprocess_exec", _fake_exec)brain = AntigravityBrain()async for _ in brain.complete(_req()):pass@@ -435,11 +445,11 @@ async def test_complete_agy_redirects_home_to_isolated(monkeypatch, tmp_path):monkeypatch.setattr(agmod, "resolve_google_cli", _agy_cli)captured: dict[str, object] = {}- def _fake_run(argv, *, timeout_s, cwd=None, env=None, **kw):- captured["env"] = env- return _fake_pty_result("ok")+ async def _fake_exec(*argv, **kwargs):+ captured["env"] = kwargs["env"]+ return _FakeProc(b'{"response": "ok"}')- monkeypatch.setattr(agmod, "run_cli_over_pty", _fake_run)+ monkeypatch.setattr(asyncio, "create_subprocess_exec", _fake_exec)brain = AntigravityBrain()async for _ in brain.complete(_req()):pass@@ -454,7 +464,11 @@ async def test_complete_agy_redirects_home_to_isolated(monkeypatch, tmp_path):@pytest.mark.asyncioasync def test_complete_agy_empty_answer_raises(monkeypatch):monkeypatch.setattr(agmod, "resolve_google_cli", _agy_cli)- monkeypatch.setattr(agmod, "run_cli_over_pty", lambda *a, **k: _fake_pty_result(""))++ async def _fake_exec(*args, **kwargs):+ return _FakeProc(b'{"response": ""}')++ monkeypatch.setattr(asyncio, "create_subprocess_exec", _fake_exec)brain = AntigravityBrain()with pytest.raises(RuntimeError):async for _ in brain.complete(_req()):@@ -462,16 +476,15 @@ async def test_complete_agy_empty_answer_raises(monkeypatch):@pytest.mark.asyncio-async def test_complete_agy_pty_unavailable_raises(monkeypatch):+async def test_complete_agy_spawn_failure_raises(monkeypatch):monkeypatch.setattr(agmod, "resolve_google_cli", _agy_cli)- monkeypatch.setattr(- agmod,- "run_cli_over_pty",- lambda *a, **k: _fake_pty_result("", error="No pseudo-terminal backend available"),- )- brain = AntigravityBrain()- with pytest.raises(RuntimeError):- async for _ in brain.complete(_req()):++ async def spawn(*args, **kwargs):+ raise OSError("CLI not available")++ monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)+ with pytest.raises(RuntimeError, match="could not be launched"):+ async for _ in AntigravityBrain().complete(_req()):pass@@ -481,7 +494,70 @@ def test_cli_timeout_accepts_a_caller_budget() -> None:from jarvis.plugins.brain.antigravity import AntigravityBrainassert AntigravityBrain(cli_timeout_s=180.0)._cli_timeout_s == 180.0- assert (- AntigravityBrain()._cli_timeout_s- == antigravity_module._CLI_TIMEOUT_S- )+ assert AntigravityBrain()._cli_timeout_s == antigravity_module._CLI_TIMEOUT_S++[email protected]("cancel", [False, True])+async def test_stalled_stdin_is_killed_on_timeout_or_cancellation(monkeypatch, cancel):+ monkeypatch.setattr(agmod, "resolve_google_cli", _agy_cli)+ started = asyncio.Event()++ class StalledProc(_FakeProc):+ pid = None++ def __init__(self):+ super().__init__(b"")+ self.pid = None+ self.killed = False+ self.waited = False++ async def communicate(self, input=None): # noqa: A002 - subprocess API+ started.set()+ await asyncio.Event().wait()++ def kill(self):+ self.killed = True++ async def wait(self):+ self.waited = True+ return -1++ proc = StalledProc()++ async def spawn(*args, **kwargs):+ return proc++ monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)++ async def run():+ return [d async for d in AntigravityBrain(cli_timeout_s=0.1).complete(_req())]++ task = asyncio.create_task(run())+ await asyncio.wait_for(started.wait(), timeout=2)+ if cancel:+ task.cancel()+ with pytest.raises(asyncio.CancelledError if cancel else RuntimeError):+ await asyncio.wait_for(task, timeout=2)+ assert proc.killed and proc.waited+++ "code,output",+ [+ (1, b'{"response":"failure text"}'),+ (0, b'{"status":"ERROR","response":"failure text"}'),+ (0, b'{"error":{"message":"failure"},"response":"failure text"}'),+ ],+)+async def test_failed_cli_response_is_never_an_answer(monkeypatch, code, output):+ monkeypatch.setattr(agmod, "resolve_google_cli", _agy_cli)++ async def spawn(*args, **kwargs):+ return _FakeProc(output, returncode=code)++ monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)+ with pytest.raises(RuntimeError):+ async for _ in AntigravityBrain().complete(_req()):+ passdiff --git a/tests/unit/society/test_review_responsiveness.py b/tests/unit/society/test_review_responsiveness.pynew file mode 100644index 0000000000..0d54a75fb0--- /dev/null+++ b/tests/unit/society/test_review_responsiveness.py@@ -0,0 +1,89 @@+"""Slow review provider initialization must not stall the desktop event loop."""++import asyncio+import contextvars+import threading+from types import SimpleNamespace++import pytest++from jarvis.core.protocols import BrainDelta+from jarvis.society.review import _ask++[email protected]("fallback", [False, True])+async def test_review_provider_resolution_keeps_loop_responsive(monkeypatch, fallback):+ from jarvis.agent_chat import runner_brain+ from jarvis.core import config+ from jarvis.society import learning++ loop = asyncio.get_running_loop()+ loop_thread = threading.get_ident()+ entered = asyncio.Event()+ release = threading.Event()+ context = contextvars.ContextVar("review-test-context", default="missing")+ context.set("inherited")+ calls = []++ class Provider:+ def __init__(self, name):+ self.name = name+ self._model = "test-model"++ async def complete(self, request):+ assert threading.get_ident() == loop_thread+ if self.name == "primary" and fallback:+ raise RuntimeError("primary unavailable")+ yield BrainDelta(content='{"memories": [], "skill": null}')++ def getter(name, model, *, scope):+ calls.append((name, scope))+ if name == ("fallback" if fallback else "primary"):+ assert threading.get_ident() != loop_thread+ assert context.get() == "inherited"+ loop.call_soon_threadsafe(entered.set)+ assert release.wait(timeout=3), "event loop could not release provider initialization"+ return Provider(name)++ class Creator:+ def _candidate_brains(self):+ assert threading.get_ident() != loop_thread+ yield Provider("fallback"), "fallback"++ monkeypatch.setattr(runner_brain, "brain_manager", lambda: SimpleNamespace(_get_brain=getter))+ monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda provider: None)+ monkeypatch.setattr(learning, "default_creator_factory", lambda cfg: lambda *args: Creator())+ runtime = SimpleNamespace(config=lambda: None, skills_for=lambda agent_id: None)+ agent = SimpleNamespace(provider="primary", model="test-model", effort="low", agent_id="test")+ task = asyncio.create_task(_ask(runtime, agent, "Evidence"))+ try:+ await asyncio.wait_for(entered.wait(), timeout=2)+ # This callback runs while synchronous provider construction is blocked.+ await asyncio.sleep(0)+ assert not task.done()+ finally:+ release.set()+ assert await asyncio.wait_for(task, timeout=2) == {"memories": [], "skill": None}+ assert calls == [("primary", "society-review:test")] + (+ [("fallback", "society-review:test")] if fallback else []+ )+++async def test_unavailable_review_providers_finish_without_stop_iteration(monkeypatch):+ from jarvis.agent_chat import runner_brain+ from jarvis.core import config+ from jarvis.society import learning++ def unavailable(*args, **kwargs):+ raise RuntimeError("no usable provider")++ monkeypatch.setattr(+ runner_brain, "brain_manager", lambda: SimpleNamespace(_get_brain=unavailable)+ )+ monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda provider: None)+ monkeypatch.setattr(learning, "default_creator_factory", lambda cfg: lambda *args: None)+ runtime = SimpleNamespace(config=lambda: None, skills_for=lambda agent_id: None)+ agent = SimpleNamespace(provider="primary", model="test", effort="low", agent_id="test")+ assert await asyncio.wait_for(_ask(runtime, agent, "Evidence"), timeout=2) is None