Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(agentic-ide): stop two panes of one account racing on its config
Ruben Lütke2ab45e674ecb
diff --git a/jarvis/agent_config_parity.py b/jarvis/agent_config_parity.pyindex b2fca33833..dbdb62bdeb 100644--- a/jarvis/agent_config_parity.py+++ b/jarvis/agent_config_parity.py@@ -68,6 +68,7 @@ import jsonimport osimport shutilimport sys+import threadingfrom dataclasses import dataclass, fieldfrom hashlib import sha256from pathlib import Path@@ -92,6 +93,41 @@ STATE_FILE = "jarvis-shared-setup.json"#: beside it rather than deleted — see :func:`_supersede`.SUPERSEDED_SUFFIX = ".jarvis-superseded"+#: One lock per account directory. See :func:`setup_lock`.+_LOCKS: dict[str, threading.RLock] = {}+_LOCKS_GUARD = threading.Lock()+++def setup_lock(config_dir: Path) -> threading.RLock:+ """The lock every writer into ONE account's config dir must hold.++ Panes attach CONCURRENTLY — a restored workspace re-attaches all of them at+ once, deliberately, so that eight agents do not start one after the other.+ Several of them can therefore prepare the same account's directory in+ different threads at the same moment, and two of the things that happen+ there are read-modify-write cycles on the SAME file: Claude Code's+ ``.claude.json`` receives the folder's trust entry (via+ :mod:`jarvis.workspace.trust`) and the user's MCP servers (via+ :func:`ensure_parity`). Unserialized, the later write is built on a document+ read before the earlier one landed, and it silently drops it — a lost trust+ entry is a dialog the user has to click, a lost merge is a pane without its+ connectors.++ Re-entrant on purpose: the registry holds this across BOTH steps, and the+ parity run inside it takes the same lock again on the same thread.++ Per directory rather than global, so two accounts still prepare in parallel;+ the map is bounded by how many accounts exist (a handful, capped at+ :data:`jarvis.agent_accounts.MAX_ACCOUNTS_PER_PLATFORM`).+ """+ key = os.path.normcase(str(config_dir))+ with _LOCKS_GUARD:+ lock = _LOCKS.get(key)+ if lock is None:+ lock = threading.RLock()+ _LOCKS[key] = lock+ return lock+@dataclass(frozen=True, slots=True)class Shared:@@ -628,14 +664,34 @@ def ensure_parity(platform: Platform, account_id: str | None) -> ParityReport:logger.warning("Agent setup: {} is not usable: {}", account.config_dir, exc)return ParityReport(redirected=True, skipped=((str(account.config_dir), str(exc)),))- state = _read_state(account.config_dir)+ with setup_lock(account.config_dir):+ shared, skipped = _provision(platform, native, account.config_dir)++ fresh = {name: how for name, how in shared.items() if how != "current"}+ if fresh:+ logger.info(+ "Agent setup: {!r} now shares your own {} setup ({})",+ account.label,+ platform,+ ", ".join(f"{name} [{how}]" for name, how in fresh.items()),+ )+ for name, why in skipped:+ logger.info("Agent setup: {} stayed the account's own — {}", name, why)+ return ParityReport(shared=shared, skipped=tuple(skipped), redirected=True)+++def _provision(+ platform: Platform, native: Path, config_dir: Path+) -> tuple[dict[str, str], list[tuple[str, str]]]:+ """Share every allowlisted entry into ``config_dir``. Caller holds its lock."""+ state = _read_state(config_dir)before = dict(state)shared: dict[str, str] = {}skipped: list[tuple[str, str]] = []for entry in USER_SETUP.get(platform, ()):source = native / entry.name- target = account.config_dir / entry.name+ target = config_dir / entry.nametry:if entry.kind == "dir":if not source.is_dir():@@ -659,7 +715,7 @@ def ensure_parity(platform: Platform, account_id: str | None) -> ParityReport:for merged in MERGED_KEYS.get(platform, ()):source = native / merged.name- target = account.config_dir / merged.name+ target = config_dir / merged.namelabel = f"{merged.name}#{merged.key}"try:how, why = _merge_key(source, target, merged.key, state_key=label, state=state)@@ -671,19 +727,8 @@ def ensure_parity(platform: Platform, account_id: str | None) -> ParityReport:skipped.append((label, why))if state != before:- _write_state(account.config_dir, state)-- fresh = {name: how for name, how in shared.items() if how != "current"}- if fresh:- logger.info(- "Agent setup: {!r} now shares your own {} setup ({})",- account.label,- platform,- ", ".join(f"{name} [{how}]" for name, how in fresh.items()),- )- for name, why in skipped:- logger.info("Agent setup: {} stayed the account's own — {}", name, why)- return ParityReport(shared=shared, skipped=tuple(skipped), redirected=True)+ _write_state(config_dir, state)+ return shared, skipped__all__ = [@@ -696,4 +741,5 @@ __all__ = ["ParityReport","Shared","ensure_parity",+ "setup_lock",]diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex c3a385e084..8d81747108 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -1633,11 +1633,26 @@ class Registry:pane on an added subscription must open as the same session the user'sown terminal opens (:func:`_spawn_env`), and it must not stop on a "doyou trust this directory?" dialog on the way there.++ Both under ONE lock on the account's directory, because panes attach+ concurrently: a restored workspace re-attaches all of them at once, and+ the two steps below are read-modify-write cycles on the same file — the+ trust entry and the user's MCP servers both live in Claude Code's+ ``.claude.json``. Unserialized, the second write is built on a document+ read before the first one landed and drops it silently."""- self._pre_trust(term, folder)- return _spawn_env(term)+ home = _redirected_home(term)+ if home is None:+ # Nothing was redirected: this pane already inherits the machine's+ # own configuration, which is exactly what a terminal does.+ return None+ from jarvis import agent_config_parity- def _pre_trust(self, term: Terminal, folder: str) -> None:+ with agent_config_parity.setup_lock(home):+ self._pre_trust(term, folder, home)+ return _spawn_env(term)++ def _pre_trust(self, term: Terminal, folder: str, home: Path) -> None:"""Mark this folder trusted in the config dir THIS pane will run from.The workspace open already seeded the machine's own config, which covers@@ -1647,11 +1662,8 @@ class Registry:an agent that never starts. Once per folder and account per process.Never raises: an unseeded pane costs one click, a failed spawn costs the- pane.+ pane. Caller holds that directory's setup lock."""- home = _redirected_home(term)- if home is None:- returnkey = (os.path.normcase(folder), os.path.normcase(str(home)))if key in self._pre_trusted:returndiff --git a/tests/unit/agentic_ide/test_account_spawn.py b/tests/unit/agentic_ide/test_account_spawn.pyindex c24c06ca19..4735c0bf56 100644--- a/tests/unit/agentic_ide/test_account_spawn.py+++ b/tests/unit/agentic_ide/test_account_spawn.py@@ -339,6 +339,41 @@ async def test_a_pane_pre_trusts_the_folder_in_its_own_account_directory(assert len([call for call in seen if call[2]]) == 1+async def test_the_trust_seeding_and_the_setup_run_under_one_lock(+ registry: Registry, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Both write Claude Code's .claude.json, and panes attach concurrently.++ Held apart, the second read-modify-write is built on a document read before+ the first one landed and drops it — a lost trust entry is a dialog the user+ has to click, a lost merge is a pane without its connectors.+ """+ from jarvis import agent_config_parity+ from jarvis.workspace import trust++ real_lock = agent_config_parity.setup_lock+ events: list[str] = []++ def _tracking_lock(path: Path) -> object:+ events.append("lock")+ return real_lock(path)++ def _record(_root: Path, _agents: list[str], **kwargs: object) -> list[object]:+ # The workspace open seeds the machine's own config; only the per-account+ # seeding is the one that has to happen under the lock.+ events.append("trust:account" if kwargs.get("config_dirs") else "trust:machine")+ return []++ monkeypatch.setattr(agent_config_parity, "setup_lock", _tracking_lock)+ monkeypatch.setattr(trust, "ensure_trusted", _record)+ second = agent_accounts.create_account("claude", "Second seat")+ await registry.start(str(tmp_path), [{"agent": "claude", "account": second.id}])+ await _attach(registry, registry.session.terminals[0].name)++ assert "trust:account" in events+ assert events.index("lock") < events.index("trust:account")++async def test_a_pane_on_the_builtin_login_is_not_pre_trusted_twice(registry: Registry, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/tests/unit/test_agent_config_parity.py b/tests/unit/test_agent_config_parity.pyindex 69db7a1851..7665540234 100644--- a/tests/unit/test_agent_config_parity.py+++ b/tests/unit/test_agent_config_parity.py@@ -388,6 +388,57 @@ def test_a_dangling_link_is_repaired_rather_than_inherited(assert (native / "skills").is_dir()+def test_panes_provisioning_one_account_at_once_do_not_race(native: Path) -> None:+ """Panes attach CONCURRENTLY — a restored workspace re-attaches all of them.++ Eight threads on one account directory, doing the very thing eight panes do.+ Every one must come back with the same answer and the directory must end up+ whole, rather than two of them half-writing the same file.+ """+ import threading++ account = _account()+ results: list[dict[str, str]] = []+ errors: list[BaseException] = []+ start = threading.Barrier(8)++ def _provision() -> None:+ try:+ start.wait(timeout=5)+ results.append(ensure_parity("claude", account.id).shared)+ except BaseException as exc: # noqa: BLE001 - the assertion is below+ errors.append(exc)++ threads = [threading.Thread(target=_provision) for _ in range(8)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(timeout=20)++ assert not errors+ assert len(results) == 8+ # Same entries every time — no thread saw a half-provisioned directory.+ assert {tuple(sorted(r)) for r in results} == {tuple(sorted(results[0]))}+ assert (account.config_dir / "skills" / "git-rescue" / "SKILL.md").is_file()+ assert json.loads(+ (account.config_dir / agent_config_parity.STATE_FILE).read_text(encoding="utf-8")+ )["version"] == agent_config_parity.STATE_VERSION+++def test_the_setup_lock_is_one_per_account_and_re_entrant(tmp_path: Path) -> None:+ """One account serializes; two accounts still prepare in parallel.++ Re-entrant because the registry holds it across the trust seeding AND the+ parity run, and the parity run takes it again on the same thread.+ """+ first, second = tmp_path / "one", tmp_path / "two"+ assert agent_config_parity.setup_lock(first) is agent_config_parity.setup_lock(first)+ assert agent_config_parity.setup_lock(first) is not agent_config_parity.setup_lock(second)+ lock = agent_config_parity.setup_lock(first)+ with lock, lock:+ pass # a plain Lock would deadlock here++def test_it_never_raises_on_a_host_that_refuses_everything(native: Path, monkeypatch: pytest.MonkeyPatch) -> None: