Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(runtime): register Claude processes off the event loop, and keep only live ones (#2512)
Call Whiteb1e1a7b767ed
diff --git a/modules/agents/claude_process_reaper.py b/modules/agents/claude_process_reaper.pyindex 4ff10ffb5..c60098bca 100644--- a/modules/agents/claude_process_reaper.py+++ b/modules/agents/claude_process_reaper.py@@ -8,7 +8,8 @@ import loggingimport osimport signalimport subprocess-from dataclasses import dataclass+from concurrent.futures import Future, ThreadPoolExecutor+from dataclasses import dataclass, replacefrom pathlib import PathKILL_SIGNAL = getattr(signal, "SIGKILL", signal.SIGTERM)@@ -17,6 +18,11 @@ AVIBE_CLAUDE_PROCESS_OWNER_ENV = "AVIBE_CLAUDE_PROCESS_OWNER"AVIBE_CLAUDE_SESSION_OWNER = "session"AVIBE_CLAUDE_AUTH_OWNER = "auth"CLAUDE_PROCESS_REGISTRY_NAME = "claude_processes.json"+# This process's registry writer. Registering is called on the service's+# event loop, so reading the process's start time (`ps`) and rewriting the file+# run here instead, one write at a time; the registry's file lock orders them+# against the other processes that register (the Web UI's auth and probes).+_REGISTRY_WRITER = ThreadPoolExecutor(max_workers=1, thread_name_prefix="claude-process-registry")@dataclass(frozen=True)@@ -186,39 +192,71 @@ def register_claude_owned_process(native_session_id: str | None = None,owner: str = AVIBE_CLAUDE_SESSION_OWNER,runtime_dir: Path | None = None,-) -> None:+) -> Future[None] | None:+ """Record the client's Claude CLI process as this service's, on the registry's writer.++ Returns the pending write, or None when there is no process to record.+ """+pid = get_claude_client_pid(client)if not pid or os.name == "nt":- return- path = _registry_path(runtime_dir)- records = [record for record in _load_owned_process_registry(runtime_dir) if record.pid != pid]- records.append(+ return None+ return _REGISTRY_WRITER.submit(+ _record_owned_process,+ _registry_path(runtime_dir).parent,ClaudeOwnedProcess(pid=pid,native_session_id=str(native_session_id) if native_session_id else None,owner=owner,- started_at=_process_start_time(pid),- )+ ),)- payload = {- "processes": [- {- "pid": record.pid,- "native_session_id": record.native_session_id,- "owner": record.owner,- "started_at": record.started_at,- }- for record in records- ]- }+++def _record_owned_process(runtime_dir: Path, owned: ClaudeOwnedProcess) -> None:+ """Rewrite the registry with ``owned``, without the records of processes that have exited."""++ from storage.lock import MigrationFileLock++ path = _registry_path(runtime_dir)+ started_at = _process_start_time(owned.pid)try:path.parent.mkdir(parents=True, exist_ok=True)- tmp_path = path.with_suffix(path.suffix + ".tmp")- tmp_path.write_text(json.dumps(payload, separators=(",", ":")) + "\n", encoding="utf-8")- tmp_path.replace(path)+ with MigrationFileLock(path.with_suffix(path.suffix + ".lock")):+ records = [+ existing+ for existing in _load_owned_process_registry(runtime_dir)+ if existing.pid != owned.pid and _pid_exists(existing.pid)+ ]+ records.append(replace(owned, started_at=started_at))+ payload = {+ "processes": [+ {+ "pid": record.pid,+ "native_session_id": record.native_session_id,+ "owner": record.owner,+ "started_at": record.started_at,+ }+ for record in records+ ]+ }+ tmp_path = path.with_suffix(path.suffix + ".tmp")+ tmp_path.write_text(json.dumps(payload, separators=(",", ":")) + "\n", encoding="utf-8")+ tmp_path.replace(path)except Exception:- logger = logging.getLogger(__name__)- logger.debug("Failed to persist Claude process registry", exc_info=True)+ # Nobody reads the write's future: this log is the only trace of a failure.+ logging.getLogger(__name__).warning("Failed to persist Claude process registry", exc_info=True)+++def _pid_exists(pid: int) -> bool:+ try:+ os.kill(pid, 0)+ except (ProcessLookupError, OverflowError, ValueError):+ # OverflowError and ValueError: a recorded pid no process can have.+ return False+ except OSError:+ # Another user's process: it exists.+ return True+ return Truedef _run_ps() -> str:@@ -619,7 +657,11 @@ async def reap_orphaned_claude_processes(if row.pid != service_pid and _command_is_claude(row.command, cli_path=cli_path)]row_by_pid = {row.pid: row for row in claude_rows}- registry = owned_processes if owned_processes is not None else _load_owned_process_registry()+ registry = (+ owned_processes+ if owned_processes is not None+ else await loop.run_in_executor(None, _load_owned_process_registry)+ )registry_pids = {record.pidfor record in registrydiff --git a/tests/test_claude_process_reaper.py b/tests/test_claude_process_reaper.pyindex def8f2cc5..ca7c49d42 100644--- a/tests/test_claude_process_reaper.py+++ b/tests/test_claude_process_reaper.py@@ -2,6 +2,12 @@ import asyncioimport loggingimport osimport signal+import subprocess+import sys+import threading+import time+from concurrent.futures import ThreadPoolExecutor+from pathlib import Pathfrom types import SimpleNamespacefrom modules.agents import claude_process_reaper@@ -714,3 +720,184 @@ def test_reap_orphaned_ignores_other_backend_stream_json_descendant_without_regiassert reaped == 0assert signals == []+++def _client(pid: int) -> SimpleNamespace:+ return SimpleNamespace(_transport=SimpleNamespace(_process=SimpleNamespace(pid=pid)))+++def _sleeper() -> subprocess.Popen:+ return subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])+++def test_registering_a_process_reads_and_writes_on_the_registry_thread(tmp_path, monkeypatch):+ # The service registers on its event loop; the `ps` read and the file rewrite must not run there.+ threads: list[str] = []++ def start_time(pid):+ threads.append(threading.current_thread().name)+ return 1000.0++ monkeypatch.setattr(claude_process_reaper, "_process_start_time", start_time)+ child = _sleeper()+ try:+ pending = claude_process_reaper.register_claude_owned_process(+ _client(child.pid), native_session_id="sess-1", runtime_dir=tmp_path+ )+ pending.result(timeout=10)+ finally:+ child.kill()+ child.wait(10)++ assert threads and all(name.startswith("claude-process-registry") for name in threads)+ assert claude_process_reaper._load_owned_process_registry(tmp_path) == [+ claude_process_reaper.ClaudeOwnedProcess(pid=child.pid, native_session_id="sess-1", started_at=1000.0)+ ]+++def test_a_registration_drops_the_records_of_processes_that_have_exited(tmp_path, monkeypatch):+ monkeypatch.setattr(claude_process_reaper, "_process_start_time", lambda pid: 1000.0)+ exited = subprocess.Popen([sys.executable, "-c", "pass"])+ exited.wait(10)+ running, registering = _sleeper(), _sleeper()+ try:+ for child in (exited, running):+ claude_process_reaper.register_claude_owned_process(_client(child.pid), runtime_dir=tmp_path).result(timeout=10)++ claude_process_reaper.register_claude_owned_process(_client(registering.pid), runtime_dir=tmp_path).result(timeout=10)++ recorded = {record.pid for record in claude_process_reaper._load_owned_process_registry(tmp_path)}+ finally:+ for child in (running, registering):+ child.kill()+ child.wait(10)++ assert recorded == {running.pid, registering.pid}+++def test_concurrent_registrations_keep_every_record(tmp_path, monkeypatch):+ monkeypatch.setattr(claude_process_reaper, "_process_start_time", lambda pid: 1000.0)+ children = [_sleeper() for _ in range(4)]+ try:+ with ThreadPoolExecutor(max_workers=4) as callers:+ pending = list(+ callers.map(+ lambda child: claude_process_reaper.register_claude_owned_process(+ _client(child.pid), runtime_dir=tmp_path+ ),+ children,+ )+ )+ for write in pending:+ write.result(timeout=10)++ recorded = {record.pid for record in claude_process_reaper._load_owned_process_registry(tmp_path)}+ finally:+ for child in children:+ child.kill()+ child.wait(10)++ assert recorded == {child.pid for child in children}+++# Holds the registry's file lock the way another service process's registration does, until stdin closes.+_HOLD_REGISTRY_LOCK = """+import sys+from pathlib import Path+sys.path.insert(0, sys.argv[1])+from storage.lock import MigrationFileLock+with MigrationFileLock(Path(sys.argv[2]), timeout_seconds=None):+ print("held", flush=True)+ sys.stdin.read()+"""+++def test_a_registration_waits_while_another_process_rewrites_the_registry(tmp_path, monkeypatch):+ # The Web UI's process registers auth and probe clients into the same file.+ monkeypatch.setattr(claude_process_reaper, "_process_start_time", lambda pid: 1000.0)+ lock_path = tmp_path / f"{claude_process_reaper.CLAUDE_PROCESS_REGISTRY_NAME}.lock"+ holder = subprocess.Popen(+ [sys.executable, "-c", _HOLD_REGISTRY_LOCK, str(Path(__file__).resolve().parents[1]), str(lock_path)],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ text=True,+ )+ child = _sleeper()+ try:+ assert holder.stdout.readline().strip() == "held"+ pending = claude_process_reaper.register_claude_owned_process(_client(child.pid), runtime_dir=tmp_path)+ time.sleep(0.5)+ assert not pending.done()++ holder.stdin.close()+ holder.wait(10)+ pending.result(timeout=10)++ recorded = {record.pid for record in claude_process_reaper._load_owned_process_registry(tmp_path)}+ finally:+ for process in (holder, child):+ process.kill()+ process.wait(10)+ holder.stdout.close()++ assert recorded == {child.pid}+++def test_a_recorded_pid_no_process_can_have_is_dropped(tmp_path, monkeypatch):+ monkeypatch.setattr(claude_process_reaper, "_process_start_time", lambda pid: 1000.0)+ (tmp_path / claude_process_reaper.CLAUDE_PROCESS_REGISTRY_NAME).write_text(+ '{"processes":[{"pid":%d,"native_session_id":null,"owner":"session","started_at":1.0}]}' % 2**63+ )+ child = _sleeper()+ try:+ claude_process_reaper.register_claude_owned_process(_client(child.pid), runtime_dir=tmp_path).result(timeout=10)++ recorded = {record.pid for record in claude_process_reaper._load_owned_process_registry(tmp_path)}+ finally:+ child.kill()+ child.wait(10)++ assert recorded == {child.pid}+++def test_two_writers_interleaved_by_force_keep_both_records(tmp_path, monkeypatch):+ # Without the registry lock, the second writer would load the file before the first replaced it,+ # and its rewrite would drop the first record.+ monkeypatch.setattr(claude_process_reaper, "_process_start_time", lambda pid: 1000.0)+ first_loaded = threading.Event()+ release_first = threading.Event()+ real_load = claude_process_reaper._load_owned_process_registry++ def load(runtime_dir=None):+ records = real_load(runtime_dir)+ if threading.current_thread().name == "first-writer":+ first_loaded.set()+ assert release_first.wait(10)+ return records++ monkeypatch.setattr(claude_process_reaper, "_load_owned_process_registry", load)+ first, second = _sleeper(), _sleeper()+ try:+ writers = [+ threading.Thread(+ target=claude_process_reaper._record_owned_process,+ args=(tmp_path, claude_process_reaper.ClaudeOwnedProcess(pid=child.pid)),+ name=name,+ )+ for child, name in ((first, "first-writer"), (second, "second-writer"))+ ]+ writers[0].start()+ assert first_loaded.wait(10)+ writers[1].start()+ time.sleep(0.3)+ release_first.set()+ for writer in writers:+ writer.join(10)++ recorded = {record.pid for record in real_load(tmp_path)}+ finally:+ for child in (first, second):+ child.kill()+ child.wait(10)++ assert recorded == {first.pid, second.pid}