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(opencode): judge this controller's own servers by their process handle (#2356)
Call Whitea6b14d12d4d6
diff --git a/modules/agents/catalog.py b/modules/agents/catalog.pyindex 6842daa26..fe4069bf4 100644--- a/modules/agents/catalog.py+++ b/modules/agents/catalog.py@@ -81,13 +81,6 @@ WEB_OAUTH_BACKENDS: Final[frozenset[str]] = frozenset(if descriptor.capabilities.supports_web_oauth)-_RUNTIME_REFRESH_SUCCESS_MESSAGES: Final[dict[str, str]] = {- "opencode": "OpenCode restart accepted; active turns will drain before the server refreshes.",- "claude": "Claude restart accepted; active turns will drain before sessions reconnect.",- "codex": "Codex restart accepted; active turns will drain before transports refresh.",-}--def agent_backend_descriptors() -> list[AgentBackendDescriptor]:"""Return backend descriptors in stable UI/routing order."""return list(AGENT_BACKEND_REGISTRY.values())@@ -155,11 +148,3 @@ def supports_install(name: str) -> bool:if name not in AGENT_BACKEND_REGISTRY:return Falsereturn AGENT_BACKEND_REGISTRY[name].capabilities.supports_install---def runtime_refresh_success_message(name: str) -> str:- """Return the success message for a refreshed backend runtime."""- return _RUNTIME_REFRESH_SUCCESS_MESSAGES.get(- name,- f"{name} restart accepted; active turns will drain before runtime refresh.",- )diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.pyindex 375cb764b..da0f4f1c9 100644--- a/modules/agents/opencode/server.py+++ b/modules/agents/opencode/server.py@@ -74,6 +74,11 @@ _UNRECORDED_RUNTIME_ID = object()# its spawn, before its record is written, until a stop proves it gone or its# start proves it exited, so this controller's shutdown stops it, recorded or not._OWNED_HERE: dict[str, tuple[int, Optional[float]]] = {}+# The process handle of each owned generation this process spawned. Until the+# handle reaps it, its pid cannot name another process, so the handle, never+# the start time the platform reports (which moves with every clock step),+# says whether it is still running.+_CHILDREN_HERE: dict[str, Any] = {}# A busy server after a controller crash can miss one health probe; adoption# gives it this many before stopping it._ADOPTION_PROBES = 3@@ -1699,8 +1704,10 @@ class OpenCodeGeneration(OpenCodeServerClient):def process_alive(self) -> bool:process = self._process- if process is not None and process.returncode is not None:- return False+ if process is not None:+ # This controller's own child: its handle is the authority, and+ # its pid cannot be reused before the handle reaps it.+ return process.returncode is Nonecreated_at = runtime.process_create_time(self.pid)if self.process_created_at is None:return created_at is not None or _pid_exists(self.pid)@@ -1834,6 +1841,7 @@ async def start_generation(# Owned before anything else can fail, the record write included.created_at = runtime.process_create_time(process.pid)_OWNED_HERE[generation_id] = (process.pid, created_at)+ _CHILDREN_HERE[generation_id] = processgeneration = OpenCodeGeneration(generation_id=generation_id,pid=process.pid,@@ -1893,10 +1901,23 @@ async def start_generation(raise+def _disown(generation_id: str) -> None:+ _OWNED_HERE.pop(generation_id, None)+ _CHILDREN_HERE.pop(generation_id, None)+++def _child_running(generation_id: object) -> Optional[bool]:+ """Whether a process this controller spawned still runs; None for any other process."""+ child = _CHILDREN_HERE.get(generation_id) if isinstance(generation_id, str) else None+ if child is None:+ return None+ return child.returncode is None++def _disown_ended_start(generation: OpenCodeGeneration) -> None:"""A start's process exited: it is no longer owned here, and its record goes."""- _OWNED_HERE.pop(generation.generation_id, None)+ _disown(generation.generation_id)_remove_quietly(generation.record_path)@@ -1922,7 +1943,7 @@ async def stop_generation(generation: OpenCodeGeneration) -> None:f"OpenCode generation {generation.generation_id} pid={generation.pid} did not exit")generation._record_removed = True- _OWNED_HERE.pop(generation.generation_id, None)+ _disown(generation.generation_id)_remove_quietly(generation.record_path)_remove_quietly(generation.overlay_path)if generation._supersedes is not None:@@ -2312,24 +2333,41 @@ def stop_owned_generations_sync() -> None:recorded: set[str] = set()for path, info in _recorded_processes():- if _owned_here(info):+ if not _owned_here(info):+ continue+ generation_id = info.get("generation_id")+ running = _child_running(generation_id)+ if running is None:stop_recorded_server_sync(path, info)- if isinstance(info.get("generation_id"), str):- recorded.add(info["generation_id"])+ elif not running or terminate_pid_tree_sync(_CHILDREN_HERE[generation_id].pid):+ # This controller's own child, stopped or already exited.+ forget_record(path)+ _disown(generation_id)+ else:+ logger.warning("OpenCode generation %s survived its stop", generation_id)+ if isinstance(generation_id, str):+ recorded.add(generation_id)for generation_id, (pid, created_at) in list(_OWNED_HERE.items()):if generation_id not in recorded:_stop_unrecorded_process_sync(generation_id, pid, created_at)def _stop_unrecorded_process_sync(generation_id: str, pid: int, created_at: Optional[float]) -> None:- """Stop an owned process no record names, proven by its pid and create time.+ """Stop an owned process no record names.- A process whose create time is unknown or cannot be read now is never- signalled: its pid may have been reused. One whose pid is gone, or now- names another process, has ended, and is no longer owned here.+ This controller's own child is judged by its handle. Any other is proven by+ its pid and create time: one whose create time is unknown or cannot be+ read now is never signalled, since its pid may have been reused, and one+ whose pid is gone, or now names another process, has ended and is no+ longer owned here."""- if _pid_exists(pid):+ running = _child_running(generation_id)+ if running is not None:+ if running and not terminate_pid_tree_sync(pid):+ logger.warning("OpenCode generation %s pid=%s survived its stop", generation_id, pid)+ return+ elif _pid_exists(pid):current = runtime.process_create_time(pid)if created_at is None or current is None:logger.warning("Leaving OpenCode generation %s pid=%s: its process cannot be proven", generation_id, pid)@@ -2337,7 +2375,7 @@ def _stop_unrecorded_process_sync(generation_id: str, pid: int, created_at: Optiif current == created_at and not terminate_pid_tree_sync(pid):logger.warning("OpenCode generation %s pid=%s survived its stop", generation_id, pid)return- _OWNED_HERE.pop(generation_id, None)+ _disown(generation_id)_remove_quietly(generation_records_dir() / f"{generation_id}.overlay.json")diff --git a/tests/scenarios/runtime_generations/catalog.yaml b/tests/scenarios/runtime_generations/catalog.yamlindex 2226707af..86a60cbeb 100644--- a/tests/scenarios/runtime_generations/catalog.yaml+++ b/tests/scenarios/runtime_generations/catalog.yaml@@ -252,3 +252,13 @@ scenarios:- tests/test_opencode_generations.py::test_adoption_leaves_every_record_of_another_desktop_runtime_alone- tests/test_opencode_restore_polls.py::test_restore_leaves_every_poll_whose_run_another_desktop_runtimes_live_server_executes- tests/test_opencode_generations.py::test_a_malformed_record_never_disables_opencode+ - id: RUNTIME-GEN-026+ name: A clock step never makes a live OpenCode server this controller started look exited or foreign; its process handle, never the start time the platform reports, decides whether it runs, both for each turn and when the service shuts down+ status: covered+ kind: recovery+ layer: unit+ backend: opencode+ test: tests/test_opencode_generations.py::test_runtime_gen_026_a_generation_this_controller_started_is_alive_while_its_handle_says_so+ related_tests:+ - tests/test_opencode_generations.py::test_runtime_gen_026_service_shutdown_stops_its_own_recorded_server_after_a_clock_step+ - tests/test_opencode_generations.py::test_service_shutdown_stops_a_started_process_whose_record_was_never_writtendiff --git a/tests/test_agent_backend_catalog.py b/tests/test_agent_backend_catalog.pyindex 5d7b8e6a9..cea702e42 100644--- a/tests/test_agent_backend_catalog.py+++ b/tests/test_agent_backend_catalog.py@@ -9,7 +9,6 @@ from modules.agents.catalog import (display_name_for_backend,is_agent_backend,latest_probe_for_backend,- runtime_refresh_success_message,supports_install,supports_runtime_refresh,supports_web_oauth,@@ -28,7 +27,6 @@ def test_agent_catalog_is_backend_management_source_of_truth() -> None:assert supports_install(backend)assert default_cli_for_backend(backend)assert latest_probe_for_backend(backend) is not None- assert backend.lower() in runtime_refresh_success_message(backend).lower()assert display_name_for_backend("opencode") == "OpenCode"assert display_name_for_backend("claude") == "Claude Code"diff --git a/tests/test_opencode_generations.py b/tests/test_opencode_generations.pyindex 9c0839565..1daa08ade 100644--- a/tests/test_opencode_generations.py+++ b/tests/test_opencode_generations.py@@ -160,6 +160,7 @@ def isolated_launch(tmp_path, monkeypatch):monkeypatch.setattr(opencode_server, "generation_records_dir", lambda: tmp_path / "generations")monkeypatch.setattr(opencode_server, "_OWNED_HERE", {})+ monkeypatch.setattr(opencode_server, "_CHILDREN_HERE", {})monkeypatch.setattr(opencode_server, "_ADOPTION_PROBE_INTERVAL_SECONDS", 0)monkeypatch.setattr(opencode_server, "ensure_plugin_installed", lambda: None)monkeypatch.setattr(opencode_server.runtime, "process_create_time", lambda pid: 100.0 + pid)@@ -350,6 +351,7 @@ def fake_processes(tmp_path, monkeypatch):monkeypatch.setattr(opencode_server, "generation_records_dir", lambda: tmp_path / "generations")monkeypatch.setattr(opencode_server, "_OWNED_HERE", {})+ monkeypatch.setattr(opencode_server, "_CHILDREN_HERE", {})started: list[OpenCodeGeneration] = []stopped: list[OpenCodeGeneration] = []alive: set[str] = set()@@ -458,6 +460,29 @@ def test_an_old_generation_stays_until_the_activity_it_started_ends(fake_processassert fake_processes.stopped == [old]+def test_runtime_gen_026_a_generation_this_controller_started_is_alive_while_its_handle_says_so(monkeypatch):+ """RUNTIME-GEN-026: its own child's handle decides, never a start-time+ comparison. A clock step moves the start time the platform reports, and the+ generation was then taken for exited, replaced on the next turn, and left+ running with no record."""++ process = SimpleNamespace(returncode=None)+ generation = OpenCodeGeneration(+ generation_id="ocg_own",+ pid=fake_pid(7),+ port=50107,+ spec_digest="v1",+ process_created_at=1_000.0,+ process=process,+ )+ # The start time read now differs from the one recorded at spawn.+ monkeypatch.setattr(opencode_server.runtime, "process_create_time", lambda _pid: 998.0)++ assert generation.process_alive()+ process.returncode = 0+ assert not generation.process_alive()++def test_a_current_generation_whose_process_died_is_replaced(fake_processes):async def scenario():runtime = _runtime()@@ -2060,12 +2085,13 @@ def test_a_failed_start_whose_process_survives_is_reaped_until_it_is_gone(isolatdef test_service_shutdown_stops_a_started_process_whose_record_was_never_written(isolated_launch, monkeypatch):"""A start's record write fails and its process survives the stop. Avibestops before any reap retries it: the controller's shutdown still stops- that process, proven by its pid and create time, and drops its Hub- overlay. It never signals a pid whose create time changed or cannot be read."""+ that process and drops its Hub overlay. It is this controller's own child,+ so its handle decides, never the start time the platform reports now: a+ clock step does not spare one, and one that exited is not signalled."""- proven, reused, unreadable = fake_pid(67), fake_pid(68), fake_pid(69)- isolated_launch.processes.extend(_Process(pid) for pid in (proven, reused, unreadable))- create_times = {proven: 1.0, reused: 2.0, unreadable: 3.0}+ proven, shifted, exited = fake_pid(67), fake_pid(68), fake_pid(69)+ isolated_launch.processes.extend(_Process(pid) for pid in (proven, shifted, exited))+ create_times = {proven: 1.0, shifted: 2.0, exited: 3.0}monkeypatch.setattr(opencode_server.runtime, "process_create_time", create_times.get)monkeypatch.setattr(opencode_server.runtime, "pid_alive", lambda pid: pid in create_times)monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: isolated_launch.records / "absent.json")@@ -2093,15 +2119,39 @@ def test_service_shutdown_stops_a_started_process_whose_record_was_never_writtenawait opencode_server.start_generation(spec, on_survivor=survivors.append)asyncio.run(start_three())- create_times[reused] = 9.0- create_times[unreadable] = None+ create_times[shifted] = 9.0 # The clock stepped.+ next(generation for generation in survivors if generation.pid == exited)._process.returncode = 0++ opencode_server.stop_owned_generations_sync()++ assert stopped == [proven, shifted]+ assert opencode_server._OWNED_HERE == {} and opencode_server._CHILDREN_HERE == {}+ assert list(isolated_launch.records.iterdir()) == []+++def test_runtime_gen_026_service_shutdown_stops_its_own_recorded_server_after_a_clock_step(isolated_launch, monkeypatch):+ """RUNTIME-GEN-026: the start time the platform reports for a server this+ controller started moved with the clock, so its record no longer proves+ it. Its handle still does: shutdown stops it and forgets its record."""++ pid = fake_pid(70)+ isolated_launch.processes.append(_Process(pid))+ monkeypatch.setattr(opencode_server.runtime, "pid_alive", lambda candidate: candidate == pid)+ monkeypatch.setattr(opencode_server, "legacy_pid_file", lambda: isolated_launch.records / "absent.json")+ stopped: list[int] = []+ monkeypatch.setattr(opencode_server, "terminate_pid_tree_sync", lambda target, timeout=5.0: stopped.append(target) or True)++ generation = asyncio.run(+ opencode_server.start_generation(OpenCodeLaunchSpec(digest="spec", binary="/bin/opencode"))+ )+ assert generation.record_path.exists()+ monkeypatch.setattr(opencode_server.runtime, "process_create_time", lambda _pid: 7.0)opencode_server.stop_owned_generations_sync()- assert stopped == [proven]- kept = next(generation for generation in survivors if generation.pid == unreadable)- assert list(opencode_server._OWNED_HERE) == [kept.generation_id]- assert [path.name for path in isolated_launch.records.iterdir()] == [kept.overlay_path.name]+ assert stopped == [pid]+ assert not generation.record_path.exists()+ assert opencode_server._OWNED_HERE == {} and opencode_server._CHILDREN_HERE == {}def test_a_turn_keeps_the_opencode_settings_it_was_admitted_with(monkeypatch):diff --git a/vibe/api.py b/vibe/api.pyindex 9b1c14d54..0251db2c2 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -108,7 +108,6 @@ from modules.agents.catalog import (display_name_for_backend,is_agent_backend,latest_probe_for_backend,- runtime_refresh_success_message,supports_runtime_refresh,supports_web_oauth,)@@ -10345,7 +10344,12 @@ def _restart_backend(name: str, *, metadata: Optional[dict[str, Any]] = None) ->"ok": False,"message": f"Backend refresh failed: {controller_error}",}- return {"ok": True, "message": runtime_refresh_success_message(name)}+ return {+ "ok": True,+ "message": backend_t(+ "backendConnection.restartAccepted", lang=language, agent=display_name_for_backend(name)+ ),+ }# A running service with broken IPC is not a stopped backend. Killing its# child process here would hide stale controller state and split ownership.diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex e3e8fc4bd..2eb1c8a99 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -1,7 +1,8 @@{"backendConnection": {"applyOnStart": "Configuration will apply on next start.",- "applyUnacknowledged": "Backend refresh was not acknowledged by the controller."+ "applyUnacknowledged": "Backend refresh was not acknowledged by the controller.",+ "restartAccepted": "{agent} restarted. Running work finishes where it started; new turns use the new runtime."},"errors": {"agentModelRequired": "Select a model for the {backend} Agent or Session in Avibe before running it.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex e6632aa2b..c85b837f5 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -1,7 +1,8 @@{"backendConnection": {"applyOnStart": "配置将在下次启动时应用。",- "applyUnacknowledged": "控制器未确认后端刷新请求。"+ "applyUnacknowledged": "控制器未确认后端刷新请求。",+ "restartAccepted": "{agent} 已重启。正在进行的工作会在原来的运行环境中完成,新的对话轮次会使用新的运行环境。"},"errors": {"agentModelRequired": "请先在 Avibe 中为 {backend} Agent 或会话选择模型。",