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.

test: consolidate in-flight test suite changes

Ruben Lütkeebc3fabfa9be
diff --git a/tests/contract/test_single_instance.py b/tests/contract/test_single_instance.py
index a55d5e4f45..a8100672cb 100644
--- a/tests/contract/test_single_instance.py
+++ b/tests/contract/test_single_instance.py
@@ -51,6 +51,108 @@ def test_second_claim_raises_when_first_alive(tmp_path) -> None:
first.release()
+def test_live_but_portless_holder_is_evicted(tmp_path, monkeypatch) -> None:
+ """Forensic 2026-06-26: a LIVE but non-serving "lock-zombie" (its webserver
+ socket died on WinError 64, but voice/telegram kept the process alive) held
+ the lock with no port and no window, so every restart bounced. A live holder
+ whose port does NOT answer health must be evicted so the boot can proceed."""
+ lock_file = tmp_path / "jarvis.lock"
+ meta_file = tmp_path / ".jarvis-running"
+
+ from filelock import FileLock
+
+ holder = FileLock(str(lock_file))
+ holder.acquire(timeout=0.0)
+ meta_file.write_text(
+ json.dumps({"pid": 424242, "port": 47821, "started_at": 0}),
+ encoding="utf-8",
+ )
+ # Pretend the zombie pid is alive (it is — that is the whole trap).
+ monkeypatch.setattr(
+ "jarvis.ui.desktop_app._pid_alive", lambda pid: pid == 424242
+ )
+
+ killed: dict[str, int] = {}
+
+ def fake_terminate(pid: int) -> bool:
+ killed["pid"] = pid
+ holder.release() # simulate the zombie dying → OS frees the lock
+ return True
+
+ fresh = acquire_single_instance_lock(
+ timeout=0.0,
+ lock_path=lock_file,
+ meta_path=meta_file,
+ health_probe=lambda port: False, # dead port → zombie
+ terminate=fake_terminate,
+ )
+ try:
+ assert killed["pid"] == 424242, "the non-serving zombie must be terminated"
+ assert fresh.is_locked, "the fresh boot must reclaim the lock"
+ finally:
+ fresh.release()
+
+
+def test_live_holder_with_responsive_port_is_respected(tmp_path) -> None:
+ """A live holder whose port ANSWERS health is a real running instance — it
+ must NOT be evicted (anti-false-positive: never kill a healthy Jarvis)."""
+ lock_file = tmp_path / "jarvis.lock"
+ meta_file = tmp_path / ".jarvis-running"
+
+ first = acquire_single_instance_lock(
+ timeout=0.0, lock_path=lock_file, meta_path=meta_file
+ )
+ meta_file.write_text(
+ json.dumps({"pid": os.getpid(), "port": 47821, "started_at": 0}),
+ encoding="utf-8",
+ )
+
+ def must_not_terminate(pid: int) -> bool: # pragma: no cover - must never run
+ raise AssertionError("a healthy holder must never be terminated")
+
+ try:
+ with pytest.raises(SingleInstanceError):
+ acquire_single_instance_lock(
+ timeout=0.0,
+ lock_path=lock_file,
+ meta_path=meta_file,
+ health_probe=lambda port: True, # port answers → healthy
+ terminate=must_not_terminate,
+ )
+ finally:
+ first.release()
+
+
+def test_live_self_pid_holder_is_never_terminated(tmp_path) -> None:
+ """Defense: even with a dead port, the holder pid == our own pid must never
+ be evicted (no suicide). It is treated as a live instance instead."""
+ lock_file = tmp_path / "jarvis.lock"
+ meta_file = tmp_path / ".jarvis-running"
+
+ first = acquire_single_instance_lock(
+ timeout=0.0, lock_path=lock_file, meta_path=meta_file
+ )
+ meta_file.write_text(
+ json.dumps({"pid": os.getpid(), "port": 47821, "started_at": 0}),
+ encoding="utf-8",
+ )
+
+ def must_not_terminate(pid: int) -> bool: # pragma: no cover - must never run
+ raise AssertionError("self pid must never be terminated")
+
+ try:
+ with pytest.raises(SingleInstanceError):
+ acquire_single_instance_lock(
+ timeout=0.0,
+ lock_path=lock_file,
+ meta_path=meta_file,
+ health_probe=lambda port: False, # dead port, but it's US
+ terminate=must_not_terminate,
+ )
+ finally:
+ first.release()
+
+
def test_stale_lock_is_reclaimed(tmp_path) -> None:
"""Wenn der PID im Meta-File tot ist, darf ein neuer Prozess übernehmen."""
lock_file = tmp_path / "jarvis.lock"
diff --git a/tests/integration/test_dispatch_to_harness.py b/tests/integration/test_dispatch_to_harness.py
index 436de0796a..6eaa0e0dab 100644
--- a/tests/integration/test_dispatch_to_harness.py
+++ b/tests/integration/test_dispatch_to_harness.py
@@ -93,6 +93,33 @@ async def test_missing_prompt_fails(ctx):
assert result.success is False
+async def test_unknown_harness_returns_neutral_error_no_inventory_leak(ctx):
+ """A missing harness must NOT leak the internal active/failed harness list.
+
+ Forensic 2026-06-28: the raw KeyError ("...Aktiv: [mcp-remote, …]") rode into
+ the voice path and was read aloud verbatim. The returned error must be
+ neutral — it may name the requested harness, but must never contain the
+ internal harness inventory.
+ """
+ bus = EventBus()
+ mgr = _make_manager_with_fakes(bus, {
+ "python-script": FakeHarness(scripted_output="ok"),
+ "mcp-remote": FakeHarness(scripted_output="ok"),
+ })
+ tool = DispatchToHarnessTool(bus=bus, manager=mgr)
+
+ result = await tool.execute({"harness": "openclaw", "prompt": "x"}, ctx)
+ assert result.success is False
+ err = result.error or ""
+ # No internal inventory leak — neither the registered harness names nor the
+ # "Aktiv: [...]"/available wording may appear.
+ assert "python-script" not in err
+ assert "mcp-remote" not in err
+ assert "Aktiv" not in err
+ assert "available" not in err.lower()
+
+
@pytest.mark.asyncio
async def test_output_trim_for_large_stdout(ctx):
bus = EventBus()
diff --git a/tests/integration/test_downloads_routes.py b/tests/integration/test_downloads_routes.py
new file mode 100644
index 0000000000..f58f85be3d
--- /dev/null
+++ b/tests/integration/test_downloads_routes.py
@@ -0,0 +1,126 @@
+"""Integration tests for /api/downloads (save-to-Downloads) routes.
+
+The desktop shell saves files via this backend route because pywebview silently
+drops browser downloads. These tests pin: desktop-gating (404 when disabled),
+filename hardening, collision avoidance, base64 decode, and the size cap.
+"""
+from __future__ import annotations
+
+import base64
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+import jarvis.ui.web.downloads_routes as downloads_routes
+from jarvis.ui.web.downloads_routes import router as downloads_router
+
+
+def _client(native: bool, home: Path) -> TestClient:
+ app = FastAPI()
+ app.state.native_file_actions = native
+ app.include_router(downloads_router)
+ client = TestClient(app)
+ # Both Path.home() (in the route) resolve to the temp home.
+ return client
+
+
+def home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ return tmp_path
+
+
+def _b64(data: bytes) -> str:
+ return base64.b64encode(data).decode("ascii")
+
+
+def test_capabilities_reflects_flag(home: Path) -> None:
+ client = _client(native=True, home=home)
+ body = client.get("/api/downloads/capabilities").json()
+ assert body["native_file_actions"] is True
+ assert body["platform"] in ("win32", "darwin", "linux")
+
+ client_off = _client(native=False, home=home)
+ assert (
+ client_off.get("/api/downloads/capabilities").json()["native_file_actions"]
+ is False
+ )
+
+
+def test_save_writes_to_downloads(home: Path) -> None:
+ client = _client(native=True, home=home)
+ res = client.post(
+ "/api/downloads/save",
+ json={"filename": "note.txt", "content_b64": _b64("hällo".encode())},
+ )
+ assert res.status_code == 200, res.text
+ data = res.json()
+ target = home / "Downloads" / "note.txt"
+ assert target.exists()
+ assert target.read_text(encoding="utf-8") == "hällo"
+ assert data["saved_path"] == str(target)
+ assert data["filename"] == "note.txt"
+ assert data["bytes_written"] == len("hällo".encode())
+
+
+def test_save_disabled_returns_404(home: Path) -> None:
+ client = _client(native=False, home=home)
+ res = client.post(
+ "/api/downloads/save",
+ json={"filename": "x.txt", "content_b64": _b64(b"data")},
+ )
+ assert res.status_code == 404
+ assert not (home / "Downloads").exists()
+
+
+def test_save_sanitizes_path_traversal(home: Path) -> None:
+ client = _client(native=True, home=home)
+ res = client.post(
+ "/api/downloads/save",
+ json={
+ "filename": "../../etc/pa:ss<wd>.txt",
+ "content_b64": _b64(b"x"),
+ },
+ )
+ assert res.status_code == 200, res.text
+ saved = Path(res.json()["saved_path"])
+ # Stays inside Downloads, directory parts + illegal chars stripped.
+ assert saved.parent == home / "Downloads"
+ assert saved.name == "pa_ss_wd_.txt"
+
+
+def test_save_avoids_collision(home: Path) -> None:
+ client = _client(native=True, home=home)
+ first = client.post(
+ "/api/downloads/save",
+ json={"filename": "dup.txt", "content_b64": _b64(b"one")},
+ ).json()
+ second = client.post(
+ "/api/downloads/save",
+ json={"filename": "dup.txt", "content_b64": _b64(b"two")},
+ ).json()
+ assert Path(first["saved_path"]).name == "dup.txt"
+ assert Path(second["saved_path"]).name == "dup-1.txt"
+ assert (home / "Downloads" / "dup.txt").read_bytes() == b"one"
+ assert (home / "Downloads" / "dup-1.txt").read_bytes() == b"two"
+
+
+def test_save_rejects_invalid_base64(home: Path) -> None:
+ client = _client(native=True, home=home)
+ res = client.post(
+ "/api/downloads/save",
+ json={"filename": "x.txt", "content_b64": "not!base64!!"},
+ )
+ assert res.status_code == 400
+
+
+def test_save_rejects_oversized(home: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(downloads_routes, "_MAX_BYTES", 8)
+ client = _client(native=True, home=home)
+ res = client.post(
+ "/api/downloads/save",
+ json={"filename": "big.bin", "content_b64": _b64(b"x" * 16)},
+ )
+ assert res.status_code == 413
diff --git a/tests/integration/test_subagent_active_brain.py b/tests/integration/test_jarvis_agent_active_brain.py
similarity index 71%
rename from tests/integration/test_subagent_active_brain.py
rename to tests/integration/test_jarvis_agent_active_brain.py
index c377402d52..3b5d66feed 100644
--- a/tests/integration/test_subagent_active_brain.py
+++ b/tests/integration/test_jarvis_agent_active_brain.py
@@ -167,11 +167,11 @@ def test_subagent_switch_updates_status_endpoint(monkeypatch: pytest.MonkeyPatch
cfg.brain.sub_jarvis = BrainTierConfig(provider="claude-api", model="")
client = _client(cfg)
- client.post("/api/subagent/switch", json={"provider": "grok", "persist": True})
+ client.post("/api/subagent/switch", json={"provider": "openrouter", "persist": True})
data = client.get("/api/openclaw/status").json()
active = {r["jarvis"]: r["is_active_brain"] for r in data["mapping"]}
- assert active["grok"] is True
+ assert active["openrouter"] is True
assert active["claude-api"] is False
@@ -297,6 +297,81 @@ def test_subagent_switch_409_codex_when_not_connected(
assert persisted == []
+# --- Claude Max OAuth as a subagent credential (no API key needed) ---------
+# The ClaudeDirectWorker authenticates via the live Claude Max OAuth login in
+# ~/.claude/.credentials.json (read_live_claude_oauth_token), NOT a stored
+# Anthropic API key. A fresh Claude-Max user who only ran `claude login` must
+# therefore see claude-api unlocked + selectable, mirroring the codex/agy OAuth
+# rows above. Source of the worker auth: missions/init.py::_worker_factory.
+
+
+def test_claude_api_row_key_set_via_max_oauth(monkeypatch: pytest.MonkeyPatch) -> None:
+ """No API key anywhere, but a live Claude Max OAuth login -> row unlocked."""
+ import jarvis.core.config as cfg_mod
+
+ monkeypatch.setattr(cfg_mod, "get_secret", lambda *_a, **_k: None)
+ monkeypatch.setattr(
+ "jarvis.missions.isolation.env.read_live_claude_oauth_token",
+ lambda: "sk-ant-oat-live",
+ )
+ cfg = load_config()
+ row = next(r for r in _status(cfg)["mapping"] if r["jarvis"] == "claude-api")
+ assert row["key_set"] is True
+
+
+def test_claude_api_row_locked_without_key_or_oauth(monkeypatch: pytest.MonkeyPatch) -> None:
+ import jarvis.core.config as cfg_mod
+
+ monkeypatch.setattr(cfg_mod, "get_secret", lambda *_a, **_k: None)
+ monkeypatch.setattr(
+ "jarvis.missions.isolation.env.read_live_claude_oauth_token", lambda: None
+ )
+ cfg = load_config()
+ row = next(r for r in _status(cfg)["mapping"] if r["jarvis"] == "claude-api")
+ assert row["key_set"] is False
+
+
+def test_subagent_switch_accepts_claude_max_oauth(monkeypatch: pytest.MonkeyPatch) -> None:
+ """OAuth login present, no API key -> claude-api selectable as subagent."""
+ import jarvis.core.config as cfg_mod
+ import jarvis.core.config_writer as config_writer
+
+ monkeypatch.setattr(cfg_mod, "get_provider_secret", lambda _p: None)
+ monkeypatch.setattr(
+ "jarvis.missions.isolation.env.read_live_claude_oauth_token",
+ lambda: "sk-ant-oat-live",
+ )
+ calls: list[str] = []
+ monkeypatch.setattr(config_writer, "set_sub_jarvis_provider", lambda n: calls.append(n))
+
+ cfg = load_config()
+ resp = _client(cfg).post(
+ "/api/subagent/switch", json={"provider": "claude-api", "persist": True}
+ )
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["active"] == "claude-api"
+ assert calls == ["claude-api"]
+
+
+def test_subagent_switch_409_claude_api_no_key_no_oauth(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import jarvis.core.config as cfg_mod
+ import jarvis.core.config_writer as config_writer
+
+ monkeypatch.setattr(cfg_mod, "get_provider_secret", lambda _p: None)
+ monkeypatch.setattr(
+ "jarvis.missions.isolation.env.read_live_claude_oauth_token", lambda: None
+ )
+ persisted: list[str] = []
+ monkeypatch.setattr(config_writer, "set_sub_jarvis_provider", lambda n: persisted.append(n))
+
+ cfg = load_config()
+ resp = _client(cfg).post("/api/subagent/switch", json={"provider": "claude-api"})
+ assert resp.status_code == 409
+ assert persisted == []
+
+
# --- Antigravity as a subagent (direct GoogleCliWorker, no OpenClaw slug) ---
# The Google sibling of Codex: a selectable subagent row backed by the Google
# subscription OAuth login (no API key), so the user can run heavy tasks over
@@ -339,7 +414,11 @@ def test_openclaw_status_includes_antigravity_row(monkeypatch: pytest.MonkeyPatc
def test_antigravity_row_key_set_reflects_oauth(monkeypatch: pytest.MonkeyPatch) -> None:
- """No API key — the row is unlocked iff the Google OAuth login is connected."""
+ """With NO Gemini API key, the row is unlocked iff the Google OAuth login is
+ connected. (The Gemini-key path is covered separately below.)"""
+ import jarvis.core.config as cfg_mod
+
+ monkeypatch.setattr(cfg_mod, "get_secret", lambda *_a, **_k: None)
_patch_antigravity(monkeypatch, connected=True)
cfg = load_config()
row = next(r for r in _status(cfg)["mapping"] if r["jarvis"] == "antigravity")
@@ -382,11 +461,12 @@ def test_subagent_switch_accepts_antigravity(monkeypatch: pytest.MonkeyPatch) ->
def test_subagent_switch_409_antigravity_when_not_connected(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """Not signed in with Google -> 409, nothing persisted."""
+ """Not signed in with Google AND no Gemini key -> 409, nothing persisted."""
import jarvis.core.config as cfg_mod
import jarvis.core.config_writer as config_writer
monkeypatch.setattr(cfg_mod, "get_provider_secret", lambda _p: None)
+ monkeypatch.setattr(cfg_mod, "get_secret", lambda *_a, **_k: None)
_patch_antigravity(monkeypatch, connected=False)
persisted: list[str] = []
monkeypatch.setattr(config_writer, "set_sub_jarvis_provider", lambda n: persisted.append(n))
@@ -395,3 +475,63 @@ def test_subagent_switch_409_antigravity_when_not_connected(
resp = _client(cfg).post("/api/subagent/switch", json={"provider": "antigravity"})
assert resp.status_code == 409
assert persisted == []
+
+
+# --- Antigravity DUAL billing: subscription OAuth OR a Gemini API key ---------
+# Mirror of Codex (subscription_or_api). A user with no Google login but a Gemini
+# API key set can still run the Antigravity subagent, billed per token.
+
+
+def test_antigravity_row_key_set_via_gemini_api_key(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """No OAuth login, but a Gemini API key is set -> the row unlocks (API billing)."""
+ import jarvis.core.config as cfg_mod
+
+ _patch_antigravity(monkeypatch, connected=False)
+ monkeypatch.setattr(
+ cfg_mod, "get_secret",
+ lambda key, *a, **k: "AIza-fake" if key == "gemini_api_key" else None,
+ )
+ cfg = load_config()
+ row = next(r for r in _status(cfg)["mapping"] if r["jarvis"] == "antigravity")
+ assert row["key_set"] is True
+
+
+def test_antigravity_row_billing_is_subscription_or_api(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The row exposes its billing mode so the UI can badge it."""
+ _patch_antigravity(monkeypatch, connected=True)
+ cfg = load_config()
+ row = next(r for r in _status(cfg)["mapping"] if r["jarvis"] == "antigravity")
+ assert row["billing"] == "subscription_or_api"
+ codex_row = next(r for r in _status(cfg)["mapping"] if r["jarvis"] == "openai-codex")
+ assert codex_row["billing"] == "subscription_or_api"
+ gemini_row = next(r for r in _status(cfg)["mapping"] if r["jarvis"] == "gemini")
+ assert gemini_row["billing"] == "api"
+
+
+def test_subagent_switch_accepts_antigravity_via_api_key(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """No OAuth, but a Gemini API key -> antigravity selectable (per-token billing)."""
+ import jarvis.core.config as cfg_mod
+ import jarvis.core.config_writer as config_writer
+
+ monkeypatch.setattr(cfg_mod, "get_provider_secret", lambda _p: None)
+ monkeypatch.setattr(
+ cfg_mod, "get_secret",
+ lambda key, *a, **k: "AIza-fake" if key == "gemini_api_key" else None,
+ )
+ _patch_antigravity(monkeypatch, connected=False)
+ calls: list[str] = []
+ monkeypatch.setattr(config_writer, "set_sub_jarvis_provider", lambda n: calls.append(n))
+
+ cfg = load_config()
+ resp = _client(cfg).post(
+ "/api/subagent/switch", json={"provider": "antigravity", "persist": True}
+ )
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["active"] == "antigravity"
+ assert calls == ["antigravity"]
diff --git a/tests/integration/test_subagent_model_drift.py b/tests/integration/test_jarvis_agent_model_drift.py
similarity index 100%
rename from tests/integration/test_subagent_model_drift.py
rename to tests/integration/test_jarvis_agent_model_drift.py
diff --git a/tests/integration/test_subagent_model_route.py b/tests/integration/test_jarvis_agent_model_route.py
similarity index 100%
rename from tests/integration/test_subagent_model_route.py
rename to tests/integration/test_jarvis_agent_model_route.py
diff --git a/tests/integration/test_provider_routes.py b/tests/integration/test_provider_routes.py
index a1fb243890..b1e98d021d 100644
--- a/tests/integration/test_provider_routes.py
+++ b/tests/integration/test_provider_routes.py
@@ -123,6 +123,83 @@ def test_list_providers_returns_full_catalog(server_with_brain: WebServer, secre
assert "ollama-local" not in ids, "Ollama wurde 2026-04-21 entfernt"
+# ----------------------------------------------------------------------
+# /api/providers/section-health — the at-a-glance tab indicators
+# ----------------------------------------------------------------------
+
+
+class _FakeTestResult:
+ """Minimal stand-in for provider_test.ProviderTestResult — the section-health
+ route only reads ``.status`` and ``.detail``."""
+
+ def __init__(self, status: str = "ok", detail: str = "") -> None:
+ self.status = status
+ self.detail = detail
+
+
+def no_real_provider_test(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Stub the REAL connectivity call so section-health never hits the network
+ (and can't pick up the maintainer's live keyring keys), keeping the test
+ hermetic and fast."""
+ from jarvis.brain import provider_test as _pt
+
+ async def _fake_run(spec: Any, cfg: Any) -> _FakeTestResult: # noqa: ANN401
+ return _FakeTestResult("ok", "")
+
+ monkeypatch.setattr(_pt, "run_provider_test", _fake_run)
+
+
+def test_section_health_returns_all_tabs(
+ server_with_brain: WebServer,
+ secret_store: _InMemorySecretStore,
+ no_real_provider_test: None,
+) -> None:
+ """Every tab gets a status drawn from the SSOT vocabulary, and the response
+ is honestly marked uncached on the first call."""
+ with TestClient(server_with_brain.app) as client:
+ resp = client.get("/api/providers/section-health")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert set(body["sections"]) == {"brain", "tts", "stt", "subagents", "advanced"}
+ valid = {"ok", "needs_setup", "error", "unknown"}
+ for sec in body["sections"].values():
+ assert sec["status"] in valid
+ assert body["cached"] is False
+ # No telephony manager mounted → the optional Advanced tab stays silent.
+ assert body["sections"]["advanced"]["status"] == "unknown"
+
+
+def test_section_health_missing_key_is_needs_setup(
+ server_with_brain: WebServer,
+ secret_store: _InMemorySecretStore,
+ no_real_provider_test: None,
+) -> None:
+ """The active brain provider with no stored key rolls up to needs_setup —
+ the 'you still have to set this up' (amber) signal, distinct from a broken
+ key (which would be 'error')."""
+ with TestClient(server_with_brain.app) as client:
+ body = client.get("/api/providers/section-health").json()
+ assert body["sections"]["brain"]["status"] == "needs_setup"
+ assert body["sections"]["brain"]["reason"] == "not_configured"
+
+
+def test_section_health_caches_then_refresh_bypasses(
+ server_with_brain: WebServer,
+ secret_store: _InMemorySecretStore,
+ no_real_provider_test: None,
+) -> None:
+ """Repeated opens / tab switches reuse the cached rollup; ?refresh=true (used
+ after a key save or provider switch) forces a fresh check."""
+ with TestClient(server_with_brain.app) as client:
+ assert client.get("/api/providers/section-health").json()["cached"] is False
+ assert client.get("/api/providers/section-health").json()["cached"] is True
+ assert (
+ client.get("/api/providers/section-health?refresh=true").json()["cached"]
+ is False
+ )
+
+
def test_list_providers_exposes_credential_help_and_billing(
server_with_brain: WebServer, secret_store: _InMemorySecretStore
) -> None:
diff --git a/tests/integration/test_sessions_open_with.py b/tests/integration/test_sessions_open_with.py
new file mode 100644
index 0000000000..416b5f68a1
--- /dev/null
+++ b/tests/integration/test_sessions_open_with.py
@@ -0,0 +1,137 @@
+"""Integration tests for POST /api/sessions/{id}/open-with (open-in-editor).
+
+Pins the security/gating contract: desktop-only (404 when disabled), the closed
+opener-id set (400 on anything else, 409 when the opener isn't installed), and
+that the transcript is materialized to a temp file and handed to the right
+``open_path`` launcher (open_file for "default", open_file_with for an editor).
+"""
+from __future__ import annotations
+
+import tempfile
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+import jarvis.platform.open_path as open_path_mod
+import jarvis.ui.web.outputs_routes as outputs_routes
+from jarvis.sessions.models import VoiceSessionRow, VoiceTurnRow
+from jarvis.ui.web.sessions_routes import router as sessions_router
+
+
+class _FakeStore:
+ def __init__(self, session: VoiceSessionRow | None) -> None:
+ self._session = session
+ self._turns = [
+ VoiceTurnRow(
+ id="t0", session_id="sess-1", idx=0, started_ms=1_717_780_000_000,
+ user_text="Hallo", jarvis_text="Hi.",
+ )
+ ]
+
+ def get_session(self, sid: str) -> VoiceSessionRow | None:
+ if self._session and self._session.id == sid:
+ return self._session
+ return None
+
+ def get_turns(self, sid: str) -> list[VoiceTurnRow]:
+ return self._turns
+
+ def get_events(self, sid: str) -> list:
+ return []
+
+
+def _client(native: bool, *, session: VoiceSessionRow | None) -> TestClient:
+ app = FastAPI()
+ app.state.native_file_actions = native
+ app.state.session_store = _FakeStore(session)
+ app.include_router(sessions_router)
+ return TestClient(app)
+
+
+def session() -> VoiceSessionRow:
+ return VoiceSessionRow(id="sess-1", started_ms=1_717_780_000_000)
+
+
[email protected](autouse=True)
+def _temp_transcripts(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ monkeypatch.setattr(tempfile, "gettempdir", lambda: str(tmp_path))
+ return tmp_path
+
+
+def test_open_with_disabled_returns_404(session: VoiceSessionRow) -> None:
+ client = _client(native=False, session=session)
+ res = client.post(
+ "/api/sessions/sess-1/open-with?format=markdown", json={"opener": "default"}
+ )
+ assert res.status_code == 404
+
+
+def test_open_with_rejects_unknown_opener(session: VoiceSessionRow) -> None:
+ client = _client(native=True, session=session)
+ res = client.post(
+ "/api/sessions/sess-1/open-with",
+ json={"opener": "/usr/bin/evil"},
+ )
+ assert res.status_code == 400
+
+
+def test_open_with_default_uses_open_file(
+ session: VoiceSessionRow, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ calls: list[Path] = []
+ monkeypatch.setattr(
+ open_path_mod, "open_file", lambda p: (calls.append(p) or True)
+ )
+ client = _client(native=True, session=session)
+ res = client.post(
+ "/api/sessions/sess-1/open-with?format=markdown", json={"opener": "default"}
+ )
+ assert res.status_code == 200, res.text
+ body = res.json()
+ assert body["opened"] is True
+ assert body["opener"] == "default"
+ # Transcript was materialized under the temp dir and handed to open_file.
+ assert len(calls) == 1
+ assert calls[0].parent == tmp_path / "jarvis-transcripts"
+ assert calls[0].exists()
+ assert calls[0].suffix == ".md"
+
+
+def test_open_with_editor_uses_open_file_with(
+ session: VoiceSessionRow, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(
+ outputs_routes, "_resolve_opener", lambda oid: ("executable", "/usr/bin/code")
+ )
+ captured: dict = {}
+ monkeypatch.setattr(
+ open_path_mod,
+ "open_file_with",
+ lambda p, kind, value: (
+ captured.update({"path": p, "kind": kind, "value": value}) or True
+ ),
+ )
+ client = _client(native=True, session=session)
+ res = client.post(
+ "/api/sessions/sess-1/open-with?format=plain", json={"opener": "code"}
+ )
+ assert res.status_code == 200, res.text
+ assert res.json()["opened"] is True
+ assert captured["kind"] == "executable"
+ assert captured["value"] == "/usr/bin/code"
+ assert captured["path"].suffix == ".txt"
+
+
+def test_open_with_unavailable_opener_returns_409(
+ session: VoiceSessionRow, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # Known id, but not installed on this host → resolver yields None.
+ monkeypatch.setattr(outputs_routes, "_resolve_opener", lambda oid: None)
+ client = _client(native=True, session=session)
+ res = client.post(
+ "/api/sessions/sess-1/open-with", json={"opener": "cursor"}
+ )
+ assert res.status_code == 409
diff --git a/tests/integration/test_tasks_recurring.py b/tests/integration/test_tasks_recurring.py
index efd8722dfb..0e1faae4ea 100644
--- a/tests/integration/test_tasks_recurring.py
+++ b/tests/integration/test_tasks_recurring.py
@@ -95,7 +95,7 @@ class _FakeRunner:
def __init__(self) -> None:
self.dispatched: list[str] = []
- async def run(self, task_id: str) -> None:
+ async def run(self, task_id: str, **_kwargs: object) -> None:
self.dispatched.append(task_id)
diff --git a/tests/integration/test_when_then_e2e.py b/tests/integration/test_when_then_e2e.py
new file mode 100644
index 0000000000..4cbf450bbd
--- /dev/null
+++ b/tests/integration/test_when_then_e2e.py
@@ -0,0 +1,130 @@
+"""End-to-end When-Then proof: MissionCompleted on the global bus drives a real
+TaskScheduler → real TaskRunner → Computer-Use dispatch + spoken confirmation.
+
+This is the whole feature wired together with the production Scheduler and Runner
+(only the harness is a fake) — a regression anywhere in the chain (filter, event
+passthrough, templating, notify) fails here.
+"""
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.core.bus import EventBus
+from jarvis.core.events import AnnouncementRequested, MissionCompleted
+from jarvis.core.protocols import HarnessResult
+from jarvis.tasks.runner import TaskRunner
+from jarvis.tasks.scheduler import TaskScheduler
+from jarvis.tasks.schema import HarnessDispatchAction, TaskSpec, TriggerOnEvent
+from jarvis.tasks.store import TaskStore
+
+
+class FakeHarnessManager:
+ def __init__(self) -> None:
+ self.dispatched: list[tuple[str, Any]] = []
+
+ async def dispatch(self, name: str, task: Any):
+ self.dispatched.append((name, task))
+
+ async def gen():
+ yield HarnessResult(stdout="opened\n", exit_code=0, is_final=True)
+ return gen()
+
+
+async def store(tmp_path: Path):
+ s = TaskStore(tmp_path / "e2e.db")
+ await s.init()
+ try:
+ yield s
+ finally:
+ await s.close()
+
+
+async def test_mission_finished_opens_browser_and_speaks(store: TaskStore) -> None:
+ bus = EventBus()
+ harness = FakeHarnessManager()
+ runner = TaskRunner(store=store, bus=bus, harness_manager=harness)
+ scheduler = TaskScheduler(store=store, bus=bus, runner=runner)
+ scheduler.bind_bus()
+
+ announcements: list[AnnouncementRequested] = []
+
+ async def on_ann(e: AnnouncementRequested) -> None:
+ announcements.append(e)
+
+ bus.subscribe(AnnouncementRequested, on_ann)
+
+ # The standing When-Then rule the user would build in the dialog.
+ rule = TaskSpec(
+ title="Mission done → open + notify",
+ trigger=TriggerOnEvent(
+ event_name="MissionCompleted",
+ filter_expr="status == 'approved'",
+ max_firings=None,
+ ),
+ action=HarnessDispatchAction(
+ harness="screenshot",
+ prompt="Open {result_uri} in the browser.",
+ allow_computer_use=True,
+ ),
+ announce_on_success="Your mission is ready — I opened {result_uri}.",
+ )
+ await scheduler.schedule(rule)
+
+ # A mission finishes — the bridge would publish exactly this on the global bus.
+ await bus.publish(
+ MissionCompleted(
+ mission_id="run-42",
+ status="approved",
+ result_uri="/outputs/report.md",
+ summary_en="Report written.",
+ )
+ )
+ # The scheduler dispatches the runner fire-and-forget; let it run to completion.
+ for _ in range(50):
+ await asyncio.sleep(0.01)
+ if announcements:
+ break
+
+ # Computer-Use was dispatched with the interpolated goal.
+ assert len(harness.dispatched) == 1
+ name, task = harness.dispatched[0]
+ assert name == "screenshot"
+ assert task.prompt == "Open /outputs/report.md in the browser."
+ assert task.allow_computer_use is True
+
+ # And Jarvis confirmed it (the post-hangup-capable readback kind).
+ assert len(announcements) == 1
+ assert announcements[0].text == "Your mission is ready — I opened /outputs/report.md."
+ assert announcements[0].kind == "subagent"
+
+ # The task itself completed.
+ task_row = await store.get(str(rule.id))
+ assert task_row is not None
+ assert task_row["state"] == "completed"
+
+
+async def test_failed_mission_does_not_fire_an_approved_rule(store: TaskStore) -> None:
+ bus = EventBus()
+ harness = FakeHarnessManager()
+ runner = TaskRunner(store=store, bus=bus, harness_manager=harness)
+ scheduler = TaskScheduler(store=store, bus=bus, runner=runner)
+ scheduler.bind_bus()
+
+ rule = TaskSpec(
+ title="only on success",
+ trigger=TriggerOnEvent(event_name="MissionCompleted",
+ filter_expr="status == 'approved'", max_firings=None),
+ action=HarnessDispatchAction(harness="screenshot", prompt="x",
+ allow_computer_use=True),
+ )
+ await scheduler.schedule(rule)
+
+ await bus.publish(MissionCompleted(mission_id="run-7", status="failed"))
+ await asyncio.sleep(0.1)
+
+ assert harness.dispatched == []
diff --git a/tests/missions/critic/test_runner_claude_direct.py b/tests/missions/critic/test_runner_claude_direct.py
index 5f2e05bd7a..a2a829550c 100644
--- a/tests/missions/critic/test_runner_claude_direct.py
+++ b/tests/missions/critic/test_runner_claude_direct.py
@@ -172,19 +172,28 @@ async def test_non_claude_provider_critic_uses_claude_model_not_foreign(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path,
provider: str, foreign_model: str,
) -> None:
- """Regression (2026-06-08): with a non-claude [brain.sub_jarvis].provider the
- critic correctly falls back to the direct claude critic — but it MUST pass a
- claude model to ``claude --model``, never the foreign provider model
- (e.g. ``grok-4.3``), which the claude CLI rejects with returncode=1. That
- failed the critic twice -> ``critic_unavailable`` and the whole mission
- FAILED even though the worker had delivered real work (the sibling of the
- ClaudeDirectWorker provider-refusal bug, same root cause in the critic path).
+ """Regression (2026-06-08): with a non-claude [brain.sub_jarvis].provider AND
+ no usable API key (so the in-process API critic cannot run, B2), the critic
+ falls back to the direct claude critic — but it MUST pass a claude model to
+ ``claude --model``, never the foreign provider model (e.g. ``grok-4.3``), which
+ the claude CLI rejects with returncode=1. That failed the critic twice ->
+ ``critic_unavailable`` and the whole mission FAILED even though the worker had
+ delivered real work.
+
+ B2 (2026-06-29): a keyed API provider now grades IN-PROCESS first; this test
+ pins the NO-API-KEY fallback path, so the in-process resolver is forced empty.
"""
captured: dict[str, Any] = {}
monkeypatch.setattr(
"jarvis.missions.critic.runner._resolve_critic_provider_model",
lambda: (provider, foreign_model),
)
+ # No API key available → the in-process API critic is skipped and the flow
+ # falls through to the claude-direct critic this test pins.
+ monkeypatch.setattr(
+ "jarvis.missions.critic.runner._resolve_api_critic_provider",
+ lambda *a, **k: (None, None),
+ )
monkeypatch.setattr(
"jarvis.missions.workers.claude_direct_worker."
"_resolve_claude_argv_prefix",
diff --git a/tests/missions/test_subagent_worker_routing.py b/tests/missions/test_jarvis_agent_worker_routing.py
similarity index 100%
rename from tests/missions/test_subagent_worker_routing.py
rename to tests/missions/test_jarvis_agent_worker_routing.py
diff --git a/tests/missions/test_mission_event_bridge.py b/tests/missions/test_mission_event_bridge.py
new file mode 100644
index 0000000000..685fcc3f41
--- /dev/null
+++ b/tests/missions/test_mission_event_bridge.py
@@ -0,0 +1,101 @@
+"""MissionEventBridge — terminal MissionBus events become global MissionCompleted.
+
+Guards the When-Then seam: a finished mission must surface as exactly one flat
+``MissionCompleted`` on the global bus (so the Tasks scheduler can match it), and
+non-terminal events must NOT leak through.
+"""
+from __future__ import annotations
+
+from jarvis.core.bus import EventBus
+from jarvis.core.events import MissionCompleted
+from jarvis.missions.event_bus import MissionBus
+from jarvis.missions.events import (
+ EventEnvelope,
+ MissionApproved,
+ MissionCancelled,
+ MissionFailed,
+ MissionTimedOut,
+ WorkerProgress,
+ now_ms,
+)
+from jarvis.missions.task_bridge import MissionEventBridge
+
+
+def _env(payload, *, mission_id: str = "m1", source_actor: str = "kontrollierer"):
+ return EventEnvelope(
+ mission_id=mission_id,
+ source_actor=source_actor, # type: ignore[arg-type]
+ ts_ms=now_ms(),
+ payload=payload,
+ )
+
+
+async def _bridge_with_collector() -> tuple[MissionBus, list[MissionCompleted]]:
+ mbus = MissionBus()
+ gbus = EventBus()
+ got: list[MissionCompleted] = []
+
+ async def collect(e: MissionCompleted) -> None:
+ got.append(e)
+
+ gbus.subscribe(MissionCompleted, collect)
+ bridge = MissionEventBridge(bus=mbus, global_bus=gbus)
+ await bridge.start()
+ return mbus, got
+
+
+async def test_approved_becomes_mission_completed() -> None:
+ mbus, got = await _bridge_with_collector()
+ await mbus.publish(
+ _env(
+ MissionApproved(
+ result_uri="/out/result.md",
+ tokens_used=100,
+ cost_usd=0.01,
+ wall_ms=5000,
+ summary_de="Fertig.",
+ summary_en="Done.",
+ ),
+ mission_id="abc",
+ )
+ )
+ assert len(got) == 1
+ sig = got[0]
+ assert sig.mission_id == "abc"
+ assert sig.status == "approved"
+ assert sig.result_uri == "/out/result.md"
+ assert sig.summary_de == "Fertig."
+ assert sig.summary_en == "Done."
+
+
+async def test_failed_carries_reason() -> None:
+ mbus, got = await _bridge_with_collector()
+ await mbus.publish(
+ _env(MissionFailed(reason="timeout: worker", last_state="running"))
+ )
+ assert len(got) == 1
+ assert got[0].status == "failed"
+ assert got[0].reason == "timeout: worker"
+
+
+async def test_cancelled_and_timed_out_map() -> None:
+ mbus, got = await _bridge_with_collector()
+ await mbus.publish(_env(MissionCancelled(cascade=False, reason="user")))
+ await mbus.publish(_env(MissionTimedOut(deadline_ms=1000, last_progress_ms=500)))
+ statuses = [g.status for g in got]
+ assert statuses == ["cancelled", "timed_out"]
+
+
+async def test_non_terminal_event_does_not_bridge() -> None:
+ mbus, got = await _bridge_with_collector()
+ await mbus.publish(_env(WorkerProgress(worker_id="w1", note="step 2")))
+ assert got == []
+
+
+async def test_completed_signal_matches_status_filter() -> None:
+ """The flat ``status`` field must satisfy the scheduler's filter_expr AST."""
+ from jarvis.tasks.scheduler import _match_filter
+
+ sig = MissionCompleted(mission_id="m1", status="approved")
+ assert _match_filter(sig, "status == 'approved'") is True
+ assert _match_filter(sig, "status == 'failed'") is False
diff --git a/tests/missions/test_voice_announcer.py b/tests/missions/test_voice_announcer.py
index b9dd54b710..ef10b20b3f 100644
--- a/tests/missions/test_voice_announcer.py
+++ b/tests/missions/test_voice_announcer.py
@@ -29,6 +29,28 @@ from jarvis.missions.ids import uuid7_str
from jarvis.missions.voice.announcer import MissionAnnouncer
+class _FakeAckProvider:
+ """Minimal flash-provider stand-in for ReadbackComposer wiring tests."""
+
+ def __init__(self, reply: str | None) -> None:
+ self.reply = reply
+
+ async def run(self, utterance: str, language: str, *, persona_prompt: str) -> str | None:
+ return self.reply
+
+
+def _composer_with(reply: str | None):
+ from jarvis.brain.ack_brain import CircuitBreaker
+ from jarvis.brain.ack_brain.config import AckBrainConfig
+ from jarvis.voice.contextual_readback import ReadbackComposer
+
+ return ReadbackComposer(
+ provider=_FakeAckProvider(reply),
+ config=AckBrainConfig(timeout_ms=1500),
+ breaker=CircuitBreaker(threshold=3, cooldown_s=60),
+ )
+
+
@pytest.fixture
async def store_and_bus(tmp_missions_db: Path):
bus = MissionBus()
@@ -124,6 +146,74 @@ async def test_approved_emits_announcement(store_and_bus) -> None:
assert ann.priority == "normal"
+async def test_approved_readback_is_contextually_rephrased(store_and_bus) -> None:
+ """With a composer wired, the signed summary is spoken in a fresh phrasing
+ (maintainer mandate: no fixed stock phrases) — but still faithfully."""
+ store, bus = store_and_bus
+ speech_bus = EventBus()
+ captured = _collect_announcements(speech_bus)
+
+ announcer = MissionAnnouncer(
+ bus=bus, store=store, speech_bus=speech_bus,
+ readback_composer=_composer_with("All done — the mission completed."),
+ )
+ await announcer.start()
+
+ mid = await _seed_voice_mission(store, language="en")
+ await store.append_and_publish(
+ EventEnvelope(
+ mission_id=mid,
+ source_actor="kontrollierer",
+ ts_ms=now_ms(),
+ payload=MissionApproved(
+ result_uri=f"mission://{mid}", tokens_used=100, cost_usd=0.05,
+ wall_ms=1000, summary_de="Mission abgeschlossen.",
+ summary_en="Mission completed.",
+ ),
+ )
+ )
+
+ assert len(captured) == 1
+ text = captured[0].text
+ assert text != "Mission completed." # rephrased, not the canned summary
+ assert "completed" in text.lower() # but still faithful to the signed fact
+
+
+async def test_approved_falls_back_to_signed_summary_when_generation_fails(
+ store_and_bus,
+) -> None:
+ """A composer whose provider yields nothing must fall back to the exact
+ Kontrollierer-signed summary (ADR-0009 + AD-OE6 zero silent drops)."""
+ store, bus = store_and_bus
+ speech_bus = EventBus()
+ captured = _collect_announcements(speech_bus)
+
+ announcer = MissionAnnouncer(
+ bus=bus, store=store, speech_bus=speech_bus,
+ readback_composer=_composer_with(""), # provider returns empty -> fallback
+ )
+ await announcer.start()
+
+ mid = await _seed_voice_mission(store, language="de")
+ await store.append_and_publish(
+ EventEnvelope(
+ mission_id=mid,
+ source_actor="kontrollierer",
+ ts_ms=now_ms(),
+ payload=MissionApproved(
+ result_uri=f"mission://{mid}", tokens_used=100, cost_usd=0.05,
+ wall_ms=1000, summary_de="Mission abgeschlossen.",
+ summary_en="Mission completed.",
+ ),
+ )
+ )
+
+ assert len(captured) == 1
+ assert captured[0].text == "Mission abgeschlossen."
+
+
@pytest.mark.asyncio
async def test_approved_uses_summary_en_when_lang_en(store_and_bus) -> None:
store, bus = store_and_bus
diff --git a/tests/missions/workers/test_api_agent_worker_model_resolution.py b/tests/missions/workers/test_api_agent_worker_model_resolution.py
new file mode 100644
index 0000000000..a207742baa
--- /dev/null
+++ b/tests/missions/workers/test_api_agent_worker_model_resolution.py
@@ -0,0 +1,66 @@
+"""Regression: the in-process API-agent worker must run the user's PICKED model,
+never a hardcoded paid foreign-family default.
+
+Live forensic 2026-06-29: ``api_agent_worker._DEFAULT_MODEL["openrouter"]`` was
+``anthropic/claude-opus-4.8``. When a mission step carried no model and the
+sub-agent provider was OpenRouter, the heavy worker ran Opus 4.8 ON THE OPENROUTER
+KEY — a paid model the user never picked (the user's OpenRouter pick was a FREE
+model). The worker must resolve the model from the user's selection first:
+the step's explicit model → the matching ``[brain.sub_jarvis].model`` →
+``[brain.providers[provider]].model`` → only then a non-paid default
+(AP-21/AP-22, open-source single-key §3).
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.core.config import BrainProviderConfig, BrainTierConfig, JarvisConfig
+from jarvis.missions.workers import api_agent_worker as m
+
+_FREE = "nvidia/nemotron-3-ultra-550b-a55b:free"
+
+
+def _patch_config(monkeypatch: pytest.MonkeyPatch, config: JarvisConfig) -> None:
+ monkeypatch.setattr("jarvis.core.config.load_config", lambda: config)
+
+
+def test_explicit_step_model_always_wins(monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_config(monkeypatch, JarvisConfig())
+ assert m._resolve_worker_model("openrouter", "openai/gpt-5.5") == "openai/gpt-5.5"
+
+
+def test_openrouter_uses_provider_pick_not_paid_opus(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ config = JarvisConfig()
+ config.brain.providers["openrouter"] = BrainProviderConfig(model=_FREE)
+ _patch_config(monkeypatch, config)
+
+ got = m._resolve_worker_model("openrouter", "")
+ assert got == _FREE
+ assert "anthropic/claude" not in got
+
+
+def test_subagent_pin_used_only_for_its_own_provider(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """[brain.sub_jarvis].model belongs to [brain.sub_jarvis].provider — it must
+ NOT be applied to a different worker provider (that is how a claude-opus pin
+ set for antigravity would otherwise leak onto the OpenRouter key)."""
+ config = JarvisConfig()
+ config.brain.sub_jarvis = BrainTierConfig(
+ provider="antigravity", model="claude-opus-4-8",
+ )
+ config.brain.providers["openrouter"] = BrainProviderConfig(model=_FREE)
+ _patch_config(monkeypatch, config)
+
+ got = m._resolve_worker_model("openrouter", "")
+ assert got == _FREE, "antigravity's opus pin leaked onto the openrouter worker"
+
+
+def test_openrouter_default_without_any_pick_is_not_paid_anthropic(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _patch_config(monkeypatch, JarvisConfig()) # nothing configured
+ got = m._resolve_worker_model("openrouter", "") or ""
+ assert "anthropic/claude" not in got
diff --git a/tests/missions/workers/test_google_cli_worker.py b/tests/missions/workers/test_google_cli_worker.py
index b11ea0e91d..4ed934aca3 100644
--- a/tests/missions/workers/test_google_cli_worker.py
+++ b/tests/missions/workers/test_google_cli_worker.py
@@ -27,11 +27,19 @@ class _FakeJob:
self.assigned.append(pid)
-def test_agy_worker_argv_is_print_plus_skip_permissions() -> None:
- argv = _build_agy_worker_argv("agy.exe", "Create a file\nThen stop")
+def test_agy_worker_argv_is_print_plus_skip_permissions(tmp_path) -> None:
+ argv = _build_agy_worker_argv("agy.exe", "Create a file\nThen stop", tmp_path)
assert argv[0] == "agy.exe"
assert "--print" in argv
assert "--dangerously-skip-permissions" in argv # auto-approve so it can write
+ # The per-mission git worktree MUST be added as agy's active workspace.
+ # Without it agy has "no active workspace" in --print mode and writes every
+ # deliverable into its home-relative brain/<session>/ (or scratch/<project>/)
+ # dir — the worktree stays empty, the Critic sees an empty `git diff HEAD`,
+ # and EVERY antigravity mission fails `critic_loop_exhausted`
+ # (forensic 2026-06-27, mission_019f07cb et al.).
+ assert "--add-dir" in argv
+ assert argv[argv.index("--add-dir") + 1] == str(tmp_path)
# gemini-CLI flags must NOT appear — agy doesn't understand them.
assert "--yolo" not in argv
assert "--output-format" not in argv
@@ -54,6 +62,8 @@ async def test_spawn_agy_uses_pty_and_assigns_job(monkeypatch, tmp_path) -> None
mod, "resolve_google_cli", lambda: GoogleCli(kind="agy", argv_prefix=["agy.exe"])
)
monkeypatch.setattr(mod, "ensure_isolated_home", lambda **k: str(tmp_path / "iso"))
+ # User is signed in (OAuth) → agy runs over the subscription, not the key.
+ monkeypatch.setattr(mod, "_oauth_login_present", lambda *_a: True)
captured: dict = {}
def _fake_run(argv, *, timeout_s, cwd=None, env=None, on_spawn=None, **kw):
@@ -81,6 +91,10 @@ async def test_spawn_agy_uses_pty_and_assigns_job(monkeypatch, tmp_path) -> None
)
]
assert "--dangerously-skip-permissions" in captured["argv"]
+ # The worktree is handed to agy as its active workspace (--add-dir) so files
+ # land where the Critic's git diff can see them, not in agy's brain/scratch.
+ assert "--add-dir" in captured["argv"]
+ assert str(tmp_path) in captured["argv"]
assert captured["cwd"] == str(tmp_path)
assert "GEMINI_API_KEY" not in captured["env"] # OAuth, not the key
assert job.assigned == [4321] # PID assigned to the Job Object via on_spawn
@@ -97,6 +111,7 @@ async def test_spawn_agy_timeout_is_error(monkeypatch, tmp_path) -> None:
mod, "resolve_google_cli", lambda: GoogleCli(kind="agy", argv_prefix=["agy.exe"])
)
monkeypatch.setattr(mod, "ensure_isolated_home", lambda **k: str(tmp_path / "iso"))
+ monkeypatch.setattr(mod, "_oauth_login_present", lambda *_a: True)
monkeypatch.setattr(
mod,
"run_cli_over_pty",
@@ -134,3 +149,43 @@ async def test_spawn_gemini_kind_delegates_to_gemini_worker(monkeypatch, tmp_pat
]
assert called["gemini"] is True # Gemini CLI uses the pipe path, not the PTY
assert "GEMINI_EVENT" in events
+
+
+async def test_spawn_agy_with_gemini_key_but_no_oauth_bills_via_gemini(
+ monkeypatch, tmp_path
+) -> None:
+ """Antigravity dual billing: agy is installed, but the user has NO Google
+ OAuth login and a Gemini API key IS set → bill per token via the proven
+ GeminiWorker, NOT the agy PTY path (which would coerce OAuth)."""
+ monkeypatch.setattr(
+ mod, "resolve_google_cli", lambda: GoogleCli(kind="agy", argv_prefix=["agy.exe"])
+ )
+ monkeypatch.setattr(mod, "_oauth_login_present", lambda *_a: False) # not signed in
+
+ called = {"gemini": False}
+
+ async def _fake_gemini_spawn(self, prompt, **kw):
+ called["gemini"] = True
+ yield "GEMINI_EVENT"
+
+ monkeypatch.setattr(mod.GeminiWorker, "spawn", _fake_gemini_spawn)
+ # run_cli_over_pty must NOT be called on this path — make it explode if it is.
+ monkeypatch.setattr(
+ mod, "run_cli_over_pty",
+ lambda *a, **k: (_ for _ in ()).throw(AssertionError("agy PTY path must not run")),
+ )
+ worker = GoogleCliWorker()
+ events = [
+ e
+ async for e in worker.spawn(
+ "x",
+ worktree=tmp_path,
+ env={"GEMINI_API_KEY": "AIza-fake", "PATH": "/p"},
+ job=_FakeJob(),
+ worker_id="w",
+ log_dir=tmp_path / "l",
+ )
+ ]
+ assert called["gemini"] is True # billed via the Gemini API worker
+ assert "GEMINI_EVENT" in events
diff --git a/tests/overlay/test_cursor_motion.py b/tests/overlay/test_cursor_motion.py
index 545038c33d..d5872d1268 100644
--- a/tests/overlay/test_cursor_motion.py
+++ b/tests/overlay/test_cursor_motion.py
@@ -82,3 +82,23 @@ def test_glide_os_cursor_zero_duration_is_instant() -> None:
duration_ms=0,
)
assert moves == [(42, 42)]
+
+
+def test_win_set_pos_does_not_raise_on_unreliable_zero_return(monkeypatch) -> None:
+ """Regression (CU clicks void on the LEFT monitor): SetCursorPos returns 0
+ (reports failure) yet STILL moves the cursor when crossing into a monitor
+ positioned left of primary — negative virtual-desktop X. The old
+ ``if not SetCursorPos(): raise`` turned that spurious 0 into a hard error that
+ aborted every left-monitor click. _win_set_pos must trust the move and NOT
+ raise on the boolean."""
+ from jarvis.control import cursor_motion
+
+ calls: list[tuple[int, int]] = []
+
+ def _fake_raw(x: int, y: int) -> int:
+ calls.append((x, y))
+ return 0 # SetCursorPos "failure" return — must be ignored
+
+ monkeypatch.setattr(cursor_motion, "_raw_set_cursor", _fake_raw)
+ cursor_motion._win_set_pos(-1280, 720) # negative X, must not raise
+ assert calls == [(-1280, 720)]
diff --git a/tests/overlay/test_subagent_noop.py b/tests/overlay/test_jarvis_agent_noop.py
similarity index 100%
rename from tests/overlay/test_subagent_noop.py
rename to tests/overlay/test_jarvis_agent_noop.py
diff --git a/tests/review/test_dispatch_tool.py b/tests/review/test_dispatch_tool.py
index cd81c75eb0..3dc1b45d5b 100644
--- a/tests/review/test_dispatch_tool.py
+++ b/tests/review/test_dispatch_tool.py
@@ -279,8 +279,9 @@ def test_entry_point_registered() -> None:
def test_router_tools_includes_dispatch_with_review() -> None:
"""Plan-§AD-14 / Phase 8.4: ROUTER_TOOLS enthält dispatch-with-review."""
- from jarvis.brain.factory import ROUTER_TOOLS, SUB_TOOLS
+ # NB: ``SUB_TOOLS`` was deleted in Welle 4 (the Sub-Jarvis tier no longer
+ # exists — only "router" remains). The former recursion-guard assertion
+ # against SUB_TOOLS is obsolete; updated 2026-06-28.
+ from jarvis.brain.factory import ROUTER_TOOLS
assert "dispatch-with-review" in ROUTER_TOOLS
- # Recursion-Schutz: Sub-Jarvis darf das Tool NICHT haben
- assert "dispatch-with-review" not in SUB_TOOLS
diff --git a/tests/review/test_subagent_files.py b/tests/review/test_jarvis_agent_files.py
similarity index 100%
rename from tests/review/test_subagent_files.py
rename to tests/review/test_jarvis_agent_files.py
diff --git a/tests/unit/audio/test_player_stall_recovery.py b/tests/unit/audio/test_player_stall_recovery.py
index a9c9a05794..9873f0f623 100644
--- a/tests/unit/audio/test_player_stall_recovery.py
+++ b/tests/unit/audio/test_player_stall_recovery.py
@@ -107,6 +107,24 @@ async def test_play_chunks_resets_progress_at_start() -> None:
assert player.frames_written == 0
+async def test_play_chunks_stamps_progress_owner_at_start() -> None:
+ """The pipeline watchdog can only ignore unrelated playback progress if the
+ real player stamps which ``play_chunks`` task owns the current progress
+ counter."""
+ player = AudioPlayer.__new__(AudioPlayer)
+ player._init_progress()
+ player._device_logged = True
+ player._play_lock = None
+
+ task = asyncio.current_task()
+ assert task is not None
+
+ await player.play_chunks(_no_chunks())
+
+ assert player.last_write_owner_task_id == id(task)
+
+
@pytest.mark.asyncio
async def test_play_chunks_resets_progress_before_lock_wait() -> None:
"""The reset must happen BEFORE awaiting the play lock.
diff --git a/tests/unit/audio/test_player_welle2.py b/tests/unit/audio/test_player_welle2.py
index c578f60c8e..fdf9fd5b9d 100644
--- a/tests/unit/audio/test_player_welle2.py
+++ b/tests/unit/audio/test_player_welle2.py
@@ -140,7 +140,7 @@ def test_write_samples_logs_warning_on_underflow(monkeypatch, caplog) -> None:
with caplog.at_level(logging.WARNING, logger="jarvis.audio.player"):
player._write_samples(stream, arr, source_rate=24000, device_rate=24000)
- # Audio is written in ~60 ms sub-blocks (so the whisper-bar equalizer can
+ # Audio is written in ~60 ms sub-blocks (so the jarvis-bar equalizer can
# follow Jarvis's voice), so 2400 frames @ 24 kHz become 1440 + 960 = two
# writes; each underflowing sub-block logs a warning. The behaviour under
# test is "an underflow is never silently discarded", not the block count.
diff --git a/tests/unit/audio/test_vad_torch_free.py b/tests/unit/audio/test_vad_torch_free.py
new file mode 100644
index 0000000000..1914da773d
--- /dev/null
+++ b/tests/unit/audio/test_vad_torch_free.py
@@ -0,0 +1,93 @@
+"""Silero VAD runs torch-free (onnxruntime + numpy) on the voice-boot path.
+
+The torch ``silero_vad`` package import was the dominant voice-boot cost
+(``vad-load`` 6-16 s — ``import torch`` starved in the serve-first boot storm),
+and it gated honest ``VoiceBootStatus(ready=True)``. ``SileroEndpointer`` now
+runs the bundled ``silero_vad.onnx`` model directly via onnxruntime (already warm
+from the wake model) with numpy-managed recurrent state, so the VAD load never
+imports torch and drops to ~0.1 s.
+
+These tests pin that contract: (1) the VAD path imports NO torch (checked in a
+fresh subprocess so an unrelated earlier import can't mask a regression), and
+(2) per-frame probabilities are well-formed (in [0, 1], silence reads low). The
+bit-for-bit match against the torch model is verified out-of-band (it would pull
+the heavy torch import into the test process); here we guard the boot-cost win.
+"""
+from __future__ import annotations
+
+import subprocess
+import sys
+
+import numpy as np
+import pytest
+
+from jarvis.audio.vad import SileroEndpointer
+
+
+def _bare_endpointer() -> SileroEndpointer:
+ """A SileroEndpointer with only the fields ``_prob`` touches (no __init__)."""
+ ep = SileroEndpointer.__new__(SileroEndpointer)
+ ep._session = None
+ ep._vad_state = None
+ ep._vad_context = None
+ return ep
+
+
+def _silero_onnx_available() -> bool:
+ import importlib.util
+
+ spec = importlib.util.find_spec("silero_vad")
+ if spec is None or spec.origin is None:
+ return False
+ import os
+
+ return os.path.exists(
+ os.path.join(os.path.dirname(spec.origin), "data", "silero_vad.onnx")
+ )
+
+
+pytestmark = pytest.mark.skipif(
+ not _silero_onnx_available(), reason="silero_vad ONNX model not installed"
+)
+
+
+def test_prob_is_well_formed_and_silence_reads_low() -> None:
+ ep = _bare_endpointer()
+ # Silence must score low; a couple of frames to let the RNN settle.
+ probs = [ep._prob(np.zeros(512, dtype=np.float32)) for _ in range(5)]
+ for p in probs:
+ assert 0.0 <= p <= 1.0
+ assert max(probs) < 0.3, f"silence should read low, got {probs}"
+
+
+def test_prob_accepts_exactly_512_float_samples() -> None:
+ ep = _bare_endpointer()
+ p = ep._prob(np.linspace(-0.1, 0.1, 512).astype(np.float32))
+ assert 0.0 <= p <= 1.0
+
+
+def test_vad_path_imports_no_torch() -> None:
+ """The whole point of the change: exercising the VAD must not import torch.
+
+ Run in a FRESH interpreter so a torch already imported by another test in
+ this process cannot mask a regression. Exit code 0 == torch absent.
+ """
+ script = (
+ "import sys, numpy as np;\n"
+ "from jarvis.audio.vad import SileroEndpointer;\n"
+ "ep = SileroEndpointer.__new__(SileroEndpointer);\n"
+ "ep._session = None; ep._vad_state = None; ep._vad_context = None;\n"
+ "ep._prob(np.zeros(512, dtype=np.float32));\n"
+ "assert 'torch' not in sys.modules, 'VAD path imported torch';\n"
+ "assert 'onnxruntime' in sys.modules, 'VAD should use onnxruntime';\n"
+ "print('OK')\n"
+ )
+ res = subprocess.run(
+ [sys.executable, "-c", script],
+ capture_output=True,
+ text=True,
+ timeout=120,
+ )
+ assert res.returncode == 0, (
+ f"VAD imported torch or failed.\nstdout={res.stdout}\nstderr={res.stderr}"
+ )
diff --git a/tests/unit/awareness/test_system_prompt_injection.py b/tests/unit/awareness/test_system_prompt_injection.py
index cf09e8ccae..5212ff777d 100644
--- a/tests/unit/awareness/test_system_prompt_injection.py
+++ b/tests/unit/awareness/test_system_prompt_injection.py
@@ -22,8 +22,14 @@ from jarvis.core.config import JarvisConfig
def _make_brain(awareness_manager: AwarenessManager | None) -> BrainManager:
+ # These tests assert the snapshot lands in the cached SYSTEM prompt. The
+ # default `cache_optimized_prompt=True` deliberately moves the snapshot into
+ # the per-turn user message instead (Wave-2 omni-latency), so pin the legacy
+ # in-system-prompt path here to test exactly that contract.
+ config = JarvisConfig()
+ config.performance.cache_optimized_prompt = False
return BrainManager(
- config=JarvisConfig(),
+ config=config,
bus=EventBus(),
tools={},
awareness_manager=awareness_manager,
diff --git a/tests/unit/brain/test_ack_brain/test_persona_language.py b/tests/unit/brain/test_ack_brain/test_persona_language.py
new file mode 100644
index 0000000000..ec8ba46f64
--- /dev/null
+++ b/tests/unit/brain/test_ack_brain/test_persona_language.py
@@ -0,0 +1,44 @@
+"""Language resolution + name-neutrality for the Flash-Brain preamble persona.
+
+Added 2026-06-29 with the name-neutral + Spanish rework. Guards that the
+preamble resolves de/en/es natively, never bakes in a product name, and carries
+no em dashes (which render as hard TTS pauses).
+"""
+from __future__ import annotations
+
+from jarvis.brain.ack_brain.persona_prompt import (
+ PERSONA_PROMPT_DE,
+ PERSONA_PROMPT_EN,
+ PERSONA_PROMPT_ES,
+ get_persona_prompt,
+)
+
+
+def test_get_persona_prompt_resolves_each_language() -> None:
+ assert get_persona_prompt("de") == PERSONA_PROMPT_DE
+ assert get_persona_prompt("en") == PERSONA_PROMPT_EN
+ assert get_persona_prompt("es") == PERSONA_PROMPT_ES
+
+
+def test_get_persona_prompt_normalises_tags_and_falls_back_to_de() -> None:
+ assert get_persona_prompt("en-US") == PERSONA_PROMPT_EN
+ assert get_persona_prompt("es-ES") == PERSONA_PROMPT_ES
+ assert get_persona_prompt("de-DE") == PERSONA_PROMPT_DE
+ # Unknown / empty / None falls back to German (the STT default on ambiguity).
+ assert get_persona_prompt("fr") == PERSONA_PROMPT_DE
+ assert get_persona_prompt("") == PERSONA_PROMPT_DE
+ assert get_persona_prompt(None) == PERSONA_PROMPT_DE
+
+
+def test_preamble_personas_are_name_neutral() -> None:
+ # No baked-in product name: the assistant's name is runtime-derived from the
+ # wake word and owned by the deep brain.
+ for prompt in (PERSONA_PROMPT_DE, PERSONA_PROMPT_EN, PERSONA_PROMPT_ES):
+ assert "JARVIS" not in prompt
+ assert "Jarvis" not in prompt
+
+
+def test_preamble_personas_have_no_em_dash() -> None:
+ for prompt in (PERSONA_PROMPT_DE, PERSONA_PROMPT_EN, PERSONA_PROMPT_ES):
+ assert "—" not in prompt # em dash
+ assert "–" not in prompt # en dash
diff --git a/tests/unit/brain/test_ack_brain/test_preferences.py b/tests/unit/brain/test_ack_brain/test_preferences.py
index 6f14a1b08d..2d127b7694 100644
--- a/tests/unit/brain/test_ack_brain/test_preferences.py
+++ b/tests/unit/brain/test_ack_brain/test_preferences.py
@@ -56,7 +56,7 @@ async def test_ack_prompt_includes_user_preferences_when_set() -> None:
assert provider.persona_prompts, "the provider should have been called"
prompt = provider.persona_prompts[0]
assert "PREFS-MARKER-XYZZY" in prompt
- assert "JARVIS" in prompt # base persona still present
+ assert "Vor-Antwort" in prompt # base persona still present (name-neutral marker)
async def test_ack_prompt_is_base_persona_when_no_preferences() -> None:
diff --git a/tests/unit/brain/test_anthropic_tool_name_sanitize.py b/tests/unit/brain/test_anthropic_tool_name_sanitize.py
new file mode 100644
index 0000000000..141c4884da
--- /dev/null
+++ b/tests/unit/brain/test_anthropic_tool_name_sanitize.py
@@ -0,0 +1,33 @@
+"""Direct-Anthropic (claude-api) tool-name sanitization — mirror of the
+OpenAI/OpenRouter fix so a user whose single key IS Anthropic also survives a tool
+turn that includes a slash-named MCP tool (jarvis/mcp/adapter.py). Anthropic
+rejects ``tools.N.custom.name`` for anything outside ``[a-zA-Z0-9_-]{1,128}``.
+"""
+from __future__ import annotations
+
+import re
+
+from jarvis.plugins.brain._anthropic_base import _tools_anthropic_format
+
+_VALID = re.compile(r"^[A-Za-z0-9_-]{1,128}$")
+
+
+def test_mcp_slash_tool_name_sanitized_for_anthropic():
+ out = _tools_anthropic_format(({"name": "github/get_pull_request"},))
+ assert _VALID.match(out[0]["name"]), f"{out[0]['name']!r} violates Anthropic pattern"
+
+
+def test_dot_and_colon_sanitized_for_anthropic():
+ out = _tools_anthropic_format(({"name": "notion.search:page"},))
+ assert _VALID.match(out[0]["name"])
+
+
+def test_valid_name_unchanged_for_anthropic():
+ out = _tools_anthropic_format(({"name": "search_web"},))
+ assert out[0]["name"] == "search_web"
+
+
+def test_collisions_stay_unique_for_anthropic():
+ out = _tools_anthropic_format(({"name": "a/b"}, {"name": "a_b"}))
+ names = [t["name"] for t in out]
+ assert len(set(names)) == 2 and all(_VALID.match(n) for n in names)
diff --git a/tests/unit/brain/test_antigravity_subagent_only.py b/tests/unit/brain/test_antigravity_worker_only.py
similarity index 100%
rename from tests/unit/brain/test_antigravity_subagent_only.py
rename to tests/unit/brain/test_antigravity_worker_only.py
diff --git a/tests/unit/brain/test_chosen_model_no_foreign_default.py b/tests/unit/brain/test_chosen_model_no_foreign_default.py
new file mode 100644
index 0000000000..ee1ccad5cf
--- /dev/null
+++ b/tests/unit/brain/test_chosen_model_no_foreign_default.py
@@ -0,0 +1,179 @@
+"""Regression: a provider's missing ``deep_model`` must reuse the user's CHOSEN
+model, never a hardcoded foreign-family default.
+
+Live forensic 2026-06-29 (session 18:09:59): the user's brain was OpenRouter with
+``model = "nvidia/nemotron-3-ultra-550b-a55b:free"`` — a FREE model that answers
+HTTP 200 with the current key. Yet every turn spoke the provider-down apology
+("Entschuldige, ich komme gerade nicht an mein Sprachmodell"). Root cause: the
+OpenRouter account had hit its per-key spend limit, so PAID models 403'd
+("Key limit exceeded (total limit)") while the chosen FREE model kept working.
+But the fallback chain never tried the free model for the deep slot:
+``_deep_model("openrouter")`` returned the hardcoded ``anthropic/claude-opus-4.8``
+default (no ``deep_model`` in jarvis.toml) — a PAID model blocked by the same
+limit — so the turn bricked despite a healthy, user-selected model.
+
+A universal gateway (OpenRouter) selected by the user must run the model the user
+chose, not silently hijack the turn onto the most expensive Anthropic model.
+Provider-agnostic per AP-21/AP-22 and the open-source single-key mandate (§3).
+"""
+from __future__ import annotations
+
+import logging
+
+import pytest
+
+from jarvis.brain.manager import BrainManager
+from jarvis.core.bus import EventBus
+from jarvis.core.config import BrainProviderConfig, JarvisConfig
+
+_FREE = "nvidia/nemotron-3-ultra-550b-a55b:free"
+
+
+def _manager_with_openrouter_free() -> BrainManager:
+ config = JarvisConfig()
+ config.brain.primary = "openrouter"
+ # The user picked a single free model and set NO separate deep_model — the
+ # common case for an OpenRouter-only downloader.
+ config.brain.providers["openrouter"] = BrainProviderConfig(model=_FREE)
+ return BrainManager(config=config, bus=EventBus(), tools={})
+
+
+def test_fast_model_uses_chosen_openrouter_model() -> None:
+ mgr = _manager_with_openrouter_free()
+ assert mgr._fast_model("openrouter") == _FREE
+
+
+def test_deep_model_without_explicit_deep_reuses_chosen_model() -> None:
+ mgr = _manager_with_openrouter_free()
+ deep = mgr._deep_model("openrouter") or ""
+ # The bug returned "anthropic/claude-opus-4.8" here.
+ assert deep == _FREE, f"deep slot hijacked to a foreign-family default: {deep!r}"
+ assert "anthropic/claude" not in deep
+
+
+def test_fast_chain_never_injects_paid_anthropic_default_for_openrouter() -> None:
+ mgr = _manager_with_openrouter_free()
+ # Only OpenRouter is reachable (single-provider downloader).
+ mgr._registry.available = lambda: {"openrouter"} # type: ignore[assignment]
+ mgr._dead_providers.clear()
+
+ chain = mgr._build_fallback_chain("fast")
+ openrouter_models = [m for (p, m) in chain if p == "openrouter"]
+
+ assert openrouter_models, "OpenRouter must appear in its own chain"
+ for m in openrouter_models:
+ assert "anthropic/claude" not in (m or ""), (
+ f"chain hijacked OpenRouter onto a paid Anthropic default: {m!r}"
+ )
+ assert m == _FREE
+
+
+def test_get_brain_keeps_chosen_model_when_base_url_kwarg_rejected() -> None:
+ """The deepest root cause (live forensic 2026-06-29): even with the chain
+ correctly choosing nemotron:free, the brain that actually ran sent
+ anthropic/claude-opus-4.8 on the wire.
+
+ ``jarvis.toml`` sets ``[brain.providers.openrouter] base_url=...``, so
+ ``_get_brain`` passes ``base_url`` to ``instantiate``. But
+ ``OpenRouterBrain.__init__`` accepts only ``model`` → ``TypeError`` → the old
+ fallback re-instantiated with NO kwargs at all, dropping ``model`` too, so the
+ brain fell back to its hardcoded ``DEFAULT_MODEL`` = anthropic/claude-opus-4.8
+ — a PAID model 403-blocked by the user's spend-limited OpenRouter key. The
+ chosen model MUST survive a rejected optional kwarg. Generic: any
+ OpenAI-compatible brain (openai/grok/openrouter) with a base_url in config
+ would otherwise silently run its hardcoded default model.
+ """
+ config = JarvisConfig()
+ config.brain.primary = "openrouter"
+ config.brain.providers["openrouter"] = BrainProviderConfig(
+ model=_FREE,
+ base_url="https://openrouter.ai/api/v1",
+ )
+ mgr = BrainManager(config=config, bus=EventBus(), tools={})
+
+ brain = mgr._get_brain("openrouter", _FREE)
+ got = getattr(brain, "_model", None)
+ assert got == _FREE, f"brain ran the wrong model on the wire: {got!r}"
+ assert got != "anthropic/claude-opus-4.8"
+
+
+def test_explicit_deep_model_still_wins() -> None:
+ """Guard: providers that DO set deep_model keep it (claude-api/gemini/openai)."""
+ config = JarvisConfig()
+ config.brain.primary = "claude-api"
+ config.brain.providers["claude-api"] = BrainProviderConfig(
+ model="claude-haiku-4-5-20251001",
+ deep_model="claude-opus-4-8",
+ )
+ mgr = BrainManager(config=config, bus=EventBus(), tools={})
+ assert mgr._deep_model("claude-api") == "claude-opus-4-8"
+ assert mgr._fast_model("claude-api") == "claude-haiku-4-5-20251001"
+
+
+# ----------------------------------------------------------------------
+# Chosen-model contract: the model on the wire == the SELECTED model, for
+# EVERY provider/model. User mandate 2026-06-29: "it must work with whatever
+# model you pick — pick GPT-5.5 and GPT-5.5 runs, never Opus in the background
+# while the UI shows GPT-5.5." Provider-agnostic, OS-independent (pure model
+# resolution — no keyring/OS/network touched by _get_brain construction).
+# ----------------------------------------------------------------------
+
+# (provider, chosen_model, has_base_url): each pairing a downloader might pick.
+# openrouter carries base_url in jarvis.toml — the kwarg that triggered the
+# TypeError → DEFAULT_MODEL collapse — so both an openrouter-namespaced model
+# AND a cross-vendor model picked THROUGH openrouter (the user's GPT-5.5 example)
+# are covered.
+_CONTRACT_CASES = [
+ ("openrouter", "openai/gpt-5.5", True),
+ ("openrouter", "deepseek/deepseek-v4-flash", True),
+ ("openrouter", _FREE, True),
+ ("openai", "gpt-5.5", False),
+ ("claude-api", "claude-opus-4-8", False),
+ ("gemini", "gemini-3.5-flash", False),
+ ("antigravity", "gemini-3.5-flash", False),
+]
+
+
[email protected]("provider,model,has_base_url", _CONTRACT_CASES)
+def test_get_brain_runs_exactly_the_selected_model(
+ provider: str, model: str, has_base_url: bool
+) -> None:
+ """The constructed brain must run the SELECTED model — never a DEFAULT_MODEL."""
+ config = JarvisConfig()
+ config.brain.primary = provider
+ kwargs: dict[str, str] = {"model": model}
+ if has_base_url:
+ kwargs["base_url"] = "https://openrouter.ai/api/v1"
+ config.brain.providers[provider] = BrainProviderConfig(**kwargs)
+ mgr = BrainManager(config=config, bus=EventBus(), tools={})
+
+ brain = mgr._get_brain(provider, model)
+ got = getattr(brain, "_model", None)
+ assert got == model, (
+ f"{provider}: picked {model!r} but the brain runs {got!r} — the selected "
+ f"model is not the one used (silent DEFAULT_MODEL drift)."
+ )
+
+
+def test_model_drift_is_logged_loudly_not_silent(caplog: pytest.LogCaptureFixture) -> None:
+ """If a brain ever ignores the requested model (future regression), _get_brain
+ must surface it as an ERROR — never let a wrong model run silently.
+
+ Simulated by a registry whose instantiate ignores the model kwarg, so the
+ built brain reports a different _model than requested."""
+ config = JarvisConfig()
+ config.brain.primary = "openrouter"
+ config.brain.providers["openrouter"] = BrainProviderConfig(model="openai/gpt-5.5")
+ mgr = BrainManager(config=config, bus=EventBus(), tools={})
+
+ class _Stub:
+ _model = "anthropic/claude-opus-4.8" # ignores the requested model
+
+ mgr._registry.instantiate = lambda name, **kw: _Stub() # type: ignore[assignment]
+
+ with caplog.at_level(logging.ERROR):
+ mgr._get_brain("openrouter", "openai/gpt-5.5")
+
+ assert any("MODEL DRIFT" in r.message for r in caplog.records), (
+ "a wrong model on the wire must be logged loudly, not silently accepted"
+ )
diff --git a/tests/unit/brain/test_codex_oauth_rescue.py b/tests/unit/brain/test_codex_oauth_rescue.py
new file mode 100644
index 0000000000..281d4375f3
--- /dev/null
+++ b/tests/unit/brain/test_codex_oauth_rescue.py
@@ -0,0 +1,29 @@
+"""Pre-boot key check must NOT dead-list a connected codex ChatGPT-OAuth login.
+
+B1 (open-source AP-22): codex authenticates via ~/.codex/auth.json (OAuth login),
+not an API key in PROVIDER_SECRET_CANDIDATES. A ChatGPT-subscription-only user
+(no OPENAI_API_KEY) was getting codex pushed into _dead_providers at boot, which
+emptied the chain → every chat AND voice turn returned the provider-down apology.
+A keyless-but-OAuth-connected codex must survive the key check.
+"""
+from __future__ import annotations
+
+from jarvis.brain.manager import _keyless_provider_is_rescued_by_oauth
+
+
+def test_codex_keyless_but_oauth_connected_is_rescued(monkeypatch):
+ import jarvis.plugins.brain.codex as codex_mod
+ monkeypatch.setattr(codex_mod, "_codex_oauth_connected", lambda: True)
+ assert _keyless_provider_is_rescued_by_oauth("codex") is True
+
+
+def test_codex_keyless_no_oauth_is_not_rescued(monkeypatch):
+ import jarvis.plugins.brain.codex as codex_mod
+ monkeypatch.setattr(codex_mod, "_codex_oauth_connected", lambda: False)
+ assert _keyless_provider_is_rescued_by_oauth("codex") is False
+
+
+def test_api_key_provider_is_never_rescued():
+ # Only OAuth-login brains get the rescue; an ordinary API provider stays dead.
+ assert _keyless_provider_is_rescued_by_oauth("openai") is False
+ assert _keyless_provider_is_rescued_by_oauth("openrouter") is False
diff --git a/tests/unit/brain/test_computer_use_offload.py b/tests/unit/brain/test_computer_use_offload.py
index 15cd745b01..3185ee326d 100644
--- a/tests/unit/brain/test_computer_use_offload.py
+++ b/tests/unit/brain/test_computer_use_offload.py
@@ -129,3 +129,81 @@ async def test_computer_use_failure_is_announced_not_dropped(monkeypatch) -> Non
completions = [e for e in bus.published if getattr(e, "kind", None) == "completion"]
assert completions, "a failed Computer-Use action must still be announced (AD-OE6)"
+
+
+async def test_user_cancel_offload_is_silent_not_announced(monkeypatch) -> None:
+ """A user-initiated hangup (cancel token -> harness exit 130) must NOT speak
+ a "the action was cancelled" readback.
+
+ The user just triggered the abort themselves ("auflegen" is a hard,
+ immediately-silent kill-switch), so the cancel readback is redundant — and
+ with N parallel offloaded missions it spams the phrase N times. Live forensic
+ 2026-06-27: three CU missions all cancelled by one F1+F2 hangup spoke
+ "Die Aktion am Bildschirm wurde abgebrochen." three times. The cancel is the
+ receipt of an abort the user already made — not a result they are waiting on,
+ so AD-OE6's zero-silent-drop (which protects real outcomes) does not apply.
+ """
+ bus = _FakeBus()
+ # The harness reports a user cancel as exit 130 ("[cu] cancelled mid-batch").
+ output = {
+ "harness": "screenshot",
+ "exit_code": 130,
+ "stdout": "",
+ "stderr": "[cu] cancelled mid-batch\n",
+ "cost_usd": 0.0,
+ "duration_ms": 6200,
+ }
+ executor = _SlowHarnessExecutor(
+ output=output, success=False, error="exit 130", delay=0.1
+ )
+ mgr = _make_manager(executor, bus)
+ plan = LocalActionPlan(
+ mode=LocalActionMode.COMPUTER_USE,
+ harness="computer-use",
+ prompt="screenshot the repo",
+ )
+ monkeypatch.setattr("jarvis.brain.manager.match_local_action", lambda _t: plan)
+
+ await mgr._run_local_action_fast_path("mach einen screenshot")
+ await asyncio.gather(*getattr(mgr, "_cu_background_tasks", set()))
+
+ assert executor.called
+ completions = [e for e in bus.published if getattr(e, "kind", None) == "completion"]
+ assert not completions, (
+ "a user-initiated cancel (exit 130 / hangup) must not be announced; got "
+ f"{[getattr(e, 'text', '') for e in completions]}"
+ )
+
+
+async def test_three_parallel_cancels_speak_nothing(monkeypatch) -> None:
+ """The exact 2026-06-27 forensic: three offloaded CU missions, all cancelled
+ by one hangup, must produce ZERO spoken cancel readbacks (not three)."""
+ bus = _FakeBus()
+ output = {
+ "harness": "screenshot",
+ "exit_code": 130,
+ "stdout": "",
+ "stderr": "[cu] cancelled mid-batch\n",
+ "cost_usd": 0.0,
+ "duration_ms": 5100,
+ }
+ plan = LocalActionPlan(
+ mode=LocalActionMode.COMPUTER_USE, harness="computer-use", prompt="do it"
+ )
+ monkeypatch.setattr("jarvis.brain.manager.match_local_action", lambda _t: plan)
+
+ # Each turn spawns its own background mission off a shared manager.
+ executor = _SlowHarnessExecutor(
+ output=output, success=False, error="exit 130", delay=0.05
+ )
+ mgr = _make_manager(executor, bus)
+ for _ in range(3):
+ await mgr._run_local_action_fast_path("öffentlich, dann screenshot")
+ await asyncio.gather(*getattr(mgr, "_cu_background_tasks", set()))
+
+ completions = [e for e in bus.published if getattr(e, "kind", None) == "completion"]
+ assert not completions, (
+ f"three hangup-cancelled missions must speak nothing; got {len(completions)}"
+ )
diff --git a/tests/unit/brain/test_custom_system_prompt.py b/tests/unit/brain/test_custom_system_prompt.py
index 0f05c26dc2..9ca794bdaa 100644
--- a/tests/unit/brain/test_custom_system_prompt.py
+++ b/tests/unit/brain/test_custom_system_prompt.py
@@ -29,8 +29,8 @@ def test_effective_prompt_is_default_when_no_custom_file() -> None:
def test_default_persona_prompt_is_the_packaged_block() -> None:
default = persona_loader.default_persona_prompt()
assert default == persona_loader.load_persona_prompt()
- # Sanity: it is the real JARVIS persona, not an empty fallback.
- assert "JARVIS" in default
+ # Sanity: it is the real (name-neutral) voice persona, not an empty fallback.
+ assert "voice companion" in default
def test_save_custom_then_effective_returns_custom() -> None:
diff --git a/tests/unit/brain/test_depleted_credits_classification.py b/tests/unit/brain/test_depleted_credits_classification.py
new file mode 100644
index 0000000000..3ef45cf60e
--- /dev/null
+++ b/tests/unit/brain/test_depleted_credits_classification.py
@@ -0,0 +1,38 @@
+"""A depleted-credits 429 must be classified as a DEAD provider (account_blocked),
+not a transient rate-limit.
+
+Live forensic (2026-06-28): Gemini returned HTTP 429 with the body "Your prepayment
+credits are depleted." Because `_is_account_blocked_exc` did not know that phrasing
+AND the brain loop short-circuited on any "429" to the transient rate-limit branch,
+the depleted Gemini was never marked dead — so a single empty provider kept leading
+the chain every turn and bricked voice/chat even though the user's OpenRouter key
+was funded and working. Terminal billing must mark the provider dead so the chain
+crosses to whatever provider family actually has a usable key (AP-22).
+"""
+from __future__ import annotations
+
+from jarvis.brain.manager import _classify_provider_error, _is_account_blocked_exc
+
+GEMINI_DEPLETED = (
+ "Your prepayment credits are depleted. Please go to AI Studio at "
+ "https://ai.studio/projects to manage your project and billing."
+)
+
+
+def test_depleted_prepayment_credits_is_account_blocked():
+ assert _is_account_blocked_exc(GEMINI_DEPLETED) is True
+
+
+def test_depleted_credits_429_classifies_as_account_blocked_not_rate_limit():
+ # The real error also carries an HTTP 429. It must NOT win the rate-limit
+ # branch (which keeps the dead provider in rotation) — terminal billing is
+ # account_blocked, which dead-lists the provider so the chain crosses family.
+ msg = "Error code: 429 - " + GEMINI_DEPLETED
+ assert _classify_provider_error(msg, default="call_fail") == "account_blocked"
+
+
+def test_openai_style_insufficient_quota_is_account_blocked():
+ # Cross-provider coverage: the same class of terminal-billing wording from a
+ # different vendor must also dead-list, never read as a transient 429.
+ msg = "Error code: 429 - You exceeded your current quota, please check your plan and billing."
+ assert _classify_provider_error(msg, default="call_fail") == "account_blocked"
diff --git a/tests/unit/brain/test_failure_readback_no_exit_token.py b/tests/unit/brain/test_failure_readback_no_exit_token.py
new file mode 100644
index 0000000000..cfa58378e0
--- /dev/null
+++ b/tests/unit/brain/test_failure_readback_no_exit_token.py
@@ -0,0 +1,208 @@
+"""A FAILED action must never speak a raw machine token like "exit 1".
+
+Live forensic 2026-06-28 (voice session 16:57): the user asked for a sub-agent
+to write an HTML file; a garbled follow-up turn dispatched a harness that failed
+with a non-zero exit code, and Jarvis spoke the single word-pair "exit 1" — the
+opaque ``ToolResult.error`` (``dispatch_to_harness`` emits ``f"exit {code}"``)
+returned VERBATIM to the user.
+
+Root cause: ``BrainManager._run_local_action_fast_path`` (and the spawn /
+leaked-tool recovery paths) returned ``result.error`` directly as the spoken
+text. The Computer-Use path was already protected via
+``cu_failure_readback``; these action / spawn paths were not.
+
+Contract (the maintainer's directive, all supported languages — de/en/es):
+when an action fails or cannot be made sense of, Jarvis communicates that
+intelligently — never a bare ``exit N``, never a hardcoded German string on an
+English/Spanish turn, never an empty/silent drop.
+"""
+from __future__ import annotations
+
+import re
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.brain.local_action_gate import (
+ LocalActionMode,
+ LocalActionPlan,
+ LocalToolCall,
+)
+from jarvis.brain.manager import BrainManager
+from jarvis.voice.action_phrases import extract_speakable_reason
+
+_BARE_EXIT = re.compile(r"\bexit\s*-?\d", re.IGNORECASE)
+
+
+def _has_letters(text: str) -> bool:
+ return bool(re.search(r"[A-Za-zÀ-ÿ]", text or ""))
+
+
+# ---------------------------------------------------------------------------
+# extract_speakable_reason — the opaque-token gate (pure, no LLM)
+# ---------------------------------------------------------------------------
+
+
+def test_extract_reason_rejects_bare_exit_token() -> None:
+ assert extract_speakable_reason("exit 1", None) is None
+ assert extract_speakable_reason("exit 137", {}) is None
+ assert extract_speakable_reason("(exit 2)", None) is None
+
+
+def test_extract_reason_rejects_empty_and_numeric() -> None:
+ assert extract_speakable_reason(None, None) is None
+ assert extract_speakable_reason("", None) is None
+ assert extract_speakable_reason(" ", None) is None
+ assert extract_speakable_reason("255", None) is None
+
+
+def test_extract_reason_forwards_human_stderr_from_output_dict() -> None:
+ out = {"harness": "screenshot", "exit_code": 1, "stderr": "Permission denied", "stdout": ""}
+ reason = extract_speakable_reason("exit 1", out)
+ assert reason is not None
+ assert "Permission denied" in reason
+ assert _BARE_EXIT.search(reason) is None
+
+
+def test_extract_reason_forwards_human_error_string() -> None:
+ reason = extract_speakable_reason("The file could not be written", None)
+ assert reason == "The file could not be written"
+
+
+def test_extract_reason_rejects_diagnostic_noise() -> None:
+ # A "[cu] mission profile" telemetry dump is not a human reason.
+ out = {"stderr": "[cu] mission profile: steps=3 total=9.5s act=3.0s", "exit_code": 5}
+ assert extract_speakable_reason("exit 5", out) is None
+
+
+# ---------------------------------------------------------------------------
+# DIRECT local-action fast path — the path that fired in the transcript
+# ---------------------------------------------------------------------------
+
+
+class _FailingExecutor:
+ """tool_executor whose tool fails with the opaque ``exit N`` token."""
+
+ def __init__(self, *, error: str = "exit 1", output=None) -> None:
+ self._error = error
+ self._output = output
+
+ async def execute(self, tool, args, *, user_utterance, trace_id): # noqa: ANN001
+ return SimpleNamespace(success=False, output=self._output, error=self._error)
+
+
+class _FakeBus:
+ async def publish(self, event) -> None: # noqa: ANN001
+ pass
+
+
+def _make_manager(executor, *, reply_language: str = "auto") -> BrainManager:
+ mgr = BrainManager.__new__(BrainManager)
+ mgr._config = SimpleNamespace(
+ local_action=SimpleNamespace(
+ enabled=True, harness_timeout_s=30.0, direct_timeout_s=3.0
+ )
+ )
+ mgr._bus = _FakeBus()
+ mgr._tool_executor = executor
+ mgr._local_action_tools = {"open_app": object()}
+ mgr._cost_meter = None
+ mgr._reply_language = reply_language
+ mgr._turn_detected_lang = ""
+ # No _readback_composer attribute -> render_readback uses the canned fallback,
+ # so these assertions test the DETERMINISTIC fallback (the worst case).
+ return mgr
+
+
+def _direct_plan(_text: str) -> LocalActionPlan:
+ return LocalActionPlan(
+ mode=LocalActionMode.DIRECT,
+ tool_calls=(LocalToolCall(name="open_app", args={"app_name": "x"}),),
+ )
+
+
[email protected]("pin", ["de", "en", "es", "auto"])
+async def test_direct_failure_never_speaks_exit_token(monkeypatch, pin) -> None:
+ mgr = _make_manager(_FailingExecutor(error="exit 1"), reply_language=pin)
+ monkeypatch.setattr("jarvis.brain.manager.match_local_action", _direct_plan)
+
+ reply = await mgr._run_local_action_fast_path("do the thing")
+
+ assert reply is not None and reply.strip(), "a failure must not be silent"
+ assert _BARE_EXIT.search(reply) is None, f"raw exit token leaked: {reply!r}"
+ assert _has_letters(reply), f"reply is not a real sentence: {reply!r}"
+
+
+async def test_direct_failure_forwards_human_reason(monkeypatch) -> None:
+ out = {"exit_code": 1, "stderr": "Disk is full", "stdout": ""}
+ mgr = _make_manager(_FailingExecutor(error="exit 1", output=out), reply_language="en")
+ monkeypatch.setattr("jarvis.brain.manager.match_local_action", _direct_plan)
+
+ reply = await mgr._run_local_action_fast_path("do the thing")
+
+ assert "Disk is full" in reply, f"human reason dropped: {reply!r}"
+ assert _BARE_EXIT.search(reply) is None
+
+
+async def test_english_pin_failure_is_not_hardcoded_german(monkeypatch) -> None:
+ mgr = _make_manager(_FailingExecutor(error="exit 1"), reply_language="en")
+ monkeypatch.setattr("jarvis.brain.manager.match_local_action", _direct_plan)
+
+ reply = await mgr._run_local_action_fast_path("do the thing")
+
+ # The historical German hardcoded fallbacks ("nicht geklappt", "Aktion")
+ # must not surface on an English-pinned turn.
+ assert "geklappt" not in reply.lower()
+ assert "konnte nicht" not in reply.lower()
+
+
+# ---------------------------------------------------------------------------
+# _honest_failure_readback — shared helper behind every spawn / tool path
+# ---------------------------------------------------------------------------
+
+
[email protected]("lang", ["de", "en", "es"])
+async def test_honest_failure_readback_generic_all_languages(lang) -> None:
+ mgr = BrainManager.__new__(BrainManager)
+ mgr._reply_language = lang
+ result = SimpleNamespace(success=False, output=None, error="exit 1")
+
+ reply = await mgr._honest_failure_readback(
+ result,
+ user_text="do it",
+ situation="The action could not be completed.",
+ generic_key="action_failed_generic",
+ reason_key="action_failed_reason",
+ lang=lang,
+ )
+
+ assert reply.strip()
+ assert _BARE_EXIT.search(reply) is None
+ assert _has_letters(reply)
+
+
+async def test_honest_failure_readback_with_reason() -> None:
+ mgr = BrainManager.__new__(BrainManager)
+ mgr._reply_language = "en"
+ result = SimpleNamespace(
+ success=False,
+ output={"exit_code": 1, "stderr": "Network unreachable"},
+ error="exit 1",
+ )
+
+ reply = await mgr._honest_failure_readback(
+ result,
+ user_text="do it",
+ situation="The background helper could not be started.",
+ generic_key="spawn_failed_generic",
+ reason_key="spawn_failed_reason",
+ lang="en",
+ )
+
+ assert "Network unreachable" in reply
+ assert _BARE_EXIT.search(reply) is None
diff --git a/tests/unit/brain/test_from_tier_config_honors_override_model.py b/tests/unit/brain/test_from_tier_config_honors_override_model.py
new file mode 100644
index 0000000000..6c60390500
--- /dev/null
+++ b/tests/unit/brain/test_from_tier_config_honors_override_model.py
@@ -0,0 +1,59 @@
+"""Regression: ``from_tier_config`` must honor the OVERRIDE provider's OWN picked
+model, never clobber it with the hardcoded paid TIER default.
+
+The decisive boot-path money leak (live forensic 2026-06-29): ``brain.primary=
+"openrouter"`` differs from ``[brain.router].provider``, so ``factory.py`` passes
+``provider_override="openrouter"`` into ``from_tier_config``. The builder then set
+``explicit_model = None`` and WROTE the hardcoded TIER default
+(``anthropic/claude-haiku-4.5`` for router, ``anthropic/claude-opus-4.8`` for deep)
+INTO ``[brain.providers.openrouter].model`` — overwriting the user's FREE pick in
+the in-memory config BEFORE ``_fast_model``/``_deep_model`` ever read it. So every
+router and deep turn billed a paid Anthropic model over OpenRouter despite the free
+selection (~5€ key drained). The ``_fast_model``/``_deep_model`` "prefer cfg.model"
+fixes do not help on their own — this clobber poisons ``cfg.model`` upstream.
+
+A user-selected provider must run the model the user picked, never a hardcoded
+foreign-family default (AP-21/AP-22, open-source single-key §3).
+"""
+from __future__ import annotations
+
+from jarvis.brain.manager import BrainManager
+from jarvis.core.bus import EventBus
+from jarvis.core.config import (
+ BrainProviderConfig,
+ BrainTierConfig,
+ JarvisConfig,
+)
+
+_FREE = "nvidia/nemotron-3-ultra-550b-a55b:free"
+
+
+def _build_router_with_openrouter_primary() -> BrainManager:
+ config = JarvisConfig()
+ config.brain.primary = "openrouter"
+ config.brain.providers["openrouter"] = BrainProviderConfig(model=_FREE)
+ # The router tier points at a DIFFERENT provider — exactly what makes
+ # factory.py set provider_override = brain.primary at boot.
+ config.brain.router = BrainTierConfig(provider="gemini")
+ return BrainManager.from_tier_config(
+ "router", config=config, bus=EventBus(), provider_override="openrouter",
+ )
+
+
+def test_override_provider_keeps_its_picked_model_fast() -> None:
+ mgr = _build_router_with_openrouter_primary()
+ assert mgr._fast_model("openrouter") == _FREE
+ assert "anthropic/claude" not in (mgr._fast_model("openrouter") or "")
+
+
+def test_override_provider_keeps_its_picked_model_deep() -> None:
+ mgr = _build_router_with_openrouter_primary()
+ assert mgr._deep_model("openrouter") == _FREE
+ assert "anthropic/claude" not in (mgr._deep_model("openrouter") or "")
+
+
+def test_in_memory_config_not_clobbered_to_paid_default() -> None:
+ """The in-memory provider config the manager runs from must still hold the
+ user's pick — not the hardcoded paid TIER default."""
+ mgr = _build_router_with_openrouter_primary()
+ assert mgr._config.brain.providers["openrouter"].model == _FREE
diff --git a/tests/unit/brain/test_subagent_voice_switch_validated.py b/tests/unit/brain/test_jarvis_agent_voice_switch_validated.py
similarity index 100%
rename from tests/unit/brain/test_subagent_voice_switch_validated.py
rename to tests/unit/brain/test_jarvis_agent_voice_switch_validated.py
diff --git a/tests/unit/brain/test_local_action_gate.py b/tests/unit/brain/test_local_action_gate.py
index b351e84550..505adc06c9 100644
--- a/tests/unit/brain/test_local_action_gate.py
+++ b/tests/unit/brain/test_local_action_gate.py
@@ -213,6 +213,56 @@ def test_verb_at_end_open_phrasings_take_direct_path(text: str, app: str) -> Non
assert plan.tool_calls[0].args == {"app_name": app}
+ "text",
+ [
+ # Live bug 2026-06-26 (voice session): "in meinen Explorer meine Bilder
+ # öffnen" launched a BLANK explorer.exe and dropped the real target
+ # ("meine Bilder"). The robust open-app fallback extracted the first known
+ # app name ("explorer") from anywhere in the utterance and bare-launched
+ # it, ignoring that the app is a CONTAINER the user navigates INTO.
+ "Kannst du für mich bitte in meinen Explorer meine Bilder öffnen?",
+ "Öffne meine Bilder im Explorer",
+ "Öffne meine Dokumente im Explorer",
+ "In meinem Explorer die Downloads öffnen",
+ ],
+)
+def test_open_target_in_container_app_routes_to_computer_use(text: str) -> None:
+ """"open <target> in <app>" — the app is a folder/window to navigate into,
+ not the whole goal. A bare deterministic launch would drop the real target
+ (the Bilder/Downloads/Dokumente), so the goal routes to the multi-step
+ Computer-Use loop instead (maintainer decision 2026-06-26: ANY target beyond
+ the bare app hands off to Computer-Use)."""
+ plan = match_local_action(text, _registry=None)
+ assert plan is not None, f"{text!r} fell through to the brain"
+ assert plan.mode is LocalActionMode.COMPUTER_USE, (
+ f"{text!r} → {plan.mode}, want COMPUTER_USE (app used as a container)"
+ )
+ assert plan.harness == "screenshot"
+ assert plan.prompt == text
+
+
+ ("text", "app"),
+ [
+ # The container guard must NOT swallow a plain bare open — "den/der" are
+ # articles, not container prepositions, so these stay the fast DIRECT path.
+ ("Öffne den Explorer", "explorer"),
+ ("Öffne den Explorer für mich", "explorer"),
+ ("Mach mir mal den Explorer auf", "explorer"),
+ ],
+)
+def test_bare_open_known_app_stays_direct_despite_container_guard(
+ text: str, app: str
+) -> None:
+ """A bare "open <app>" with no target behind it keeps the instant DIRECT path;
+ the container guard only fires on a real "in/im <app>" navigation."""
+ plan = match_local_action(text, _registry=None)
+ assert plan is not None, f"{text!r} fell through to the brain"
+ assert plan.mode is LocalActionMode.DIRECT, f"{text!r} → {plan.mode}, want DIRECT"
+ assert plan.tool_calls[0].args == {"app_name": app}
+
+
@pytest.mark.parametrize(
"text",
[
@@ -938,6 +988,56 @@ class TestBrowserSearchFastPath:
assert plan.mode is LocalActionMode.COMPUTER_USE
assert plan.prompt == utterance
+ @pytest.mark.parametrize(
+ "utterance",
+ [
+ # Finding 2026-06-26: the non-greedy query capture swallows a trailing
+ # desktop action ("... und scrolle runter", "... then click the first
+ # result") into the Google query, so the follow-up is silently dropped
+ # and a wrong search runs. A connector + GUI verb means the goal is
+ # multi-step → the whole turn must take the computer-use loop, which
+ # runs BOTH the search and the follow-up action.
+ "öffne chrome und google das wetter und scrolle runter",
+ "open chrome and google cats then click the first result",
+ "öffne chrome und google die nachrichten und dann klick das erste ergebnis",
+ ],
+ )
+ def test_search_query_with_trailing_gui_action_routes_to_cu(
+ self, utterance: str
+ ) -> None:
+ plan = match_local_action(utterance, _registry=None)
+ assert plan is not None, f"{utterance!r} fell through to the brain"
+ assert plan.mode is LocalActionMode.COMPUTER_USE, (
+ f"{utterance!r} → {plan.mode}, want COMPUTER_USE "
+ "(trailing GUI action smuggled into the search query)"
+ )
+ assert plan.prompt == utterance
+
+ @pytest.mark.parametrize(
+ ("utterance", "must_contain"),
+ [
+ # Legit multi-term searches must STAY a clean DIRECT search — a bare
+ # connector ("and"/"und") without a desktop verb is part of the query,
+ # not a follow-up action. A GUI word with NO connector in front of it
+ # ("how to click a button") is likewise just search terms.
+ ("open chrome and google cats and dogs", ("cats", "dogs")),
+ ("open chrome and search for how to click a button", ("click", "button")),
+ ("öffne chrome und google katzen und hunde", ("katzen", "hunde")),
+ ],
+ )
+ def test_legit_multiterm_search_stays_direct(
+ self, utterance: str, must_contain: tuple[str, ...]
+ ) -> None:
+ plan = match_local_action(utterance, lang="en", _registry=None)
+ assert plan is not None, f"{utterance!r} fell through"
+ assert plan.mode is LocalActionMode.DIRECT, (
+ f"{utterance!r} → {plan.mode}, want DIRECT (legit search, no follow-up)"
+ )
+ url = plan.tool_calls[0].args["arguments"]
+ assert url.startswith("https://www.google.com/search?q=")
+ for token in must_contain:
+ assert token in url, f"{token!r} dropped from search url {url!r}"
+
# requires_external_integration — real-world booking/transaction requests no
# generic sub-agent worker can fulfil (no travel/lodging/ticketing tool exists).
diff --git a/tests/unit/brain/test_model_catalog.py b/tests/unit/brain/test_model_catalog.py
index c598200cfa..f881555a66 100644
--- a/tests/unit/brain/test_model_catalog.py
+++ b/tests/unit/brain/test_model_catalog.py
@@ -148,6 +148,30 @@ class TestParseModelsResponse:
) in models
assert ModelInfo(id="openai/gpt-5.5", label="openai/gpt-5.5") in models
+ def test_openrouter_extracts_output_modalities(self) -> None:
+ payload = {
+ "data": [
+ {
+ "id": "openai/gpt-5.5",
+ "name": "GPT-5.5",
+ "architecture": {"output_modalities": ["text"]},
+ },
+ {
+ "id": "openai/gpt-5-image",
+ "name": "Image",
+ "architecture": {"output_modalities": ["image", "text"]},
+ },
+ ]
+ }
+ by_id = {m.id: m for m in parse_models_response("openrouter", payload)}
+ assert by_id["openai/gpt-5.5"].output_modalities == ("text",)
+ assert by_id["openai/gpt-5-image"].output_modalities == ("image", "text")
+
+ def test_missing_architecture_yields_none_modalities(self) -> None:
+ # Direct providers (Anthropic/OpenAI /v1/models) return no architecture.
+ payload = {"data": [{"id": "gpt-5.5"}]}
+ assert parse_models_response("openai", payload)[0].output_modalities is None
+
def test_empty_payload_yields_empty_list(self) -> None:
assert parse_models_response("openai", {}) == []
assert parse_models_response("gemini", {}) == []
@@ -180,6 +204,118 @@ class TestSortModels:
assert ordered[0].id == "openai/gpt-5.5"
assert ordered[-1].id == "openai/gpt-4o"
+ def test_frontier_families_rank_above_obscure_models(self) -> None:
+ # The user's exact complaint: with OpenRouter's namespaced ids, plain
+ # reverse-alphabetical sorting buried GPT/Claude/Gemini below
+ # z-ai/qwen/community fine-tunes (whose vendor prefix sorts after "o").
+ # The flagship families must come first.
+ models = [
+ ModelInfo(id="sao10k/l3.3-euryale-70b", label="Euryale"),
+ ModelInfo(id="thedrummer/rocinante-12b", label="Rocinante"),
+ ModelInfo(id="z-ai/glm-4.5v", label="GLM 4.5V"),
+ ModelInfo(id="openai/gpt-5.5", label="GPT-5.5"),
+ ModelInfo(id="anthropic/claude-opus-4.8", label="Opus 4.8"),
+ ModelInfo(id="google/gemini-3-pro-preview", label="Gemini 3 Pro"),
+ ]
+ ordered = [m.id for m in sort_models("openrouter", models)]
+ assert ordered.index("openai/gpt-5.5") < ordered.index("sao10k/l3.3-euryale-70b")
+ assert ordered.index("anthropic/claude-opus-4.8") < ordered.index(
+ "thedrummer/rocinante-12b"
+ )
+ assert ordered.index("google/gemini-3-pro-preview") < ordered.index(
+ "z-ai/glm-4.5v"
+ )
+
+ def test_newer_version_ranks_above_older_in_same_family(self) -> None:
+ models = [
+ ModelInfo(id="openai/gpt-5.1", label="x"),
+ ModelInfo(id="openai/gpt-5.5", label="y"),
+ ModelInfo(id="openai/gpt-5.4", label="z"),
+ ]
+ ordered = [m.id for m in sort_models("openrouter", models)]
+ assert ordered == ["openai/gpt-5.5", "openai/gpt-5.4", "openai/gpt-5.1"]
+
+ def test_main_variant_ranks_above_mini_nano_and_free(self) -> None:
+ models = [
+ ModelInfo(id="openai/gpt-5.5-mini", label="mini"),
+ ModelInfo(id="openai/gpt-5.5", label="main"),
+ ModelInfo(id="openai/gpt-5.5-nano", label="nano"),
+ ModelInfo(id="openai/gpt-5.5:free", label="free"),
+ ]
+ ordered = [m.id for m in sort_models("openrouter", models)]
+ assert ordered[0] == "openai/gpt-5.5"
+
+ def test_popular_value_family_outranks_unknown_vendor(self) -> None:
+ # "Bang per token" families people actually run (DeepSeek, GLM, Qwen,
+ # Kimi) rank above an unknown vendor whose prefix sorts high alphabetically.
+ models = [
+ ModelInfo(id="zzz-vendor/mystery-70b", label="Mystery"),
+ ModelInfo(id="deepseek/deepseek-v3.2", label="DeepSeek V3.2"),
+ ModelInfo(id="moonshotai/kimi-k2", label="Kimi K2"),
+ ]
+ ordered = [m.id for m in sort_models("openrouter", models)]
+ assert ordered[-1] == "zzz-vendor/mystery-70b"
+
+ def test_superseded_version_sinks_below_other_families_flagship(self) -> None:
+ # The "wall of old Claude versions before GPT" fix: only the NEWEST of a
+ # product line stays in the top band; older same-line versions drop
+ # below every OTHER family's current flagship, so the leading rows show
+ # different providers' flagships instead of one provider's back-catalog.
+ models = [
+ ModelInfo(id="anthropic/claude-opus-4.8", label="Opus 4.8"),
+ ModelInfo(id="anthropic/claude-opus-4.7", label="Opus 4.7"),
+ ModelInfo(id="anthropic/claude-opus-4.6", label="Opus 4.6"),
+ ModelInfo(id="openai/gpt-5.5", label="GPT-5.5"),
+ ]
+ ordered = [m.id for m in sort_models("openrouter", models)]
+ assert ordered[0] == "anthropic/claude-opus-4.8" # newest Claude = flagship
+ assert ordered.index("openai/gpt-5.5") < ordered.index("anthropic/claude-opus-4.7")
+ assert ordered.index("openai/gpt-5.5") < ordered.index("anthropic/claude-opus-4.6")
+ # The superseded Claude versions still rank above an unknown vendor.
+ # (they keep their family relevance in the second band).
+
+ def test_distinct_product_tiers_are_not_treated_as_one_line(self) -> None:
+ # gemini flash and pro are different product lines even though the
+ # version number sits in the middle — neither must "supersede" the other.
+ models = [
+ ModelInfo(id="google/gemini-3.5-flash", label="Flash"),
+ ModelInfo(id="google/gemini-3.1-pro-preview", label="Pro"),
+ ]
+ ordered = [m.id for m in sort_models("openrouter", models)]
+ # Both are their line's newest → both stay flagship (top band); neither
+ # is demoted as "an older version of the other".
+ assert set(ordered[:2]) == {"google/gemini-3.5-flash", "google/gemini-3.1-pro-preview"}
+
+ def test_special_purpose_variants_rank_below_the_plain_model(self) -> None:
+ # Deep-research / multi-agent / custom-tools are special-purpose siblings,
+ # not the default chat brain — the plain model leads each of them.
+ models = [
+ ModelInfo(id="openai/o3-deep-research", label="o3 DR"),
+ ModelInfo(id="openai/o3", label="o3"),
+ ModelInfo(id="x-ai/grok-4.3-multi-agent", label="Grok MA"),
+ ModelInfo(id="x-ai/grok-4.3", label="Grok"),
+ ModelInfo(id="google/gemini-3.1-pro-customtools", label="Gem CT"),
+ ModelInfo(id="google/gemini-3.1-pro", label="Gem"),
+ ]
+ ordered = [m.id for m in sort_models("openrouter", models)]
+ assert ordered.index("openai/o3") < ordered.index("openai/o3-deep-research")
+ assert ordered.index("x-ai/grok-4.3") < ordered.index("x-ai/grok-4.3-multi-agent")
+ assert ordered.index("google/gemini-3.1-pro") < ordered.index(
+ "google/gemini-3.1-pro-customtools"
+ )
+
+ def test_gpt_5_5_lands_in_leading_slice_against_full_catalog(self) -> None:
+ # End-to-end: a realistic mixed catalog (lots of obscure high-alpha
+ # vendors) must surface GPT-5.5 within the first handful — the dropdown
+ # only shows the leading slice, so rank ~130 (the old bug) hid it.
+ obscure = [
+ ModelInfo(id=f"zzz-vendor-{i}/model-{i}", label=str(i))
+ for i in range(60)
+ ]
+ models = obscure + [ModelInfo(id="openai/gpt-5.5", label="GPT-5.5")]
+ ordered = [m.id for m in sort_models("openrouter", models)]
+ assert ordered.index("openai/gpt-5.5") < 10
+
# ----------------------------------------------------------------------
# filter_brain_models — drop non-text / generative-media models
@@ -236,6 +372,47 @@ class TestFilterBrainModels:
]
assert len(filter_brain_models(models)) == 2
+ def test_excludes_image_output_model_even_without_name_marker(self) -> None:
+ # openrouter/auto outputs text OR image but its id has NO blocklist
+ # marker — the old substring filter let it slip through. Modality wins.
+ models = [
+ ModelInfo(id="openrouter/auto", label="Auto", output_modalities=("text", "image")),
+ ModelInfo(id="openai/gpt-5.5", label="GPT", output_modalities=("text",)),
+ ]
+ assert {m.id for m in filter_brain_models(models)} == {"openai/gpt-5.5"}
+
+ def test_keeps_vision_input_text_output_model(self) -> None:
+ # A model that ACCEPTS image input but OUTPUTS text is a valid brain
+ # (Computer-Use needs vision-input). It must be kept.
+ models = [ModelInfo(id="vendor/vision-llm", label="V", output_modalities=("text",))]
+ assert len(filter_brain_models(models)) == 1
+
+ def test_excludes_audio_output_model_by_modality(self) -> None:
+ models = [ModelInfo(id="vendor/voice", label="X", output_modalities=("text", "audio"))]
+ assert filter_brain_models(models) == []
+
+ def test_excludes_classifier_and_embedding_even_with_text_output(self) -> None:
+ # Safety-classifiers (llama-guard) and embedding/rerank/moderation models
+ # OUTPUT text but are NOT chat brains. The name blocklist must apply EVEN
+ # WHEN modality data is present (regression: modality-only filtering let
+ # llama-guard-4-12b / gpt-oss-safeguard-20b slip through with output text).
+ models = [
+ ModelInfo(id="meta-llama/llama-guard-4-12b", label="Guard", output_modalities=("text",)),
+ ModelInfo(id="openai/gpt-oss-safeguard-20b", label="Safeguard", output_modalities=("text",)),
+ ModelInfo(id="openai/text-embedding-3-large", label="Embed", output_modalities=("text",)),
+ ModelInfo(id="cohere/rerank-3.5", label="Rerank", output_modalities=("text",)),
+ ModelInfo(id="openai/gpt-5.5", label="GPT", output_modalities=("text",)),
+ ]
+ assert {m.id for m in filter_brain_models(models)} == {"openai/gpt-5.5"}
+
+ def test_falls_back_to_substring_when_modalities_absent(self) -> None:
+ # No modality data (direct provider /v1/models) → substring blocklist.
+ models = [
+ ModelInfo(id="veo-3.1-generate", label="Veo"), # None modalities
+ ModelInfo(id="gpt-5.5", label="gpt"), # None modalities
+ ]
+ assert {m.id for m in filter_brain_models(models)} == {"gpt-5.5"}
+
# ----------------------------------------------------------------------
# Cache I/O + TTL
diff --git a/tests/unit/brain/test_model_catalog_parity.py b/tests/unit/brain/test_model_catalog_parity.py
new file mode 100644
index 0000000000..17e0462570
--- /dev/null
+++ b/tests/unit/brain/test_model_catalog_parity.py
@@ -0,0 +1,44 @@
+"""Drift guard: every selectable Brain/TTS/STT provider must have a model catalog.
+
+The API-Keys model picker (``BrainModelSelector``) calls
+``GET /api/providers/{id}/models`` for every brain provider and the active
+TTS/STT provider. That endpoint 400s when ``catalog_spec(provider_id)`` returns
+None — so a provider shipped without a catalog entry has a silently broken
+picker ("the model dropdown doesn't work for provider X").
+
+This parity test fails the moment a provider is added to ``PROVIDERS`` without a
+matching ``model_catalog`` entry, preventing that regression class — the same
+single-source-of-truth shape as the BUG-008 enum-drift guards
+(see ``docs/anti-drift-three-layer.md``).
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.brain.model_catalog import catalog_spec
+from jarvis.ui.web.provider_spec import PROVIDERS
+
+# Tiers that surface a model/voice picker in the API-Keys view.
+_PICKER_TIERS = {"brain", "tts", "stt"}
+_SPECS = [s for s in PROVIDERS if s.tier in _PICKER_TIERS]
+
+
[email protected]("spec", _SPECS, ids=lambda s: s.id)
+def test_every_provider_has_a_model_catalog(spec):
+ cat = catalog_spec(spec.id)
+ assert cat is not None, (
+ f"Provider '{spec.id}' (tier={spec.tier}) has no model_catalog entry — "
+ f"its model picker would 400. Add it in jarvis/brain/model_catalog.py "
+ f"(CATALOG_PROVIDERS / CURATED_MODELS for brain, TTS_CATALOG, or "
+ f"STT_CATALOG)."
+ )
+
+
[email protected]("spec", _SPECS, ids=lambda s: s.id)
+def test_catalog_tier_matches_provider_tier(spec):
+ cat = catalog_spec(spec.id)
+ assert cat is not None # covered by the test above; guards the access below
+ assert cat.tier == spec.tier, (
+ f"Provider '{spec.id}' is tier={spec.tier} in provider_spec but "
+ f"tier={cat.tier} in model_catalog — the two drifted."
+ )
diff --git a/tests/unit/brain/test_openai_tool_name_sanitize.py b/tests/unit/brain/test_openai_tool_name_sanitize.py
new file mode 100644
index 0000000000..b6610c5d0e
--- /dev/null
+++ b/tests/unit/brain/test_openai_tool_name_sanitize.py
@@ -0,0 +1,49 @@
+"""OpenAI/Anthropic tool-name sanitization.
+
+Live forensic 2026-06-29: a real voice question failed with HTTP 400
+``tools.19.custom.name: String should match pattern '^[a-zA-Z0-9_-]{1,128}$'``
+on the OpenRouter→Anthropic primary, then cascaded through the dead Gemini + a
+bad Claude key and surfaced as "I can't reach my language model." Root cause: MCP
+tools are namespaced ``"<server>/<tool>"`` (jarvis/mcp/adapter.py:70), and the
+slash is rejected by Anthropic AND OpenAI. Gemini has its own sanitizer; the
+OpenAI-base path (used by OpenRouter + OpenAI) sent the raw name. A tool turn that
+includes any MCP tool therefore bricked every Anthropic/OpenAI-family model.
+
+Anthropic allows ``[a-zA-Z0-9_-]{1,128}``; OpenAI allows ``[a-zA-Z0-9_-]{1,64}``.
+We sanitize to the stricter (<=64) so both accept it, and keep a forward+reverse
+map so the model's tool_call resolves back to the original tool.
+"""
+from __future__ import annotations
+
+import re
+
+from jarvis.plugins.brain._openai_base import _tools_openai_format
+
+# The strictest of the two families (OpenAI's 64-char cap; Anthropic's is 128).
+_VALID = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
+
+
+def test_mcp_slash_tool_name_is_sanitized():
+ out = _tools_openai_format(({"name": "github/get_pull_request"},))
+ name = out[0]["function"]["name"]
+ assert _VALID.match(name), f"tool name {name!r} violates ^[A-Za-z0-9_-]{{1,64}}$"
+
+
+def test_dot_and_colon_names_are_sanitized():
+ out = _tools_openai_format(({"name": "mcp.notion:search.page"},))
+ name = out[0]["function"]["name"]
+ assert _VALID.match(name), f"tool name {name!r} not sanitized"
+
+
+def test_valid_name_is_left_unchanged():
+ out = _tools_openai_format(({"name": "search_web"},))
+ assert out[0]["function"]["name"] == "search_web"
+
+
+def test_collisions_stay_unique():
+ # "a/b" and "a_b" both sanitize to "a_b" — the second must get a suffix so the
+ # tool-call→original map stays bijective.
+ out = _tools_openai_format(({"name": "a/b"}, {"name": "a_b"}))
+ names = [t["function"]["name"] for t in out]
+ assert len(set(names)) == 2, f"names collided: {names}"
+ assert all(_VALID.match(n) for n in names)
diff --git a/tests/unit/brain/test_openrouter_model_capabilities.py b/tests/unit/brain/test_openrouter_model_capabilities.py
new file mode 100644
index 0000000000..99e67b236b
--- /dev/null
+++ b/tests/unit/brain/test_openrouter_model_capabilities.py
@@ -0,0 +1,56 @@
+"""H4/H5 (OpenRouter special case): OpenRouter gateways ~325 models with mixed
+capabilities. supports_vision / supports_tools must be resolved PER SELECTED model
+(from the cached /v1/models data) — not a fixed class attr — so a text-only or
+non-tool model the user picked degrades honestly (CU planner delegates, tool turns
+skip) instead of 400-ing the provider. Unknown → capable (no regression).
+"""
+from __future__ import annotations
+
+import json
+
+import jarvis.core.config as cfg
+from jarvis.brain.model_catalog import model_capabilities
+
+
+def _write_cache(tmp_path, models):
+ (tmp_path / "model_catalog_cache.json").write_text(
+ json.dumps({"openrouter": {"fetched_at": 0, "models": models}}), encoding="utf-8"
+ )
+
+
+def test_capabilities_text_only_model(monkeypatch, tmp_path):
+ monkeypatch.setattr(cfg, "DATA_DIR", tmp_path)
+ _write_cache(tmp_path, [{"id": "x/text", "input_modalities": ["text"], "supported_parameters": ["temperature"]}])
+ assert model_capabilities("openrouter", "x/text") == {"vision": False, "tools": False}
+
+
+def test_capabilities_vision_and_tools_model(monkeypatch, tmp_path):
+ monkeypatch.setattr(cfg, "DATA_DIR", tmp_path)
+ _write_cache(tmp_path, [{"id": "x/multi", "input_modalities": ["text", "image"], "supported_parameters": ["tools", "temperature"]}])
+ assert model_capabilities("openrouter", "x/multi") == {"vision": True, "tools": True}
+
+
+def test_capabilities_unknown_model_is_none(monkeypatch, tmp_path):
+ monkeypatch.setattr(cfg, "DATA_DIR", tmp_path)
+ _write_cache(tmp_path, [])
+ assert model_capabilities("openrouter", "x/missing") == {"vision": None, "tools": None}
+
+
+def test_openrouter_brain_reflects_text_only_model(monkeypatch, tmp_path):
+ monkeypatch.setattr(cfg, "DATA_DIR", tmp_path)
+ _write_cache(tmp_path, [{"id": "x/text", "input_modalities": ["text"], "supported_parameters": []}])
+ from jarvis.plugins.brain.openrouter import OpenRouterBrain
+
+ b = OpenRouterBrain("x/text")
+ assert b.supports_vision is False
+ assert b.can_call_tools() is False
+
+
+def test_openrouter_brain_defaults_capable_when_unknown(monkeypatch, tmp_path):
+ monkeypatch.setattr(cfg, "DATA_DIR", tmp_path)
+ _write_cache(tmp_path, [])
+ from jarvis.plugins.brain.openrouter import OpenRouterBrain
+
+ b = OpenRouterBrain("x/unknown-model")
+ assert b.supports_vision is True
+ assert b.can_call_tools() is True
diff --git a/tests/unit/brain/test_openrouter_no_paid_default.py b/tests/unit/brain/test_openrouter_no_paid_default.py
new file mode 100644
index 0000000000..d7383a62e7
--- /dev/null
+++ b/tests/unit/brain/test_openrouter_no_paid_default.py
@@ -0,0 +1,60 @@
+"""Regression: no OpenRouter code path may default to a PAID Anthropic model.
+
+OpenRouter is a universal gateway — sending ``anthropic/claude-opus-4.8`` bills the
+user's OpenRouter key for the single most expensive model in the catalog. When the
+user pinned no model, the LAST-RESORT default must be a free/non-Anthropic id (a
+wrong free id degrades with a clean 404; a wrong-but-valid paid id bills silently).
+When the user DID pin a model, their pick must win over any default. Live forensic
+2026-06-29 (~5€ drained on Opus 4.8 + Haiku 4.5). AP-21/AP-22, open-source §3.
+"""
+from __future__ import annotations
+
+from jarvis.core.config import BrainProviderConfig, JarvisConfig
+
+_FREE = "nvidia/nemotron-3-ultra-550b-a55b:free"
+
+
+def test_tier_defaults_openrouter_not_paid_anthropic() -> None:
+ from jarvis.brain.manager import TIER_DEFAULTS_BY_PROVIDER
+
+ for tier in ("router", "deep"):
+ got = TIER_DEFAULTS_BY_PROVIDER[tier]["openrouter"]
+ assert "anthropic/claude" not in got, (
+ f"TIER_DEFAULTS[{tier}][openrouter] is a paid Anthropic id: {got!r}"
+ )
+
+
+def test_openrouter_plugin_default_model_not_paid_anthropic() -> None:
+ from jarvis.plugins.brain.openrouter import DEFAULT_MODEL
+
+ assert "anthropic/claude" not in DEFAULT_MODEL, (
+ f"OpenRouterBrain.DEFAULT_MODEL is a paid Anthropic id: {DEFAULT_MODEL!r}"
+ )
+
+
+def test_curator_cheap_fallback_openrouter_not_paid_anthropic() -> None:
+ from jarvis.memory.wiki.curator_llm import _CHEAP_MODEL_FALLBACK
+
+ got = _CHEAP_MODEL_FALLBACK["openrouter"]
+ assert "anthropic/claude" not in got, (
+ f"curator cheap fallback for openrouter is paid Anthropic: {got!r}"
+ )
+
+
+def test_frontier_resolver_chain_honors_openrouter_pick() -> None:
+ """resolve_frontier_brain (skill creation, board/bio) must run the user's
+ picked OpenRouter model, not the hardcoded deep TIER default."""
+ from jarvis.brain.resolver import _resolve_chain
+
+ config = JarvisConfig()
+ config.brain.primary = "openrouter"
+ config.brain.providers["openrouter"] = BrainProviderConfig(model=_FREE)
+ # No legacy sub_jarvis tier so stage 3 (primary) is the one under test.
+ config.brain.sub_jarvis = None
+
+ chain = _resolve_chain(config)
+ openrouter_models = [m for (p, m) in chain if p == "openrouter"]
+ assert openrouter_models, "openrouter primary must appear in the frontier chain"
+ for m in openrouter_models:
+ assert m == _FREE, f"frontier chain ignored the pick, used {m!r}"
+ assert "anthropic/claude" not in (m or "")
diff --git a/tests/unit/brain/test_output_filter.py b/tests/unit/brain/test_output_filter.py
index 6f14544788..f51235b0ec 100644
--- a/tests/unit/brain/test_output_filter.py
+++ b/tests/unit/brain/test_output_filter.py
@@ -144,6 +144,53 @@ def test_self_reference_is_removed() -> None:
assert "removed_self_reference" in result.actions
+ ("text", "language", "gone", "kept"),
+ [
+ # The maintainer never wants Jarvis to SAY it is noting / reviewing the
+ # last transcription — it happens silently in the background.
+ ("Verstanden. Ich notiere mir das. Das Wetter ist sonnig.", "de",
+ "notiere", "sonnig"),
+ ("Ich schaue mir die letzte Transkription an. Die Hauptstadt ist Rom.",
+ "de", "transkription", "rom"),
+ ("Ich merke mir das. Hier ist die Antwort.", "de", "merke mir", "antwort"),
+ ("Got it. I am noting that down. The capital is Rome.", "en",
+ "noting", "rome"),
+ ("Sure. Let me look at the last transcription. It is 25 degrees.", "en",
+ "transcription", "25 degrees"),
+ ("Entendido, tomo nota. La capital es Roma.", "es", "tomo nota", "roma"),
+ ],
+)
+def test_background_action_narration_is_removed(
+ text: str, language: str, gone: str, kept: str,
+) -> None:
+ """Noting / 'review the last transcription' narration is stripped (DE/EN/ES)."""
+ result = scrub_for_voice(text, language=language)
+ low = result.cleaned.lower()
+ assert gone not in low
+ assert kept in low # the real content survives
+ assert "removed_background_action_narration" in result.actions
+
+
+ ("text", "language"),
+ [
+ # Must NOT be stripped: content lead-ins + legit save/check confirmations.
+ ("Looking at the data, the answer is 42.", "en"),
+ ("Ich schaue gleich nach dem Wetter und melde mich.", "de"),
+ ("I'm saving the file now.", "en"),
+ ("Die Datei ist gespeichert.", "de"),
+ ("I will check the weather for you.", "en"),
+ ],
+)
+def test_background_action_narration_no_false_positive(
+ text: str, language: str,
+) -> None:
+ """A content lead-in or a legit save/check action is left intact."""
+ result = scrub_for_voice(text, language=language)
+ assert "removed_background_action_narration" not in result.actions
+
+
def test_echo_paraphrase_in_opener_is_cut() -> None:
"""Echo-Paraphrase am Satzanfang wird abgeschnitten — Antwort ist die Substanz."""
text = "Du möchtest also wissen, wie spät es ist. Halb drei."
@@ -271,6 +318,41 @@ def test_echo_paraphrase_mid_sentence_is_kept() -> None:
assert "rephrased_echo" not in result.actions
+# ---------------------------------------------------------------------------
+# Em-dash / en-dash scrub (2026-06-29 "choppy voice" forensic): a parenthetical
+# dash renders as a hard TTS pause. Collapse it to a comma; hyphen compounds
+# (plain ASCII '-', no surrounding spaces) must survive.
+# ---------------------------------------------------------------------------
+
+
+def test_em_dash_becomes_comma() -> None:
+ text = "Kurz nach drei — Viertel nach, genau genommen."
+ result = scrub_for_voice(text)
+ assert "—" not in result.cleaned
+ assert "Kurz nach drei, Viertel nach" in result.cleaned
+
+
+def test_en_dash_becomes_comma() -> None:
+ text = "Alles bereit – wir können sofort loslegen."
+ result = scrub_for_voice(text)
+ assert "–" not in result.cleaned
+ assert "Alles bereit, wir können" in result.cleaned
+
+
+def test_hyphen_compound_survives_em_dash_filter() -> None:
+ """A plain ASCII hyphen compound has no surrounding spaces and must stay."""
+ text = "Dein T-Shirt liegt im Schrank."
+ result = scrub_for_voice(text)
+ assert "T-Shirt" in result.cleaned
+
+
+def test_trailing_em_dash_leaves_no_dangling_comma() -> None:
+ text = "Im Hintergrund laufen mehrere Programme —"
+ result = scrub_for_voice(text)
+ assert "—" not in result.cleaned
+ assert not result.cleaned.endswith(",")
+
+
def test_fallback_used_true_only_for_stacktrace() -> None:
"""``fallback_used`` nur ``True`` wenn der gesamte Text durch Standard-
Phrase ersetzt wurde (Stacktrace), nicht bei Teil-Scrub."""
@@ -654,6 +736,55 @@ def test_scrub_strips_end_call_sentinel() -> None:
assert "stripped_end_signal" in result.actions
+# ---------------------------------------------------------------------------
+# Web-search / SERP source artefacts (live forensic 2026-06-28, voice Turn 4).
+# The brain occasionally reads a raw search hit verbatim — title, snippet, URL,
+# "Weitere Ergebnisse von <domain>" — instead of synthesizing an answer. The
+# search_web tool result now instructs the brain to synthesize (primary fix);
+# this is the fail-closed defense so a source URL / domain can never be spoken.
+# ---------------------------------------------------------------------------
+
+
+def test_http_url_is_stripped_from_voice() -> None:
+ """A spoken answer must never read out an http(s) URL."""
+ text = "Die Prüfung dauert 190 Minuten. Mehr unter https://www.km.bayern.de/schueler.html"
+ result = scrub_for_voice(text)
+ assert "http" not in result.cleaned.lower()
+ assert "km.bayern.de" not in result.cleaned.lower()
+ assert "190 minuten" in result.cleaned.lower()
+ assert "removed_source_artifacts" in result.actions
+
+
+def test_serp_more_results_footer_is_stripped() -> None:
+ """The 'Weitere Ergebnisse von <domain>' SERP footer is never spoken."""
+ text = "Note 2 gibt es ab 34,5 Punkten. Weitere Ergebnisse von www.gutefrage.net"
+ result = scrub_for_voice(text)
+ low = result.cleaned.lower()
+ assert "gutefrage" not in low
+ assert "weitere ergebnisse" not in low
+ assert "note 2" in low
+ assert "removed_source_artifacts" in result.actions
+
+
+def test_bare_www_domain_is_stripped_from_voice() -> None:
+ """A bare www-domain hit reference is stripped (English/Spanish SERP too)."""
+ text = "Insgesamt 190 Minuten. Mehr dazu: www.realschule.bayern.de Viel Erfolg."
+ result = scrub_for_voice(text)
+ assert "www." not in result.cleaned.lower()
+ assert "realschule.bayern.de" not in result.cleaned.lower()
+ assert "190 minuten" in result.cleaned.lower()
+ assert "viel erfolg" in result.cleaned.lower()
+
+
+def test_clean_answer_without_sources_is_untouched() -> None:
+ """Defense against false positives: a normal spoken answer with no URL /
+ domain / SERP footer must pass through unchanged (no source-artifact pass)."""
+ text = "Morgen schreiben alle Realschüler in Bayern ihre Mathe-Abschlussprüfung."
+ result = scrub_for_voice(text)
+ assert result.cleaned == text
+ assert "removed_source_artifacts" not in result.actions
+
+
def test_scrub_sentinel_only_yields_empty() -> None:
from jarvis.speech.hangup import END_CALL_SIGNAL
@@ -761,3 +892,49 @@ def test_scrub_keeps_sentence_with_inline_brace_not_a_dump() -> None:
result = scrub_for_voice(text, language="de")
assert result.fallback_used is False
assert "test()" in result.cleaned or "test" in result.cleaned
+
+
+# ---------------------------------------------------------------------------
+# Raw shell / PowerShell command guard (live bug 2026-06-28): the fast tier
+# emitted a SendKeys PowerShell command as its reply and TTS read it aloud
+# "mit Sonderzeichen und allem". A raw command is code, never a spoken
+# sentence -> fail-closed to the standard phrase, like a stacktrace.
+# ---------------------------------------------------------------------------
+
+SHELL_COMMAND_CASES = [
+ pytest.param(
+ "Add-Type -AssemblyName System.Windows.Forms; "
+ "[System.Windows.Forms.SendKeys]::SendWait('^(g)')",
+ id="powershell-sendkeys-the-live-bug",
+ ),
+ pytest.param(
+ "[System.Windows.Forms.SendKeys]::SendWait('^g')",
+ id="dotnet-static-call",
+ ),
+ pytest.param("$env:USERPROFILE", id="ps-env-var"),
+ pytest.param("cmd /c start discord", id="cmd-invocation"),
+]
+
+
[email protected]("text", SHELL_COMMAND_CASES)
+def test_raw_shell_command_is_never_spoken(text: str) -> None:
+ result = scrub_for_voice(text, language="de")
+ assert result.fallback_used is True
+ for frag in ("SendKeys", "Add-Type", "::", "$env", "cmd /c"):
+ assert frag not in result.cleaned
+
+
+ "clean",
+ [
+ "Schau bitte im Browser-Verlauf nach.",
+ "Das kostet 5-10 Euro.",
+ "Die E-Mail ist raus.",
+ "Ich habe die Datei gespeichert.",
+ "Ruf Anna an und sag ihr Bescheid.",
+ ],
+)
+def test_shell_guard_does_not_destroy_normal_prose(clean: str) -> None:
+ # Hyphen compounds, ranges and ordinary speech must NOT trip the guard.
+ result = scrub_for_voice(clean, language="de")
+ assert result.fallback_used is False
diff --git a/tests/unit/brain/test_persona_loader.py b/tests/unit/brain/test_persona_loader.py
index 3d70f0a20a..c5eac6a8f8 100644
--- a/tests/unit/brain/test_persona_loader.py
+++ b/tests/unit/brain/test_persona_loader.py
@@ -87,7 +87,12 @@ def test_load_persona_prompt_extracts_real_persona(monkeypatch) -> None:
finally:
invalidate_cache()
assert prompt
- assert "JARVIS" in prompt
+ # Name-neutral persona (2026-06-29): the assistant name is injected at
+ # runtime from the wake word (see assistant_name.py), so the default persona
+ # must NOT bake in a fixed product name like "Jarvis". This guards against a
+ # regression back to a hardcoded "You are JARVIS" opener.
+ assert "JARVIS" not in prompt
+ assert "voice companion" in prompt
assert "LANGUAGE POLICY" in prompt
# Mandat-Phase-2: ECHO-PARAPHRASE-Sektion direkt nach OUTPUT RULES
assert "ECHO-PARAPHRASE" in prompt
diff --git a/tests/unit/brain/test_plugin_tool_spawn_hide.py b/tests/unit/brain/test_plugin_tool_spawn_hide.py
new file mode 100644
index 0000000000..dd27ce70f3
--- /dev/null
+++ b/tests/unit/brain/test_plugin_tool_spawn_hide.py
@@ -0,0 +1,87 @@
+"""A connected plugin tool's turn must use the (router-only) plugin tool directly,
+not spawn a worker that can't reach it.
+
+Forensic 2026-06-27 (voice 17:44): "Schau mal nach was in meinem Google Calendar
+am 29. ist" spawned a worker ("umfangreicheres Stueck Arbeit") which has no
+google_calendar tool (plugin tools are router-tier only, AP-5/AP-14) and answered
+"kann ich nicht". ``_hide_spawn_when_plugin_tool_handles_turn`` drops the spawn
+vehicles on a calendar (plugin-tool) turn so the router calls the tool inline."""
+from __future__ import annotations
+
+import re
+
+from jarvis.brain.manager import BrainManager
+
+_NEVER = re.compile(r"(?!)") # matches nothing
+
+
+def _mgr() -> BrainManager:
+ m = BrainManager.__new__(BrainManager) # bypass heavy __init__
+ m._force_spawn_pattern = _NEVER # no explicit heavy-work vehicle phrase
+ return m
+
+
+def _surface() -> dict:
+ return {
+ "google_calendar": object(),
+ "search_web": object(),
+ "spawn_worker": object(),
+ "multi_spawn": object(),
+ }
+
+
+def test_calendar_turn_hides_spawn_keeps_tool():
+ m = _mgr()
+ out = m._hide_spawn_when_plugin_tool_handles_turn(
+ _surface(), "Was habe ich heute für Termine?"
+ )
+ assert "google_calendar" in out
+ assert "search_web" in out # inline answer path stays open
+ assert "spawn_worker" not in out
+ assert "multi_spawn" not in out
+
+
+def test_exact_failing_utterance_now_hides_spawn():
+ m = _mgr()
+ out = m._hide_spawn_when_plugin_tool_handles_turn(
+ _surface(),
+ "Schau mal bitte nach, was in meinem Google Calendar am 29. für Termine sind",
+ )
+ assert "spawn_worker" not in out and "multi_spawn" not in out
+ assert "google_calendar" in out
+
+
+def test_non_calendar_turn_keeps_spawn():
+ m = _mgr()
+ surface = _surface()
+ out = m._hide_spawn_when_plugin_tool_handles_turn(surface, "Erzähl mir einen Witz")
+ assert out == surface # untouched — no plugin keyword matched
+
+
+def test_artifact_build_request_keeps_spawn():
+ # A request to BUILD a file/report legitimately offloads to a worker.
+ m = _mgr()
+ m._research_wants_artifact = lambda _t: True # type: ignore[method-assign]
+ out = m._hide_spawn_when_plugin_tool_handles_turn(
+ _surface(), "Erstelle mir einen Kalender-Report als Datei"
+ )
+ assert "spawn_worker" in out
+
+
+def test_explicit_subagent_vehicle_keeps_spawn():
+ m = _mgr()
+ m._force_spawn_pattern = re.compile(r"deep dive|subagent", re.I)
+ out = m._hide_spawn_when_plugin_tool_handles_turn(
+ _surface(), "Mach einen deep dive in meinen Kalender"
+ )
+ assert "spawn_worker" in out
+
+
+def test_no_plugin_tool_in_surface_keeps_spawn():
+ # If the plugin tool isn't available, hiding spawn would blind the turn.
+ m = _mgr()
+ surface = {"search_web": object(), "spawn_worker": object()}
+ out = m._hide_spawn_when_plugin_tool_handles_turn(
+ surface, "Was habe ich heute für Termine?"
+ )
+ assert "spawn_worker" in out # no calendar tool present => don't hide
diff --git a/tests/unit/brain/test_provider_test_local_stt_not_installed.py b/tests/unit/brain/test_provider_test_local_stt_not_installed.py
new file mode 100644
index 0000000000..ff71bfec38
--- /dev/null
+++ b/tests/unit/brain/test_provider_test_local_stt_not_installed.py
@@ -0,0 +1,24 @@
+"""M5 (honest status): on a headless host without the [desktop] extra, the local
+faster-whisper STT import raises ModuleNotFoundError. The API-Keys "Test" must
+report NOT_CONFIGURED ("extra not installed") — an actionable amber chip — not a
+red ERROR "integration bug".
+"""
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+from jarvis.brain.provider_test import NOT_CONFIGURED, run_provider_test
+
+
+def test_local_stt_import_error_reports_not_installed():
+ spec = SimpleNamespace(id="faster-whisper", tier="stt", auth_mode="none")
+
+ def _make_stt(cfg, provider):
+ raise ModuleNotFoundError("No module named 'faster_whisper'")
+
+ res = asyncio.run(
+ run_provider_test(spec, SimpleNamespace(stt=SimpleNamespace()), make_stt=_make_stt)
+ )
+ assert res.status == NOT_CONFIGURED
+ assert "extra" in res.detail.lower() or "install" in res.detail.lower()
diff --git a/tests/unit/brain/test_routing.py b/tests/unit/brain/test_routing.py
index 9cbe1bdcf6..3be3454375 100644
--- a/tests/unit/brain/test_routing.py
+++ b/tests/unit/brain/test_routing.py
@@ -891,6 +891,45 @@ def test_router_tools_stays_frozenset() -> None:
assert isinstance(ROUTER_TOOLS, frozenset)
+def test_dispatch_to_harness_not_in_router_tools() -> None:
+ """``dispatch-to-harness`` must NOT be an LLM-visible router tool.
+
+ Phantom-openclaw regression (forensic 2026-06-28): the tool's raw ``harness``
+ parameter let the brain request ``harness="openclaw"`` — an unregistered
+ harness (Welle-4 removal) — which surfaced a raw "Harness not available"
+ KeyError to voice. Heavy sub-agent work is ``spawn-worker``; live desktop
+ work is ``computer-use``. The tool class still exists for the INTERNAL
+ local-action fast path, but it must never be router-selectable again.
+ """
+ from jarvis.brain.factory import ROUTER_TOOLS
+
+ assert "dispatch-to-harness" not in ROUTER_TOOLS
+
+
+async def test_subagent_request_forces_spawn_worker() -> None:
+ """An explicit "start a subagent" request forces spawn_worker, never a harness.
+
+ Structural guarantee #2 (the #1 guarantee is that dispatch-to-harness is no
+ longer router-visible): a cleanly recognised subagent trigger must route to
+ spawn_worker deterministically, before any free LLM tool choice.
+ """
+ manager, executor = _manager_with_spawn()
+ utterance = "Starte einen Subagenten, der mir einen Lernzettel schreibt"
+
+ assert manager._should_force_spawn(utterance), (
+ "explicit subagent request did not trigger the force-spawn heuristic"
+ )
+ result = await manager._force_spawn_worker(utterance)
+ assert result is not None
+ assert len(executor.calls) == 1, (
+ f"expected exactly one spawn call, got {len(executor.calls)}"
+ )
+ tool, _args, user_utterance = executor.calls[0]
+ assert tool.name == "spawn_worker"
+ assert user_utterance == utterance # verbatim, never paraphrased
+
+
def test_no_spawn_tool_leaked_into_worker_set() -> None:
"""No spawn/dispatch/run-skill tool may appear in a worker tool-set.
@@ -1514,8 +1553,14 @@ def test_router_tools_is_pure_dispatcher_set() -> None:
"screen-snapshot",
"multi-spawn",
"spawn-worker",
- # Phase-5-Endstand (ADR-0011 + Re-Introduction Begruendung im Code)
- "dispatch-to-harness",
+ # NB: ``dispatch-to-harness`` was REMOVED from the LLM-visible router
+ # set on 2026-06-28 (ADR-0011 amendment "dispatch-to-harness removal").
+ # Its raw ``harness`` param let the brain request a phantom
+ # ``harness="openclaw"`` (unregistered, Welle-4 removal), surfacing a
+ # raw "Harness not available" KeyError to voice. Heavy work →
+ # spawn-worker, desktop → computer-use. It must NOT reappear here;
+ # the negative guard ``test_dispatch_to_harness_not_in_router_tools``
+ # pins that.
# Phase 8.4 (Quality-Gate, Recursion-geschuetzt analog spawn-worker)
"dispatch-with-review",
# AI Pointer (pull path): resolve the element under the mouse cursor
@@ -1556,6 +1601,11 @@ def test_router_tools_is_pure_dispatcher_set() -> None:
# rationale as gmail — its rest_wrapper transport produced zero MCP
# tools, so it must be router-visible directly. Read-only.
"vercel",
+ # Google Calendar Marketplace plugin (2026-06-27): native bridge tool
+ # whose bot logic is a Node script (calendar_bot.mjs). Same rationale
+ # as gmail — no MCP server block, so it must be router-visible
+ # directly. Full autonomy (writes are monitor, never ask).
+ "google_calendar",
# Computer-Use (Wave 1, 2026-05-29): first-class tool to drive the
# live desktop. Router-tier only — a direct safe-gated action (the
# loop gates each action via ToolExecutor, ADR-0008), never a spawn,
@@ -2850,3 +2900,173 @@ async def test_force_spawn_worker_skips_dropped_mission_recap() -> None:
)
assert result is None, "no mission for a dropped-card recap"
assert executor.calls == [], "zero spawn_worker dispatches for a recap turn"
+
+
+# ---------------------------------------------------------------------------
+# Knowledge-question spawn-hide (forensic 2026-06-27, voice session 08:35):
+# "Welche Unternehmen haben so viel Speicherplatz?" was a pure factual question,
+# yet the router-LLM reflexively CHOSE spawn_worker and announced "ich ziehe
+# einen Experten hinzu". The deterministic force-spawn gate correctly stands
+# down on such a turn (it only FORCES spawns, it never CONSTRAINS the LLM's own
+# spawn reflex). The fix mirrors the smalltalk tool-hide: on a plain knowledge
+# question the spawn tools are removed from the per-turn LLM surface, so the
+# model cannot grab spawn_worker against its own prompt rule. Read/search tools
+# stay visible so the question is still answerable inline.
+# ---------------------------------------------------------------------------
+
+
+class _FakeSearchTool:
+ name = "search_web"
+ schema: dict[str, Any] = {}
+
+
+def _manager_with_spawn_and_search() -> BrainManager:
+ executor = _RecordingExecutor()
+ manager = BrainManager(
+ config=JarvisConfig(),
+ bus=EventBus(),
+ tools={"spawn_worker": _FakeTool(), "search_web": _FakeSearchTool()},
+ tool_executor=executor, # type: ignore[arg-type]
+ )
+ return manager
+
+
+PLAIN_KNOWLEDGE_QUESTIONS = [
+ "Welche Unternehmen haben so viel Speicherplatz?",
+ "Welche Firmen besitzen so viele Rechenzentren?",
+ "Wie viele Menschen leben in Australien?",
+ "Which companies own that much storage?",
+ "Was ist der groesste Cloud-Anbieter der Welt?",
+]
+
+
[email protected]("utterance", PLAIN_KNOWLEDGE_QUESTIONS)
+def test_plain_knowledge_question_hides_spawn_worker(utterance: str) -> None:
+ """A pure factual/knowledge question removes spawn_worker from the per-turn
+ LLM tool surface, while keeping the read/search tools to answer inline."""
+ manager = _manager_with_spawn_and_search()
+ gated = manager._hide_spawn_on_knowledge_question(dict(manager._tools), utterance)
+ assert "spawn_worker" not in gated, (
+ f"spawn_worker must be hidden on a plain knowledge question: {utterance!r}"
+ )
+ assert "search_web" in gated, "search_web must stay visible to answer inline"
+
+
+BUILD_OR_ACTION_REQUESTS = [
+ "Bau mir eine HTML-Uebersicht der groessten Cloud-Anbieter",
+ "Schreib mir einen Bericht ueber Rechenzentren in eine Datei",
+]
+
+
[email protected]("utterance", BUILD_OR_ACTION_REQUESTS)
+def test_build_request_keeps_spawn_worker(utterance: str) -> None:
+ """A request that BUILDS a deliverable keeps spawn_worker available — the
+ artifact gate must not be stripped by the knowledge-question hide."""
+ manager = _manager_with_spawn_and_search()
+ gated = manager._hide_spawn_on_knowledge_question(dict(manager._tools), utterance)
+ assert "spawn_worker" in gated, (
+ f"spawn_worker must stay for a build request: {utterance!r}"
+ )
+
+
+def test_explicit_subagent_question_keeps_spawn_worker() -> None:
+ """Even in question form, an explicitly named heavy-work vehicle keeps the
+ spawn tool — the user named the vehicle, respect it (AD-S9)."""
+ manager = _manager_with_spawn_and_search()
+ gated = manager._hide_spawn_on_knowledge_question(
+ dict(manager._tools),
+ "Kannst du einen Subagenten spawnen der die groessten Cloud-Anbieter recherchiert?",
+ )
+ assert "spawn_worker" in gated, (
+ "an explicit 'Subagent' trigger must never be hidden, even in question form"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Signalless-turn action-hide (forensic 2026-06-27, voice session): the German
+# smalltalk "Was geht ab?" was mis-transcribed by STT as "Lask it up!" [en]
+# confidence 0.509 — missing BOTH the smalltalk allowlist AND the whisper-junk
+# seed lists — so the action tools stayed visible and gemini, reading a
+# 30k-token context full of the PREVIOUS "open Discord, bridge-mine channel"
+# command, re-ran that exact computer_use plan on a turn that asked for nothing.
+# A short turn with no actionable signal of its own must not reach computer_use
+# / spawn so it cannot inherit the prior turn's desktop action.
+# ---------------------------------------------------------------------------
+
+
+class _FakeCuTool:
+ name = "computer_use"
+ schema: dict[str, Any] = {}
+
+
+def _manager_with_cu_spawn_search() -> BrainManager:
+ executor = _RecordingExecutor()
+ return BrainManager(
+ config=JarvisConfig(),
+ bus=EventBus(),
+ tools={
+ "computer_use": _FakeCuTool(),
+ "spawn_worker": _FakeTool(),
+ "search_web": _FakeSearchTool(),
+ },
+ tool_executor=executor, # type: ignore[arg-type]
+ )
+
+
+# GENERAL rule (user mandate 2026-06-27 — "this must apply to ALL questions"):
+# ANY turn with no action signal of its own — short or long, with or without a
+# trailing "?" — loses computer_use/spawn so it cannot inherit the previous
+# turn's CU action. Mis-transcriptions, smalltalk, and plain questions all
+# qualify. (The real "Was geht ab?" is ALSO caught upstream by the smalltalk
+# gate; here we prove the filter itself no longer exempts it.)
+NO_ACTION_SIGNAL_TURNS = [
+ "Lask it up!", # the live STT junk
+ "Mask it up.", # sibling STT-junk variant
+ "Was geht ab?", # i18n-allow: the original question
+ "Wie viele Menschen leben in Australien?", # i18n-allow: long factual question
+ "Which company owns the most data centers in the world right now?",
+ "Erzaehl mir einen Witz", # i18n-allow: chit-chat, no action
+]
+
+
[email protected]("utterance", NO_ACTION_SIGNAL_TURNS)
+def test_no_action_signal_turn_hides_computer_use_and_spawn(utterance: str) -> None:
+ """ANY turn with no action signal of its own (question, remark, or
+ mis-transcription — regardless of length or a trailing '?') cannot reach
+ computer_use/spawn, so the LLM cannot inherit the previous turn's CU action.
+ The read-only search tool stays visible so the turn is still answerable."""
+ manager = _manager_with_cu_spawn_search()
+ gated = manager._hide_action_tools_on_signalless_turn(
+ dict(manager._tools), utterance
+ )
+ assert "computer_use" not in gated, (
+ f"computer_use must be hidden on a no-action-signal turn: {utterance!r}"
+ )
+ assert "spawn_worker" not in gated, (
+ f"spawn_worker must be hidden on a no-action-signal turn: {utterance!r}"
+ )
+ assert "search_web" in gated, "read-only search_web must stay visible"
+
+
+ACTIONABLE_TURNS = [
+ "Oeffne Discord fuer mich", # explicit open-app intent
+ "Klick auf den Play-Button", # PC-control verb
+ "Mach das am Bildschirm", # names the screen surface
+ "Was siehst du auf meinem Bildschirm?", # i18n-allow: a VISUAL question keeps CU (Bildschirm)
+ "Bau mir eine HTML-Uebersicht der groessten Cloud-Anbieter", # artifact build
+]
+
+
[email protected]("utterance", ACTIONABLE_TURNS)
+def test_actionable_turn_keeps_computer_use(utterance: str) -> None:
+ """A turn that DOES carry an action signal — an action verb, a named app, the
+ screen surface, or an artifact-build request — keeps computer_use. This holds
+ even for a question ('Was siehst du auf meinem Bildschirm?'): naming the
+ screen is action-intent, so the heavy tools stay available."""
+ manager = _manager_with_cu_spawn_search()
+ gated = manager._hide_action_tools_on_signalless_turn(
+ dict(manager._tools), utterance
+ )
+ assert "computer_use" in gated, (
+ f"computer_use must stay for an actionable turn: {utterance!r}"
+ )
diff --git a/tests/unit/brain/test_section_health.py b/tests/unit/brain/test_section_health.py
new file mode 100644
index 0000000000..d6bbf95e3f
--- /dev/null
+++ b/tests/unit/brain/test_section_health.py
@@ -0,0 +1,72 @@
+"""Unit tests for the pure section-health rollup core.
+
+Guards the two pure functions the ``/api/providers/section-health`` endpoint
+composes, plus the status vocabulary itself. The I/O orchestration (resolving the
+active provider, running the real connectivity test) is exercised separately; here
+we only pin the rules so the tab indicator can never silently change meaning.
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.brain import provider_test
+from jarvis.brain import section_health as sh
+
+
+class TestSectionStatusForTest:
+ def test_missing_credential_is_needs_setup_regardless_of_test(self) -> None:
+ # No key stored → the tab is "not set up", even if a stale test string is
+ # passed in. Missing always wins over any test outcome.
+ assert sh.section_status_for_test(None, configured=False) == sh.NEEDS_SETUP
+ assert sh.section_status_for_test("ok", configured=False) == sh.NEEDS_SETUP
+ assert sh.section_status_for_test("bad_key", configured=False) == sh.NEEDS_SETUP
+
+ def test_configured_and_ok_is_ok(self) -> None:
+ assert sh.section_status_for_test("ok", configured=True) == sh.OK
+
+ def test_configured_but_not_tested_is_unknown(self) -> None:
+ # Honesty: a stored key we haven't called yet must not claim "ok".
+ assert sh.section_status_for_test(None, configured=True) == sh.UNKNOWN
+
+ def test_test_not_configured_is_needs_setup(self) -> None:
+ # The live call itself found no key — treat as not set up, never a red error.
+ assert sh.section_status_for_test("not_configured", configured=True) == sh.NEEDS_SETUP
+
+ @pytest.mark.parametrize(
+ "bad",
+ ["bad_key", "no_credits", "rate_limited", "model_unavailable", "unreachable", "error"],
+ )
+ def test_every_failing_test_status_is_error(self, bad: str) -> None:
+ assert sh.section_status_for_test(bad, configured=True) == sh.ERROR
+
+ def test_covers_every_provider_test_status(self) -> None:
+ # Anti-drift: every status the provider test can emit must map to a
+ # defined section bucket (no unmapped/silently-dropped outcome).
+ for status in provider_test.PROVIDER_TEST_STATUSES:
+ mapped = sh.section_status_for_test(status, configured=True)
+ assert mapped in sh.SECTION_HEALTH_STATUSES
+
+
+class TestAggregate:
+ def test_empty_is_unknown(self) -> None:
+ assert sh.aggregate([]) == sh.UNKNOWN
+
+ def test_single_passthrough(self) -> None:
+ assert sh.aggregate([sh.OK]) == sh.OK
+ assert sh.aggregate([sh.NEEDS_SETUP]) == sh.NEEDS_SETUP
+
+ def test_error_beats_everything(self) -> None:
+ assert sh.aggregate([sh.OK, sh.NEEDS_SETUP, sh.ERROR]) == sh.ERROR
+ assert sh.aggregate([sh.ERROR, sh.UNKNOWN]) == sh.ERROR
+
+ def test_needs_setup_beats_ok_and_unknown(self) -> None:
+ assert sh.aggregate([sh.OK, sh.NEEDS_SETUP]) == sh.NEEDS_SETUP
+ assert sh.aggregate([sh.UNKNOWN, sh.NEEDS_SETUP]) == sh.NEEDS_SETUP
+
+ def test_ok_beats_unknown(self) -> None:
+ assert sh.aggregate([sh.UNKNOWN, sh.OK]) == sh.OK
+
+
+def test_vocabulary_is_exactly_four() -> None:
+ assert set(sh.SECTION_HEALTH_STATUSES) == {sh.OK, sh.NEEDS_SETUP, sh.ERROR, sh.UNKNOWN}
+ assert len(sh.SECTION_HEALTH_STATUSES) == 4
diff --git a/tests/unit/brain/test_self_mod_tools.py b/tests/unit/brain/test_self_mod_tools.py
index 7e52df1aa2..fa96281bfa 100644
--- a/tests/unit/brain/test_self_mod_tools.py
+++ b/tests/unit/brain/test_self_mod_tools.py
@@ -189,17 +189,17 @@ class TestSchemaCompliance:
class TestListMutableSettings:
- def test_returns_thirteen_entries(self, tools: dict[str, Any]) -> None:
- # 9 historical settings + the language keys (brain.reply_language,
- # stt.language, tts.language_code) + ui.language (interface language)
- # added for the Jarvis Control API.
+ def test_returns_full_schema_set(self, tools: dict[str, Any]) -> None:
+ # Wave 1.1: list_mutable_settings now returns the whole schema-derived
+ # mutable set, not the 13-entry hand-list. Wave 2: each entry also
+ # carries value_type (+ enum/range) for NL value-mapping.
result = _exec(tools["list_mutable_settings"], {})
assert result.success is True
- assert len(result.output) == 13
+ assert len(result.output) > 50
+ core = {"path", "current_value", "description", "risk_tier", "needs_restart"}
for entry in result.output:
- assert {"path", "current_value", "description", "risk_tier", "needs_restart"} == set(
- entry.keys()
- )
+ assert core <= set(entry.keys())
+ assert "value_type" in entry
# The voice-tunable computer-use step ceiling must be present. Points at
# step_budget (the field the loop reads), not the legacy max_steps no-op.
paths = {entry["path"] for entry in result.output}
@@ -207,6 +207,15 @@ class TestListMutableSettings:
# The canonical reply-language path must be discoverable by agents.
assert "brain.reply_language" in paths
+ def test_enriches_with_type_and_constraints(self, tools: dict[str, Any]) -> None:
+ # Wave 2: the brain needs the type + bounds to map "talk slower" to a
+ # concrete value. tts.speed is a float; ui.language is an enum.
+ result = _exec(tools["list_mutable_settings"], {})
+ by_path = {entry["path"]: entry for entry in result.output}
+ assert by_path["tts.speed"]["value_type"] == "float"
+ assert by_path["ui.language"]["value_type"] == "enum"
+ assert set(by_path["ui.language"]["allowed_values"]) == {"en", "de", "es"}
+
def test_current_values_match_fixture(self, tools: dict[str, Any]) -> None:
result = _exec(tools["list_mutable_settings"], {})
by_path = {entry["path"]: entry for entry in result.output}
@@ -231,6 +240,40 @@ class TestListMutableSettings:
assert "invalid_input" in result.error
+# ----------------------------------------------------------------------
+# build factory: auto_apply policy wiring (Wave 1.3)
+# ----------------------------------------------------------------------
+
+
+class TestBuildAutoApply:
+ def test_all_policy_applies_ask_tier_immediately(
+ self, writer: AtomicConfigWriter
+ ) -> None:
+ # The voice wiring passes auto_apply="all"; an ASK-tier change then
+ # applies at once (no pending), matching "never ask, always now".
+ tools = build_self_mod_tools(writer=writer, auto_apply="all")
+ result = _exec(
+ tools["set_config_value"],
+ {"path": "tts.provider", "new_value": "elevenlabs", "reason": ""},
+ )
+ assert result.success is True
+ assert result.output["applied"] is True
+ assert result.output["needs_confirmation"] is False
+
+ def test_default_policy_defers_ask_tier(
+ self, writer: AtomicConfigWriter
+ ) -> None:
+ # REST/CLI wiring (default) keeps the ASK confirm round-trip.
+ tools = build_self_mod_tools(writer=writer)
+ result = _exec(
+ tools["set_config_value"],
+ {"path": "tts.provider", "new_value": "elevenlabs", "reason": ""},
+ )
+ assert result.success is True
+ assert result.output["applied"] is False
+ assert result.output["needs_confirmation"] is True
+
+
# ----------------------------------------------------------------------
# get_config_value
# ----------------------------------------------------------------------
@@ -244,7 +287,7 @@ class TestGetConfigValue:
"path": "tts.provider",
"value": "gemini-flash-tts",
"in_allowlist": True,
- "description": "TTS-Provider (Hot-Reload abgedeckt)",
+ "description": "TTS provider (hot-reload covered).",
}
def test_unknown_path_returns_in_allowlist_false(
diff --git a/tests/unit/brain/test_skill_inline_tool_gate.py b/tests/unit/brain/test_skill_inline_tool_gate.py
new file mode 100644
index 0000000000..2e408d2645
--- /dev/null
+++ b/tests/unit/brain/test_skill_inline_tool_gate.py
@@ -0,0 +1,44 @@
+"""A skill-matched turn injects the skill's instructions into the turn context
+deterministically (AD-S4: "no run-skill round trip needed"). But the run-skill
+tool stayed visible, so a weak model (gemini-3.5-flash) made a REDUNDANT
+run-skill call and leaked the raw ``<call:tool.run-skill ...>`` text instead of
+executing it (forensic 2026-06-24).
+
+Hiding run-skill once the instructions are already inline makes skill execution
+PROVIDER- and MODEL-agnostic: no tool call is needed by any model (gemini-fast,
+Claude, or a tool-incapable CLI brain) — it just follows the injected
+instructions. These tests pin that gate.
+"""
+from __future__ import annotations
+
+from jarvis.brain.manager import BrainManager
+
+
+def _mgr() -> BrainManager:
+ return BrainManager.__new__(BrainManager) # bypass heavy __init__
+
+
+def test_run_skill_hidden_when_injected_inline() -> None:
+ m = _mgr()
+ m._skill_injected_inline = True
+ tools = {"run-skill": object(), "screenshot": object()}
+ out = m._drop_run_skill_when_inline_injected(tools)
+ assert "run-skill" not in out
+ assert "screenshot" in out
+
+
+def test_run_skill_kept_when_not_injected() -> None:
+ m = _mgr()
+ m._skill_injected_inline = False
+ tools = {"run-skill": object(), "screenshot": object()}
+ out = m._drop_run_skill_when_inline_injected(tools)
+ assert "run-skill" in out
+ assert "screenshot" in out
+
+
+def test_gate_is_noop_on_non_dict() -> None:
+ """A router-lead turn can pass a non-dict tool set through; the gate must
+ not choke on it."""
+ m = _mgr()
+ m._skill_injected_inline = True
+ assert m._drop_run_skill_when_inline_injected(None) is None
diff --git a/tests/unit/brain/test_skill_routing_guard.py b/tests/unit/brain/test_skill_routing_guard.py
index d097faa3e4..22191a8656 100644
--- a/tests/unit/brain/test_skill_routing_guard.py
+++ b/tests/unit/brain/test_skill_routing_guard.py
@@ -510,3 +510,36 @@ async def test_open_discord_e2e_dispatches_computer_use_not_refusal(
name == "dispatch_to_harness" for name, *_ in executor.harness_calls
), f"Computer-Use was never dispatched; calls={executor.harness_calls}"
assert reply, "the turn must speak an immediate ACK, not stay silent"
+
+
+# ----------------------------------------------------------------------
+# Definitional-question guard (2026-06-24 skill-routing eval): a bare-name
+# plugin trigger must not capture a "was ist <App>?" knowledge turn, while a
+# real data request that merely opens with "was ist" stays a skill hit.
+# ----------------------------------------------------------------------
+
+import pytest as _pytest # noqa: E402
+
+from jarvis.brain.manager import _is_definitional_question_about # noqa: E402
+
+
+@_pytest.mark.parametrize(
+ "text,token,expected",
+ [
+ # Definitional questions ABOUT the app → suppress (do not fire skill).
+ ("was ist eigentlich github fuer eine plattform?", "github", True), # i18n-allow
+ ("was ist stripe ueberhaupt und wofuer nutzt man das?", "stripe", True), # i18n-allow
+ ("what is github?", "github", True),
+ ("what is stripe used for", "stripe", True),
+ # Real data requests / commands that merely mention the token → keep.
+ ("was ist in meinem posteingang?", "posteingang", False), # i18n-allow
+ ("lies meine github issues vor", "github", False), # i18n-allow
+ ("check my stripe payments", "stripe", False),
+ ("starte die morgenroutine", "morgenroutine", False), # i18n-allow
+ # Degenerate inputs.
+ ("", "github", False),
+ ("was ist github", "", False),
+ ],
+)
+def test_definitional_question_guard(text: str, token: str, expected: bool) -> None:
+ assert _is_definitional_question_about(text, token) is expected
diff --git a/tests/unit/brain/test_system_prompt_name.py b/tests/unit/brain/test_system_prompt_name.py
index c36aeebc49..5f83b62e48 100644
--- a/tests/unit/brain/test_system_prompt_name.py
+++ b/tests/unit/brain/test_system_prompt_name.py
@@ -1,9 +1,14 @@
"""The configurable assistant name must flow into the brain system prompt.
User mandate 2026-05-29: renaming the assistant (e.g. to "Micron") must make it
-call itself Micron instead of the hardcoded "Jarvis". These lock that the name
-reaches ``_build_system_prompt`` — both the base prompt and, for a non-default
-name, the prominent identity directive that overrides the persona files.
+call itself Micron instead of a hardcoded name. These lock that the name reaches
+``_build_system_prompt`` — both the base prompt and the prominent identity
+directive.
+
+2026-06-29: the persona files were made name-neutral (no baked-in "Jarvis"), so
+the identity directive is now emitted for EVERY resolved name except the neutral
+``Assistant`` fallback, and it no longer carries the old self-contradictory
+"nicht Jarvis" anchor.
"""
from __future__ import annotations
@@ -29,26 +34,26 @@ def _manager_with_name(*, wake_phrase: str = "Hey Jarvis") -> BrainManager:
return m
-def test_default_name_keeps_jarvis_and_no_identity_directive() -> None:
+def test_wake_jarvis_gets_identity_directive_without_contradiction() -> None:
prompt = _manager_with_name(wake_phrase="Hey Jarvis")._build_system_prompt()
assert "Du bist Jarvis" in prompt
- # "Jarvis" is the persona-file baseline (SOUL.md / JARVIS_PERSONA.md already
- # say "Jarvis"), so no identity-override directive is needed — emitting one
- # would produce the self-contradictory "Du heisst Jarvis — nicht Jarvis".
- assert "DEIN NAME IST" not in prompt
+ # The persona is now name-neutral, so even a user-chosen "Jarvis" wake word
+ # gets a clean identity directive — never the old "Du heisst Jarvis — nicht
+ # Jarvis" self-contradiction.
+ assert "DEIN NAME IST JARVIS" in prompt
+ assert "nicht Jarvis" not in prompt
def test_wake_phrase_micron_makes_assistant_micron() -> None:
prompt = _manager_with_name(wake_phrase="Micron")._build_system_prompt()
assert "Du bist Micron" in prompt
- # The prominent identity directive overrides the persona files' "Jarvis".
assert "DEIN NAME IST MICRON" in prompt
- assert "nicht Jarvis" in prompt
+ assert "nicht Jarvis" not in prompt
def test_wake_phrase_is_the_only_name_source() -> None:
- # "Hey Computer" wake → the assistant is "Computer"; there is no override.
+ # "Hey Computer" wake → the assistant is "Computer".
prompt = _manager_with_name(wake_phrase="Hey Computer")._build_system_prompt()
assert "Du bist Computer" in prompt
assert "DEIN NAME IST COMPUTER" in prompt
- assert "nicht Jarvis" in prompt
+ assert "nicht Jarvis" not in prompt
diff --git a/tests/unit/brain/test_tool_use_loop_config_readback.py b/tests/unit/brain/test_tool_use_loop_config_readback.py
new file mode 100644
index 0000000000..7c665facf2
--- /dev/null
+++ b/tests/unit/brain/test_tool_use_loop_config_readback.py
@@ -0,0 +1,102 @@
+"""ToolUseLoop deterministic honest readback for set_config_value (Wave 1.4).
+
+In the voice/chat path config changes apply immediately (no pre-confirm), so the
+loop must speak the REAL pipeline outcome and end the turn — never let the brain
+phrase a second free-form "done". Mirrors the voice-confirm sentinel handling.
+"""
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from typing import Any
+from uuid import uuid4
+
+import pytest
+
+# config first → satisfies the writer→config→brain→voice→self_mod import order.
+import jarvis.core.config # noqa: F401, E402 isort:skip
+from jarvis.brain.tool_use_loop import ToolUseLoop # noqa: E402
+from jarvis.core.protocols import BrainDelta, BrainRequest, ToolResult # noqa: E402
+from jarvis.core.self_mod import PendingMutation # noqa: E402
+
+
+class _ConfigTool:
+ name = "set_config_value"
+ schema: dict[str, Any] = {}
+
+
+class _OneToolBrain:
+ """Turn 1 calls set_config_value; a turn 2 would mean the loop did NOT
+ suppress the second round."""
+
+ def __init__(self) -> None:
+ self.requests: list[BrainRequest] = []
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ self.requests.append(req)
+ if len(self.requests) == 1:
+ yield BrainDelta(tool_call={
+ "id": "c1", "name": "set_config_value",
+ "input": {"path": "tts.speed", "new_value": 1.25, "reason": ""},
+ })
+ yield BrainDelta(finish_reason="tool_use")
+ return
+ yield BrainDelta(content="second round should not happen")
+ yield BrainDelta(finish_reason="stop")
+
+
+class _Executor:
+ def __init__(self, result: ToolResult) -> None:
+ self._result = result
+
+ async def execute(self, tool: Any, args: dict[str, Any], **_: Any) -> ToolResult:
+ return self._result
+
+
+def _applied_result() -> ToolResult:
+ dump = PendingMutation(
+ id=uuid4(), path="tts.speed", old_value=1.0, new_value=1.25,
+ needs_confirmation=False, risk_tier="safe", requires_restart=False,
+ applied=True, description="TTS speed",
+ ).model_dump(mode="json")
+ return ToolResult(success=True, output=dump, error=None)
+
+
+async def test_applied_speaks_honest_readback_and_ends_turn() -> None:
+ brain = _OneToolBrain()
+ loop = ToolUseLoop(brain, {"set_config_value": _ConfigTool()}, _Executor(_applied_result())) # type: ignore[arg-type]
+ spoken: list[str] = []
+
+ result = await loop.run(
+ [], user_utterance="set the speech speed to one point two five",
+ reply_language="en", text_consumer=spoken.append,
+ )
+
+ assert len(brain.requests) == 1 # second brain round suppressed
+ assert result.finish_reason == "suppress_response"
+ assert "1.25" in result.text # the real value, not a vague "done"
+ assert "done" in result.text.lower()
+ assert spoken and spoken[-1] == result.text
+
+
+async def test_forbidden_never_reads_back_as_done() -> None:
+ refused = ToolResult(
+ success=False,
+ output={"error_kind": "forbidden_path", "path": "security.admin_password_hash"},
+ error="forbidden_path: ...",
+ )
+ brain = _OneToolBrain()
+ loop = ToolUseLoop(brain, {"set_config_value": _ConfigTool()}, _Executor(refused)) # type: ignore[arg-type]
+ spoken: list[str] = []
+
+ result = await loop.run(
+ [], user_utterance="change the admin password hash",
+ reply_language="en", text_consumer=spoken.append,
+ )
+
+ assert len(brain.requests) == 1 # no free-form second round
+ assert result.finish_reason == "suppress_response"
+ # The crucial guarantee: a refused change is never spoken as success.
+ assert "done" not in result.text.lower()
+ assert "security" not in result.text.lower() # no path leak
diff --git a/tests/unit/ci/test_privacy_pre_push.py b/tests/unit/ci/test_privacy_pre_push.py
index 27c1df9e89..efa9601645 100644
--- a/tests/unit/ci/test_privacy_pre_push.py
+++ b/tests/unit/ci/test_privacy_pre_push.py
@@ -80,7 +80,7 @@ class TestTargetIsPublic:
def test_private_work_repo_is_not_public(self):
assert not gate.target_is_public(
- "origin", "https://github.com/personal-jarvis/personal-jarvis.git"
+ "origin", "https://github.com/example-org/private-work.git"
)
def test_url_match_is_case_insensitive(self):
@@ -249,7 +249,7 @@ class TestMain:
f"refs/heads/main {_NONZERO_A} refs/heads/main {_NONZERO_B}\n"
)
rc = gate.main(
- ["prog", "origin", "https://github.com/personal-jarvis/personal-jarvis.git"],
+ ["prog", "origin", "https://github.com/example-org/private-work.git"],
stdin,
)
assert rc == 0
diff --git a/tests/unit/cli_ctl/test_cli_coverage.py b/tests/unit/cli_ctl/test_cli_coverage.py
index 6488fe6aee..94c0f1dce9 100644
--- a/tests/unit/cli_ctl/test_cli_coverage.py
+++ b/tests/unit/cli_ctl/test_cli_coverage.py
@@ -27,5 +27,31 @@ def test_gate_discovers_route_modules():
gate = _load_gate()
mods = gate.route_modules()
assert len(mods) > 15, f"expected many route modules, found {mods}"
- # frontier_routes was the route module we had to mount; it must be tracked.
+ # frontier_routes + self_mod_routes were the route modules we had to mount;
+ # they must be tracked.
assert "frontier_routes" in mods
+ assert "self_mod_routes" in mods
+
+
+def test_all_route_modules_are_tagged():
+ gate = _load_gate()
+ untagged = gate.untagged_modules()
+ assert untagged == [], (
+ f"route modules with an untagged APIRouter (land in `default` group): {untagged}"
+ )
+
+
+def test_tag_detection_handles_nested_parens():
+ gate = _load_gate()
+ src = (
+ 'tagged = APIRouter(prefix="/api/x", tags=["x"], '
+ "dependencies=[Depends(require_key)])\n"
+ 'untagged = APIRouter(prefix="/api/y")\n'
+ )
+ blocks = gate._apirouter_arg_blocks(src)
+ assert len(blocks) == 2
+ # Balanced-paren scan keeps the nested Depends(...) call inside the first
+ # block; a naive `.*?\)` regex would have truncated it there and lost tags=.
+ assert "tags=" in blocks[0]
+ assert "Depends(require_key)" in blocks[0]
+ assert "tags=" not in blocks[1]
diff --git a/tests/unit/cli_ctl/test_commands_wave23.py b/tests/unit/cli_ctl/test_commands_wave23.py
index 8f5af334bc..b5f02a10e8 100644
--- a/tests/unit/cli_ctl/test_commands_wave23.py
+++ b/tests/unit/cli_ctl/test_commands_wave23.py
@@ -1,5 +1,6 @@
"""Tests for the Wave 2-3 curated domains (skills, outputs, board, workflows,
-conductor, contacts, telephony, marketplace, mcps, docs, frontier)."""
+conductor, contacts, telephony, marketplace, mcps, docs, frontier) plus the
+later friends / socials / clis groups."""
from __future__ import annotations
from typer.testing import CliRunner
@@ -163,3 +164,79 @@ def test_frontier_ack_proceeds(capture_api):
res = runner.invoke(app, ["frontier", "ack"])
assert res.exit_code == 0
assert _last(capture_api)["path"] == "/api/frontier/ack"
+
+
+# --- friends --------------------------------------------------------------
+def test_friends_list(capture_api):
+ runner.invoke(app, ["friends", "list"])
+ assert _last(capture_api)["path"] == "/api/friends"
+
+
+def test_friends_add(capture_api):
+ res = runner.invoke(app, ["friends", "add", "--json-body", '{"display_name": "Bob"}'])
+ assert res.exit_code == 0
+ call = _last(capture_api)
+ assert call["method"] == "POST" and call["body"] == {"display_name": "Bob"}
+
+
+def test_friends_delete_requires_yes(capture_api):
+ assert runner.invoke(app, ["friends", "delete", "f1"]).exit_code == 1
+ assert capture_api["calls"] == []
+
+
+def test_friends_message_requires_yes(capture_api):
+ # Sending a real outbound DM is marked dangerous=True → fails closed.
+ assert runner.invoke(app, ["friends", "message", "f1", "--text", "hi"]).exit_code == 1
+ assert capture_api["calls"] == []
+
+
+def test_friends_message_with_yes(capture_api):
+ res = runner.invoke(app, ["friends", "message", "f1", "--text", "hi", "--yes"])
+ assert res.exit_code == 0
+ call = _last(capture_api)
+ assert call["method"] == "POST" and call["path"] == "/api/friends/f1/messages"
+ assert call["body"] == {"text": "hi"}
+
+
+# --- socials ---------------------------------------------------------------
+def test_socials_list(capture_api):
+ runner.invoke(app, ["socials", "list"])
+ assert _last(capture_api)["path"] == "/api/socials"
+
+
+def test_socials_add(capture_api):
+ res = runner.invoke(
+ app, ["socials", "add", "--json-body", '{"platform": "x", "label": "X", "url": "u"}']
+ )
+ assert res.exit_code == 0
+ assert _last(capture_api)["method"] == "POST"
+
+
+def test_socials_delete_requires_yes(capture_api):
+ assert runner.invoke(app, ["socials", "delete", "1"]).exit_code == 1
+ assert capture_api["calls"] == []
+
+
+# --- clis ------------------------------------------------------------------
+def test_clis_list(capture_api):
+ runner.invoke(app, ["clis", "list"])
+ assert _last(capture_api)["path"] == "/api/clis"
+
+
+def test_clis_show(capture_api):
+ runner.invoke(app, ["clis", "show", "gcloud"])
+ assert _last(capture_api)["path"] == "/api/clis/gcloud"
+
+
+def test_clis_install_proceeds(capture_api):
+ # POST install is a reversible, server-audited mutation → proceeds, no --yes.
+ res = runner.invoke(app, ["clis", "install", "gcloud", "--method", "winget"])
+ assert res.exit_code == 0
+ call = _last(capture_api)
+ assert call["method"] == "POST" and call["path"] == "/api/clis/gcloud/install"
+ assert call["body"] == {"method": "winget"}
+
+
+def test_clis_usage_stats(capture_api):
+ runner.invoke(app, ["clis", "usage-stats", "gcloud"])
+ assert _last(capture_api)["path"] == "/api/clis/gcloud/usage/stats"
diff --git a/tests/unit/core/test_capabilities.py b/tests/unit/core/test_capabilities.py
index 62ef554886..effdc8632c 100644
--- a/tests/unit/core/test_capabilities.py
+++ b/tests/unit/core/test_capabilities.py
@@ -315,7 +315,8 @@ class TestSeedRegistry:
for tool in (
"tool.run-shell",
"tool.screen-snapshot",
- "tool.dispatch-to-harness",
+ # NB: tool.dispatch-to-harness removed 2026-06-28 (no longer an
+ # LLM-visible router tool — phantom-openclaw routing fix).
"tool.multi-spawn",
"tool.spawn-worker",
"tool.dispatch-with-review",
@@ -328,6 +329,11 @@ class TestSeedRegistry:
):
assert tool in ids, f"{tool!r} missing from seed"
+ def test_dispatch_to_harness_capability_removed(self) -> None:
+ """The dead dispatch-to-harness capability must not reappear (2026-06-28)."""
+ ids = {c.id for c in self.reg.all()}
+ assert "tool.dispatch-to-harness" not in ids
+
def test_local_actions_present(self) -> None:
ids = {c.id for c in self.reg.all()}
for la in (
@@ -341,21 +347,38 @@ class TestSeedRegistry:
def test_harness_adapters_present(self) -> None:
ids = {c.id for c in self.reg.all()}
+ # NB: harness.openclaw removed 2026-06-28 — OpenClaw is not a registered
+ # harness (Welle-4 removal); seeding it advertised a phantom vehicle.
for ha in (
- "harness.openclaw",
"harness.mcp-remote",
"harness.computer-use",
"harness.python-script",
"harness.open-interpreter",
):
assert ha in ids, f"{ha!r} missing from seed"
+ assert "harness.openclaw" not in ids
+
+ def test_no_capability_advertises_openclaw(self) -> None:
+ """No seeded capability may advertise the phantom 'openclaw' vehicle.
+
+ OpenClaw is unregistered (Welle-4 removal). Advertising it in a router
+ tool's verbs/objects/description mis-routed "start a subagent" turns
+ toward a vehicle that cannot run (forensic 2026-06-28). Heavy sub-agent
+ work is tool.spawn-worker.
+ """
+ for cap in self.reg.all():
+ haystack = " ".join(
+ (cap.description, *cap.verbs, *cap.objects)
+ ).lower()
+ assert "openclaw" not in haystack, (
+ f"capability {cap.id!r} still advertises 'openclaw'"
+ )
def test_requires_evidence_true_for_action_tools(self) -> None:
"""Action tools must have requires_evidence=True."""
action_ids = {
"tool.run-shell",
"tool.screen-snapshot",
- "tool.dispatch-to-harness",
"tool.multi-spawn",
"tool.spawn-worker",
"tool.dispatch-with-review",
diff --git a/tests/unit/core/test_config_writer_discord.py b/tests/unit/core/test_config_writer_discord.py
index 8deb5770ba..d61ef888bc 100644
--- a/tests/unit/core/test_config_writer_discord.py
+++ b/tests/unit/core/test_config_writer_discord.py
@@ -42,9 +42,11 @@ def test_add_allowed_user_id_is_idempotent_and_appends(tmp_path):
assert data["integrations"]["discord"]["allowed_user_ids"] == [12345, 67890]
-def test_raises_when_config_missing(tmp_path):
- with pytest.raises(FileNotFoundError):
- add_discord_allowed_user_id(1, path=tmp_path / "absent.toml")
+def test_creates_config_when_missing(tmp_path):
+ # M1 (headless VPS): in-app writers create the config if absent, not raise.
+ p = tmp_path / "absent.toml"
+ add_discord_allowed_user_id(1, path=p)
+ assert p.exists()
def test_set_discord_enabled_creates_nested_table(tmp_path):
@@ -83,6 +85,7 @@ def test_set_discord_pairing_writes_flag(tmp_path):
assert data["integrations"]["discord"]["enabled"] is True
-def test_set_discord_enabled_raises_when_config_missing(tmp_path):
- with pytest.raises(FileNotFoundError):
- set_discord_enabled(True, path=tmp_path / "absent.toml")
+def test_set_discord_enabled_creates_config_when_missing(tmp_path):
+ p = tmp_path / "absent.toml"
+ set_discord_enabled(True, path=p)
+ assert p.exists()
diff --git a/tests/unit/core/test_config_writer_headless_create.py b/tests/unit/core/test_config_writer_headless_create.py
new file mode 100644
index 0000000000..fdc0ced201
--- /dev/null
+++ b/tests/unit/core/test_config_writer_headless_create.py
@@ -0,0 +1,35 @@
+"""M1 (open-source AP-22 / headless VPS): in-app config writers (channel toggles,
+provider switches, wiki curator) defaulted to /app/jarvis.toml and RAISED
+FileNotFoundError when it was absent — so connecting a channel / switching a
+provider in the UI 500'd on a fresh headless container. They must instead resolve
+the active config path (JARVIS_CONFIG) and create it if missing.
+"""
+from __future__ import annotations
+
+import tomllib
+
+from jarvis.core import config_writer as cw
+
+
+def test_set_telegram_enabled_creates_missing_config(tmp_path):
+ p = tmp_path / "sub" / "jarvis.toml" # neither file nor parent exists
+ cw.set_telegram_enabled(True, path=p)
+ assert p.exists()
+ data = tomllib.loads(p.read_text(encoding="utf-8"))
+ assert data["integrations"]["telegram"]["enabled"] is True
+
+
+def test_add_telegram_allowed_user_creates_missing_config(tmp_path):
+ p = tmp_path / "jarvis.toml"
+ cw.add_telegram_allowed_user_id(7911329168, path=p)
+ assert p.exists()
+ data = tomllib.loads(p.read_text(encoding="utf-8"))
+ assert 7911329168 in data["integrations"]["telegram"]["allowed_user_ids"]
+
+
+def test_set_discord_enabled_creates_missing_config(tmp_path):
+ p = tmp_path / "jarvis.toml"
+ cw.set_discord_enabled(True, path=p)
+ assert p.exists()
+ data = tomllib.loads(p.read_text(encoding="utf-8"))
+ assert data["integrations"]["discord"]["enabled"] is True
diff --git a/tests/unit/core/test_config_writer_overlay.py b/tests/unit/core/test_config_writer_overlay.py
index e0b7d20821..d132081590 100644
--- a/tests/unit/core/test_config_writer_overlay.py
+++ b/tests/unit/core/test_config_writer_overlay.py
@@ -9,9 +9,9 @@ from jarvis.core import config_writer
def test_set_overlay_style_round_trip(tmp_path):
cfg = tmp_path / "jarvis.toml"
cfg.write_text('[ui]\norb_style = "mascot"\n', encoding="utf-8")
- config_writer.set_overlay_style("whisper_bar", path=cfg)
+ config_writer.set_overlay_style("jarvis_bar", path=cfg)
data = tomllib.loads(cfg.read_text(encoding="utf-8"))
- assert data["ui"]["orb_style"] == "whisper_bar"
+ assert data["ui"]["orb_style"] == "jarvis_bar"
def test_set_overlay_style_creates_section_and_preserves_siblings(tmp_path):
diff --git a/tests/unit/core/test_config_writer_taskbar.py b/tests/unit/core/test_config_writer_taskbar.py
index b4ad276bb2..79df9251dd 100644
--- a/tests/unit/core/test_config_writer_taskbar.py
+++ b/tests/unit/core/test_config_writer_taskbar.py
@@ -17,16 +17,16 @@ def test_ducking_config_defaults():
def test_set_mute_music_round_trip(tmp_path):
cfg = tmp_path / "jarvis.toml"
- cfg.write_text('[ui]\norb_style = "whisper_bar"\n', encoding="utf-8")
+ cfg.write_text('[ui]\norb_style = "jarvis_bar"\n', encoding="utf-8")
config_writer.set_mute_music(True, path=cfg)
data = tomllib.loads(cfg.read_text(encoding="utf-8"))
assert data["ducking"]["enabled"] is True
- assert data["ui"]["orb_style"] == "whisper_bar" # sibling preserved
+ assert data["ui"]["orb_style"] == "jarvis_bar" # sibling preserved
def test_set_bar_persistent_round_trip(tmp_path):
cfg = tmp_path / "jarvis.toml"
- cfg.write_text('[ui]\norb_style = "whisper_bar"\n', encoding="utf-8")
+ cfg.write_text('[ui]\norb_style = "jarvis_bar"\n', encoding="utf-8")
config_writer.set_bar_persistent(False, path=cfg)
data = tomllib.loads(cfg.read_text(encoding="utf-8"))
assert data["ui"]["bar_persistent"] is False
diff --git a/tests/unit/core/test_config_writer_telegram.py b/tests/unit/core/test_config_writer_telegram.py
index b6140462d8..45b7daa543 100644
--- a/tests/unit/core/test_config_writer_telegram.py
+++ b/tests/unit/core/test_config_writer_telegram.py
@@ -43,9 +43,11 @@ def test_toggles_existing_flag_and_preserves_siblings(tmp_path):
assert data["integrations"]["telegram"]["chat_id"] == "123"
-def test_raises_when_config_missing(tmp_path):
- with pytest.raises(FileNotFoundError):
- set_telegram_enabled(True, path=tmp_path / "absent.toml")
+def test_creates_config_when_missing(tmp_path):
+ # M1 (headless VPS): in-app writers create the config if absent, not raise.
+ p = tmp_path / "absent.toml"
+ set_telegram_enabled(True, path=p)
+ assert p.exists()
def test_add_allowed_user_id_creates_list(tmp_path):
diff --git a/tests/unit/core/test_config_writer_tts_stt_model.py b/tests/unit/core/test_config_writer_tts_stt_model.py
index c45089123a..425575f8bf 100644
--- a/tests/unit/core/test_config_writer_tts_stt_model.py
+++ b/tests/unit/core/test_config_writer_tts_stt_model.py
@@ -38,10 +38,31 @@ def test_set_tts_model_writes_model(tmp_path: Path) -> None:
assert 'model = "sonic-2"' in p.read_text(encoding="utf-8")
-def test_set_stt_model_writes_model(tmp_path: Path) -> None:
+def test_set_stt_model_writes_all_three_layers(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The STT model picker writes TOML + config-soll + the JARVIS__STT__MODEL ENV
+ var — a stale single-word ENV override otherwise masks the TOML at boot (the
+ "model is hardcoded, I can't change it" trap, forensic 2026-06-28)."""
p = _toml(tmp_path)
- config_writer.set_stt_model("whisper-large-v3", path=p)
- assert 'model = "whisper-large-v3"' in p.read_text(encoding="utf-8")
+ soll = tmp_path / "config-soll.json"
+ soll.write_text('{"stt": {"model": "distil-large-v3"}}', encoding="utf-8")
+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: soll)
+ env_calls: list[tuple[str, str]] = []
+ monkeypatch.setattr(
+ config_writer, "_set_user_env_var", lambda n, v: env_calls.append((n, v))
+ )
+
+ config_writer.set_stt_model("large-v3-turbo", path=p)
+
+ # Layer 1: TOML.
+ assert 'model = "large-v3-turbo"' in p.read_text(encoding="utf-8")
+ # Layer 2: config-soll.json.
+ import json
+
+ assert json.loads(soll.read_text(encoding="utf-8"))["stt"]["model"] == "large-v3-turbo"
+ # Layer 3: the User-scope ENV var that overrides TOML at boot.
+ assert env_calls == [("JARVIS__STT__MODEL", "large-v3-turbo")]
def test_set_tts_cartesia_model_writes_subtable(tmp_path: Path) -> None:
@@ -58,9 +79,9 @@ def test_set_tts_cartesia_model_writes_subtable(tmp_path: Path) -> None:
assert data["tts"]["cartesia"]["model_id"] == "sonic-2"
-def test_writers_raise_when_config_missing(tmp_path: Path) -> None:
+def test_writers_create_config_when_missing(tmp_path: Path) -> None:
+ # M1 (headless VPS): provider-switch writers create the config if absent.
missing = tmp_path / "nope.toml"
- with pytest.raises(FileNotFoundError):
- config_writer.set_tts_voice("Kore", path=missing)
- with pytest.raises(FileNotFoundError):
- config_writer.set_stt_model("whisper-large-v3", path=missing)
+ config_writer.set_tts_voice("Kore", path=missing)
+ assert missing.exists()
+ config_writer.set_stt_model("whisper-large-v3", path=missing)
diff --git a/tests/unit/core/test_ensure_project_root_cwd.py b/tests/unit/core/test_ensure_project_root_cwd.py
index 75b4473c82..7fd713d4a4 100644
--- a/tests/unit/core/test_ensure_project_root_cwd.py
+++ b/tests/unit/core/test_ensure_project_root_cwd.py
@@ -43,7 +43,7 @@ def test_ensure_project_root_cwd_adds_root_to_sys_path(monkeypatch, tmp_path):
``sys.path``. ``python -m`` seeds ``sys.path[0]`` from the *start-time* CWD;
a later ``os.chdir`` does NOT fix it. A manual start / restart-app inheriting
the user home therefore left ``ui`` unimportable, and the on-screen overlay
- (whisper-bar) silently failed to start ("No module named 'ui'"). Pinning the
+ (jarvis-bar) silently failed to start ("No module named 'ui'"). Pinning the
CWD is not enough — the root must be put on the import path too.
"""
root = str(config.PROJECT_ROOT)
diff --git a/tests/unit/core/test_get_secret_env_fallback.py b/tests/unit/core/test_get_secret_env_fallback.py
new file mode 100644
index 0000000000..9187d8c5fd
--- /dev/null
+++ b/tests/unit/core/test_get_secret_env_fallback.py
@@ -0,0 +1,38 @@
+"""H2 (open-source AP-22 / headless VPS): the documented keyring → ENV → .env
+hierarchy must hold for EVERY credential slot, not only brain providers whose
+callers happen to pass an explicit env var. A headless user sets GROQ_API_KEY in
+the environment (no OS keyring on python:3.11-slim) and the STT/TTS/integration
+slots must read it — so get_secret derives the env var from the slot name when
+the caller passes none.
+"""
+from __future__ import annotations
+
+import keyring
+
+from jarvis.core.config import get_secret
+
+
+def test_get_secret_derives_env_fallback_from_key(monkeypatch):
+ monkeypatch.setattr(keyring, "get_password", lambda *a, **k: None)
+ monkeypatch.setenv("GROQ_API_KEY", "gsk-from-env")
+ assert get_secret("groq_api_key") == "gsk-from-env"
+
+
+def test_explicit_env_fallback_still_wins(monkeypatch):
+ monkeypatch.setattr(keyring, "get_password", lambda *a, **k: None)
+ monkeypatch.setenv("MY_EXPLICIT_VAR", "explicit")
+ assert get_secret("some_slot", env_fallback="MY_EXPLICIT_VAR") == "explicit"
+
+
+def test_keyring_value_wins_over_env(monkeypatch):
+ monkeypatch.setattr(
+ keyring, "get_password", lambda svc, k: "kr-value" if k == "x_api_key" else None
+ )
+ monkeypatch.setenv("X_API_KEY", "env-value")
+ assert get_secret("x_api_key") == "kr-value"
+
+
+def test_absent_everywhere_returns_none(monkeypatch):
+ monkeypatch.setattr(keyring, "get_password", lambda *a, **k: None)
+ monkeypatch.delenv("TOTALLY_UNSET_SLOT", raising=False)
+ assert get_secret("totally_unset_slot") is None
diff --git a/tests/unit/core/test_headless_keyring_fallback.py b/tests/unit/core/test_headless_keyring_fallback.py
new file mode 100644
index 0000000000..fe40cc0da5
--- /dev/null
+++ b/tests/unit/core/test_headless_keyring_fallback.py
@@ -0,0 +1,64 @@
+"""C1 (open-source AP-22 / headless VPS): on python:3.11-slim there is no OS
+Secret Service, so the platform keyring resolves to fail.Keyring and every in-app
+key save / channel-connect / plugin-connect would raise → the whole API-Keys
+section is unusable. Jarvis must fall back to a local 0600 file store so a fresh
+VPS downloader can paste a key in the UI and have it persist.
+"""
+from __future__ import annotations
+
+import sys
+
+import jarvis.core.config as cfg
+
+
+def test_file_cred_store_roundtrip(tmp_path):
+ store = cfg._FileCredStore(path=tmp_path / "creds.json")
+ assert store.get("personal-jarvis", "groq_api_key") is None
+ store.set("personal-jarvis", "groq_api_key", "gsk-secret")
+ assert store.get("personal-jarvis", "groq_api_key") == "gsk-secret"
+ store.delete("personal-jarvis", "groq_api_key")
+ assert store.get("personal-jarvis", "groq_api_key") is None
+
+
+def test_file_cred_store_is_0600_on_posix(tmp_path):
+ p = tmp_path / "creds.json"
+ cfg._FileCredStore(path=p).set("svc", "k", "v")
+ if sys.platform != "win32":
+ assert (p.stat().st_mode & 0o777) == 0o600
+
+
+def test_ensure_keyring_backend_registers_file_store_when_os_keyring_dead(monkeypatch, tmp_path):
+ import keyring
+ from keyring.backends import fail
+
+ monkeypatch.setattr(keyring, "get_keyring", lambda: fail.Keyring())
+ captured: dict = {}
+ monkeypatch.setattr(keyring, "set_keyring", lambda kr: captured.__setitem__("kr", kr))
+ monkeypatch.setattr(cfg, "DATA_DIR", tmp_path)
+ monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", False, raising=False)
+
+ cfg._ensure_keyring_backend()
+
+ kr = captured.get("kr")
+ assert kr is not None, "a file backend must be registered when the OS keyring is dead"
+ # The registered backend must actually store + retrieve.
+ kr.set_password("personal-jarvis", "telegram_bot_token", "123:abc")
+ assert kr.get_password("personal-jarvis", "telegram_bot_token") == "123:abc"
+
+
+def test_ensure_keyring_backend_leaves_working_os_keyring_untouched(monkeypatch):
+ import keyring
+
+ class _RealishBackend:
+ def get_password(self, s, u): return None
+ def set_password(self, s, u, p): return None
+ def delete_password(self, s, u): return None
+
+ monkeypatch.setattr(keyring, "get_keyring", lambda: _RealishBackend())
+ called: dict = {}
+ monkeypatch.setattr(keyring, "set_keyring", lambda kr: called.__setitem__("kr", kr))
+ monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", False, raising=False)
+
+ cfg._ensure_keyring_backend()
+
+ assert "kr" not in called, "a working OS keyring must NOT be replaced by the file fallback"
diff --git a/tests/unit/core/test_runtime_refs_chat_abort.py b/tests/unit/core/test_runtime_refs_chat_abort.py
index ce3d0e20e7..1117cdf83e 100644
--- a/tests/unit/core/test_runtime_refs_chat_abort.py
+++ b/tests/unit/core/test_runtime_refs_chat_abort.py
@@ -1,6 +1,6 @@
"""The bar's X must abort an in-flight CHAT turn, not just a voice turn.
-Live bug 2026-06-19: clicking the whisper-bar X (``request_hangup``) while a
+Live bug 2026-06-19: clicking the jarvis-bar X (``request_hangup``) while a
chat-originated brain turn was THINKING did nothing — the chat dispatcher
(``desktop_app._on_user_message``) ran a bare ``await generate(...)`` with no
task handle and never observed the voice pipeline's ``_hangup_event``. The
diff --git a/tests/unit/core/test_ui_config_bar.py b/tests/unit/core/test_ui_config_bar.py
index 502969078d..74282e102c 100644
--- a/tests/unit/core/test_ui_config_bar.py
+++ b/tests/unit/core/test_ui_config_bar.py
@@ -1,12 +1,12 @@
-"""UIConfig selects the whisper bar by default and carries its flags."""
+"""UIConfig selects the jarvis bar by default and carries its flags."""
from __future__ import annotations
from jarvis.core.config import UIConfig
-def test_defaults_select_whisper_bar():
+def test_defaults_select_jarvis_bar():
c = UIConfig()
- assert c.orb_style == "whisper_bar"
+ assert c.orb_style == "jarvis_bar"
assert c.bar_persistent is True
assert c.bar_accent == "#e7c46e"
diff --git a/tests/unit/diagnostics/test_doctor.py b/tests/unit/diagnostics/test_doctor.py
new file mode 100644
index 0000000000..243b34d63b
--- /dev/null
+++ b/tests/unit/diagnostics/test_doctor.py
@@ -0,0 +1,113 @@
+"""Tests for the completeness self-check (``jarvis/diagnostics/doctor.py``).
+
+The doctor is the generalised defence against the phantom-openclaw class of bug
+(2026-06-28): a name advertised to the brain that resolves to no registered
+backend. These tests pin the two highest-value checks — phantom router tools and
+inert harness config — plus the isolation guarantee that one crashing probe never
+blinds the rest of the report.
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from jarvis.diagnostics import doctor
+from jarvis.diagnostics.doctor import (
+ check_brain_provider,
+ check_harness_config,
+ check_router_tools,
+ has_failures,
+ run_doctor,
+)
+
+
+def test_router_tools_ok_with_real_registry() -> None:
+ """The shipped ROUTER_TOOLS set must have NO phantom — every name resolves.
+
+ This is the regression guard for the original bug: a router tool advertised
+ but not registered. After the 2026-06-28 fix this is clean.
+ """
+ findings = check_router_tools()
+ assert len(findings) == 1
+ assert findings[0].status == "ok", findings[0].message
+
+
+def test_router_tools_detects_phantom(monkeypatch) -> None:
+ """A router tool with no registered entry-point is flagged as a phantom."""
+ # Simulate a registry where jarvis.tool entry-points are empty → every
+ # ROUTER_TOOLS name that is not a self-mod tool becomes a phantom.
+ monkeypatch.setattr(doctor, "entry_points", lambda *a, **k: [])
+ findings = check_router_tools()
+ assert len(findings) == 1
+ assert findings[0].status == "fail"
+ assert "advertised but not registered" in findings[0].message
+
+
+def test_harness_config_flags_inert_openclaw() -> None:
+ """[harness.openclaw].enabled=true without registration → warn (dead config)."""
+ config = SimpleNamespace(
+ harness=SimpleNamespace(openclaw=SimpleNamespace(enabled=True)),
+ )
+ findings = check_harness_config(config)
+ warns = [f for f in findings if f.status == "warn"]
+ assert warns, "inert openclaw config was not flagged"
+ assert "inert" in warns[0].message
+
+
+def test_harness_config_silent_when_disabled() -> None:
+ config = SimpleNamespace(
+ harness=SimpleNamespace(openclaw=SimpleNamespace(enabled=False)),
+ )
+ findings = check_harness_config(config)
+ assert not any(f.status == "warn" for f in findings)
+
+
+def test_harness_config_silent_when_no_block() -> None:
+ config = SimpleNamespace(harness=SimpleNamespace(openclaw=None))
+ findings = check_harness_config(config)
+ assert not any(f.status == "warn" for f in findings)
+
+
+def test_brain_provider_fail_when_empty() -> None:
+ config = SimpleNamespace(brain=SimpleNamespace(primary=""))
+ findings = check_brain_provider(config)
+ assert findings[0].status == "fail"
+
+
+def test_brain_provider_info_when_set() -> None:
+ config = SimpleNamespace(brain=SimpleNamespace(primary="gemini"))
+ findings = check_brain_provider(config)
+ assert findings[0].status == "info"
+ assert "gemini" in findings[0].message
+
+
+def test_run_doctor_aggregates_all_categories() -> None:
+ config = SimpleNamespace(
+ harness=SimpleNamespace(openclaw=None),
+ brain=SimpleNamespace(primary="gemini"),
+ )
+ findings = run_doctor(config)
+ cats = {f.category for f in findings}
+ assert {
+ "router-tools",
+ "harness-config",
+ "subagent-backend",
+ "brain-provider",
+ } <= cats
+
+
+def test_run_doctor_isolates_a_crashing_check(monkeypatch) -> None:
+ """A crashing probe must not blind the rest of the report."""
+ def boom():
+ raise RuntimeError("kaboom")
+
+ monkeypatch.setattr(doctor, "check_router_tools", boom)
+ config = SimpleNamespace(
+ harness=SimpleNamespace(openclaw=None),
+ brain=SimpleNamespace(primary="gemini"),
+ )
+ findings = run_doctor(config)
+ # The crashing check produced a fail finding for its category...
+ assert any(f.category == "router-tools" and f.status == "fail" for f in findings)
+ # ...and the other checks still ran.
+ assert any(f.category == "brain-provider" for f in findings)
+ assert has_failures(findings)
diff --git a/tests/unit/google_cli/test_auth_service.py b/tests/unit/google_cli/test_auth_service.py
index 71047e6930..d6e691f809 100644
--- a/tests/unit/google_cli/test_auth_service.py
+++ b/tests/unit/google_cli/test_auth_service.py
@@ -83,7 +83,7 @@ def test_status_not_installed(monkeypatch):
def test_status_installed_but_logged_out(tmp_path, monkeypatch):
gem = tmp_path / ".gemini"
- gem.mkdir() # no oauth_creds.json
+ gem.mkdir() # no oauth_creds.json, no agy token
monkeypatch.setenv("GEMINI_HOME", str(gem))
svc = GoogleCliAuthService()
svc._resolve = lambda: GoogleCli( # type: ignore[method-assign]
@@ -94,6 +94,63 @@ def test_status_installed_but_logged_out(tmp_path, monkeypatch):
assert st.cli_kind == "agy"
+def _seed_agy_home(tmp_path):
+ """A real-world agy login: the OAuth token lives under ``antigravity-cli/``,
+ NOT as ``oauth_creds.json`` (verified live 2026-06-26 with agy 1.0.12)."""
+ gem = tmp_path / ".gemini"
+ (gem / "antigravity-cli").mkdir(parents=True)
+ (gem / "antigravity-cli" / "antigravity-oauth-token").write_text(
+ json.dumps({"auth_method": "personal", "token": {"access_token": "x"}})
+ )
+ # agy shares ~/.gemini for the account + the (clean) selected-type marker.
+ (gem / "settings.json").write_text(
+ json.dumps({"security": {"auth": {"selectedType": "oauth-personal"}}})
+ )
+ (gem / "google_accounts.json").write_text(json.dumps({"active": "[email protected]"}))
+ return gem
+
+
+def test_status_connected_via_agy_oauth_token(tmp_path, monkeypatch):
+ # The reported bug: agy is logged in (token under antigravity-cli/) but the
+ # status read the wrong path (~/.gemini/oauth_creds.json) and showed
+ # "Installed but not logged in". It must now report connected.
+ gem = _seed_agy_home(tmp_path)
+ monkeypatch.setenv("GEMINI_HOME", str(gem))
+ svc = GoogleCliAuthService()
+ svc._resolve = lambda: GoogleCli( # type: ignore[method-assign]
+ kind="agy", argv_prefix=["agy.exe"], version="1.0.12"
+ )
+ st = svc.status()
+ assert st.installed and st.connected
+ assert st.mode == "oauth-personal"
+ assert st.cli_kind == "agy"
+ assert st.user_email == "[email protected]"
+
+
+def test_status_agy_empty_token_file_is_not_connected(tmp_path, monkeypatch):
+ # A zero-byte token file (interrupted login) must not read as connected.
+ gem = tmp_path / ".gemini"
+ (gem / "antigravity-cli").mkdir(parents=True)
+ (gem / "antigravity-cli" / "antigravity-oauth-token").write_text("")
+ monkeypatch.setenv("GEMINI_HOME", str(gem))
+ svc = GoogleCliAuthService()
+ svc._resolve = lambda: GoogleCli(kind="agy", argv_prefix=["agy"]) # type: ignore[method-assign]
+ assert not svc.status().connected
+
+
+def test_logout_removes_agy_token(tmp_path, monkeypatch):
+ # Disconnect must clear the agy token too, not only oauth_creds.json — else
+ # the Disconnect button is a no-op for an agy login.
+ gem = _seed_agy_home(tmp_path)
+ monkeypatch.setenv("GEMINI_HOME", str(gem))
+ svc = GoogleCliAuthService()
+ svc._resolve = lambda: GoogleCli(kind="agy", argv_prefix=["agy.exe"]) # type: ignore[method-assign]
+ ok, err = svc.logout_blocking()
+ assert ok and err is None
+ assert not (gem / "antigravity-cli" / "antigravity-oauth-token").is_file()
+ assert not svc.status().connected
+
+
def test_start_login_uses_bare_agy_not_login_subcommand(monkeypatch):
# agy has NO `login` subcommand (verified 2026-06-21: `agy login` hangs
# forever). The login is an interactive bare run, so start_login must NOT
diff --git a/tests/unit/google_cli/test_isolated_home.py b/tests/unit/google_cli/test_isolated_home.py
new file mode 100644
index 0000000000..cc1a8d46cb
--- /dev/null
+++ b/tests/unit/google_cli/test_isolated_home.py
@@ -0,0 +1,102 @@
+"""Isolated CLI-home builder for the agy/gemini worker.
+
+The worker redirects HOME to a hook/mcp-free isolated home and mirrors only the
+OAuth *login material* into it. Regression focus (2026-06-26): agy stores its
+token under ``antigravity-cli/antigravity-oauth-token``, NOT as
+``oauth_creds.json`` — mirroring only the latter left the worker logged out
+under the redirected HOME even though the user was signed in.
+"""
+from __future__ import annotations
+
+import json
+import os
+
+from jarvis.google_cli.isolated_home import ensure_isolated_home
+
+
+def _iso(real_dir, dest_root, model="gemini-3.5-flash"):
+ return ensure_isolated_home(real_dir=str(real_dir), dest_root=str(dest_root), model=model)
+
+
+def test_mirrors_gemini_oauth_creds(tmp_path):
+ real = tmp_path / "real" / ".gemini"
+ real.mkdir(parents=True)
+ (real / "oauth_creds.json").write_text(json.dumps({"access_token": "x"}))
+ (real / "google_accounts.json").write_text(json.dumps({"active": "[email protected]"}))
+ dest = tmp_path / "iso"
+ out = _iso(real, dest)
+ assert out == str(dest)
+ assert (dest / ".gemini" / "oauth_creds.json").is_file()
+ assert (dest / ".gemini" / "google_accounts.json").is_file()
+ # settings.json is rewritten minimal (no hooks / mcpServers).
+ settings = json.loads((dest / ".gemini" / "settings.json").read_text())
+ assert "hooks" not in settings and "mcpServers" not in settings
+
+
+def test_mirrors_agy_token_under_subdir(tmp_path):
+ # The bug: agy's real login lives under antigravity-cli/, so the worker home
+ # must mirror it there, preserving the subdir, or agy runs logged out.
+ real = tmp_path / "real" / ".gemini"
+ (real / "antigravity-cli").mkdir(parents=True)
+ (real / "antigravity-cli" / "antigravity-oauth-token").write_text(
+ json.dumps({"auth_method": "personal", "token": {"access_token": "x"}})
+ )
+ (real / "antigravity-cli" / "installation_id").write_text("abc123")
+ (real / "google_accounts.json").write_text(json.dumps({"active": "[email protected]"}))
+ dest = tmp_path / "iso"
+ _iso(real, dest)
+ mirrored = dest / ".gemini" / "antigravity-cli" / "antigravity-oauth-token"
+ assert mirrored.is_file()
+ assert json.loads(mirrored.read_text())["auth_method"] == "personal"
+
+
+def test_logout_drops_mirrored_agy_token(tmp_path):
+ # First a logged-in mirror, then the real login vanishes (logout) → the
+ # isolated home must drop the stale agy token so agy logs out there too.
+ real = tmp_path / "real" / ".gemini"
+ (real / "antigravity-cli").mkdir(parents=True)
+ token = real / "antigravity-cli" / "antigravity-oauth-token"
+ token.write_text(json.dumps({"token": {"access_token": "x"}}))
+ dest = tmp_path / "iso"
+ _iso(real, dest)
+ assert (dest / ".gemini" / "antigravity-cli" / "antigravity-oauth-token").is_file()
+
+ token.unlink() # the user logged out
+ _iso(real, dest)
+ assert not (dest / ".gemini" / "antigravity-cli" / "antigravity-oauth-token").is_file()
+
+
+def test_empty_token_is_not_a_login(tmp_path):
+ real = tmp_path / "real" / ".gemini"
+ (real / "antigravity-cli").mkdir(parents=True)
+ (real / "antigravity-cli" / "antigravity-oauth-token").write_text("") # 0 bytes
+ dest = tmp_path / "iso"
+ _iso(real, dest)
+ assert not (dest / ".gemini" / "antigravity-cli" / "antigravity-oauth-token").is_file()
+
+
+def test_resync_on_token_refresh(tmp_path):
+ # A fresh login (token mtime changes) must re-copy; an unchanged token must
+ # not clobber agy's in-home refreshed token (the marker guards that).
+ real = tmp_path / "real" / ".gemini"
+ real.mkdir(parents=True)
+ creds = real / "oauth_creds.json"
+ creds.write_text(json.dumps({"access_token": "v1"}))
+ dest = tmp_path / "iso"
+ _iso(real, dest)
+ mirrored = dest / ".gemini" / "oauth_creds.json"
+ assert json.loads(mirrored.read_text())["access_token"] == "v1"
+
+ # Simulate agy refreshing its own copy inside the home; an unchanged source
+ # mtime must NOT overwrite it.
+ mirrored.write_text(json.dumps({"access_token": "in-home-refreshed"}))
+ os.utime(creds, (creds.stat().st_atime, creds.stat().st_mtime)) # mtime unchanged
+ _iso(real, dest)
+ assert json.loads(mirrored.read_text())["access_token"] == "in-home-refreshed"
+
+ # A real new login (newer mtime) re-syncs.
+ creds.write_text(json.dumps({"access_token": "v2"}))
+ new_mtime = creds.stat().st_mtime + 10
+ os.utime(creds, (new_mtime, new_mtime))
+ _iso(real, dest)
+ assert json.loads(mirrored.read_text())["access_token"] == "v2"
diff --git a/tests/unit/harness/test_cu_awareness_and_switch.py b/tests/unit/harness/test_cu_awareness_and_switch.py
index 32ed236233..d16c73703d 100644
--- a/tests/unit/harness/test_cu_awareness_and_switch.py
+++ b/tests/unit/harness/test_cu_awareness_and_switch.py
@@ -140,3 +140,124 @@ def test_awareness_line_dedupes_and_caps(monkeypatch):
# capped well below 51 entries; "App 0" appears once despite the duplicate
assert line.count("App 0") == 1
assert line.count(";") < 20
+
+
+# --- 1c + audit #13: switch_window routes through the ToolExecutor ------------
+
+
+class _RecordingExecutor:
+ """Captures execute() calls and returns a pre-set ToolResult-shaped object."""
+
+ def __init__(self, result: object) -> None:
+ self._result = result
+ self.calls: list[tuple[str | None, dict]] = []
+
+ async def execute(self, tool: object, args: dict, *,
+ user_utterance: str = "", trace_id: object = None) -> object:
+ self.calls.append((getattr(tool, "name", None), dict(args)))
+ return self._result
+
+
+class _FakeSwitchTool:
+ name = "switch_window"
+
+
+def _ctx_with_switch(executor: object) -> ComputerUseContext:
+ return ComputerUseContext(
+ vision_engine=None, brain_manager=None,
+ tool_executor=executor, tools={"switch_window": _FakeSwitchTool()},
+ )
+
+
+async def test_execute_switch_window_routes_through_executor():
+ # When the switch_window tool is wired, the action must go through the
+ # ToolExecutor (tier/blacklist/audit parity) with the tool's own arg key.
+ from types import SimpleNamespace
+
+ ex = _RecordingExecutor(
+ SimpleNamespace(success=True, output="Fokus auf Fenster: OBS", error=None)
+ )
+ ok, msg = await _execute_action(
+ {"action": "switch_window", "name": "OBS"}, _ctx_with_switch(ex),
+ trace_id=None, user_goal="x",
+ )
+ assert ok is True
+ assert ex.calls == [("switch_window", {"title_contains": "OBS"})]
+ assert "OBS" in msg
+
+
+async def test_execute_switch_window_executor_failure_is_reported():
+ from types import SimpleNamespace
+
+ ex = _RecordingExecutor(
+ SimpleNamespace(success=False, output=None, error="no window")
+ )
+ ok, msg = await _execute_action(
+ {"action": "switch_window", "name": "Ghost"}, _ctx_with_switch(ex),
+ trace_id=None, user_goal="x",
+ )
+ assert ok is False
+ assert "no window" in msg
+
+
+async def test_execute_switch_window_falls_back_to_inline_without_tool(monkeypatch):
+ # No switch_window tool wired -> graceful inline focus fallback (preserves the
+ # module's degradation contract; the executor path is production-only).
+ monkeypatch.setattr(
+ "jarvis.platform.window_state.focus_window", lambda t: (True, f"inline:{t}")
+ )
+ ok, msg = await _execute_action(
+ {"action": "switch_window", "name": "OBS"}, _ctx(), # _ctx() has tools={}
+ trace_id=None, user_goal="x",
+ )
+ assert ok is True
+ assert "inline:OBS" in msg
+
+
+# --- audit #13: drag routes through the ToolExecutor -------------------------
+
+
+class _FakeDragTool:
+ name = "drag"
+
+
+def _ctx_with_drag(executor: object) -> ComputerUseContext:
+ return ComputerUseContext(
+ vision_engine=None, brain_manager=None,
+ tool_executor=executor, tools={"drag": _FakeDragTool()},
+ )
+
+
+async def test_execute_drag_routes_through_executor():
+ # 0-1000 normalized coords against a 1000x1000 monitor map 1:1 to pixels, so
+ # the executor must receive the resolved pixel endpoints under the tool's keys.
+ from types import SimpleNamespace
+
+ ex = _RecordingExecutor(
+ SimpleNamespace(success=True, output="dragged (100,200)->(300,400)", error=None)
+ )
+ ok, msg = await _execute_action(
+ {"action": "drag", "x": 100, "y": 200, "x2": 300, "y2": 400},
+ _ctx_with_drag(ex),
+ trace_id=None, user_goal="x", monitor_geom=(0, 0, 1000, 1000),
+ )
+ assert ok is True
+ assert ex.calls and ex.calls[0][0] == "drag"
+ sent = ex.calls[0][1]
+ assert (sent["x1"], sent["y1"], sent["x2"], sent["y2"]) == (100, 200, 300, 400)
+
+
+async def test_execute_drag_falls_back_to_inline_without_tool(monkeypatch):
+ # No drag tool wired -> inline _perform_drag fallback (degradation contract).
+ calls: list[tuple] = []
+ monkeypatch.setattr(
+ "jarvis.harness.screenshot_only_loop._perform_drag",
+ lambda x1, y1, x2, y2, d: calls.append((x1, y1, x2, y2)),
+ )
+ ok, _msg = await _execute_action(
+ {"action": "drag", "x": 100, "y": 200, "x2": 300, "y2": 400},
+ _ctx(), # tools={}
+ trace_id=None, user_goal="x", monitor_geom=(0, 0, 1000, 1000),
+ )
+ assert ok is True
+ assert calls == [(100, 200, 300, 400)]
diff --git a/tests/unit/harness/test_cu_click_button.py b/tests/unit/harness/test_cu_click_button.py
new file mode 100644
index 0000000000..939aa8da36
--- /dev/null
+++ b/tests/unit/harness/test_cu_click_button.py
@@ -0,0 +1,99 @@
+"""Right/middle/double-click on the CU click action (audit 🟢 #21).
+
+The actuation tool always supported button + double-click; the CU action never
+exposed them, so the agent could only ever left-single-click (no context menus,
+no double-click-to-open). These pin: the flags are parsed/validated, default to a
+left single-click (purely additive), and thread through to the click dispatch.
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jarvis.harness.screenshot_only_loop import (
+ CULoopError,
+ _dispatch_raw_click,
+ _normalize_click_button,
+ _parse_action,
+ _validate_action_dict,
+)
+
+
+# --- _normalize_click_button (pure) -----------------------------------------
+
+
+def test_defaults_to_left_single_click():
+ obj: dict[str, Any] = {"action": "click", "x": 1, "y": 2}
+ _normalize_click_button(obj)
+ assert obj["button"] == "left"
+ assert obj["double"] is False
+
+
+def test_accepts_right_and_middle():
+ for b in ("right", "RIGHT", "middle"):
+ obj = {"button": b}
+ _normalize_click_button(obj)
+ assert obj["button"] == b.lower()
+
+
+def test_double_flag_is_coerced_to_bool():
+ obj = {"double": 1}
+ _normalize_click_button(obj)
+ assert obj["double"] is True
+
+
+def test_invalid_button_raises():
+ with pytest.raises(CULoopError):
+ _normalize_click_button({"button": "scroll"})
+
+
+# --- validation entry points carry the flags --------------------------------
+
+
+def test_validate_action_dict_carries_button_double():
+ obj = _validate_action_dict(
+ {"action": "click", "x": 5, "y": 6, "button": "right", "double": True}
+ )
+ assert obj["button"] == "right"
+ assert obj["double"] is True
+
+
+def test_parse_action_defaults_left_single():
+ obj = _parse_action('{"action":"click","x":5,"y":6}')
+ assert obj["button"] == "left"
+ assert obj["double"] is False
+
+
+def test_parse_action_rejects_bad_button():
+ with pytest.raises(CULoopError):
+ _parse_action('{"action":"click","x":5,"y":6,"button":"nope"}')
+
+
+# --- dispatch threads the flags to the tool ---------------------------------
+
+
+class _RecordingExecutor:
+ def __init__(self) -> None:
+ self.args: dict[str, Any] | None = None
+
+ async def execute(self, tool: Any, args: dict, *,
+ user_utterance: str = "", trace_id: Any = None) -> Any:
+ self.args = dict(args)
+ return SimpleNamespace(success=True, output="clicked", error=None)
+
+
+async def test_dispatch_defaults_left_single():
+ ex = _RecordingExecutor()
+ await _dispatch_raw_click(ex, SimpleNamespace(name="click"), 10, 20, None)
+ assert ex.args == {"x": 10, "y": 20, "button": "left", "double": False}
+
+
+async def test_dispatch_threads_right_double():
+ ex = _RecordingExecutor()
+ await _dispatch_raw_click(
+ ex, SimpleNamespace(name="click"), 10, 20, None, button="right", double=True
+ )
+ assert ex.args["button"] == "right"
+ assert ex.args["double"] is True
diff --git a/tests/unit/harness/test_cu_click_element_focus.py b/tests/unit/harness/test_cu_click_element_focus.py
new file mode 100644
index 0000000000..141fad3d77
--- /dev/null
+++ b/tests/unit/harness/test_cu_click_element_focus.py
@@ -0,0 +1,126 @@
+"""Post-click focus confirmation for click_element (audit 🔴 #1B).
+
+click_element used to return success the moment a node matched, with no check that
+the click had any effect. It now re-reads the tree and CONFIRMS the element took
+keyboard focus. The confirmation is deliberately positive-only: focus proves a
+field/control was clicked, but its ABSENCE never flips a button/menu click to a
+false failure (those legitimately don't retain focus).
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jarvis.harness import screenshot_only_loop as sol
+from jarvis.harness.computer_use_context import ComputerUseContext
+from jarvis.harness.screenshot_only_loop import _element_is_focused, _execute_action
+
+
+def _node(name: str, *, focused: bool = False, role: str = "Edit") -> Any:
+ return SimpleNamespace(
+ role=role, name=name, value="", focused=focused,
+ bounds=(0, 0, 10, 10), enabled=True,
+ )
+
+
+# --- pure helper: _element_is_focused (positive-only) ------------------------
+
+
+def test_focused_match_returns_true():
+ nodes = (_node("Search", focused=True),)
+ assert _element_is_focused(nodes, "Search") is True
+
+
+def test_substring_match_counts():
+ nodes = (_node("Username field", focused=True),)
+ assert _element_is_focused(nodes, "username") is True
+
+
+def test_matching_node_not_focused_returns_none_not_false():
+ # The positive-only contract: a found-but-unfocused control is "can't
+ # confirm" (None), NEVER False — clicking a button rarely keeps focus.
+ nodes = (_node("Submit", focused=False, role="Button"),)
+ assert _element_is_focused(nodes, "Submit") is None
+
+
+def test_no_match_returns_none():
+ nodes = (_node("Other", focused=True),)
+ assert _element_is_focused(nodes, "Search") is None
+
+
+def test_short_name_returns_none():
+ assert _element_is_focused((_node("X", focused=True),), "X") is None
+
+
+def test_never_returns_false():
+ # Whatever the input, the helper is True-or-None, never False.
+ for nodes in [(), (_node("A", focused=False),), (_node("B", focused=True),)]:
+ assert _element_is_focused(nodes, "search") in (True, None)
+
+
+# --- dispatch wiring ---------------------------------------------------------
+
+
+class _OkExecutor:
+ async def execute(self, tool: Any, args: dict, *,
+ user_utterance: str = "", trace_id: Any = None) -> Any:
+ return SimpleNamespace(success=True, output="clicked 'Search'", error=None)
+
+
+class _FakeClickElementTool:
+ name = "click_element"
+
+
+class _FakeSource:
+ def __init__(self, nodes: tuple) -> None:
+ self._nodes = nodes
+
+ async def observe(self) -> Any:
+ return SimpleNamespace(nodes=self._nodes)
+
+
+def _ctx() -> ComputerUseContext:
+ return ComputerUseContext(
+ vision_engine=None, brain_manager=None,
+ tool_executor=_OkExecutor(), tools={"click_element": _FakeClickElementTool()},
+ )
+
+
+async def test_dispatch_appends_focus_confirmation(monkeypatch):
+ monkeypatch.setattr(sol, "_get_ui_tree_source", lambda: _FakeSource((_node("Search", focused=True),)))
+ ok, msg = await _execute_action(
+ {"action": "click_element", "name": "Search"}, _ctx(),
+ trace_id=None, user_goal="x",
+ )
+ assert ok is True
+ assert "focus" in msg.lower()
+
+
+async def test_dispatch_unconfirmed_focus_leaves_success_unchanged(monkeypatch):
+ # A button that doesn't retain focus: still success, NO false failure, and no
+ # bogus focus claim appended.
+ monkeypatch.setattr(sol, "_get_ui_tree_source", lambda: _FakeSource((_node("Submit", focused=False, role="Button"),)))
+ ok, msg = await _execute_action(
+ {"action": "click_element", "name": "Submit"}, _ctx(),
+ trace_id=None, user_goal="x",
+ )
+ assert ok is True
+ assert "now has focus" not in msg
+
+
+async def test_dispatch_tree_error_leaves_success_unchanged(monkeypatch):
+ class _BoomSource:
+ async def observe(self):
+ raise OSError("tree gone")
+
+ monkeypatch.setattr(sol, "_get_ui_tree_source", lambda: _BoomSource())
+ ok, msg = await _execute_action(
+ {"action": "click_element", "name": "Search"}, _ctx(),
+ trace_id=None, user_goal="x",
+ )
+ assert ok is True # a flaky tree never turns a good click into a failure
diff --git a/tests/unit/harness/test_cu_engine_switch.py b/tests/unit/harness/test_cu_engine_switch.py
new file mode 100644
index 0000000000..98418b46aa
--- /dev/null
+++ b/tests/unit/harness/test_cu_engine_switch.py
@@ -0,0 +1,125 @@
+"""Reversible Computer-Use engine switch ([computer_use].engine).
+
+Covers (a) the harness selector that picks the maintained vs the frozen
+"june13" engine per config, and (b) a runtime smoke proving the frozen
+2026-06-10 engine (jarvis/harness/screenshot_only_loop_june13.py) still drives a
+trivial mission to completion against TODAY's codebase — the compatibility claim
+the switch relies on.
+"""
+from __future__ import annotations
+
+import time
+from types import SimpleNamespace
+from typing import Any
+from uuid import uuid4
+
+import jarvis.harness.screenshot_only_loop_june13 as june13
+import jarvis.plugins.harness.computer_use as harness
+from jarvis.core.protocols import HarnessTask, Observation
+from jarvis.harness.computer_use_context import ComputerUseContext
+
+# --- minimal fakes (mirror tests/unit/harness/test_cu_loop_robustness.py) -----
+
+
+class _FakeVision:
+ def __init__(self, titles: list[str] | None = None) -> None:
+ self.calls = 0
+ self._titles = titles
+
+ def _guess_active_app_hint(self, _f: str | None = None) -> str:
+ if not self._titles:
+ return ""
+ return self._titles[min(self.calls, len(self._titles) - 1)]
+
+ async def observe(self, *, mode: str = "auto", cancel_token: Any = None,
+ window_title_filter: str | None = None) -> Observation:
+ idx = self.calls
+ self.calls += 1
+ title = self._titles[min(idx, len(self._titles) - 1)] if self._titles else ""
+ return Observation(
+ trace_id=uuid4(), timestamp_ns=time.time_ns(), screenshot_path=None,
+ screenshot_hash=f"h-{idx}", nodes=(), window_title=title, active_pid=0,
+ source="screenshot_only", pruning_stats={},
+ )
+
+
+class _FakeBrain:
+ def __init__(self, reply: str) -> None:
+ self.reply = reply
+ self.calls = 0
+
+ async def complete_text(self, *, system: str, user: str) -> str:
+ self.calls += 1
+ return self.reply
+
+
+class _FakeExecutor:
+ async def execute(self, tool: Any, args: dict[str, Any], *,
+ user_utterance: str = "", trace_id: Any = None) -> Any:
+ return SimpleNamespace(success=True, output="ok", error="")
+
+
+def _ctx(brain: _FakeBrain, vision: _FakeVision) -> ComputerUseContext:
+ return ComputerUseContext(
+ vision_engine=vision, brain_manager=brain, tool_executor=_FakeExecutor(),
+ tools={}, verify_after_each_step=False, step_budget=5,
+ )
+
+
+# --- runtime smoke: the frozen june13 engine still runs on today's codebase ---
+
+
+async def test_june13_engine_runs_a_trivial_mission_to_completion():
+ # A reply that satisfies BOTH the action parser (action=done) and any
+ # verifier parser (done=true + proof), so the loop terminates cleanly
+ # regardless of which path the frozen engine takes for this goal.
+ brain = _FakeBrain('{"action": "done", "done": true, "proof": "the app is open"}')
+ ctx = _ctx(brain, _FakeVision(titles=["New Tab - Google Chrome"]))
+ task = HarnessTask(prompt="oeffne chrome", timeout_s=10.0)
+
+ chunks = []
+ async for chunk in june13._run_screenshot_loop(task, ctx, cancel_token=None):
+ chunks.append(chunk)
+
+ assert chunks, "frozen june13 engine produced no output (crashed?)"
+ assert chunks[-1].is_final
+ assert chunks[-1].exit_code == 0
+ assert brain.calls >= 1 # it actually drove the brain
+
+
+# --- selector: [computer_use].engine picks the right module -------------------
+
+
+def _patch_engine(monkeypatch, value: str) -> None:
+ monkeypatch.setattr(
+ "jarvis.core.config.load_config",
+ lambda: SimpleNamespace(computer_use=SimpleNamespace(engine=value)),
+ )
+
+
+def test_selector_picks_june13_when_configured(monkeypatch):
+ _patch_engine(monkeypatch, "june13")
+ loop = harness._resolve_run_cu_loop()
+ assert loop.__module__ == "jarvis.harness.screenshot_only_loop_june13"
+
+
+def test_selector_picks_current_by_default(monkeypatch):
+ _patch_engine(monkeypatch, "current")
+ loop = harness._resolve_run_cu_loop()
+ assert loop.__module__ == "jarvis.harness.screenshot_only_loop"
+
+
+def test_selector_picks_stable_when_configured(monkeypatch):
+ # The pre-Wave-1 frozen fallback the user flips to if the new work misbehaves.
+ _patch_engine(monkeypatch, "stable")
+ loop = harness._resolve_run_cu_loop()
+ assert loop.__module__ == "jarvis.harness.screenshot_only_loop_stable"
+
+
+def test_selector_falls_back_to_current_on_config_error(monkeypatch):
+ def _boom() -> Any:
+ raise RuntimeError("config unreadable")
+
+ monkeypatch.setattr("jarvis.core.config.load_config", _boom)
+ loop = harness._resolve_run_cu_loop()
+ assert loop.__module__ == "jarvis.harness.screenshot_only_loop"
diff --git a/tests/unit/harness/test_cu_ensure_on_primary.py b/tests/unit/harness/test_cu_ensure_on_primary.py
new file mode 100644
index 0000000000..d632e59f96
--- /dev/null
+++ b/tests/unit/harness/test_cu_ensure_on_primary.py
@@ -0,0 +1,112 @@
+"""CU works on the MAIN monitor: move the target window to primary at mission
+start (audit G8c).
+
+``_ensure_target_on_primary`` runs once before the first observe when
+monitor="primary": if the foreground window is on a secondary screen it is moved
+to the primary, and a note steers the model to re-read the freshly-captured main
+screen. Honest no-op when already on primary, when the rect can't be read
+(macOS/Linux today), or when the move is refused (Wayland) — never a blind act.
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from jarvis.harness import screenshot_only_loop as sol
+from jarvis.platform import monitors as mon
+from jarvis.platform import window_state as ws
+
+# The harness conftest autouse-stubs sol._ensure_target_on_primary to a no-op so
+# loop tests never move a real window. THIS file tests the real function, so we
+# capture its reference at import time (before any fixture patches the module).
+_ensure_target_on_primary = sol._ensure_target_on_primary
+
+_VIRT = {"left": -2560, "top": 0, "width": 6400, "height": 2160}
+_LEFT = {"left": -2560, "top": 0, "width": 2560, "height": 1440, "name": "left"}
+_MAIN = {"left": 0, "top": 0, "width": 3840, "height": 2160, "name": "main"}
+
+
+class _FakeSct:
+ def __init__(self, mons: list) -> None:
+ self.monitors = mons
+
+ def __enter__(self) -> _FakeSct:
+ return self
+
+ def __exit__(self, *_a: object) -> bool:
+ return False
+
+
+def _patch_env(monkeypatch, *, rect, fg=True, move_result=(True, "moved App")):
+ import mss
+
+ monkeypatch.setattr(mss, "mss", lambda: _FakeSct([_VIRT, _LEFT, _MAIN]))
+ monkeypatch.setattr(mon, "native_primary_origin", lambda: None) # -> (0,0) = MAIN
+ monkeypatch.setattr(
+ ws, "foreground_window",
+ lambda: ws.WindowInfo(title="App", handle=1) if fg else None,
+ )
+ monkeypatch.setattr(ws, "window_rect", lambda _w: rect)
+ seen: dict = {}
+
+ def _move(_w, p):
+ seen["primary"] = p
+ return move_result
+
+ monkeypatch.setattr(ws, "move_window_to_primary", _move)
+ return seen
+
+
+def _ctx(monitor: str = "primary") -> SimpleNamespace:
+ return SimpleNamespace(monitor=monitor, main_monitor="primary")
+
+
+def test_skips_when_not_primary_mode():
+ # monitor="foreground" -> the whole hook is a no-op (never touches windows).
+ assert _ensure_target_on_primary(_ctx(monitor="foreground")) is None
+
+
+def test_no_move_when_already_on_primary(monkeypatch):
+ seen = _patch_env(monkeypatch, rect=(100, 100, 800, 600)) # center on MAIN
+ assert _ensure_target_on_primary(_ctx()) is None
+ assert "primary" not in seen # move_window_to_primary never called
+
+
+def test_moves_when_window_is_on_secondary(monkeypatch):
+ seen = _patch_env(monkeypatch, rect=(-2000, 200, 800, 600)) # center on LEFT
+ note = _ensure_target_on_primary(_ctx())
+ assert note is not None
+ assert "main monitor" in note.lower()
+ assert seen["primary"]["name"] == "main" # moved onto the resolved primary
+
+
+def test_none_when_no_foreground_window(monkeypatch):
+ _patch_env(monkeypatch, rect=(-2000, 200, 800, 600), fg=False)
+ assert _ensure_target_on_primary(_ctx()) is None
+
+
+def test_none_when_rect_unreadable(monkeypatch):
+ _patch_env(monkeypatch, rect=None) # macOS/Linux today
+ assert _ensure_target_on_primary(_ctx()) is None
+
+
+def test_honest_note_when_move_refused_and_stuck_on_secondary(monkeypatch):
+ # Off-primary AND the move is refused (e.g. Wayland / an owned window): be
+ # HONEST (G8c Part 3) — return a note that tells the model the window is stuck
+ # on a secondary screen, instead of silently grounding on the empty primary.
+ _patch_env(
+ monkeypatch, rect=(-2000, 200, 800, 600),
+ move_result=(False, "Wayland refusal"),
+ )
+ note = _ensure_target_on_primary(_ctx())
+ assert note is not None
+ assert "could not move" in note.lower()
+ assert "secondary" in note.lower() or "drag" in note.lower()
+
+
+def test_foreground_window_non_windows_is_title_only(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "linux")
+ monkeypatch.setattr(ws, "get_foreground_title", lambda: "Some App")
+ win = ws.foreground_window()
+ assert win is not None
+ assert win.title == "Some App"
+ assert win.handle is None
diff --git a/tests/unit/harness/test_cu_focus_task_target.py b/tests/unit/harness/test_cu_focus_task_target.py
new file mode 100644
index 0000000000..f673f9bf22
--- /dev/null
+++ b/tests/unit/harness/test_cu_focus_task_target.py
@@ -0,0 +1,97 @@
+"""Proactively focus the goal's target app across ALL monitors (live 2026-06-28).
+
+The user's case: Chrome is already open on a SECONDARY monitor (not foreground);
+"do something in Chrome" — CU only ever looked at the current foreground screen,
+never found Chrome, and "didn't get it". ``_focus_task_target_window`` finds the
+named app among ALL open windows and brings it to the front first, deterministic
+and conservative (a distinctive goal token, not a generic verb; already-foreground
+is a no-op).
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+from jarvis.harness import screenshot_only_loop as sol
+from jarvis.platform import window_state as ws
+
+_REAL = sol._focus_task_target_window
+
+
+def _win(title: str) -> Any:
+ return SimpleNamespace(title=title, minimized=False, handle=1)
+
+
+def _patch(monkeypatch, *, windows, foreground="", raised=True):
+ monkeypatch.setattr(ws, "list_windows", lambda: list(windows))
+ monkeypatch.setattr(ws, "get_foreground_title", lambda: foreground)
+ calls = {"raised": []}
+
+ def _raise(win):
+ calls["raised"].append(win.title)
+ return (raised, win.title)
+
+ monkeypatch.setattr(ws, "raise_window", _raise)
+ return calls
+
+
+def _ctx() -> Any:
+ return SimpleNamespace(window_awareness=True)
+
+
+def test_focuses_named_app_open_on_another_monitor(monkeypatch):
+ # Chrome open (not foreground) + goal mentions chrome -> raise it.
+ calls = _patch(
+ monkeypatch,
+ windows=[_win("Inbox - Visual Studio Code"), _win("Reddit - Google Chrome")],
+ foreground="Inbox - Visual Studio Code",
+ )
+ note = _REAL(_ctx(), "search the last post in chrome")
+ assert note is not None
+ assert "front" in note.lower()
+ assert calls["raised"] == ["Reddit - Google Chrome"]
+
+
+def test_no_op_when_target_already_foreground(monkeypatch):
+ calls = _patch(
+ monkeypatch,
+ windows=[_win("Reddit - Google Chrome")],
+ foreground="Reddit - Google Chrome",
+ )
+ assert _REAL(_ctx(), "do something in chrome") is None
+ assert calls["raised"] == []
+
+
+def test_no_match_when_app_not_open(monkeypatch):
+ calls = _patch(
+ monkeypatch,
+ windows=[_win("Inbox - Visual Studio Code")],
+ foreground="Inbox - Visual Studio Code",
+ )
+ assert _REAL(_ctx(), "do something in chrome") is None
+ assert calls["raised"] == []
+
+
+def test_generic_verbs_do_not_focus_a_window(monkeypatch):
+ # "mach"/"bitte"/"etwas" must not match a window title and focus it wrongly.
+ calls = _patch(
+ monkeypatch,
+ windows=[_win("machen.txt - Editor")], # contains "mach" but goal has no app
+ foreground="Other",
+ )
+ assert _REAL(_ctx(), "mach bitte etwas") is None
+ assert calls["raised"] == []
+
+
+def test_disabled_when_window_awareness_off(monkeypatch):
+ _patch(monkeypatch, windows=[_win("Reddit - Google Chrome")])
+ ctx = SimpleNamespace(window_awareness=False)
+ assert _REAL(ctx, "do something in chrome") is None
+
+
+def test_never_raises_on_error(monkeypatch):
+ def _boom():
+ raise OSError("enum failed")
+
+ monkeypatch.setattr(ws, "list_windows", _boom)
+ assert _REAL(_ctx(), "do something in chrome") is None
diff --git a/tests/unit/harness/test_cu_human_handoff.py b/tests/unit/harness/test_cu_human_handoff.py
new file mode 100644
index 0000000000..407182a2fb
--- /dev/null
+++ b/tests/unit/harness/test_cu_human_handoff.py
@@ -0,0 +1,116 @@
+"""Deterministic human-handoff detector for Computer-Use (audit 🔴 #5).
+
+A pure detector that recognizes a screen the *human* must handle — a CAPTCHA, a
+2FA / one-time-code prompt, or a login/password entry — so the loop can hand off
+instead of typing a secret it does not hold (AP-2). Reads only accessibility node
+*names/roles* (every OS tree exposes them, so this is cross-platform), never a
+field VALUE (a value can be a typed secret). Conservative: a bare "password" word
+is not enough — a real password EDIT field or an explicit CAPTCHA/2FA phrase is
+required, so an ordinary settings page mentioning "change password" does not trip
+a false handoff.
+
+This covers only the pure detector. Wiring it into the loop (pause + poll resume,
+reusing the UAC elevation-clearance pattern) is the next increment.
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+from jarvis.harness import screenshot_only_loop as sol
+
+
+def _node(role: str, name: str, value: str = "") -> Any:
+ return SimpleNamespace(role=role, name=name, value=value, bounds=(0, 0, 10, 10), enabled=True)
+
+
+# --- positives ---------------------------------------------------------------
+
+
+def test_captcha_phrase_is_detected():
+ nodes = (_node("Text", "Verify you are human"), _node("CheckBox", "I'm not a robot"))
+ assert sol._human_handoff_reason(nodes) == "captcha challenge"
+
+
+def test_recaptcha_label_is_detected():
+ nodes = (_node("Text", "reCAPTCHA"),)
+ assert sol._human_handoff_reason(nodes) == "captcha challenge"
+
+
+def test_two_factor_code_is_detected():
+ nodes = (_node("Text", "Enter the verification code we sent you"),)
+ assert sol._human_handoff_reason(nodes) == "two-factor / one-time code"
+
+
+def test_authenticator_2fa_is_detected():
+ nodes = (_node("Text", "Open your authenticator app"), _node("Edit", "Code"))
+ assert sol._human_handoff_reason(nodes) == "two-factor / one-time code"
+
+
+def test_password_edit_field_is_login():
+ nodes = (_node("Edit", "Password"), _node("Button", "Sign in"))
+ assert sol._human_handoff_reason(nodes) == "login / password entry"
+
+
+def test_german_passwort_edit_field_is_login():
+ nodes = (_node("Edit", "Passwort"),)
+ assert sol._human_handoff_reason(nodes) == "login / password entry"
+
+
+def test_captcha_wins_over_login_priority():
+ nodes = (_node("Edit", "Password"), _node("Text", "Please solve the captcha"))
+ assert sol._human_handoff_reason(nodes) == "captcha challenge"
+
+
+# --- negatives (no false handoff) --------------------------------------------
+
+
+def test_bare_password_text_label_is_not_login():
+ # A settings page that merely *mentions* password must not trip a handoff —
+ # there is no editable password field, just a button label.
+ nodes = (_node("Button", "Change password"), _node("Text", "Account settings"))
+ assert sol._human_handoff_reason(nodes) is None
+
+
+def test_ordinary_screen_returns_none():
+ nodes = (_node("Button", "Save"), _node("Edit", "Search", value="cats"))
+ assert sol._human_handoff_reason(nodes) is None
+
+
+def test_empty_nodes_returns_none():
+ assert sol._human_handoff_reason(()) is None
+ assert sol._human_handoff_reason(None) is None
+
+
+def test_value_is_never_read_for_secrets():
+ # Even if a field VALUE happens to contain "captcha"/"password", only NAMES
+ # are inspected — so a value never drives a handoff (AP-2: a value is a secret).
+ nodes = (_node("Edit", "Search", value="how to solve a captcha and password"),)
+ assert sol._human_handoff_reason(nodes) is None
+
+
+# --- is_password flag (a11y foundation) drives detection too ------------------
+
+
+def _secure_node(name: str = "", *, is_password: bool = True) -> Any:
+ return SimpleNamespace(
+ role="Edit", name=name, value="", is_password=is_password,
+ focused=False, bounds=(0, 0, 10, 10), enabled=True,
+ )
+
+
+def test_secure_edit_flag_is_login_even_without_label():
+ # An unlabeled password field (empty UIA Name) is caught by the is_password
+ # flag — the name heuristic alone would miss it.
+ nodes = (_secure_node(name=""),)
+ assert sol._human_handoff_reason(nodes) == "login / password entry"
+
+
+def test_secure_edit_flag_beats_missing_name_tokens():
+ nodes = (_secure_node(name="PIN"), _node("Button", "Sign in"))
+ assert sol._human_handoff_reason(nodes) == "login / password entry"
+
+
+def test_is_password_false_does_not_trip_on_ordinary_field():
+ nodes = (_secure_node(name="Search", is_password=False),)
+ assert sol._human_handoff_reason(nodes) is None
diff --git a/tests/unit/harness/test_cu_human_handoff_pause.py b/tests/unit/harness/test_cu_human_handoff_pause.py
new file mode 100644
index 0000000000..1326f39182
--- /dev/null
+++ b/tests/unit/harness/test_cu_human_handoff_pause.py
@@ -0,0 +1,164 @@
+"""Computer-Use pause-and-resume on a human-handoff screen (login / 2FA / CAPTCHA,
+audit 🔴 #5).
+
+When the loop reaches a screen only the USER may complete — a login/password
+entry, a one-time-code / 2FA prompt, or a CAPTCHA — it must NOT type a secret it
+does not hold (AP-2). Instead it speaks a one-time "please take over" request,
+polls the accessibility tree until the cue clears, then RESUMES — or, if the user
+never acts within the wait budget, stops honestly (timeout). The caller passes the
+already-detected ``reason`` so there is no extra observe on the hot path; the
+helper only re-observes while polling.
+"""
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jarvis.harness import screenshot_only_loop as loop
+from jarvis.voice.action_phrases import action_phrase
+
+
+class _RecordingBus:
+ def __init__(self) -> None:
+ self.events: list = []
+
+ async def publish(self, event: object) -> None:
+ self.events.append(event)
+
+
+class _FakeToken:
+ def __init__(self, cancelled: bool = False) -> None:
+ self._cancelled = cancelled
+
+ def is_cancelled(self) -> bool:
+ return self._cancelled
+
+
+def _node(role: str, name: str) -> Any:
+ return SimpleNamespace(role=role, name=name, value="", bounds=(0, 0, 10, 10), enabled=True)
+
+
+_LOGIN_NODES = (_node("Edit", "Password"), _node("Button", "Sign in"))
+_CLEAR_NODES = (_node("Button", "Home"), _node("Edit", "Search"))
+
+
+class _FakeSource:
+ """Yields a configurable sequence of node-tuples from observe(); the LAST
+ entry repeats once the sequence is exhausted (so 'cleared forever' is easy)."""
+
+ def __init__(self, seq: list[tuple]) -> None:
+ self._seq = seq
+ self._i = 0
+
+ async def observe(self) -> Any:
+ nodes = self._seq[min(self._i, len(self._seq) - 1)]
+ self._i += 1
+ return SimpleNamespace(nodes=nodes)
+
+
[email protected](autouse=True)
+def _fast_handoff_timings(monkeypatch):
+ # Keep the poll loop sub-second so the timeout test does not sleep 120s.
+ monkeypatch.setattr(loop, "_HANDOFF_WAIT_TIMEOUT_S", 0.05)
+ monkeypatch.setattr(loop, "_HANDOFF_POLL_S", 0.005)
+
+
+def _use_source(monkeypatch, seq: list[tuple]) -> None:
+ # ONE shared instance: each _get_ui_tree_source() call must advance the same
+ # cursor, else every poll re-reads node[0] (a fresh source resets _i to 0).
+ src = _FakeSource(seq)
+ monkeypatch.setattr(loop, "_get_ui_tree_source", lambda: src)
+
+
+async def test_cleared_when_handoff_screen_disappears(monkeypatch):
+ # Login screen up on the first poll, gone afterwards -> the user signed in.
+ _use_source(monkeypatch, [_LOGIN_NODES, _CLEAR_NODES])
+ ctx = SimpleNamespace(bus=_RecordingBus())
+
+ result = await loop._await_human_handoff_clearance(
+ ctx, "open my mail", 3, None, reason="login / password entry"
+ )
+
+ assert result == "cleared"
+
+
+async def test_timeout_when_handoff_screen_persists(monkeypatch):
+ _use_source(monkeypatch, [_LOGIN_NODES]) # never clears
+ ctx = SimpleNamespace(bus=_RecordingBus())
+
+ result = await loop._await_human_handoff_clearance(
+ ctx, "open my mail", 3, None, reason="login / password entry"
+ )
+
+ assert result == "timeout"
+
+
+async def test_cancelled_while_waiting(monkeypatch):
+ _use_source(monkeypatch, [_LOGIN_NODES])
+ ctx = SimpleNamespace(bus=_RecordingBus())
+
+ result = await loop._await_human_handoff_clearance(
+ ctx, "open my mail", 3, _FakeToken(cancelled=True),
+ reason="login / password entry",
+ )
+
+ assert result == "cancelled"
+
+
+async def test_observe_failure_is_treated_as_cleared(monkeypatch):
+ class _BoomSource:
+ async def observe(self) -> Any:
+ raise OSError("tree blew up")
+
+ monkeypatch.setattr(loop, "_get_ui_tree_source", lambda: _BoomSource())
+ ctx = SimpleNamespace(bus=_RecordingBus())
+
+ result = await loop._await_human_handoff_clearance(
+ ctx, "open my mail", 1, None, reason="captcha challenge"
+ )
+
+ assert result == "cleared" # a flaky tree must never strand the mission
+
+
+async def test_announces_handoff_request_in_german(monkeypatch):
+ _use_source(monkeypatch, [_CLEAR_NODES]) # clears at once; we only check speech
+ bus = _RecordingBus()
+ ctx = SimpleNamespace(bus=bus)
+
+ await loop._await_human_handoff_clearance(
+ ctx, "Kannst du bitte meine Mails oeffnen?", 1, None,
+ reason="login / password entry",
+ )
+ await asyncio.sleep(0.01) # let the detached announcement task run
+
+ texts = [getattr(e, "text", "") for e in bus.events]
+ assert action_phrase("cu_awaiting_human", "de") in texts
+
+
+async def test_announces_handoff_request_in_english(monkeypatch):
+ _use_source(monkeypatch, [_CLEAR_NODES])
+ bus = _RecordingBus()
+ ctx = SimpleNamespace(bus=bus)
+
+ await loop._await_human_handoff_clearance(
+ ctx, "Could you open my mail?", 1, None,
+ reason="login / password entry",
+ )
+ await asyncio.sleep(0.01)
+
+ texts = [getattr(e, "text", "") for e in bus.events]
+ assert action_phrase("cu_awaiting_human", "en") in texts
+
+
+def test_phrase_table_has_all_three_languages():
+ for lang in ("de", "en", "es"):
+ assert action_phrase("cu_awaiting_human", lang).strip()
diff --git a/tests/unit/harness/test_cu_loop_robustness.py b/tests/unit/harness/test_cu_loop_robustness.py
index d17217dc9a..3175e77f13 100644
--- a/tests/unit/harness/test_cu_loop_robustness.py
+++ b/tests/unit/harness/test_cu_loop_robustness.py
@@ -723,6 +723,13 @@ async def test_open_app_waits_for_the_window_before_next_think(
"Program Manager", "Program Manager", "New Tab - Google Chrome",
],
)
+ # The happy path matches the probe and returns early — the timeout
+ # fallback raise must NOT fire.
+ fallback: list = []
+ monkeypatch.setattr(
+ loop_mod.window_state, "focus_window",
+ lambda t: (fallback.append(t), (True, t))[1],
+ )
results = await run_loop(ctx, "oeffne chrome")
assert results[-1].exit_code == 0
@@ -731,6 +738,7 @@ async def test_open_app_waits_for_the_window_before_next_think(
# Still exactly 2 think calls — the settle wait replaced the wasted
# stale-frame round, it did not add LLM cost.
assert len(brain.requests) == 2
+ assert fallback == [], "fallback raise fired on the happy path (double-raise)"
async def test_open_app_settle_gives_up_when_window_never_appears(
@@ -740,6 +748,13 @@ async def test_open_app_settle_gives_up_when_window_never_appears(
up after its timeout and the mission continues (and may fail honestly)."""
monkeypatch.setattr(loop_mod, "_OPEN_APP_SETTLE_POLL_S", 0.005)
monkeypatch.setattr(loop_mod, "_OPEN_APP_SETTLE_TIMEOUT_S", 0.05)
+ # On timeout the settle probe makes ONE last-ditch raise before observing,
+ # so a backgrounded window still gets a correct next frame. Record it.
+ fallback: list = []
+ monkeypatch.setattr(
+ loop_mod.window_state, "focus_window",
+ lambda t: (fallback.append(t), (False, "no window"))[1],
+ )
brain = FakeBrain([
'{"action": "open_app", "name": "spotify"}',
'{"action": "fail", "reason": "window never appeared"}',
@@ -754,6 +769,7 @@ async def test_open_app_settle_gives_up_when_window_never_appears(
assert time.monotonic() - start < 1.0, "settle probe wedged the loop"
assert results[-1].is_final
+ assert fallback == ["spotify"], "settle timeout did not attempt the fallback raise"
async def test_mission_profile_summary_is_emitted() -> None:
@@ -1610,3 +1626,213 @@ async def test_uac_detected_before_brain_call_skips_blind_step(
from jarvis.voice.action_phrases import action_phrase
texts = [getattr(e, "text", "") for e in bus.events]
assert action_phrase("cu_awaiting_elevation", "en") in texts
+
+
+async def test_focus_click_then_type_is_not_blind_batched() -> None:
+ """Audit 🔴 #2: a [click_element, type] batch must NOT type under the same
+ pre-batch screenshot. The type is held back so it re-observes the focused
+ state first (where the type read-back gate then verifies it) — instead of
+ typing into a possibly-missed focus while Enter still fires."""
+ brain = FakeBrain([
+ '[{"action": "click_element", "name": "search"}, '
+ '{"action": "type", "text": "hello world"}]',
+ '{"action": "done"}',
+ ])
+ ctx = make_ctx(brain, titles=["App"])
+ await run_loop(ctx, "search hello world")
+
+ executed = [name for name, _args in ctx.tool_executor.calls]
+ assert "click_element" in executed # the focus-click ran
+ assert "type_text" not in executed # the type was held back, not blind-typed
+ assert len(brain.requests) >= 2 # it re-planned against a fresh observe
+
+
+async def test_loop_refuses_cleanly_on_wayland(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Audit 🔴 #8: a Wayland session can't capture or inject, so the loop refuses
+ with a clear message BEFORE any model call — instead of clicking blind."""
+ monkeypatch.setattr(
+ loop_mod, "_wayland_block_message",
+ lambda: "Computer-Use is unavailable on this Wayland session. Run X11.",
+ )
+ brain = FakeBrain(['{"action": "done"}']) # must never be reached
+ ctx = make_ctx(brain, titles=["App"])
+ results = await run_loop(ctx, "click the button")
+
+ assert results[-1].is_final
+ assert results[-1].exit_code == loop_mod._OBSERVE_EXIT_CODE
+ assert "wayland" in (results[-1].stderr or "").lower()
+ assert len(brain.requests) == 0 # refused before any model call
+
+
+# ---------------------------------------------------------------------------
+# Audit 🔴 #5 — human-handoff guard wired into the observe phase
+# ---------------------------------------------------------------------------
+
+
+async def test_human_handoff_pauses_then_resumes(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A login/2FA/CAPTCHA screen detected from the observation pauses the loop
+ (the brain is NOT asked to act on it), and once the user clears it the loop
+ RESUMES and finishes — far better than mashing wrong clicks at a password box."""
+ calls = {"labels": 0, "clearance": 0}
+
+ async def _labels(timeout_s: float, max_n: int = 28):
+ calls["labels"] += 1
+ # Login screen on the first step; gone after the user signs in.
+ reason = "login / password entry" if calls["labels"] == 1 else None
+ return ([], "", reason)
+
+ async def _clearance(ctx, task_prompt, step_idx, cancel_token, *, reason):
+ calls["clearance"] += 1
+ return "cleared"
+
+ monkeypatch.setattr(loop_mod, "_foreground_clickable_labels", _labels)
+ monkeypatch.setattr(loop_mod, "_await_human_handoff_clearance", _clearance)
+
+ brain = FakeBrain(['{"action": "done"}'])
+ ctx = make_ctx(brain, titles=["App"])
+ results = await run_loop(ctx, "open my mail")
+
+ assert results[-1].exit_code == 0
+ assert calls["clearance"] == 1 # paused exactly once
+ assert len(brain.requests) == 1 # brain NOT asked on the blocked step
+
+
+async def test_human_handoff_timeout_fails_honestly(monkeypatch: pytest.MonkeyPatch) -> None:
+ """If the user never completes the handoff, the loop stops with an honest
+ fail naming the screen — it does not silently push through."""
+ async def _labels(timeout_s: float, max_n: int = 28):
+ return ([], "", "captcha challenge") # never clears
+
+ async def _clearance(ctx, task_prompt, step_idx, cancel_token, *, reason):
+ return "timeout"
+
+ monkeypatch.setattr(loop_mod, "_foreground_clickable_labels", _labels)
+ monkeypatch.setattr(loop_mod, "_await_human_handoff_clearance", _clearance)
+
+ brain = FakeBrain(['{"action": "done"}']) # must never be reached
+ ctx = make_ctx(brain, titles=["App"])
+ results = await run_loop(ctx, "open my mail")
+
+ assert results[-1].is_final
+ assert results[-1].exit_code == loop_mod._FAIL_EXIT_CODE
+ assert "captcha challenge" in (results[-1].stderr or "")
+ assert len(brain.requests) == 0
+
+
+async def test_human_handoff_cancelled_exits_clean(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Cancelling (hangup) while awaiting the user's handoff exits with the
+ cancel code, not a generic failure."""
+ async def _labels(timeout_s: float, max_n: int = 28):
+ return ([], "", "two-factor / one-time code")
+
+ async def _clearance(ctx, task_prompt, step_idx, cancel_token, *, reason):
+ return "cancelled"
+
+ monkeypatch.setattr(loop_mod, "_foreground_clickable_labels", _labels)
+ monkeypatch.setattr(loop_mod, "_await_human_handoff_clearance", _clearance)
+
+ brain = FakeBrain(['{"action": "done"}'])
+ ctx = make_ctx(brain, titles=["App"])
+ results = await run_loop(ctx, "open my mail")
+
+ assert results[-1].exit_code == loop_mod._CANCEL_EXIT_CODE
+ assert len(brain.requests) == 0
+
+
+# ---------------------------------------------------------------------------
+# Audit 🟠 #15 — modal/banner "handle the dialog first" note injection
+# ---------------------------------------------------------------------------
+
+
+async def test_modal_banner_note_injected_into_brain_prompt(monkeypatch: pytest.MonkeyPatch) -> None:
+ """When the foreground labels look like a cookie/consent banner, the loop
+ injects a 'handle the dialog first' note into the model's context before the
+ next decision."""
+ async def _cookie_labels(timeout_s: float, max_n: int = 28):
+ return (["Accept all", "Reject all", "Manage preferences"], "", None)
+
+ monkeypatch.setattr(loop_mod, "_foreground_clickable_labels", _cookie_labels)
+
+ brain = FakeBrain(['{"action": "click_element", "name": "Accept all"}',
+ '{"action": "done"}'])
+ ctx = make_ctx(brain, titles=["Site"])
+ await run_loop(ctx, "accept the cookies")
+
+ # The very first decision must already carry the modal note.
+ assert brain.requests, "brain was never called"
+ _system, first_user = brain.requests[0]
+ assert "modal dialog or banner" in first_user
+
+
+async def test_no_modal_note_on_ordinary_screen(monkeypatch: pytest.MonkeyPatch) -> None:
+ async def _plain_labels(timeout_s: float, max_n: int = 28):
+ return (["File", "Edit", "View", "Settings"], "", None)
+
+ monkeypatch.setattr(loop_mod, "_foreground_clickable_labels", _plain_labels)
+
+ brain = FakeBrain(['{"action": "done"}'])
+ ctx = make_ctx(brain, titles=["App"])
+ await run_loop(ctx, "do the thing")
+
+ _system, first_user = brain.requests[0]
+ assert "modal dialog or banner" not in first_user
+
+
+# ---------------------------------------------------------------------------
+# G8c Part 1 — re-ensure-on-primary AFTER a mid-mission open_app launch
+# ---------------------------------------------------------------------------
+
+
+async def test_ensure_on_primary_reruns_after_mid_mission_open_app(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A mission-start ensure-on-primary cannot cover an app launched LATER. After
+ a mid-mission open_app the loop must re-bring the (now foreground) window onto
+ the main monitor, or CU keeps operating on the secondary (live bug 2026-06-28:
+ CU launched Chrome on the secondary and worked there)."""
+ calls = {"n": 0}
+
+ def _spy(_ctx):
+ calls["n"] += 1
+ return None
+
+ # Overrides the conftest autouse no-op stub for this test.
+ monkeypatch.setattr(loop_mod, "_ensure_target_on_primary", _spy)
+
+ brain = FakeBrain([
+ '{"action": "open_app", "name": "chrome"}',
+ '{"action": "done"}',
+ ])
+ ctx = make_ctx(brain, titles=["Chrome"])
+ await run_loop(ctx, "open chrome")
+
+ # Once at mission start + once after the open_app action.
+ assert calls["n"] >= 2, f"ensure-on-primary ran {calls['n']}x, want >= 2"
+
+
+# ---------------------------------------------------------------------------
+# Problem 2 — a guard-BLOCKED repeated click must TELL the model (or it spins to
+# the no-progress abort: "macht nicht weiter", live 2026-06-28).
+# ---------------------------------------------------------------------------
+
+
+async def test_toggle_stop_tells_the_model_its_click_was_blocked(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The model keeps clicking the SAME point; the toggle-stop guard blocks it.
+ Unlike the open_app suppression, the click guard injected NO history note, so
+ the model never learned WHY nothing happened and kept repeating until the
+ no-progress abort. It must now be told its click was blocked + to try a
+ different element/approach."""
+ brain = FakeBrain([
+ '{"action": "click", "x": 500, "y": 500, "target": "thing"}',
+ '{"action": "click", "x": 500, "y": 500, "target": "thing"}',
+ '{"action": "click", "x": 500, "y": 500, "target": "thing"}',
+ '{"action": "done"}',
+ ])
+ ctx = make_ctx(brain, titles=["App"], verify=False)
+ await run_loop(ctx, "do the thing")
+
+ joined = " ".join(user for _sys, user in brain.requests).lower()
+ assert "blocked" in joined
+ assert "stop clicking" in joined or "different" in joined
diff --git a/tests/unit/harness/test_cu_modal_detection.py b/tests/unit/harness/test_cu_modal_detection.py
new file mode 100644
index 0000000000..337f048956
--- /dev/null
+++ b/tests/unit/harness/test_cu_modal_detection.py
@@ -0,0 +1,72 @@
+"""Generic modal / banner detection for Computer-Use (audit 🟠 #15).
+
+A cookie/consent banner, a "save changes?" prompt, or a small confirm dialog in
+front swallows the agent's clicks until handled. ``_modal_dialog_hint`` detects
+it from the foreground control LABELS (cross-platform, no role needed) and
+returns a one-time "handle the dialog first" note. Conservative: an ordinary page
+with a lone OK button (or a large control set) must not trip it.
+"""
+from __future__ import annotations
+
+from jarvis.harness import screenshot_only_loop as sol
+
+
+# --- positives ---------------------------------------------------------------
+
+
+def test_save_prompt_is_detected():
+ hint = sol._modal_dialog_hint(["Save changes", "Don't save", "Cancel"])
+ assert hint is not None
+ assert "save" in hint.lower()
+
+
+def test_cookie_banner_is_detected():
+ hint = sol._modal_dialog_hint(["Accept all", "Reject all", "Manage preferences"])
+ assert hint is not None
+ assert "cookie" in hint.lower() or "consent" in hint.lower()
+
+
+def test_small_confirm_dialog_is_detected():
+ hint = sol._modal_dialog_hint(["OK", "Cancel"])
+ assert hint is not None
+ assert "confirmation" in hint.lower()
+
+
+def test_yes_no_pair_is_a_confirm_dialog():
+ assert sol._modal_dialog_hint(["Yes", "No"]) is not None
+
+
+def test_save_wins_over_cookie_priority():
+ # Both clusters present -> the save prompt (more urgent/destructive) wins.
+ hint = sol._modal_dialog_hint(["Save changes", "Accept all cookies", "Cancel"])
+ assert "save" in hint.lower()
+
+
+# --- negatives (no false nudge) ----------------------------------------------
+
+
+def test_ordinary_page_returns_none():
+ assert sol._modal_dialog_hint(
+ ["File", "Edit", "View", "Search", "Settings", "Profile"]
+ ) is None
+
+
+def test_lone_ok_button_is_not_a_dialog():
+ assert sol._modal_dialog_hint(["OK"]) is None
+
+
+def test_confirm_pair_in_large_control_set_is_not_a_dialog():
+ # A positive+negative pair inside a big app window is not a focused modal.
+ labels = ["OK", "Cancel"] + [f"Item {i}" for i in range(10)]
+ assert sol._modal_dialog_hint(labels) is None
+
+
+def test_empty_and_none_return_none():
+ assert sol._modal_dialog_hint([]) is None
+ assert sol._modal_dialog_hint(None) is None
+
+
+def test_close_button_alone_is_not_negative_confirm():
+ # "Close" (a window X) is deliberately NOT a confirm-negative, so an OK+Close
+ # pair must not read as a dialog.
+ assert sol._modal_dialog_hint(["OK", "Close"]) is None
diff --git a/tests/unit/harness/test_cu_monitor_geom_source.py b/tests/unit/harness/test_cu_monitor_geom_source.py
new file mode 100644
index 0000000000..30213f3a3c
--- /dev/null
+++ b/tests/unit/harness/test_cu_monitor_geom_source.py
@@ -0,0 +1,47 @@
+"""Click coords map against the EXACT captured monitor (mixed-DPI fix, 2026-06-28).
+
+On a 150%-primary + 100%-secondary desktop the screenshot (mss) and a separate
+GetForegroundWindow/MonitorFromWindow click-geometry probe can pick different
+monitors at a boundary, so clicks land on the wrong screen. The ScreenshotSource
+now threads the captured monitor on the Observation, and ``_resolve_monitor_geom``
+uses it — falling back to the win32 probe only when it is absent.
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from jarvis.harness import screenshot_only_loop as sol
+
+
+def test_uses_observation_geometry_when_present(monkeypatch):
+ monkeypatch.setattr(sol, "_capture_monitor_geometry", lambda: (0, 0, 1920, 1080))
+ obs = SimpleNamespace(monitor_geom=(-2560, 0, 2560, 1440)) # the secondary
+ assert sol._resolve_monitor_geom(obs) == (-2560, 0, 2560, 1440)
+
+
+def test_falls_back_to_win32_probe_when_geom_unknown(monkeypatch):
+ monkeypatch.setattr(sol, "_capture_monitor_geometry", lambda: (0, 0, 3840, 2160))
+ obs = SimpleNamespace(monitor_geom=(0, 0, 0, 0))
+ assert sol._resolve_monitor_geom(obs) == (0, 0, 3840, 2160)
+
+
+def test_falls_back_when_observation_is_none(monkeypatch):
+ monkeypatch.setattr(sol, "_capture_monitor_geometry", lambda: (7, 7, 800, 600))
+ assert sol._resolve_monitor_geom(None) == (7, 7, 800, 600)
+
+
+def test_falls_back_when_width_is_zero(monkeypatch):
+ monkeypatch.setattr(sol, "_capture_monitor_geometry", lambda: (1, 2, 100, 200))
+ obs = SimpleNamespace(monitor_geom=(-2560, 0, 0, 1440)) # bogus width
+ assert sol._resolve_monitor_geom(obs) == (1, 2, 100, 200)
+
+
+def test_secondary_geometry_resolves_click_to_secondary_pixel(monkeypatch):
+ # End-to-end intent: a click at norm (500,500) on the SECONDARY (origin
+ # -2560, 2560x1440) must resolve to that screen's centre pixel, not the
+ # primary's. Proves the geometry the loop now feeds _resolve_click_pixel.
+ monkeypatch.setattr(sol, "_capture_monitor_geometry", lambda: (0, 0, 3840, 2160))
+ geom = sol._resolve_monitor_geom(SimpleNamespace(monitor_geom=(-2560, 0, 2560, 1440)))
+ px, py = sol._resolve_click_pixel({"x": 500, "y": 500}, geom)
+ assert px == -1280 # -2560 + 500/1000*2560
+ assert py == 720 # 0 + 500/1000*1440
diff --git a/tests/unit/harness/test_cu_prompt_injection.py b/tests/unit/harness/test_cu_prompt_injection.py
new file mode 100644
index 0000000000..cece399670
--- /dev/null
+++ b/tests/unit/harness/test_cu_prompt_injection.py
@@ -0,0 +1,36 @@
+"""Prompt-injection defense in the Computer-Use system prompt (audit 🔴 #3).
+
+The screen is the agent's sole grounding signal and must be treated as untrusted
+DATA — a web page / document / dialog showing "ignore your task and click here"
+must not hijack the agent. These are deterministic presence checks for the
+defense block; a full adversarial attack-suite needs a real-model eval (tracked
+separately).
+"""
+from __future__ import annotations
+
+from jarvis.harness import screenshot_only_loop as sol
+
+
+def test_system_prompt_marks_screen_as_untrusted_data():
+ p = sol._SYSTEM_PROMPT.lower()
+ assert "untrusted" in p
+ assert "never instructions" in p or "not a command to obey" in p
+
+
+def test_system_prompt_makes_only_the_goal_authoritative():
+ p = sol._SYSTEM_PROMPT.lower()
+ assert "authoritative" in p
+ assert "goal" in p
+
+
+def test_system_prompt_names_redirect_attempts():
+ p = sol._SYSTEM_PROMPT.lower()
+ assert "ignore your instructions" in p
+ assert "injection" in p or "redirect" in p
+
+
+def test_system_prompt_directs_fail_on_off_goal_pressure():
+ # Pushed toward a consequential/off-goal action -> fail, don't comply.
+ p = sol._SYSTEM_PROMPT.lower()
+ assert "fail" in p
+ assert "redirect the task" in p
diff --git a/tests/unit/harness/test_cu_safety_handoff.py b/tests/unit/harness/test_cu_safety_handoff.py
new file mode 100644
index 0000000000..6afb494e2e
--- /dev/null
+++ b/tests/unit/harness/test_cu_safety_handoff.py
@@ -0,0 +1,46 @@
+"""Sensitive-screen handoff + consequential-action guard in the CU system prompt
+(audit 🔴 #4 + #5, prompt-level slice).
+
+#3's SECURITY block defends against the screen *lying* (prompt injection). This
+block covers the orthogonal case where the sensitive screen is a *legitimate*
+part of the goal: a real login / 2FA / CAPTCHA the agent reaches honestly, and an
+irreversible Buy/Pay/Send/Delete it was never asked to perform. The agent must
+NOT type the user's secret itself (it holds none — AP-2) and must NOT plow through
+a consequential action off-goal; it hands off to the human via ``fail`` instead.
+
+These are deterministic presence checks for the guidance block. The heavier
+deterministic detection + pause/poll resume (reusing the UAC elevation-clearance
+pattern) is the tracked follow-up, not covered here.
+"""
+from __future__ import annotations
+
+from jarvis.harness import screenshot_only_loop as sol
+
+
+def test_block_names_sensitive_screens():
+ p = sol._SYSTEM_PROMPT.lower()
+ assert "password" in p
+ assert "2fa" in p or "two-factor" in p
+ assert "captcha" in p
+ assert "sign in" in p or "log in" in p or "login" in p
+
+
+def test_block_forbids_typing_secrets_and_hands_off():
+ p = sol._SYSTEM_PROMPT.lower()
+ assert "do not type" in p or "never type" in p
+ assert "hand off" in p or "handoff" in p
+ assert "human" in p
+
+
+def test_block_names_consequential_actions():
+ p = sol._SYSTEM_PROMPT.lower()
+ assert "buy" in p
+ assert "pay" in p
+ assert "delete" in p
+ assert "send" in p
+
+
+def test_block_ties_consequential_to_goal():
+ p = sol._SYSTEM_PROMPT.lower()
+ assert "consequential" in p
+ assert "goal" in p
diff --git a/tests/unit/harness/test_cu_type_verify.py b/tests/unit/harness/test_cu_type_verify.py
new file mode 100644
index 0000000000..7af0b7e19d
--- /dev/null
+++ b/tests/unit/harness/test_cu_type_verify.py
@@ -0,0 +1,131 @@
+"""Type read-back verification (audit 🔴 #1, the user's #1 complaint).
+
+After a `type`, the loop re-reads the editable field's value from the accessibility
+tree and confirms the text actually landed — instead of returning success the moment
+it dispatched (which let "typed into the wrong field, didn't notice" through). On a
+confirmed miss it FAILS the action so the loop re-focuses and retries (and a blind
+focus->type->Enter batch stops at the type).
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+from jarvis.harness import screenshot_only_loop as sol
+from jarvis.harness.computer_use_context import ComputerUseContext
+
+
+def _node(role: str, value: str, name: str = "f") -> Any:
+ return SimpleNamespace(role=role, value=value, name=name, bounds=(0, 0, 10, 10), enabled=True)
+
+
+# --- pure helper: _typed_text_landed (tri-state) -----------------------------
+
+
+def test_landed_true_when_editable_field_contains_text():
+ nodes = (_node("Edit", "hello world", name="search"),)
+ assert sol._typed_text_landed(nodes, "hello world") is True
+
+
+def test_landed_true_on_substring_after_existing_text():
+ # field had pre-existing text and the typed text was appended.
+ nodes = (_node("Edit", "see: hello world", name="box"),)
+ assert sol._typed_text_landed(nodes, "hello world") is True
+
+
+def test_landed_false_when_editable_present_but_text_absent():
+ nodes = (_node("Edit", "something totally different", name="search"),)
+ assert sol._typed_text_landed(nodes, "hello world") is False
+
+
+def test_landed_none_when_no_editable_node():
+ nodes = (_node("Button", "Submit"),)
+ assert sol._typed_text_landed(nodes, "hello world") is None
+
+
+def test_landed_none_when_text_too_short():
+ nodes = (_node("Edit", "x"),)
+ assert sol._typed_text_landed(nodes, "ab") is None # < _TYPE_VERIFY_MIN_CHARS
+
+
+# --- integration: the type action gate in _execute_action --------------------
+
+
+class _FakeResult:
+ success = True
+ output = "ok"
+ error = ""
+
+
+class _FakeExecutor:
+ async def execute(self, tool: Any, args: dict, *, user_utterance: str = "",
+ trace_id: Any = None) -> Any:
+ return _FakeResult()
+
+
+class _FakeTree:
+ def __init__(self, nodes: tuple) -> None:
+ self._nodes = nodes
+
+ async def observe(self, **_kw) -> Any:
+ return SimpleNamespace(nodes=self._nodes)
+
+
+def _ctx(*, strict: bool = True) -> ComputerUseContext:
+ return ComputerUseContext(
+ vision_engine=None, brain_manager=None, tool_executor=_FakeExecutor(),
+ tools={"type_text": object(), "hotkey": object()},
+ settle_scale=0.0, strict_verify=strict,
+ )
+
+
+async def _type(ctx: ComputerUseContext, text: str) -> tuple:
+ return await sol._execute_action(
+ {"action": "type", "text": text}, ctx,
+ trace_id=None, user_goal="x", monitor_geom=(0, 0, 1000, 1000), observation=None,
+ )
+
+
+async def test_type_confirmed_when_text_lands(monkeypatch):
+ monkeypatch.setattr(sol, "_get_ui_tree_source",
+ lambda: _FakeTree((_node("Edit", "hello world", name="search"),)))
+ ok, msg = await _type(_ctx(), "hello world")
+ assert ok is True
+ assert "confirmed" in msg.lower()
+
+
+async def test_type_fails_when_text_did_not_land(monkeypatch):
+ # editable field readable, but it holds something else -> confirmed miss -> FAIL,
+ # so the loop re-focuses (and a focus->type->Enter batch stops here).
+ monkeypatch.setattr(sol, "_get_ui_tree_source",
+ lambda: _FakeTree((_node("Edit", "unrelated", name="search"),)))
+ ok, msg = await _type(_ctx(), "hello world")
+ assert ok is False
+ assert "did not land" in msg.lower() and "field" in msg.lower()
+
+
+async def test_type_passes_when_tree_unreadable(monkeypatch):
+ # no editable node -> can't tell -> keep the legacy success (no false failure).
+ monkeypatch.setattr(sol, "_get_ui_tree_source",
+ lambda: _FakeTree((_node("Button", "Submit"),)))
+ ok, msg = await _type(_ctx(), "hello world")
+ assert ok is True
+ assert msg == "ok"
+
+
+async def test_short_text_skips_the_gate(monkeypatch):
+ called: list = []
+ monkeypatch.setattr(sol, "_get_ui_tree_source",
+ lambda: called.append(1) or _FakeTree(()))
+ ok, msg = await _type(_ctx(), "ab") # < min chars
+ assert ok is True and msg == "ok"
+ assert called == [] # gate skipped -> no tree fetch
+
+
+async def test_strict_verify_off_skips_the_gate(monkeypatch):
+ called: list = []
+ monkeypatch.setattr(sol, "_get_ui_tree_source",
+ lambda: called.append(1) or _FakeTree((_node("Edit", "unrelated"),)))
+ ok, msg = await _type(_ctx(strict=False), "hello world")
+ assert ok is True and msg == "ok" # legacy path despite a non-matching field
+ assert called == []
diff --git a/tests/unit/harness/test_cu_uia_snap.py b/tests/unit/harness/test_cu_uia_snap.py
index 67160aa2cf..8457097427 100644
--- a/tests/unit/harness/test_cu_uia_snap.py
+++ b/tests/unit/harness/test_cu_uia_snap.py
@@ -18,8 +18,11 @@ from jarvis.harness.computer_use_context import ComputerUseContext
def _ctx() -> ComputerUseContext:
+ # uia_click_fallback defaults OFF in production (restore-to-good, 2026-06-27);
+ # these tests exercise the snap FEATURE, so they opt it on explicitly.
return ComputerUseContext(
- vision_engine=None, brain_manager=None, tool_executor=object(), tools={}
+ vision_engine=None, brain_manager=None, tool_executor=object(), tools={},
+ uia_click_fallback=True,
)
@@ -62,6 +65,27 @@ def test_pick_snap_node_empty():
assert sol._pick_snap_node([], 10, 10, 80) is None
+def test_pick_snap_node_rejects_window_whose_center_is_far():
+ # BUG-CU-UIASNAP (live 2026-06-24): a full-window node "contains" the miss,
+ # but clicking its CENTRE (~screen centre) relocates the click ~1500px. A
+ # snap must only NUDGE, never RELOCATE -> reject -> caller falls to refine.
+ nodes = [_node(0, 0, 3840, 2088, name="(8) Home / X - Google Chrome")]
+ assert sol._pick_snap_node(nodes, 438, 168, 80) is None
+
+
+def test_pick_snap_node_uses_near_control_over_containing_window():
+ # The miss is just OUTSIDE a small control but INSIDE the page window. Old
+ # code returned the window (centre far, ~screen centre); the fix rejects the
+ # window by the nudge bound and snaps to the genuinely near control instead.
+ nodes = [
+ _node(0, 0, 3840, 2088, name="window"), # contains miss, centre far
+ _node(500, 150, 30, 30, name="button"), # centre (515,165), near the miss
+ ]
+ picked = sol._pick_snap_node(nodes, 490, 165, 80) # inside window, just left of button
+ assert picked is not None
+ assert picked.name == "button"
+
+
# --- snap helper ------------------------------------------------------------
@@ -80,7 +104,7 @@ async def test_uia_snap_clicks_element_center(monkeypatch):
)
clicks: list = []
- async def fake_dispatch(executor, tool, cx, cy, tid):
+ async def fake_dispatch(executor, tool, cx, cy, tid, *, button="left", double=False):
clicks.append((cx, cy))
return True, "clicked"
@@ -171,6 +195,7 @@ async def test_snap_fires_inside_click_with_refine_on_miss(monkeypatch):
tool_executor=_RecordingExecutor(),
tools={"click": _FakeClickTool()},
verify_after_each_step=True,
+ uia_click_fallback=True, # snap defaults OFF now; this test exercises it
)
ok, msg = await sol._execute_action(
{"action": "click", "x": 500, "y": 500, "target": "submit"},
@@ -183,3 +208,27 @@ async def test_snap_fires_inside_click_with_refine_on_miss(monkeypatch):
assert ctx.tool_executor.clicks == [(500, 500), (480, 480)]
assert "UIA-snapped" in msg
assert "Submit" in msg
+
+
+# --- restore-to-good guard: the two click-correction layers stay OFF ----------
+
+
+def test_click_correction_layers_default_off():
+ """2026-06-27 restore-to-good: the UIA snap (BUG-CU-UIASNAP wild-snap, added
+ 2026-06-24) and proactive zoom-before-click (made default-on then reverted)
+ BOTH default OFF. The known-good click pipeline is coarse click -> verify ->
+ LLM refine on miss; these correction layers stacked and degraded accuracy, so
+ they must not silently re-enable. Re-enable per [computer_use] with a bench."""
+ from jarvis.core.config import ComputerUseConfig
+
+ cfg = ComputerUseConfig()
+ assert cfg.uia_click_fallback is False
+ assert cfg.zoom_before_click is False
+
+ ctx = ComputerUseContext(
+ vision_engine=None, brain_manager=None, tool_executor=object(), tools={}
+ )
+ assert ctx.uia_click_fallback is False
+ assert ctx.zoom_before_click is False
+ # And the snap helper no-ops on a default context (the layer is truly off).
+ assert sol._uia_snap_click is not None # symbol still present for re-enable
diff --git a/tests/unit/harness/test_cu_verifier_proof_language.py b/tests/unit/harness/test_cu_verifier_proof_language.py
new file mode 100644
index 0000000000..8ecf0f5986
--- /dev/null
+++ b/tests/unit/harness/test_cu_verifier_proof_language.py
@@ -0,0 +1,270 @@
+"""The Computer-Use verifier writes its ``proof`` in the turn's output language.
+
+Live bug 2026-06-27 (German voice session 07:47): "öffne meinen Explorer und
+navigiere zum Videos-Ordner" was read back as
+"Erledigt — The file explorer window is open and navigated to the 'Videos'
+folder, as shown" — a German frame ("Erledigt —") around an ENGLISH body. The
+body is the verifier's ``proof``: the verifier LLM never learned the
+conversation language, so it defaulted to English (the language of its own
+system prompt). The German→English mismatch (and the symmetric EN/ES cases) is
+a Runtime-Output-Language doctrine violation — an embedded LLM observation that
+ignores the one resolved output language.
+
+Fix: the turn's resolved output language (the ``brain.reply_language`` pin +
+conversation stickiness, de/en/es) is threaded via ``HarnessTask.env`` into the
+loop, and the verifier ``user_message`` is told to write ``proof`` in that
+language. The spoken frame and the embedded body then share ONE language source.
+
+All tests drive ``_run_screenshot_loop`` directly with fakes — no real
+screenshots, no real UIA, no real model calls (mirrors
+``test_cu_read_informational_goal.py``).
+"""
+from __future__ import annotations
+
+import time
+from typing import Any
+from uuid import uuid4
+
+import pytest
+
+import jarvis.harness.screenshot_only_loop as loop_mod
+from jarvis.core.protocols import HarnessResult, HarnessTask, Observation
+from jarvis.harness.computer_use_context import ComputerUseContext
+from jarvis.harness.screenshot_only_loop import (
+ _OUTPUT_LANGUAGE_ENV_KEY,
+ _proof_language_directive,
+ _run_screenshot_loop,
+)
+
+# ---------------------------------------------------------------------------
+# Fakes (compact mirror of test_cu_read_informational_goal.py)
+# ---------------------------------------------------------------------------
+
+
+class FakeVisionEngine:
+ def __init__(self, window_titles: list[str] | None = None) -> None:
+ self.calls = 0
+ self._titles = window_titles
+
+ def _guess_active_app_hint(self, window_title_filter: str | None = None) -> str:
+ if self._titles is None:
+ return ""
+ return self._titles[min(self.calls, len(self._titles) - 1)]
+
+ async def observe(self, *, mode: str = "auto", cancel_token: Any = None,
+ window_title_filter: str | None = None) -> Observation:
+ idx = self.calls
+ self.calls += 1
+ title = ""
+ if self._titles is not None:
+ title = self._titles[min(idx, len(self._titles) - 1)]
+ return Observation(
+ trace_id=uuid4(),
+ timestamp_ns=time.time_ns(),
+ screenshot_path=None,
+ screenshot_hash=f"hash-{idx}",
+ nodes=(),
+ window_title=title,
+ active_pid=0,
+ source="screenshot_only",
+ pruning_stats={},
+ )
+
+
+class FakeToolResult:
+ def __init__(self, success: bool = True, output: str = "ok") -> None:
+ self.success = success
+ self.output = output
+ self.error = ""
+
+
+class FakeTool:
+ def __init__(self, name: str) -> None:
+ self.name = name
+
+
+class FakeExecutor:
+ def __init__(self) -> None:
+ self.calls: list[tuple[str, dict[str, Any]]] = []
+
+ async def execute(self, tool: Any, args: dict[str, Any], *,
+ user_utterance: str = "", trace_id: Any = None) -> FakeToolResult:
+ self.calls.append((tool.name, dict(args)))
+ return FakeToolResult()
+
+
+class PlanningBrain:
+ """Routes planner / judge / executor calls to separate scripts and records
+ the exact (system, user) pair each one saw."""
+
+ def __init__(self, executor_script: list[str],
+ plan_script: list[str] | None = None,
+ judge_script: list[str] | None = None) -> None:
+ self.executor_script = list(executor_script)
+ self.plan_script = list(plan_script or [])
+ self.judge_script = list(judge_script or [])
+ self.planner_calls: list[tuple[str, str]] = []
+ self.judge_calls: list[tuple[str, str]] = []
+ self.executor_calls: list[tuple[str, str]] = []
+
+ async def complete_text(self, *, system: str, user: str) -> str:
+ low = system.lower()
+ if "planner" in low:
+ self.planner_calls.append((system, user))
+ return self.plan_script.pop(0) if self.plan_script else '{"plan": []}'
+ if "judge" in low:
+ self.judge_calls.append((system, user))
+ return self.judge_script.pop(0) if self.judge_script else (
+ '{"done": true, "proof": "ok"}'
+ )
+ self.executor_calls.append((system, user))
+ return self.executor_script.pop(0) if self.executor_script else (
+ '{"action": "fail", "reason": "script exhausted"}'
+ )
+
+
+def make_ctx(brain: PlanningBrain, *, verify: bool = True,
+ titles: list[str] | None = None,
+ step_budget: int = 12) -> ComputerUseContext:
+ tools = {
+ name: FakeTool(name)
+ for name in ("open_app", "click", "type_text", "hotkey",
+ "click_element", "scroll")
+ }
+ return ComputerUseContext(
+ vision_engine=FakeVisionEngine(window_titles=titles),
+ brain_manager=brain,
+ tool_executor=FakeExecutor(),
+ tools=tools,
+ bus=None,
+ step_budget=step_budget,
+ per_step_timeout_s=5.0,
+ verify_after_each_step=verify,
+ announce_progress=False,
+ )
+
+
+async def run_loop(ctx: ComputerUseContext, goal: str, *,
+ output_language: str | None = None) -> list[HarnessResult]:
+ env = {_OUTPUT_LANGUAGE_ENV_KEY: output_language} if output_language else {}
+ task = HarnessTask(prompt=goal, timeout_s=30, env=env)
+ chunks: list[HarnessResult] = []
+ async for chunk in _run_screenshot_loop(task, ctx):
+ chunks.append(chunk)
+ return chunks
+
+
[email protected](autouse=True)
+def _isolate_host(monkeypatch: pytest.MonkeyPatch) -> None:
+ async def _no_labels(timeout_s: float, max_n: int = 28) -> list[str]:
+ return []
+
+ monkeypatch.setattr(loop_mod, "_foreground_clickable_labels", _no_labels)
+ monkeypatch.setattr(
+ loop_mod, "_capture_monitor_geometry", lambda: (0, 0, 1920, 1080),
+ )
+ monkeypatch.setattr(loop_mod, "_UI_TREE_SOURCE", None, raising=False)
+ monkeypatch.setattr(loop_mod, "_OPEN_APP_SETTLE_TIMEOUT_S", 0.0)
+
+
+# ---------------------------------------------------------------------------
+# 1. The directive builder is a pure de/en/es lookup
+# ---------------------------------------------------------------------------
+
+
+def test_proof_language_directive_names_each_language() -> None:
+ assert "german" in _proof_language_directive("de").lower()
+ assert "english" in _proof_language_directive("en").lower()
+ assert "spanish" in _proof_language_directive("es").lower()
+
+
+def test_proof_language_directive_mentions_proof_field() -> None:
+ # The directive must steer the `proof` field specifically — that is the only
+ # part of the verdict that gets spoken back.
+ assert "proof" in _proof_language_directive("de").lower()
+
+
+def test_proof_language_directive_empty_for_none_or_unknown() -> None:
+ # No resolved language (tests / minimal wiring) → no language coercion, the
+ # historical behaviour. An unknown locale is treated the same way.
+ assert _proof_language_directive(None) == ""
+ assert _proof_language_directive("") == ""
+ assert _proof_language_directive("fr") == ""
+
+
+# ---------------------------------------------------------------------------
+# 2. The verifier user_message carries the directive for the turn's language
+# ---------------------------------------------------------------------------
+
+
+def _judge_user_messages(brain: PlanningBrain) -> str:
+ return "\n".join(user for _system, user in brain.judge_calls).lower()
+
+
+async def test_generic_verifier_user_message_carries_german_directive() -> None:
+ """A German turn → the generic verifier is told to write proof in German."""
+ brain = PlanningBrain(
+ executor_script=['{"action": "open_app", "name": "explorer"}',
+ '{"action": "done"}'],
+ plan_script=['{"plan": []}'],
+ judge_script=['{"done": true, "proof": "Der Explorer ist offen"}'],
+ )
+ ctx = make_ctx(brain, verify=True, titles=["Datei-Explorer"] * 5)
+ await run_loop(ctx, "öffne den datei explorer", output_language="de")
+
+ assert brain.judge_calls, "the verifier was never consulted"
+ assert "german" in _judge_user_messages(brain)
+
+
+async def test_generic_verifier_user_message_carries_english_directive() -> None:
+ brain = PlanningBrain(
+ executor_script=['{"action": "open_app", "name": "explorer"}',
+ '{"action": "done"}'],
+ plan_script=['{"plan": []}'],
+ judge_script=['{"done": true, "proof": "The explorer is open"}'],
+ )
+ # A neutral title that does NOT contain the goal's app token, so the
+ # deterministic open-app fast path is skipped and the LLM verifier runs.
+ ctx = make_ctx(brain, verify=True, titles=["Workspace"] * 5)
+ await run_loop(ctx, "open the file explorer", output_language="en")
+
+ assert brain.judge_calls, "the verifier was never consulted"
+ assert "english" in _judge_user_messages(brain)
+
+
+async def test_read_verifier_user_message_carries_spanish_directive() -> None:
+ """A read goal pinned to Spanish → the READ verifier writes proof in Spanish."""
+ brain = PlanningBrain(
+ executor_script=['{"action": "open_app", "name": "discord"}',
+ '{"action": "scroll", "direction": "down"}',
+ '{"action": "done"}'],
+ plan_script=['{"plan": []}'],
+ judge_script=['{"done": true, "proof": "los mensajes mas recientes ..."}'],
+ )
+ ctx = make_ctx(brain, verify=True, titles=["Discord"] * 5)
+ await run_loop(
+ ctx, "open discord and tell me what the newest messages say",
+ output_language="es",
+ )
+
+ assert brain.judge_calls, "the verifier was never consulted"
+ assert "spanish" in _judge_user_messages(brain)
+
+
+async def test_no_output_language_leaves_verifier_unchanged() -> None:
+ """Without a resolved language (no env) the verifier prompt is unchanged —
+ no language coercion is injected (backward-compatible default)."""
+ brain = PlanningBrain(
+ executor_script=['{"action": "open_app", "name": "explorer"}',
+ '{"action": "done"}'],
+ plan_script=['{"plan": []}'],
+ judge_script=['{"done": true, "proof": "the explorer is open"}'],
+ )
+ # Neutral title (see English test) so the LLM verifier runs, not the fast path.
+ ctx = make_ctx(brain, verify=True, titles=["Workspace"] * 5)
+ await run_loop(ctx, "open the file explorer") # no output_language
+
+ assert brain.judge_calls, "the verifier was never consulted"
+ joined = _judge_user_messages(brain)
+ for marker in ("german", "english", "spanish"):
+ assert marker not in joined, f"unexpected language directive: {marker!r}"
diff --git a/tests/unit/harness/test_cu_wayland_guard.py b/tests/unit/harness/test_cu_wayland_guard.py
new file mode 100644
index 0000000000..65d638d311
--- /dev/null
+++ b/tests/unit/harness/test_cu_wayland_guard.py
@@ -0,0 +1,31 @@
+"""Wayland honest-refusal guard for Computer-Use (audit 🔴 #8).
+
+Wayland blocks global screen capture and input injection by design, and no
+portal/libei/uinput backend is built yet — so CU would capture a black frame and
+click nowhere. The loop refuses cleanly on a Wayland session instead of acting
+blind. Windows / macOS / Linux-X11 are unaffected (is_wayland() is False).
+"""
+from __future__ import annotations
+
+from jarvis.harness import screenshot_only_loop as sol
+
+
+def test_block_message_on_wayland(monkeypatch):
+ monkeypatch.setattr("jarvis.platform.probes.is_wayland", lambda: True)
+ msg = sol._wayland_block_message()
+ assert msg is not None
+ assert "wayland" in msg.lower()
+ assert "x11" in msg.lower() # tells the user the way out
+
+
+def test_no_block_off_wayland(monkeypatch):
+ monkeypatch.setattr("jarvis.platform.probes.is_wayland", lambda: False)
+ assert sol._wayland_block_message() is None
+
+
+def test_block_message_never_raises(monkeypatch):
+ def _boom() -> bool:
+ raise RuntimeError("probe failed")
+
+ monkeypatch.setattr("jarvis.platform.probes.is_wayland", _boom)
+ assert sol._wayland_block_message() is None # a probe error must not block
diff --git a/tests/unit/harness/test_cu_zoom_before_click_config.py b/tests/unit/harness/test_cu_zoom_before_click_config.py
index 7b9a4ccd8f..833561dd4d 100644
--- a/tests/unit/harness/test_cu_zoom_before_click_config.py
+++ b/tests/unit/harness/test_cu_zoom_before_click_config.py
@@ -1,4 +1,11 @@
-"""Plumbing tests for the [computer_use].zoom_before_click flag (default ON)."""
+"""Plumbing tests for the [computer_use] click-correction flags.
+
+Restore-to-good (2026-06-27): both proactive zoom-before-click and the UIA
+snap fallback DEFAULT OFF. Making zoom default-on (and the 2026-06-24 wild-snap)
+stacked correction layers onto every click and degraded accuracy, so the
+known-good pipeline (coarse click -> verify -> LLM refine on miss) is restored.
+The flags stay as opt-in escape hatches, hot-reloadable per [computer_use].
+"""
from __future__ import annotations
from jarvis.core.config import ComputerUseConfig
@@ -8,26 +15,34 @@ from jarvis.harness.computer_use_context import (
)
-def test_config_zoom_before_click_defaults_on() -> None:
- # Default ON: Computer-Use clicks are accurate out-of-the-box with no
- # opt-in. The model_fields check guards against the field being silently
- # absorbed as an extra under the model's extra="allow".
+def test_config_zoom_before_click_defaults_off() -> None:
+ # Default OFF (restore-to-good). The model_fields check guards against the
+ # field being silently absorbed as an extra under the model's extra="allow".
assert "zoom_before_click" in ComputerUseConfig.model_fields
- assert ComputerUseConfig().zoom_before_click is True
+ assert ComputerUseConfig().zoom_before_click is False
-def test_config_zoom_before_click_can_be_disabled() -> None:
- assert ComputerUseConfig(zoom_before_click=False).zoom_before_click is False
+def test_config_uia_click_fallback_defaults_off() -> None:
+ # The 2026-06-24 wild-snap layer (BUG-CU-UIASNAP) — off by default.
+ assert "uia_click_fallback" in ComputerUseConfig.model_fields
+ assert ComputerUseConfig().uia_click_fallback is False
-def test_context_zoom_before_click_defaults_on() -> None:
+def test_correction_flags_can_be_enabled() -> None:
+ assert ComputerUseConfig(zoom_before_click=True).zoom_before_click is True
+ assert ComputerUseConfig(uia_click_fallback=True).uia_click_fallback is True
+
+
+def test_context_correction_flags_default_off() -> None:
ctx = ComputerUseContext(
vision_engine=None, brain_manager=None, tool_executor=None,
)
- assert ctx.zoom_before_click is True
+ assert ctx.zoom_before_click is False
+ assert ctx.uia_click_fallback is False
-def test_zoom_before_click_is_hot_reloadable() -> None:
- # Listed in _RELOADABLE_FIELDS so a voice / Self-Mod toggle applies to the
+def test_correction_flags_are_hot_reloadable() -> None:
+ # Listed in _RELOADABLE_FIELDS so a config / Self-Mod toggle applies to the
# next mission without an app restart (mirrors verify_after_each_step).
assert "zoom_before_click" in _RELOADABLE_FIELDS
+ assert "uia_click_fallback" in _RELOADABLE_FIELDS
diff --git a/tests/unit/harness/test_native_computer_use.py b/tests/unit/harness/test_native_computer_use.py
index 1af4c4069b..7579db46b8 100644
--- a/tests/unit/harness/test_native_computer_use.py
+++ b/tests/unit/harness/test_native_computer_use.py
@@ -294,7 +294,10 @@ async def test_decide_native_batch_uses_and_validates_native_actions(monkeypatch
_SeamCtx(native=native), _Obs(), "click login", ["step1"], 2
)
- assert result == [{"action": "click", "x": 100, "y": 200}]
+ # button/double normalized onto every validated click (audit #21) — additive.
+ assert result == [
+ {"action": "click", "x": 100, "y": 200, "button": "left", "double": False}
+ ]
assert native.calls and native.calls[0][0] == "click login"
diff --git a/tests/unit/harness/test_screenshot_only_loop.py b/tests/unit/harness/test_screenshot_only_loop.py
index 682daced7f..2b069a8fb4 100644
--- a/tests/unit/harness/test_screenshot_only_loop.py
+++ b/tests/unit/harness/test_screenshot_only_loop.py
@@ -219,7 +219,11 @@ def test_parse_actions_wraps_single_object_in_list() -> None:
# plural parser treats it as a one-element batch so the executor can
# iterate uniformly.
actions = _parse_actions('{"action": "click", "x": 10, "y": 20}')
- assert actions == [{"action": "click", "x": 10, "y": 20}]
+ # button/double are normalized onto every click (audit #21): default
+ # left single-click — additive, the coordinates are unchanged.
+ assert actions == [
+ {"action": "click", "x": 10, "y": 20, "button": "left", "double": False}
+ ]
def test_parse_actions_accepts_list_of_actions() -> None:
@@ -231,7 +235,9 @@ def test_parse_actions_accepts_list_of_actions() -> None:
assert len(actions) == 3
assert actions[0] == {"action": "open_app", "name": "calc"}
assert actions[1] == {"action": "wait", "ms": 500}
- assert actions[2] == {"action": "click", "x": 100, "y": 200}
+ assert actions[2] == {
+ "action": "click", "x": 100, "y": 200, "button": "left", "double": False
+ }
def test_parse_actions_rejects_empty_list() -> None:
@@ -441,11 +447,62 @@ def test_cancel_active_cu_registry() -> None:
def cancel(self, reason: str) -> None:
raise RuntimeError("boom")
+ register_active_cu_token(None)
register_active_cu_token(_BadTok())
assert cancel_active_cu("voice_hangup") is False
register_active_cu_token(None)
+def test_cancel_active_cu_cancels_all_concurrent_missions() -> None:
+ """A hangup must stop EVERY running Computer-Use mission, not just the
+ most-recently-registered one.
+
+ Live regression (2026-06-24, feat/fast-boot-bootstrap): two CU missions
+ ran concurrently as overlapping background tasks. The single-slot active
+ token only remembered the last registration, so ``cancel_active_cu``
+ cancelled one mission while the other kept clicking the screen for ~22 s
+ after the user hung up (data/jarvis_desktop.log 20:45:54 -> 20:46:16).
+ """
+ from jarvis.harness.computer_use_context import (
+ cancel_active_cu,
+ register_active_cu_token,
+ unregister_active_cu_token,
+ )
+
+ class _Tok:
+ def __init__(self) -> None:
+ self.reason: str | None = None
+
+ def cancel(self, reason: str) -> None:
+ self.reason = reason
+
+ def is_cancelled(self) -> bool:
+ return self.reason is not None
+
+ register_active_cu_token(None)
+ mission_a = _Tok()
+ mission_b = _Tok()
+ register_active_cu_token(mission_a)
+ register_active_cu_token(mission_b)
+
+ # ONE hangup must cancel BOTH concurrent missions.
+ assert cancel_active_cu("voice_hangup") is True
+ assert mission_a.reason == "voice_hangup"
+ assert mission_b.reason == "voice_hangup"
+
+ # A finished mission removes only ITS OWN token; a sibling stays cancelable.
+ register_active_cu_token(None)
+ mission_c = _Tok()
+ mission_d = _Tok()
+ register_active_cu_token(mission_c)
+ register_active_cu_token(mission_d)
+ unregister_active_cu_token(mission_c) # C's harness finally ran
+ assert cancel_active_cu("voice_hangup") is True
+ assert mission_c.reason is None # C already gone — untouched
+ assert mission_d.reason == "voice_hangup" # D still cancelled
+ register_active_cu_token(None)
+
+
# ---------------------------------------------------------------------------
# Plan-first planner (BUG-CU-NO-PLAN, 2026-05-28): a multi-step goal must be
# decomposed into an ordered plan instead of mashing one button.
@@ -821,6 +878,15 @@ def test_execute_type_settles_before_dispatch(monkeypatch) -> None:
monkeypatch.setattr(loop.asyncio, "sleep", _fake_sleep)
+ # The type read-back gate (audit 🔴 #1) fetches the a11y tree after dispatch.
+ # Isolate it with an empty tree so this settle-ORDERING test stays deterministic
+ # and never depends on the live desktop's editable fields.
+ class _EmptyTree:
+ async def observe(self, **_kw):
+ return type("_Obs", (), {"nodes": ()})()
+
+ monkeypatch.setattr(loop, "_get_ui_tree_source", lambda: _EmptyTree())
+
type_tool = object()
executor = _OrderRecordingExecutor()
ctx = _FakeCtx(executor=executor, tools={"type_text": type_tool})
diff --git a/tests/unit/marketplace/test_mcp_liveness_runtime_gate.py b/tests/unit/marketplace/test_mcp_liveness_runtime_gate.py
new file mode 100644
index 0000000000..cb66ac2c5f
--- /dev/null
+++ b/tests/unit/marketplace/test_mcp_liveness_runtime_gate.py
@@ -0,0 +1,27 @@
+"""M2 (honest status): a stdio MCP plugin (GitHub=docker, Supabase=npx) must NOT
+report "Live" when its launcher binary is absent — connecting saves the token but
+the tools never appear, and a green "Connected · Live" badge is a lie. Gate stdio
+liveness on the launcher being on PATH and surface ``runtime_missing``.
+"""
+from __future__ import annotations
+
+from jarvis.ui.web.marketplace_routes import _mcp_live
+
+
+def test_http_transport_is_always_live():
+ assert _mcp_live({"transport": "http"}) == (True, None)
+
+
+def test_stdio_with_present_launcher_is_live():
+ # "python" is guaranteed on PATH in the test runner.
+ assert _mcp_live({"transport": "stdio", "install": ["python", "-m", "x"]}) == (True, None)
+
+
+def test_stdio_with_missing_launcher_is_not_live_and_flags_runtime():
+ live, missing = _mcp_live({"transport": "stdio", "install": ["definitely-not-a-binary-xyz", "run"]})
+ assert live is False
+ assert missing == "definitely-not-a-binary-xyz"
+
+
+def test_no_transport_is_not_live():
+ assert _mcp_live({}) == (False, None)
diff --git a/tests/unit/marketplace/test_pkce_hosted_callback.py b/tests/unit/marketplace/test_pkce_hosted_callback.py
new file mode 100644
index 0000000000..a4f4dc53ee
--- /dev/null
+++ b/tests/unit/marketplace/test_pkce_hosted_callback.py
@@ -0,0 +1,30 @@
+"""H3 (open-source AP-22 / headless VPS): the PKCE-loopback OAuth flow
+(Gmail/Google Drive/Calendar, Slack, Asana) hardcoded a 127.0.0.1 callback server,
+so a remote browser on a VPS got an unreachable loopback redirect → CallbackTimeout.
+It must route through ``make_callback_server`` so a configured
+``public_callback_base_url`` yields a publicly-reachable hosted rendezvous — while
+the desktop loopback still passes the plugin's registered fixed port + callback path.
+"""
+from __future__ import annotations
+
+import jarvis.marketplace.hosted_callback as hc
+
+
+def test_make_callback_server_forwards_callback_path_to_loopback(monkeypatch):
+ monkeypatch.setattr(hc, "get_public_callback_base_url", lambda: "")
+ captured: dict = {}
+
+ class _FakeLoopback:
+ def __init__(self, **kw):
+ captured.update(kw)
+
+ monkeypatch.setattr(hc, "OAuthCallbackServer", _FakeLoopback)
+ hc.make_callback_server("state-1", timeout_seconds=300, fixed_port=3118, callback_path="/slack/oauth")
+ assert captured.get("callback_path") == "/slack/oauth"
+ assert captured.get("port") == 3118
+
+
+def test_make_callback_server_hosted_when_public_base_url_set(monkeypatch):
+ monkeypatch.setattr(hc, "get_public_callback_base_url", lambda: "https://jarvis.example.com")
+ srv = hc.make_callback_server("state-1", timeout_seconds=300, fixed_port=3118, callback_path="/slack/oauth")
+ assert type(srv).__name__ == "HostedCallbackServer"
diff --git a/tests/unit/marketplace/test_refresh_scheduler.py b/tests/unit/marketplace/test_refresh_scheduler.py
index 385eb06062..6402c1fd47 100644
--- a/tests/unit/marketplace/test_refresh_scheduler.py
+++ b/tests/unit/marketplace/test_refresh_scheduler.py
@@ -6,6 +6,7 @@ back; a `revoked` refresh drops the entry so the UI can prompt a reconnect.
"""
from __future__ import annotations
+import logging
from datetime import UTC, datetime, timedelta
import pytest
@@ -283,6 +284,35 @@ async def test_scheduler_run_once_delegates() -> None:
assert outcomes == {"notion": REFRESHED}
+def test_log_cycle_names_dead_plugins_at_warning(caplog) -> None: # noqa: ANN001
+ # A revoked connection must be named at WARNING so it doesn't rot unseen
+ # behind an anonymous "revoked=1" count (live: linear sat dead 22 days
+ # unnoticed). A healthy refresh must not appear in the warning.
+ caplog.set_level(logging.WARNING)
+ RefreshScheduler._log_cycle({"gmail": REVOKED, "notion": REFRESHED})
+
+ warnings = [r for r in caplog.records if r.levelno == logging.WARNING]
+ assert any("gmail" in r.getMessage() for r in warnings)
+ assert not any("notion" in r.getMessage() for r in warnings)
+
+
+def test_log_cycle_lists_every_dead_plugin(caplog) -> None: # noqa: ANN001
+ caplog.set_level(logging.WARNING)
+ RefreshScheduler._log_cycle({"gmail": REVOKED, "linear": REVOKED, "slack": SKIPPED})
+
+ msg = " ".join(
+ r.getMessage() for r in caplog.records if r.levelno == logging.WARNING
+ )
+ assert "gmail" in msg and "linear" in msg
+
+
+def test_log_cycle_no_warning_when_all_healthy(caplog) -> None: # noqa: ANN001
+ caplog.set_level(logging.WARNING)
+ RefreshScheduler._log_cycle({"notion": REFRESHED, "slack": SKIPPED})
+
+ assert not [r for r in caplog.records if r.levelno == logging.WARNING]
+
+
@pytest.mark.asyncio
async def test_scheduler_keep_alive_refreshes_long_lived_token() -> None:
# The scheduler must apply keep-alive so a long-lived / no-expiry token still
diff --git a/tests/unit/marketplace/test_token_store.py b/tests/unit/marketplace/test_token_store.py
index 5808bb71c2..ba946072be 100644
--- a/tests/unit/marketplace/test_token_store.py
+++ b/tests/unit/marketplace/test_token_store.py
@@ -5,7 +5,106 @@ revoked token is KEPT and flagged, so a connected plugin never silently
disappears across an app close / PC restart.
"""
-from jarvis.marketplace.token_store import InMemoryBackend, Tokens, TokenStore
+import pytest
+
+from jarvis.marketplace.token_store import (
+ ChunkedBackend,
+ InMemoryBackend,
+ Tokens,
+ TokenStore,
+)
+
+
+class _SizeLimitedFakeBackend:
+ """Mimics the Windows Credential Manager: ``set`` raises over ``limit``
+ characters (the real CredWrite caps a blob at 2560 bytes / 1280 UTF-16
+ chars and fails with WinError 1783)."""
+
+ def __init__(self, limit: int) -> None:
+ self._limit = limit
+ self.store: dict[str, str] = {}
+
+ def get(self, key: str) -> str | None:
+ return self.store.get(key)
+
+ def set(self, key: str, value: str) -> None:
+ if len(value) > self._limit:
+ raise RuntimeError(f"CredWrite blob too large ({len(value)} > {self._limit})")
+ self.store[key] = value
+
+ def delete(self, key: str) -> None:
+ self.store.pop(key, None)
+
+
+def test_chunked_backend_round_trips_value_larger_than_primitive_limit():
+ # A long Google OAuth token blob exceeds the Credential Manager's hard
+ # per-entry limit. The chunking backend must split it across several
+ # primitive entries and reassemble it on read.
+ primitive = _SizeLimitedFakeBackend(limit=50)
+ backend = ChunkedBackend(primitive, chunk_size=20)
+ big = "z" * 200 # 4x the primitive's hard limit
+
+ backend.set("plugin_gmail_tokens", big)
+
+ assert backend.get("plugin_gmail_tokens") == big
+
+
+def test_chunked_backend_reads_legacy_plain_value():
+ # A short value written by the pre-chunking code (a bare string in the
+ # primary key) must still load unchanged.
+ primitive = _SizeLimitedFakeBackend(limit=50)
+ primitive.store["plugin_discord_tokens"] = '{"access":"abc"}'
+ backend = ChunkedBackend(primitive, chunk_size=20)
+
+ assert backend.get("plugin_discord_tokens") == '{"access":"abc"}'
+
+
+def test_chunked_backend_delete_removes_all_chunks():
+ primitive = _SizeLimitedFakeBackend(limit=50)
+ backend = ChunkedBackend(primitive, chunk_size=20)
+ backend.set("plugin_gmail_tokens", "z" * 200)
+
+ backend.delete("plugin_gmail_tokens")
+
+ assert backend.get("plugin_gmail_tokens") is None
+ assert primitive.store == {} # no orphaned overflow chunks
+
+
+def test_chunked_backend_resave_smaller_clears_stale_chunks():
+ primitive = _SizeLimitedFakeBackend(limit=50)
+ backend = ChunkedBackend(primitive, chunk_size=20)
+ backend.set("plugin_gmail_tokens", "z" * 200) # many chunks
+
+ backend.set("plugin_gmail_tokens", "small") # now fits in one
+
+ assert backend.get("plugin_gmail_tokens") == "small"
+ # Only the primary key remains — overflow chunks were cleaned up.
+ assert list(primitive.store) == ["plugin_gmail_tokens"]
+
+
+def test_chunked_backend_raises_when_a_single_chunk_still_too_big():
+ # Defensive: if even one chunk can't be stored, fail loudly rather than
+ # silently persisting a partial blob that can never be reassembled.
+ primitive = _SizeLimitedFakeBackend(limit=10)
+ backend = ChunkedBackend(primitive, chunk_size=50) # chunk bigger than limit
+
+ with pytest.raises(RuntimeError):
+ backend.set("plugin_gmail_tokens", "z" * 200)
+
+
+def test_store_round_trips_oversized_token_through_chunked_keyring():
+ # End-to-end: a TokenStore over a size-limited backend persists and reloads
+ # a token whose JSON exceeds the primitive's per-entry cap.
+ primitive = _SizeLimitedFakeBackend(limit=50)
+ store = TokenStore(ChunkedBackend(primitive, chunk_size=20))
+ big_token = Tokens(access="y" * 300, refresh="r" * 200)
+
+ store.save("gmail", big_token)
+ loaded = store.load("gmail")
+
+ assert loaded is not None
+ assert loaded.access == "y" * 300
+ assert loaded.refresh == "r" * 200
def test_needs_reauth_round_trips_through_json():
diff --git a/tests/unit/memory/test_user_profile.py b/tests/unit/memory/test_user_profile.py
index b5e774200b..f058f108a9 100644
--- a/tests/unit/memory/test_user_profile.py
+++ b/tests/unit/memory/test_user_profile.py
@@ -72,6 +72,74 @@ class TestAppendList:
profile.append_list("foo", "bar", "baz")
+# ======================================================================
+# clear / remove_list_item — manual deletion from the Profile UI
+# ======================================================================
+
+class TestClearField:
+ def test_clear_scalar_returns_true_and_empties(self, profile: UserProfile) -> None:
+ profile.set("identity", "name", "Ruben")
+ assert profile.clear("identity", "name") is True
+ # The field reads back as unset (None) — "not known yet".
+ assert profile.get("identity", "name") is None
+
+ def test_clear_already_empty_returns_false(self, profile: UserProfile) -> None:
+ # Template ships name=null → nothing to clear → no change.
+ assert profile.clear("identity", "name") is False
+
+ def test_clear_list_field_empties_it(self, profile: UserProfile) -> None:
+ profile.append_list("identity", "languages", "Deutsch")
+ assert profile.clear("identity", "languages") is True
+ # Empty list / None — either reads as "not known yet" to the UI.
+ assert not profile.get("identity", "languages")
+
+ def test_clear_rejects_unknown_cluster(self, profile: UserProfile) -> None:
+ with pytest.raises(ValueError):
+ profile.clear("unknown_cluster", "name")
+
+ def test_clear_survives_save_reload(self, profile: UserProfile) -> None:
+ profile.set("identity", "preferred_address", "Chef")
+ profile.save()
+ profile.clear("identity", "preferred_address")
+ profile.save()
+ reloaded = UserProfile.load(profile.path)
+ assert reloaded.get("identity", "preferred_address") is None
+
+
+class TestRemoveListItem:
+ def test_remove_existing_item(self, profile: UserProfile) -> None:
+ profile.append_list("identity", "languages", "Deutsch")
+ profile.append_list("identity", "languages", "English")
+ assert profile.remove_list_item("identity", "languages", "Deutsch") is True
+ assert profile.get("identity", "languages") == ["English"]
+
+ def test_remove_absent_item_returns_false(self, profile: UserProfile) -> None:
+ profile.append_list("identity", "languages", "Deutsch")
+ assert profile.remove_list_item("identity", "languages", "Spanish") is False
+ assert profile.get("identity", "languages") == ["Deutsch"]
+
+ def test_remove_last_item_leaves_field_empty(self, profile: UserProfile) -> None:
+ profile.append_list("identity", "languages", "Deutsch")
+ assert profile.remove_list_item("identity", "languages", "Deutsch") is True
+ assert not profile.get("identity", "languages")
+
+ def test_remove_from_unset_field_returns_false(self, profile: UserProfile) -> None:
+ assert profile.remove_list_item("values", "top_values", "Pizza") is False
+
+ def test_remove_rejects_unknown_cluster(self, profile: UserProfile) -> None:
+ with pytest.raises(ValueError):
+ profile.remove_list_item("foo", "bar", "baz")
+
+ def test_remove_survives_save_reload(self, profile: UserProfile) -> None:
+ profile.append_list("identity", "languages", "Deutsch")
+ profile.append_list("identity", "languages", "English")
+ profile.save()
+ profile.remove_list_item("identity", "languages", "Deutsch")
+ profile.save()
+ reloaded = UserProfile.load(profile.path)
+ assert reloaded.get("identity", "languages") == ["English"]
+
+
# ======================================================================
# save / load / reload Roundtrip
# ======================================================================
diff --git a/tests/unit/missions/test_api_agent_worker_providers.py b/tests/unit/missions/test_api_agent_worker_providers.py
new file mode 100644
index 0000000000..5f1139126c
--- /dev/null
+++ b/tests/unit/missions/test_api_agent_worker_providers.py
@@ -0,0 +1,29 @@
+"""B3/B4 (open-source AP-22): the in-process ApiAgentWorker is provider-agnostic
+(it drives a BrainProvider in a tool loop), so claude-api and gemini must be
+registered too — a user whose single key is an Anthropic or Gemini API key can
+then run heavy missions WITHOUT the npm `claude`/`gemini` CLI binary.
+"""
+from __future__ import annotations
+
+from jarvis.missions.workers.api_agent_worker import (
+ _BRAIN_BY_PROVIDER,
+ _DEFAULT_MODEL,
+ supports_api_agent_worker,
+)
+
+
+def test_claude_api_has_in_process_worker():
+ assert supports_api_agent_worker("claude-api") is True
+ mod, cls = _BRAIN_BY_PROVIDER["claude-api"]
+ assert "claude" in mod and cls.endswith("Brain")
+
+
+def test_gemini_has_in_process_worker():
+ assert supports_api_agent_worker("gemini") is True
+ mod, cls = _BRAIN_BY_PROVIDER["gemini"]
+ assert "gemini" in mod and cls.endswith("Brain")
+
+
+def test_every_api_agent_provider_has_a_default_model():
+ for provider in _BRAIN_BY_PROVIDER:
+ assert _DEFAULT_MODEL.get(provider), f"{provider} has no documented default model"
diff --git a/tests/unit/missions/test_api_critic.py b/tests/unit/missions/test_api_critic.py
new file mode 100644
index 0000000000..23620200e3
--- /dev/null
+++ b/tests/unit/missions/test_api_critic.py
@@ -0,0 +1,70 @@
+"""B2 (open-source AP-22): the mission Critic must be able to grade in-process via
+any keyed API brain provider, so a mission's review no longer requires the absent
+`claude` CLI binary. Covers the provider-agnostic critic resolver + the text→verdict
+parser used by the in-process path.
+"""
+from __future__ import annotations
+
+import jarvis.core.config as cfg_mod
+from jarvis.missions.critic.runner import (
+ REQUIRED_AXES,
+ CriticAxis,
+ CriticVerdict,
+ _parse_verdict_from_text,
+ _resolve_api_critic_provider,
+)
+
+
+def _valid_verdict_json() -> str:
+ v = CriticVerdict(
+ verdict="approve",
+ axes={ax: CriticAxis(status="pass", evidence=["ok"]) for ax in REQUIRED_AXES},
+ issues=[],
+ correction_instruction="",
+ summary="Looks good.",
+ summary_de="Sieht gut aus.",
+ confidence=0.9,
+ suggested_next_action="accept",
+ )
+ return v.model_dump_json()
+
+
+def test_parse_verdict_from_clean_json():
+ out = _parse_verdict_from_text(_valid_verdict_json(), iteration=0, adversarial_reframe=False)
+ assert out is not None and out.verdict == "approve"
+
+
+def test_parse_verdict_from_fenced_json():
+ fenced = "```json\n" + _valid_verdict_json() + "\n```"
+ out = _parse_verdict_from_text(fenced, iteration=0, adversarial_reframe=False)
+ assert out is not None and out.verdict == "approve"
+
+
+def test_parse_verdict_recovers_from_surrounding_prose():
+ noisy = "Let me think...\nIssuing the JSON verdict:\n" + _valid_verdict_json() + "\nDone."
+ out = _parse_verdict_from_text(noisy, iteration=1, adversarial_reframe=True)
+ assert out is not None and out.verdict == "approve"
+
+
+def test_parse_verdict_returns_none_on_garbage():
+ assert _parse_verdict_from_text("no json here at all", iteration=0, adversarial_reframe=False) is None
+
+
+def test_api_critic_provider_prefers_keyed_primary(monkeypatch):
+ monkeypatch.setattr(cfg_mod, "get_provider_secret", lambda p: "k" if p == "openrouter" else None)
+ prov, model = _resolve_api_critic_provider("openrouter", "anthropic/claude-opus-4.8")
+ assert prov == "openrouter" and model == "anthropic/claude-opus-4.8"
+
+
+def test_api_critic_falls_back_to_any_keyed_api_provider(monkeypatch):
+ # Worker provider is antigravity (no API critic backend); the critic must grade
+ # via whatever API key the user actually has (here: gemini).
+ monkeypatch.setattr(cfg_mod, "get_provider_secret", lambda p: "k" if p == "gemini" else None)
+ prov, model = _resolve_api_critic_provider("antigravity", "gemini-3.1-pro-preview")
+ assert prov == "gemini"
+
+
+def test_api_critic_none_when_no_api_key(monkeypatch):
+ monkeypatch.setattr(cfg_mod, "get_provider_secret", lambda p: None)
+ prov, model = _resolve_api_critic_provider("antigravity", None)
+ assert prov is None
diff --git a/tests/unit/missions/test_api_critic_provider_model.py b/tests/unit/missions/test_api_critic_provider_model.py
new file mode 100644
index 0000000000..8f64d32d73
--- /dev/null
+++ b/tests/unit/missions/test_api_critic_provider_model.py
@@ -0,0 +1,51 @@
+"""Regression: the in-process API critic must grade with the user's PICKED model
+for the keyed provider, never fall to a hardcoded paid default.
+
+Live forensic 2026-06-29: ``_resolve_api_critic_provider`` returned ``model=None``
+for any provider that was not the worker's primary. The in-process critic then did
+``cls()`` → the plugin's ``DEFAULT_MODEL`` (OpenRouter = anthropic/claude-opus-4.8),
+billing the user's OpenRouter key for Opus while reviewing a mission whose worker
+ran elsewhere. The critic must reuse the provider's own configured model
+(AP-21/AP-22, open-source single-key §3).
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.core.config import BrainProviderConfig, JarvisConfig
+from jarvis.missions.critic import runner
+
+_FREE = "nvidia/nemotron-3-ultra-550b-a55b:free"
+
+
+def test_cross_family_critic_uses_provider_pick(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ config = JarvisConfig()
+ config.brain.providers["openrouter"] = BrainProviderConfig(model=_FREE)
+ monkeypatch.setattr("jarvis.core.config.load_config", lambda: config)
+ # Only the OpenRouter key is present at runtime.
+ monkeypatch.setattr(
+ "jarvis.core.config.get_provider_secret",
+ lambda p: "sk-test" if p == "openrouter" else None,
+ )
+
+ # Worker ran on antigravity (a non-API provider) → critic crosses family to
+ # the keyed OpenRouter provider.
+ prov, model = runner._resolve_api_critic_provider("antigravity", None)
+
+ assert prov == "openrouter"
+ assert model == _FREE, f"cross-family critic did not reuse the pick: {model!r}"
+ assert "anthropic/claude" not in (model or "")
+
+
+def test_same_provider_critic_keeps_primary_model(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ "jarvis.core.config.get_provider_secret",
+ lambda p: "sk-test" if p == "openrouter" else None,
+ )
+ prov, model = runner._resolve_api_critic_provider("openrouter", _FREE)
+ assert prov == "openrouter"
+ assert model == _FREE
diff --git a/tests/unit/missions/test_jarvis_agent_default_provider.py b/tests/unit/missions/test_jarvis_agent_default_provider.py
new file mode 100644
index 0000000000..babbac3a67
--- /dev/null
+++ b/tests/unit/missions/test_jarvis_agent_default_provider.py
@@ -0,0 +1,47 @@
+"""B6 (open-source AP-22): when no sub-agent provider is explicitly configured,
+the heavy mission worker must default to the user's ACTIVE brain provider — NOT
+the legacy Claude CLI. A fresh openrouter/gemini/codex install (which never sets
+[brain.sub_jarvis].provider) otherwise routes every mission to a non-existent
+`claude` binary and fails.
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import jarvis.core.config as cfg_mod
+
+
+def _stub_config(monkeypatch, *, sub_provider, primary):
+ stub = SimpleNamespace(
+ brain=SimpleNamespace(
+ sub_jarvis=SimpleNamespace(provider=sub_provider),
+ primary=primary,
+ )
+ )
+ monkeypatch.setattr(cfg_mod, "load_config", lambda: stub)
+ monkeypatch.setattr(
+ cfg_mod, "refresh_persisted_env_from_user_registry", lambda: None, raising=False
+ )
+
+
+def test_unset_subagent_provider_defaults_to_brain_primary(monkeypatch):
+ _stub_config(monkeypatch, sub_provider=None, primary="openrouter")
+ from jarvis.missions.init import _live_subagent_provider
+
+ assert _live_subagent_provider(None) == "openrouter"
+
+
+def test_explicit_subagent_provider_still_wins(monkeypatch):
+ _stub_config(monkeypatch, sub_provider="antigravity", primary="openrouter")
+ from jarvis.missions.init import _live_subagent_provider
+
+ assert _live_subagent_provider(None) == "antigravity"
+
+
+def test_defaulted_provider_routes_to_a_non_claude_worker_kind():
+ # Once defaulted to the active provider, the worker kind must be that
+ # provider's own worker, not the legacy "subjarvis" (= ClaudeDirectWorker).
+ from jarvis.missions.init import _select_subagent_worker_kind
+
+ assert _select_subagent_worker_kind("openrouter", "") == "api_agent"
+ assert _select_subagent_worker_kind("openai", "") == "api_agent"
diff --git a/tests/unit/platform/test_monitors.py b/tests/unit/platform/test_monitors.py
new file mode 100644
index 0000000000..2917f7e0df
--- /dev/null
+++ b/tests/unit/platform/test_monitors.py
@@ -0,0 +1,80 @@
+"""Robust cross-platform primary-monitor resolution (audit G8a).
+
+``resolve_primary_monitor`` picks which physical monitor is "the main one" Jarvis
+works on. Default is the OS primary (identified robustly, NOT by assuming origin
+(0,0)); ``largest`` and an explicit id/index are config overrides. The native
+primary origin is a best-effort hint (Win MONITORINFOF_PRIMARY etc.); the pure
+decision logic is what these pin — the native query is monkeypatched.
+"""
+from __future__ import annotations
+
+from jarvis.platform import monitors as mon
+
+# mss-style: monitors[0] = virtual bounding box, [1:] = physical screens.
+_VIRTUAL = {"left": -2560, "top": 0, "width": 6400, "height": 2160}
+_LEFT = {"left": -2560, "top": 0, "width": 2560, "height": 1440, "name": "DELL-left"}
+_MAIN = {"left": 0, "top": 0, "width": 3840, "height": 2160, "name": "LG-main"}
+
+
+def _rig() -> list[dict]:
+ return [_VIRTUAL, dict(_LEFT), dict(_MAIN)]
+
+
+def test_single_monitor_returns_the_only_one(monkeypatch):
+ monkeypatch.setattr(mon, "native_primary_origin", lambda: None)
+ only = {"left": 0, "top": 0, "width": 1920, "height": 1080}
+ assert mon.resolve_primary_monitor([only]) is only
+
+
+def test_is_primary_flag_wins(monkeypatch):
+ monkeypatch.setattr(mon, "native_primary_origin", lambda: None)
+ rig = _rig()
+ rig[1]["is_primary"] = True # mark the LEFT one primary explicitly
+ assert mon.resolve_primary_monitor(rig)["name"] == "DELL-left"
+
+
+def test_native_origin_identifies_primary_when_not_at_zero(monkeypatch):
+ # A rig whose primary is NOT at (0,0) — the native origin must still find it
+ # (this is the "do not assume (0,0)" requirement).
+ virtual = {"left": 0, "top": 0, "width": 5760, "height": 2160}
+ left = {"left": 0, "top": 0, "width": 1920, "height": 1080, "name": "sec"}
+ main = {"left": 1920, "top": 0, "width": 3840, "height": 2160, "name": "primary"}
+ monkeypatch.setattr(mon, "native_primary_origin", lambda: (1920, 0))
+ assert mon.resolve_primary_monitor([virtual, left, main])["name"] == "primary"
+
+
+def test_falls_back_to_origin_when_no_native(monkeypatch):
+ monkeypatch.setattr(mon, "native_primary_origin", lambda: None)
+ assert mon.resolve_primary_monitor(_rig())["name"] == "LG-main" # the (0,0) one
+
+
+def test_largest_override_picks_biggest_area(monkeypatch):
+ monkeypatch.setattr(mon, "native_primary_origin", lambda: (-2560, 0)) # would be LEFT
+ # ...but override=largest must pick MAIN (3840x2160 > 2560x1440).
+ assert mon.resolve_primary_monitor(_rig(), override="largest")["name"] == "LG-main"
+
+
+def test_explicit_name_override(monkeypatch):
+ monkeypatch.setattr(mon, "native_primary_origin", lambda: None)
+ assert mon.resolve_primary_monitor(_rig(), override="dell")["name"] == "DELL-left"
+
+
+def test_explicit_index_override(monkeypatch):
+ monkeypatch.setattr(mon, "native_primary_origin", lambda: None)
+ # 1-based physical index: "1" = LEFT, "2" = MAIN.
+ assert mon.resolve_primary_monitor(_rig(), override="2")["name"] == "LG-main"
+
+
+def test_unknown_explicit_id_falls_back_to_primary_not_wrong(monkeypatch):
+ # An unmatched id must NOT silently pick a wrong screen — fall back to primary.
+ monkeypatch.setattr(mon, "native_primary_origin", lambda: None)
+ assert mon.resolve_primary_monitor(_rig(), override="nonexistent")["name"] == "LG-main"
+
+
+def test_native_primary_origin_never_raises():
+ # Whatever the host, the best-effort native query returns a tuple or None.
+ result = mon.native_primary_origin()
+ assert result is None or (
+ isinstance(result, tuple) and len(result) == 2
+ and all(isinstance(v, int) for v in result)
+ )
diff --git a/tests/unit/platform/test_open_path.py b/tests/unit/platform/test_open_path.py
index 8e9d066b28..6ee25001b1 100644
--- a/tests/unit/platform/test_open_path.py
+++ b/tests/unit/platform/test_open_path.py
@@ -2,12 +2,18 @@
from __future__ import annotations
from pathlib import Path
+from types import SimpleNamespace
from unittest.mock import patch
import jarvis.platform.open_path as op
from jarvis.platform.capabilities import Capabilities
+def _ok(returncode: int = 0) -> SimpleNamespace:
+ """A fake completed process for patching ``subprocess.run`` (open/xdg-open)."""
+ return SimpleNamespace(returncode=returncode)
+
+
def _caps(display: bool = True) -> Capabilities:
return Capabilities(
platform="linux",
@@ -141,3 +147,231 @@ def test_open_file_with_never_raises_on_error():
patch.object(op, "detect_platform", return_value="linux"), \
patch.object(op.subprocess, "Popen", side_effect=OSError("boom")):
assert op.open_file_with(Path("/x/y.md"), "executable", "/a/b") is False
+
+
+# --- open_url (open an http(s) URL in the OS default browser) -----------------
+# Used by the desktop shell because the embedded WebView2 drops window.open /
+# target=_blank, so OAuth-authorize + token-creation pages never reach a browser.
+
+
+def test_open_url_linux_uses_xdg_open():
+ # xdg-open is run with an exit-code check (not fire-and-forget), so a broken
+ # association is detectable; on success no direct-binary fallback is launched.
+ with patch.object(op, "detect_capabilities", return_value=_caps()), \
+ patch.object(op, "detect_platform", return_value="linux"), \
+ patch.object(op.subprocess, "run", return_value=_ok()) as run, \
+ patch.object(op.subprocess, "Popen") as popen:
+ assert op.open_url("https://accounts.google.com/o/oauth2/v2/auth?x=1") is True
+ argv = run.call_args.args[0]
+ assert argv[0] == "xdg-open"
+ assert argv[1].startswith("https://accounts.google.com")
+ popen.assert_not_called() # no double-open when xdg-open succeeds
+
+
+def test_open_url_linux_falls_back_to_browser_bin_when_xdg_open_fails():
+ # xdg-open exits non-zero (no handler) -> launch a real browser binary on PATH.
+ def _which(binname):
+ return "/usr/bin/firefox" if binname == "firefox" else None
+
+ with patch.object(op, "detect_capabilities", return_value=_caps()), \
+ patch.object(op, "detect_platform", return_value="linux"), \
+ patch.object(op.subprocess, "run", return_value=_ok(3)), \
+ patch.object(op.shutil, "which", side_effect=_which), \
+ patch.object(op.subprocess, "Popen") as popen:
+ assert op.open_url("https://example.com/x") is True
+ argv = popen.call_args.args[0]
+ assert argv[0] == "/usr/bin/firefox"
+ assert argv[1] == "https://example.com/x"
+ assert (
+ popen.call_args.kwargs.get("creationflags")
+ == op.NO_WINDOW_CREATIONFLAGS
+ )
+
+
+def test_open_url_linux_returns_false_when_no_browser():
+ with patch.object(op, "detect_capabilities", return_value=_caps()), \
+ patch.object(op, "detect_platform", return_value="linux"), \
+ patch.object(op.subprocess, "run", return_value=_ok(1)), \
+ patch.object(op.shutil, "which", return_value=None), \
+ patch.object(op.subprocess, "Popen") as popen:
+ assert op.open_url("https://example.com/x") is False
+ popen.assert_not_called()
+
+
+def test_open_url_darwin_uses_open():
+ with patch.object(op, "detect_capabilities", return_value=_caps()), \
+ patch.object(op, "detect_platform", return_value="darwin"), \
+ patch.object(op.subprocess, "run", return_value=_ok()) as run:
+ assert op.open_url("http://127.0.0.1:3118/authorize") is True
+ assert run.call_args.args[0][0] == "open"
+
+
+def test_open_url_darwin_falls_back_to_open_dash_a():
+ # Plain `open <url>` fails -> try `open -a <App> <url>` for each known browser.
+ calls: list[list[str]] = []
+
+ def _run(argv, **_kw):
+ calls.append(argv)
+ # default opener fails; the first `open -a` succeeds.
+ return _ok(0) if len(argv) >= 2 and argv[1] == "-a" else _ok(1)
+
+ with patch.object(op, "detect_capabilities", return_value=_caps()), \
+ patch.object(op, "detect_platform", return_value="darwin"), \
+ patch.object(op.subprocess, "run", side_effect=_run):
+ assert op.open_url("https://example.com/x") is True
+ assert calls[0] == ["open", "https://example.com/x"]
+ assert calls[1][:2] == ["open", "-a"]
+ assert calls[1][-1] == "https://example.com/x"
+
+
+def test_open_url_darwin_returns_false_when_nothing_opens():
+ with patch.object(op, "detect_capabilities", return_value=_caps()), \
+ patch.object(op, "detect_platform", return_value="darwin"), \
+ patch.object(op.subprocess, "run", return_value=_ok(1)):
+ assert op.open_url("https://example.com/x") is False
+
+
+def test_open_url_windows_launches_browser_exe_directly():
+ # Bypass the OS file association (rundll32/ShellExecute) — which silently opens
+ # nothing when the default https handler is hijacked to a dead profile — by
+ # launching a real browser exe directly, URL as one argv ('&' is safe).
+ url = "https://github.com/login/oauth/authorize?a=1&b=2"
+ chrome = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
+ with patch.object(op, "detect_capabilities", return_value=_caps()), \
+ patch.object(op, "detect_platform", return_value="win32"), \
+ patch.object(op, "_windows_browser_candidates", return_value=[chrome]), \
+ patch.object(op.subprocess, "Popen") as popen:
+ assert op.open_url(url) is True
+ argv = popen.call_args.args[0]
+ assert argv[0] == chrome
+ assert argv[1] == url # whole URL as one arg — '&' is safe (no shell)
+ # AP-1: every subprocess must suppress a console window under pythonw.
+ assert (
+ popen.call_args.kwargs.get("creationflags")
+ == op.NO_WINDOW_CREATIONFLAGS
+ )
+
+
+def test_open_url_windows_tries_next_candidate_on_error():
+ # First exe fails to launch -> fall through to the next candidate, not bail.
+ url = "https://example.com/x"
+ with patch.object(op, "detect_capabilities", return_value=_caps()), \
+ patch.object(op, "detect_platform", return_value="win32"), \
+ patch.object(op, "_windows_browser_candidates",
+ return_value=[r"A.exe", r"B.exe"]), \
+ patch.object(op.subprocess, "Popen",
+ side_effect=[OSError("boom"), None]) as popen:
+ assert op.open_url(url) is True
+ assert popen.call_count == 2
+ assert popen.call_args.args[0][0] == r"B.exe"
+
+
+def test_open_url_windows_falls_back_to_shellexecute_when_no_browser():
+ # No browser exe discoverable -> hand the URL to the OS association as a last
+ # resort (may be a UWP handler with no classic exe).
+ url = "https://example.com/x"
+ with patch.object(op, "detect_capabilities", return_value=_caps()), \
+ patch.object(op, "detect_platform", return_value="win32"), \
+ patch.object(op, "_windows_browser_candidates", return_value=[]), \
+ patch.object(op.subprocess, "Popen") as popen, \
+ patch.object(op.os, "startfile", create=True) as startfile:
+ assert op.open_url(url) is True
+ popen.assert_not_called()
+ startfile.assert_called_once_with(url)
+
+
+def test_open_url_windows_shellexecute_when_all_candidates_fail():
+ # Candidates exist but every direct launch raises -> reach the ShellExecute
+ # last resort rather than bailing.
+ url = "https://example.com/x"
+ with patch.object(op, "detect_capabilities", return_value=_caps()), \
+ patch.object(op, "detect_platform", return_value="win32"), \
+ patch.object(op, "_windows_browser_candidates", return_value=[r"A.exe"]), \
+ patch.object(op.subprocess, "Popen", side_effect=OSError("boom")), \
+ patch.object(op.os, "startfile", create=True) as startfile:
+ assert op.open_url(url) is True
+ startfile.assert_called_once_with(url)
+
+
+def test_open_url_windows_returns_false_when_everything_fails():
+ url = "https://example.com/x"
+ with patch.object(op, "detect_capabilities", return_value=_caps()), \
+ patch.object(op, "detect_platform", return_value="win32"), \
+ patch.object(op, "_windows_browser_candidates", return_value=[]), \
+ patch.object(op.os, "startfile", create=True,
+ side_effect=OSError("boom")):
+ assert op.open_url(url) is False
+
+
+def test_parse_exe_from_shell_command_quoted_drops_profile_args():
+ # The real-world hijacked Chrome handler: quoted exe + a --user-data-dir that
+ # points at a dead isolated profile. We keep ONLY the exe.
+ cmd = (
+ r'"C:\Program Files\Google\Chrome\Application\chrome.exe" '
+ r"--user-data-dir=C:\Users\x\.bh-chrome --profile-directory=Default "
+ r"--single-argument %1"
+ )
+ assert (
+ op._parse_exe_from_shell_command(cmd)
+ == r"C:\Program Files\Google\Chrome\Application\chrome.exe"
+ )
+
+
+def test_parse_exe_from_shell_command_unquoted():
+ assert (
+ op._parse_exe_from_shell_command(r"C:\Apps\firefox.exe %1")
+ == r"C:\Apps\firefox.exe"
+ )
+
+
+def test_parse_exe_from_shell_command_exe_substring_in_dir():
+ # ".exe" as a substring inside a path segment must not truncate the exe early;
+ # only a ".exe" that ends a token (space/quote/end) is a real boundary.
+ cmd = r"C:\my.exefoo\firefox.exe --flag"
+ assert (
+ op._parse_exe_from_shell_command(cmd) == r"C:\my.exefoo\firefox.exe"
+ )
+
+
+def test_parse_exe_from_shell_command_empty_or_blank():
+ assert op._parse_exe_from_shell_command("") is None
+ assert op._parse_exe_from_shell_command(" ") is None
+
+
+def test_open_url_headless_is_noop():
+ with patch.object(op, "detect_capabilities", return_value=_caps(display=False)), \
+ patch.object(op.subprocess, "Popen") as popen, \
+ patch.object(op.subprocess, "run") as run:
+ assert op.open_url("https://example.com") is False
+ popen.assert_not_called()
+ run.assert_not_called()
+
+
+def test_open_url_rejects_non_http_schemes():
+ # A hostile open_url payload must never reach a launcher: file:, javascript:,
+ # an app protocol, or a bare path are all refused before any dispatch.
+ for bad in (
+ "file:///C:/Windows/System32/calc.exe",
+ "javascript:alert(1)",
+ "obsidian://open?vault=x",
+ "/etc/passwd",
+ "ftp://host/x",
+ ):
+ with patch.object(op, "detect_capabilities", return_value=_caps()), \
+ patch.object(op, "detect_platform", return_value="linux"), \
+ patch.object(op.subprocess, "Popen") as popen, \
+ patch.object(op.subprocess, "run") as run, \
+ patch.object(op.os, "startfile", create=True) as startfile:
+ assert op.open_url(bad) is False, bad
+ popen.assert_not_called()
+ run.assert_not_called()
+ startfile.assert_not_called()
+
+
+def test_open_url_never_raises_on_error():
+ # Opener raises, no browser binary on PATH -> honest False, never an exception.
+ with patch.object(op, "detect_capabilities", return_value=_caps()), \
+ patch.object(op, "detect_platform", return_value="linux"), \
+ patch.object(op.subprocess, "run", side_effect=OSError("boom")), \
+ patch.object(op.shutil, "which", return_value=None):
+ assert op.open_url("https://example.com") is False
diff --git a/tests/unit/platform/test_window_move_to_primary.py b/tests/unit/platform/test_window_move_to_primary.py
new file mode 100644
index 0000000000..9f3369cd45
--- /dev/null
+++ b/tests/unit/platform/test_window_move_to_primary.py
@@ -0,0 +1,69 @@
+"""Move the target window onto the primary monitor (audit G8b).
+
+The pure geometry (which monitor a window is on) is unit-tested here; the per-OS
+move is best-effort (Windows full + live-proven elsewhere, Wayland an honest
+refusal, never a silent wrong-monitor act). The dispatch's refusal paths are
+pinned by monkeypatching the platform probes.
+"""
+from __future__ import annotations
+
+from jarvis.platform import window_state as ws
+from jarvis.platform.window_state import WindowInfo
+
+# --- pure: window_is_on_monitor ----------------------------------------------
+
+_MAIN = {"left": 0, "top": 0, "width": 3840, "height": 2160}
+_LEFT = {"left": -2560, "top": 0, "width": 2560, "height": 1440}
+
+
+def test_window_centered_on_main_is_on_main():
+ # A window at (100,100) 800x600 -> center (500,400) is on MAIN, not LEFT.
+ assert ws.window_is_on_monitor((100, 100, 800, 600), _MAIN) is True
+ assert ws.window_is_on_monitor((100, 100, 800, 600), _LEFT) is False
+
+
+def test_window_on_left_monitor_negative_x():
+ # A window on the LEFT screen: left=-2000, center ~ -1600 -> on LEFT.
+ rect = (-2000, 200, 800, 600)
+ assert ws.window_is_on_monitor(rect, _LEFT) is True
+ assert ws.window_is_on_monitor(rect, _MAIN) is False
+
+
+def test_straddling_window_counts_where_its_center_is():
+ # Center decides: a window mostly on MAIN (center x>0) is "on MAIN".
+ rect = (-200, 100, 800, 600) # center x = 200 -> MAIN
+ assert ws.window_is_on_monitor(rect, _MAIN) is True
+
+
+# --- dispatch refusals (no silent wrong-monitor act) -------------------------
+
+
+def test_move_refuses_on_wayland(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "linux")
+ monkeypatch.setattr(ws, "is_wayland", lambda: True)
+ ok, msg = ws.move_window_to_primary(WindowInfo(title="App"), _MAIN)
+ assert ok is False
+ assert "wayland" in msg.lower()
+
+
+def test_move_refuses_on_headless_linux(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "linux")
+ monkeypatch.setattr(ws, "is_wayland", lambda: False)
+ monkeypatch.setattr(ws, "display_present", lambda: False)
+ ok, msg = ws.move_window_to_primary(WindowInfo(title="App"), _MAIN)
+ assert ok is False
+ assert "headless" in msg.lower() or "display" in msg.lower()
+
+
+def test_move_never_raises_on_unknown_platform(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "plan9")
+ ok, msg = ws.move_window_to_primary(WindowInfo(title="App"), _MAIN)
+ assert ok is False
+ assert isinstance(msg, str) and msg
+
+
+def test_windows_move_without_handle_fails_cleanly(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "win32")
+ ok, msg = ws.move_window_to_primary(WindowInfo(title="App", handle=None), _MAIN)
+ assert ok is False
+ assert "handle" in msg.lower()
diff --git a/tests/unit/platform/test_window_state.py b/tests/unit/platform/test_window_state.py
index 98b317c265..6c9a38dc0d 100644
--- a/tests/unit/platform/test_window_state.py
+++ b/tests/unit/platform/test_window_state.py
@@ -198,6 +198,123 @@ def test_get_foreground_title_macos_empty_without_tool(monkeypatch):
assert ws.get_foreground_title() == ""
+# --- raise_window (raise a known window via the hardened path) ---------------
+
+
+def test_raise_window_windows_uses_handle(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "win32")
+ forced: list = []
+ monkeypatch.setattr(ws, "_force_foreground_windows", lambda h: forced.append(h) or True)
+ monkeypatch.setattr(ws, "focus_window", lambda t: (_ for _ in ()).throw(AssertionError("title path used")))
+ ok, title = ws.raise_window(WindowInfo("WhatsApp", handle=777))
+ assert ok is True
+ assert title == "WhatsApp"
+ assert forced == [777]
+
+
+def test_raise_window_non_windows_uses_title(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "linux")
+ seen: list = []
+ monkeypatch.setattr(ws, "focus_window", lambda t: (seen.append(t), (True, t))[1])
+ ok, _title = ws.raise_window(WindowInfo("WhatsApp", handle=None))
+ assert ok is True
+ assert seen == ["WhatsApp"]
+
+
+def test_raise_window_windows_without_handle_falls_back_to_title(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "win32")
+ seen: list = []
+ monkeypatch.setattr(ws, "focus_window", lambda t: (seen.append(t), (True, t))[1])
+ ok, _title = ws.raise_window(WindowInfo("WhatsApp", handle=None))
+ assert ok is True
+ assert seen == ["WhatsApp"]
+
+
+def test_raise_window_never_raises(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "win32")
+
+ def boom(_h):
+ raise RuntimeError("foreground blew up")
+
+ monkeypatch.setattr(ws, "_force_foreground_windows", boom)
+ ok, _msg = ws.raise_window(WindowInfo("WhatsApp", handle=5))
+ assert ok is False
+
+
+# --- raise_after_launch (poll for the new window, then actively foreground it) -
+
+
+def test_raise_after_launch_windows_uses_hardened_path(monkeypatch):
+ # The window appears on the 3rd poll; on Windows we raise it by hwnd via the
+ # hardened foreground path, never the title path.
+ monkeypatch.setattr(ws, "detect_platform", lambda: "win32")
+ polls: list[int] = []
+
+ def _list():
+ polls.append(1)
+ if len(polls) < 3:
+ return []
+ return [WindowInfo("New Tab - Google Chrome", handle=4242)]
+
+ monkeypatch.setattr(ws, "list_windows", _list)
+ forced: list[int] = []
+ monkeypatch.setattr(
+ ws, "_force_foreground_windows", lambda h: (forced.append(h), True)[1]
+ )
+ # focus_window (title path) must NOT be used on Windows.
+ monkeypatch.setattr(ws, "focus_window", lambda t: (_ for _ in ()).throw(AssertionError("title path used on win32")))
+
+ ok, title = ws.raise_after_launch("chrome", timeout_s=1.0, poll_s=0.001)
+ assert ok is True
+ assert title == "New Tab - Google Chrome"
+ assert forced == [4242]
+ assert len(polls) >= 3
+
+
+def test_raise_after_launch_macos_uses_title_focus(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "darwin")
+ monkeypatch.setattr(ws, "list_windows", lambda: [WindowInfo("Spotify Premium")])
+ focused: list[str] = []
+ monkeypatch.setattr(
+ ws, "focus_window", lambda t: (focused.append(t), (True, t))[1]
+ )
+ ok, title = ws.raise_after_launch("spotify", timeout_s=0.1, poll_s=0.001)
+ assert ok is True
+ assert focused == ["Spotify Premium"]
+
+
+def test_raise_after_launch_gives_up_when_window_never_appears(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "win32")
+ monkeypatch.setattr(ws, "list_windows", lambda: [WindowInfo("Program Manager")])
+ monkeypatch.setattr(ws, "_force_foreground_windows", lambda h: True)
+ import time as _t
+
+ start = _t.monotonic()
+ ok, _msg = ws.raise_after_launch("spotify", timeout_s=0.05, poll_s=0.005)
+ assert ok is False
+ assert _t.monotonic() - start < 1.0 # bounded by timeout, never wedges
+
+
+def test_raise_after_launch_short_token_skips_polling(monkeypatch):
+ # A 1-2 char token must not poll/match arbitrary windows.
+ called: list[int] = []
+ monkeypatch.setattr(ws, "list_windows", lambda: called.append(1) or [])
+ ok, _msg = ws.raise_after_launch("x", timeout_s=1.0, poll_s=0.001)
+ assert ok is False
+ assert called == [] # returned before any enumeration
+
+
+def test_raise_after_launch_never_raises(monkeypatch):
+ monkeypatch.setattr(ws, "detect_platform", lambda: "win32")
+
+ def boom():
+ raise RuntimeError("enum blew up")
+
+ monkeypatch.setattr(ws, "list_windows", boom)
+ ok, _msg = ws.raise_after_launch("chrome", timeout_s=0.1, poll_s=0.001)
+ assert ok is False
+
+
# --- real smoke on the host platform (non-deterministic, just must not crash)
diff --git a/tests/unit/plugins/stt/test_fwhisper_multilingual_guard.py b/tests/unit/plugins/stt/test_fwhisper_multilingual_guard.py
new file mode 100644
index 0000000000..4cbcda904e
--- /dev/null
+++ b/tests/unit/plugins/stt/test_fwhisper_multilingual_guard.py
@@ -0,0 +1,85 @@
+"""English-only STT model must never be used for a non-English / auto user.
+
+Forensic 2026-06-28 (clipboard screenshot + jarvis.toml): the post-wake STT ran
+``distil-large-v3`` — an ENGLISH-ONLY Distil-Whisper checkpoint — while the user
+spoke German. An English-only Whisper model cannot emit German: fed German audio
+it phonetically mangles it into English words. The live "Listening" bubble showed
+the German "Kannst du mir bitte ..." as "Can't you me my ... Can't you me pl ...".
+``[stt].language = "auto"`` did NOT help, because auto-detect on a model that only
+knows English still only yields English.
+
+Defense-in-depth: ``FasterWhisperProvider`` transparently swaps an English-only
+model for a multilingual checkpoint whenever the recognition language is NOT a
+deliberate ``en`` pin (i.e. ``auto`` / ``de`` / ``es`` / unset). A user who
+explicitly pins ``en`` keeps the fast English-only model.
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.plugins.stt.fwhisper import (
+ FasterWhisperProvider,
+ _multilingual_equivalent,
+)
+
+
+# ---------------------------------------------------------------------------
+# Helper: which models are English-only and what they map to.
+# ---------------------------------------------------------------------------
+
+ ("model", "expected"),
+ [
+ # Distil-Whisper is English-only -> fast multilingual turbo.
+ ("distil-large-v3", "large-v3-turbo"),
+ ("distil-large-v2", "large-v3-turbo"),
+ ("distil-medium.en", "large-v3-turbo"),
+ ("distil-small.en", "large-v3-turbo"),
+ # Plain ``*.en`` Whisper sizes -> drop the suffix (same size, multilingual).
+ ("base.en", "base"),
+ ("small.en", "small"),
+ ("medium.en", "medium"),
+ # Already-multilingual models are left untouched.
+ ("large-v3-turbo", None),
+ ("large-v3", None),
+ ("base", None),
+ ("small", None),
+ # Opaque HuggingFace repo ids are never rewritten.
+ ("Systran/faster-whisper-large-v3", None),
+ ],
+)
+def test_multilingual_equivalent(model: str, expected: str | None) -> None:
+ assert _multilingual_equivalent(model) == expected
+
+
+# ---------------------------------------------------------------------------
+# Constructor guard: non-English / auto upgrades; explicit ``en`` keeps it.
+# ---------------------------------------------------------------------------
+
[email protected]("language", ["auto", None, "de", "es"])
+def test_english_only_model_upgraded_for_non_english(language: str | None) -> None:
+ p = FasterWhisperProvider(model="distil-large-v3", language=language)
+ assert p._model_name == "large-v3-turbo"
+
+
+def test_english_only_model_kept_for_explicit_english_pin() -> None:
+ # A user who deliberately speaks only English keeps the fast English model.
+ p = FasterWhisperProvider(model="distil-large-v3", language="en")
+ assert p._model_name == "distil-large-v3"
+
+
+def test_dot_en_model_stripped_to_multilingual_for_auto() -> None:
+ p = FasterWhisperProvider(model="base.en", language="auto")
+ assert p._model_name == "base"
+
+
+def test_multilingual_model_is_untouched() -> None:
+ p = FasterWhisperProvider(model="large-v3-turbo", language="de")
+ assert p._model_name == "large-v3-turbo"
+
+
+def test_bare_default_provider_is_multilingual_for_autodetect() -> None:
+ # The bare ``FasterWhisperProvider()`` (auto-detect) must not silently fall
+ # onto an English-only model — the default path a bilingual user hits.
+ p = FasterWhisperProvider()
+ assert _multilingual_equivalent(p._model_name) is None
diff --git a/tests/unit/plugins/stt/test_fwhisper_warmup.py b/tests/unit/plugins/stt/test_fwhisper_warmup.py
new file mode 100644
index 0000000000..89df23bb07
--- /dev/null
+++ b/tests/unit/plugins/stt/test_fwhisper_warmup.py
@@ -0,0 +1,83 @@
+"""Wake-model warm-up: the first LIVE transcription must not be cold.
+
+Forensic (2026-06-28): after a fresh boot the user had to say "Hey Jarvis"
+TWICE — the first wake was swallowed, the second worked. Root cause: the boot
+path loaded the wake Whisper model with ``_ensure_model`` (weights into VRAM)
+and immediately reported "listening", but never ran a real inference. On a
+faster-whisper / CTranslate2 CUDA backend the FIRST ``model.transcribe`` pays a
+one-off cold cost (kernel selection/JIT, cuDNN algo search, memory-pool setup)
+of several seconds; steady state is ~100 ms. That cold inference landed on the
+user's first "Hey Jarvis": the rolling-window wake loop blocked on it long
+enough that the wake audio rolled out of the 1.8 s buffer before the transcript
+returned, so the first wake was missed.
+
+``warm_up`` primes the engine with one throwaway inference so the cost is paid
+off the wake path, before the model goes live (and again after the background
+turbo/cuda hot-swap, so the swapped-in model is warm too).
+"""
+from __future__ import annotations
+
+from jarvis.plugins.stt import fwhisper
+from jarvis.plugins.stt.fwhisper import FasterWhisperProvider
+
+
+class _FakeInfo:
+ language = "de"
+
+
+class _CountingModel:
+ """Fake WhisperModel that records how many real inferences ran."""
+
+ def __init__(self) -> None:
+ self.transcribe_calls = 0
+
+ def transcribe(self, audio, **kwargs): # noqa: ANN001, ANN003
+ self.transcribe_calls += 1
+ return iter(()), _FakeInfo()
+
+
+def test_warm_up_runs_a_real_inference_not_just_model_load(monkeypatch) -> None:
+ model = _CountingModel()
+ monkeypatch.setattr(fwhisper, "_new_whisper_model", lambda *a, **k: model)
+
+ p = FasterWhisperProvider(model="base", device="cpu", compute_type="int8")
+ p.warm_up()
+
+ # Model loaded …
+ assert p._model is model
+ # … AND a real inference ran (this is what primes the CUDA/cuDNN kernels so
+ # the user's first "Hey Jarvis" hits a warm engine, not a cold one).
+ assert model.transcribe_calls >= 1
+
+
+def test_warm_up_swallows_inference_failure(monkeypatch) -> None:
+ class _BoomModel:
+ def transcribe(self, audio, **kwargs): # noqa: ANN001, ANN003
+ raise RuntimeError("CUDA kernel boom")
+
+ monkeypatch.setattr(fwhisper, "_new_whisper_model", lambda *a, **k: _BoomModel())
+
+ p = FasterWhisperProvider(model="base", device="cpu", compute_type="int8")
+ # A best-effort prime must NEVER break boot: a warm-up failure is swallowed,
+ # the model stays loaded and still lazy-works on the first real transcribe.
+ p.warm_up()
+
+ assert p._model is not None
+
+
+def test_warm_up_is_idempotent_on_model_load(monkeypatch) -> None:
+ builds: list[_CountingModel] = []
+
+ def factory(name: str, device: str, compute_type: str) -> _CountingModel:
+ m = _CountingModel()
+ builds.append(m)
+ return m
+
+ monkeypatch.setattr(fwhisper, "_new_whisper_model", factory)
+
+ p = FasterWhisperProvider(model="base", device="cpu", compute_type="int8")
+ p.warm_up()
+ p.warm_up()
+
+ # The model is built once and reused — a second prime never reloads weights.
+ assert len(builds) == 1
diff --git a/tests/unit/plugins/stt/test_stt_keyaware_fallback.py b/tests/unit/plugins/stt/test_stt_keyaware_fallback.py
new file mode 100644
index 0000000000..e27cb7aea4
--- /dev/null
+++ b/tests/unit/plugins/stt/test_stt_keyaware_fallback.py
@@ -0,0 +1,68 @@
+"""Key-aware STT fallback: a cloud STT with no usable credential must fall back
+to the local, key-free faster-whisper instead of being constructed and then
+RuntimeError-ing on every utterance.
+
+Open-source resilience (AP-22): the shipped default STT is the cloud `groq-api`,
+but jarvis.toml is gitignored, so a fresh downloader whose single key is for any
+OTHER provider (OpenAI / OpenRouter / Claude / Gemini) would otherwise get a Groq
+instance that raises on the first transcription — bricking ALL voice input. The
+factory must consult "is there actually a key?" and cross over to local Whisper
+when there is not.
+"""
+from __future__ import annotations
+
+from typing import Any
+
+import jarvis.core.config as cfg
+import jarvis.plugins.stt as stt_pkg
+import jarvis.plugins.stt.fwhisper as fwhisper
+from jarvis.core.config import ResolvedEndpoint, STTConfig
+
+
+class _FakeCloudSTT:
+ name = "groq-api"
+
+ def __init__(self, **kwargs: Any) -> None:
+ self.kwargs = kwargs
+
+
+class _FakeLocalSTT:
+ def __init__(self, **kwargs: Any) -> None:
+ self.kwargs = kwargs
+
+
+def _direct_mode(monkeypatch) -> None:
+ """No team proxy: the factory must rely on the user's own key resolution."""
+ monkeypatch.setattr(
+ cfg,
+ "resolve_provider_endpoint",
+ lambda pid, **kw: ResolvedEndpoint(base_url=None, credential=None, via_proxy=False),
+ )
+ monkeypatch.setattr(stt_pkg, "_load_provider_class", lambda name: _FakeCloudSTT)
+ monkeypatch.setattr(fwhisper, "FasterWhisperProvider", _FakeLocalSTT)
+
+
+def test_cloud_stt_without_key_falls_back_to_local(monkeypatch):
+ _direct_mode(monkeypatch)
+ # The user has NO Groq credential anywhere.
+ monkeypatch.setattr(cfg, "get_secret_any", lambda candidates: None)
+
+ provider = stt_pkg.build_stt_from_config(STTConfig(provider="groq-api"))
+
+ assert isinstance(provider, _FakeLocalSTT), (
+ "A cloud STT with no usable key must fall back to local faster-whisper, "
+ "not be constructed and then brick on the first utterance."
+ )
+
+
+def test_cloud_stt_with_key_is_still_used(monkeypatch):
+ _direct_mode(monkeypatch)
+ # The user DOES have a Groq credential — the cloud provider must be used.
+ monkeypatch.setattr(cfg, "get_secret_any", lambda candidates: "gsk-real-key")
+
+ provider = stt_pkg.build_stt_from_config(STTConfig(provider="groq-api"))
+
+ assert isinstance(provider, _FakeCloudSTT), (
+ "When the cloud STT's key IS present, the factory must use the cloud "
+ "provider, not needlessly fall back to local."
+ )
diff --git a/tests/unit/plugins/stt/test_stt_proxy_wiring.py b/tests/unit/plugins/stt/test_stt_proxy_wiring.py
index 4144cbd3a3..e27fc8bbf2 100644
--- a/tests/unit/plugins/stt/test_stt_proxy_wiring.py
+++ b/tests/unit/plugins/stt/test_stt_proxy_wiring.py
@@ -51,6 +51,9 @@ def test_groq_stt_direct_mode_untouched(monkeypatch):
"resolve_provider_endpoint",
lambda pid, **kw: ResolvedEndpoint(base_url=None, credential=None, via_proxy=False),
)
+ # Direct mode requires the user's own key to exist (else the key-aware
+ # factory correctly falls back to local faster-whisper, AP-22).
+ monkeypatch.setattr(cfg, "get_secret_any", lambda candidates: "gsk-direct-key")
stt_pkg.build_stt_from_config(STTConfig(provider="groq-api"))
# Direct mode: factory injects neither endpoint nor api_key — the provider
# falls back to its own DEFAULT_ENDPOINT + key resolution.
diff --git a/tests/unit/plugins/stt/test_wake_whisper_build.py b/tests/unit/plugins/stt/test_wake_whisper_build.py
index bb7874f5af..46a804633b 100644
--- a/tests/unit/plugins/stt/test_wake_whisper_build.py
+++ b/tests/unit/plugins/stt/test_wake_whisper_build.py
@@ -42,15 +42,30 @@ def test_build_wake_whisper_uses_wake_fields_not_utterance_model() -> None:
assert p._compute_type == "int8"
-def test_build_wake_whisper_gpu_turbo_drops_bias_when_cuda() -> None:
- # Capability-gated upgrade (forensic 2026-06-24): on a CUDA box the wake runs
- # the fast turbo model AND drops the bias — the strong model hears the name
- # without it, and the bias on a strong model is what hallucinated the wake
- # onto silence (the false-wake source). Offline-validated 0 false-wakes.
+def test_build_wake_whisper_custom_phrase_keeps_base_cpu_bias_on_cuda() -> None:
+ # Forensic 2026-06-29: turbo WITHOUT the phrase bias MANGLES a short custom
+ # wake phrase ("Hey Nico" -> "cuf ich" -> the wake never fired). The strong
+ # turbo model is still unbiased there, and unbiased recall on a custom proper
+ # noun is poor (2-13% vs 83% with the initial_prompt bias). So a CUSTOM wake
+ # phrase stays on the validated base/cpu + bias config even on a CUDA box; it
+ # does NOT upgrade to turbo-without-bias (which is why the background hot-swap
+ # is a no-op for it — the rebuilt model stays "base"). Supersedes the
+ # 2026-06-24 "turbo drops bias" decision, which only validated false-wakes (0)
+ # and missed that turbo-without-bias also wrecks custom-phrase recall.
p = build_wake_whisper(STTConfig(), wake_phrase="Hey Ruben", cuda_available=True)
+ assert p._model_name == "base"
+ assert p._device == "cpu"
+ assert p._initial_prompt == "Hey Ruben" # bias KEPT — needed to hear the name
+
+
+def test_build_wake_whisper_default_phrase_gets_turbo_no_bias_on_cuda() -> None:
+ # The default "Hey Jarvis" / OWW path carries NO custom bias, so on a CUDA
+ # box it still gets the fast turbo upgrade (no bias means nothing to
+ # hallucinate the wake onto silence).
+ p = build_wake_whisper(STTConfig(), wake_phrase=None, cuda_available=True)
assert p._model_name == "large-v3-turbo"
assert p._device == "cuda"
- assert p._initial_prompt is None # bias OFF on turbo
+ assert p._initial_prompt is None # bias OFF on turbo (no custom phrase)
def test_build_wake_whisper_cpu_keeps_bias() -> None:
@@ -103,3 +118,63 @@ def test_build_wake_whisper_default_has_no_prompt_bias() -> None:
STTConfig(), language="de", wake_phrase=" ", cuda_available=False
)
assert p_blank._initial_prompt is None
+
+
+# --- Persisted CUDA-availability probe (boot-speed fix) ---------------------
+#
+# The first CUDA call (``ctranslate2.get_cuda_device_count``) JIT-compiles
+# kernels for ~30-60 s on a Blackwell GPU and used to run synchronously on the
+# desktop boot path, freezing "VOICE STARTING…". The probe result is a stable
+# hardware fact, so it is cached to disk and skipped on every boot after the
+# first.
+import json # noqa: E402
+
+from jarvis.plugins.stt import _wake_cuda_available, _wake_cuda_cache_path # noqa: E402
+
+
+def test_wake_cuda_cache_path_honours_data_dir_env(tmp_path, monkeypatch) -> None:
+ monkeypatch.setenv("JARVIS__MEMORY__DATA_DIR", str(tmp_path))
+ assert _wake_cuda_cache_path() == tmp_path / "wake_cuda_probe.json"
+
+
+def test_wake_cuda_available_returns_persisted_value_without_probing(
+ tmp_path, monkeypatch
+) -> None:
+ """A cache HIT must return the stored value and never touch ctranslate2."""
+ monkeypatch.setenv("JARVIS__MEMORY__DATA_DIR", str(tmp_path))
+ _wake_cuda_available.cache_clear()
+ (tmp_path / "wake_cuda_probe.json").write_text(
+ json.dumps({"cuda": True}), encoding="utf-8"
+ )
+ # A real probe in CI (no GPU) would return False; a True result therefore
+ # proves the cached value was used, not a fresh probe.
+ assert _wake_cuda_available() is True
+ _wake_cuda_available.cache_clear()
+
+
+def test_wake_cuda_available_writes_cache_on_miss(tmp_path, monkeypatch) -> None:
+ """A cold probe (no cache) must persist its result for the next boot."""
+ monkeypatch.setenv("JARVIS__MEMORY__DATA_DIR", str(tmp_path))
+ _wake_cuda_available.cache_clear()
+ cache_file = tmp_path / "wake_cuda_probe.json"
+ assert not cache_file.exists()
+
+ value = _wake_cuda_available() # CI has no GPU → False, but the path runs.
+
+ assert cache_file.exists()
+ assert json.loads(cache_file.read_text(encoding="utf-8"))["cuda"] == value
+ _wake_cuda_available.cache_clear()
+
+
+def test_wake_cuda_available_survives_corrupt_cache(tmp_path, monkeypatch) -> None:
+ """A corrupt cache file must not break boot — it falls back to a fresh probe."""
+ monkeypatch.setenv("JARVIS__MEMORY__DATA_DIR", str(tmp_path))
+ _wake_cuda_available.cache_clear()
+ cache_file = tmp_path / "wake_cuda_probe.json"
+ cache_file.write_text("{not json", encoding="utf-8")
+
+ # Must not raise; re-probes and overwrites the corrupt file with a valid one.
+ value = _wake_cuda_available()
+ assert isinstance(value, bool)
+ assert json.loads(cache_file.read_text(encoding="utf-8"))["cuda"] == value
+ _wake_cuda_available.cache_clear()
diff --git a/tests/unit/plugins/tool/test_app_resolver.py b/tests/unit/plugins/tool/test_app_resolver.py
index c8680093b0..711d588459 100644
--- a/tests/unit/plugins/tool/test_app_resolver.py
+++ b/tests/unit/plugins/tool/test_app_resolver.py
@@ -190,6 +190,12 @@ async def test_open_app_launches_discord_via_start_menu_shortcut(
expected = str(programs / "Discord Inc" / "Discord.lnk")
started: list[str] = []
monkeypatch.setattr(os, "startfile", lambda target: started.append(target), raising=False)
+ # Force the launch path: this test asserts launch resolution, so the
+ # already-running short-circuit must not fire if Discord happens to be open
+ # on the host (the hardened raise now succeeds where the old focus failed).
+ monkeypatch.setattr(
+ "jarvis.plugins.tool.open_app.window_state.is_app_running", lambda n: None
+ )
result = await OpenAppTool().execute({"app_name": "discord"}, _ctx())
@@ -204,6 +210,12 @@ async def test_open_app_uses_resolved_startfile_target_before_launch(
started: list[str] = []
monkeypatch.setattr(os, "startfile", lambda target: started.append(target), raising=False)
+ # Force the launch path (deterministic regardless of whether Spotify is open
+ # on the host): the already-running short-circuit now succeeds via the
+ # hardened raise, which would otherwise skip the launch this test asserts.
+ monkeypatch.setattr(
+ "jarvis.plugins.tool.open_app.window_state.is_app_running", lambda n: None
+ )
result = await OpenAppTool().execute({"app_name": "spotify"}, _ctx())
diff --git a/tests/unit/plugins/tool/test_click_virtualdesk.py b/tests/unit/plugins/tool/test_click_virtualdesk.py
new file mode 100644
index 0000000000..8800f5e199
--- /dev/null
+++ b/tests/unit/plugins/tool/test_click_virtualdesk.py
@@ -0,0 +1,47 @@
+"""Absolute virtual-desktop click coordinates (audit 🔴 #7).
+
+Clicks dispatched via MOUSEEVENTF_ABSOLUTE | VIRTUALDESK land on their exact
+target on EVERY monitor — including one positioned LEFT of primary (negative
+virtual-desktop X), where the old SetCursorPos-then-relative-click path lands in
+the void. _normalize_virtualdesk folds the (possibly negative) virtual origin
+into a 0..65535 coordinate; these guard that math.
+"""
+from __future__ import annotations
+
+from jarvis.plugins.tool.click import _normalize_virtualdesk
+
+# The reported two-monitor rig: left monitor at X<0 (-2560..0), main 4K at 0..3840.
+_VX, _VY, _VW, _VH = -2560, 0, 6400, 2160
+
+
+def test_left_monitor_negative_x_maps_to_valid_positive_coord():
+ nx, ny = _normalize_virtualdesk(-1280, 720, _VX, _VY, _VW, _VH)
+ assert 0 <= nx <= 65535 and 0 <= ny <= 65535
+ assert 13000 < nx < 13200 # ~20% across the virtual desktop = left-monitor centre
+ assert 21700 < ny < 22000
+
+
+def test_main_monitor_maps_to_right_portion():
+ nx, _ny = _normalize_virtualdesk(1920, 1080, _VX, _VY, _VW, _VH)
+ assert 45700 < nx < 46050 # ~70% across = main-monitor centre
+
+
+def test_left_is_left_of_main():
+ nx_left, _ = _normalize_virtualdesk(-1280, 720, _VX, _VY, _VW, _VH)
+ nx_main, _ = _normalize_virtualdesk(1920, 1080, _VX, _VY, _VW, _VH)
+ assert nx_left < nx_main
+
+
+def test_origin_corner_is_zero():
+ assert _normalize_virtualdesk(_VX, _VY, _VX, _VY, _VW, _VH) == (0, 0)
+
+
+def test_clamps_out_of_bounds():
+ assert _normalize_virtualdesk(-99999, -99999, _VX, _VY, _VW, _VH) == (0, 0)
+ assert _normalize_virtualdesk(99999, 99999, _VX, _VY, _VW, _VH) == (65535, 65535)
+
+
+def test_single_monitor_at_origin_maps_linearly():
+ # Primary-only 1920x1080: centre -> ~32767.
+ nx, ny = _normalize_virtualdesk(960, 540, 0, 0, 1920, 1080)
+ assert 32700 < nx < 32830 and 32700 < ny < 32830
diff --git a/tests/unit/plugins/tool/test_computer_use_tool.py b/tests/unit/plugins/tool/test_computer_use_tool.py
index 5b72ddf03f..6097996363 100644
--- a/tests/unit/plugins/tool/test_computer_use_tool.py
+++ b/tests/unit/plugins/tool/test_computer_use_tool.py
@@ -396,6 +396,50 @@ async def test_success_readback_surfaces_verifier_observation() -> None:
assert text != action_phrase("cu_done", "en"), "must not be the content-free Done phrase"
+# ---------------------------------------------------------------------------
+# Output-language threading to the verifier (fix 2026-06-27). The verifier's
+# spoken `proof` was English even in a German turn ("Erledigt — The file explorer
+# window is open ..."). The resolved turn output language must reach the harness
+# via task.env so the verifier writes proof in the user's language. This pins the
+# whole chain: tool → dispatch_to_harness → HarnessTask.env.
+# ---------------------------------------------------------------------------
+
+
+class _EnvCapturingManager(_FakeHarnessManager):
+ def __init__(self) -> None:
+ super().__init__()
+ self.task_envs: list[dict] = []
+
+ async def dispatch(self, name, task) -> AsyncIterator[HarnessResult]:
+ self.task_envs.append(dict(getattr(task, "env", None) or {}))
+ self.dispatched.append((name, task.prompt))
+ yield HarnessResult(stdout="[cu] done at step 1", exit_code=0, is_final=True)
+
+
+async def test_tool_threads_output_language_into_harness_env() -> None:
+ from jarvis.harness.screenshot_only_loop import _OUTPUT_LANGUAGE_ENV_KEY
+ from jarvis.plugins.tool.computer_use_tool import ComputerUseTool
+
+ bus = _FakeBus()
+ fake = _EnvCapturingManager()
+ tool = ComputerUseTool(bus=bus, manager=fake)
+
+ # A German conversation (loop-stamped output language) must arrive at the
+ # harness as env["JARVIS_OUTPUT_LANGUAGE"] = "de".
+ ctx = ExecutionContext(
+ trace_id=uuid.uuid4(),
+ user_utterance="öffne den explorer", # i18n-allow: DE fixture
+ config={"output_language": "de"},
+ memory_read=None,
+ )
+ result = await tool.execute({"goal": "öffne den explorer"}, ctx) # i18n-allow: DE fixture
+ assert result.success
+
+ await _collect_completion(bus)
+ assert fake.task_envs, "harness was never dispatched"
+ assert fake.task_envs[0].get(_OUTPUT_LANGUAGE_ENV_KEY) == "de"
+
+
async def test_success_readback_falls_back_to_done_without_proof() -> None:
from jarvis.plugins.tool.computer_use_tool import ComputerUseTool
from jarvis.voice.action_phrases import action_phrase
diff --git a/tests/unit/plugins/tool/test_drag.py b/tests/unit/plugins/tool/test_drag.py
new file mode 100644
index 0000000000..d9a338910c
--- /dev/null
+++ b/tests/unit/plugins/tool/test_drag.py
@@ -0,0 +1,90 @@
+"""DragTool — press-and-hold drag routed through the ToolExecutor (audit #13).
+
+The drag gesture used to run inline in the CU loop, bypassing the risk-tier /
+blacklist / audit path. It is now a real tool. These cover its arg validation,
+the success readback, and graceful failure when the desktop backend is absent —
+without driving the real mouse (``_perform_drag`` is monkeypatched).
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.plugins.tool import drag as drag_mod
+from jarvis.plugins.tool.drag import DragTool
+
+
+def _no_real_mouse(monkeypatch):
+ calls: list[tuple] = []
+
+ def _fake(x1, y1, x2, y2, duration_s):
+ calls.append((x1, y1, x2, y2, duration_s))
+
+ monkeypatch.setattr(drag_mod, "_perform_drag", _fake)
+ return calls
+
+
+async def test_drag_success_calls_backend_with_pixels(_no_real_mouse):
+ res = await DragTool().execute(
+ {"x1": 100, "y1": 200, "x2": 300, "y2": 400, "duration_ms": 500},
+ SimpleNamespace(),
+ )
+ assert res.success is True
+ assert "(100,200)->(300,400)" in res.output
+ assert _no_real_mouse == [(100, 200, 300, 400, 0.5)]
+
+
+async def test_drag_defaults_duration_when_omitted(_no_real_mouse):
+ await DragTool().execute(
+ {"x1": 0, "y1": 0, "x2": 10, "y2": 10}, SimpleNamespace()
+ )
+ # default 400 ms -> 0.4 s
+ assert _no_real_mouse[0][4] == pytest.approx(0.4)
+
+
+async def test_drag_rejects_non_integer_coords(_no_real_mouse):
+ res = await DragTool().execute(
+ {"x1": "nope", "y1": 0, "x2": 10, "y2": 10}, SimpleNamespace()
+ )
+ assert res.success is False
+ assert "integer" in (res.error or "")
+ assert _no_real_mouse == [] # never touched the mouse on bad input
+
+
+async def test_drag_missing_coord_fails_cleanly(_no_real_mouse):
+ res = await DragTool().execute({"x1": 0, "y1": 0, "x2": 10}, SimpleNamespace())
+ assert res.success is False
+ assert _no_real_mouse == []
+
+
+async def test_drag_reports_backend_error(monkeypatch):
+ def _boom(*_a, **_k):
+ raise RuntimeError("display gone")
+
+ monkeypatch.setattr(drag_mod, "_perform_drag", _boom)
+ res = await DragTool().execute(
+ {"x1": 0, "y1": 0, "x2": 10, "y2": 10}, SimpleNamespace()
+ )
+ assert res.success is False
+ assert "failed" in (res.error or "")
+
+
+async def test_drag_reports_missing_pyautogui(monkeypatch):
+ def _no_pyautogui(*_a, **_k):
+ raise ImportError("No module named 'pyautogui'")
+
+ monkeypatch.setattr(drag_mod, "_perform_drag", _no_pyautogui)
+ res = await DragTool().execute(
+ {"x1": 0, "y1": 0, "x2": 10, "y2": 10}, SimpleNamespace()
+ )
+ assert res.success is False
+ assert "pyautogui" in (res.error or "")
+
+
+def test_drag_tool_identity():
+ t = DragTool()
+ assert t.name == "drag"
+ assert t.risk_tier == "monitor"
+ assert {"x1", "y1", "x2", "y2"} <= set(t.schema["required"])
diff --git a/tests/unit/plugins/tool/test_google_calendar_rest.py b/tests/unit/plugins/tool/test_google_calendar_rest.py
new file mode 100644
index 0000000000..6559a0dca1
--- /dev/null
+++ b/tests/unit/plugins/tool/test_google_calendar_rest.py
@@ -0,0 +1,238 @@
+"""google_calendar tool: a thin Python bridge over the JS/Node calendar bot.
+
+These tests mock the Node call boundary (``node_runner``) so they run without
+Node and without the network, the same way the Gmail tests mock the httpx
+transport. They lock the contract: action → payload, 401 → one refresh + retry,
+full autonomy (no action is ever ``ask``), and graceful "not connected" /
+"node missing" behavior.
+"""
+
+import pytest
+
+from jarvis.plugins.tool.google_calendar_rest import (
+ GoogleCalendarRestTool,
+ _default_node_runner,
+)
+
+
+def _ok(data):
+ return {"ok": True, "data": data}
+
+
+async def test_list_events_passes_window_and_token():
+ captured = {}
+
+ async def runner(action, args, token):
+ captured["action"] = action
+ captured["args"] = args
+ captured["bearer"] = token
+ return _ok({"events": [{"id": "e1", "summary": "Standup"}]})
+
+ tool = GoogleCalendarRestTool(
+ access_token_provider=lambda: "at_123", node_runner=runner
+ )
+ out = await tool.list_events(time_min="2026-06-28T00:00:00", time_max="2026-06-28T23:59:59")
+ assert out["data"]["events"][0]["id"] == "e1"
+ assert captured["action"] == "list_events"
+ assert captured["bearer"] == "at_123"
+ assert captured["args"]["time_min"] == "2026-06-28T00:00:00"
+
+
+async def test_create_event_builds_payload():
+ captured = {}
+
+ async def runner(action, args, token):
+ captured["action"] = action
+ captured["args"] = args
+ return _ok({"id": "new1", "summary": "Lunch"})
+
+ tool = GoogleCalendarRestTool(
+ access_token_provider=lambda: "at_123", node_runner=runner
+ )
+ out = await tool.create_event(
+ summary="Lunch", start="2026-06-28T12:00:00", end="2026-06-28T13:00:00",
+ time_zone="Europe/Berlin",
+ )
+ assert out["data"]["id"] == "new1"
+ assert captured["action"] == "create_event"
+ assert captured["args"]["summary"] == "Lunch"
+ assert captured["args"]["time_zone"] == "Europe/Berlin"
+
+
+async def test_delete_event_passes_id():
+ captured = {}
+
+ async def runner(action, args, token):
+ captured["action"] = action
+ captured["args"] = args
+ return _ok({"deleted": "e9"})
+
+ tool = GoogleCalendarRestTool(
+ access_token_provider=lambda: "at_123", node_runner=runner
+ )
+ out = await tool.delete_event(event_id="e9")
+ assert out["data"]["deleted"] == "e9"
+ assert captured["action"] == "delete_event"
+ assert captured["args"]["event_id"] == "e9"
+
+
+async def test_delete_passes_calendar_id_for_secondary_calendar():
+ # An event found by list_events on a non-primary calendar must be deletable
+ # by threading its calendar_id back through — else delete hits 'primary' and
+ # 404s. (Root cause of the "found nothing / can't touch it" lesson bug.)
+ captured = {}
+
+ async def runner(action, args, token):
+ captured["args"] = args
+ return _ok({"deleted": "e9", "calendar_id": "[email protected]"})
+
+ tool = GoogleCalendarRestTool(
+ access_token_provider=lambda: "at_123", node_runner=runner
+ )
+ out = await tool.execute(
+ {"action": "delete_event", "event_id": "e9",
+ "calendar_id": "[email protected]"},
+ ctx=None,
+ )
+ assert out.success is True
+ assert captured["args"]["calendar_id"] == "[email protected]"
+
+
+async def test_execute_returns_error_when_not_connected():
+ tool = GoogleCalendarRestTool(access_token_provider=lambda: None)
+ result = await tool.execute({"action": "list_events"}, ctx=None)
+ assert result.success is False
+ assert "connect" in (result.error or "").lower()
+
+
+async def test_refreshes_on_401_then_retries():
+ # An expired access token → the bot reports status 401. The bridge must
+ # refresh once and retry — the same self-heal as Gmail.
+ calls = {"n": 0, "refresh": 0}
+
+ async def runner(action, args, token):
+ calls["n"] += 1
+ if calls["n"] == 1:
+ return {"ok": False, "status": 401, "error": "Calendar API 401"}
+ return _ok({"events": [{"id": "ok9"}]})
+
+ async def refresher():
+ calls["refresh"] += 1
+ return True
+
+ tool = GoogleCalendarRestTool(
+ access_token_provider=lambda: "at_dead",
+ node_runner=runner,
+ token_refresher=refresher,
+ )
+ out = await tool.list_events()
+ assert out["data"]["events"][0]["id"] == "ok9"
+ assert calls["refresh"] == 1
+ assert calls["n"] == 2 # retried exactly once after a successful refresh
+
+
+async def test_returns_reconnect_error_when_refresh_fails():
+ async def runner(action, args, token):
+ return {"ok": False, "status": 401, "error": "Calendar API 401"}
+
+ async def refresher():
+ return False # un-healable (revoked / invalid_client)
+
+ tool = GoogleCalendarRestTool(
+ access_token_provider=lambda: "at_dead",
+ node_runner=runner,
+ token_refresher=refresher,
+ )
+ result = await tool.execute({"action": "list_events"}, ctx=None)
+ assert result.success is False
+ assert "reconnect" in (result.error or "").lower()
+
+
+async def test_non_401_error_is_not_retried():
+ # A 500 is not an auth problem — do not refresh, do not retry.
+ calls = {"n": 0, "refresh": 0}
+
+ async def runner(action, args, token):
+ calls["n"] += 1
+ return {"ok": False, "status": 500, "error": "Calendar API 500"}
+
+ async def refresher():
+ calls["refresh"] += 1
+ return True
+
+ tool = GoogleCalendarRestTool(
+ access_token_provider=lambda: "at_123",
+ node_runner=runner,
+ token_refresher=refresher,
+ )
+ result = await tool.execute({"action": "list_events"}, ctx=None)
+ assert result.success is False
+ assert calls["refresh"] == 0
+ assert calls["n"] == 1
+
+
+async def test_execute_missing_required_fields():
+ tool = GoogleCalendarRestTool(access_token_provider=lambda: "at_1")
+ # create without summary
+ r1 = await tool.execute({"action": "create_event", "start": "x", "end": "y"}, ctx=None)
+ assert r1.success is False and "summary" in (r1.error or "")
+ # update without id
+ r2 = await tool.execute({"action": "update_event", "summary": "z"}, ctx=None)
+ assert r2.success is False and "event_id" in (r2.error or "")
+ # delete without id
+ r3 = await tool.execute({"action": "delete_event"}, ctx=None)
+ assert r3.success is False and "event_id" in (r3.error or "")
+
+
+def test_tool_contract_shape():
+ tool = GoogleCalendarRestTool()
+ assert tool.name == "google_calendar"
+ assert tool.risk_tier == "monitor"
+ assert "schema" in dir(tool)
+
+
+# ----------------------------------------------------------------------
+# Full autonomy (user mandate): NO action is ever gated behind ``ask`` —
+# read is safe, every write is monitor (executed without a prompt, audited).
+# ----------------------------------------------------------------------
+
+
+def test_risk_tier_read_is_safe():
+ tool = GoogleCalendarRestTool(access_token_provider=lambda: "x")
+ assert tool.risk_tier_for_args({"action": "list_events"}) == "safe"
+ assert tool.risk_tier_for_args({}) == "safe" # defaults to list_events
+
+
+def test_risk_tier_writes_are_monitor_never_ask():
+ tool = GoogleCalendarRestTool(access_token_provider=lambda: "x")
+ for action in ("create_event", "update_event", "delete_event"):
+ tier = tool.risk_tier_for_args({"action": action})
+ assert tier == "monitor", f"{action} should be monitor, got {tier}"
+ assert tier != "ask"
+
+
+def test_risk_tier_unknown_action_is_not_safe():
+ # An unrecognised action must not silently become safe; the monitor default
+ # keeps an audit trail without a prompt.
+ tool = GoogleCalendarRestTool(access_token_provider=lambda: "x")
+ assert tool.risk_tier_for_args({"action": "purge_all"}) == "monitor"
+
+
+async def test_node_runner_graceful_when_node_missing(monkeypatch):
+ # If `node` is not on PATH the bridge degrades to a clear error, never a crash.
+ import shutil
+
+ monkeypatch.setattr(shutil, "which", lambda _name: None)
+ out = await _default_node_runner("list_events", {}, "at_1")
+ assert out["ok"] is False
+ assert "node" in out["error"].lower()
diff --git a/tests/unit/plugins/tool/test_open_app_reuse.py b/tests/unit/plugins/tool/test_open_app_reuse.py
index f836169ebd..3eba4e1655 100644
--- a/tests/unit/plugins/tool/test_open_app_reuse.py
+++ b/tests/unit/plugins/tool/test_open_app_reuse.py
@@ -27,28 +27,34 @@ def _ctx() -> ExecutionContext:
def _stub_launch(monkeypatch) -> list:
- """Stub resolve + Popen so no real process starts; return the Popen call log."""
+ """Stub resolve + Popen so no real process starts; return the Popen call log.
+
+ Also stubs the post-launch foreground raise to a fast no-op so the launch
+ tests stay deterministic and host-independent (the real raise polls
+ list_windows for up to 3 s). Tests that care about the raise re-stub it.
+ """
calls: list = []
monkeypatch.setattr(
oa, "resolve_app_launch_target",
lambda n: types.SimpleNamespace(kind="executable", value=r"C:\fake\obs.exe"),
)
monkeypatch.setattr(oa.subprocess, "Popen", lambda *a, **k: calls.append((a, k)))
+ monkeypatch.setattr(oa.window_state, "raise_after_launch", lambda n, **k: (False, ""))
return calls
async def test_focuses_when_already_running(monkeypatch):
calls = _stub_launch(monkeypatch)
monkeypatch.setattr(oa.window_state, "is_app_running", lambda n: WindowInfo("OBS 30.0.0"))
- focused: list = []
+ raised: list = []
monkeypatch.setattr(
- oa.window_state, "focus_window", lambda t: (focused.append(t), (True, t))[1]
+ oa.window_state, "raise_window", lambda w: (raised.append(w.title), (True, w.title))[1]
)
res = await OpenAppTool().execute({"app_name": "obs"}, _ctx())
assert res.success is True
assert "already running" in (res.output or "").lower()
assert calls == [] # never launched a second instance
- assert focused # focus was attempted
+ assert raised # hardened raise was attempted on the existing window
async def test_launches_when_not_running(monkeypatch):
@@ -63,14 +69,14 @@ async def test_launches_when_not_running(monkeypatch):
async def test_multi_instance_app_always_launches(monkeypatch):
calls = _stub_launch(monkeypatch)
monkeypatch.setattr(oa.window_state, "is_app_running", lambda n: WindowInfo("File Explorer"))
- focused: list = []
+ raised: list = []
monkeypatch.setattr(
- oa.window_state, "focus_window", lambda t: (focused.append(t), (True, t))[1]
+ oa.window_state, "raise_window", lambda w: (raised.append(w.title), (True, w.title))[1]
)
res = await OpenAppTool().execute({"app_name": "explorer"}, _ctx())
assert res.success is True
assert len(calls) == 1 # explorer is multi-instance -> launch anyway
- assert focused == [] # short-circuit skipped, never focused
+ assert raised == [] # short-circuit skipped, never raised
async def test_reuse_existing_false_always_launches(monkeypatch):
@@ -84,10 +90,10 @@ async def test_reuse_existing_false_always_launches(monkeypatch):
async def test_focus_failure_falls_through_to_launch(monkeypatch):
calls = _stub_launch(monkeypatch)
monkeypatch.setattr(oa.window_state, "is_app_running", lambda n: WindowInfo("OBS 30"))
- monkeypatch.setattr(oa.window_state, "focus_window", lambda t: (False, "lock timeout"))
+ monkeypatch.setattr(oa.window_state, "raise_window", lambda w: (False, "lock timeout"))
res = await OpenAppTool().execute({"app_name": "obs"}, _ctx())
assert res.success is True
- assert "Gestartet" in (res.output or "") # launched after focus failed
+ assert "Gestartet" in (res.output or "") # launched after the raise failed
assert len(calls) == 1
@@ -100,3 +106,62 @@ async def test_url_is_not_short_circuited(monkeypatch):
res = await OpenAppTool().execute({"app_name": "https://example.com"}, _ctx())
assert res.success is True
assert seen == [] # URL must not be treated as an app to focus
+
+
+# --- post-launch foreground raise (the "opens in background" bug) ------------
+
+
+async def test_fresh_launch_raises_window_to_foreground(monkeypatch):
+ calls = _stub_launch(monkeypatch)
+ monkeypatch.setattr(oa.window_state, "is_app_running", lambda n: None)
+ raised: list = []
+ monkeypatch.setattr(
+ oa.window_state, "raise_after_launch",
+ lambda n, **k: (raised.append(n), (True, "New Tab - Google Chrome"))[1],
+ )
+ res = await OpenAppTool().execute({"app_name": "chrome"}, _ctx())
+ assert res.success is True
+ assert len(calls) == 1 # launched once
+ assert raised == ["chrome"] # and actively pulled to the front
+ assert "vorn" in (res.output or "").lower() # honest readback
+
+
+async def test_raise_miss_keeps_success(monkeypatch):
+ # The launch already succeeded; a foreground-raise miss must NOT flip the
+ # result to failure — it only softens the readback back to plain "Gestartet".
+ calls = _stub_launch(monkeypatch)
+ monkeypatch.setattr(oa.window_state, "is_app_running", lambda n: None)
+ monkeypatch.setattr(oa.window_state, "raise_after_launch", lambda n, **k: (False, "no window"))
+ res = await OpenAppTool().execute({"app_name": "chrome"}, _ctx())
+ assert res.success is True
+ assert "Gestartet" in (res.output or "")
+ assert "vorn" not in (res.output or "").lower()
+ assert len(calls) == 1
+
+
+async def test_raise_crash_never_breaks_launch(monkeypatch):
+ calls = _stub_launch(monkeypatch)
+ monkeypatch.setattr(oa.window_state, "is_app_running", lambda n: None)
+
+ def boom(_n, **_k):
+ raise RuntimeError("focus blew up")
+
+ monkeypatch.setattr(oa.window_state, "raise_after_launch", boom)
+ res = await OpenAppTool().execute({"app_name": "chrome"}, _ctx())
+ assert res.success is True # crash in the raise never fails the launch
+ assert "Gestartet" in (res.output or "")
+ assert len(calls) == 1
+
+
+async def test_url_launch_does_not_raise(monkeypatch):
+ # A URL reuses an existing browser window; the app-name raise would not
+ # apply, so it must be skipped (no pointless 3 s poll).
+ _stub_launch(monkeypatch)
+ monkeypatch.setattr(oa.window_state, "is_app_running", lambda n: None)
+ raised: list = []
+ monkeypatch.setattr(
+ oa.window_state, "raise_after_launch", lambda n, **k: raised.append(n) or (True, n)
+ )
+ res = await OpenAppTool().execute({"app_name": "https://example.com"}, _ctx())
+ assert res.success is True
+ assert raised == [] # raise skipped for URLs
diff --git a/tests/unit/plugins/tool/test_profile_update.py b/tests/unit/plugins/tool/test_profile_update.py
index 3c47e5f7eb..8306f287ff 100644
--- a/tests/unit/plugins/tool/test_profile_update.py
+++ b/tests/unit/plugins/tool/test_profile_update.py
@@ -15,7 +15,12 @@ import pytest
from jarvis.core.bus import EventBus
from jarvis.core.events import ProfileUpdated
from jarvis.memory.user_profile import UserProfile
-from jarvis.plugins.tool.profile_update import _CANONICAL_FIELDS, UpdateProfileTool
+from jarvis.plugins.tool.profile_update import (
+ _BOOL_FIELDS,
+ _CANONICAL_FIELDS,
+ _LIST_FIELDS,
+ UpdateProfileTool,
+)
def test_canonical_fields_match_matrix_ui():
@@ -43,6 +48,25 @@ def test_canonical_fields_match_matrix_ui():
"CLUSTER_FIELD_KEYS — a writable-but-invisible field is silent enum drift."
)
+
+def test_list_and_bool_field_shapes_match_ui_editor():
+ """The list/bool field shapes MUST mirror ledger.ts (LIST_FIELD_KEYS /
+ BOOL_FIELD_KEYS), which drives the inline Profile editor: a list field is
+ edited as chips (append/remove), a bool as a yes/no toggle. If these drift,
+ the editor sends an operation the PATCH /api/profile/field endpoint rejects
+ with 400 (e.g. a "set" on a field the UI thinks is scalar). Keep this in sync
+ with jarvis/ui/web/frontend/src/views/profile/ledger.ts.
+ """
+ list_field_names = {field for _cluster, field in _LIST_FIELDS}
+ assert list_field_names == {
+ "languages", "devices", "humor_types", "top_values", "pet_peeves", "motivations",
+ }
+ bool_field_names = {field for _cluster, field in _BOOL_FIELDS}
+ assert bool_field_names == {"emoji_ok"}
+ # Every list/bool field must be a real, writable field.
+ for cluster, field in _LIST_FIELDS | _BOOL_FIELDS:
+ assert field in _CANONICAL_FIELDS[cluster]
+
_SEED = """---
schema_version: 1
subject_type: user
diff --git a/tests/unit/plugins/tool/test_search_web.py b/tests/unit/plugins/tool/test_search_web.py
index 6b1c8d0879..26ebd0b6af 100644
--- a/tests/unit/plugins/tool/test_search_web.py
+++ b/tests/unit/plugins/tool/test_search_web.py
@@ -64,3 +64,34 @@ async def test_execute_empty_has_no_detail(monkeypatch: pytest.MonkeyPatch) -> N
async def test_execute_missing_query_still_fails() -> None:
result = await SearchWebTool().execute({"query": " "}, _ctx())
assert result.success is False
+
+
+async def test_execute_ok_carries_synthesis_instruction(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A result set with hits MUST tell the brain to synthesize, not read the
+ raw hits aloud. Live forensic 2026-06-28 (voice Turn 4): Gemini read a whole
+ DuckDuckGo result list verbatim — titles, dates, 'Weitere Ergebnisse von
+ www.gutefrage.net' — instead of answering the question."""
+ async def fake_run_search(query, max_results, *, client, searcher=None):
+ return SearchOutcome(
+ results=[{"title": "Notenschluessel", "snippet": "43 bis 34,5 = Note 2",
+ "url": "https://www.gutefrage.net/x"}],
+ backend="ddg_serp", status="ok")
+ monkeypatch.setattr(search_web, "run_search", fake_run_search)
+ result = await SearchWebTool().execute({"query": "wie viele punkte note 1"}, _ctx())
+ instr = (result.output.get("answer_instruction") or "").lower()
+ assert instr, "ok result must carry an answer_instruction"
+ # It must steer the brain away from reading titles / URLs / source names.
+ assert "url" in instr
+ assert "never" in instr
+
+
+async def test_execute_empty_has_no_synthesis_instruction(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def fake_run_search(query, max_results, *, client, searcher=None):
+ return SearchOutcome(results=[], backend="ddg", status="empty")
+ monkeypatch.setattr(search_web, "run_search", fake_run_search)
+ result = await SearchWebTool().execute({"query": "asdfqwer"}, _ctx())
+ assert "answer_instruction" not in result.output
diff --git a/tests/unit/self_mod/test_pending_store.py b/tests/unit/self_mod/test_pending_store.py
new file mode 100644
index 0000000000..506704f946
--- /dev/null
+++ b/tests/unit/self_mod/test_pending_store.py
@@ -0,0 +1,79 @@
+"""Tests for the PendingMutationStore auto-apply policy (Wave 1.3).
+
+The voice path applies every change immediately ("never ask, always now"), while
+REST/CLI keep the SAFE-auto / ASK-confirm split. The store carries the policy:
+``auto_apply="all"`` applies any non-forbidden tier at once; the default
+``"safe_only"`` preserves today's behaviour.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import tomllib
+
+import pytest
+
+from jarvis.core.config import JarvisConfig
+from jarvis.core.self_mod import (
+ AtomicConfigWriter,
+ PendingMutationStore,
+ SecretAccessError,
+ SelfModAudit,
+)
+from jarvis.core.self_mod.schema import MutationRequest
+
+FIXTURE = Path(__file__).parent / "fixtures" / "minimal_jarvis.toml"
+
+
+def _isolated_loader(path: Path) -> JarvisConfig:
+ raw = path.read_bytes()
+ if raw.startswith(b"\xef\xbb\xbf"):
+ raw = raw[3:]
+ return JarvisConfig.model_validate(tomllib.loads(raw.decode("utf-8")))
+
+
+def writer(tmp_path: Path) -> AtomicConfigWriter:
+ target = tmp_path / "jarvis.toml"
+ target.write_text(FIXTURE.read_text(encoding="utf-8"), encoding="utf-8")
+ return AtomicConfigWriter(
+ config_path=target,
+ backup_dir=tmp_path / "backups",
+ audit=SelfModAudit(path=tmp_path / "audit.log"),
+ config_loader=_isolated_loader,
+ )
+
+
+def _req(path: str, value: object) -> MutationRequest:
+ return MutationRequest(path=path, new_value=value, reason="test")
+
+
+class TestAutoApplyAll:
+ def test_applies_ask_tier_immediately(self, writer: AtomicConfigWriter) -> None:
+ # tts.provider is ASK-tier; under "all" it applies without confirmation.
+ store = PendingMutationStore(writer=writer, auto_apply="all")
+ pending = store.create(_req("tts.provider", "elevenlabs"))
+ assert pending.applied is True
+ assert pending.needs_confirmation is False
+ assert len(store) == 0 # nothing parked in the pending bucket
+
+ def test_still_refuses_forbidden(self, writer: AtomicConfigWriter) -> None:
+ store = PendingMutationStore(writer=writer, auto_apply="all")
+ with pytest.raises(SecretAccessError):
+ store.create(_req("security.admin_password_hash", "x"))
+
+
+class TestDefaultSafeOnly:
+ def test_defers_ask_tier(self, writer: AtomicConfigWriter) -> None:
+ # The default policy keeps ASK-tier in the bucket for confirmation.
+ store = PendingMutationStore(writer=writer)
+ pending = store.create(_req("tts.provider", "elevenlabs"))
+ assert pending.applied is False
+ assert pending.needs_confirmation is True
+ assert len(store) == 1
+
+ def test_applies_safe_tier(self, writer: AtomicConfigWriter) -> None:
+ store = PendingMutationStore(writer=writer)
+ pending = store.create(_req("tts.speed", 1.25))
+ assert pending.applied is True
+ assert pending.needs_confirmation is False
diff --git a/tests/unit/self_mod/test_registry.py b/tests/unit/self_mod/test_registry.py
index e3483deabd..c5b575fb2e 100644
--- a/tests/unit/self_mod/test_registry.py
+++ b/tests/unit/self_mod/test_registry.py
@@ -10,7 +10,6 @@ from __future__ import annotations
import pytest
from pydantic import BaseModel, ValidationError
-import jarvis.core.config as cfg_module
from jarvis.core.self_mod import (
FORBIDDEN_PATTERNS,
AllowlistViolationError,
@@ -18,14 +17,13 @@ from jarvis.core.self_mod import (
SecretAccessError,
SelfModRegistry,
)
+from jarvis.core.self_mod.schema_introspect import resolve_model_for_path
-# Plan-§7.1 table + voice-tunable computer_use.step_budget (the field the
-# screenshot loop actually reads; the legacy max_steps field was a no-op) +
-# the language keys added 2026-06-08 for the Jarvis Control API. The canonical
-# reply-language path is ``brain.reply_language`` (SAFE); ``profile.language``
-# is kept (legacy, no runtime effect) so old configs/flows keep validating.
-# 12 paths in the current allowlist.
-EXPECTED_PATHS = {
+# The 13 CURATED paths — since Wave 1.1 the mutable set is derived from the
+# whole JarvisConfig schema, but these keep their human-judgement overrides
+# (risk_tier / needs_restart / description). They must remain present and keep
+# those attributes; the rest of the schema is now mutable too with safe defaults.
+CURATED_PATHS = {
"tts.provider",
"tts.voice_de",
"tts.voice_en",
@@ -54,14 +52,13 @@ RESTART_REQUIRED_PATHS = {
class TestListAll:
- def test_returns_thirteen_specs(self) -> None:
- # 9 historical paths + brain.reply_language/stt.language/tts.language_code
- # + ui.language (interface language, live-synced to the frontend).
- assert len(SelfModRegistry.list_all()) == 13
+ def test_returns_many_specs(self) -> None:
+ # Wave 1.1: the set is schema-derived now, not a 13-entry hand-list.
+ assert len(SelfModRegistry.list_all()) > 50
- def test_returns_expected_paths(self) -> None:
+ def test_curated_paths_remain_present(self) -> None:
paths = {spec.path for spec in SelfModRegistry.list_all()}
- assert paths == EXPECTED_PATHS
+ assert CURATED_PATHS <= paths
def test_returns_independent_list_each_call(self) -> None:
a = SelfModRegistry.list_all()
@@ -78,7 +75,7 @@ class TestListAll:
class TestIsMutable:
- @pytest.mark.parametrize("path", sorted(EXPECTED_PATHS))
+ @pytest.mark.parametrize("path", sorted(CURATED_PATHS))
def test_returns_true_for_allowed_path(self, path: str) -> None:
assert SelfModRegistry.is_mutable(path) is True
@@ -147,7 +144,7 @@ class TestGetSpec:
)
def test_ask_tier_paths_match_plan(self) -> None:
- for path in EXPECTED_PATHS - SAFE_TIER_PATHS:
+ for path in CURATED_PATHS - SAFE_TIER_PATHS:
spec = SelfModRegistry.get_spec(path)
assert spec is not None
assert spec.risk_tier == "ask", (
@@ -155,11 +152,13 @@ class TestGetSpec:
)
def test_restart_flags_match_plan(self) -> None:
- """Plan-§7.1-Tabelle: stt.provider und brain.primary brauchen Restart."""
- for spec in SelfModRegistry.list_all():
- expected = spec.path in RESTART_REQUIRED_PATHS
+ """Curated paths keep their overridden needs_restart flag."""
+ for path in CURATED_PATHS:
+ spec = SelfModRegistry.get_spec(path)
+ assert spec is not None
+ expected = path in RESTART_REQUIRED_PATHS
assert spec.needs_restart is expected, (
- f"needs_restart-Flag von {spec.path} weicht vom Plan ab"
+ f"needs_restart flag of {path} deviates from the override table"
)
@@ -282,7 +281,7 @@ class TestNoConfigFileIO:
assert not (tmp_path / "jarvis.toml").exists()
# Alle drei Public-API-Aufrufe müssen funktionieren.
- assert len(SelfModRegistry.list_all()) == 13
+ assert len(SelfModRegistry.list_all()) > 50
assert SelfModRegistry.is_mutable("tts.provider") is True
assert SelfModRegistry.is_mutable("security.admin_password_hash") is False
spec = SelfModRegistry.get_spec("brain.primary")
@@ -304,13 +303,15 @@ class TestAllowlistFieldParity:
@pytest.mark.parametrize("spec", SelfModRegistry.list_all(), ids=lambda s: s.path)
def test_model_and_field_exist(self, spec: MutableSpec) -> None:
- model = getattr(cfg_module, spec.pydantic_model_name, None)
- assert model is not None, (
- f"{spec.path}: pydantic_model_name '{spec.pydantic_model_name}' "
- "does not exist in jarvis.core.config"
- )
- assert isinstance(model, type) and issubclass(model, BaseModel), (
- f"{spec.path}: '{spec.pydantic_model_name}' is not a Pydantic model"
+ # Resolve the owning model by navigating JarvisConfig along the path,
+ # not getattr(config, name): a submodule section model (e.g.
+ # AwarenessPrivacyConfig) is never re-exported into config, but it is
+ # still the real owner. This is the stronger anti-drift check.
+ model = resolve_model_for_path(spec.path)
+ assert issubclass(model, BaseModel)
+ assert model.__name__ == spec.pydantic_model_name, (
+ f"{spec.path}: spec names '{spec.pydantic_model_name}' but the "
+ f"owning model is '{model.__name__}'"
)
# A declared field is the strict case. A model with extra="allow"
# legitimately stores undeclared keys (e.g. ui.theme on UIConfig), so
diff --git a/tests/unit/self_mod/test_schema_introspect.py b/tests/unit/self_mod/test_schema_introspect.py
new file mode 100644
index 0000000000..b6f1be352f
--- /dev/null
+++ b/tests/unit/self_mod/test_schema_introspect.py
@@ -0,0 +1,231 @@
+"""Tests for the schema introspector (Voice-First Config Control, Wave 1.1).
+
+The introspector walks ``JarvisConfig`` and emits one ``MutableSpec`` per leaf
+primitive field, so the voice-mutable set is derived from the schema instead of
+a hand-maintained list. Secrets / self-lockout paths are excluded; a curated
+override table refines risk_tier / needs_restart / description for known paths.
+"""
+from __future__ import annotations
+
+import pytest
+from pydantic import BaseModel
+
+from jarvis.core.self_mod.registry import FORBIDDEN_PATTERNS, SelfModRegistry
+from jarvis.core.self_mod.schema import MutableSpec
+from jarvis.core.self_mod.schema_introspect import (
+ SpecOverride,
+ describe_field,
+ introspect_mutable_specs,
+ resolve_model_for_path,
+)
+
+
+def _paths(specs: tuple[MutableSpec, ...]) -> set[str]:
+ return {s.path for s in specs}
+
+
+class TestReach:
+ def test_deep_nested_primitive_field_is_mutable(self) -> None:
+ # A leaf two levels deep that is NOT in today's 13-entry list — proves
+ # the reach now spans the whole schema, not a curated subset.
+ paths = _paths(introspect_mutable_specs())
+ assert "brain.plausibility.confidence_threshold" in paths
+ assert "brain.policy.prompt_cache_heartbeat_seconds" in paths
+
+ def test_top_level_primitive_field_is_mutable(self) -> None:
+ paths = _paths(introspect_mutable_specs())
+ assert "tts.speed" in paths
+ assert "stt.bias_prompt" in paths
+
+ def test_literal_enum_field_is_mutable(self) -> None:
+ # ui.language is Literal["en","de","es"] — a constrained string, fully
+ # settable by voice. A Literal must count as a primitive leaf.
+ paths = _paths(introspect_mutable_specs())
+ assert "ui.language" in paths
+
+ def test_emits_far_more_than_the_legacy_handful(self) -> None:
+ # The hand-list had 13; the schema has hundreds of leaves.
+ assert len(introspect_mutable_specs()) > 50
+
+
+class TestExclusions:
+ @pytest.mark.parametrize("prefix", ["security.", "safety.", "harness.", "mcp_server."])
+ def test_forbidden_sections_excluded(self, prefix: str) -> None:
+ paths = _paths(introspect_mutable_specs())
+ assert not any(p.startswith(prefix) for p in paths), (
+ f"forbidden prefix {prefix} leaked into the mutable set"
+ )
+
+ def test_no_emitted_path_matches_forbidden_patterns(self) -> None:
+ for spec in introspect_mutable_specs():
+ assert not SelfModRegistry.is_forbidden(spec.path), (
+ f"{spec.path} overlaps FORBIDDEN_PATTERNS"
+ )
+
+ def test_list_and_dict_fields_skipped(self) -> None:
+ # brain.policy.voice_switch_patterns is a list[str] — not a scalar the
+ # dotted-path writer can set, so it must not appear.
+ paths = _paths(introspect_mutable_specs())
+ assert "brain.policy.voice_switch_patterns" not in paths
+
+ def test_self_lockout_provider_list_not_mutable(self) -> None:
+ # brain.providers.enabled is a list — the only "kill the active brain"
+ # vector. Because the walker skips lists, it is unreachable by voice, so
+ # a user can never empty the provider list and lock out the brain. This
+ # is the architectural self-lockout guard (no broad deny pattern needed).
+ paths = _paths(introspect_mutable_specs())
+ assert not any(p.endswith(".enabled") and "provider" in p for p in paths)
+
+
+class TestSpecShape:
+ def test_pydantic_model_name_and_field_resolve(self) -> None:
+ # Every emitted spec must point at a real (or extra-allowed) field on the
+ # model that actually owns it in the schema — the TestAllowlistFieldParity
+ # contract, applied to the whole introspected set via schema navigation
+ # (more robust than getattr(config, name): covers submodule section
+ # models like AwarenessPrivacyConfig that config never re-exports).
+ for spec in introspect_mutable_specs():
+ model = resolve_model_for_path(spec.path)
+ assert issubclass(model, BaseModel)
+ assert model.__name__ == spec.pydantic_model_name, (
+ f"{spec.path}: spec names '{spec.pydantic_model_name}' but the "
+ f"owning model is '{model.__name__}'"
+ )
+ declared = spec.field_name in model.model_fields
+ allows_extra = model.model_config.get("extra") == "allow"
+ assert declared or allows_extra, (
+ f"{spec.path}: field '{spec.field_name}' not on "
+ f"{spec.pydantic_model_name} and extras forbidden"
+ )
+
+ def test_containing_class_is_used_not_root(self) -> None:
+ spec = next(
+ s for s in introspect_mutable_specs()
+ if s.path == "brain.plausibility.confidence_threshold"
+ )
+ assert spec.pydantic_model_name == "BrainPlausibilityConfig"
+ assert spec.field_name == "confidence_threshold"
+
+ def test_unknown_field_defaults_to_needs_restart_true(self) -> None:
+ # A field with no override gets the safe, honest "restart to be sure".
+ spec = next(
+ s for s in introspect_mutable_specs()
+ if s.path == "brain.policy.prompt_cache_heartbeat_seconds"
+ )
+ assert spec.needs_restart is True
+
+
+class TestOverrides:
+ def test_override_wins_over_auto_derivation(self) -> None:
+ overrides = {
+ "tts.speed": SpecOverride(
+ risk_tier="safe", needs_restart=False, description="Speech speed"
+ ),
+ }
+ spec = next(
+ s for s in introspect_mutable_specs(overrides=overrides)
+ if s.path == "tts.speed"
+ )
+ assert spec.risk_tier == "safe"
+ assert spec.needs_restart is False
+ assert spec.description == "Speech speed"
+
+ def test_override_can_force_an_undeclared_extra_key(self) -> None:
+ # ui.theme is an undeclared extra="allow" key on UIConfig — the schema
+ # walk can't see it. An override carrying pydantic_model_name + field_name
+ # force-includes it.
+ overrides = {
+ "ui.theme": SpecOverride(
+ risk_tier="safe", needs_restart=False,
+ pydantic_model_name="UIConfig", field_name="theme",
+ description="UI theme",
+ ),
+ }
+ spec = next(
+ (s for s in introspect_mutable_specs(overrides=overrides)
+ if s.path == "ui.theme"), None
+ )
+ assert spec is not None
+ assert spec.pydantic_model_name == "UIConfig"
+ assert spec.field_name == "theme"
+ assert spec.risk_tier == "safe"
+
+ def test_override_does_not_force_a_forbidden_path(self) -> None:
+ # A forced extra key still cannot override the deny layer.
+ overrides = {
+ "security.admin_password_hash": SpecOverride(
+ pydantic_model_name="SecurityConfig", field_name="admin_password_hash",
+ ),
+ }
+ paths = _paths(introspect_mutable_specs(overrides=overrides))
+ assert "security.admin_password_hash" not in paths
+
+ def test_forbidden_patterns_constant_still_exported(self) -> None:
+ # Sanity: the introspector relies on the registry's forbidden set.
+ assert "security.*" in FORBIDDEN_PATTERNS
+
+
+class TestDescribeField:
+ """Wave 2: value type + constraints, the material the brain needs to map a
+ natural-language phrase ("talk slower") onto a concrete (path, value)."""
+
+ def test_int_with_range(self) -> None:
+ d = describe_field("computer_use.max_steps")
+ assert d["value_type"] == "int"
+ assert d["minimum"] == 1
+ assert d["maximum"] == 1000
+
+ def test_float_with_exclusive_min(self) -> None:
+ d = describe_field("computer_use.per_step_timeout_s")
+ assert d["value_type"] == "float"
+ assert d["exclusive_minimum"] == 0.0
+ assert d["maximum"] == 300.0
+
+ def test_bool(self) -> None:
+ d = describe_field("computer_use.enabled")
+ assert d["value_type"] == "bool"
+
+ def test_enum_literal(self) -> None:
+ d = describe_field("ui.language")
+ assert d["value_type"] == "enum"
+ assert set(d["allowed_values"]) == {"en", "de", "es"}
+
+ def test_undeclared_extra_key_is_graceful(self) -> None:
+ # ui.theme is an extra="allow" key — no declared type to read.
+ d = describe_field("ui.theme")
+ assert d["value_type"] == "unknown"
+
+ def test_unknown_path_is_graceful(self) -> None:
+ d = describe_field("totally.made.up.path")
+ assert d["value_type"] == "unknown"
+
+
+class TestDescribeField:
+ """Value-type + constraint extraction for NL value-mapping (Wave 2)."""
+
+ def test_int_with_range(self) -> None:
+ d = describe_field("computer_use.max_steps")
+ assert d["value_type"] == "int"
+ assert d["minimum"] == 1
+ assert d["maximum"] == 1000
+
+ def test_float_with_exclusive_min(self) -> None:
+ d = describe_field("computer_use.per_step_timeout_s")
+ assert d["value_type"] == "float"
+ assert d.get("exclusive_minimum") == 0.0
+ assert d["maximum"] == 300.0
+
+ def test_bool(self) -> None:
+ assert describe_field("computer_use.enabled")["value_type"] == "bool"
+
+ def test_enum_literal_lists_allowed_values(self) -> None:
+ d = describe_field("ui.language")
+ assert d["value_type"] == "enum"
+ assert set(d["allowed_values"]) == {"en", "de", "es"}
+
+ def test_undeclared_extra_key_is_graceful(self) -> None:
+ # ui.theme is an undeclared extra="allow" key — no schema type.
+ assert describe_field("ui.theme")["value_type"] in ("str", "unknown")
+
+ def test_unknown_path_is_graceful(self) -> None:
+ assert describe_field("totally.made.up.path")["value_type"] == "unknown"
diff --git a/tests/unit/self_mod/test_writer.py b/tests/unit/self_mod/test_writer.py
index 4ddac98bc9..8995f6b652 100644
--- a/tests/unit/self_mod/test_writer.py
+++ b/tests/unit/self_mod/test_writer.py
@@ -257,7 +257,9 @@ class TestAllowlistRejection:
entries = _read_audit_lines(audit_log)
assert len(entries) == 1
assert entries[0]["ok"] is False
- assert "ALLOWED" in entries[0]["error"]
+ # Wave 1.1 reworded the allowlist-violation message (the set is now the
+ # schema minus the deny layer, no longer a literal ALLOWED tuple).
+ assert "not a mutable config setting" in entries[0]["error"]
def test_secret_path_raises_secret_access(
self, writer: AtomicConfigWriter
diff --git a/tests/unit/self_mod/test_writer_readonly.py b/tests/unit/self_mod/test_writer_readonly.py
new file mode 100644
index 0000000000..5da1ddddf1
--- /dev/null
+++ b/tests/unit/self_mod/test_writer_readonly.py
@@ -0,0 +1,78 @@
+"""Writer robustness against a read-only target (config-drift defense, BUG-010).
+
+The drift defense sets jarvis.toml read-only to stop parallel sessions from
+silently overwriting it. The AUTHORIZED atomic writer is itself part of that
+defense, so it must still get through: on Windows os.replace fails with WinError
+5 (Access Denied) when the target is read-only. The writer must clear the
+attribute for the atomic swap and restore it afterwards — keeping the defense in
+place. Live forensic 2026-06-25: every CLI/voice config write returned
+"write_failed: [WinError 5] Zugriff verweigert ... jarvis.toml".
+"""
+from __future__ import annotations
+
+import os
+import stat
+import tomllib
+from pathlib import Path
+
+import pytest
+
+from jarvis.core.config import JarvisConfig
+from jarvis.core.self_mod import AtomicConfigWriter, SelfModAudit
+from jarvis.core.self_mod.schema import MutationRequest
+
+FIXTURE = Path(__file__).parent / "fixtures" / "minimal_jarvis.toml"
+
+
+def _loader(path: Path) -> JarvisConfig:
+ raw = path.read_bytes()
+ if raw.startswith(b"\xef\xbb\xbf"):
+ raw = raw[3:]
+ return JarvisConfig.model_validate(tomllib.loads(raw.decode("utf-8")))
+
+
+def _read_speed(target: Path) -> float:
+ raw = target.read_bytes()
+ if raw.startswith(b"\xef\xbb\xbf"):
+ raw = raw[3:]
+ return tomllib.loads(raw.decode("utf-8"))["tts"]["speed"]
+
+
+def writer_and_target(tmp_path: Path):
+ target = tmp_path / "jarvis.toml"
+ target.write_text(FIXTURE.read_text(encoding="utf-8"), encoding="utf-8")
+ writer = AtomicConfigWriter(
+ config_path=target,
+ backup_dir=tmp_path / "backups",
+ audit=SelfModAudit(path=tmp_path / "audit.log"),
+ config_loader=_loader,
+ )
+ return writer, target
+
+
+def test_mutate_succeeds_when_target_is_readonly(writer_and_target) -> None:
+ writer, target = writer_and_target
+ os.chmod(target, stat.S_IREAD) # config-drift defense: read-only
+ assert not os.access(target, os.W_OK), "precondition: target is read-only"
+
+ result = writer.mutate(
+ MutationRequest(path="tts.speed", new_value=1.25, reason="test")
+ )
+
+ assert result.ok is True, f"write must succeed on a read-only target: {result.error_message}"
+ assert _read_speed(target) == 1.25 # the value actually landed on disk
+ # The drift defense is preserved: the file is read-only again afterwards.
+ assert not os.access(target, os.W_OK)
+
+
+def test_mutate_leaves_writable_target_writable(writer_and_target) -> None:
+ # State-preserving: a normally-writable target stays writable (no surprise
+ # read-only attribute introduced by the writer).
+ writer, target = writer_and_target
+ assert os.access(target, os.W_OK)
+ result = writer.mutate(
+ MutationRequest(path="tts.speed", new_value=0.9, reason="test")
+ )
+ assert result.ok is True
+ assert os.access(target, os.W_OK)
diff --git a/tests/unit/skills/test_authoring_service.py b/tests/unit/skills/test_authoring_service.py
index f5dc84cc71..269d5c9a25 100644
--- a/tests/unit/skills/test_authoring_service.py
+++ b/tests/unit/skills/test_authoring_service.py
@@ -81,7 +81,9 @@ async def test_create_skill_is_on_by_default(
"""A user who fills the form and hits Create expects an active skill —
not a draft they have to flip on. No explicit state → VALIDATED ("on")."""
svc = _service(registry, skills_root)
- await svc.create(SkillCreateRequest(name="Active One", body="## x\n"))
+ await svc.create(
+ SkillCreateRequest(name="Active One", body="## Active One\n\nDo the active thing.\n")
+ )
skill = registry.get("Active One")
assert skill.state in (
SkillLifecycleState.VALIDATED,
@@ -97,7 +99,7 @@ async def test_create_persists_voice_trigger(
await svc.create(
SkillCreateRequest(
name="Trigger Skill",
- body="## x\n",
+ body="## Trigger Skill\n\nDo the thing when invoked.\n",
triggers=({"type": "voice", "pattern": "^do the thing"},),
)
)
@@ -113,9 +115,13 @@ async def test_create_rejects_duplicate_name(
registry: SkillRegistry, skills_root: Path
) -> None:
svc = _service(registry, skills_root)
- await svc.create(SkillCreateRequest(name="Dup Skill", body="## x\n"))
+ await svc.create(
+ SkillCreateRequest(name="Dup Skill", body="## Dup Skill\n\nFirst body.\n")
+ )
with pytest.raises(SkillAuthoringError) as exc:
- await svc.create(SkillCreateRequest(name="Dup Skill", body="## y\n"))
+ await svc.create(
+ SkillCreateRequest(name="Dup Skill", body="## Dup Skill\n\nSecond body.\n")
+ )
assert exc.value.status == 409
@@ -150,5 +156,56 @@ async def test_create_rejects_name_that_slugs_to_nothing(
not a path-traversal or an empty-dir write."""
svc = _service(registry, skills_root)
with pytest.raises(SkillAuthoringError) as exc:
- await svc.create(SkillCreateRequest(name="!!!", body="## x\n"))
+ await svc.create(
+ SkillCreateRequest(name="!!!", body="## x\n\nDo something.\n")
+ )
+ assert exc.value.status == 400
+
+
+# ----------------------------------------------------------------------
+# Body must carry real instructions — the root cause of the "Hallo Hallo
+# Hallo" forensic: a skill created with no instructions in its body is
+# functionless (run-skill loads an empty body → the brain does nothing).
+# A skill with only a heading / whitespace must be refused at 400 so no
+# path (UI form, REST, AI-commit) can persist a dead skill.
+# ----------------------------------------------------------------------
+
+
+async def test_create_rejects_empty_body(
+ registry: SkillRegistry, skills_root: Path
+) -> None:
+ svc = _service(registry, skills_root)
+ with pytest.raises(SkillAuthoringError) as exc:
+ await svc.create(SkillCreateRequest(name="Empty Body", body=""))
assert exc.value.status == 400
+ assert not (skills_root / "empty-body").exists()
+
+
+async def test_create_rejects_heading_only_body(
+ registry: SkillRegistry, skills_root: Path
+) -> None:
+ """Just ``## Title`` (the default when the form body is left blank) is not
+ a usable skill — this is exactly the Hallo-Hallo-Hallo failure."""
+ svc = _service(registry, skills_root)
+ with pytest.raises(SkillAuthoringError) as exc:
+ await svc.create(
+ SkillCreateRequest(name="Hallo Hallo Hallo", body="## Hallo Hallo Hallo\n")
+ )
+ assert exc.value.status == 400
+ assert not (skills_root / "hallo-hallo-hallo").exists()
+
+
+async def test_create_accepts_body_with_instructions(
+ registry: SkillRegistry, skills_root: Path
+) -> None:
+ svc = _service(registry, skills_root)
+ created = await svc.create(
+ SkillCreateRequest(
+ name="Good Skill",
+ body="## Good Skill\n\nReply with a cheerful greeting.\n",
+ )
+ )
+ assert created.name == "Good Skill"
diff --git a/tests/unit/skills/test_prompt_injection.py b/tests/unit/skills/test_prompt_injection.py
index 22bd95928b..c4a2243b4d 100644
--- a/tests/unit/skills/test_prompt_injection.py
+++ b/tests/unit/skills/test_prompt_injection.py
@@ -194,6 +194,32 @@ def test_framing_mentions_instruction_loading() -> None:
assert "instructions" in out
+def test_framing_is_imperative_and_skill_first() -> None:
+ """Claude-Code-parity stance (2026-06-24): the listing must push the brain
+ to check skills BEFORE answering/spawning and to prefer calling a skill on
+ a loose match — not a passive "when it matches" note. Locks the framing so a
+ future edit cannot silently revert to the weak wording that made skills
+ never fire.
+ """
+ registry = _FakeRegistry(skills=[
+ _FakeSkill(name="demo", frontmatter=_FakeFrontmatter(description="Does X.")),
+ ])
+
+ out = render_available_skills_section(registry) # type: ignore[arg-type]
+
+ assert out is not None
+ lowered = out.lower()
+ # Imperative "must call run-skill first", and the before-answer/spawn check.
+ assert "must call" in lowered
+ assert "before you answer" in lowered
+ assert "spawn a worker" in lowered
+ # Loose-match stance ("even loosely" / prefer calling when unsure).
+ assert "even loosely" in lowered
+ assert "prefer calling" in lowered
+ # Over-fire guard is present (a topic mention is not a skill match).
+ assert "what is gmail" in lowered
+
+
# ----------------------------------------------------------------------
# AD-S2 L1: total char budget with least-recently-modified eviction
# ----------------------------------------------------------------------
diff --git a/tests/unit/speech/test_dictation_stale_hangup.py b/tests/unit/speech/test_dictation_stale_hangup.py
new file mode 100644
index 0000000000..bf50df6682
--- /dev/null
+++ b/tests/unit/speech/test_dictation_stale_hangup.py
@@ -0,0 +1,68 @@
+"""Regression test: chat mic-dictation must not inherit a stale hangup.
+
+User-reported symptom (2026-06-28): clicking the chat mic button starts
+dictation and it *immediately* stops again — the recording never stays open.
+
+Root cause: ``_hangup_event`` ("auflegen" — the hard voice kill-switch) is set
+on every voice hangup and only ever cleared when the NEXT voice session is
+accepted (``_run_session`` loop). The transcribe-only dictation lane shares that
+event in its ``asyncio.wait({stop, hangup, drain})`` gate, so a leftover hangup
+from an earlier voice call makes ``hangup_task`` complete instantly →
+``FIRST_COMPLETED`` returns → the session finalizes → a final
+``DictationTranscript`` flips the UI ``dictating`` flag back to false the moment
+it went true.
+
+A fresh dictation session must start clean, mirroring the voice path's
+``self._hangup_event.clear()`` at session accept. This pins that contract.
+"""
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from jarvis.speech.pipeline import PipelineState, SpeechPipeline
+
+
+class _StubSTT:
+ async def transcribe_pcm(self, pcm: bytes): # pragma: no cover - never called
+ raise AssertionError("dictation session must not run in this unit test")
+
+
+def _make_idle_pipeline() -> SpeechPipeline:
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._utterance_stt = _StubSTT()
+ pipe._dictation_task = None
+ pipe._dictation_stop_event = asyncio.Event()
+ pipe._ptt_mode = False
+ pipe._state = PipelineState.IDLE
+ pipe._input_device = "default"
+ # Stale hangup left over from a previous voice call that was never followed
+ # by a fresh voice session (so the voice-path clear never ran).
+ pipe._hangup_event = asyncio.Event()
+ pipe._hangup_event.set()
+ return pipe
+
+
+async def test_start_dictation_clears_stale_hangup() -> None:
+ pipe = _make_idle_pipeline()
+ assert pipe._hangup_event.is_set() # precondition: stale hangup present
+
+ started = pipe.start_dictation()
+
+ # Cancel the spawned session immediately — we only assert on the synchronous
+ # state set BEFORE the mic-touching task body runs.
+ task = pipe._dictation_task
+ if task is not None:
+ task.cancel()
+ try:
+ await task
+ except (asyncio.CancelledError, Exception): # noqa: BLE001
+ pass
+
+ assert started is True
+ assert not pipe._hangup_event.is_set(), (
+ "start_dictation must clear a stale hangup so the session is not "
+ "finalized on its first wait tick"
+ )
diff --git a/tests/unit/speech/test_hangup_cancels_chat_turn.py b/tests/unit/speech/test_hangup_cancels_chat_turn.py
index babe3229c9..6abe5691f1 100644
--- a/tests/unit/speech/test_hangup_cancels_chat_turn.py
+++ b/tests/unit/speech/test_hangup_cancels_chat_turn.py
@@ -1,6 +1,6 @@
"""The voice-hangup chokepoint must also cancel an in-flight CHAT turn.
-Live bug 2026-06-19: the whisper-bar X (``request_hangup`` → ``_trigger_voice_hangup``)
+Live bug 2026-06-19: the jarvis-bar X (``request_hangup`` → ``_trigger_voice_hangup``)
set the voice ``_hangup_event`` and cancelled active Computer-Use, but a chat
turn dispatched through ``desktop_app._on_user_message`` runs on a separate path
that ignored the X — so the brain kept thinking through ~27 X presses. The fix
diff --git a/tests/unit/speech/test_subagent_readback.py b/tests/unit/speech/test_jarvis_agent_readback.py
similarity index 100%
rename from tests/unit/speech/test_subagent_readback.py
rename to tests/unit/speech/test_jarvis_agent_readback.py
diff --git a/tests/unit/speech/test_pipeline_mute_toggle.py b/tests/unit/speech/test_pipeline_mute_toggle.py
index 72cbb9164e..45307cb811 100644
--- a/tests/unit/speech/test_pipeline_mute_toggle.py
+++ b/tests/unit/speech/test_pipeline_mute_toggle.py
@@ -4,8 +4,10 @@ Trigger surface: the desktop mascot publishes ``VoiceMuteToggleRequested``
when the user double-clicks the sprite. The pipeline must:
1. Flip ``self._muted`` (and expose it via ``is_muted``).
-2. Stop in-flight playback so the user is not stuck listening to a
- sentence that started before the click.
+2. Leave Jarvis's in-flight voice ALONE — mute is input-only (maintainer
+ intent 2026-06-29: "mute my mic for Jarvis, do not mute Jarvis"). Calling
+ ``player.stop()`` here used to abort the output stream mid-write and wedge
+ the WASAPI device, killing the wake-mic afterwards.
3. Reject wake activations through ``_activation_allowed`` while muted.
4. Suppress every ``AnnouncementRequested`` / ``_speak`` exit while muted.
5. Broadcast a follow-up ``VoiceMuteChanged`` for UI / overlay mirrors.
@@ -122,14 +124,26 @@ async def test_mute_suppresses_announcements() -> None:
@pytest.mark.asyncio
-async def test_mute_stops_inflight_playback() -> None:
- """Mute should immediately silence what is currently coming out."""
+async def test_mute_does_not_stop_inflight_playback() -> None:
+ """Mute is INPUT-ONLY: it must NOT abort Jarvis's in-flight voice.
+
+ The maintainer asked for "mute my mic FOR Jarvis, do not mute Jarvis — other
+ things keep working" (2026-06-29). The old behaviour called ``player.stop()``
+ on mute, which ran ``stream.abort()`` (Pa_AbortStream) mid-TTS-write. That
+ (a) contradicted the input-only intent and (b) wedged the shared WASAPI
+ device: the next wake-mic opened "successfully" but delivered only dead/silent
+ frames (no rolling-whisper transcripts, and the 3 s no-chunk Mic-Stall
+ watchdog never fired because chunks kept arriving), so "Hey <wake>" silently
+ stopped working after a mute-during-speech + hangup. Jarvis now finishes the
+ current sentence; new ``_speak`` calls stay suppressed and input frames are
+ dropped at our boundary (see ``test_session_input_is_dropped_while_muted``).
+ """
bus = EventBus()
pipeline, _tts, player = _make_pipeline(bus)
assert player.stop_calls == 0
await bus.publish(VoiceMuteToggleRequested(source="mascot_dblclick"))
- assert player.stop_calls == 1
+ assert player.stop_calls == 0 # mute no longer aborts the output stream
@pytest.mark.asyncio
@@ -145,6 +159,40 @@ async def test_speak_short_circuits_when_muted() -> None:
assert player.plays == 0
+async def test_session_input_is_dropped_while_muted() -> None:
+ """Input mute: while muted Jarvis must STOP HEARING the user mid-session.
+
+ The mute flag gated wake activation + TTS output, but the active-session
+ input stream (mic -> VAD -> STT) ignored it, so a user who muted during a
+ conversation kept being heard ("ich rede, aber er hoert mich trotzdem",
+ 2026-06-28). Muting drops every frame at Jarvis' input boundary WITHOUT
+ touching the OS mic, so other apps still get the microphone.
+ """
+ bus = EventBus()
+ pipeline, _tts, _player = _make_pipeline(bus)
+
+ async def _src() -> AsyncIterator[AudioChunk]:
+ for i in range(3):
+ yield AudioChunk(
+ pcm=b"\x01\x00" * 1600, sample_rate=16_000, timestamp_ns=i + 1
+ )
+
+ # Unmuted: every frame reaches the VAD.
+ out = [c async for c in pipeline._session_input_stream(_src())]
+ assert len(out) == 3
+
+ # Muted: every frame is dropped — Jarvis is deaf to the user.
+ await bus.publish(VoiceMuteToggleRequested(source="mascot_dblclick"))
+ out_muted = [c async for c in pipeline._session_input_stream(_src())]
+ assert out_muted == []
+
+ # Unmute again: hearing resumes.
+ await bus.publish(VoiceMuteToggleRequested(source="mascot_dblclick"))
+ out_resumed = [c async for c in pipeline._session_input_stream(_src())]
+ assert len(out_resumed) == 3
+
+
@pytest.mark.asyncio
async def test_activation_gate_blocked_even_when_external_gate_says_yes() -> None:
"""Mute must beat the external gate — UI saying ``yes`` cannot un-mute."""
diff --git a/tests/unit/speech/test_rolling_whisper_wake_timeout.py b/tests/unit/speech/test_rolling_whisper_wake_timeout.py
new file mode 100644
index 0000000000..22f0c2fbd0
--- /dev/null
+++ b/tests/unit/speech/test_rolling_whisper_wake_timeout.py
@@ -0,0 +1,111 @@
+"""RollingWhisperWake must self-heal from a hung local-Whisper transcription.
+
+Live forensic (2026-06-29, data/jarvis_desktop.log): a user with a custom wake
+word ("Hey Nico" -> engine=stt_match -> RollingWhisperWake) said the wake word
+for minutes with no reaction. The log showed the chunk-consumer heartbeat ALIVE
+(audio flowing, max-rms up to 0.27 while speaking) but the poll loop emitted ZERO
+``rolling-whisper:`` transcripts for 12 minutes after a single mid-session line —
+and the frozen ``last-transcript`` proved ``_last_transcript`` never updated. No
+error was logged. That is a SILENT hang inside ``await stt.transcribe_pcm(...)``:
+the local faster-whisper call blocked and never returned, so the poll loop waited
+forever and the wake word was permanently dead (the "sometimes stops waking
+entirely" symptom; the "no dead state blocks waking" requirement).
+
+The fix is the same per-call cap the OWW prefix-verifier already uses
+(``wake_verifier._WAKE_VERIFY_TIMEOUT_S``): bound each transcription with
+``asyncio.wait_for`` so a hung STT is abandoned and the loop re-polls fresh audio
+instead of freezing.
+"""
+from __future__ import annotations
+
+import asyncio
+
+import numpy as np
+
+from jarvis.core.protocols import AudioChunk, Transcript
+from jarvis.speech.rolling_whisper_wake import RollingWhisperWake
+
+
+def _loud_chunk(marker: int, n: int = 1600) -> AudioChunk:
+ val = 12000 + (marker % 80) * 100 # < 32767, well above min_peak
+ arr = np.full(n, val, dtype=np.int16)
+ return AudioChunk(pcm=arr.tobytes(), sample_rate=16000, timestamp_ns=0)
+
+
+class _HangFirstThenMatchSTT:
+ """First ``transcribe_pcm`` hangs forever; later calls return a match.
+
+ Mirrors the live wedge: one transcription blocks indefinitely (here on an
+ Event the test never sets), every subsequent call transcribes normally.
+ """
+
+ def __init__(self, phrase: str) -> None:
+ self._phrase = phrase
+ self.calls = 0
+ self._hang = asyncio.Event() # never set -> first call blocks until cancelled
+
+ async def transcribe_pcm(
+ self, pcm: bytes, sample_rate: int = 16000, language: str | None = None
+ ) -> Transcript:
+ self.calls += 1
+ if self.calls == 1:
+ await self._hang.wait() # the wedge: blocks until wait_for cancels it
+ return Transcript(text=self._phrase, language="de", confidence=0.9)
+
+
+async def test_hung_transcription_does_not_freeze_wake_forever() -> None:
+ import re
+
+ stt = _HangFirstThenMatchSTT("hey nico")
+ wake = RollingWhisperWake(
+ stt,
+ pattern=re.compile(r"hey\W+nico", re.IGNORECASE),
+ poll_interval_s=0.01,
+ cooldown_s=0.0,
+ save_debug_wavs=False,
+ min_rms=0.0,
+ min_peak=0.0,
+ transcribe_timeout_s=0.15, # abandon a hung transcription fast (test)
+ )
+
+ src: asyncio.Queue = asyncio.Queue()
+ stop_feed = asyncio.Event()
+
+ async def _iter():
+ while True:
+ chunk = await src.get()
+ if chunk is None:
+ return
+ yield chunk
+
+ async def _feed() -> None:
+ i = 0
+ while not stop_feed.is_set():
+ await src.put(_loud_chunk(i))
+ i += 1
+ await asyncio.sleep(0.002)
+
+ async def _first_keyword() -> str:
+ async for kw in wake.detect(_iter()):
+ return kw
+ return ""
+
+ feeder = asyncio.create_task(_feed())
+ try:
+ # Without the per-call timeout, the poll loop blocks forever on the first
+ # (hung) transcription and this wait_for trips -> the wake is dead. With
+ # the timeout, the first call is abandoned, the loop re-polls, the second
+ # call matches, and the keyword is yielded.
+ kw = await asyncio.wait_for(_first_keyword(), timeout=3.0)
+ assert kw.lower() == "hey nico"
+ assert stt.calls >= 2, (
+ f"poll loop never retried after the hung first call (calls={stt.calls})"
+ )
+ finally:
+ stop_feed.set()
+ await src.put(None)
+ feeder.cancel()
+ try:
+ await feeder
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
+ pass
diff --git a/tests/unit/speech/test_spawn_watchdog.py b/tests/unit/speech/test_spawn_watchdog.py
index 58398b24cc..1b1976e299 100644
--- a/tests/unit/speech/test_spawn_watchdog.py
+++ b/tests/unit/speech/test_spawn_watchdog.py
@@ -413,3 +413,29 @@ async def test_heartbeat_dropped_not_deferred_while_user_holds_floor() -> None:
"stale heartbeat was deferred — kind='progress' must be DROPPED so it "
"never replays after the user finishes or after the answer"
)
+
+
+async def test_heartbeat_dropped_not_deferred_while_turn_is_processing() -> None:
+ """A background heartbeat must not speak during a new foreground turn.
+
+ Live regression 2026-06-25: a Notion research mission heartbeat fired while
+ Jarvis was processing a simple election question. The user heard "still on
+ it" instead of immediate progress on the foreground answer, and the shared
+ audio progress counter polluted that turn's playback watchdog. A progress
+ beat is ephemeral, so it is dropped rather than queued.
+ """
+ from jarvis.speech.pipeline import TurnTakingState
+
+ bus = EventBus()
+ pipe = _pipeline(bus, watchdog_delay_s=0.03)
+ pipe._turn_state = TurnTakingState.PROCESSING
+
+ await bus.publish(OpenClawAnnouncement(action="bauen", target="x"))
+ await asyncio.sleep(0.2) # heartbeat fires into _on_announcement
+
+ assert pipe._player.plays == [], "heartbeat was spoken during a foreground turn"
+ assert pipe._deferred_announcements == [], (
+ "stale heartbeat was deferred; progress beats must be dropped during "
+ "active foreground turns"
+ )
diff --git a/tests/unit/speech/test_speak_playback_timeout.py b/tests/unit/speech/test_speak_playback_timeout.py
index d1fd348997..b94508f569 100644
--- a/tests/unit/speech/test_speak_playback_timeout.py
+++ b/tests/unit/speech/test_speak_playback_timeout.py
@@ -69,6 +69,33 @@ class HangingPlayer:
self._release.set()
+@dataclass
+class OwnerTaggedNoFramePlayer:
+ """A turn playback that has not produced its own first frame yet.
+
+ Another playback, such as a mission-progress announcement, can update the
+ player's global write-progress counter while this task is still waiting.
+ The pipeline watchdog must ignore that unrelated progress.
+ """
+
+ last_write_ns: int = 0
+ last_write_owner_task_id: int | None = None
+ stop_calls: int = 0
+ _release: asyncio.Event = field(default_factory=asyncio.Event)
+
+ async def play_chunks(self, chunks: AsyncIterator[AudioChunk]) -> None:
+ task = asyncio.current_task()
+ self.last_write_owner_task_id = id(task) if task is not None else None
+ self.last_write_ns = 0
+ async for _ in chunks:
+ pass
+ await self._release.wait()
+
+ def stop(self) -> None:
+ self.stop_calls += 1
+ self._release.set()
+
+
def _make_pipeline() -> tuple[SpeechPipeline, HangingPlayer]:
bus = EventBus()
pipeline = SpeechPipeline(tts=FakeTTS(), bus=bus, enable_whisper_wake=False)
@@ -725,6 +752,48 @@ async def test_hung_brain_times_out_despite_thinking_heartbeat() -> None:
)
+async def test_await_playback_ignores_unrelated_announcement_audio_progress() -> None:
+ """A background announcement must not satisfy the current turn's playback.
+
+ Live regression 2026-06-25: a spawn heartbeat spoke while a simple question
+ was still in the brain/tool path. The heartbeat updated ``last_write_ns`` on
+ the shared player; the current answer had not produced its own first frame
+ yet, but ``_await_playback`` treated the stale foreign timestamp as
+ mid-playback progress and fired the 5 s device-wedge abort. The generated
+ answer was recorded in the transcript but not reliably spoken.
+ """
+ bus = EventBus()
+ pipeline = SpeechPipeline(tts=FakeTTS(), bus=bus, enable_whisper_wake=False)
+ player = OwnerTaggedNoFramePlayer()
+ pipeline._player = player # type: ignore[assignment]
+ pipeline._speak_playback_ceiling_s = 0.2 # type: ignore[attr-defined]
+ pipeline._speak_playback_stall_s = 0.08 # type: ignore[attr-defined]
+
+ play_task = asyncio.create_task(player.play_chunks(_empty_chunks()))
+
+ async def _foreign_audio_then_brain_finishes() -> None:
+ await asyncio.sleep(0.03)
+ # Simulate AudioPlayer progress from a different play_chunks task.
+ player.last_write_owner_task_id = -1
+ player.last_write_ns = time.monotonic_ns()
+ for _ in range(8):
+ pipeline._brain_thinking_heartbeat = time.monotonic() # type: ignore[attr-defined]
+ await asyncio.sleep(0.04)
+ player._release.set()
+
+ foreign = asyncio.create_task(_foreign_audio_then_brain_finishes())
+ try:
+ done = await asyncio.wait_for(
+ pipeline._await_playback(play_task, set()), timeout=5.0
+ )
+ finally:
+ foreign.cancel()
+
+ assert done == {play_task}, "foreign announcement audio must not abort this turn"
+ assert player.stop_calls == 0
+
+
@pytest.mark.asyncio
async def test_await_playback_still_aborts_genuine_midplayback_wedge() -> None:
"""A real mid-playback device wedge (frames then freeze) must still abort."""
diff --git a/tests/unit/speech/test_warmup_two_phase.py b/tests/unit/speech/test_warmup_two_phase.py
index 3b25e22455..041ed0d42d 100644
--- a/tests/unit/speech/test_warmup_two_phase.py
+++ b/tests/unit/speech/test_warmup_two_phase.py
@@ -5,17 +5,23 @@ visible because warm-up ran every step sequentially — the dominant cost being
~20 confirmation-audio phrases pre-rendered one at a time. This split warm-up
into:
-* **Phase A (critical, parallel):** audio-device stabilization + VAD +
- OpenWakeWord + TTS-client init run concurrently. When it finishes the
- pipeline emits ``VoiceBootStatus(ready=True)`` — the listening path is live.
+* **Phase A (critical):** audio-device stabilization + wake-loop start. It does
+ the absolute minimum so the wake LOOP is listening fast; the heavy VAD/STT/TTS
+ loads are deferred so they never gate wake-loop start (BUG class: "Hey Jarvis"
+ dead while heavy loads serialize on the import lock).
+* **Deferred loaders (background):** wake model + VAD + TTS-client load off the
+ wake-critical path. HONEST readiness lives here: ``VoiceBootStatus(ready=True)``
+ and the audible "you can speak" cue fire only at the END of this task — the
+ first moment wake (model) + VAD + TTS are ALL up. Flipping ready in Phase A
+ (before TTS) was the "it says ready but I can't talk" bug (2026-06-29).
* **Phase B (background, fire-and-forget):** confirmation audio is pre-rendered
off the critical path (ACK "Ja?" first, then the task-ack phrases
concurrently). It must NOT block the ready signal.
These tests pin the contract: ``ready=False`` is emitted before Phase A,
-``ready=True`` after Phase A completes, and the background render never blocks
-ready. They also keep the BUG-014 audio-stabilization guard and the chime/ready
-fallback intact.
+``ready=True`` (and the cue) only after the DEFERRED loaders complete the full
+stack, and the Phase-B confirmation render never blocks ready. They also keep
+the BUG-014 audio-stabilization guard and the chime/ready fallback intact.
"""
from __future__ import annotations
@@ -93,6 +99,11 @@ def _new_pipe(monkeypatch, *, bus=None, ack_phrase: str = "Ja?") -> SpeechPipeli
pipe._player = FakePlayer()
pipe._bus = bus
pipe._stt = None
+ # Honest-ready anchor (2026-06-27): _warmup reads _whisper_wake_enabled to
+ # decide whether wake is hear-ready at Phase A (openWakeWord) or only after
+ # the wake model loads (custom rolling-whisper). With _stt=None this is the
+ # openWakeWord path, exactly as the real __init__ computes it.
+ pipe._whisper_wake_enabled = False
pipe._vad = FakeVad()
pipe._tts = FakeTts()
pipe._wake = FakeWake()
@@ -123,12 +134,15 @@ def _new_pipe(monkeypatch, *, bus=None, ack_phrase: str = "Ja?") -> SpeechPipeli
@pytest.mark.asyncio
async def test_emits_ready_false_then_true(monkeypatch) -> None:
- """Boot-status order: ready=False at the very start, ready=True after the
- critical Phase A completes."""
+ """Boot-status order: ready=False at the very start, ready=True only after
+ the DEFERRED loaders bring up the full stack (honest readiness)."""
bus = FakeBus()
pipe = _new_pipe(monkeypatch, bus=bus)
await pipe._warmup()
+ # Honest readiness fires from the background deferred-loaders task, not from
+ # _warmup itself (which returns fast so the wake loop starts immediately).
+ await pipe._deferred_warmup_task
boot_events = [e for e in bus.published if isinstance(e, VoiceBootStatus)]
assert len(boot_events) >= 2
@@ -239,6 +253,10 @@ async def test_ready_signaled_before_background_render_finishes(monkeypatch) ->
pipe._tts.synthesize = gated_synth # type: ignore[method-assign]
await pipe._warmup()
+ # Honest readiness comes from the deferred loaders (which use the TTS
+ # client's _ensure_client, NOT synthesize), so it completes while the Phase-B
+ # confirmation render (synthesize) is still gated.
+ await pipe._deferred_warmup_task
# ready=True is already on the bus while the background render is blocked.
boot_events = [e for e in bus.published if isinstance(e, VoiceBootStatus)]
@@ -269,12 +287,14 @@ async def test_background_renders_ack_and_task_acks(monkeypatch) -> None:
@pytest.mark.asyncio
-async def test_ready_cue_played_after_phase_a(monkeypatch) -> None:
- """The audible boot-ready cue still plays so the user hears when listening
- starts — the wake/chime fallback for a not-yet-cached ACK is intact."""
+async def test_ready_cue_played_after_deferred_loaders(monkeypatch) -> None:
+ """The audible boot-ready cue still plays so the user hears when the voice
+ stack is genuinely ready — now fired at the END of the deferred loaders
+ (honest readiness), not after Phase A."""
pipe = _new_pipe(monkeypatch, bus=FakeBus())
await pipe._warmup()
+ await pipe._deferred_warmup_task
task = pipe._warmup_ready_cue_task
assert task is not None
await task
@@ -303,6 +323,10 @@ async def test_ready_cue_does_not_block_wake_loop_start(monkeypatch) -> None:
pipe._play_ready_cue = _blocking_ready_cue # type: ignore[method-assign]
await asyncio.wait_for(pipe._warmup(), timeout=0.5)
+ # The cue is created + fired by the deferred-loaders task (honest readiness)
+ # as a fire-and-forget task, so neither _warmup NOR the deferred task itself
+ # is blocked by a slow/wedged output device.
+ await asyncio.wait_for(pipe._deferred_warmup_task, timeout=0.5)
boot_events = [e for e in bus.published if isinstance(e, VoiceBootStatus)]
assert any(e.ready for e in boot_events), "ready=True must be emitted"
@@ -358,3 +382,51 @@ async def test_cancel_background_is_noop_when_absent(monkeypatch) -> None:
await pipe._cancel_warmup_background() # must not raise
assert pipe._warmup_background_task is None
+
+
+async def test_deferred_warmup_task_cancelled_on_shutdown(monkeypatch) -> None:
+ """The deferred wake/VAD/TTS loader task is fire-and-forget; on shutdown it
+ must be cancelled + awaited, not orphaned. It owns the honest ready signal
+ and spawns the ready-cue task, so a leak here strands both."""
+ pipe = _new_pipe(monkeypatch, bus=FakeBus())
+
+ started = asyncio.Event()
+
+ async def _never_ends() -> None:
+ started.set()
+ await asyncio.Event().wait() # blocks until cancelled
+
+ task = asyncio.create_task(_never_ends())
+ pipe._deferred_warmup_task = task
+ await started.wait() # the task is genuinely running
+
+ await pipe._cancel_warmup_background()
+
+ assert task.cancelled(), "the deferred loader task must be cancelled, not leaked"
+ assert pipe._deferred_warmup_task is None
+
+
+async def test_ready_cue_task_cancelled_on_shutdown(monkeypatch) -> None:
+ """The boot-ready audio cue task is created INSIDE the deferred loaders; a
+ shutdown after it is armed must cancel + await it, not orphan it (a wedged
+ output device must not keep the cue alive past pipeline shutdown). The
+ cue-task-may-be-None-before-creation race is covered by the getattr() in
+ _cancel_warmup_background and the noop test above."""
+ pipe = _new_pipe(monkeypatch, bus=FakeBus())
+
+ started = asyncio.Event()
+
+ async def _never_ends() -> None:
+ started.set()
+ await asyncio.Event().wait() # blocks until cancelled
+
+ task = asyncio.create_task(_never_ends())
+ pipe._warmup_ready_cue_task = task
+ await started.wait() # the task is genuinely running
+
+ await pipe._cancel_warmup_background()
+
+ assert task.cancelled(), "the ready-cue task must be cancelled, not leaked"
+ assert pipe._warmup_ready_cue_task is None
diff --git a/tests/unit/tasks/test_action_parity.py b/tests/unit/tasks/test_action_parity.py
new file mode 100644
index 0000000000..d1cb564d37
--- /dev/null
+++ b/tests/unit/tasks/test_action_parity.py
@@ -0,0 +1,38 @@
+"""Parity test for the task ACTION vocabulary across Python ↔ TypeScript.
+
+The create dialog must never emit an action ``kind`` the Pydantic
+``TaskAction`` discriminator rejects (that is an instant HTTP 422 on save).
+The TS side is a SUBSET of Python by design — the UI does not surface every
+action kind (e.g. ``tool_call`` has no dialog) — so the contract is
+containment, not equality: every kind the frontend builds must be a known
+Python kind.
+
+Source of truth: ``ACTION_KINDS`` in ``jarvis/tasks/schema.py``.
+"""
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from jarvis.tasks.schema import ACTION_KINDS
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+TASK_SPEC_TS = REPO_ROOT / "jarvis/ui/web/frontend/src/views/tasks/taskSpec.ts"
+
+
+def test_ts_action_kinds_are_all_known_to_python() -> None:
+ text = TASK_SPEC_TS.read_text(encoding="utf-8")
+ found = set(re.findall(r'kind:\s*"([^"]+)"', text))
+ assert found, "no action kinds found in taskSpec.ts"
+ unknown = found - set(ACTION_KINDS)
+ assert unknown == set(), (
+ f"taskSpec.ts emits action kinds the Python schema rejects: {unknown}"
+ )
+
+
+def test_whenthen_uses_harness_dispatch_for_computer_use() -> None:
+ """The When-Then Computer-Use path must dispatch via the harness action —
+ a regression here would silently drop CU rules."""
+ text = TASK_SPEC_TS.read_text(encoding="utf-8")
+ assert "harness_dispatch" in text
+ assert "harness_dispatch" in ACTION_KINDS
diff --git a/tests/unit/tasks/test_runner_whenthen.py b/tests/unit/tasks/test_runner_whenthen.py
new file mode 100644
index 0000000000..85c060cbc7
--- /dev/null
+++ b/tests/unit/tasks/test_runner_whenthen.py
@@ -0,0 +1,198 @@
+"""TaskRunner When-Then behaviour — event templating + notify-on-complete.
+
+Covers the runner half of the When-Then feature: the triggering event's fields
+interpolate into the action prompt, and ``announce_on_success`` /
+``announce_on_failure`` emit a spoken confirmation (AnnouncementRequested,
+kind="subagent") that survives the voice hangup gate.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.core.bus import EventBus
+from jarvis.core.events import AnnouncementRequested
+from jarvis.core.protocols import HarnessResult
+from jarvis.tasks.runner import TaskRunner, _safe_format
+from jarvis.tasks.schema import (
+ HarnessDispatchAction,
+ TaskSpec,
+ TriggerOnEvent,
+)
+from jarvis.tasks.store import TaskStore
+
+
+class FakeHarnessManager:
+ def __init__(self, results: list[HarnessResult] | None = None) -> None:
+ self.dispatched: list[tuple[str, Any]] = []
+ self._results = results or [
+ HarnessResult(stdout="ok\n", exit_code=0, is_final=True),
+ ]
+
+ async def dispatch(self, name: str, task: Any):
+ self.dispatched.append((name, task))
+
+ async def gen():
+ for r in self._results:
+ yield r
+ return gen()
+
+
+async def store(tmp_path: Path):
+ s = TaskStore(tmp_path / "wt.db")
+ await s.init()
+ try:
+ yield s
+ finally:
+ await s.close()
+
+
+def bus() -> EventBus:
+ return EventBus()
+
+
+def _collect_announcements(bus: EventBus) -> list[AnnouncementRequested]:
+ got: list[AnnouncementRequested] = []
+
+ async def on_ann(e: AnnouncementRequested) -> None:
+ got.append(e)
+
+ bus.subscribe(AnnouncementRequested, on_ann)
+ return got
+
+
+def _mission_event(**over: Any) -> dict[str, Any]:
+ base = {
+ "mission_id": "m1",
+ "status": "approved",
+ "summary_de": "Fertig.",
+ "summary_en": "Done.",
+ "result_uri": "/out/result.md",
+ "reason": "",
+ }
+ base.update(over)
+ return base
+
+
+# ----------------------------------------------------------------------
+# _safe_format
+# ----------------------------------------------------------------------
+
+def test_safe_format_interpolates_known_fields() -> None:
+ assert _safe_format("open {result_uri}", {"result_uri": "/x"}) == "open /x"
+
+
+def test_safe_format_passes_unknown_through() -> None:
+ assert _safe_format("hi {nope}", {"result_uri": "/x"}) == "hi {nope}"
+
+
+def test_safe_format_tolerates_malformed_braces() -> None:
+ assert _safe_format("100% { done", {}) == "100% { done"
+
+
+def test_safe_format_no_braces_is_identity() -> None:
+ assert _safe_format("plain text", {"a": 1}) == "plain text"
+
+
+# ----------------------------------------------------------------------
+# Templating into the action
+# ----------------------------------------------------------------------
+
+async def test_harness_prompt_is_templated_from_event(
+ store: TaskStore, bus: EventBus
+) -> None:
+ hm = FakeHarnessManager()
+ runner = TaskRunner(store=store, bus=bus, harness_manager=hm)
+ spec = TaskSpec(
+ title="open result",
+ trigger=TriggerOnEvent(event_name="MissionCompleted",
+ filter_expr="status == 'approved'"),
+ action=HarnessDispatchAction(
+ harness="screenshot",
+ prompt="open {result_uri} in the browser",
+ allow_computer_use=True,
+ ),
+ )
+ tid = await store.insert(spec)
+
+ await runner.run(tid, trigger_event=_mission_event())
+
+ assert len(hm.dispatched) == 1
+ name, task = hm.dispatched[0]
+ assert name == "screenshot"
+ assert task.prompt == "open /out/result.md in the browser"
+ assert task.allow_computer_use is True
+
+
+# ----------------------------------------------------------------------
+# Notify-on-complete
+# ----------------------------------------------------------------------
+
+async def test_announce_on_success_emits_subagent_announcement(
+ store: TaskStore, bus: EventBus
+) -> None:
+ hm = FakeHarnessManager()
+ runner = TaskRunner(store=store, bus=bus, harness_manager=hm)
+ anns = _collect_announcements(bus)
+ spec = TaskSpec(
+ title="open + notify",
+ trigger=TriggerOnEvent(event_name="MissionCompleted"),
+ action=HarnessDispatchAction(harness="screenshot", prompt="x",
+ allow_computer_use=True),
+ announce_on_success="Done — opened {result_uri}.",
+ )
+ tid = await store.insert(spec)
+
+ await runner.run(tid, trigger_event=_mission_event())
+
+ assert len(anns) == 1
+ assert anns[0].text == "Done — opened /out/result.md."
+ assert anns[0].kind == "subagent"
+
+
+async def test_announce_on_failure_fires_when_action_fails(
+ store: TaskStore, bus: EventBus
+) -> None:
+ hm = FakeHarnessManager(
+ results=[HarnessResult(stdout="", stderr="boom", exit_code=5, is_final=True)]
+ )
+ runner = TaskRunner(store=store, bus=bus, harness_manager=hm)
+ anns = _collect_announcements(bus)
+ spec = TaskSpec(
+ title="open + notify-fail",
+ trigger=TriggerOnEvent(event_name="MissionCompleted"),
+ action=HarnessDispatchAction(harness="screenshot", prompt="x",
+ allow_computer_use=True),
+ announce_on_success="should not fire",
+ announce_on_failure="Could not open the result.",
+ )
+ tid = await store.insert(spec)
+
+ await runner.run(tid, trigger_event=_mission_event())
+
+ assert len(anns) == 1
+ assert anns[0].text == "Could not open the result."
+ task = await store.get(tid)
+ assert task is not None
+ assert task["state"] == "failed"
+
+
+async def test_no_announcement_when_unset(store: TaskStore, bus: EventBus) -> None:
+ hm = FakeHarnessManager()
+ runner = TaskRunner(store=store, bus=bus, harness_manager=hm)
+ anns = _collect_announcements(bus)
+ spec = TaskSpec(
+ title="silent",
+ trigger=TriggerOnEvent(event_name="MissionCompleted"),
+ action=HarnessDispatchAction(harness="screenshot", prompt="x",
+ allow_computer_use=True),
+ )
+ tid = await store.insert(spec)
+
+ await runner.run(tid, trigger_event=_mission_event())
+
+ assert anns == []
diff --git a/tests/unit/tasks/test_scheduler_whenthen.py b/tests/unit/tasks/test_scheduler_whenthen.py
new file mode 100644
index 0000000000..9d96e554a3
--- /dev/null
+++ b/tests/unit/tasks/test_scheduler_whenthen.py
@@ -0,0 +1,105 @@
+"""TaskScheduler When-Then behaviour — event passthrough + fire-once dedup.
+
+The scheduler must hand the triggering event's flat fields to the runner as
+``trigger_event`` and must never fire the same standing rule twice for the same
+event subject (one mission's terminal event).
+"""
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.core.bus import EventBus
+from jarvis.core.events import MissionCompleted
+from jarvis.tasks.scheduler import TaskScheduler
+from jarvis.tasks.schema import SpeakAction, TaskSpec, TriggerOnEvent
+from jarvis.tasks.store import TaskStore
+
+
+class CapturingRunner:
+ """Records every ``run()`` call with its ``trigger_event`` context."""
+
+ def __init__(self) -> None:
+ self.calls: list[tuple[str, dict[str, Any] | None]] = []
+
+ async def run(
+ self, task_id: str, *, trigger_event: dict[str, Any] | None = None
+ ) -> None:
+ self.calls.append((task_id, trigger_event))
+
+
+async def store(tmp_path: Path):
+ s = TaskStore(tmp_path / "sched-wt.db")
+ await s.init()
+ try:
+ yield s
+ finally:
+ await s.close()
+
+
+async def _standing_rule(store: TaskStore, scheduler: TaskScheduler) -> str:
+ spec = TaskSpec(
+ title="whenever a mission finishes",
+ trigger=TriggerOnEvent(
+ event_name="MissionCompleted",
+ filter_expr="status == 'approved'",
+ max_firings=None, # standing rule: fires for every matching mission
+ ),
+ action=SpeakAction(text="done"),
+ )
+ return await scheduler.schedule(spec)
+
+
+async def test_event_fields_passthrough_to_runner(store: TaskStore) -> None:
+ bus = EventBus()
+ cap = CapturingRunner()
+ scheduler = TaskScheduler(store=store, bus=bus, runner=cap)
+ scheduler.bind_bus()
+ await _standing_rule(store, scheduler)
+
+ await bus.publish(
+ MissionCompleted(mission_id="m1", status="approved", result_uri="/out/r.md")
+ )
+ await asyncio.sleep(0.05)
+
+ assert len(cap.calls) == 1
+ _tid, ctx = cap.calls[0]
+ assert ctx is not None
+ assert ctx["result_uri"] == "/out/r.md"
+ assert ctx["status"] == "approved"
+ assert ctx["mission_id"] == "m1"
+
+
+async def test_dedup_same_mission_fires_once(store: TaskStore) -> None:
+ bus = EventBus()
+ cap = CapturingRunner()
+ scheduler = TaskScheduler(store=store, bus=bus, runner=cap)
+ scheduler.bind_bus()
+ await _standing_rule(store, scheduler)
+
+ # Same mission re-published — must fire exactly once.
+ await bus.publish(MissionCompleted(mission_id="m1", status="approved"))
+ await bus.publish(MissionCompleted(mission_id="m1", status="approved"))
+ await asyncio.sleep(0.05)
+ assert len(cap.calls) == 1
+
+ # A different mission is a distinct subject — fires again.
+ await bus.publish(MissionCompleted(mission_id="m2", status="approved"))
+ await asyncio.sleep(0.05)
+ assert len(cap.calls) == 2
+
+
+async def test_filter_blocks_non_approved(store: TaskStore) -> None:
+ bus = EventBus()
+ cap = CapturingRunner()
+ scheduler = TaskScheduler(store=store, bus=bus, runner=cap)
+ scheduler.bind_bus()
+ await _standing_rule(store, scheduler)
+
+ await bus.publish(MissionCompleted(mission_id="m1", status="failed"))
+ await asyncio.sleep(0.05)
+ assert cap.calls == []
diff --git a/tests/unit/tasks/test_trigger_parity.py b/tests/unit/tasks/test_trigger_parity.py
new file mode 100644
index 0000000000..cb235021df
--- /dev/null
+++ b/tests/unit/tasks/test_trigger_parity.py
@@ -0,0 +1,73 @@
+"""Parity test for the task TRIGGER vocabulary across Python ↔ TypeScript.
+
+BUG-008 class: a vocabulary that spans Python (the Pydantic discriminator),
+the TS trigger union (what the create dialog emits) and the TasksView display
+(icon + label maps) drifts silently — the dialog emits a trigger the backend
+rejects, or the list view shows a blank icon for a trigger it never learned.
+
+Source of truth: ``TRIGGER_TYPES`` in ``jarvis/tasks/schema.py``. Every TS layer
+must spell exactly the same four values. (When-Then added ``on_event`` to the TS
+side; this test would have failed on the missing value before that change.)
+"""
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from jarvis.tasks.schema import TRIGGER_TYPES
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+TASK_SPEC_TS = REPO_ROOT / "jarvis/ui/web/frontend/src/views/tasks/taskSpec.ts"
+TASKS_VIEW_TSX = REPO_ROOT / "jarvis/ui/web/frontend/src/views/TasksView.tsx"
+
+
+def _expected() -> set[str]:
+ return set(TRIGGER_TYPES)
+
+
+def test_taskspec_ts_trigger_union_matches_python() -> None:
+ text = TASK_SPEC_TS.read_text(encoding="utf-8")
+ # Capture up to the next top-level `export` — the union body contains inner
+ # `;` (e.g. `{ type: "after_delay"; ... }`) so a non-greedy `;` stops short.
+ block = re.search(r"export type TaskTrigger =([\s\S]+?)\nexport ", text)
+ assert block is not None, "could not find TaskTrigger union in taskSpec.ts"
+ found = set(re.findall(r'type:\s*"([^"]+)"', block.group(1)))
+ assert found == _expected(), (
+ f"taskSpec.ts TaskTrigger drift: extra={found - _expected()}, "
+ f"missing={_expected() - found}"
+ )
+
+
+def test_tasksview_triggertype_matches_python() -> None:
+ text = TASKS_VIEW_TSX.read_text(encoding="utf-8")
+ block = re.search(r"type TriggerType =([\s\S]+?);", text)
+ assert block is not None, "could not find TriggerType in TasksView.tsx"
+ found = set(re.findall(r'"([^"]+)"', block.group(1)))
+ assert found == _expected(), (
+ f"TasksView.tsx TriggerType drift: extra={found - _expected()}, "
+ f"missing={_expected() - found}"
+ )
+
+
+def test_tasksview_icon_map_covers_every_trigger() -> None:
+ text = TASKS_VIEW_TSX.read_text(encoding="utf-8")
+ block = re.search(r"const TRIGGER_ICON[^{]+\{([\s\S]+?)\};", text)
+ assert block is not None, "could not find TRIGGER_ICON map in TasksView.tsx"
+ found = set(re.findall(r"(\w+)\s*:", block.group(1)))
+ assert found == _expected(), (
+ f"TasksView.tsx TRIGGER_ICON drift: extra={found - _expected()}, "
+ f"missing={_expected() - found}"
+ )
+
+
+def test_tasksview_label_map_covers_every_trigger() -> None:
+ text = TASKS_VIEW_TSX.read_text(encoding="utf-8")
+ block = re.search(
+ r"function makeTriggerLabels[\s\S]+?return\s*\{([\s\S]+?)\};", text
+ )
+ assert block is not None, "could not find makeTriggerLabels in TasksView.tsx"
+ found = set(re.findall(r"(\w+)\s*:\s*t\(", block.group(1)))
+ assert found == _expected(), (
+ f"TasksView.tsx label map drift: extra={found - _expected()}, "
+ f"missing={_expected() - found}"
+ )
diff --git a/tests/unit/telemetry/test_recorder_attach.py b/tests/unit/telemetry/test_recorder_attach.py
new file mode 100644
index 0000000000..a1b9ddd1ec
--- /dev/null
+++ b/tests/unit/telemetry/test_recorder_attach.py
@@ -0,0 +1,52 @@
+"""attach_flight_recorder — the single boot wiring point for the audit log
+(audit 🟠 #14).
+
+The FlightRecorder was defined but never attached at boot, so
+``telemetry.flight_recorder = true`` promised a replayable audit trail that was
+silently empty. These pin the gating: enabled -> a wildcard subscriber is
+registered and a recorder returned; disabled -> nothing is touched.
+"""
+from __future__ import annotations
+
+from typing import Any
+
+from jarvis.telemetry.recorder import FlightRecorder, attach_flight_recorder
+
+
+class _FakeBus:
+ def __init__(self) -> None:
+ self.subscribed: list[Any] = []
+
+ def subscribe_all(self, handler: Any) -> None:
+ self.subscribed.append(handler)
+
+
+def test_disabled_returns_none_and_does_not_subscribe():
+ bus = _FakeBus()
+ rec = attach_flight_recorder(bus, enabled=False)
+ assert rec is None
+ assert bus.subscribed == []
+
+
+def test_enabled_attaches_one_wildcard_subscriber(tmp_path):
+ bus = _FakeBus()
+ rec = attach_flight_recorder(bus, enabled=True, data_dir=tmp_path / "fr")
+ assert isinstance(rec, FlightRecorder)
+ assert len(bus.subscribed) == 1
+
+
+def test_enabled_creates_the_data_dir(tmp_path):
+ target = tmp_path / "fr"
+ attach_flight_recorder(_FakeBus(), enabled=True, data_dir=target)
+ assert target.is_dir()
+ assert (target / "blobs").is_dir()
+
+
+def test_attach_is_idempotent_per_bus(tmp_path):
+ # FlightRecorder.attach is idempotent; re-attaching the SAME recorder to the
+ # SAME bus must not double-subscribe (guards a double-init at boot).
+ bus = _FakeBus()
+ rec = attach_flight_recorder(bus, enabled=True, data_dir=tmp_path / "fr")
+ assert rec is not None
+ rec.attach(bus) # second call, same bus
+ assert len(bus.subscribed) == 1
diff --git a/tests/unit/telephony/test_is_available_audioop.py b/tests/unit/telephony/test_is_available_audioop.py
new file mode 100644
index 0000000000..16d9629a97
--- /dev/null
+++ b/tests/unit/telephony/test_is_available_audioop.py
@@ -0,0 +1,38 @@
+"""L7 (cross-platform): Python 3.13 removed the stdlib ``audioop`` module that the
+telephony media path needs. is_available() must report False on 3.13+ when neither
+``audioop`` nor the ``audioop-lts`` backport is importable — else it claims
+"available" and then 500s on the first media socket.
+"""
+from __future__ import annotations
+
+import importlib.util
+
+import jarvis.telephony as tel
+
+
+def test_is_available_false_when_audioop_missing_on_py313(monkeypatch):
+ monkeypatch.setattr(tel, "_PY313_PLUS", True)
+ monkeypatch.setattr(
+ importlib.util, "find_spec", lambda name: None if name == "audioop" else object()
+ )
+ assert tel.is_available() is False
+
+
+def test_is_available_true_when_audioop_present_on_py313(monkeypatch):
+ monkeypatch.setattr(tel, "_PY313_PLUS", True)
+ monkeypatch.setattr(importlib.util, "find_spec", lambda name: object())
+ assert tel.is_available() is True
+
+
+def test_is_available_ignores_audioop_before_py313(monkeypatch):
+ # On <=3.12 audioop is stdlib; only the twilio SDK gates availability.
+ monkeypatch.setattr(tel, "_PY313_PLUS", False)
+ monkeypatch.setattr(
+ importlib.util, "find_spec", lambda name: object() if name == "twilio" else None
+ )
+ assert tel.is_available() is True
+
+
+def test_is_available_false_without_twilio(monkeypatch):
+ monkeypatch.setattr(importlib.util, "find_spec", lambda name: None)
+ assert tel.is_available() is False
diff --git a/tests/unit/telephony/test_routes.py b/tests/unit/telephony/test_routes.py
index 7ff2c3ae94..6140caf7c5 100644
--- a/tests/unit/telephony/test_routes.py
+++ b/tests/unit/telephony/test_routes.py
@@ -194,7 +194,10 @@ def test_scripts_endpoint_lists_helpers(app, secret_store):
assert r.status_code == 200
scripts = r.json()["scripts"]
names = {s["name"] for s in scripts}
- assert "Public tunnel (dev)" in names
+ # M7: a cross-platform (cloudflared) tunnel command alongside the Windows one.
+ assert "Public tunnel (portable)" in names
+ assert "Public tunnel (Windows dev)" in names
+ assert any("cloudflared tunnel --url" in s["command"] for s in scripts)
assert "Provision number" in names
for s in scripts:
assert s["command"]
diff --git a/tests/unit/test_claude_auth.py b/tests/unit/test_claude_auth.py
new file mode 100644
index 0000000000..9a96ff1fe6
--- /dev/null
+++ b/tests/unit/test_claude_auth.py
@@ -0,0 +1,212 @@
+"""Unit tests for jarvis.claude_auth.ClaudeAuthService.
+
+Exercises the real credential parsing (subscription OAuth vs API key vs not
+connected) and the display-safe account/subscription surfacing against temp
+files, with the binary discovery + version probe stubbed so the suite never
+depends on a real ``claude`` install or the user's real credentials.
+"""
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from jarvis import claude_auth
+from jarvis.claude_auth import (
+ ClaudeAuthService,
+ _account_from_claude_json,
+ _oauth_from_credentials,
+ _subscription_label,
+)
+
+
[email protected](autouse=True)
+def _clear_cache() -> None:
+ claude_auth.clear_version_cache()
+
+
+def _service(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ creds: dict | None,
+ claude_json: dict | None,
+ binary: str | None = "/usr/bin/claude",
+ api_key_present: bool = False,
+) -> ClaudeAuthService:
+ """Build a service whose seams point at temp files / a stubbed binary."""
+ creds_path = tmp_path / ".credentials.json"
+ claude_json_path = tmp_path / ".claude.json"
+ if creds is not None:
+ creds_path.write_text(json.dumps(creds), encoding="utf-8")
+ if claude_json is not None:
+ claude_json_path.write_text(json.dumps(claude_json), encoding="utf-8")
+
+ svc = ClaudeAuthService(api_key_present=api_key_present)
+ monkeypatch.setattr(svc, "_resolve_binary", lambda: binary)
+ monkeypatch.setattr(svc, "_probe_version", lambda _b: "claude 1.2.3")
+ monkeypatch.setattr(svc, "_credentials_path", lambda: creds_path)
+ monkeypatch.setattr(svc, "_claude_json_path", lambda: claude_json_path)
+ return svc
+
+
+# -- pure helpers -------------------------------------------------------
+
+
+def test_oauth_from_credentials_detects_subscription() -> None:
+ creds = {"claudeAiOauth": {"accessToken": "sk-ant-oat01-abc", "subscriptionType": "max"}}
+ connected, sub = _oauth_from_credentials(creds)
+ assert connected is True
+ assert sub == "max"
+
+
+def test_oauth_from_credentials_rejects_api_key_token() -> None:
+ # A classic API key in the bearer slot is NOT a subscription login.
+ creds = {"claudeAiOauth": {"accessToken": "sk-ant-api03-abc"}}
+ connected, sub = _oauth_from_credentials(creds)
+ assert connected is False
+ assert sub is None
+
+
[email protected]("bad", [None, {}, {"claudeAiOauth": "nope"}, {"claudeAiOauth": {}}])
+def test_oauth_from_credentials_tolerates_garbage(bad) -> None:
+ assert _oauth_from_credentials(bad) == (False, None)
+
+
+def test_account_from_claude_json_reads_email() -> None:
+ data = {"oauthAccount": {"emailAddress": "[email protected]", "displayName": "Ruben"}}
+ assert _account_from_claude_json(data) == ("[email protected]", "Ruben")
+
+
[email protected]("bad", [None, {}, {"oauthAccount": 5}])
+def test_account_from_claude_json_tolerates_garbage(bad) -> None:
+ assert _account_from_claude_json(bad) == (None, None)
+
+
+def test_subscription_label_maps_known_tiers() -> None:
+ assert _subscription_label("max") == "Claude Max"
+ assert _subscription_label("pro") == "Claude Pro"
+ assert _subscription_label(None) == "Claude subscription"
+
+
+# -- status() integration ----------------------------------------------
+
+
+def test_status_subscription_with_email(tmp_path, monkeypatch) -> None:
+ svc = _service(
+ tmp_path,
+ monkeypatch,
+ creds={"claudeAiOauth": {"accessToken": "sk-ant-oat01-x", "subscriptionType": "max"}},
+ claude_json={"oauthAccount": {"emailAddress": "[email protected]"}},
+ )
+ st = svc.status()
+ assert st.installed is True
+ assert st.connected is True
+ assert st.mode == "subscription"
+ assert st.user_email == "[email protected]"
+ assert st.subscription_type == "max"
+ assert st.account_label == "Claude Max"
+ assert "[email protected]" in st.message
+
+
+def test_status_api_key_when_no_oauth(tmp_path, monkeypatch) -> None:
+ svc = _service(
+ tmp_path,
+ monkeypatch,
+ creds=None,
+ claude_json=None,
+ api_key_present=True,
+ )
+ st = svc.status()
+ assert st.connected is True
+ assert st.mode == "api_key"
+ assert st.user_email is None
+ assert st.account_label == "Anthropic API key"
+
+
+def test_status_not_connected_without_creds_or_key(tmp_path, monkeypatch) -> None:
+ svc = _service(tmp_path, monkeypatch, creds=None, claude_json=None)
+ st = svc.status()
+ assert st.installed is True
+ assert st.connected is False
+ assert st.mode == "unknown"
+ assert st.api_key_present is False
+
+
+def test_status_surfaces_api_key_present_even_under_subscription(
+ tmp_path, monkeypatch
+) -> None:
+ # A user with BOTH a live Claude Max login AND a stored API key: mode stays
+ # "subscription" (billed first), but api_key_present must be True so the UI
+ # renders the key field in its configured state instead of an empty input.
+ svc = _service(
+ tmp_path,
+ monkeypatch,
+ creds={"claudeAiOauth": {"accessToken": "sk-ant-oat01-x", "subscriptionType": "max"}},
+ claude_json={"oauthAccount": {"emailAddress": "[email protected]"}},
+ api_key_present=True,
+ )
+ st = svc.status()
+ assert st.mode == "subscription"
+ assert st.api_key_present is True
+
+
+def test_status_api_key_present_when_not_installed(tmp_path, monkeypatch) -> None:
+ # The key field stays "configured" even if the CLI binary is absent — the
+ # stored key is independent of the local install.
+ svc = _service(
+ tmp_path,
+ monkeypatch,
+ creds=None,
+ claude_json=None,
+ binary=None,
+ api_key_present=True,
+ )
+ st = svc.status()
+ assert st.installed is False
+ assert st.api_key_present is True
+
+
+def test_status_not_installed(tmp_path, monkeypatch) -> None:
+ svc = _service(tmp_path, monkeypatch, creds=None, claude_json=None, binary=None)
+ st = svc.status()
+ assert st.installed is False
+ assert st.connected is False
+ assert "not installed" in st.message.lower()
+
+
+def test_to_dict_has_wire_fields(tmp_path, monkeypatch) -> None:
+ svc = _service(
+ tmp_path,
+ monkeypatch,
+ creds={"claudeAiOauth": {"accessToken": "sk-ant-oat01-x", "subscriptionType": "max"}},
+ claude_json={"oauthAccount": {"emailAddress": "[email protected]"}},
+ )
+ d = svc.status().to_dict()
+ for key in (
+ "installed",
+ "connected",
+ "mode",
+ "message",
+ "user_email",
+ "subscription_type",
+ "account_label",
+ "api_key_present",
+ ):
+ assert key in d
+ # The bearer token is never surfaced.
+ assert "accessToken" not in d
+ assert "sk-ant-oat" not in json.dumps(d)
+
+
+def test_status_never_logs_secret(tmp_path, monkeypatch, caplog) -> None:
+ svc = _service(
+ tmp_path,
+ monkeypatch,
+ creds={"claudeAiOauth": {"accessToken": "sk-ant-oat01-SECRET", "subscriptionType": "max"}},
+ claude_json={"oauthAccount": {"emailAddress": "[email protected]"}},
+ )
+ with caplog.at_level("DEBUG"):
+ svc.status()
+ assert "sk-ant-oat01-SECRET" not in caplog.text
diff --git a/tests/unit/test_codex_auth.py b/tests/unit/test_codex_auth.py
index fe76af7ff5..92156f1a4a 100644
--- a/tests/unit/test_codex_auth.py
+++ b/tests/unit/test_codex_auth.py
@@ -162,6 +162,74 @@ def test_status_tolerates_corrupt_auth_json(
assert status.mode == "unknown"
+# ----------------------------------------------------------------------
+# version-probe caching — the cold-start latency fix
+# ----------------------------------------------------------------------
+
+
+def test_probe_version_cached_across_status_calls(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """`codex --version` is invariant at runtime but is the dominant cold-start
+ cost — /api/providers used to spawn it 2-4x PER request. It must be probed
+ once per binary and cached, so every later status() is a pure auth-file read.
+ """
+ import jarvis.codex_auth as codex_mod
+
+ codex_mod.clear_version_cache()
+ monkeypatch.setenv("CODEX_HOME", str(tmp_path))
+ _write_auth(tmp_path, {"tokens": {"access_token": "t"}})
+
+ runs = {"n": 0}
+
+ def _fake_run(_argv, **_kw): # noqa: ANN001, ANN003
+ runs["n"] += 1
+
+ class _R:
+ stdout = "codex 1.2.3"
+ stderr = ""
+ returncode = 0
+
+ return _R()
+
+ monkeypatch.setattr(codex_mod.subprocess, "run", _fake_run)
+ # Stub on the class so a fresh instance resolves the SAME binary key (and
+ # thus shares the module-level cache).
+ monkeypatch.setattr(CodexAuthService, "_resolve_binary", lambda self: "codex")
+
+ v1 = CodexAuthService("codex").status()
+ v2 = CodexAuthService("codex").status()
+ v3 = CodexAuthService("codex").status() # a fresh instance shares the cache
+
+ assert v1.version == v2.version == v3.version == "codex 1.2.3"
+ assert runs["n"] == 1, "codex --version must run once, then be cached"
+
+
+def test_probe_version_caches_failure_to_avoid_repeated_timeouts(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A hanging/absent codex must not pay a 4s subprocess timeout on every
+ status() call — the failed probe is cached too."""
+ import jarvis.codex_auth as codex_mod
+
+ codex_mod.clear_version_cache()
+ monkeypatch.setenv("CODEX_HOME", str(tmp_path))
+ _write_auth(tmp_path, {"tokens": {"access_token": "t"}})
+
+ runs = {"n": 0}
+
+ def _fake_run(_argv, **_kw): # noqa: ANN001, ANN003
+ runs["n"] += 1
+ raise codex_mod.subprocess.TimeoutExpired(cmd="codex", timeout=4.0)
+
+ monkeypatch.setattr(codex_mod.subprocess, "run", _fake_run)
+ monkeypatch.setattr(CodexAuthService, "_resolve_binary", lambda self: "codex")
+
+ assert CodexAuthService("codex").status().version is None
+ assert CodexAuthService("codex").status().version is None
+ assert runs["n"] == 1, "a failed probe must be cached, not retried every call"
+
+
# ----------------------------------------------------------------------
# start_login / logout — spawn discipline (cross-platform, AP-1)
# ----------------------------------------------------------------------
diff --git a/tests/unit/test_codex_subagent_parity.py b/tests/unit/test_codex_jarvis_agent_parity.py
similarity index 100%
rename from tests/unit/test_codex_subagent_parity.py
rename to tests/unit/test_codex_jarvis_agent_parity.py
diff --git a/tests/unit/test_config_writer_stt_sync.py b/tests/unit/test_config_writer_stt_sync.py
index 7ea7aecc54..34ff472961 100644
--- a/tests/unit/test_config_writer_stt_sync.py
+++ b/tests/unit/test_config_writer_stt_sync.py
@@ -168,3 +168,58 @@ def test_raises_on_missing_toml(
with pytest.raises(FileNotFoundError):
config_writer.set_stt_provider("faster-whisper", path=tmp_path / "nope.toml")
+
+
+# ---------------------------------------------------------------------------
+# set_stt_language: TOML + config-soll sync (drift-guard pinned, no ENV var).
+# ---------------------------------------------------------------------------
+
+
+def test_set_stt_language_writes_all_three_layers(
+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The recognition-language switch persists to TOML + config-soll + the
+ JARVIS__STT__LANGUAGE ENV var, so neither the drift-guard nor a stale ENV
+ override reverts it (same 3-layer trap as stt.model)."""
+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)
+ env_calls: list[tuple[str, str]] = []
+ monkeypatch.setattr(
+ config_writer, "_set_user_env_var", lambda n, v: env_calls.append((n, v))
+ )
+
+ config_writer.set_stt_language("de", path=sample_toml)
+
+ assert 'language = "de"' in sample_toml.read_text(encoding="utf-8")
+ soll = json.loads(sample_soll.read_text(encoding="utf-8"))
+ assert soll["stt"]["language"] == "de"
+ # Sibling keys untouched.
+ assert soll["stt"]["provider"] == "groq-api"
+ assert soll["stt"]["model"] == "large-v3-turbo"
+ # ENV layer written so a stale JARVIS__STT__LANGUAGE cannot mask the choice.
+ assert env_calls == [("JARVIS__STT__LANGUAGE", "de")]
+
+
+def test_set_stt_language_auto_roundtrip(
+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)
+ monkeypatch.setattr(config_writer, "_set_user_env_var", lambda n, v: None)
+
+ config_writer.set_stt_language("auto", path=sample_toml)
+
+ assert 'language = "auto"' in sample_toml.read_text(encoding="utf-8")
+ soll = json.loads(sample_soll.read_text(encoding="utf-8"))
+ assert soll["stt"]["language"] == "auto"
+
+
+def test_set_stt_language_soll_failure_does_not_break_toml(
+ sample_toml: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ broken = tmp_path / "config-soll.json"
+ broken.write_text("{ not valid json ", encoding="utf-8")
+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: broken)
+ monkeypatch.setattr(config_writer, "_set_user_env_var", lambda n, v: None)
+
+ config_writer.set_stt_language("es", path=sample_toml)
+
+ assert 'language = "es"' in sample_toml.read_text(encoding="utf-8")
diff --git a/tests/unit/test_config_writer_sub_jarvis_sync.py b/tests/unit/test_config_writer_worker_sync.py
similarity index 100%
rename from tests/unit/test_config_writer_sub_jarvis_sync.py
rename to tests/unit/test_config_writer_worker_sync.py
diff --git a/tests/unit/test_subagent_board_listing.py b/tests/unit/test_jarvis_agent_board_listing.py
similarity index 100%
rename from tests/unit/test_subagent_board_listing.py
rename to tests/unit/test_jarvis_agent_board_listing.py
diff --git a/tests/unit/test_openclaw_config.py b/tests/unit/test_jarvis_agent_harness_config.py
similarity index 100%
rename from tests/unit/test_openclaw_config.py
rename to tests/unit/test_jarvis_agent_harness_config.py
diff --git a/tests/unit/test_provider_spec.py b/tests/unit/test_provider_spec.py
index 8b81b3521c..9f3f3c6de5 100644
--- a/tests/unit/test_provider_spec.py
+++ b/tests/unit/test_provider_spec.py
@@ -123,17 +123,30 @@ def test_every_provider_has_credential_help() -> None:
def test_provider_billing_is_derived_from_auth_mode() -> None:
- """Billing is a pure function of auth_mode — never branched on a provider
- name (multi-provider mandate). API-key → pay-per-token; antigravity →
- subscription; codex → either; local → no credential."""
+ """Billing is capability-driven, never branched on a provider name
+ (multi-provider mandate). API-key → pay-per-token; a subscription-login
+ provider that ALSO accepts an API key → subscription_or_api; one that does
+ not → subscription; local → no credential. Both Codex and Antigravity now
+ accept an API key (the ChatGPT/Google subscription OR a per-token key), so
+ both are subscription_or_api."""
by_id = {spec.id: spec for spec in PROVIDERS}
assert provider_billing(by_id["claude-api"]) == "api"
assert provider_billing(by_id["gemini"]) == "api"
- assert provider_billing(by_id["antigravity"]) == "subscription"
+ assert provider_billing(by_id["antigravity"]) == "subscription_or_api"
assert provider_billing(by_id["codex"]) == "subscription_or_api"
assert provider_billing(by_id["faster-whisper"]) == "local"
+def test_antigravity_accepts_api_key_billing() -> None:
+ """Antigravity mirrors Codex: it bills over the Google subscription OAuth OR
+ a Gemini API key (the Google Cloud credential), so it carries a secret key."""
+ antigravity = get_spec("antigravity")
+ assert antigravity is not None
+ assert antigravity.auth_mode == "antigravity"
+ assert "gemini_api_key" in antigravity.secret_keys
+ assert provider_billing(antigravity) == "subscription_or_api"
+
+
def test_billing_covers_every_provider() -> None:
allowed = {"api", "subscription", "subscription_or_api", "local"}
for spec in PROVIDERS:
diff --git a/tests/unit/ui/jarvisbar/test_boot_visibility.py b/tests/unit/ui/jarvisbar/test_boot_visibility.py
new file mode 100644
index 0000000000..7d2a4fc0d0
--- /dev/null
+++ b/tests/unit/ui/jarvisbar/test_boot_visibility.py
@@ -0,0 +1,53 @@
+"""The persistent JarvisBar is visible immediately at boot.
+
+Regression: the boot wiring used to build the persistent bar WITHDRAWN
+(``start_hidden=True``) and reveal it only once voice was ready
+(``VoiceBootStatus(ready=True)``). On the serve-first fast-boot path that reveal
+was late and/or lost the topmost z-order, so the bar stayed hidden until the
+first wake word incidentally re-showed it. The bar's boot visibility must be
+decoupled from the voice/wake path: a persistent bar maps its window at boot,
+always; a non-persistent bar still pops on a real session.
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from jarvis.ui.desktop_app import DesktopApp
+from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay
+
+
+def _app(*, bar_persistent: bool) -> DesktopApp:
+ app = DesktopApp.__new__(DesktopApp) # bypass heavy __init__
+ app.cfg = SimpleNamespace(
+ ui=SimpleNamespace(
+ orb_style="jarvis_bar",
+ bar_persistent=bar_persistent,
+ bar_accent="#e7c46e",
+ orb_mascot_path="",
+ )
+ )
+ return app
+
+
+def test_boot_persistent_bar_is_visible_not_withdrawn(monkeypatch) -> None:
+ # Don't spawn a real Tk window in the unit test.
+ monkeypatch.setattr(
+ JarvisBarOverlay, "start_in_thread", lambda self, timeout=3.0: None
+ )
+ surface = _app(bar_persistent=True)._build_overlay_surface("jarvis_bar")
+
+ assert isinstance(surface, JarvisBarOverlay)
+ assert surface._persistent is True
+ # Visible at boot — NOT gated behind VoiceBootStatus(ready=True) / a wake word.
+ assert surface._start_hidden is False
+ assert surface._should_start_withdrawn() is False
+
+
+def test_boot_non_persistent_bar_still_starts_withdrawn(monkeypatch) -> None:
+ monkeypatch.setattr(
+ JarvisBarOverlay, "start_in_thread", lambda self, timeout=3.0: None
+ )
+ surface = _app(bar_persistent=False)._build_overlay_surface("jarvis_bar")
+
+ # A non-persistent bar still pops on a real session (unchanged).
+ assert surface._should_start_withdrawn() is True
diff --git a/tests/unit/ui/jarvisbar/test_click_no_session_guard.py b/tests/unit/ui/jarvisbar/test_click_no_session_guard.py
new file mode 100644
index 0000000000..5f0cf3533f
--- /dev/null
+++ b/tests/unit/ui/jarvisbar/test_click_no_session_guard.py
@@ -0,0 +1,105 @@
+"""Regression — the bar must never fire a destructive (and useless) hang-up
+when no voice session is actually live.
+
+Forensic 2026-06-28 (data/jarvis_desktop.log ~07:49): a wake popped the bar into
+its active "listen" look, but the post-hangup wake-lock cooldown rejected the
+session, so NO ``VoiceSessionStarted`` and NO ``IDLE`` ``SystemStateChanged``
+followed — the bridge left the bar stuck in the active mode. In that stuck state
+``resolve_click`` reads a close-X click as ``"hangup"`` → ``request_hangup()``, a
+no-op that just traps the user ("frozen, nothing works"). The bar must instead
+treat a click as a session start whenever no session is live, so the user can
+always escape the stuck state.
+"""
+from __future__ import annotations
+
+from jarvis.ui.jarvisbar import renderer as R
+from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay
+
+
+class _FakePipeline:
+ def __init__(self, *, session_active: bool) -> None:
+ self._session_active = session_active
+ self.hangup_calls = 0
+ self.session_calls = 0
+ self.ptt_calls = 0
+
+ def is_session_active(self) -> bool:
+ return self._session_active
+
+ def request_hangup(self) -> None:
+ self.hangup_calls += 1
+
+ def request_voice_session(self) -> None:
+ self.session_calls += 1
+
+ def request_ptt_toggle(self) -> None:
+ self.ptt_calls += 1
+
+
+def _x_glyph() -> int:
+ """The on-screen End-X centre for the deployed pill (mirror renderer)."""
+ return round(R.WIN_W / 2.0 - 0.30 * R.ACTIVE_W)
+
+
+def _patch_pipeline(monkeypatch, fake) -> None:
+ # _on_click does `from jarvis.core.runtime_refs import get_speech_pipeline`
+ # at call time, so patching the module attribute is enough.
+ monkeypatch.setattr(
+ "jarvis.core.runtime_refs.get_speech_pipeline", lambda: fake
+ )
+
+
+def test_stuck_active_bar_without_session_starts_session_not_hangup(monkeypatch):
+ bar = JarvisBarOverlay()
+ bar._mode = "listen" # stuck active after a wake-lock-rejected wake
+ fake = _FakePipeline(session_active=False)
+ _patch_pipeline(monkeypatch, fake)
+
+ bar._on_click(_x_glyph(), hovered=True)
+
+ assert fake.hangup_calls == 0 # never the useless trap-hangup
+ assert fake.session_calls == 1 # the click escapes the stuck state
+
+
+def test_live_session_close_x_still_hangs_up(monkeypatch):
+ bar = JarvisBarOverlay()
+ bar._mode = "listen"
+ fake = _FakePipeline(session_active=True)
+ _patch_pipeline(monkeypatch, fake)
+
+ bar._on_click(_x_glyph(), hovered=True)
+
+ assert fake.hangup_calls == 1 # a genuine session is still hang-up-able
+ assert fake.session_calls == 0
+
+
+def test_missing_accessor_preserves_legacy_hangup(monkeypatch):
+ """Fail-safe: an older pipeline without ``is_session_active`` keeps the
+ legacy behaviour (trust ``_mode``) so the gate can never silence a real
+ hang-up by accident."""
+
+ class _Legacy:
+ def __init__(self) -> None:
+ self.hangup_calls = 0
+ self.session_calls = 0
+
+ def request_hangup(self) -> None:
+ self.hangup_calls += 1
+
+ def request_voice_session(self) -> None:
+ self.session_calls += 1
+
+ def request_ptt_toggle(self) -> None: # pragma: no cover - unused here
+ ...
+
+ fake = _Legacy()
+ monkeypatch.setattr(
+ "jarvis.core.runtime_refs.get_speech_pipeline", lambda: fake
+ )
+ bar = JarvisBarOverlay()
+ bar._mode = "listen"
+
+ bar._on_click(_x_glyph(), hovered=True)
+
+ assert fake.hangup_calls == 1
+ assert fake.session_calls == 0
diff --git a/tests/unit/ui/jarvisbar/test_frame_loop_resilience.py b/tests/unit/ui/jarvisbar/test_frame_loop_resilience.py
new file mode 100644
index 0000000000..2a42af130e
--- /dev/null
+++ b/tests/unit/ui/jarvisbar/test_frame_loop_resilience.py
@@ -0,0 +1,139 @@
+"""The JarvisBar animation loop must be self-healing.
+
+Forensic: the bar "stopped moving / froze" until an app restart. Root cause —
+``_schedule_frame`` re-arms the next frame ONLY from its tail line, so a single
+transient render/Tk error (e.g. ``ImageTk.PhotoImage`` raising, a ``TclError``
+during a window move) skips the re-arm and the loop dies permanently while the
+Tk mainloop keeps running (window stays visible, frozen on its last frame).
+
+These tests pin the contract: one frame error drops just that frame and the
+loop keeps ticking. Headless — a fake root/canvas/renderer, no real Tk display.
+"""
+from __future__ import annotations
+
+import time
+
+from jarvis.ui.jarvisbar.overlay import FRAME_STALL_THRESHOLD_NS, JarvisBarOverlay
+
+
+class _FakeRoot:
+ def __init__(self) -> None:
+ self.scheduled: list[tuple[int, object]] = []
+
+ def after(self, ms: int, fn: object) -> None:
+ self.scheduled.append((ms, fn))
+
+
+class _FakeCanvas:
+ def create_image(self, *a: object, **k: object) -> int:
+ return 1
+
+ def itemconfig(self, *a: object, **k: object) -> None:
+ pass
+
+
+class _BoomRenderer:
+ """A renderer whose render() always raises — simulates a transient
+ PIL/Tk hiccup mid-frame."""
+
+ def render(self, *a: object, **k: object): # noqa: ANN201
+ raise RuntimeError("transient render/Tk hiccup")
+
+
+def _bare_bar(renderer_obj: object) -> tuple[JarvisBarOverlay, _FakeRoot]:
+ bar = JarvisBarOverlay.__new__(JarvisBarOverlay)
+ bar._running = True
+ bar._mode = "think"
+ bar._ext_level = 0.0
+ bar._last_audible_t = 0.0
+ bar._t0 = 0.0
+ bar._hovered = False
+ bar._image_id = None
+ bar._photo = None
+ bar._last_frame_ns = 0
+ root = _FakeRoot()
+ bar._root = root
+ bar._canvas = _FakeCanvas()
+ bar._renderer = renderer_obj # type: ignore[assignment]
+ return bar, root
+
+
+def test_frame_loop_reschedules_after_render_error():
+ """A render exception must NOT kill the loop: the next frame is still armed
+ and the call itself does not propagate (the Tk mainloop must keep running)."""
+ bar, root = _bare_bar(_BoomRenderer())
+
+ bar._schedule_frame() # must not raise
+
+ assert root.scheduled, "frame loop died: next frame was not rescheduled"
+ ms, fn = root.scheduled[-1]
+ assert fn == bar._schedule_frame
+ assert ms == 16
+
+
+def test_frame_loop_stops_rearming_when_not_running():
+ """The self-heal must not fight a deliberate stop(): once _running is False
+ the loop returns early and does NOT re-arm."""
+ bar, root = _bare_bar(_BoomRenderer())
+ bar._running = False
+
+ bar._schedule_frame()
+
+ assert root.scheduled == []
+
+
+def test_frame_loop_stamps_a_heartbeat_even_when_render_fails():
+ """Every tick stamps ``_last_frame_ns`` so the watchdog can tell a live loop
+ from a dead one — and it must stamp even when the render itself raised, since
+ a dropped-but-rearmed frame is still a LIVING loop."""
+ bar, _root = _bare_bar(_BoomRenderer())
+ assert bar._last_frame_ns == 0
+
+ bar._schedule_frame() # render raises, finally must still stamp + re-arm
+
+ assert bar._last_frame_ns > 0, "frame loop did not stamp its heartbeat"
+
+
+def test_watchdog_revives_a_stalled_frame_loop():
+ """The watchdog is the second, independent after-chain. When the frame loop's
+ heartbeat goes stale (it died silently — the very class of bug the tail-only
+ re-arm cannot recover from), the watchdog must kick the frame loop back to
+ life."""
+ bar, root = _bare_bar(_BoomRenderer())
+ bar._last_frame_ns = time.monotonic_ns() - (FRAME_STALL_THRESHOLD_NS * 2)
+ revived: list[bool] = []
+ bar._schedule_frame = lambda: revived.append(True) # type: ignore[method-assign]
+
+ bar._schedule_frame_watchdog()
+
+ assert revived == [True], "watchdog did not revive the stalled frame loop"
+ assert any(
+ fn == bar._schedule_frame_watchdog for _ms, fn in root.scheduled
+ ), "watchdog did not re-arm itself"
+
+
+def test_watchdog_does_not_revive_a_healthy_loop():
+ """A fresh heartbeat means the loop is alive — the watchdog must NOT kick it
+ again (no double frame-chains, no spurious revival). It still re-arms itself.
+ This is the AP-19/BUG-032 guard: a continuously-stamped heartbeat cannot
+ false-fire while the loop is actually ticking."""
+ bar, root = _bare_bar(_BoomRenderer())
+ bar._last_frame_ns = time.monotonic_ns() # just ticked
+ revived: list[bool] = []
+ bar._schedule_frame = lambda: revived.append(True) # type: ignore[method-assign]
+
+ bar._schedule_frame_watchdog()
+
+ assert revived == [], "watchdog falsely revived a healthy loop"
+ assert any(fn == bar._schedule_frame_watchdog for _ms, fn in root.scheduled)
+
+
+def test_watchdog_stops_when_not_running():
+ """A deliberate stop() must end the watchdog too — once _running is False it
+ returns early and does not re-arm."""
+ bar, root = _bare_bar(_BoomRenderer())
+ bar._running = False
+
+ bar._schedule_frame_watchdog()
+
+ assert root.scheduled == []
diff --git a/tests/unit/ui/jarvisbar/test_hover_expand_stability.py b/tests/unit/ui/jarvisbar/test_hover_expand_stability.py
new file mode 100644
index 0000000000..fca2fac994
--- /dev/null
+++ b/tests/unit/ui/jarvisbar/test_hover_expand_stability.py
@@ -0,0 +1,164 @@
+"""The idle bar must stay expanded WHILE hovered and collapse only on real exit.
+
+Forensic (2026-06-28): hovering the idle (non-active) bar made it "open briefly
+and immediately snap shut". Root cause — the idle pill SIZE is bound to the
+instantaneous ``_hovered`` flag, which Tk drives from ``<Enter>``/``<Leave>``
+over the COLOR-KEYED opaque pill. That pill is a tiny ~48x8 px sliver inside a
+107x48 window (the rest is click-through magenta), redrawn every frame with
+antialiased edges, and it RESIZES on hover. So the pointer near its edge emits
+rapid ``<Leave>``/``<Enter>`` pairs; each ``<Leave>`` collapsed the pill, which
+shrank the opaque region inward under the pointer and reinforced the collapse.
+
+The fix decouples the collapse from the raw ``<Leave>``: a leave starts a short
+poll of the REAL pointer position and the idle pill collapses only once the
+pointer has genuinely left the bar's window rect. The ACTIVE state is untouched
+— its pill size comes from ``_mode``, and its hover controls keep the old,
+instantaneous ``_hovered`` flag.
+
+Headless — a fake root (after / after_cancel / winfo_pointerxy), no real Tk.
+"""
+from __future__ import annotations
+
+from jarvis.ui.jarvisbar import interaction as I
+from jarvis.ui.jarvisbar import renderer as R
+from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay
+
+
+class _FakeRoot:
+ """Fakes the bits of Tk the collapse poll touches. The window rect is the
+ LIVE on-screen geometry (winfo_rootx/rooty/width/height) — the same source
+ the production code now reads — defaulting to the bar's footprint at (100,100).
+ """
+
+ def __init__(
+ self, pointer: tuple[int, int] = (0, 0), rect: tuple[int, int, int, int] | None = None
+ ) -> None:
+ self.pointer = pointer
+ self.rect = rect or (100, 100, R.WIN_W, R.WIN_H) # (x, y, w, h)
+ self.after_calls: list[tuple[int, object, int]] = []
+ self.cancelled: list[int] = []
+ self._next_id = 0
+
+ def after(self, ms: int, fn: object) -> int:
+ self._next_id += 1
+ self.after_calls.append((ms, fn, self._next_id))
+ return self._next_id
+
+ def after_cancel(self, cid: int) -> None:
+ self.cancelled.append(cid)
+
+ def winfo_pointerxy(self) -> tuple[int, int]:
+ return self.pointer
+
+ def winfo_rootx(self) -> int:
+ return self.rect[0]
+
+ def winfo_rooty(self) -> int:
+ return self.rect[1]
+
+ def winfo_width(self) -> int:
+ return self.rect[2]
+
+ def winfo_height(self) -> int:
+ return self.rect[3]
+
+
+def _idle_bar(pointer: tuple[int, int]) -> tuple[JarvisBarOverlay, _FakeRoot]:
+ bar = JarvisBarOverlay()
+ bar._mode = "idle" # noqa: SLF001
+ bar._x, bar._y = 100, 100 # noqa: SLF001 — window top-left in screen coords
+ root = _FakeRoot(pointer=pointer)
+ bar._root = root # noqa: SLF001
+ return bar, root
+
+
+def _center() -> tuple[int, int]:
+ return (100 + R.WIN_W // 2, 100 + R.WIN_H // 2)
+
+
+# --------------------------------------------------------------------------- #
+# Pure geometry helper #
+# --------------------------------------------------------------------------- #
+def test_pointer_in_window_bounds():
+ assert I.pointer_in_window(50, 50, 0, 0, 100, 100) is True
+ assert I.pointer_in_window(-1, 50, 0, 0, 100, 100) is False
+ assert I.pointer_in_window(50, 200, 0, 0, 100, 100) is False
+ assert I.pointer_in_window(0, 0, 0, 0, 100, 100) is True # top-left inclusive
+ assert I.pointer_in_window(100, 100, 0, 0, 100, 100) is False # bottom-right exclusive
+
+
+# --------------------------------------------------------------------------- #
+# Idle hover stability — the actual bug #
+# --------------------------------------------------------------------------- #
+def test_enter_expands_idle_bar():
+ bar, _root = _idle_bar(_center())
+ bar._on_enter() # noqa: SLF001
+ assert bar._hover_expanded is True # noqa: SLF001
+
+
+def test_spurious_leave_keeps_expanded_while_pointer_over_bar():
+ """The regression: an edge/antialiasing ``<Leave>`` fired while the pointer
+ is STILL over the bar's footprint must NOT collapse the idle pill."""
+ bar, root = _idle_bar(_center())
+ bar._on_enter() # noqa: SLF001
+ bar._on_leave() # noqa: SLF001 — spurious leave; pointer still inside
+
+ # Not collapsed synchronously; a poll was scheduled instead.
+ assert bar._hover_expanded is True # noqa: SLF001
+ assert root.after_calls, "collapse poll was not scheduled"
+
+ # Running the poll keeps it open (pointer still inside) and re-arms.
+ _ms, fn, _cid = root.after_calls[-1]
+ fn()
+ assert bar._hover_expanded is True # noqa: SLF001
+ assert len(root.after_calls) >= 2, "poll did not re-arm while still hovered"
+
+
+def test_collapse_only_after_pointer_leaves_footprint():
+ bar, root = _idle_bar(pointer=(0, 0)) # pointer far outside the window rect
+ bar._on_enter() # noqa: SLF001
+ bar._on_leave() # noqa: SLF001
+ _ms, fn, _cid = root.after_calls[-1]
+ fn() # poll sees the pointer outside → collapse
+ assert bar._hover_expanded is False # noqa: SLF001
+
+
+def test_enter_cancels_pending_collapse_poll():
+ bar, root = _idle_bar(pointer=(0, 0))
+ bar._on_enter() # noqa: SLF001
+ bar._on_leave() # noqa: SLF001 — schedules a poll
+ pending = bar._hover_collapse_id # noqa: SLF001
+ assert pending is not None
+
+ bar._on_enter() # noqa: SLF001 — re-entering must cancel the pending collapse
+ assert pending in root.cancelled
+ assert bar._hover_expanded is True # noqa: SLF001
+ assert bar._hover_collapse_id is None # noqa: SLF001
+
+
+def test_no_tk_root_falls_back_to_immediate_collapse():
+ """Headless / pre-start: with no Tk root, a leave collapses immediately so
+ the flag never sticks True without a poll to clear it."""
+ bar = JarvisBarOverlay()
+ bar._mode = "idle" # noqa: SLF001
+ bar._on_enter() # noqa: SLF001 — _root is None
+ assert bar._hover_expanded is True # noqa: SLF001
+ bar._on_leave() # noqa: SLF001
+ assert bar._hover_expanded is False # noqa: SLF001
+
+
+# --------------------------------------------------------------------------- #
+# Active state stays exactly as before #
+# --------------------------------------------------------------------------- #
+def test_active_hover_uses_instantaneous_flag_unchanged():
+ """The active bar's controls follow the raw ``_hovered`` flag (hidden the
+ instant the pointer leaves the opaque pill) — unchanged by the idle fix."""
+ bar = JarvisBarOverlay()
+ bar._mode = "speak" # noqa: SLF001 — live session
+ bar._x, bar._y = 100, 100 # noqa: SLF001
+ bar._root = _FakeRoot(pointer=_center()) # noqa: SLF001
+
+ bar._on_enter() # noqa: SLF001
+ assert bar._hovered is True # noqa: SLF001
+ bar._on_leave() # noqa: SLF001
+ assert bar._hovered is False # noqa: SLF001 — instantaneous, as before
diff --git a/tests/unit/ui/whisperbar/test_interaction.py b/tests/unit/ui/jarvisbar/test_interaction.py
similarity index 53%
rename from tests/unit/ui/whisperbar/test_interaction.py
rename to tests/unit/ui/jarvisbar/test_interaction.py
index 2b7b71bfef..75efbaac12 100644
--- a/tests/unit/ui/whisperbar/test_interaction.py
+++ b/tests/unit/ui/jarvisbar/test_interaction.py
@@ -1,8 +1,8 @@
-"""Unit tests for whisper-bar click/drag classification + default placement."""
+"""Unit tests for jarvis-bar click/drag classification + default placement."""
from __future__ import annotations
-from jarvis.ui.whisperbar import interaction as I
-from jarvis.ui.whisperbar import renderer as R
+from jarvis.ui.jarvisbar import interaction as I
+from jarvis.ui.jarvisbar import renderer as R
def test_is_drag_threshold():
@@ -16,12 +16,12 @@ def test_classify_release():
assert I.classify_release(moved=True) == "drag"
-def test_resolve_click_idle_and_dictate_zones():
+def test_resolve_click_idle_and_mute_zones():
W = 100
- # right zone → the square → dictate (non-destructive), regardless of state
- assert I.resolve_click(90, W, "idle") == "dictate"
- assert I.resolve_click(90, W, "listen") == "dictate"
- # idle → a click anywhere starts a normal session
+ # right zone → the microphone → mute toggle (non-destructive), any state
+ assert I.resolve_click(90, W, "idle") == "mute"
+ assert I.resolve_click(90, W, "listen") == "mute"
+ # idle → a click anywhere else starts a normal session
assert I.resolve_click(10, W, "idle") == "talk" # idle left → start normal session
assert I.resolve_click(50, W, "idle") == "talk"
# active middle (no control there) → nothing
@@ -31,42 +31,42 @@ def test_resolve_click_idle_and_dictate_zones():
def test_active_bar_body_click_does_not_hang_up():
"""REGRESSION — the silent-hangup trap (live bug 2026-06-19).
- A low-intent click on the BODY of an active bar — where the user sees only
- the equalizer / orbital-core and NO close-X (the X is drawn only on hover,
- renderer.py) — must NOT end the session. The old code treated the whole
- left 40% of the bar as the hang-up X, so any such click silently hung up
- ("Jarvis legt von selbst auf, ich hab nichts von Auflegen gesagt").
+ A low-intent click on the BODY of an active bar — between the End button and
+ the mic, where NO control is drawn — must NOT end the session. The old code
+ treated the whole left 40% of the bar as the hang-up X, so any such click
+ silently hung up ("Jarvis legt von selbst auf, ich hab nichts von Auflegen
+ gesagt").
"""
W, PW = 100, 100
- # Left-of-centre body, past the X glyph (centre ≈ cx - 0.42*pw = 8) → none,
- # even with the controls shown and across every active state.
- assert I.resolve_click(35, W, "speak", hovered=True, pill_w=PW) == "none"
- assert I.resolve_click(35, W, "listen", hovered=True, pill_w=PW) == "none"
- assert I.resolve_click(35, W, "think", hovered=True, pill_w=PW) == "none"
+ # Body gap between the End X (centre 20, hit ±16 → up to 36) and the mic zone
+ # (frac ≥ 0.60 → x ≥ 60): a click at 48 lands on neither → none.
+ assert I.resolve_click(48, W, "speak", hovered=True, pill_w=PW) == "none"
+ assert I.resolve_click(48, W, "listen", hovered=True, pill_w=PW) == "none"
+ assert I.resolve_click(48, W, "think", hovered=True, pill_w=PW) == "none"
-def test_hangup_requires_visible_close_x():
- """A hang-up fires only when the close-X is actually shown (hovered) AND the
- click lands on the X glyph — so behaviour matches the visible affordance."""
+def test_hangup_requires_visible_end_button():
+ """A hang-up fires only when the End X is actually shown (hovered) AND the
+ click lands on it — so behaviour matches the visible affordance."""
W, PW = 100, 100
- # X glyph centre ≈ cx - 0.42*pw = 8 for these dimensions.
- # On the X, controls visible → hang up (the deliberate gesture still works).
- assert I.resolve_click(8, W, "speak", hovered=True, pill_w=PW) == "hangup"
+ # End-X centre ≈ cx - 0.30*pw = 20 for these dimensions.
+ # On the X, controls visible → hang up (the deliberate gesture works).
+ assert I.resolve_click(20, W, "speak", hovered=True, pill_w=PW) == "hangup"
# Same spot, but the controls are NOT shown (not hovered) → no hang up.
- assert I.resolve_click(8, W, "speak", hovered=False, pill_w=PW) == "none"
- # Hovered, but the click is far from the X (centre of the bar) → no hang up.
+ assert I.resolve_click(20, W, "speak", hovered=False, pill_w=PW) == "none"
+ # Hovered, but the click is far from the X (centre of the bar) → none.
assert I.resolve_click(50, W, "speak", hovered=True, pill_w=PW) == "none"
def test_hangup_hitbox_at_real_bar_geometry():
"""Anchor the contract to the ACTUAL deployed pill, not just W=PW=100.
- At the real dims the close-X glyph sits at WIN_W/2 - 0.42*ACTIVE_W, the
- equalizer bars start ~24px in, and the bar window is only ~107px wide — so a
- centre click (over the bars) must NOT hang up while a click on the X does.
+ At the real dims the End X sits at WIN_W/2 - 0.30*ACTIVE_W and the bar window
+ is ~107px wide — so a centre click (over the equalizer) must NOT hang up
+ while a click on the End X does.
"""
W, PW = R.WIN_W, R.ACTIVE_W
- x_glyph = round(W / 2.0 - 0.42 * PW) # mirror renderer._draw_close_x centre
+ x_glyph = round(W / 2.0 - 0.30 * PW) # mirror renderer x_left (End X)
# Deliberate click on the visible X glyph, controls shown → hang up.
assert I.resolve_click(x_glyph, W, "speak", hovered=True, pill_w=PW) == "hangup"
# The bar's centre (where the live equalizer is drawn) → never a hang up.
@@ -99,21 +99,21 @@ def test_clamp_to_screen_keeps_bar_visible():
def test_position_round_trip(tmp_path):
cfg = tmp_path / "jarvis.toml"
- cfg.write_text("[ui]\norb_style = \"whisper_bar\"\n", encoding="utf-8")
- assert I.load_whisperbar_position(cfg) is None # not set yet
- I.save_whisperbar_position(cfg, 640, 980)
- assert I.load_whisperbar_position(cfg) == (640, 980)
+ cfg.write_text("[ui]\norb_style = \"jarvis_bar\"\n", encoding="utf-8")
+ assert I.load_jarvisbar_position(cfg) is None # not set yet
+ I.save_jarvisbar_position(cfg, 640, 980)
+ assert I.load_jarvisbar_position(cfg) == (640, 980)
# overwrite + preserve the pre-existing [ui] section
- I.save_whisperbar_position(cfg, 100, 200)
- assert I.load_whisperbar_position(cfg) == (100, 200)
+ I.save_jarvisbar_position(cfg, 100, 200)
+ assert I.load_jarvisbar_position(cfg) == (100, 200)
assert "orb_style" in cfg.read_text(encoding="utf-8")
def test_load_missing_file_is_none(tmp_path):
- assert I.load_whisperbar_position(tmp_path / "nope.toml") is None
+ assert I.load_jarvisbar_position(tmp_path / "nope.toml") is None
def test_save_missing_file_is_noop(tmp_path):
missing = tmp_path / "nope.toml"
- I.save_whisperbar_position(missing, 1, 2) # must not raise
+ I.save_jarvisbar_position(missing, 1, 2) # must not raise
assert not missing.exists()
diff --git a/tests/unit/ui/jarvisbar/test_mute_button.py b/tests/unit/ui/jarvisbar/test_mute_button.py
new file mode 100644
index 0000000000..4eee746177
--- /dev/null
+++ b/tests/unit/ui/jarvisbar/test_mute_button.py
@@ -0,0 +1,109 @@
+"""The jarvis-bar RIGHT control is the microphone mute toggle.
+
+Replaces the former endpoint-free-dictation square (maintainer request,
+2026-06-28): clicking the mic fires the wired ``_on_mute_toggle`` (which the
+OrbBusBridge points at ``VoiceMuteToggleRequested``) and optimistically flips
+the local mirror so the slashed-mic icon shows on the very next frame. The
+authoritative ``VoiceMuteChanged`` is reconciled via ``set_muted``.
+"""
+from __future__ import annotations
+
+from jarvis.ui.jarvisbar import renderer as R
+from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay
+
+
+class _FakePipeline:
+ """Minimal pipeline: the mute path only needs a non-None pipeline + the
+ session probe; the toggle itself goes through ``_on_mute_toggle``."""
+
+ def is_session_active(self) -> bool:
+ return True
+
+ def request_voice_session(self) -> None: # pragma: no cover - unused here
+ ...
+
+ def request_hangup(self) -> None: # pragma: no cover - unused here
+ ...
+
+
+def _mic_x() -> int:
+ """The on-screen microphone-button centre (mirror renderer x_right)."""
+ return round(R.WIN_W / 2.0 + 0.30 * R.ACTIVE_W)
+
+
+def _patch_pipeline(monkeypatch, fake) -> None:
+ monkeypatch.setattr(
+ "jarvis.core.runtime_refs.get_speech_pipeline", lambda: fake
+ )
+
+
+def test_mic_click_fires_toggle_and_optimistically_mutes(monkeypatch):
+ bar = JarvisBarOverlay()
+ fired: list[int] = []
+ bar.set_on_mute_toggle(lambda: fired.append(1))
+ _patch_pipeline(monkeypatch, _FakePipeline())
+
+ assert bar._muted is False
+ bar._on_click(_mic_x(), hovered=True)
+ assert fired == [1]
+ assert bar._muted is True # optimistic flip → slash shows immediately
+
+ bar._on_click(_mic_x(), hovered=True)
+ assert fired == [1, 1]
+ assert bar._muted is False # toggles back
+
+
+def test_mic_click_without_callback_is_noop(monkeypatch):
+ bar = JarvisBarOverlay()
+ bar._on_mute_toggle = None # boot race: bridge not wired yet
+ _patch_pipeline(monkeypatch, _FakePipeline())
+
+ bar._on_click(_mic_x(), hovered=True)
+ assert bar._muted is False # no callback → genuine no-op, no false slash
+
+
+def test_set_muted_mirrors_authoritative_state():
+ bar = JarvisBarOverlay()
+ bar.set_muted(True)
+ assert bar._muted is True
+ bar.set_muted(False)
+ assert bar._muted is False
+
+
+def test_muted_render_differs_from_unmuted():
+ """The slashed-mic (red disc + white slash) must be visibly distinct from
+ the live mic so the user can tell at a glance whether they are muted."""
+ rnd = R.JarvisBarRenderer()
+ for _ in range(60): # settle the eased pill size
+ rnd.render(0.0, "listen", 0.0, hovered=True, muted=False)
+ unmuted = list(rnd.render(0.1, "listen", 0.0, hovered=True, muted=False).getdata())
+ muted = list(rnd.render(0.1, "listen", 0.0, hovered=True, muted=True).getdata())
+ assert unmuted != muted
+
+
+def test_muted_render_is_safe_for_every_mode():
+ rnd = R.JarvisBarRenderer()
+ for mode in ("idle", "listen", "speak", "think"):
+ img = rnd.render(0.1, mode, 0.5, hovered=True, muted=True)
+ assert img.size == (R.WIN_W, R.WIN_H)
+
+
+def test_muted_idle_pill_stays_open_not_collapsed():
+ """A muted user must not be left with the tiny empty collapsed pill: the bar
+ stays OPEN so the red rim + slashed mic (the ONLY unmute target — voice can't
+ unmute while Jarvis is deaf) are always on screen. Forensic 2026-06-29: a
+ user got 'stuck muted' and read the silent collapsed bar as 'frozen'."""
+ assert R.target_pill_size("idle", hovered=False, muted=True) == (R.OPEN_W, R.OPEN_H)
+ assert R.target_pill_size("idle", hovered=False, muted=False) == (
+ R.COLLAPSED_W,
+ R.COLLAPSED_H,
+ )
+
+
+def test_muted_idle_shows_slashed_mic_without_hover():
+ """Muted standby renders the slashed mic even with no hover, so the muted
+ state (and the click-to-unmute target) is always visible — unlike the clean
+ empty idle pill when unmuted."""
+ empty = R.JarvisBarRenderer().render(0.1, "idle", 0.0, hovered=False, muted=False)
+ muted = R.JarvisBarRenderer().render(0.1, "idle", 0.0, hovered=False, muted=True)
+ assert list(empty.getdata()) != list(muted.getdata())
diff --git a/tests/unit/ui/jarvisbar/test_phantom_click_guard.py b/tests/unit/ui/jarvisbar/test_phantom_click_guard.py
new file mode 100644
index 0000000000..c710c3349b
--- /dev/null
+++ b/tests/unit/ui/jarvisbar/test_phantom_click_guard.py
@@ -0,0 +1,78 @@
+"""Regression — the bar must ignore SYNTHETIC / phantom button events.
+
+Forensic 2026-06-28 (data/jarvis_desktop.log ~22:14): a frameless color-key
+topmost Tk window emitted phantom press/release events on withdraw / deiconify /
+turn-mode-switch under a stationary cursor. Read as close-X clicks, they fired a
+machine-paced ``request_hangup`` STORM that killed live sessions AND armed the
+3 s post-hangup wake-lock, so the next "Hey Jarvis" was swallowed ("wake triggers,
+nothing happens"). ``_on_release`` must honour a click only when the OS pointer
+is really over the bar — ``_pointer_over_bar`` is that guard. It uses only Tk's
+own screen-pixel measurements, so it stays correct under HiDPI scaling, and it
+fails CLOSED (a missed real click is recoverable, a phantom hang-up is not).
+"""
+from __future__ import annotations
+
+from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay
+
+
+class _FakeRoot:
+ """Minimal stand-in for the Tk root with the four winfo_* probes the
+ guard reads. Coordinates are in one screen-pixel space (as real Tk)."""
+
+ def __init__(
+ self, *, mapped: int = 1, w: int = 320, h: int = 64,
+ rx: int = 100, ry: int = 900, px: int = 150, py: int = 920,
+ ) -> None:
+ self._mapped, self._w, self._h = mapped, w, h
+ self._rx, self._ry, self._px, self._py = rx, ry, px, py
+
+ def winfo_ismapped(self) -> int:
+ return self._mapped
+
+ def winfo_width(self) -> int:
+ return self._w
+
+ def winfo_height(self) -> int:
+ return self._h
+
+ def winfo_rootx(self) -> int:
+ return self._rx
+
+ def winfo_rooty(self) -> int:
+ return self._ry
+
+ def winfo_pointerxy(self) -> tuple[int, int]:
+ return (self._px, self._py)
+
+
+def test_pointer_inside_bar_is_a_real_click() -> None:
+ bar = JarvisBarOverlay()
+ bar._root = _FakeRoot(rx=100, ry=900, w=320, h=64, px=150, py=920)
+ assert bar._pointer_over_bar() is True
+
+
+def test_pointer_far_from_bar_is_a_phantom() -> None:
+ bar = JarvisBarOverlay()
+ # Cursor parked at the desktop top-left while the bar sits at the bottom —
+ # the exact deiconify-under-stationary-cursor phantom.
+ bar._root = _FakeRoot(rx=100, ry=900, w=320, h=64, px=10, py=10)
+ assert bar._pointer_over_bar() is False
+
+
+def test_unmapped_window_fails_closed() -> None:
+ bar = JarvisBarOverlay()
+ bar._root = _FakeRoot(mapped=0, px=150, py=920)
+ assert bar._pointer_over_bar() is False
+
+
+def test_zero_size_window_fails_closed() -> None:
+ # Right after deiconify Tk may report a 1x1 window before layout settles.
+ bar = JarvisBarOverlay()
+ bar._root = _FakeRoot(w=1, h=1, px=150, py=920)
+ assert bar._pointer_over_bar() is False
+
+
+def test_no_root_fails_closed() -> None:
+ bar = JarvisBarOverlay()
+ bar._root = None
+ assert bar._pointer_over_bar() is False
diff --git a/tests/unit/ui/whisperbar/test_renderer.py b/tests/unit/ui/jarvisbar/test_renderer.py
similarity index 96%
rename from tests/unit/ui/whisperbar/test_renderer.py
rename to tests/unit/ui/jarvisbar/test_renderer.py
index f63168b85b..8d67496a88 100644
--- a/tests/unit/ui/whisperbar/test_renderer.py
+++ b/tests/unit/ui/jarvisbar/test_renderer.py
@@ -1,9 +1,9 @@
-"""Unit tests for the whisper-bar pure renderer math + draw smoke."""
+"""Unit tests for the jarvis-bar pure renderer math + draw smoke."""
from __future__ import annotations
import pytest
-from jarvis.ui.whisperbar import renderer as R
+from jarvis.ui.jarvisbar import renderer as R
def test_ease_moves_toward_target():
@@ -163,7 +163,7 @@ def test_core_highlight_swings_across_the_sphere():
def test_render_think_mode_animates_over_time():
- r = R.WhisperBarRenderer()
+ r = R.JarvisBarRenderer()
for _ in range(60): # settle pill size
r.render(0.0, "think", 0.0)
a = list(r.render(1.0, "think", 0.0).getdata())
@@ -172,7 +172,7 @@ def test_render_think_mode_animates_over_time():
def test_render_returns_image_for_every_mode():
- rnd = R.WhisperBarRenderer(accent="#e7c46e")
+ rnd = R.JarvisBarRenderer(accent="#e7c46e")
for mode in ("idle", "listen", "speak", "think"):
img = rnd.render(0.1, mode, 0.5)
assert img.size == (R.WIN_W, R.WIN_H)
@@ -180,7 +180,7 @@ def test_render_returns_image_for_every_mode():
def _settled(mode, hovered, frames=40, final_t=0.1):
- r = R.WhisperBarRenderer()
+ r = R.JarvisBarRenderer()
for _ in range(frames):
r.render(0.0, mode, 0.0) # deterministic settle
return list(r.render(final_t, mode, 0.0, hovered=hovered).getdata())
@@ -198,7 +198,7 @@ def test_hover_reveals_controls():
def test_idle_collapses_expansion_over_frames():
- rnd = R.WhisperBarRenderer()
+ rnd = R.JarvisBarRenderer()
for _ in range(40):
rnd.render(0.0, "listen", 0.5)
active_h = rnd._st.ph
@@ -265,7 +265,7 @@ def test_visual_mode_shows_bars_while_tts_playback_is_active():
def _grow_settle(mode, *, hovered=False, frames=120):
"""Run enough frames that the eased pill size has converged on its target."""
- r = R.WhisperBarRenderer()
+ r = R.JarvisBarRenderer()
for _ in range(frames):
r.render(0.0, mode, 0.0, hovered=hovered)
return r
@@ -311,7 +311,7 @@ def test_equalizer_bars_scale_with_pill_height():
assert R.bar_max_for(R.ACTIVE_H) > R.bar_max_for(R.OPEN_H)
-# --- a dictation app-style refinement: thin strokes + standby dots ---------------------
+# --- Slim-bar refinement: thin strokes + standby dots ---------------------
def test_evenly_spaced_is_centered_and_symmetric():
@@ -329,7 +329,7 @@ def test_evenly_spaced_single_item_sits_at_center():
def test_idle_pill_is_empty_no_standby_dots():
# When nothing is happening the standby pill is CLEAN — no dots, no bars.
# (User: "when nothing is happening, nothing is in the bar.")
- r = R.WhisperBarRenderer()
+ r = R.JarvisBarRenderer()
img = None
for _ in range(150): # settle to the collapsed idle pill
img = r.render(0.0, "idle", 0.0)
@@ -343,5 +343,5 @@ def test_idle_pill_is_empty_no_standby_dots():
def test_active_bars_are_slim_not_chunky():
- # a dictation app-style: the equalizer strokes are thin, not the old chunky ~6px bars.
+ # Slim-bar style: the equalizer strokes are thin, not the old chunky ~6px bars.
assert R.bar_half_w_for(R.ACTIVE_W) <= 2.0
diff --git a/tests/unit/ui/jarvisbar/test_show_lifts_topmost.py b/tests/unit/ui/jarvisbar/test_show_lifts_topmost.py
new file mode 100644
index 0000000000..df005eeec1
--- /dev/null
+++ b/tests/unit/ui/jarvisbar/test_show_lifts_topmost.py
@@ -0,0 +1,73 @@
+"""The reveal path must LIFT + re-pin topmost, not just deiconify.
+
+Forensic (2026-06-27): on the fast-boot path the persistent bar's boot reveal
+(``VoiceBootStatus(ready=True)`` → ``show("idle")``) fires within ~200 ms of
+window creation, before the desktop main window + tray finish mapping. A
+withdrawn→deiconified ``overrideredirect`` window loses its topmost z-order on
+Windows, so the later boot windows mapped on top of the bar and it stayed hidden
+until the first wake-word re-showed it ("bar does not appear when ready, only
+after the wake-word"). ``_do_show`` now re-asserts ``-topmost`` and lifts, matching
+the mascot orb. These tests pin that contract without a real Tk window.
+"""
+from __future__ import annotations
+
+from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay
+
+
+class _FakeRoot:
+ """Records the order of the visibility calls ``_do_show`` makes."""
+
+ def __init__(self) -> None:
+ self.calls: list[str] = []
+ self.attrs: dict[str, object] = {}
+
+ def deiconify(self) -> None:
+ self.calls.append("deiconify")
+
+ def lift(self) -> None:
+ self.calls.append("lift")
+
+ def wm_attributes(self, name: str, value: object) -> None:
+ self.calls.append(f"wm_attributes:{name}={value}")
+ self.attrs[name] = value
+
+
+def _bar_with_fake_root() -> tuple[JarvisBarOverlay, _FakeRoot]:
+ bar = JarvisBarOverlay(persistent=True)
+ root = _FakeRoot()
+ bar._root = root # noqa: SLF001 — inject a fake Tk root (no real window)
+ return bar, root
+
+
+def test_do_show_deiconifies_then_lifts_and_repins_topmost() -> None:
+ bar, root = _bar_with_fake_root()
+
+ bar._do_show() # noqa: SLF001
+
+ # deiconify must come first, then the topmost re-assert + lift.
+ assert root.calls[0] == "deiconify"
+ assert "lift" in root.calls
+ assert root.attrs.get("-topmost") is True
+ # The lift happens after the deiconify (Windows remaps without topmost).
+ assert root.calls.index("deiconify") < root.calls.index("lift")
+
+
+def test_do_show_lift_failure_does_not_swallow_deiconify() -> None:
+ bar, root = _bar_with_fake_root()
+
+ def _boom(*_a: object, **_k: object) -> None:
+ raise RuntimeError("lift exploded")
+
+ root.lift = _boom # type: ignore[method-assign]
+
+ # Must not raise even when the lift/topmost re-assert fails — the deiconify
+ # already ran and the bar is visible; the lift is best-effort.
+ bar._do_show() # noqa: SLF001
+
+ assert "deiconify" in root.calls
+
+
+def test_do_show_safe_without_root() -> None:
+ bar = JarvisBarOverlay(persistent=True)
+ # No Tk root yet (boot race) → silent no-op, never raises.
+ bar._do_show() # noqa: SLF001
diff --git a/tests/unit/ui/whisperbar/test_show_window_gesture.py b/tests/unit/ui/jarvisbar/test_show_window_gesture.py
similarity index 76%
rename from tests/unit/ui/whisperbar/test_show_window_gesture.py
rename to tests/unit/ui/jarvisbar/test_show_window_gesture.py
index 4d75540e11..3510493571 100644
--- a/tests/unit/ui/whisperbar/test_show_window_gesture.py
+++ b/tests/unit/ui/jarvisbar/test_show_window_gesture.py
@@ -1,4 +1,4 @@
-"""Whisper-bar right-click → show-window gesture.
+"""Jarvis-bar right-click → show-window gesture.
The bar exposes ``set_on_show_window`` (injected by OrbBusBridge) and binds
``<Button-3>`` to ``_on_right_click``, which fires that callback. The handler
@@ -6,18 +6,18 @@ must be safe before/without a callback (boot race / no bridge).
"""
from __future__ import annotations
-from jarvis.ui.whisperbar.overlay import WhisperBarOverlay
+from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay
def test_set_on_show_window_stores_callback() -> None:
- bar = WhisperBarOverlay(persistent=False, accent="#abcdef")
+ bar = JarvisBarOverlay(persistent=False, accent="#abcdef")
cb = lambda: None # noqa: E731
bar.set_on_show_window(cb)
assert bar._on_show_window is cb # noqa: SLF001
def test_right_click_fires_show_window_callback() -> None:
- bar = WhisperBarOverlay(persistent=False)
+ bar = JarvisBarOverlay(persistent=False)
fired: list[bool] = []
bar.set_on_show_window(lambda: fired.append(True))
@@ -27,6 +27,6 @@ def test_right_click_fires_show_window_callback() -> None:
def test_right_click_safe_without_callback() -> None:
- bar = WhisperBarOverlay(persistent=False)
+ bar = JarvisBarOverlay(persistent=False)
# No callback registered → must be a silent no-op, never raise.
bar._on_right_click(None) # noqa: SLF001
diff --git a/tests/unit/ui/whisperbar/test_start_hidden.py b/tests/unit/ui/jarvisbar/test_start_hidden.py
similarity index 50%
rename from tests/unit/ui/whisperbar/test_start_hidden.py
rename to tests/unit/ui/jarvisbar/test_start_hidden.py
index 601cc3eea0..e152330a34 100644
--- a/tests/unit/ui/whisperbar/test_start_hidden.py
+++ b/tests/unit/ui/jarvisbar/test_start_hidden.py
@@ -1,19 +1,20 @@
-"""A persistent WhisperBar must be able to start HIDDEN at boot.
-
-The persistent bar normally maps its Tk window the moment the mainloop runs
-(no ``withdraw``), so on boot it appears seconds before the speech pipeline can
-actually hear the user — the "looks ready but isn't" boot confusion. The boot
-wiring opts the persistent bar into ``start_hidden=True`` and only reveals it
-once voice is ready; these tests pin the start-withdrawn decision so the boot
-path stays headless-testable (no real Tk window needed).
+"""The ``start_hidden`` capability of the JarvisBar overlay.
+
+A persistent bar normally maps its Tk window the moment the mainloop runs (no
+``withdraw``); ``start_hidden=True`` lets a caller opt it into starting
+withdrawn instead. NOTE: the boot wiring no longer uses ``start_hidden`` for the
+persistent bar — the bar is visible immediately at boot, decoupled from the
+voice/wake path (see ``tests/unit/ui/jarvisbar/test_boot_visibility.py``). These
+tests pin the overlay's own start-withdrawn decision so the boot path stays
+headless-testable (no real Tk window needed).
"""
from __future__ import annotations
-from jarvis.ui.whisperbar.overlay import WhisperBarOverlay
+from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay
def test_persistent_bar_with_start_hidden_starts_withdrawn() -> None:
- bar = WhisperBarOverlay(persistent=True, start_hidden=True)
+ bar = JarvisBarOverlay(persistent=True, start_hidden=True)
assert bar._start_hidden is True
assert bar._should_start_withdrawn() is True
@@ -22,7 +23,7 @@ def test_persistent_bar_default_does_not_start_withdrawn() -> None:
# Backward compatibility: without start_hidden a persistent bar is mapped
# immediately, exactly as before (e.g. the live swap / set_bar_persistent
# paths that explicitly show it after construction).
- bar = WhisperBarOverlay(persistent=True)
+ bar = JarvisBarOverlay(persistent=True)
assert bar._start_hidden is False
assert bar._should_start_withdrawn() is False
@@ -30,5 +31,5 @@ def test_persistent_bar_default_does_not_start_withdrawn() -> None:
def test_non_persistent_bar_starts_withdrawn_regardless() -> None:
# The non-persistent bar already starts hidden (pops on a session); the new
# flag must not change that.
- bar = WhisperBarOverlay(persistent=False)
+ bar = JarvisBarOverlay(persistent=False)
assert bar._should_start_withdrawn() is True
diff --git a/tests/unit/ui/whisperbar/test_surface_contract.py b/tests/unit/ui/jarvisbar/test_surface_contract.py
similarity index 80%
rename from tests/unit/ui/whisperbar/test_surface_contract.py
rename to tests/unit/ui/jarvisbar/test_surface_contract.py
index e15d21f5bd..d6048cb367 100644
--- a/tests/unit/ui/whisperbar/test_surface_contract.py
+++ b/tests/unit/ui/jarvisbar/test_surface_contract.py
@@ -1,14 +1,15 @@
-"""WhisperBarOverlay must expose the duck-typed surface OrbBusBridge drives,
+"""JarvisBarOverlay must expose the duck-typed surface OrbBusBridge drives,
and every method must be safe to call before/without a Tk window."""
from __future__ import annotations
-from jarvis.ui.whisperbar.overlay import WhisperBarOverlay
+from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay
# Every method OrbBusBridge invokes on the surface (directly or via getattr).
REQUIRED = [
"show",
"hide",
"set_level",
+ "set_muted",
"play_animation",
"stop_animation",
"show_listening_transcript",
@@ -26,18 +27,18 @@ REQUIRED = [
def test_surface_exposes_every_method_the_bridge_calls():
for name in REQUIRED:
- assert callable(getattr(WhisperBarOverlay, name, None)), name
+ assert callable(getattr(JarvisBarOverlay, name, None)), name
def test_constructs_headless_without_tk():
- bar = WhisperBarOverlay(persistent=False, accent="#abcdef")
+ bar = JarvisBarOverlay(persistent=False, accent="#abcdef")
assert bar._mode == "idle"
assert bar._persistent is False
assert bar._root is None
def test_methods_safe_without_tk_window():
- bar = WhisperBarOverlay.__new__(WhisperBarOverlay)
+ bar = JarvisBarOverlay.__new__(JarvisBarOverlay)
bar._root = None
bar._mode = "idle"
bar._ext_level = 0.0
@@ -60,6 +61,11 @@ def test_methods_safe_without_tk_window():
bar.set_level(-2.0)
assert bar._ext_level == 0.0
+ bar.set_muted(True) # _root None → safe atomic write
+ assert bar._muted is True
+ bar.set_muted(False)
+ assert bar._muted is False
+
bar.hide() # _root None → safe no-op
bar.play_animation("wave", x=1)
bar.stop_animation("think")
diff --git a/tests/unit/ui/test_desktop_backend_start_order.py b/tests/unit/ui/test_desktop_backend_start_order.py
index 15c4674750..7b37b2d849 100644
--- a/tests/unit/ui/test_desktop_backend_start_order.py
+++ b/tests/unit/ui/test_desktop_backend_start_order.py
@@ -35,19 +35,45 @@ class _FakeApp:
class _FakeWebServer:
+ # The test sets this to the shared events list so ``start`` records when the
+ # heavy ``server.start()`` _init_* chain runs relative to the wake listener.
+ events: list[str] | None = None
+
def __init__(self, cfg: Any) -> None:
self.cfg = cfg
self.bus = _FakeBus()
self.app = _FakeApp()
self.stopped = False
- async def start(self) -> None:
+ async def start(self, *, start_serving: bool = True) -> None:
+ if _FakeWebServer.events is not None:
+ _FakeWebServer.events.append("server_start")
+ self.start_serving = start_serving
return None
async def stop(self) -> None:
self.stopped = True
+class _FakeBootstrap:
+ """Stand-in for FastBootstrap: no real socket bind in the unit test."""
+
+ def __init__(self, *_args: Any, **_kwargs: Any) -> None:
+ self.app_set: Any = None
+
+ async def serve(self, _host: str, _port: int) -> None:
+ return None
+
+ def set_app(self, app: Any) -> None:
+ self.app_set = app
+
+ async def wait_shell_served(self, timeout: float = 0.0) -> bool: # noqa: ASYNC109
+ return True
+
+ async def stop(self) -> None:
+ return None
+
+
class _FakeChatStore:
def __init__(self, *_args: Any, **_kwargs: Any) -> None:
pass
@@ -96,7 +122,11 @@ class _FakeLoop:
def create_task(self, coro: Any, **_kwargs: Any) -> SimpleNamespace:
self.tasks.append(coro)
- return SimpleNamespace(cancel=lambda: None, done=lambda: True)
+ return SimpleNamespace(
+ cancel=lambda: None,
+ done=lambda: True,
+ add_done_callback=lambda _cb: None,
+ )
def call_soon(self, callback: Any, *args: Any) -> None:
self.callbacks.append((callback, args))
@@ -134,7 +164,7 @@ def _cfg(tmp_path: Path) -> SimpleNamespace:
)
-def test_desktop_post_ready_warmups_run_after_event_loop_starts(monkeypatch, tmp_path):
+def test_desktop_voice_start_does_not_wait_for_brain_ready(monkeypatch, tmp_path):
events: list[str] = []
monkeypatch.setattr(asyncio, "new_event_loop", lambda: _FakeLoop(events))
monkeypatch.setattr(asyncio, "set_event_loop", lambda _loop: None)
@@ -148,6 +178,7 @@ def test_desktop_post_ready_warmups_run_after_event_loop_starts(monkeypatch, tmp
monkeypatch,
"jarvis.speech.warmup_prefetch",
start_wake_import_prefetch=lambda: None,
+ start_tts_import_prefetch=lambda: None,
)
_install_fake_module(
monkeypatch,
@@ -159,6 +190,11 @@ def test_desktop_post_ready_warmups_run_after_event_loop_starts(monkeypatch, tmp
"jarvis.ui.web.server",
WebServer=_FakeWebServer,
)
+ _install_fake_module(
+ monkeypatch,
+ "jarvis.ui.web.fast_bootstrap",
+ FastBootstrap=_FakeBootstrap,
+ )
_install_fake_module(
monkeypatch,
"jarvis.state.chat_store",
@@ -240,15 +276,35 @@ def test_desktop_post_ready_warmups_run_after_event_loop_starts(monkeypatch, tmp
app._conductor_store = None
app._conductor_scheduler = None
- def _speech(*_args: Any, **_kwargs: Any) -> None:
+ async def _speech(*_args: Any, **_kwargs: Any) -> None:
events.append("speech")
+ # The real _start_speech_and_orb signals this once the wake model has
+ # loaded; the heavy backend gates the brain/mcp build on it (GIL
+ # priority for the wake-model load). Set it so the gate releases.
+ app._wake_model_loaded.set()
def _cursor() -> None:
events.append("cursor")
monkeypatch.setattr(app, "_start_speech_and_orb", _speech)
monkeypatch.setattr(app, "_start_virtual_cursor", _cursor)
-
- app._run_backend()
-
- assert events[:4] == ["run_forever", "build_brain", "speech", "cursor"]
+ _FakeWebServer.events = events
+ try:
+ app._run_backend()
+ finally:
+ _FakeWebServer.events = None
+
+ # Serve-WAKE-first contract: the Jarvis-Bar / wake listener must arm as soon
+ # as the backend loop is serving — BEFORE the heavy ``server.start()`` _init_*
+ # chain (mission/wiki/session/channel) AND before the BrainManager build. The
+ # window appears, then the wake word, then the rest, all overlapping. A slow
+ # backend must never keep the wake word deaf after the window is visible.
+ assert events[0] == "run_forever"
+ assert events[1] == "speech"
+ assert "server_start" in events
+ assert events.index("speech") < events.index("server_start"), (
+ f"wake must arm before the heavy server.start() chain; got {events}"
+ )
+ assert events.index("speech") < events.index("build_brain"), (
+ f"wake must arm before the brain build; got {events}"
+ )
diff --git a/tests/unit/ui/test_desktop_minimize_to_tray_overlay.py b/tests/unit/ui/test_desktop_minimize_to_tray_overlay.py
new file mode 100644
index 0000000000..89c9bd3209
--- /dev/null
+++ b/tests/unit/ui/test_desktop_minimize_to_tray_overlay.py
@@ -0,0 +1,169 @@
+"""Closing the window (X) = minimise to tray AND clear the overlay bar.
+
+The X on the main window is wired to "minimise to tray", not "quit" (the app
+keeps running so voice stays live). Previously the persistent jarvis-bar stayed
+on screen after the X, which read as "the bar won't go away when I close Jarvis".
+
+Contract:
+- ``_on_window_closing`` vetoes the destroy (returns False), hides the window,
+ and takes the bar off the screen too — without destroying the user's saved
+ ``bar_persistent`` preference, so reopening restores it.
+- a genuine quit (``_user_requested_quit``) is allowed through untouched; the
+ real ``shutdown()`` tears the bar down there.
+- ``_restore_overlay_for_visible_window`` puts the bar back into the user's
+ configured persistence regime when the window is shown again.
+- both helpers no-op on a headless host (no overlay / no bridge).
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from jarvis.ui.desktop_app import DesktopApp
+
+
+class FakeBar:
+ def __init__(self) -> None:
+ self._persistent = True
+ self._mode = "idle"
+ self.shown: str | None = None
+ self.hidden = False
+
+ def show(self, mode: str) -> None:
+ self.shown = mode
+
+ def hide(self) -> None:
+ self.hidden = True
+
+
+class FakeWindow:
+ def __init__(self) -> None:
+ self.hidden = False
+
+ def hide(self) -> None:
+ self.hidden = True
+
+
+def _app(*, persistent: bool, orb: object, bridge: object) -> DesktopApp:
+ app = DesktopApp.__new__(DesktopApp)
+ app.cfg = SimpleNamespace(ui=SimpleNamespace(bar_persistent=persistent))
+ app._orb = orb
+ app._bridge = bridge
+ return app
+
+
+# --- suppress (window hidden) ------------------------------------------------
+
+
+def test_suppress_before_boot_reveal_does_not_cancel_startup_bar() -> None:
+ bar = FakeBar()
+ bridge = SimpleNamespace(_hide_on_idle=False, _boot_reveal_done=False)
+ app = _app(persistent=True, orb=bar, bridge=bridge)
+
+ app._suppress_overlay_for_hidden_window()
+
+ assert bar.hidden is False
+ assert bridge._hide_on_idle is False
+ assert bar._persistent is True
+ assert app.cfg.ui.bar_persistent is True
+
+
+def test_suppress_hides_bar_and_flips_bridge_to_hide_on_idle() -> None:
+ bar = FakeBar()
+ bridge = SimpleNamespace(_hide_on_idle=False)
+ app = _app(persistent=True, orb=bar, bridge=bridge)
+
+ app._suppress_overlay_for_hidden_window()
+
+ assert bar.hidden is True
+ assert bridge._hide_on_idle is True
+ assert bar._persistent is False
+ # The user's saved preference must NOT be mutated — only the live regime.
+ assert app.cfg.ui.bar_persistent is True
+
+
+def test_suppress_is_noop_without_overlay() -> None:
+ app = _app(persistent=True, orb=None, bridge=None)
+ # Must not raise on a headless host.
+ app._suppress_overlay_for_hidden_window()
+
+
+# --- restore (window shown again) --------------------------------------------
+
+
+def test_restore_shows_idle_bar_for_persistent_user() -> None:
+ bar = FakeBar()
+ bar._persistent = False # left in the suppressed regime
+ bridge = SimpleNamespace(_hide_on_idle=True)
+ app = _app(persistent=True, orb=bar, bridge=bridge)
+
+ app._restore_overlay_for_visible_window()
+
+ assert bridge._hide_on_idle is False
+ assert bar._persistent is True
+ assert bar.shown == "idle"
+
+
+def test_restore_keeps_bar_hidden_for_non_persistent_user() -> None:
+ bar = FakeBar()
+ bridge = SimpleNamespace(_hide_on_idle=True)
+ app = _app(persistent=False, orb=bar, bridge=bridge)
+
+ app._restore_overlay_for_visible_window()
+
+ # Non-persistent: hide-at-idle regime stays, bar is not force-shown.
+ assert bridge._hide_on_idle is True
+ assert bar.shown is None
+
+
+def test_restore_is_noop_without_overlay() -> None:
+ app = _app(persistent=True, orb=None, bridge=None)
+ app._restore_overlay_for_visible_window()
+
+
+def test_restore_keeps_mascot_hide_on_idle() -> None:
+ """The mascot is hide-at-idle regardless of bar_persistent (which only
+ governs the jarvis bar). Restoring must not pin the mascot on screen."""
+ bar = FakeBar()
+ bridge = SimpleNamespace(_hide_on_idle=True)
+ app = _app(persistent=True, orb=bar, bridge=bridge)
+ app.cfg.ui.orb_style = "mascot"
+
+ app._restore_overlay_for_visible_window()
+
+ assert bridge._hide_on_idle is True # stays hide-at-idle
+ assert bar.shown is None # not force-shown
+
+
+# --- the X / closing callback ------------------------------------------------
+
+
+def test_window_closing_minimises_and_clears_bar() -> None:
+ bar = FakeBar()
+ bridge = SimpleNamespace(_hide_on_idle=False)
+ app = _app(persistent=True, orb=bar, bridge=bridge)
+ app._window = FakeWindow()
+ app._user_requested_quit = False
+ app._window_visible = True
+
+ result = app._on_window_closing()
+
+ assert result is False # destroy vetoed → minimise to tray
+ assert app._window.hidden is True
+ assert app._window_visible is False
+ assert bar.hidden is True
+ assert bridge._hide_on_idle is True
+ assert app.cfg.ui.bar_persistent is True # preference untouched
+
+
+def test_window_closing_allows_genuine_quit() -> None:
+ bar = FakeBar()
+ app = _app(persistent=True, orb=bar, bridge=SimpleNamespace(_hide_on_idle=False))
+ app._window = FakeWindow()
+ app._user_requested_quit = True
+ app._window_visible = True
+
+ result = app._on_window_closing()
+
+ assert result is True # allow the destroy → shutdown() handles teardown
+ assert app._window.hidden is False # not minimised
+ assert bar.hidden is False # suppress NOT run on a real quit
diff --git a/tests/unit/ui/test_desktop_swap_overlay.py b/tests/unit/ui/test_desktop_swap_overlay.py
index 7382c5a17d..1e47f305be 100644
--- a/tests/unit/ui/test_desktop_swap_overlay.py
+++ b/tests/unit/ui/test_desktop_swap_overlay.py
@@ -11,10 +11,10 @@ from __future__ import annotations
from types import SimpleNamespace
from jarvis.ui.desktop_app import DesktopApp
-from jarvis.ui.whisperbar.null_overlay import NullOverlay
+from jarvis.ui.jarvisbar.null_overlay import NullOverlay
-def _app(*, orb_style="whisper_bar", bridge=..., orb=None):
+def _app(*, orb_style="jarvis_bar", bridge=..., orb=None):
app = DesktopApp.__new__(DesktopApp) # bypass heavy __init__
app.cfg = SimpleNamespace(
ui=SimpleNamespace(
@@ -47,7 +47,7 @@ class FakeOld:
def test_swap_to_none_uses_nulloverlay_and_hides_old():
bridge, old = FakeBridge(), FakeOld()
- app = _app(orb_style="whisper_bar", bridge=bridge, orb=old)
+ app = _app(orb_style="jarvis_bar", bridge=bridge, orb=old)
result = app.swap_overlay("none")
assert result == {"ok": True, "applied_live": True, "style": "none"}
assert isinstance(bridge.surface, NullOverlay)
@@ -75,17 +75,17 @@ def test_swap_to_uncached_real_style_needs_restart():
bridge = FakeBridge()
app = _app(orb_style="mascot", bridge=bridge, orb=FakeOld())
app._surfaces = {} # nothing cached for the bar
- result = app.swap_overlay("whisper_bar")
- assert result == {"ok": True, "applied_live": False, "style": "whisper_bar"}
+ result = app.swap_overlay("jarvis_bar")
+ assert result == {"ok": True, "applied_live": False, "style": "jarvis_bar"}
assert bridge.surface is None # bridge NOT repointed (no live apply)
def test_swap_without_bridge_is_persisted_only():
app = _app(orb_style="mascot", bridge=None, orb=None)
- assert app.swap_overlay("whisper_bar") == {
+ assert app.swap_overlay("jarvis_bar") == {
"ok": True,
"applied_live": False,
- "style": "whisper_bar",
+ "style": "jarvis_bar",
}
diff --git a/tests/unit/ui/test_orb_bus_bridge.py b/tests/unit/ui/test_orb_bus_bridge.py
index ecf47c4873..ec4a894452 100644
--- a/tests/unit/ui/test_orb_bus_bridge.py
+++ b/tests/unit/ui/test_orb_bus_bridge.py
@@ -579,7 +579,7 @@ async def test_reply_is_reset_between_turns() -> None:
# --- Boot readiness gate: the persistent bar stays hidden until voice is ready.
-# The persistent WhisperBar used to map its window the instant its mainloop ran,
+# The persistent JarvisBar used to map its window the instant its mainloop ran,
# i.e. during backend boot — seconds before the speech pipeline could actually
# hear "Hey Jarvis". The user saw the bar and assumed Jarvis was listening when
# it was not. The bridge now reveals the persistent bar only on the existing
diff --git a/tests/unit/ui/test_orb_bus_bridge_mute_loop.py b/tests/unit/ui/test_orb_bus_bridge_mute_loop.py
new file mode 100644
index 0000000000..606621f739
--- /dev/null
+++ b/tests/unit/ui/test_orb_bus_bridge_mute_loop.py
@@ -0,0 +1,104 @@
+"""Regression: Tk-thread orb gestures must marshal their ``bus.publish`` onto
+the *captured backend asyncio loop*, never a throwaway ``asyncio.run`` loop.
+
+Forensic (2026-06-28, ``data/jarvis_desktop.log`` 16:59:47): an orb
+double-click mute fired ``_publish_mute_toggle`` on the overlay's Tk thread,
+which has no asyncio loop. The old code fell back to ``asyncio.run(coro)`` —
+spinning a throwaway loop — and ``bus.publish`` then dispatched the per-WS-client
+``_forward`` subscriber, whose ``asyncio.Lock`` (``send_lock``) is bound to the
+real backend loop. Acquiring it from the throwaway loop raised
+``RuntimeError: <Lock> is bound to a different event loop`` for every connected
+client (a "WS-Forward fehlgeschlagen" storm). The mute flag flipped ON but the
+``VoiceMuteChanged`` broadcast could not reach the UI, so the mic stayed muted
+with no visible cue and the voice session sat in LISTENING — "I spoke and it
+never started thinking" — until the session died ``reason=error`` and the app
+self-restarted.
+
+These tests pin the fix: the bridge captures the backend loop and gestures use
+``run_coroutine_threadsafe`` onto it.
+"""
+from __future__ import annotations
+
+import asyncio
+import sys
+import threading
+from pathlib import Path
+
+import pytest
+
+# Repo-Root in sys.path, damit Top-Level-Modul `ui.orb.*` importierbar ist.
+_REPO_ROOT = Path(__file__).resolve().parents[3]
+if str(_REPO_ROOT) in sys.path:
+ sys.path.remove(str(_REPO_ROOT))
+sys.path.insert(0, str(_REPO_ROOT))
+sys.modules.pop("ui", None)
+
+try: # noqa: SIM105 — bewusster Try-Import wegen Discovery-Quirk
+ from ui.orb.bus_bridge import OrbBusBridge # type: ignore[import-not-found]
+except ModuleNotFoundError: # pragma: no cover
+ pytest.skip(
+ "ui.orb nicht im Pytest-Pythonpath verfügbar — Top-Level-Namespace-Package.",
+ allow_module_level=True,
+ )
+
+class _FakeOrb:
+ def __init__(self) -> None:
+ self.mute_callback = None
+
+ def set_on_mute_toggle(self, callback) -> None:
+ self.mute_callback = callback
+
+
+class _RecordingBus:
+ """Records the asyncio loop each ``publish`` coroutine actually runs on."""
+
+ def __init__(self) -> None:
+ self.ran_on: list[asyncio.AbstractEventLoop] = []
+ self.done = threading.Event()
+
+ def subscribe(self, *_args, **_kwargs) -> None:
+ pass
+
+ async def publish(self, _event) -> None:
+ self.ran_on.append(asyncio.get_running_loop())
+ self.done.set()
+
+
+def test_mute_toggle_publishes_on_captured_backend_loop() -> None:
+ """The Tk-thread mute gesture must run ``publish`` on the backend loop,
+ not a throwaway ``asyncio.run`` loop (the cross-event-loop ``send_lock``
+ crash). Calling from the main test thread mirrors the loop-less Tk thread.
+ """
+ backend = asyncio.new_event_loop()
+ thread = threading.Thread(target=backend.run_forever, daemon=True)
+ thread.start()
+ try:
+ bus = _RecordingBus()
+ bridge = OrbBusBridge(bus=bus, orb=_FakeOrb()) # type: ignore[arg-type]
+ # Simulate attach()/_on_state having captured the live backend loop.
+ bridge._loop = backend # noqa: SLF001
+
+ # Fire the gesture from this (loop-less) thread = the overlay Tk thread.
+ bridge._publish_mute_toggle() # noqa: SLF001
+
+ assert bus.done.wait(timeout=2.0), "mute publish never executed"
+ assert bus.ran_on[0] is backend, (
+ "publish ran on a throwaway loop, not the captured backend loop — "
+ "the cross-event-loop send_lock crash would recur"
+ )
+ finally:
+ backend.call_soon_threadsafe(backend.stop)
+ thread.join(timeout=2.0)
+ backend.close()
+
+
+async def test_remember_loop_captures_running_backend_loop() -> None:
+ """``_remember_loop`` (called from the backend-loop handlers ``attach`` and
+ ``_on_state``) records the live loop, so a Tk gesture firing later has a real
+ loop to marshal onto instead of falling back to a throwaway ``asyncio.run``."""
+ bridge = OrbBusBridge(bus=_RecordingBus(), orb=_FakeOrb()) # type: ignore[arg-type]
+ assert bridge._loop is None # noqa: SLF001
+
+ bridge._remember_loop() # noqa: SLF001 — exactly what _on_state/attach delegate to
+
+ assert bridge._loop is asyncio.get_running_loop() # noqa: SLF001
diff --git a/tests/unit/ui/test_orb_bus_bridge_wake_candidate.py b/tests/unit/ui/test_orb_bus_bridge_wake_candidate.py
new file mode 100644
index 0000000000..0a83b8d6b0
--- /dev/null
+++ b/tests/unit/ui/test_orb_bus_bridge_wake_candidate.py
@@ -0,0 +1,120 @@
+"""Optimistic wake-reveal: the bar pops on the OWW candidate, before STT verify.
+
+User-reported symptom (2026-06-28): after "Hey Jarvis" the overlay bar takes
+~1 s to appear. Root cause: the bar reveal is wired to ``WakeWordDetected``,
+which the pipeline only publishes AFTER the second-stage STT prefix-verification
+(``_verify_oww_hit`` — a cloud/local STT transcribe of ~3 s of audio). The
+visual feedback therefore waits for the whole confirmation round-trip.
+
+Fix: the pipeline emits a VISUAL-ONLY ``WakeCandidateDetected(active=True)`` the
+instant OWW fires (before verify); the bridge shows the bar from it immediately.
+On a rejected candidate the pipeline emits ``active=False`` and the bridge
+retracts. The authoritative ``WakeWordDetected`` that follows a confirmed wake
+still drives the real session look + greet wave.
+"""
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+_REPO_ROOT = Path(__file__).resolve().parents[3]
+if str(_REPO_ROOT) in sys.path:
+ sys.path.remove(str(_REPO_ROOT))
+sys.path.insert(0, str(_REPO_ROOT))
+sys.modules.pop("ui", None)
+
+try: # noqa: SIM105 — deliberate try-import (top-level `ui` discovery quirk)
+ from ui.orb.bus_bridge import OrbBusBridge # type: ignore[import-not-found]
+except ModuleNotFoundError: # pragma: no cover
+ pytest.skip(
+ "ui.orb not importable in this pytest pythonpath — run from repo root.",
+ allow_module_level=True,
+ )
+
+from jarvis.core.events import WakeCandidateDetected, WakeWordDetected
+
+
+class _FakeBus:
+ def subscribe(self, *_a, **_k) -> None:
+ pass
+
+
+class _FakeOrb:
+ def __init__(self) -> None:
+ self.calls: list[tuple[str, object]] = []
+
+ def show(self, mode: str = "listen") -> None:
+ self.calls.append(("show", mode))
+
+ def hide(self) -> None:
+ self.calls.append(("hide", None))
+
+ def play_animation(self, name: str) -> None:
+ self.calls.append(("play_animation", name))
+
+ def set_level(self, level: float) -> None:
+ self.calls.append(("set_level", level))
+
+ def set_mode(self, mode: str) -> None:
+ self.calls.append(("set_mode", mode))
+
+
+def _bridge(orb: _FakeOrb, *, hide_on_idle: bool) -> OrbBusBridge:
+ return OrbBusBridge( # type: ignore[arg-type]
+ bus=_FakeBus(),
+ orb=orb,
+ hide_on_idle=hide_on_idle,
+ idle_animations_enabled=False,
+ )
+
+
+async def test_candidate_shows_bar_immediately() -> None:
+ orb = _FakeOrb()
+ bridge = _bridge(orb, hide_on_idle=True)
+
+ await bridge._on_wake_candidate( # noqa: SLF001
+ WakeCandidateDetected(active=True)
+ )
+
+ assert ("show", "listen") in orb.calls
+
+
+async def test_rejected_candidate_retracts_non_persistent_bar() -> None:
+ orb = _FakeOrb()
+ bridge = _bridge(orb, hide_on_idle=True)
+
+ await bridge._on_wake_candidate(WakeCandidateDetected(active=True)) # noqa: SLF001
+ orb.calls.clear()
+ await bridge._on_wake_candidate(WakeCandidateDetected(active=False)) # noqa: SLF001
+
+ assert ("hide", None) in orb.calls
+
+
+async def test_persistent_bar_falls_back_to_idle_on_reject() -> None:
+ orb = _FakeOrb()
+ bridge = _bridge(orb, hide_on_idle=False)
+
+ await bridge._on_wake_candidate(WakeCandidateDetected(active=True)) # noqa: SLF001
+ orb.calls.clear()
+ await bridge._on_wake_candidate(WakeCandidateDetected(active=False)) # noqa: SLF001
+
+ assert ("show", "idle") in orb.calls
+ assert ("hide", None) not in orb.calls
+
+
+async def test_candidate_does_not_suppress_real_wake_greet() -> None:
+ """An optimistic show must leave _last_state IDLE so the authoritative
+ WakeWordDetected that follows still plays the greet 'wave'."""
+ orb = _FakeOrb()
+ bridge = _bridge(orb, hide_on_idle=True)
+
+ await bridge._on_wake_candidate(WakeCandidateDetected(active=True)) # noqa: SLF001
+ orb.calls.clear()
+ await bridge._on_wake_word_detected( # noqa: SLF001
+ WakeWordDetected(keyword="hey_jarvis")
+ )
+
+ assert ("show", "listen") in orb.calls
+ assert ("play_animation", "wave") in orb.calls
diff --git a/tests/unit/ui/test_orb_no_legacy_renderer.py b/tests/unit/ui/test_orb_no_legacy_renderer.py
index 8081e4c461..3868329565 100644
--- a/tests/unit/ui/test_orb_no_legacy_renderer.py
+++ b/tests/unit/ui/test_orb_no_legacy_renderer.py
@@ -8,10 +8,10 @@ from jarvis.core.config import UIConfig
from ui.orb.overlay import OrbOverlay
-def test_ui_config_default_is_whisper_bar_not_legacy_orb() -> None:
- # Default flipped to the slim whisper bar; the legacy procedural "orb" is
+def test_ui_config_default_is_jarvis_bar_not_legacy_orb() -> None:
+ # Default flipped to the slim jarvis bar; the legacy procedural "orb" is
# still never the default. The mascot stays explicitly selectable.
- assert UIConfig().orb_style == "whisper_bar"
+ assert UIConfig().orb_style == "jarvis_bar"
assert UIConfig().orb_style != "orb"
assert UIConfig(orb_style="mascot").orb_style == "mascot"
diff --git a/tests/unit/ui/test_orb_show_window_gesture.py b/tests/unit/ui/test_orb_show_window_gesture.py
index 2fa8e60cfb..2d31a7d7ed 100644
--- a/tests/unit/ui/test_orb_show_window_gesture.py
+++ b/tests/unit/ui/test_orb_show_window_gesture.py
@@ -1,6 +1,6 @@
"""Mascot orb right-click → show-window gesture.
-Parallels the whisper-bar: the orb exposes ``set_on_show_window`` (injected by
+Parallels the jarvis-bar: the orb exposes ``set_on_show_window`` (injected by
OrbBusBridge) and ``_on_right_click`` fires it. Per the 2026-06-02 spec the
right-click now raises the main window instead of opening the old Reset/Mute
context menu; "Reset position" moves to middle-click (``<Button-2>``), and the
diff --git a/tests/unit/ui/test_overlay_style_route.py b/tests/unit/ui/test_overlay_style_route.py
index 03853fa838..65adb6ed8b 100644
--- a/tests/unit/ui/test_overlay_style_route.py
+++ b/tests/unit/ui/test_overlay_style_route.py
@@ -26,7 +26,7 @@ def test_get_returns_current_and_options():
assert r.status_code == 200
body = r.json()
assert body["style"] == "mascot"
- assert set(body["options"]) == {"whisper_bar", "mascot", "none"}
+ assert set(body["options"]) == {"jarvis_bar", "mascot", "none"}
def test_put_rejects_unknown_style():
@@ -48,16 +48,16 @@ def test_put_persists_and_live_applies(monkeypatch):
desktop = SimpleNamespace(swap_overlay=swap_overlay)
r = _client(orb_style="mascot", desktop=desktop).put(
- "/api/settings/overlay-style", json={"style": "whisper_bar", "persist": True}
+ "/api/settings/overlay-style", json={"style": "jarvis_bar", "persist": True}
)
assert r.status_code == 200
body = r.json()
- assert body["style"] == "whisper_bar"
+ assert body["style"] == "jarvis_bar"
assert body["persisted"] is True
assert body["applied_live"] is True
assert body["restart_required"] is False
- assert persisted["v"] == "whisper_bar"
- assert swapped["v"] == "whisper_bar"
+ assert persisted["v"] == "jarvis_bar"
+ assert swapped["v"] == "jarvis_bar"
def test_put_without_desktop_app_persists_but_needs_restart(monkeypatch):
diff --git a/tests/unit/ui/test_profile_field_edit.py b/tests/unit/ui/test_profile_field_edit.py
new file mode 100644
index 0000000000..05be6ebb93
--- /dev/null
+++ b/tests/unit/ui/test_profile_field_edit.py
@@ -0,0 +1,207 @@
+"""Tests for PATCH /api/profile/field — inline single-field editing from the
+Profile view (the pencil-per-field UI).
+
+Contract (see jarvis/ui/web/profile_routes.py::patch_field):
+- ``set`` overwrites a scalar field in place (Chef → König)
+- ``clear`` empties any field so it reads back as "not known yet"
+- ``append`` / ``remove`` add/drop one item of a list field (the chips)
+- the canonical field allow-list (shared with update_profile) is enforced
+- list-only vs scalar-only operations are rejected with 400
+- a ProfileUpdated event is emitted for live UI sync
+- the change is persisted atomically to USER.md
+"""
+from __future__ import annotations
+
+import types
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.core.events import ProfileUpdated
+from jarvis.memory.user_profile import UserProfile
+from jarvis.ui.web.profile_routes import router
+
+INITIAL = """\
+---
+identity:
+ name: Ruben
+ preferred_address: Chef
+ languages:
+ - English
+communication:
+ emoji_ok: false
+values:
+ top_values:
+ - Pizza
+---
+
+# USER.md
+
+## Observations ueber Zeit
+
+<!-- curator:observations:start -->
+<!-- curator:observations:end -->
+"""
+
+
+class _CapturingBus:
+ """Records published events; the endpoint only needs .publish."""
+
+ def __init__(self) -> None:
+ self.published: list[object] = []
+
+ async def publish(self, event: object) -> None:
+ self.published.append(event)
+
+
+def ctx(tmp_path: Path):
+ user_md = tmp_path / "USER.md"
+ user_md.write_text(INITIAL, encoding="utf-8")
+ profile = UserProfile.load(user_md)
+ bus = _CapturingBus()
+
+ app = FastAPI()
+ app.include_router(router)
+ app.state.brain = types.SimpleNamespace(
+ _user_profile=profile,
+ _curator=None,
+ _people=None,
+ _bus=bus,
+ )
+ return types.SimpleNamespace(client=TestClient(app), profile=profile, bus=bus, path=user_md)
+
+
+def _patch(client: TestClient, **body):
+ return client.patch("/api/profile/field", json=body)
+
+
+# ----------------------------------------------------------------------
+# set — overwrite a scalar
+# ----------------------------------------------------------------------
+
+def test_set_scalar_overwrites_chef_to_koenig(ctx) -> None:
+ res = _patch(ctx.client, cluster="identity", field="preferred_address",
+ operation="set", value="König")
+ assert res.status_code == 200, res.text
+ assert res.json()["changed"] is True
+ # In-memory + the read endpoint reflect it.
+ assert ctx.profile.get("identity", "preferred_address") == "König"
+ meta = ctx.client.get("/api/profile").json()["user"]["meta"]
+ assert meta["identity"]["preferred_address"] == "König"
+
+
+def test_set_scalar_persists_to_disk(ctx) -> None:
+ _patch(ctx.client, cluster="identity", field="name", operation="set", value="Paul")
+ # A fresh load from disk sees the write (atomic persist happened).
+ assert UserProfile.load(ctx.path).get("identity", "name") == "Paul"
+
+
+def test_set_emits_profile_updated(ctx) -> None:
+ _patch(ctx.client, cluster="identity", field="name", operation="set", value="Paul")
+ events = [e for e in ctx.bus.published if isinstance(e, ProfileUpdated)]
+ assert len(events) == 1
+ assert events[0].cluster == "identity"
+ assert events[0].field == "name"
+ assert events[0].operation == "set"
+
+
+def test_set_same_value_reports_no_change(ctx) -> None:
+ res = _patch(ctx.client, cluster="identity", field="name",
+ operation="set", value="Ruben")
+ assert res.status_code == 200
+ assert res.json()["changed"] is False
+
+
+def test_set_bool_field_coerces_string(ctx) -> None:
+ res = _patch(ctx.client, cluster="communication", field="emoji_ok",
+ operation="set", value="true")
+ assert res.status_code == 200, res.text
+ assert ctx.profile.get("communication", "emoji_ok") is True
+
+
+# ----------------------------------------------------------------------
+# clear — empty a field
+# ----------------------------------------------------------------------
+
+def test_clear_scalar_field(ctx) -> None:
+ res = _patch(ctx.client, cluster="identity", field="preferred_address",
+ operation="clear")
+ assert res.status_code == 200, res.text
+ assert ctx.profile.get("identity", "preferred_address") is None
+
+
+def test_clear_list_field(ctx) -> None:
+ res = _patch(ctx.client, cluster="values", field="top_values", operation="clear")
+ assert res.status_code == 200, res.text
+ assert not ctx.profile.get("values", "top_values")
+
+
+# ----------------------------------------------------------------------
+# append / remove — list items (the chips)
+# ----------------------------------------------------------------------
+
+def test_append_list_item(ctx) -> None:
+ res = _patch(ctx.client, cluster="identity", field="languages",
+ operation="append", value="Deutsch")
+ assert res.status_code == 200, res.text
+ assert ctx.profile.get("identity", "languages") == ["English", "Deutsch"]
+
+
+def test_append_duplicate_reports_no_change(ctx) -> None:
+ res = _patch(ctx.client, cluster="identity", field="languages",
+ operation="append", value="English")
+ assert res.status_code == 200
+ assert res.json()["changed"] is False
+ assert ctx.profile.get("identity", "languages") == ["English"]
+
+
+def test_remove_list_item(ctx) -> None:
+ ctx.profile.append_list("identity", "languages", "Deutsch")
+ ctx.profile.save()
+ res = _patch(ctx.client, cluster="identity", field="languages",
+ operation="remove", value="English")
+ assert res.status_code == 200, res.text
+ assert ctx.profile.get("identity", "languages") == ["Deutsch"]
+
+
+# ----------------------------------------------------------------------
+# validation
+# ----------------------------------------------------------------------
+
+def test_unknown_cluster_rejected(ctx) -> None:
+ res = _patch(ctx.client, cluster="hobbies", field="name",
+ operation="set", value="x")
+ assert res.status_code == 400
+
+
+def test_unknown_field_rejected(ctx) -> None:
+ res = _patch(ctx.client, cluster="identity", field="shoe_size",
+ operation="set", value="44")
+ assert res.status_code == 400
+
+
+def test_set_on_list_field_rejected(ctx) -> None:
+ # A list field must use append/remove, never set (would clobber the list).
+ res = _patch(ctx.client, cluster="identity", field="languages",
+ operation="set", value="Deutsch")
+ assert res.status_code == 400
+
+
+def test_append_on_scalar_field_rejected(ctx) -> None:
+ res = _patch(ctx.client, cluster="identity", field="name",
+ operation="append", value="X")
+ assert res.status_code == 400
+
+
+def test_set_without_value_rejected(ctx) -> None:
+ res = _patch(ctx.client, cluster="identity", field="name", operation="set")
+ assert res.status_code == 400
+
+
+def test_invalid_operation_rejected(ctx) -> None:
+ res = _patch(ctx.client, cluster="identity", field="name",
+ operation="frobnicate", value="x")
+ assert res.status_code == 422 # Pydantic Literal rejects it before the handler
diff --git a/tests/unit/ui/test_restart_route.py b/tests/unit/ui/test_restart_route.py
index 965c94b62d..00230bf625 100644
--- a/tests/unit/ui/test_restart_route.py
+++ b/tests/unit/ui/test_restart_route.py
@@ -1,12 +1,14 @@
"""POST /api/settings/restart-app — one-click self-restart of the desktop app."""
from __future__ import annotations
+import asyncio
+import threading
from types import SimpleNamespace
from fastapi import FastAPI
from fastapi.testclient import TestClient
-from jarvis.ui.web.settings_routes import router
+from jarvis.ui.web.settings_routes import restart_app, router
def _client(desktop=None, kontrollierer=None, mission_manager=None):
@@ -107,3 +109,82 @@ def test_restart_proceeds_when_no_missions_running():
)
assert r.status_code == 200
assert calls["n"] == 1
+
+
+def _fake_request(desktop=None, kontrollierer=None, mission_manager=None):
+ state = SimpleNamespace()
+ if desktop is not None:
+ state.desktop_app = desktop
+ if kontrollierer is not None:
+ state.kontrollierer = kontrollierer
+ if mission_manager is not None:
+ state.mission_manager = mission_manager
+ return SimpleNamespace(app=SimpleNamespace(state=state))
+
+
+async def test_restart_survives_exhausted_default_thread_pool():
+ """A restart must work even when the shared default ThreadPoolExecutor is
+ saturated by un-cancellable hung threads.
+
+ Forensic 2026-06-29: the custom-wake ctranslate2 transcription hung in C
+ code; its 8 s ``asyncio.timeout`` cancelled only the *await*, abandoning the
+ pool thread mid-call. Within minutes every default-pool worker was wedged,
+ so the old ``await asyncio.to_thread(request_restart)`` queued forever — the
+ restart POST never returned and the button spun "Restarting…" with the
+ window still up. The restart trigger must run OFF the shared pool.
+ """
+ loop = asyncio.get_running_loop()
+ release = threading.Event()
+ # Saturate the default executor well beyond any platform's max_workers
+ # (min(32, cpu+4)); the surplus queues, so no free worker remains.
+ blockers = [loop.run_in_executor(None, release.wait) for _ in range(64)]
+ await asyncio.sleep(0.1) # let the blockers claim every pool thread
+
+ called = threading.Event()
+
+ def request_restart():
+ called.set()
+ return True
+
+ request = _fake_request(SimpleNamespace(request_restart=request_restart))
+ try:
+ # With the bug this never resolves (queued behind the dead pool); the
+ # 5 s cap turns the hang into a clean failure instead of a stuck test.
+ result = await asyncio.wait_for(restart_app(request, force=True), timeout=5.0)
+ finally:
+ release.set()
+ await asyncio.gather(*blockers, return_exceptions=True)
+
+ assert result == {"ok": True, "restarting": True}
+ assert called.is_set()
+
+
+async def test_restart_guard_does_not_hang_on_wedged_mission_manager():
+ """A wedged mission manager must not hang the restart guard.
+
+ The guard looks up titles for in-flight missions to show in the 409 body.
+ If that lookup blocks (a sick manager — the very state a user restarts to
+ escape), the guard must time out and fall back to id-only summaries rather
+ than hang the POST forever.
+ """
+ forever = asyncio.Event() # never set → mission() would block indefinitely
+
+ async def mission(mid):
+ await forever.wait()
+ return SimpleNamespace(prompt="never returns")
+
+ request = _fake_request(
+ SimpleNamespace(request_restart=lambda: True),
+ kontrollierer=_running_kontrollierer("019e-aaa"),
+ mission_manager=SimpleNamespace(mission=mission),
+ )
+ from fastapi import HTTPException
+
+ try:
+ await asyncio.wait_for(restart_app(request, force=False), timeout=5.0)
+ raise AssertionError("expected HTTPException(409)")
+ except HTTPException as exc:
+ assert exc.status_code == 409
+ detail = exc.detail
+ assert detail["error"] == "missions_running"
+ assert [m["id"] for m in detail["missions"]] == ["019e-aaa"]
diff --git a/tests/unit/ui/web/test_boot_critical_path_stays_light.py b/tests/unit/ui/web/test_boot_critical_path_stays_light.py
new file mode 100644
index 0000000000..59e67cdd61
--- /dev/null
+++ b/tests/unit/ui/web/test_boot_critical_path_stays_light.py
@@ -0,0 +1,44 @@
+"""Regression guard: the boot-critical path must stay dependency-light.
+
+The desktop/headless serve-first boot only stays fast because the
+``FastBootstrap`` can bind the port and serve the UI shell BEFORE the heavy
+imports (``fastapi``, the ``jarvis.brain`` graph, ``jarvis.core.config`` with
+its brain/awareness pulls) are paid. If a future change makes
+``jarvis.ui.web.fast_bootstrap`` transitively import any of those, the bind
+moves back behind the heavy work and the boot silently regresses — the exact
+"it keeps getting slower as I add features" rot this guards against.
+
+This test imports the module in a FRESH interpreter (so it is deterministic and
+machine-independent — no timing) and asserts the heavy modules are absent from
+``sys.modules`` afterwards.
+"""
+
+from __future__ import annotations
+
+import subprocess
+import sys
+
+# Modules that must NOT be pulled in merely by importing the bootstrap. Each is a
+# multi-hundred-ms import that the serve-first boot deliberately defers.
+_FORBIDDEN = ("fastapi", "jarvis.brain", "jarvis.core.config", "jarvis.awareness")
+
+
+def test_fast_bootstrap_import_stays_light() -> None:
+ code = (
+ "import sys\n"
+ "import jarvis.ui.web.fast_bootstrap # noqa: F401\n"
+ "bad = [m for m in %r if m in sys.modules]\n"
+ "print('LEAKED=' + ','.join(bad))\n"
+ "sys.exit(1 if bad else 0)\n"
+ ) % (_FORBIDDEN,)
+ proc = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True,
+ timeout=60,
+ )
+ assert proc.returncode == 0, (
+ "The boot-critical bootstrap import pulled in heavy modules — this "
+ "regresses cold-boot speed (serve-first relies on binding BEFORE these "
+ f"are imported). {proc.stdout.strip()}\n{proc.stderr.strip()}"
+ )
diff --git a/tests/unit/ui/web/test_brain_status_route.py b/tests/unit/ui/web/test_brain_status_route.py
new file mode 100644
index 0000000000..f5b989ad87
--- /dev/null
+++ b/tests/unit/ui/web/test_brain_status_route.py
@@ -0,0 +1,57 @@
+"""GET /api/brain/status reports the active brain provider + model.
+
+The frontend reads this on mount to seed the sidebar BRAIN footer. Under the
+fast-boot bootstrap (`feat/fast-boot-bootstrap`) the heavy ``BrainManager`` build
+is deferred to a background thread, so ``app.state.brain`` is ``None`` for the
+first ~850 ms while uvicorn already serves. A frontend that mounts inside that
+window must NOT be told ``provider="unknown"`` (which freezes the sidebar on a
+bare "—" until a manual provider switch) — the configured ``cfg.brain.primary``
+already names the provider that WILL become active, so the endpoint resolves it
+from config when the live brain object is not on ``app.state`` yet.
+"""
+from __future__ import annotations
+
+from fastapi.testclient import TestClient
+
+from jarvis.core.bus import EventBus
+from jarvis.core.config import BrainProviderConfig, JarvisConfig
+from jarvis.ui.web.server import WebServer
+
+
+def test_brain_status_falls_back_to_configured_primary_before_brain_built() -> None:
+ """Fast-boot window: no live brain on app.state yet → resolve from config."""
+ cfg = JarvisConfig()
+ cfg.brain.primary = "gemini"
+ cfg.brain.providers["gemini"] = BrainProviderConfig(model="gemini-3.1-flash")
+ srv = WebServer(cfg, bus=EventBus())
+
+ # Deliberately do NOT set app.state.brain — mirrors the deferred build.
+ with TestClient(srv.app) as client:
+ resp = client.get("/api/brain/status")
+
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["provider"] == "gemini"
+ assert body["model"] == "gemini-3.1-flash"
+
+
+def test_brain_status_prefers_live_active_provider_when_built() -> None:
+ """Once built, the live brain's active_provider is authoritative (it may
+ differ from the configured primary after a runtime switch)."""
+ cfg = JarvisConfig()
+ cfg.brain.primary = "claude-api"
+ cfg.brain.providers["claude-api"] = BrainProviderConfig(model="claude-opus-4-8")
+ cfg.brain.providers["openrouter"] = BrainProviderConfig(model="some-router-model")
+ srv = WebServer(cfg, bus=EventBus())
+
+ class _LiveBrain:
+ active_provider = "openrouter"
+
+ srv.app.state.brain = _LiveBrain()
+
+ with TestClient(srv.app) as client:
+ resp = client.get("/api/brain/status")
+
+ body = resp.json()
+ assert body["provider"] == "openrouter"
+ assert body["model"] == "some-router-model"
diff --git a/tests/unit/ui/web/test_fast_bootstrap.py b/tests/unit/ui/web/test_fast_bootstrap.py
new file mode 100644
index 0000000000..ec9915ada1
--- /dev/null
+++ b/tests/unit/ui/web/test_fast_bootstrap.py
@@ -0,0 +1,276 @@
+"""Unit tests for the reusable serve-first fast-boot bootstrap.
+
+The bootstrap binds the admin port immediately and answers ``/api/health`` with
+200 the moment it is up — so the desktop shell's ``_wait_for_backend`` poll
+succeeds and the window appears — while the heavy real app builds behind it.
+Every non-health request is held until the real app is registered, then
+delegated to it (the "serve first, init behind" contract). These tests drive
+the ASGI callable directly (no socket) to prove that behavior.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+import pytest
+
+from jarvis.ui.web.fast_bootstrap import FastBootstrap
+
+
+async def _drive(app: Any, scope: dict) -> list[dict]:
+ sent: list[dict] = []
+
+ async def send(msg: dict) -> None:
+ sent.append(msg)
+
+ async def receive() -> dict:
+ return {"type": "http.request", "body": b"", "more_body": False}
+
+ await app(scope, receive, send)
+ return sent
+
+
+def _http(path: str, method: str = "GET") -> dict:
+ return {"type": "http", "method": method, "path": path, "headers": []}
+
+
+async def test_health_returns_200_before_real_app_set() -> None:
+ bs = FastBootstrap()
+ sent = await _drive(bs.app, _http("/api/health"))
+ start = next(m for m in sent if m["type"] == "http.response.start")
+ assert start["status"] == 200
+
+
+async def test_non_health_request_holds_until_app_set_then_delegates() -> None:
+ bs = FastBootstrap()
+ seen: dict[str, str] = {}
+
+ async def real_app(scope: dict, receive: Any, send: Any) -> None:
+ seen["path"] = scope["path"]
+ await send({"type": "http.response.start", "status": 201, "headers": []})
+ await send({"type": "http.response.body", "body": b"real"})
+
+ task = asyncio.create_task(_drive(bs.app, _http("/api/missions")))
+ await asyncio.sleep(0.02)
+ assert not task.done(), "request must be held while the real app is warming"
+
+ bs.set_app(real_app)
+ sent = await asyncio.wait_for(task, timeout=2.0)
+ assert seen["path"] == "/api/missions"
+ assert any(
+ m["type"] == "http.response.start" and m["status"] == 201 for m in sent
+ )
+
+
+async def test_health_delegates_to_real_app_once_ready() -> None:
+ bs = FastBootstrap()
+ calls: list[str] = []
+
+ async def real_app(scope: dict, receive: Any, send: Any) -> None:
+ calls.append(scope["path"])
+ await send({"type": "http.response.start", "status": 200, "headers": []})
+ await send({"type": "http.response.body", "body": b"{}"})
+
+ bs.set_app(real_app)
+ await _drive(bs.app, _http("/api/health"))
+ assert calls == ["/api/health"], "once ready, even health must delegate to the real app"
+
+
+async def test_held_request_times_out_to_503_when_app_never_arrives() -> None:
+ bs = FastBootstrap(hold_timeout=0.05)
+ sent = await _drive(bs.app, _http("/api/missions"))
+ start = next(m for m in sent if m["type"] == "http.response.start")
+ assert start["status"] == 503
+
+
+async def test_websocket_held_then_closed_on_timeout() -> None:
+ bs = FastBootstrap(hold_timeout=0.05)
+ scope = {"type": "websocket", "path": "/ws", "headers": []}
+ sent = await _drive(bs.app, scope)
+ assert any(m["type"] == "websocket.close" for m in sent)
+
+
+# --- static frontend served immediately (no black screen) -------------------
+
+
+def _seed_dist(tmp_path) -> object:
+ dist = tmp_path / "dist"
+ (dist / "assets").mkdir(parents=True)
+ (dist / "index.html").write_text(
+ "<!doctype html><html><body><div id=root></div>"
+ "<script src=/assets/app.js></script></body></html>",
+ encoding="utf-8",
+ )
+ (dist / "assets" / "app.js").write_text("console.log('jarvis ui')", encoding="utf-8")
+ return dist
+
+
+def _body(sent: list[dict]) -> bytes:
+ return b"".join(m.get("body", b"") for m in sent if m["type"] == "http.response.body")
+
+
+def _status(sent: list[dict]) -> int:
+ return next(m["status"] for m in sent if m["type"] == "http.response.start")
+
+
+async def test_serves_index_html_immediately_before_app_ready(tmp_path) -> None:
+ # The whole point: GET / returns the REAL index.html while warming, so the
+ # desktop window shows the UI shell instead of a black screen.
+ bs = FastBootstrap(dist_dir=_seed_dist(tmp_path))
+ sent = await _drive(bs.app, _http("/"))
+ assert _status(sent) == 200
+ assert b"<div id=root>" in _body(sent)
+
+
+async def test_serves_static_asset_immediately_before_app_ready(tmp_path) -> None:
+ bs = FastBootstrap(dist_dir=_seed_dist(tmp_path))
+ sent = await _drive(bs.app, _http("/assets/app.js"))
+ assert _status(sent) == 200
+ assert b"jarvis ui" in _body(sent)
+ ctype = next(
+ v for (k, v) in next(m for m in sent if m["type"] == "http.response.start")["headers"]
+ if k == b"content-type"
+ )
+ assert b"javascript" in ctype
+
+
+async def test_spa_fallback_serves_index_for_unknown_route(tmp_path) -> None:
+ # A deep-link to a client-side route (no real file) must fall back to
+ # index.html so the SPA router can take over — NOT be held or 404'd.
+ bs = FastBootstrap(dist_dir=_seed_dist(tmp_path))
+ sent = await _drive(bs.app, _http("/wiki/some/page"))
+ assert _status(sent) == 200
+ assert b"<div id=root>" in _body(sent)
+
+
+async def test_api_request_is_still_held_not_served_as_static(tmp_path) -> None:
+ # /api/* must NOT be served as static — it is the dynamic surface and must
+ # be held until the real app is ready.
+ bs = FastBootstrap(dist_dir=_seed_dist(tmp_path), hold_timeout=0.05)
+ sent = await _drive(bs.app, _http("/api/missions"))
+ assert _status(sent) == 503 # held → warming timeout, never a static 200
+
+
+async def test_shell_served_event_fires_after_js_bundle(tmp_path) -> None:
+ # The backend defers its GIL-heavy build until the entry JS bundle is out,
+ # so the UI paints first. index.html alone (blank #root) must NOT satisfy it.
+ bs = FastBootstrap(dist_dir=_seed_dist(tmp_path))
+ await _drive(bs.app, _http("/")) # index.html → not enough on its own
+ assert not await bs.wait_shell_served(timeout=0.05)
+ await _drive(bs.app, _http("/assets/app.js")) # entry bundle → now ready
+ assert await bs.wait_shell_served(timeout=0.05)
+
+
+# --- listener self-healing (the lock-zombie root cause) ---------------------
+# Forensic 2026-06-26: a transient Windows socket error (OSError WinError 64,
+# "the network name is no longer available") killed the asyncio proactor accept
+# loop, which closes the LISTENING socket. uvicorn never re-binds it, so the
+# port went dead permanently while the rest of the process (voice, telegram)
+# lived on — a "lock-zombie" that held the single-instance lock with no port and
+# no window, so every restart bounced. The bootstrap owns the socket, so it must
+# notice the dead listener and re-bind itself.
+
+
+def _free_port() -> int:
+ import socket as _socket
+
+ s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
+ s.bind(("127.0.0.1", 0))
+ port = s.getsockname()[1]
+ s.close()
+ return port
+
+
+async def _port_open(host: str, port: int, timeout: float = 1.0) -> bool: # noqa: ASYNC109 — test helper, conventional timeout param
+ from contextlib import suppress
+
+ try:
+ _reader, writer = await asyncio.wait_for(
+ asyncio.open_connection(host, port), timeout=timeout
+ )
+ writer.close()
+ with suppress(Exception):
+ await writer.wait_closed()
+ return True
+ except (TimeoutError, OSError):
+ return False
+
+
+async def test_serve_starts_a_listener_that_answers_health() -> None:
+ port = _free_port()
+ bs = FastBootstrap()
+ await bs.serve("127.0.0.1", port, supervise=False)
+ try:
+ assert await _port_open("127.0.0.1", port)
+ finally:
+ await bs.stop()
+
+
+async def test_supervisor_rebinds_listener_after_socket_death() -> None:
+ # Reproduce the forensic: while serving, the OS kills the listening socket
+ # (simulated by closing the uvicorn server socket exactly as the proactor's
+ # ``sock.close()`` does on WinError 64). The supervisor must detect the dead
+ # port and re-bind, so the port comes back WITHOUT a process restart.
+ port = _free_port()
+ bs = FastBootstrap()
+ await bs.serve("127.0.0.1", port, supervise=True, supervise_interval=0.2)
+ try:
+ assert await _port_open("127.0.0.1", port), "listener must be up after serve"
+
+ # Kill the listening socket out from under uvicorn (what WinError 64 does).
+ await bs._kill_listener_for_test()
+ assert not await _port_open("127.0.0.1", port), "port must be dead after socket close"
+
+ # The supervisor probes on its interval and re-binds. Give it a few cycles.
+ recovered = False
+ for _ in range(30):
+ await asyncio.sleep(0.2)
+ if await _port_open("127.0.0.1", port):
+ recovered = True
+ break
+ assert recovered, "supervisor must re-bind the dead listener (self-heal)"
+ finally:
+ await bs.stop()
+
+
+async def test_rebind_preserves_registered_real_app() -> None:
+ # A re-bind after a socket death must keep delegating to the already
+ # registered real app — the warm-up state survives the listener swap.
+ port = _free_port()
+ bs = FastBootstrap()
+
+ async def real_app(scope: dict, receive: Any, send: Any) -> None:
+ if scope["type"] == "lifespan":
+ await FastBootstrap._handle_lifespan(receive, send)
+ return
+ await send({"type": "http.response.start", "status": 222, "headers": []})
+ await send({"type": "http.response.body", "body": b"real"})
+
+ await bs.serve("127.0.0.1", port, supervise=True, supervise_interval=0.2)
+ try:
+ bs.set_app(real_app)
+ await bs._kill_listener_for_test()
+ # wait for self-heal
+ for _ in range(30):
+ await asyncio.sleep(0.2)
+ if await _port_open("127.0.0.1", port):
+ break
+ # the rebound listener still delegates to the real app
+ sent = await _drive(bs.app, _http("/api/whoami"))
+ assert _status(sent) == 222
+ finally:
+ await bs.stop()
diff --git a/tests/unit/ui/web/test_fast_bootstrap_ws.py b/tests/unit/ui/web/test_fast_bootstrap_ws.py
new file mode 100644
index 0000000000..a9a75f5e10
--- /dev/null
+++ b/tests/unit/ui/web/test_fast_bootstrap_ws.py
@@ -0,0 +1,32 @@
+"""A warming FastBootstrap must NOT hold a WS handshake open; it must
+accept-then-close with code 1013 so the client gets a fast, readable
+"try again later" and reconnects (instead of the browser timing out the
+pending handshake -> escalating backoff -> a long spurious 'OFFLINE')."""
+from __future__ import annotations
+
+import asyncio
+import logging
+
+import pytest
+import websockets
+
+from jarvis.ui.web.fast_bootstrap import FastBootstrap
+
+
+async def test_warming_ws_is_fast_closed_with_1013() -> None:
+ logging.disable(logging.CRITICAL)
+ bs = FastBootstrap()
+ await bs.serve("127.0.0.1", 47995) # NOT set_app -> warming
+ try:
+ # Must connect quickly (handshake accepted) -- the old hold made this
+ # time out. open_timeout well under the old 120s hold proves no-hold.
+ async with websockets.connect(
+ "ws://127.0.0.1:47995/ws", open_timeout=3
+ ) as ws:
+ with pytest.raises(websockets.ConnectionClosed) as exc:
+ await asyncio.wait_for(ws.recv(), timeout=3)
+ assert exc.value.code == 1013
+ finally:
+ await bs.stop()
+ logging.disable(logging.NOTSET)
diff --git a/tests/unit/ui/web/test_launcher_bootstrap_retry.py b/tests/unit/ui/web/test_launcher_bootstrap_retry.py
new file mode 100644
index 0000000000..daa448d4ed
--- /dev/null
+++ b/tests/unit/ui/web/test_launcher_bootstrap_retry.py
@@ -0,0 +1,113 @@
+"""The fast-boot desktop bind must survive the self-restart port-release race.
+
+Live forensic (2026-06-25): after an in-app restart the app "shut down but
+never came back" — the relauncher spawned a fresh instance, but the fast-boot
+desktop backend (``_desktop_backend_main``) treated *any* port-bind failure as
+"another instance is already running", focused a (now dead) window and quit.
+The real cause is timing: the just-exited old process is still releasing the
+admin port for a few hundred ms, so the first bind fails *transiently* — NOT
+because a second live instance holds it.
+
+``_serve_bootstrap_with_retry`` fixes that: it retries the bind a few times
+before concluding "already running". The single-instance lock (acquired later)
+stays the authoritative "is another instance live?" check — this only stops a
+transient post-restart bind race from being misread.
+"""
+from __future__ import annotations
+
+import asyncio
+
+from jarvis.ui.web.launcher import _serve_bootstrap_with_retry
+
+
+class _FakeBootstrap:
+ """Stand-in for FastBootstrap whose ``serve`` either binds or raises once."""
+
+ def __init__(self, *, fail: bool) -> None:
+ self._fail = fail
+ self.served = False
+
+ async def serve(self, host: str, port: int) -> None:
+ if self._fail:
+ raise OSError("address already in use")
+ self.served = True
+
+
+def _factory_sequence(fail_count: int):
+ """A FastBootstrap factory whose first ``fail_count`` instances fail to bind
+ and every later one binds cleanly — one fresh object per attempt, mirroring
+ the production retry (a failed bind is never reused)."""
+ made: list[_FakeBootstrap] = []
+
+ def factory() -> _FakeBootstrap:
+ fb = _FakeBootstrap(fail=len(made) < fail_count)
+ made.append(fb)
+ return fb
+
+ return factory, made
+
+
+def test_binds_on_first_attempt_with_no_backoff() -> None:
+ """Port is free (the normal start): the first bind wins, zero delay."""
+ loop = asyncio.new_event_loop()
+ try:
+ factory, made = _factory_sequence(fail_count=0)
+ slept: list[float] = []
+ bootstrap = _serve_bootstrap_with_retry(
+ loop, "127.0.0.1", 47821, _factory=factory, _sleep=slept.append
+ )
+ assert bootstrap is not None
+ assert bootstrap.served is True
+ assert len(made) == 1
+ assert slept == []
+ finally:
+ loop.close()
+
+
+def test_recovers_from_transient_post_restart_bind_failure() -> None:
+ """The restart race: the old process is still releasing the port, so the
+ first two binds fail transiently — a retry must bind and return the live
+ bootstrap, NOT conclude 'already running'."""
+ loop = asyncio.new_event_loop()
+ try:
+ factory, made = _factory_sequence(fail_count=2)
+ slept: list[float] = []
+ bootstrap = _serve_bootstrap_with_retry(
+ loop,
+ "127.0.0.1",
+ 47821,
+ attempts=5,
+ delay=0.4,
+ _factory=factory,
+ _sleep=slept.append,
+ )
+ assert bootstrap is not None, "must come up, not bounce as 'already running'"
+ assert bootstrap.served is True
+ assert len(made) == 3, "bound on the third attempt"
+ assert slept == [0.4, 0.4], "backed off before each retry, not after success"
+ finally:
+ loop.close()
+
+
+def test_gives_up_when_port_stays_busy() -> None:
+ """A genuinely live second instance never frees the port: after every
+ attempt the retry returns None so the caller maps it to 'already running'
+ (the single-instance lock then confirms)."""
+ loop = asyncio.new_event_loop()
+ try:
+ factory, made = _factory_sequence(fail_count=99)
+ slept: list[float] = []
+ bootstrap = _serve_bootstrap_with_retry(
+ loop,
+ "127.0.0.1",
+ 47821,
+ attempts=4,
+ delay=0.2,
+ _factory=factory,
+ _sleep=slept.append,
+ )
+ assert bootstrap is None
+ assert len(made) == 4, "tried exactly `attempts` times"
+ assert slept == [0.2, 0.2, 0.2], "slept between attempts, not after the last"
+ finally:
+ loop.close()
diff --git a/tests/unit/ui/web/test_launcher_primary_instance.py b/tests/unit/ui/web/test_launcher_primary_instance.py
index 7a0e852efa..5d129f091a 100644
--- a/tests/unit/ui/web/test_launcher_primary_instance.py
+++ b/tests/unit/ui/web/test_launcher_primary_instance.py
@@ -18,11 +18,15 @@ tests / parallel dev / smoke probes).
from __future__ import annotations
from pathlib import Path
+from types import SimpleNamespace
import pytest
from jarvis.ui.desktop_app import acquire_single_instance_lock
-from jarvis.ui.web.launcher import _acquire_primary_lock_for_headless
+from jarvis.ui.web.launcher import (
+ _acquire_primary_lock_for_headless,
+ _claim_headless_primary_lock,
+)
def test_sole_headless_instance_is_primary(
@@ -72,3 +76,32 @@ def test_secondary_headless_instance_is_not_primary(
assert os.environ["JARVIS_PRIMARY_INSTANCE"] == "0"
finally:
held.release()
+
+
+def test_no_lock_headless_instance_is_secondary_and_does_not_hold_lock(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A --no-lock headless/dev/smoke run must not block the desktop app.
+
+ It is explicitly secondary, so it does not run crash recovery and it leaves
+ the single-instance lock free for a real desktop autostart.
+ """
+ monkeypatch.delenv("JARVIS_PRIMARY_INSTANCE", raising=False)
+ lock_path = tmp_path / "jarvis.lock"
+ meta_path = tmp_path / "jarvis.lock.meta"
+
+ lock = _claim_headless_primary_lock(
+ SimpleNamespace(no_lock=True),
+ lock_path=lock_path,
+ meta_path=meta_path,
+ )
+ assert lock is None
+
+ import os
+
+ assert os.environ["JARVIS_PRIMARY_INSTANCE"] == "0"
+
+ desktop_lock = acquire_single_instance_lock(
+ lock_path=lock_path, meta_path=meta_path
+ )
+ desktop_lock.release()
diff --git a/tests/unit/ui/web/test_missions_auth_token.py b/tests/unit/ui/web/test_missions_auth_token.py
new file mode 100644
index 0000000000..5f6d6e34b1
--- /dev/null
+++ b/tests/unit/ui/web/test_missions_auth_token.py
@@ -0,0 +1,55 @@
+"""Regression guard for the workspace-PTY "stuck on connecting" bug.
+
+Root cause: the fast-boot desktop path mints a RAW ``secrets.token_urlsafe``,
+injects it into ``window.__JARVIS_TOKEN``, but never issues it through
+``GET /api/missions/auth/token`` — so it is absent from the in-memory token set
+and every token-gated WebSocket (workspace PTY, missions PTY/stream) rejects it
+with close code 4401. The frontend then hangs forever on "connecting".
+
+Fix: the desktop session token is seeded into the token store at server build
+via ``register_session_token_from_env`` so ``validate_token`` accepts it.
+"""
+from __future__ import annotations
+
+from jarvis.ui.web.missions_auth import (
+ issue_token,
+ register_session_token_from_env,
+ register_token,
+ reset_tokens,
+ validate_token,
+)
+
+
+def test_raw_unissued_token_is_rejected_until_registered() -> None:
+ reset_tokens()
+ raw = "raw-session-token-never-issued-0123456789"
+ assert validate_token(raw) is False # exactly the 4401 path
+
+ register_token(raw)
+ assert validate_token(raw) is True
+
+
+def test_register_session_token_from_env_seeds_the_injected_token(monkeypatch) -> None:
+ reset_tokens()
+ env_var = "JARVIS_TEST_AUTH_TOKEN_ENV"
+ injected = "injected-desktop-session-token-abc"
+ monkeypatch.setenv(env_var, injected)
+
+ # Mirrors the desktop: the token is injected but not issued → invalid.
+ assert validate_token(injected) is False
+
+ returned = register_session_token_from_env(env_var)
+ assert returned == injected
+ assert validate_token(injected) is True
+
+
+def test_register_session_token_from_env_noops_when_unset(monkeypatch) -> None:
+ reset_tokens()
+ monkeypatch.delenv("JARVIS_TEST_AUTH_TOKEN_UNSET", raising=False)
+ assert register_session_token_from_env("JARVIS_TEST_AUTH_TOKEN_UNSET") is None
+
+
+def test_issued_tokens_still_validate() -> None:
+ reset_tokens()
+ tok = issue_token()
+ assert validate_token(tok) is True
diff --git a/tests/unit/ui/web/test_outputs_routes.py b/tests/unit/ui/web/test_outputs_routes.py
index 4d3d520860..ab61cf0b3a 100644
--- a/tests/unit/ui/web/test_outputs_routes.py
+++ b/tests/unit/ui/web/test_outputs_routes.py
@@ -66,6 +66,13 @@ async def db_conn() -> AsyncIterator[aiosqlite.Connection]:
"updated_ms INTEGER NOT NULL, iteration INTEGER NOT NULL DEFAULT 0, "
"cost_usd REAL NOT NULL DEFAULT 0.0)"
)
+ # The continuation-link lookup reads MissionDispatched events; mirror the
+ # subset of the real `mission_events` schema the route helper touches.
+ await conn.execute(
+ "CREATE TABLE mission_events ("
+ "seq INTEGER PRIMARY KEY AUTOINCREMENT, mission_id TEXT NOT NULL, "
+ "event_type TEXT NOT NULL, payload_json TEXT NOT NULL)"
+ )
try:
yield conn
finally:
@@ -133,6 +140,36 @@ async def _insert_mission(
)
+async def _insert_dispatch_event(
+ conn: aiosqlite.Connection,
+ *,
+ child_id: str,
+ parent_id: str,
+) -> None:
+ """Record the child's ``MissionDispatched`` event carrying its parent link.
+
+ Mirrors what ``mgr.dispatch(parent_mission_id=...)`` persists on a re-run:
+ the parent→child edge lives only in the dispatch event payload (the
+ ``missions`` header has no parent column).
+ """
+ import json
+
+ payload = json.dumps(
+ {
+ "event_type": "MissionDispatched",
+ "prompt": "task",
+ "parent_mission_id": parent_id,
+ "priority": 0,
+ "language": "en",
+ }
+ )
+ await conn.execute(
+ "INSERT INTO mission_events (mission_id, event_type, payload_json) "
+ "VALUES (?, ?, ?)",
+ (child_id, "MissionDispatched", payload),
+ )
+
+
# --- _parse_slug + _mission_id_prefix_for_dir unit tests ---------------------
@@ -292,6 +329,72 @@ async def test_list_outputs_cancelled_maps_to_cancelled_status(
assert sessions[0]["status"] == "cancelled"
+async def test_list_outputs_cancelled_with_live_child_exposes_continuation(
+ app: FastAPI, tmp_path: Path, db_conn: aiosqlite.Connection
+) -> None:
+ """A CANCELLED card whose re-run child is still running must say so.
+
+ Forensic 2026-06-28 (missions 019f0fa6 → 019f0fac): the user clicked
+ "Continue" on a cancelled mission; that spawned a linked child which ran
+ on (CRITIQUING), but the cancelled card kept showing a "Continue" button
+ with no hint that its work was already live — two visually identical
+ cards, one cancelled + continuable, one running. The list now resolves the
+ live continuation (parent_mission_id in the child's MissionDispatched
+ event) and exposes it so the UI can replace "Continue" with a "running"
+ indicator pointing at the child.
+ """
+ parent = "019f0fa6-4ff6-7bd9-87fd-a32e201b32c9"
+ child = "019f0fac-26a3-7c59-bfa3-385fb1e426fc"
+ _make_mission_dir(tmp_path, parent)
+ _make_mission_dir(tmp_path, child)
+ await _insert_mission(db_conn, mission_id=parent, state="CANCELLED")
+ await _insert_mission(db_conn, mission_id=child, state="CRITIQUING")
+ await _insert_dispatch_event(db_conn, child_id=child, parent_id=parent)
+
+ with TestClient(app) as client:
+ r = client.get("/api/outputs")
+ sessions = {s["slug"]: s for s in r.json()["sessions"]}
+
+ psum = sessions[f"mission_{parent[:13]}"]
+ assert psum["status"] == "cancelled"
+ assert psum["active_child_id"] == child, (
+ "cancelled card must expose its live re-run child so the UI can stop "
+ f"lying with a 'Continue' button, got {psum.get('active_child_id')!r}"
+ )
+ assert psum["active_child_slug"] == f"mission_{child[:13]}"
+
+ # The live child itself is just RUNNING — it has no continuation of its own.
+ csum = sessions[f"mission_{child[:13]}"]
+ assert csum["status"] == "running"
+ assert csum["active_child_id"] is None
+
+
+async def test_list_outputs_cancelled_with_terminal_child_keeps_continue(
+ app: FastAPI, tmp_path: Path, db_conn: aiosqlite.Connection
+) -> None:
+ """A re-run child that has itself finished must NOT suppress Continue.
+
+ The guard is a *liveness* signal, not a permanent lock: once the child
+ reaches a terminal state the parent is freely re-runnable again, so the
+ list must report no active continuation (active_child_id stays None) and
+ the UI shows "Continue" once more.
+ """
+ parent = "019f0fb0-1111-7000-8000-000000000001"
+ child = "019f0fb1-2222-7000-8000-000000000002"
+ _make_mission_dir(tmp_path, parent)
+ _make_mission_dir(tmp_path, child)
+ await _insert_mission(db_conn, mission_id=parent, state="CANCELLED")
+ await _insert_mission(db_conn, mission_id=child, state="FAILED")
+ await _insert_dispatch_event(db_conn, child_id=child, parent_id=parent)
+
+ with TestClient(app) as client:
+ r = client.get("/api/outputs")
+ sessions = {s["slug"]: s for s in r.json()["sessions"]}
+ assert sessions[f"mission_{parent[:13]}"]["active_child_id"] is None
+
+
@pytest.mark.asyncio
async def test_list_outputs_running_mission_duration_ticks_from_created(
app: FastAPI, tmp_path: Path, db_conn: aiosqlite.Connection
diff --git a/tests/unit/ui/web/test_skills_routes.py b/tests/unit/ui/web/test_skills_routes.py
index 7914fd5830..158b5040e1 100644
--- a/tests/unit/ui/web/test_skills_routes.py
+++ b/tests/unit/ui/web/test_skills_routes.py
@@ -261,7 +261,11 @@ def test_create_skill_endpoint_writes_and_lists(skills_root: Path) -> None:
client, _reg = _client(skills_root)
res = client.post(
"/api/skills",
- json={"name": "Form Made Skill", "description": "from the form", "body": "## x\n"},
+ json={
+ "name": "Form Made Skill",
+ "description": "from the form",
+ "body": "## Form Made Skill\n\nReply politely when invoked.\n",
+ },
)
assert res.status_code == 200, res.text
assert res.json()["name"] == "Form Made Skill"
@@ -269,10 +273,19 @@ def test_create_skill_endpoint_writes_and_lists(skills_root: Path) -> None:
assert "Form Made Skill" in names
+def test_create_skill_endpoint_rejects_empty_body(skills_root: Path) -> None:
+ """A skill with only a heading / blank body is functionless — refuse it
+ (the Hallo-Hallo-Hallo forensic) so no dead skill is ever persisted."""
+ client, _reg = _client(skills_root)
+ res = client.post("/api/skills", json={"name": "Hollow", "body": "## Hollow\n"})
+ assert res.status_code == 400, res.text
+ assert "instructions" in res.json()["detail"].lower()
+
+
def test_create_skill_endpoint_rejects_duplicate(skills_root: Path) -> None:
client, _reg = _client(skills_root)
- client.post("/api/skills", json={"name": "Dup", "body": "## x\n"})
- res = client.post("/api/skills", json={"name": "Dup", "body": "## y\n"})
+ client.post("/api/skills", json={"name": "Dup", "body": "## Dup\n\nDo a thing.\n"})
+ res = client.post("/api/skills", json={"name": "Dup", "body": "## Dup\n\nDo another.\n"})
assert res.status_code == 409, res.text
diff --git a/tests/unit/ui/web/test_voice_status_route.py b/tests/unit/ui/web/test_voice_status_route.py
index c0ae61e962..73f73050f1 100644
--- a/tests/unit/ui/web/test_voice_status_route.py
+++ b/tests/unit/ui/web/test_voice_status_route.py
@@ -20,7 +20,10 @@ from jarvis.core.events import VoiceBootStatus
from jarvis.ui.web.server import WebServer
-def test_voice_status_defaults_to_false() -> None:
+def test_voice_status_defaults_to_false(monkeypatch) -> None:
+ # Deterministic: a JARVIS_VOICE=0 in the ambient shell would otherwise seed
+ # ready=True (see test_voice_status_ready_when_voice_disabled below).
+ monkeypatch.delenv("JARVIS_VOICE", raising=False)
srv = WebServer(JarvisConfig(), bus=EventBus())
assert srv._voice_ready is False
with TestClient(srv.app) as client:
@@ -29,6 +32,20 @@ def test_voice_status_defaults_to_false() -> None:
assert resp.json() == {"ready": False}
[email protected]("value", ["0", "off", "false", "OFF"])
+def test_voice_status_ready_when_voice_disabled(monkeypatch, value: str) -> None:
+ """With the local voice stack off (JARVIS_VOICE=0 — headless / VPS /
+ browser-mic-only) nothing ever warms up, so the server seeds ready=True.
+ Otherwise the frontend "starting up" banner would hang forever even though
+ the user can already type and use browser voice."""
+ monkeypatch.setenv("JARVIS_VOICE", value)
+ srv = WebServer(JarvisConfig(), bus=EventBus())
+ assert srv._voice_ready is True
+ with TestClient(srv.app) as client:
+ resp = client.get("/api/voice/status")
+ assert resp.json() == {"ready": True}
+
+
@pytest.mark.asyncio
async def test_voice_status_flips_true_after_boot_status_event() -> None:
bus = EventBus()
diff --git a/tests/unit/ui/whisperbar/test_frame_loop_resilience.py b/tests/unit/ui/whisperbar/test_frame_loop_resilience.py
deleted file mode 100644
index cf064bcdcc..0000000000
--- a/tests/unit/ui/whisperbar/test_frame_loop_resilience.py
+++ /dev/null
@@ -1,79 +0,0 @@
-"""The JarvisBar animation loop must be self-healing.
-
-Forensic: the bar "stopped moving / froze" until an app restart. Root cause —
-``_schedule_frame`` re-arms the next frame ONLY from its tail line, so a single
-transient render/Tk error (e.g. ``ImageTk.PhotoImage`` raising, a ``TclError``
-during a window move) skips the re-arm and the loop dies permanently while the
-Tk mainloop keeps running (window stays visible, frozen on its last frame).
-
-These tests pin the contract: one frame error drops just that frame and the
-loop keeps ticking. Headless — a fake root/canvas/renderer, no real Tk display.
-"""
-from __future__ import annotations
-
-from jarvis.ui.whisperbar.overlay import WhisperBarOverlay
-
-
-class _FakeRoot:
- def __init__(self) -> None:
- self.scheduled: list[tuple[int, object]] = []
-
- def after(self, ms: int, fn: object) -> None:
- self.scheduled.append((ms, fn))
-
-
-class _FakeCanvas:
- def create_image(self, *a: object, **k: object) -> int:
- return 1
-
- def itemconfig(self, *a: object, **k: object) -> None:
- pass
-
-
-class _BoomRenderer:
- """A renderer whose render() always raises — simulates a transient
- PIL/Tk hiccup mid-frame."""
-
- def render(self, *a: object, **k: object): # noqa: ANN201
- raise RuntimeError("transient render/Tk hiccup")
-
-
-def _bare_bar(renderer_obj: object) -> tuple[WhisperBarOverlay, _FakeRoot]:
- bar = WhisperBarOverlay.__new__(WhisperBarOverlay)
- bar._running = True
- bar._mode = "think"
- bar._ext_level = 0.0
- bar._last_audible_t = 0.0
- bar._t0 = 0.0
- bar._hovered = False
- bar._image_id = None
- bar._photo = None
- root = _FakeRoot()
- bar._root = root
- bar._canvas = _FakeCanvas()
- bar._renderer = renderer_obj # type: ignore[assignment]
- return bar, root
-
-
-def test_frame_loop_reschedules_after_render_error():
- """A render exception must NOT kill the loop: the next frame is still armed
- and the call itself does not propagate (the Tk mainloop must keep running)."""
- bar, root = _bare_bar(_BoomRenderer())
-
- bar._schedule_frame() # must not raise
-
- assert root.scheduled, "frame loop died: next frame was not rescheduled"
- ms, fn = root.scheduled[-1]
- assert fn == bar._schedule_frame
- assert ms == 16
-
-
-def test_frame_loop_stops_rearming_when_not_running():
- """The self-heal must not fight a deliberate stop(): once _running is False
- the loop returns early and does NOT re-arm."""
- bar, root = _bare_bar(_BoomRenderer())
- bar._running = False
-
- bar._schedule_frame()
-
- assert root.scheduled == []
diff --git a/tests/unit/vision/test_cu_capture_strategy.py b/tests/unit/vision/test_cu_capture_strategy.py
new file mode 100644
index 0000000000..7879933f98
--- /dev/null
+++ b/tests/unit/vision/test_cu_capture_strategy.py
@@ -0,0 +1,29 @@
+"""CU capture strategy mapping (Problem 1, 2026-06-28).
+
+The [computer_use].monitor policy must NOT pin the screenshot to the primary while
+the click resolver (_capture_monitor_geometry) already follows the foreground
+window — that mismatch makes CU film an EMPTY primary and "do nothing" when the
+target app is on the secondary. ``cu_capture_strategy`` maps the policy to a
+CAPTURE strategy that FOLLOWS the foreground window for both "primary" and
+"foreground" (the "primary" policy additionally MOVES the target to the main
+monitor via the G8 hook); "all" still captures the whole virtual desktop.
+"""
+from __future__ import annotations
+
+from jarvis.vision.screenshot import cu_capture_strategy
+
+
+def test_primary_policy_captures_foreground_not_pinned():
+ assert cu_capture_strategy("primary") == "foreground"
+
+
+def test_foreground_policy_captures_foreground():
+ assert cu_capture_strategy("foreground") == "foreground"
+
+
+def test_all_policy_captures_whole_virtual_desktop():
+ assert cu_capture_strategy("all") == "all"
+
+
+def test_unknown_policy_defaults_to_following_foreground():
+ assert cu_capture_strategy("nonsense") == "foreground"
diff --git a/tests/unit/vision/test_select_capture_monitor.py b/tests/unit/vision/test_select_capture_monitor.py
new file mode 100644
index 0000000000..1d057d1895
--- /dev/null
+++ b/tests/unit/vision/test_select_capture_monitor.py
@@ -0,0 +1,54 @@
+"""select_capture_monitor — pick the right screen for a Computer-Use screenshot.
+
+Regression for the "CU works the whole time on my non-main monitor" bug: with a
+monitor positioned LEFT of primary, mss lists that left (negative-X) screen as
+physical[0], and the monitor dicts carry no ``is_primary`` flag. The old
+``physical[0]`` fallback therefore treated the LEFT secondary monitor as the
+primary, so every foreground-lookup fallback captured the wrong screen (where
+clicks are also broken). The primary is identified by its (0,0) origin instead.
+"""
+from __future__ import annotations
+
+from jarvis.vision.screenshot import select_capture_monitor
+
+
+def _mon(left: int, top: int, w: int, h: int, **extra) -> dict:
+ return {"left": left, "top": top, "width": w, "height": h, **extra}
+
+
+# The reported two-monitor setup: mss orders the LEFT (negative-X) monitor FIRST.
+_VIRTUAL = _mon(-2560, 0, 6400, 2160) # monitors[0] = virtual bounding box
+_LEFT = _mon(-2560, 0, 2560, 1440) # physical[0] — secondary, X < 0
+_MAIN = _mon(0, 0, 3840, 2160) # physical[1] — true primary at (0,0)
+_MONITORS = [_VIRTUAL, _LEFT, _MAIN]
+
+
+def test_primary_strategy_picks_the_origin_monitor_not_physical0() -> None:
+ # The Windows primary is always at virtual (0,0); it must win over the left
+ # monitor that mss happens to list first.
+ assert select_capture_monitor(_MONITORS, strategy="primary") is _MAIN
+
+
+def test_foreground_fallback_uses_true_primary(monkeypatch) -> None:
+ # Off Windows / when foreground detection is unavailable, the foreground
+ # strategy returns `primary` — which must be the (0,0) main monitor.
+ monkeypatch.setattr("jarvis.vision.screenshot.os.name", "posix")
+ assert select_capture_monitor(_MONITORS, strategy="foreground") is _MAIN
+
+
+def test_explicit_is_primary_flag_still_wins() -> None:
+ flagged = {**_LEFT, "is_primary": True}
+ mons = [_VIRTUAL, flagged, _MAIN]
+ assert select_capture_monitor(mons, strategy="primary") is flagged
+
+
+def test_single_monitor_returns_it() -> None:
+ only = _mon(0, 0, 1920, 1080)
+ assert select_capture_monitor([only], strategy="primary") is only
+
+
+def test_no_origin_monitor_falls_back_to_first_physical() -> None:
+ # Defensive: if somehow no monitor sits at (0,0), keep the old behaviour.
+ a = _mon(100, 0, 800, 600)
+ b = _mon(900, 0, 800, 600)
+ assert select_capture_monitor([_mon(100, 0, 1600, 600), a, b], strategy="primary") is a
diff --git a/tests/unit/vision/test_uia_node_state.py b/tests/unit/vision/test_uia_node_state.py
new file mode 100644
index 0000000000..df92e8f530
--- /dev/null
+++ b/tests/unit/vision/test_uia_node_state.py
@@ -0,0 +1,94 @@
+"""Accessibility state on the UIA node model (audit foundation for #5/#16/#1B).
+
+UIANode/RawNode now carry ``is_password`` (a secure/password edit -> redact before
+upload, never read its value) and ``focused`` (holds keyboard focus -> a
+click_element that focuses a field is verifiable post-hoc). These pin the
+defaults, the RawNode->UIANode copy, and the best-effort populate in the Windows
+traversal (no real UIA needed — a fake element exposes the COM-style properties).
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+from jarvis.core.protocols import UIANode
+from jarvis.vision.pruning import RawNode
+from jarvis.vision.uia_tree import UIATreeSource, _flatten
+
+
+# --- defaults + copy ---------------------------------------------------------
+
+
+def test_uianode_state_defaults_false():
+ n = UIANode(role="Edit", name="x")
+ assert n.is_password is False
+ assert n.focused is False
+
+
+def test_to_uia_nodes_copies_state():
+ raw = [
+ RawNode(role="Edit", name="pw", is_password=True, focused=True),
+ RawNode(role="Button", name="ok"),
+ ]
+ nodes = UIATreeSource._to_uia_nodes(raw)
+ assert nodes[0].is_password is True
+ assert nodes[0].focused is True
+ assert nodes[1].is_password is False
+ assert nodes[1].focused is False
+
+
+# --- best-effort populate in the Windows traversal ---------------------------
+
+
+def _fake_element(*, is_password: Any = False, focused: Any = False,
+ with_element: bool = True) -> Any:
+ rect = SimpleNamespace(left=10, top=20, right=110, bottom=60)
+ raw_el = (
+ SimpleNamespace(CurrentIsPassword=is_password, CurrentHasKeyboardFocus=focused)
+ if with_element else None
+ )
+ return SimpleNamespace(
+ control_type="Edit", name="field", automation_id="f1",
+ rectangle=rect, enabled=True, is_offscreen=False,
+ iface_value=None, element=raw_el,
+ )
+
+
+def test_flatten_populates_password_and_focus():
+ out: list[RawNode] = []
+ _flatten(_fake_element(is_password=True, focused=True),
+ depth=0, max_depth=0, parent_index=-1, out=out)
+ assert len(out) == 1
+ assert out[0].is_password is True
+ assert out[0].focused is True
+
+
+def test_flatten_defaults_false_for_plain_control():
+ out: list[RawNode] = []
+ _flatten(_fake_element(is_password=False, focused=False),
+ depth=0, max_depth=0, parent_index=-1, out=out)
+ assert out[0].is_password is False
+ assert out[0].focused is False
+
+
+def test_flatten_defaults_false_when_no_underlying_element():
+ out: list[RawNode] = []
+ _flatten(_fake_element(with_element=False),
+ depth=0, max_depth=0, parent_index=-1, out=out)
+ assert out[0].is_password is False
+ assert out[0].focused is False
+
+
+def test_flatten_state_read_never_skips_node_on_error():
+ # A COM access that raises must not drop the node — it just defaults to False.
+ class _Boom:
+ @property
+ def CurrentIsPassword(self): # noqa: N802 — mirror the COM property name
+ raise OSError("COM gone")
+
+ el = _fake_element()
+ el.element = _Boom()
+ out: list[RawNode] = []
+ _flatten(el, depth=0, max_depth=0, parent_index=-1, out=out)
+ assert len(out) == 1
+ assert out[0].is_password is False
diff --git a/tests/unit/voice/test_config_readback.py b/tests/unit/voice/test_config_readback.py
new file mode 100644
index 0000000000..2bc948d78d
--- /dev/null
+++ b/tests/unit/voice/test_config_readback.py
@@ -0,0 +1,87 @@
+"""Tests for the deterministic config readback (Wave 1.4).
+
+In the voice "apply everything now" path there is no pre-confirmation, so the
+post-change spoken line is the only source of truth. It must therefore be
+deterministic and FAITHFUL to the real pipeline outcome — never a free-form
+"done" the brain made up. config_readback renders that line in de/en/es from the
+set_config_value tool result.
+"""
+from __future__ import annotations
+
+from uuid import uuid4
+
+# Preload config before self_mod to satisfy the pre-existing import order
+# (writer→config→brain→voice→echo_confirmation cycles back onto self_mod).
+import jarvis.core.config # noqa: F401, E402 isort:skip
+from jarvis.core.self_mod import PendingMutation # noqa: E402
+from jarvis.voice.config_readback import config_readback # noqa: E402
+
+
+def _applied_dump(
+ *, description: str, new_value: object, requires_restart: bool = False,
+ path: str = "tts.speed",
+) -> dict:
+ return PendingMutation(
+ id=uuid4(),
+ path=path,
+ old_value=1.0,
+ new_value=new_value,
+ needs_confirmation=False,
+ risk_tier="ask",
+ requires_restart=requires_restart,
+ applied=True,
+ description=description,
+ ).model_dump(mode="json")
+
+
+class TestSuccess:
+ def test_applied_speaks_the_real_value(self) -> None:
+ out = _applied_dump(description="TTS speed", new_value=1.25)
+ text = config_readback(success=True, output=out, language="en")
+ assert "1.25" in text # honest: the value actually written
+ assert "done" in text.lower()
+
+ def test_applied_restart_mentions_restart(self) -> None:
+ out = _applied_dump(description="STT provider", new_value="groq",
+ requires_restart=True)
+ text = config_readback(success=True, output=out, language="en")
+ assert "restart" in text.lower()
+
+ def test_spanish_is_supported(self) -> None:
+ out = _applied_dump(description="TTS speed", new_value=1.25)
+ text = config_readback(success=True, output=out, language="es")
+ assert text is not None
+ assert "done" not in text.lower() # not English
+
+
+class TestHonestFailures:
+ def test_forbidden_is_an_honest_refusal_not_done(self) -> None:
+ out = {"error_kind": "forbidden_path", "path": "security.admin_password_hash"}
+ text = config_readback(success=False, output=out, language="en")
+ assert text is not None
+ # The crucial guarantee: a blocked change is NEVER read back as success.
+ assert "done" not in text.lower()
+ # And it must not leak the path.
+ assert "security" not in text.lower()
+
+ def test_rollback_never_says_done(self) -> None:
+ out = {"error_kind": "reload_failed_rolled_back", "path": "tts.speed"}
+ text = config_readback(success=False, output=out, language="de")
+ assert text is not None
+ assert "erledigt" not in text.lower() # never falsely "done"
+
+ def test_invalid_value_never_says_done(self) -> None:
+ out = {"error_kind": "validate_failed", "path": "tts.speed"}
+ text = config_readback(success=False, output=out, language="en")
+ assert text is not None
+ assert "done" not in text.lower()
+
+
+class TestFallthrough:
+ def test_non_config_result_returns_none(self) -> None:
+ # A result that isn't a recognizable config outcome → caller keeps its
+ # normal (free-form brain) phrasing.
+ assert config_readback(success=True, output={"foo": "bar"}, language="en") is None
+
+ def test_non_dict_output_returns_none(self) -> None:
+ assert config_readback(success=True, output="hello", language="en") is None
diff --git a/tests/unit/voice/test_contextual_readback.py b/tests/unit/voice/test_contextual_readback.py
new file mode 100644
index 0000000000..484714b4c6
--- /dev/null
+++ b/tests/unit/voice/test_contextual_readback.py
@@ -0,0 +1,304 @@
+"""Tests for the ReadbackComposer — context-aware spoken status readbacks.
+
+Maintainer mandate: status / outcome / acknowledgement replies must not be
+fixed stock phrases read out of a table; they must be phrased for the actual
+situation. The composer generates one bounded flash-LLM sentence from the
+deterministic facts and falls back to the EXISTING canned line on any failure.
+Guarantees under test:
+
+* fallback-only mode (no provider) returns the canned line verbatim
+* a healthy provider's sentence is used (and voice-scrubbed)
+* timeout / provider error / breaker-open / wrong language → canned fallback
+* honesty: a fabricated NUMBER is always rejected; for honesty_bound calls a
+ content word absent from the facts is rejected (ADR-0009 rephrase-only)
+* an in-progress situation rejects a completion claim
+* never raises and never returns an unexpected type (AD-OE6 zero silent drops)
+"""
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+import pytest
+
+from jarvis.brain.ack_brain import CircuitBreaker
+from jarvis.brain.ack_brain.config import AckBrainConfig
+from jarvis.voice.contextual_readback import ReadbackComposer, render_readback
+
+CANNED = "CANNED FALLBACK LINE"
+
+
+def _canned() -> str:
+ return CANNED
+
+
+class _FakeProvider:
+ """Records calls; returns a canned reply, optionally slow or raising."""
+
+ def __init__(
+ self,
+ reply: str | None = None,
+ *,
+ delay_s: float = 0.0,
+ raises: bool = False,
+ ) -> None:
+ self.reply = reply
+ self.delay_s = delay_s
+ self.raises = raises
+ self.calls: list[dict[str, Any]] = []
+
+ async def run(
+ self, utterance: str, language: str, *, persona_prompt: str
+ ) -> str | None:
+ self.calls.append(
+ {"utterance": utterance, "language": language, "persona": persona_prompt}
+ )
+ if self.raises:
+ raise RuntimeError("provider boom")
+ if self.delay_s:
+ await asyncio.sleep(self.delay_s)
+ return self.reply
+
+
+def _composer(
+ provider: _FakeProvider | None = None, *, timeout_ms: int = 1500
+) -> ReadbackComposer:
+ if provider is None:
+ return ReadbackComposer()
+ cfg = AckBrainConfig(timeout_ms=timeout_ms)
+ breaker = CircuitBreaker(threshold=3, cooldown_s=60)
+ return ReadbackComposer(provider=provider, config=cfg, breaker=breaker)
+
+
+# --------------------------------------------------------------------------- #
+# Fallback-only mode (no provider wired) #
+# --------------------------------------------------------------------------- #
+
+
+async def test_fallback_only_returns_canned() -> None:
+ composer = _composer()
+ out = await composer.compose(
+ instruction="The on-screen task succeeded.",
+ language="en",
+ canned=_canned,
+ facts={"observation": "the browser is open"},
+ )
+ assert out == CANNED
+
+
+async def test_render_readback_none_composer_returns_canned() -> None:
+ out = await render_readback(
+ None,
+ instruction="The on-screen task succeeded.",
+ language="de",
+ canned=_canned,
+ )
+ assert out == CANNED
+
+
+# --------------------------------------------------------------------------- #
+# Happy path — generated sentence is used #
+# --------------------------------------------------------------------------- #
+
+
+async def test_generated_sentence_is_used() -> None:
+ provider = _FakeProvider("Sure, your browser is open now.")
+ composer = _composer(provider)
+ out = await composer.compose(
+ instruction="The on-screen task succeeded.",
+ language="en",
+ canned=_canned,
+ facts={"observation": "the browser is open"},
+ )
+ assert out != CANNED
+ assert "browser" in out.lower()
+ assert provider.calls, "provider should have been called"
+
+
+async def test_spanish_generation_accepted() -> None:
+ provider = _FakeProvider("Listo, tu navegador está abierto.")
+ composer = _composer(provider)
+ out = await composer.compose(
+ instruction="The on-screen task succeeded.",
+ language="es",
+ canned=_canned,
+ facts={"observation": "el navegador está abierto"},
+ )
+ assert out != CANNED
+ assert "navegador" in out.lower()
+
+
+# --------------------------------------------------------------------------- #
+# Failure paths fall back to canned #
+# --------------------------------------------------------------------------- #
+
+
+async def test_timeout_falls_back_to_canned() -> None:
+ provider = _FakeProvider("too slow", delay_s=0.5)
+ composer = _composer(provider)
+ out = await composer.compose(
+ instruction="The on-screen task succeeded.",
+ language="en",
+ canned=_canned,
+ latency_budget_ms=20, # per-call hard deadline beats the 0.5 s provider
+ )
+ assert out == CANNED
+
+
+async def test_provider_error_falls_back_to_canned() -> None:
+ provider = _FakeProvider(raises=True)
+ composer = _composer(provider)
+ out = await composer.compose(
+ instruction="The on-screen task succeeded.",
+ language="en",
+ canned=_canned,
+ )
+ assert out == CANNED
+
+
+async def test_empty_output_falls_back_to_canned() -> None:
+ provider = _FakeProvider(" ")
+ composer = _composer(provider)
+ out = await composer.compose(
+ instruction="The on-screen task succeeded.",
+ language="en",
+ canned=_canned,
+ )
+ assert out == CANNED
+
+
+async def test_wrong_language_falls_back_to_canned() -> None:
+ # German output requested for an English turn -> rejected -> canned.
+ provider = _FakeProvider("Das hat auf dem Bildschirm geklappt und ist fertig.")
+ composer = _composer(provider)
+ out = await composer.compose(
+ instruction="The on-screen task succeeded.",
+ language="en",
+ canned=_canned,
+ )
+ assert out == CANNED
+
+
+# --------------------------------------------------------------------------- #
+# Honesty guards #
+# --------------------------------------------------------------------------- #
+
+
+async def test_fabricated_number_rejected() -> None:
+ # facts carry no number; the model invents "5 tabs" -> rejected.
+ provider = _FakeProvider("I opened 5 tabs for you.")
+ composer = _composer(provider)
+ out = await composer.compose(
+ instruction="The on-screen task succeeded.",
+ language="en",
+ canned=_canned,
+ facts={"observation": "the browser is open"},
+ )
+ assert out == CANNED
+
+
+async def test_number_from_facts_allowed() -> None:
+ provider = _FakeProvider("Your browser is open with 3 tabs.")
+ composer = _composer(provider)
+ out = await composer.compose(
+ instruction="The on-screen task succeeded.",
+ language="en",
+ canned=_canned,
+ facts={"observation": "the browser is open with 3 tabs"},
+ )
+ assert out != CANNED
+ assert "3" in out
+
+
+async def test_honesty_bound_rejects_unsupported_content_word() -> None:
+ provider = _FakeProvider("The calculator is showing the result.")
+ composer = _composer(provider)
+ out = await composer.compose(
+ instruction="The on-screen task succeeded.",
+ language="en",
+ canned=_canned,
+ facts={"observation": "the browser is open with your inbox"},
+ honesty_bound=True,
+ )
+ assert out == CANNED
+
+
+async def test_honesty_bound_accepts_rephrase_of_facts() -> None:
+ provider = _FakeProvider("Your browser is open with the inbox.")
+ composer = _composer(provider)
+ out = await composer.compose(
+ instruction="The on-screen task succeeded.",
+ language="en",
+ canned=_canned,
+ facts={"observation": "the browser is open with your inbox"},
+ honesty_bound=True,
+ )
+ assert out != CANNED
+ assert "inbox" in out.lower()
+
+
+# --------------------------------------------------------------------------- #
+# In-progress + forbidden vocab #
+# --------------------------------------------------------------------------- #
+
+
+async def test_in_progress_rejects_completion_claim() -> None:
+ provider = _FakeProvider("That is done on screen.")
+ composer = _composer(provider)
+ out = await composer.compose(
+ instruction="About to do the task on screen in the background.",
+ language="en",
+ canned=_canned,
+ in_progress=True,
+ )
+ assert out == CANNED
+
+
+async def test_forbidden_vocab_rejected() -> None:
+ provider = _FakeProvider("The harness returned exit 5 from the subprocess.")
+ composer = _composer(provider)
+ out = await composer.compose(
+ instruction="The on-screen task failed.",
+ language="en",
+ canned=_canned,
+ )
+ assert out == CANNED
+
+
+# --------------------------------------------------------------------------- #
+# Robustness — never raises, even when the canned fallback is broken #
+# --------------------------------------------------------------------------- #
+
+
+async def test_compose_never_raises_when_canned_raises() -> None:
+ def _boom() -> str:
+ raise RuntimeError("canned boom")
+
+ composer = _composer() # no provider -> must use canned, which raises
+ out = await composer.compose(
+ instruction="The on-screen task succeeded.",
+ language="en",
+ canned=_boom,
+ )
+ assert out == "" # graceful empty, no exception
+
+
+async def test_has_llm_flag() -> None:
+ assert _composer().has_llm is False
+ assert _composer(_FakeProvider("hi there friend")).has_llm is True
diff --git a/tests/unit/workspace/test_agents.py b/tests/unit/workspace/test_agents.py
new file mode 100644
index 0000000000..5ea640584a
--- /dev/null
+++ b/tests/unit/workspace/test_agents.py
@@ -0,0 +1,81 @@
+"""Agent specs + detection (with a fake prober — no real CLIs invoked)."""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.clis.spec import CliSpec, CliStatus
+from jarvis.workspace.agents import (
+ AGENT_NAMES,
+ build_agent_argv,
+ build_install_argv,
+ detect_agents,
+ get_agent,
+ install_command,
+ list_agents,
+ pty_available,
+)
+
+
+def test_only_claude_and_codex() -> None:
+ assert set(AGENT_NAMES) == {"claude", "codex"}
+
+
+def test_specs_are_valid_clispecs() -> None:
+ for agent in list_agents():
+ assert isinstance(agent.spec, CliSpec)
+ assert agent.spec.binary_name in ("claude", "codex")
+ assert agent.spec.check_command[-1] == "--version"
+
+
+def test_install_commands_use_npm() -> None:
+ assert install_command("claude") == "npm install -g @anthropic-ai/claude-code"
+ assert install_command("codex") == "npm install -g @openai/codex"
+ assert install_command("nope") is None
+
+
+def test_launch_command_is_bare_binary() -> None:
+ assert get_agent("claude").launch_command == "claude"
+ assert get_agent("codex").launch_command == "codex"
+
+
+def test_build_agent_argv_wraps_command_in_a_shell() -> None:
+ argv = build_agent_argv("claude")
+ assert argv is not None
+ # the agent command appears in the argv, wrapped by a shell
+ assert any("claude" in part for part in argv)
+ assert len(argv) >= 2 # shell + at least one flag/command
+ assert build_agent_argv("nope") is None
+
+
+def test_build_install_argv_uses_install_command() -> None:
+ argv = build_install_argv("codex")
+ assert argv is not None
+ assert any("@openai/codex" in part for part in argv)
+
+
+def test_pty_available_is_true_on_a_host_with_a_shell() -> None:
+ # CI + dev hosts have a shell + a real PTY backend.
+ assert pty_available() is True
+
+
+class FakeProber:
+ def __init__(self, statuses: dict[str, CliStatus]) -> None:
+ self._statuses = statuses
+
+ async def probe_all(self, specs) -> dict[str, CliStatus]: # noqa: ANN001
+ return {s.name: self._statuses[s.name] for s in specs}
+
+
+async def test_detect_reports_installed_and_version() -> None:
+ prober = FakeProber(
+ {
+ "claude": CliStatus(installed=True, version="2.1.195"),
+ "codex": CliStatus(installed=False, version=None),
+ }
+ )
+ infos = {i.name: i for i in await detect_agents(prober)}
+ assert infos["claude"].installed is True
+ assert infos["claude"].version == "2.1.195"
+ assert infos["codex"].installed is False
+ assert infos["codex"].install_command == "npm install -g @openai/codex"
diff --git a/tests/unit/workspace/test_launch_validation.py b/tests/unit/workspace/test_launch_validation.py
new file mode 100644
index 0000000000..cfb9848781
--- /dev/null
+++ b/tests/unit/workspace/test_launch_validation.py
@@ -0,0 +1,61 @@
+"""Validation + launch expansion for the workspace launcher."""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.workspace.launcher import (
+ LAYOUT_CHOICES,
+ build_slots,
+ validate_split,
+)
+
+
[email protected]("layout", LAYOUT_CHOICES)
+def test_valid_split_passes(layout: int) -> None:
+ validate_split(layout, {"claude": layout, "codex": 0})
+
+
+def test_split_must_sum_to_layout() -> None:
+ with pytest.raises(ValueError, match="sum to"):
+ validate_split(8, {"claude": 5, "codex": 2}) # sums to 7, not 8
+
+
+def test_layout_must_be_a_known_choice() -> None:
+ with pytest.raises(ValueError, match="layout must be"):
+ validate_split(7, {"claude": 7})
+
+
+def test_unknown_agent_rejected() -> None:
+ with pytest.raises(ValueError, match="unknown agents"):
+ validate_split(2, {"claude": 1, "grok": 1})
+
+
+def test_negative_count_rejected() -> None:
+ with pytest.raises(ValueError, match=">= 0"):
+ validate_split(2, {"claude": 4, "codex": -2})
+
+
+def test_zero_total_rejected() -> None:
+ with pytest.raises(ValueError):
+ validate_split(1, {"claude": 0, "codex": 0})
+
+
+def test_build_slots_expands_counts_grouped() -> None:
+ slots = build_slots({"claude": 5, "codex": 3})
+ assert len(slots) == 8
+ agents = [s.agent for s in slots]
+ assert agents.count("claude") == 5
+ assert agents.count("codex") == 3
+ # grouped: all claude first, then codex
+ assert agents[:5] == ["claude"] * 5
+ assert agents[5:] == ["codex"] * 3
+ # indices are unique + contiguous, display names resolved
+ assert [s.index for s in slots] == list(range(8))
+ assert slots[0].display_name == "Claude Code"
+ assert slots[5].display_name == "Codex"
+
+
+def test_build_slots_skips_zero_count_agents() -> None:
+ slots = build_slots({"claude": 2, "codex": 0})
+ assert all(s.agent == "claude" for s in slots)
+ assert len(slots) == 2
diff --git a/tests/unit/workspace/test_trust.py b/tests/unit/workspace/test_trust.py
new file mode 100644
index 0000000000..1a4f203b4d
--- /dev/null
+++ b/tests/unit/workspace/test_trust.py
@@ -0,0 +1,119 @@
+"""Trust pre-seed for Claude Code (~/.claude.json) and Codex (config.toml)."""
+from __future__ import annotations
+
+import json
+import sys
+import tomllib
+from pathlib import Path
+
+from jarvis.workspace.trust import ensure_trusted
+
+
+def _repo(tmp_path: Path) -> Path:
+ p = tmp_path / "project"
+ p.mkdir()
+ return p
+
+
+def test_claude_creates_trust_entry_when_no_config(tmp_path: Path) -> None:
+ home = tmp_path / "home"
+ home.mkdir()
+ repo = _repo(tmp_path)
+
+ [res] = ensure_trusted(repo, ["claude"], home=home)
+ assert res.ok and res.agent == "claude"
+
+ data = json.loads((home / ".claude.json").read_text(encoding="utf-8"))
+ entry = data["projects"][str(repo)]
+ assert entry["hasTrustDialogAccepted"] is True
+
+
+def test_claude_preserves_existing_keys_and_backs_up(tmp_path: Path) -> None:
+ home = tmp_path / "home"
+ home.mkdir()
+ repo = _repo(tmp_path)
+ cfg = home / ".claude.json"
+ cfg.write_text(
+ json.dumps(
+ {
+ "userID": "keep-me",
+ "projects": {
+ "C:/some/other": {"hasTrustDialogAccepted": True, "lastCost": 4},
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ ensure_trusted(repo, ["claude"], home=home)
+
+ data = json.loads(cfg.read_text(encoding="utf-8"))
+ # unrelated top-level + other project survive
+ assert data["userID"] == "keep-me"
+ assert data["projects"]["C:/some/other"]["lastCost"] == 4
+ # our project is now trusted
+ assert data["projects"][str(repo)]["hasTrustDialogAccepted"] is True
+ # original was backed up exactly once
+ assert (home / ".claude.json.jarvis-bak").exists()
+
+
+def test_claude_is_idempotent_noop_second_run(tmp_path: Path) -> None:
+ home = tmp_path / "home"
+ home.mkdir()
+ repo = _repo(tmp_path)
+ ensure_trusted(repo, ["claude"], home=home)
+ [res2] = ensure_trusted(repo, ["claude"], home=home)
+ assert res2.ok
+ assert res2.method == "noop"
+
+
+def test_codex_writes_trust_level_parseable_toml(tmp_path: Path) -> None:
+ home = tmp_path / "home"
+ home.mkdir()
+ repo = _repo(tmp_path)
+
+ [res] = ensure_trusted(repo, ["codex"], home=home)
+ assert res.ok and res.agent == "codex"
+
+ cfg = home / ".codex" / "config.toml"
+ parsed = tomllib.loads(cfg.read_text(encoding="utf-8"))
+ # key round-trips to the native path string and is marked trusted
+ assert parsed["projects"][str(repo)]["trust_level"] == "trusted"
+
+
+def test_codex_preserves_existing_config(tmp_path: Path) -> None:
+ home = tmp_path / "home"
+ home.mkdir()
+ repo = _repo(tmp_path)
+ codex_dir = home / ".codex"
+ codex_dir.mkdir()
+ (codex_dir / "config.toml").write_text(
+ 'model = "gpt-5.5"\napproval_policy = "never"\n', encoding="utf-8"
+ )
+
+ ensure_trusted(repo, ["codex"], home=home)
+
+ parsed = tomllib.loads((codex_dir / "config.toml").read_text(encoding="utf-8"))
+ assert parsed["model"] == "gpt-5.5"
+ assert parsed["approval_policy"] == "never"
+ assert parsed["projects"][str(repo)]["trust_level"] == "trusted"
+
+
+def test_codex_idempotent_noop_second_run(tmp_path: Path) -> None:
+ home = tmp_path / "home"
+ home.mkdir()
+ repo = _repo(tmp_path)
+ ensure_trusted(repo, ["codex"], home=home)
+ [res2] = ensure_trusted(repo, ["codex"], home=home)
+ assert res2.ok and res2.method == "noop"
+
+
+def test_test_mode_ignores_real_codex_home_env(tmp_path: Path, monkeypatch) -> None:
+ # A stray CODEX_HOME must NOT redirect the write away from the tmp home.
+ monkeypatch.setenv("CODEX_HOME", str(tmp_path / "REAL_DO_NOT_TOUCH"))
+ home = tmp_path / "home"
+ home.mkdir()
+ repo = _repo(tmp_path)
+ ensure_trusted(repo, ["codex"], home=home)
+ assert (home / ".codex" / "config.toml").exists()
+ assert not (tmp_path / "REAL_DO_NOT_TOUCH").exists()