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.

chore: auto-save WIP via Claude stop-hook safety net (2026-07-10 18:52)

Ruben Lütkeddc87effe6bd
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index 027ba6c920..ea12ad7772 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -15,6 +15,7 @@ import json
import logging
import os
import sys
+import threading
import tomllib
from dataclasses import dataclass
from pathlib import Path
@@ -54,6 +55,54 @@ PROFILES_DIR = PROJECT_ROOT / "profiles"
DATA_DIR = PROJECT_ROOT / "data"
ASSETS_DIR = PROJECT_ROOT / "assets"
+# Guards _resolve_writable_data_dir()'s lazy writability probe below. Named
+# separately from config_writer's _WRITE_LOCK — this protects the (rare,
+# once-per-process) directory-resolution probe, not a jarvis.toml write.
+_data_dir_lock = threading.Lock()
+_data_dir_cache: tuple[Path, Path] | None = None # (DATA_DIR seen, resolved dir)
+
+
+def _resolve_writable_data_dir() -> Path:
+ """Return the directory to use for local credential-store persistence.
+
+ Honors ``JARVIS_DATA_DIR`` when set (headless hosts / read-only
+ site-packages installs where ``PROJECT_ROOT/data`` cannot be created).
+ Otherwise defaults to :data:`DATA_DIR`, falling back to the per-user
+ app-data directory when that path turns out not to be writable. The
+ writability probe is cheap but still touches the filesystem, so it runs
+ once — lazily, on first use, never at import time — and the result is
+ cached until ``DATA_DIR`` itself changes (tests monkeypatch it directly).
+
+ Scoped to the local-file credential fallback only; every other consumer
+ of :data:`DATA_DIR` in this codebase keeps reading that constant
+ directly and is unaffected.
+ """
+ global _data_dir_cache
+ env_dir = os.environ.get("JARVIS_DATA_DIR")
+ if env_dir and env_dir.strip():
+ return Path(env_dir.strip())
+ with _data_dir_lock:
+ if _data_dir_cache is not None and _data_dir_cache[0] == DATA_DIR:
+ return _data_dir_cache[1]
+ try:
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
+ probe = DATA_DIR / f".write_probe_{os.getpid()}"
+ probe.write_text("", encoding="utf-8")
+ probe.unlink(missing_ok=True)
+ resolved = DATA_DIR
+ except OSError:
+ from jarvis.core.paths import user_data_dir
+
+ resolved = user_data_dir()
+ logging.getLogger(__name__).info(
+ "project data directory %s is not writable — using %s for "
+ "local credential storage instead",
+ DATA_DIR,
+ resolved,
+ )
+ _data_dir_cache = (DATA_DIR, resolved)
+ return resolved
+
def resolve_config_path() -> Path:
"""Return the active ``jarvis.toml`` path, honouring ``JARVIS_CONFIG``.
@@ -2406,6 +2455,14 @@ _KEYRING_BACKEND_READY: bool = False
_FILE_BACKEND_ACTIVE: bool = False
+# Serializes _FileCredStore's load-mutate-save cycle so two in-process
+# writers (e.g. a plugin connect + a concurrent API-key save) cannot race and
+# silently drop one of the two updates. Matches the config_writer lock
+# pattern. Cross-PROCESS locking is a separate, deferred concern — this only
+# protects concurrent callers within one Jarvis process.
+_FILE_CRED_STORE_LOCK = threading.Lock()
+
+
class _FileCredStore:
"""Minimal 0600 JSON credential store keyed by ``(service, username)``."""
@@ -2413,7 +2470,11 @@ class _FileCredStore:
self._explicit = path
def _file(self) -> Path:
- p = self._explicit if self._explicit is not None else (DATA_DIR / "credentials.json")
+ p = (
+ self._explicit
+ if self._explicit is not None
+ else (_resolve_writable_data_dir() / "credentials.json")
+ )
p.parent.mkdir(parents=True, exist_ok=True)
return p
@@ -2426,13 +2487,20 @@ class _FileCredStore:
def _save(self, data: dict[str, str]) -> None:
f = self._file()
- tmp = f.with_suffix(".tmp")
- tmp.write_text(json.dumps(data), encoding="utf-8")
+ # Per-process-unique temp name: two processes racing a write (no
+ # cross-process lock yet) must not clobber each other's in-flight tmp
+ # file before either reaches its atomic os.replace.
+ tmp = f.with_name(f"{f.name}.tmp.{os.getpid()}")
try:
- os.chmod(tmp, 0o600)
- except Exception: # noqa: BLE001 — chmod is a no-op on Windows
- pass
- os.replace(tmp, f)
+ tmp.write_text(json.dumps(data), encoding="utf-8")
+ try:
+ os.chmod(tmp, 0o600)
+ except Exception: # noqa: BLE001 — chmod is a no-op on Windows
+ pass
+ os.replace(tmp, f)
+ except OSError as exc:
+ tmp.unlink(missing_ok=True)
+ raise RuntimeError(f"failed to write credential store {f}: {exc}") from exc
@staticmethod
def _k(service: str, username: str) -> str:
@@ -2442,14 +2510,16 @@ class _FileCredStore:
return self._load().get(self._k(service, username))
def set(self, service: str, username: str, password: str) -> None:
- data = self._load()
- data[self._k(service, username)] = password
- self._save(data)
+ with _FILE_CRED_STORE_LOCK:
+ data = self._load()
+ data[self._k(service, username)] = password
+ self._save(data)
def delete(self, service: str, username: str) -> None:
- data = self._load()
- data.pop(self._k(service, username), None)
- self._save(data)
+ with _FILE_CRED_STORE_LOCK:
+ data = self._load()
+ data.pop(self._k(service, username), None)
+ self._save(data)
def _install_file_cred_backend(reason: str) -> bool:
@@ -2701,28 +2771,41 @@ def set_secret(key: str, value: str) -> bool:
def delete_secret(key: str) -> bool:
"""Remove a secret from both the OS keyring and local-file fallback.
- Deleting only the currently active backend can resurrect a stale fallback
- value on the next process start. The operation is intentionally idempotent:
- an already-absent key is a successful deletion.
+ Success requires that NO backend still holds the value — deleting only
+ the currently active backend can resurrect a stale fallback value on the
+ next process start. The operation is intentionally idempotent: an
+ already-absent key counts as a successful deletion.
+
+ Unlike ``get_secret``/``set_secret``, a failed OS-keyring delete does NOT
+ swap the process-global keyring backend to the file store. That retry
+ used to let a transient/locked-keyring failure masquerade as a
+ successful delete: the file copy (if any) was removed and ``True`` came
+ back, while the real OS-keyring entry survived untouched and reappeared
+ on the next boot. The ENV layer is read-only here and is never touched.
"""
_ensure_keyring_backend()
keyring_ok = False
try:
import keyring
+ from keyring.errors import PasswordDeleteError
- keyring.delete_password(KEYRING_SERVICE, key)
- keyring_ok = True
+ try:
+ keyring.delete_password(KEYRING_SERVICE, key)
+ keyring_ok = True
+ except PasswordDeleteError:
+ # Every backend we rely on raises this specifically when the
+ # entry is already absent (e.g. the Windows Credential Manager
+ # backend; the file-fallback backend's delete is idempotent and
+ # never raises at all) — "nothing to delete" is itself a success.
+ keyring_ok = True
except Exception: # noqa: BLE001
- # Locked/unusable OS keyring: degrade to the file store and retry, so a
- # file-stored credential is actually removed rather than left stale.
- if _install_file_cred_backend("keyring delete failed"):
- try:
- import keyring
-
- keyring.delete_password(KEYRING_SERVICE, key)
- keyring_ok = True
- except Exception: # noqa: BLE001, S110
- pass
+ # A genuine backend failure (locked Secret Service, transport
+ # error, ...). Deliberately do not retry via
+ # _install_file_cred_backend here: swapping the process-global
+ # keyring backend just because one delete failed would silently
+ # degrade every other credential read/write in this process while
+ # the real OS-keyring entry survives untouched.
+ keyring_ok = False
file_ok = False
try:
@@ -2732,7 +2815,7 @@ def delete_secret(key: str) -> bool:
file_ok = True
except Exception: # noqa: BLE001, S110
pass
- return keyring_ok or file_ok
+ return keyring_ok and file_ok
# ----------------------------------------------------------------------
diff --git a/jarvis/telephony/session.py b/jarvis/telephony/session.py
index d2b9111313..bc29629602 100644
--- a/jarvis/telephony/session.py
+++ b/jarvis/telephony/session.py
@@ -163,6 +163,11 @@ class TelephonyCallSession:
# Handle for the running discard timer task (if any).
self._pending_discard_task: asyncio.Task[None] | None = None
+ # Strong references for fire-and-forget bus.publish() tasks (see
+ # _publish_turn/_publish_end) so the event loop can't garbage-collect
+ # one mid-flight; each self-discards on completion.
+ self._pending_publish_tasks: set[asyncio.Task[None]] = set()
+
# -- public properties -------------------------------------------------
@property
@@ -612,14 +617,24 @@ class TelephonyCallSession:
try:
from .events import TelephonyCallTurn
- self._bus.publish(
- TelephonyCallTurn(
- call_sid=self.call_sid,
- transcript=transcript,
- response_text=response,
- outbound_frames=frames,
+ # bus.publish() is async — a bare un-awaited call just creates
+ # and drops the coroutine without ever running it. The turn loop
+ # is latency-sensitive and typed EventBus handlers are awaited
+ # uncapped, so fire-and-forget via create_task rather than
+ # inline-await; the task ref is kept so the loop can't GC it
+ # mid-flight.
+ task = asyncio.create_task(
+ self._bus.publish(
+ TelephonyCallTurn(
+ call_sid=self.call_sid,
+ transcript=transcript,
+ response_text=response,
+ outbound_frames=frames,
+ )
)
)
+ self._pending_publish_tasks.add(task)
+ task.add_done_callback(self._pending_publish_tasks.discard)
except Exception: # noqa: BLE001, S110 - bus errors never break a call
pass
@@ -629,15 +644,19 @@ class TelephonyCallSession:
try:
from .events import TelephonyCallEnded
- self._bus.publish(
- TelephonyCallEnded(
- call_sid=self.call_sid,
- status=self.status,
- duration_s=self.duration_s,
- turns=self._turns,
- reason=self._end_reason,
+ task = asyncio.create_task(
+ self._bus.publish(
+ TelephonyCallEnded(
+ call_sid=self.call_sid,
+ status=self.status,
+ duration_s=self.duration_s,
+ turns=self._turns,
+ reason=self._end_reason,
+ )
)
)
+ self._pending_publish_tasks.add(task)
+ task.add_done_callback(self._pending_publish_tasks.discard)
except Exception: # noqa: BLE001, S110 - bus errors never break a call
pass
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index f0ec615d19..c433994b8b 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -1937,7 +1937,10 @@ async def brain_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
# mirroring the codex branch (the CLI bills the Google subscription).
from jarvis.google_cli.auth_service import GoogleCliAuthService
- if not GoogleCliAuthService().status().connected:
+ def _antigravity_connected() -> bool:
+ return GoogleCliAuthService().status().connected
+
+ if not await asyncio.to_thread(_antigravity_connected):
raise HTTPException(
status_code=409,
detail=(
@@ -2410,6 +2413,7 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
),
)
+ voice_mode_write_ok = True
if body.persist:
try:
from jarvis.core.config_writer import set_realtime_provider
@@ -2426,6 +2430,7 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
set_voice_mode("realtime")
except Exception as exc: # noqa: BLE001 — best-effort, mirrors set_realtime_provider above
+ voice_mode_write_ok = False
log.warning("voice-mode persist failed after realtime switch: %s", exc)
cfg = _resolve_cfg(request)
@@ -2453,7 +2458,13 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
return {
"ok": True,
"active": body.provider,
- "persisted": body.persist,
+ # True only when persist was requested AND both writes (provider +
+ # voice mode) actually landed — previously this reported
+ # body.persist unconditionally even when the voice-mode write above
+ # failed and was only logged, so the UI showed "persisted" for a
+ # switch that silently left [voice].mode stale on disk.
+ "persisted": body.persist and voice_mode_write_ok,
+ "voice_mode_persisted": voice_mode_write_ok,
"restart_required": False,
}
@@ -2577,7 +2588,10 @@ async def jarvis_agent_switch(body: SwitchBody, request: Request) -> dict[str, A
# it is not in JARVIS_TO_WORKER_SLUG. Handle it explicitly: it can be backed by
# the ChatGPT subscription (OAuth, ``codex login``) OR an OpenAI API key.
if provider in _CODEX_SUBAGENT_SLUGS:
- codex_connected = CodexAuthService(_codex_binary_path(request)).status().connected
+ def _codex_connected() -> bool:
+ return CodexAuthService(_codex_binary_path(request)).status().connected
+
+ codex_connected = await asyncio.to_thread(_codex_connected)
has_key = bool(
cfg_mod.get_secret("codex_openai_api_key")
or cfg_mod.get_provider_secret("codex")
@@ -2626,7 +2640,10 @@ async def jarvis_agent_switch(body: SwitchBody, request: Request) -> dict[str, A
# Dual billing (mirror of codex): the Google subscription OAuth login OR
# a Gemini API key (per token). Either is enough to run the worker.
- antigravity_connected = GoogleCliAuthService().status().connected
+ def _antigravity_connected() -> bool:
+ return GoogleCliAuthService().status().connected
+
+ antigravity_connected = await asyncio.to_thread(_antigravity_connected)
antigravity_key = bool(
cfg_mod.get_secret("gemini_api_key", env_fallback="GEMINI_API_KEY")
)
diff --git a/jarvis/ui/web/telephony_routes.py b/jarvis/ui/web/telephony_routes.py
index b6f57f094e..72730d475a 100644
--- a/jarvis/ui/web/telephony_routes.py
+++ b/jarvis/ui/web/telephony_routes.py
@@ -26,10 +26,11 @@ are missing.
from __future__ import annotations
+import asyncio
import logging
import re
import time
-from typing import cast
+from typing import Any, cast
from fastapi import APIRouter, Request, Response, WebSocket, WebSocketDisconnect
from fastapi.responses import JSONResponse
@@ -124,6 +125,30 @@ def _tts_info(request: Request) -> tuple[str, str]:
return provider, voice
+def _apply_live_twilio_updates(request: Request, updates: dict[str, object]) -> None:
+ """Mutate the SHARED live config's twilio block in place.
+
+ ``post_config``/``post_credentials`` persist to ``jarvis.toml`` on disk,
+ but ``request.app.state.config`` (the same object ``WebServer`` holds as
+ ``self.cfg``, assigned once at boot) was never updated to match — so the
+ live voice webhook and media-socket handlers, which read
+ ``request.app.state.config`` directly, kept serving the STALE values
+ until a full app restart even though the write to disk succeeded.
+
+ Deliberately mutates fields on the EXISTING ``TwilioConfig`` instance
+ rather than reassigning ``request.app.state.config`` to a freshly loaded
+ one: ``WebServer`` holds its own reference to that same object, and
+ swapping it here would only create a NEW split brain between the two.
+ """
+ cfg = _resolve_cfg(request)
+ twilio = getattr(getattr(cfg, "integrations", None), "twilio", None)
+ if twilio is None:
+ return
+ for field, value in updates.items():
+ if hasattr(twilio, field):
+ setattr(twilio, field, value)
+
+
def _config_payload(twilio, *, auth_token_set: bool) -> dict[str, object]:
return {
"enabled": bool(getattr(twilio, "enabled", False)),
@@ -231,6 +256,10 @@ async def post_config(request: Request, body: ConfigUpdate) -> JSONResponse:
except Exception as exc: # noqa: BLE001
log.warning("telephony config write failed: %s", exc)
return JSONResponse({"error": f"config write failed: {exc}"}, status_code=409)
+ # The disk write succeeded — mirror it onto the live shared config so
+ # the webhook / media-socket handlers see it immediately (Bug: config
+ # split-brain, see _apply_live_twilio_updates).
+ _apply_live_twilio_updates(request, updates)
# Re-read so the response reflects the freshly persisted values.
try:
@@ -248,23 +277,49 @@ class CredentialsUpdate(BaseModel):
@router.post("/credentials")
async def post_credentials(request: Request, body: CredentialsUpdate) -> JSONResponse:
+ # Tracked so a partial commit (one half saved, the other failed) can be
+ # reported honestly instead of a bare 409 that hides the half that DID
+ # succeed. None = "not requested in this call".
+ token_saved: bool | None = None
+ sid_saved: bool | None = None
+
if body.auth_token is not None and body.auth_token.strip():
- ok = set_secret(_AUTH_TOKEN_KEY, body.auth_token.strip())
- if not ok:
+ token_saved = set_secret(_AUTH_TOKEN_KEY, body.auth_token.strip())
+ if not token_saved:
return JSONResponse(
- {"error": "could not store auth token in the credential manager"},
+ {
+ "error": "could not store auth token in the credential manager",
+ "token_saved": False,
+ "sid_saved": sid_saved,
+ },
status_code=409,
)
if body.account_sid is not None and body.account_sid.strip():
sid = body.account_sid.strip()
if not sid.startswith("AC"):
- return JSONResponse({"error": "account_sid must start with 'AC'"}, status_code=422)
+ return JSONResponse(
+ {
+ "error": "account_sid must start with 'AC'",
+ "token_saved": token_saved,
+ "sid_saved": False,
+ },
+ status_code=422,
+ )
try:
from jarvis.core.config_writer import set_telephony_config
set_telephony_config({"account_sid": sid})
except Exception as exc: # noqa: BLE001
- return JSONResponse({"error": f"config write failed: {exc}"}, status_code=409)
+ return JSONResponse(
+ {
+ "error": f"config write failed: {exc}",
+ "token_saved": token_saved,
+ "sid_saved": False,
+ },
+ status_code=409,
+ )
+ sid_saved = True
+ _apply_live_twilio_updates(request, {"account_sid": sid})
twilio = _twilio_cfg(request)
try:
@@ -275,7 +330,14 @@ async def post_credentials(request: Request, body: CredentialsUpdate) -> JSONRes
sid_now = getattr(twilio, "account_sid", "")
phone_now = getattr(twilio, "phone_number", "")
configured = bool(sid_now and phone_now and _auth_token())
- return JSONResponse({"ok": True, "configured": configured})
+ return JSONResponse(
+ {
+ "ok": True,
+ "configured": configured,
+ "token_saved": token_saved,
+ "sid_saved": sid_saved,
+ }
+ )
@router.post("/test")
@@ -672,6 +734,15 @@ async def media_socket(ws: WebSocket) -> None:
data = await ws.receive_json()
except WebSocketDisconnect:
break
+ except RuntimeError:
+ # The socket is gone — e.g. starlette raises
+ # RuntimeError('WebSocket is not connected ...') after an
+ # unclean client disconnect instead of WebSocketDisconnect.
+ # `continue` here would re-call receive_json on the dead
+ # socket forever (AP-20 log-storm); treat it as a disconnect
+ # and leave the loop. Cleanup below is unconditional (finally).
+ log.warning("telephony: media socket receive aborted for %s", call_sid)
+ break
event = data.get("event")
if event == "connected":
@@ -879,20 +950,33 @@ def _build_session(
)
+# bus.publish() is async (jarvis/core/bus.py); a bare un-awaited call just
+# creates-and-drops a coroutine without ever running it. Fire-and-forget via
+# asyncio.create_task instead, keeping a strong reference here so the event
+# loop can't garbage-collect the task mid-flight (each self-discards on
+# completion) — the same pattern used for FileSaved publishes in
+# jarvis/awareness/probes/filesystem.py.
+_PENDING_PUBLISH_TASKS: set[asyncio.Task[Any]] = set()
+
+
def _publish_start(bus, call_sid, from_number, to_number, stream_sid) -> None:
if bus is None:
return
try:
from jarvis.telephony.events import TelephonyCallStarted
- bus.publish(
- TelephonyCallStarted(
- call_sid=call_sid,
- from_number=from_number,
- to_number=to_number,
- stream_sid=stream_sid,
+ task = asyncio.create_task(
+ bus.publish(
+ TelephonyCallStarted(
+ call_sid=call_sid,
+ from_number=from_number,
+ to_number=to_number,
+ stream_sid=stream_sid,
+ )
)
)
+ _PENDING_PUBLISH_TASKS.add(task)
+ task.add_done_callback(_PENDING_PUBLISH_TASKS.discard)
except Exception: # noqa: BLE001, S110 - bus publish is best-effort
pass
diff --git a/tests/unit/core/test_headless_keyring_fallback.py b/tests/unit/core/test_headless_keyring_fallback.py
index fe40cc0da5..e1ea375aeb 100644
--- a/tests/unit/core/test_headless_keyring_fallback.py
+++ b/tests/unit/core/test_headless_keyring_fallback.py
@@ -7,6 +7,10 @@ VPS downloader can paste a key in the UI and have it persist.
from __future__ import annotations
import sys
+import threading
+from pathlib import Path
+
+import pytest
import jarvis.core.config as cfg
@@ -27,6 +31,76 @@ def test_file_cred_store_is_0600_on_posix(tmp_path):
assert (p.stat().st_mode & 0o777) == 0o600
+def test_file_cred_store_concurrent_writes_no_lost_update(tmp_path):
+ """Concurrent set() calls on the SAME store file must not race and drop
+ one of the two updates (bare read-modify-write with no lock did exactly
+ that)."""
+ store = cfg._FileCredStore(path=tmp_path / "creds.json")
+ n = 20
+ barrier = threading.Barrier(n)
+
+ def _writer(i: int) -> None:
+ barrier.wait()
+ store.set("svc", f"key{i}", f"val{i}")
+
+ threads = [threading.Thread(target=_writer, args=(i,)) for i in range(n)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+
+ for i in range(n):
+ assert store.get("svc", f"key{i}") == f"val{i}"
+
+
+def test_file_cred_store_save_failure_raises_clear_error(monkeypatch, tmp_path):
+ store = cfg._FileCredStore(path=tmp_path / "creds.json")
+
+ def _boom(self: Path, *args: object, **kwargs: object) -> None:
+ raise OSError("disk full (simulated)")
+
+ monkeypatch.setattr(Path, "write_text", _boom)
+
+ with pytest.raises(RuntimeError, match="failed to write credential store"):
+ store.set("svc", "k", "v")
+
+
+def test_resolve_writable_data_dir_honors_env_override(monkeypatch, tmp_path):
+ override_dir = tmp_path / "custom_data"
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(override_dir))
+ monkeypatch.setattr(cfg, "_data_dir_cache", None, raising=False)
+
+ assert cfg._resolve_writable_data_dir() == override_dir
+
+
+def test_resolve_writable_data_dir_default_unchanged_when_writable(monkeypatch, tmp_path):
+ writable_dir = tmp_path / "data"
+ monkeypatch.setattr(cfg, "DATA_DIR", writable_dir)
+ monkeypatch.setattr(cfg, "_data_dir_cache", None, raising=False)
+
+ assert cfg._resolve_writable_data_dir() == writable_dir
+ assert writable_dir.exists()
+
+
+def test_resolve_writable_data_dir_falls_back_when_project_dir_unwritable(monkeypatch, tmp_path):
+ unwritable_dir = tmp_path / "readonly_data"
+ fallback_dir = tmp_path / "user_data_dir"
+ monkeypatch.setattr(cfg, "DATA_DIR", unwritable_dir)
+ monkeypatch.setattr(cfg, "_data_dir_cache", None, raising=False)
+ monkeypatch.setattr("jarvis.core.paths.user_data_dir", lambda: fallback_dir)
+
+ original_write_text = Path.write_text
+
+ def _fail_on_probe(self: Path, *args: object, **kwargs: object) -> int:
+ if self.name.startswith(".write_probe_"):
+ raise OSError("read-only filesystem (simulated)")
+ return original_write_text(self, *args, **kwargs) # type: ignore[arg-type]
+
+ monkeypatch.setattr(Path, "write_text", _fail_on_probe)
+
+ assert cfg._resolve_writable_data_dir() == fallback_dir
+
+
def test_ensure_keyring_backend_registers_file_store_when_os_keyring_dead(monkeypatch, tmp_path):
import keyring
from keyring.backends import fail
@@ -62,3 +136,24 @@ def test_ensure_keyring_backend_leaves_working_os_keyring_untouched(monkeypatch)
cfg._ensure_keyring_backend()
assert "kr" not in called, "a working OS keyring must NOT be replaced by the file fallback"
+
+
+def test_delete_secret_succeeds_on_file_backend_only_host(monkeypatch, tmp_path):
+ """No OS keyring at all (pure headless VPS): _ensure_keyring_backend installs
+ the file store as the active backend, so a delete through it must succeed —
+ the honest-failure behavior for a genuinely broken/locked OS keyring must
+ not regress this already-working headless path."""
+ import keyring
+ from keyring.backends import fail
+
+ original = keyring.get_keyring()
+ monkeypatch.setattr(keyring, "get_keyring", lambda: fail.Keyring())
+ monkeypatch.setattr(cfg, "DATA_DIR", tmp_path)
+ monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", False, raising=False)
+ monkeypatch.setattr(cfg, "_FILE_BACKEND_ACTIVE", False, raising=False)
+ try:
+ assert cfg.set_secret("headless_del_key", "v1") is True
+ assert cfg.delete_secret("headless_del_key") is True
+ assert cfg.get_secret("headless_del_key") is None
+ finally:
+ keyring.set_keyring(original)
diff --git a/tests/unit/core/test_secret_locked_keyring.py b/tests/unit/core/test_secret_locked_keyring.py
index a03a7bfc3b..d48e27bfa6 100644
--- a/tests/unit/core/test_secret_locked_keyring.py
+++ b/tests/unit/core/test_secret_locked_keyring.py
@@ -73,12 +73,45 @@ def test_get_secret_reads_file_store_on_locked_keyring(locked_os_keyring) -> Non
assert c.get_secret("prior_key") == "prior-val"
-def test_delete_secret_degrades_to_file_store_on_locked_keyring(locked_os_keyring) -> None:
+def test_delete_secret_reports_failure_on_locked_keyring_without_swapping_backend(
+ locked_os_keyring,
+) -> None:
+ """A locked (not merely absent) OS keyring cannot confirm the entry is
+ gone there, so delete_secret must report failure honestly instead of
+ swapping the process-global backend to the file store and claiming
+ success — a real OS-keyring-held value would otherwise survive
+ untouched and reappear once the lock clears (the resurrection bug this
+ fix closes). The file-store copy (if any) is still removed so a
+ file-only value never lingers, but the overall result is False because
+ the OS-keyring side is unconfirmed.
+ """
store = c._FileCredStore()
store.set(c.KEYRING_SERVICE, "del_prior", "y")
- # Old behaviour: keyring.delete_password raises -> returns False, value stays.
- assert c.delete_secret("del_prior") is True
- assert c.get_secret("del_prior") is None
+ original_keyring = keyring.get_keyring()
+
+ assert c.delete_secret("del_prior") is False
+ # The file copy is gone...
+ assert c._FileCredStore().get(c.KEYRING_SERVICE, "del_prior") is None
+ # ...but the failed delete must NOT have swapped the active backend.
+ assert keyring.get_keyring() is original_keyring
+ assert c._FILE_BACKEND_ACTIVE is False
+
+
+def test_delete_secret_treats_already_absent_as_success(monkeypatch, tmp_path) -> None:
+ """PasswordDeleteError raised because the entry is already gone (not a
+ real backend failure) must count as a successful delete."""
+ from keyring.errors import PasswordDeleteError
+
+ monkeypatch.setattr(c, "DATA_DIR", tmp_path)
+ monkeypatch.setattr(c, "_KEYRING_BACKEND_READY", True)
+ monkeypatch.setattr(c, "_FILE_BACKEND_ACTIVE", False)
+
+ def _raise_missing(*_args: object) -> None:
+ raise PasswordDeleteError("not found")
+
+ monkeypatch.setattr(keyring, "delete_password", _raise_missing)
+
+ assert c.delete_secret("never_stored_key") is True
def test_delete_secret_removes_stale_file_value_when_os_delete_succeeds(
diff --git a/tests/unit/telephony/test_routes.py b/tests/unit/telephony/test_routes.py
index 6140caf7c5..538c311ada 100644
--- a/tests/unit/telephony/test_routes.py
+++ b/tests/unit/telephony/test_routes.py
@@ -171,6 +171,78 @@ def test_credentials_rejects_bad_sid(app, secret_store):
assert r.status_code == 422
+def test_config_post_updates_live_shared_config_without_reload(
+ app, secret_store, fake_cfg, monkeypatch
+):
+ """Bug: POST /config wrote to disk but request.app.state.config (the SAME
+ object WebServer holds) was never updated, so the live webhook/media
+ socket kept serving stale values until a restart."""
+
+ def fake_writer(values, **kw):
+ for k, v in values.items():
+ setattr(fake_cfg.integrations.twilio, k, v)
+
+ monkeypatch.setattr("jarvis.core.config_writer.set_telephony_config", fake_writer)
+ monkeypatch.setattr(routes.cfg_mod, "load_config", lambda *a, **k: fake_cfg)
+
+ live_twilio_before = app.state.config.integrations.twilio
+ with TestClient(app) as client:
+ r = client.post(
+ "/api/telephony/config",
+ json={"greeting": "Servus!", "max_call_seconds": 120},
+ )
+ assert r.status_code == 200
+ # The SAME object app.state.config points at must reflect the update —
+ # no reassignment, no reload needed.
+ assert app.state.config.integrations.twilio is live_twilio_before
+ assert app.state.config.integrations.twilio.greeting == "Servus!"
+ assert app.state.config.integrations.twilio.max_call_seconds == 120
+
+
+def test_credentials_post_updates_live_shared_config_sid(
+ app, secret_store, fake_cfg, monkeypatch
+):
+ monkeypatch.setattr(
+ "jarvis.core.config_writer.set_telephony_config",
+ lambda values, **kw: setattr(
+ fake_cfg.integrations.twilio, "account_sid", values["account_sid"]
+ ),
+ )
+ monkeypatch.setattr(routes.cfg_mod, "load_config", lambda *a, **k: fake_cfg)
+
+ with TestClient(app) as client:
+ r = client.post(
+ "/api/telephony/credentials",
+ json={"account_sid": "AC" + "e" * 32},
+ )
+ assert r.status_code == 200
+ assert app.state.config.integrations.twilio.account_sid == "AC" + "e" * 32
+
+
+def test_credentials_reports_partial_commit_when_sid_write_fails(
+ app, secret_store, fake_cfg, monkeypatch
+):
+ """Token save succeeds, SID write fails: the response must say so
+ honestly (token_saved=True) instead of an opaque bare 409."""
+
+ def _boom(values, **kw):
+ raise RuntimeError("disk full (simulated)")
+
+ monkeypatch.setattr("jarvis.core.config_writer.set_telephony_config", _boom)
+
+ with TestClient(app) as client:
+ r = client.post(
+ "/api/telephony/credentials",
+ json={"account_sid": "AC" + "d" * 32, "auth_token": "freshtoken"},
+ )
+ assert r.status_code == 409
+ body = r.json()
+ assert body["token_saved"] is True
+ assert body["sid_saved"] is False
+ # The token really did land in the credential store despite the SID error.
+ assert secret_store["twilio_auth_token"] == "freshtoken"
+
+
def test_calls_endpoint_returns_ring_buffer(app, secret_store):
from jarvis.telephony.status import CallRecord
@@ -355,3 +427,34 @@ def test_voice_webhook_outbound_branch_returns_opening(app, secret_store, fake_c
assert "wss://jarvis.example.com/api/telephony/media" in r.text
# A per-call secret was minted and registered for the outbound call too.
assert app.state.telephony_manager.peek_pending("CAOUT9") is not None
+
+
+class _RecordingBus:
+ """Records every published event. ``publish`` is async, mirroring
+ jarvis.core.bus.EventBus — a bare un-awaited call would silently drop
+ the event."""
+
+ def __init__(self) -> None:
+ self.events: list[object] = []
+
+ async def publish(self, event: object) -> None:
+ self.events.append(event)
+
+
+async def test_publish_start_delivers_event_via_async_bus() -> None:
+ import asyncio
+
+ from jarvis.telephony.events import TelephonyCallStarted
+
+ bus = _RecordingBus()
+ routes._publish_start(bus, "CA1", "+491", "+492", "MZ1")
+
+ pending = list(routes._PENDING_PUBLISH_TASKS)
+ if pending:
+ await asyncio.gather(*pending)
+
+ assert len(bus.events) == 1
+ event = bus.events[0]
+ assert isinstance(event, TelephonyCallStarted)
+ assert event.call_sid == "CA1"
+ assert event.stream_sid == "MZ1"
diff --git a/tests/unit/telephony/test_session.py b/tests/unit/telephony/test_session.py
index 9ccd262c2b..3f2a27c345 100644
--- a/tests/unit/telephony/test_session.py
+++ b/tests/unit/telephony/test_session.py
@@ -188,6 +188,49 @@ def test_time_cap_detection():
assert session.check_time_cap() is True
+class _FakeBus:
+ """Records every published event. ``publish`` is async, mirroring
+ jarvis.core.bus.EventBus — a bare un-awaited call would silently drop
+ every telephony event."""
+
+ def __init__(self) -> None:
+ self.events: list[object] = []
+
+ async def publish(self, event: object) -> None:
+ self.events.append(event)
+
+
+async def _drain_pending_publishes(session: TelephonyCallSession) -> None:
+ """Fire-and-forget publish tasks run on the next loop iterations -- wait
+ for them so the test can assert on delivered events."""
+ import asyncio
+
+ pending = list(session._pending_publish_tasks)
+ if pending:
+ await asyncio.gather(*pending)
+
+
+async def test_turn_and_end_events_reach_the_bus():
+ from jarvis.telephony.events import TelephonyCallEnded, TelephonyCallTurn
+
+ sink = _Sink()
+ bus = _FakeBus()
+ session = _make_session(sink, bus=bus)
+
+ await _drive_one_utterance(session)
+ await _drain_pending_publishes(session)
+ await session.end(reason="test", status=CALL_COMPLETED)
+ await _drain_pending_publishes(session)
+
+ turn_events = [e for e in bus.events if isinstance(e, TelephonyCallTurn)]
+ end_events = [e for e in bus.events if isinstance(e, TelephonyCallEnded)]
+ assert len(turn_events) == 1
+ assert turn_events[0].call_sid == "CA1"
+ assert len(end_events) == 1
+ assert end_events[0].call_sid == "CA1"
+ assert end_events[0].reason == "test"
+
+
async def test_brain_end_call_sentinel_ends_call_after_speaking():
sink = _Sink()
brain = FakeBrain("Auf Wiedersehen, Ruben. [[END_CALL]]")
diff --git a/tests/unit/web/test_realtime_provider_category.py b/tests/unit/web/test_realtime_provider_category.py
index a5186c3624..cccd6f719c 100644
--- a/tests/unit/web/test_realtime_provider_category.py
+++ b/tests/unit/web/test_realtime_provider_category.py
@@ -138,6 +138,30 @@ def test_realtime_switch_sets_voice_mode(monkeypatch):
assert app.state.config.voice.mode == "realtime"
+def test_realtime_switch_reports_voice_mode_not_persisted_on_write_failure(monkeypatch):
+ """Bug: the [voice].mode write failure was only logged, but the response
+ still reported persisted=True unconditionally — the UI showed "saved"
+ for a switch that silently left [voice].mode stale on disk."""
+ monkeypatch.setattr(cfg_mod, "get_secret", _only_openai_key)
+ monkeypatch.setattr(config_writer, "set_realtime_provider", lambda name, **kw: None)
+
+ def _boom(mode, **kw):
+ raise RuntimeError("disk full (simulated)")
+
+ monkeypatch.setattr(config_writer, "set_voice_mode", _boom)
+
+ app = _app()
+ client = TestClient(app)
+ resp = client.post(
+ "/api/realtime/switch", json={"provider": "openai-realtime", "persist": True}
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["ok"] is True
+ assert body["persisted"] is False
+ assert body["voice_mode_persisted"] is False
+
+
def test_realtime_switch_without_key_is_409(monkeypatch):
monkeypatch.setattr(cfg_mod, "get_secret", lambda *a, **kw: None)
client = TestClient(_app())