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
feat(runtime): add bounded backend rolling restart (#872)
Call White9483d6759f86
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.pyindex 532521879..5b9fdc7ef 100644--- a/core/agent_auth_service.py+++ b/core/agent_auth_service.py@@ -1553,14 +1553,17 @@ class AgentAuthService:except Exception as err: # noqa: BLE001logger.warning("Failed to clear OpenCode provider option apiKey after OAuth for %s: %s", provider, err)- async def _refresh_opencode_server(self) -> None:+ async def _refresh_opencode_server(self, *, force: bool = False) -> None:agent_service = getattr(self.controller, "agent_service", None)opencode_agent = getattr(agent_service, "agents", {}).get("opencode") if agent_service else Noneif not opencode_agent or not hasattr(opencode_agent, "_get_server"):returnserver = await opencode_agent._get_server()if hasattr(server, "restart_for_auth_refresh"):- await server.restart_for_auth_refresh()+ if force:+ await server.restart_for_auth_refresh(force=True)+ else:+ await server.restart_for_auth_refresh()def _load_backend_runtime_config(self, backend: str):from config.v2_compat import to_app_config@@ -1649,6 +1652,13 @@ class AgentAuthService:return Trueasync def _refresh_backend_runtime(self, backend: str) -> None:+ coordinator = getattr(self.controller, "backend_restart_coordinator", None)+ if coordinator is not None:+ await coordinator.request_restart(backend)+ return+ await self._apply_backend_runtime_refresh(backend, False)++ async def _apply_backend_runtime_refresh(self, backend: str, force: bool = False) -> None:agent_service = getattr(self.controller, "agent_service", None)runtime_tokens: dict[str, str] = {}snapshot_tokens = getattr(agent_service, "runtime_turn_tokens_for_backend", None)@@ -1664,6 +1674,13 @@ class AgentAuthService:returnif runtime_config is not None and self._register_missing_backend_agent(backend, runtime_config):return+ if force and backend == "opencode":+ agent = getattr(agent_service, "agents", {}).get(backend)+ refresh_config = getattr(agent, "refresh_runtime_config", None)+ if callable(refresh_config):+ await refresh_config(runtime_config, force=True)+ self._sync_builtin_default_agents()+ returnif runtime_config is not None and await refresh_runtime_config(backend, runtime_config):self._sync_builtin_default_agents()return@@ -1678,7 +1695,10 @@ class AgentAuthService:await refresh_config(runtime_config)returnif backend == "opencode":- await self._refresh_opencode_server()+ if force:+ await self._refresh_opencode_server(force=True)+ else:+ await self._refresh_opencode_server()returnrefresh = getattr(agent, "refresh_auth_state", None)if callable(refresh):diff --git a/core/backend_restart.py b/core/backend_restart.pynew file mode 100644index 000000000..cea848669--- /dev/null+++ b/core/backend_restart.py@@ -0,0 +1,122 @@+"""Shared backend restart barrier and bounded drain coordinator."""++from __future__ import annotations++import asyncio+import logging+import os+from collections.abc import Awaitable, Callable+from typing import Any++logger = logging.getLogger(__name__)++DEFAULT_DRAIN_TIMEOUT_SECONDS = 300.0+_POLL_INTERVAL_SECONDS = 0.1+++def _configured_drain_timeout() -> float:+ raw = os.environ.get("AVIBE_BACKEND_RESTART_DRAIN_TIMEOUT_SECONDS", "")+ try:+ return max(0.0, float(raw)) if raw.strip() else DEFAULT_DRAIN_TIMEOUT_SECONDS+ except ValueError:+ logger.warning("Ignoring invalid AVIBE_BACKEND_RESTART_DRAIN_TIMEOUT_SECONDS=%r", raw)+ return DEFAULT_DRAIN_TIMEOUT_SECONDS+++class BackendRestartCoordinator:+ """Serialize backend cutovers without stopping Avibe's service process."""++ def __init__(+ self,+ controller: Any,+ refresh: Callable[[str, bool], Awaitable[None]],+ *,+ drain_timeout: float | None = None,+ poll_interval: float = _POLL_INTERVAL_SECONDS,+ ) -> None:+ self.controller = controller+ self._refresh = refresh+ self._drain_timeout = _configured_drain_timeout() if drain_timeout is None else max(0.0, drain_timeout)+ self._poll_interval = max(0.001, poll_interval)+ self._tasks: dict[str, asyncio.Task[None]] = {}+ self._request_locks: dict[str, asyncio.Lock] = {}++ async def request_restart(self, backend: str) -> str:+ """Begin or join a restart and return without waiting for a long drain."""+ lock = self._request_locks.setdefault(backend, asyncio.Lock())+ async with lock:+ existing = self._tasks.get(backend)+ if existing is not None and not existing.done():+ return "draining"++ agent_service = self.controller.agent_service+ session_turns = self.controller.session_turns+ agent_service.begin_backend_drain(backend)+ session_turns.begin_backend_drain(backend)+ try:+ await agent_service.prepare_backend_restart(backend)+ except Exception:+ agent_service.end_backend_drain(backend)+ await session_turns.end_backend_drain(backend, resume_deferred=False)+ raise+ had_active_work = self._has_active_turns(backend)+ task = asyncio.create_task(self._run(backend), name=f"backend-restart:{backend}")+ self._tasks[backend] = task+ task.add_done_callback(lambda completed, name=backend: self._on_done(name, completed))++ # Idle refreshes remain synchronous so setup/config errors reach the+ # runtime-command requester. Only genuinely active work makes the+ # restart an acknowledged background drain.+ if not had_active_work:+ await task+ return "restarted"+ return "draining"++ def _on_done(self, backend: str, task: asyncio.Task[None]) -> None:+ if self._tasks.get(backend) is task:+ self._tasks.pop(backend, None)+ try:+ task.result()+ except asyncio.CancelledError:+ logger.info("Backend restart cancelled for %s", backend)+ except Exception:+ logger.exception("Backend restart failed for %s", backend)++ def _has_active_turns(self, backend: str) -> bool:+ service = self.controller.agent_service+ if service.runtime_turn_tokens_for_backend(backend):+ return True+ probe = getattr(service, "backend_runtime_active", None)+ return bool(callable(probe) and probe(backend))++ async def _run(self, backend: str) -> None:+ forced = False+ refreshed = False+ loop = asyncio.get_running_loop()+ deadline = loop.time() + self._drain_timeout+ try:+ while self._has_active_turns(backend):+ if loop.time() >= deadline:+ forced = True+ session_ids = self.controller.session_turns.active_runtime_session_ids_for_backend(backend)+ await self.controller.session_turns.release_for_backend_refresh(+ backend=backend,+ base_session_ids=session_ids,+ )+ await self.controller.agent_service.force_cancel_backend_turns(backend)+ self.controller.agent_service.force_end_backend_activities(backend)+ break+ await asyncio.sleep(self._poll_interval)+ await self._refresh(backend, forced)+ refreshed = True+ finally:+ # Runtime admission opens before durable queues are flushed. A flush+ # therefore always enters the refreshed generation.+ self.controller.agent_service.end_backend_drain(backend)+ await self.controller.session_turns.end_backend_drain(backend, resume_deferred=refreshed)++ async def wait(self, backend: str) -> None:+ """Testing/diagnostic hook: wait for the current restart, if any."""+ task = self._tasks.get(backend)+ if task is not None:+ await asyncio.shield(task)diff --git a/core/controller.py b/core/controller.pyindex f2314359f..130d3b710 100644--- a/core/controller.py+++ b/core/controller.py@@ -234,6 +234,12 @@ class Controller:# Initialize agents (depends on handlers/session handler)self._init_agents()self.agent_auth_service = AgentAuthService(self)+ from core.backend_restart import BackendRestartCoordinator++ self.backend_restart_coordinator = BackendRestartCoordinator(+ self,+ self.agent_auth_service._apply_backend_runtime_refresh,+ )self.vibe_agent_store = VibeAgentStore()self.vibe_agent_store.ensure_builtin_default_agents(@@ -1529,11 +1535,12 @@ class Controller:self._im_thread.join(timeout=5)self._im_thread = None- # Stop OpenCode server if running+ # An explicit Avibe stop/restart must not leave an adopted OpenCode+ # generation behind. Active turns have already reached shutdown cleanup.try:from modules.agents.opencode import OpenCodeServerManager- OpenCodeServerManager.stop_instance_sync()+ OpenCodeServerManager.terminate_instance_sync()except Exception as e:logger.debug(f"OpenCode server cleanup skipped: {e}")diff --git a/core/session_activities.py b/core/session_activities.pyindex f372e72f2..ea38fcb27 100644--- a/core/session_activities.py+++ b/core/session_activities.py@@ -282,6 +282,60 @@ class SessionActivityRegistry:with self._lock:return bool(self._completed_outputs.get((str(backend), str(runtime_key))))+ def has_backend_work(self, backend: str) -> bool:+ """Whether a backend has live Activities or undelivered completions."""++ identity = str(backend)+ with self._lock:+ return any(key[0] == identity for key in self._active) or any(+ key[0] == identity and bool(queue)+ for key, queue in self._completed_outputs.items()+ )++ def end_backend(self, backend: str, *, status: str = "killed") -> list[SessionActivity]:+ """Settle every Activity owned by a force-terminated backend runtime."""++ identity = str(backend)+ with self._lock:+ runtime_keys = {+ runtime_key+ for item_backend, runtime_key, _activity_id in self._active+ if item_backend == identity+ }+ runtime_keys.update(+ runtime_key+ for item_backend, runtime_key in self._connections+ if item_backend == identity+ )+ runtime_keys.update(+ runtime_key+ for item_backend, runtime_key in self._completed_outputs+ if item_backend == identity+ )+ completed: list[SessionActivity] = []+ for runtime_key in runtime_keys:+ completed.extend(self.end_runtime(identity, runtime_key, status=status))+ with self._lock:+ pending = [+ activity+ for key, queue in self._completed_outputs.items()+ if key[0] == identity+ for _completed_at, activity in queue+ ]+ for key in [key for key in self._completed_outputs if key[0] == identity]:+ self._completed_outputs.pop(key, None)+ now = _now_iso()+ completed.extend(+ replace(+ activity,+ status=status if status in TERMINAL_ACTIVITY_STATUSES else "killed",+ updated_at=now,+ completed_at=now,+ )+ for activity in pending+ )+ return completed+def end_runtime(self,backend: str,@@ -311,7 +365,7 @@ class SessionActivityRegistry:backend=backend,runtime_key=runtime_key,activity_id=activity_id,- status="disconnected",+ status=status if status in TERMINAL_ACTIVITY_STATUSES else "disconnected",)if activity is not None:completed.append(activity)diff --git a/core/session_turns.py b/core/session_turns.pyindex 188a3c764..63ad4b59c 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -558,6 +558,8 @@ class SessionTurnManager:self._build_context = build_contextself._engine: Engine | None = Noneself.in_flight: dict[str, Turn] = {}+ self._draining_backends: set[str] = set()+ self._deferred_restart_sessions: dict[str, set[str]] = {}# The live streaming turn sink per SESSION KEY (avibe/web-Chat only; IM/CLI# turns register none). Each is ``{on_chunk, done_event, turn_token}`` — the# turn's stream callback + completion event + correlation token. Keyed by@@ -580,6 +582,60 @@ class SessionTurnManager:routing from the current session row."""self._build_context = build_context+ def _context_backend(self, context: "MessageContext") -> str:+ spec = getattr(context, "platform_specific", None) or {}+ target = spec.get("agent_session_target")+ backend = str(target.get("agent_backend") or "").strip() if isinstance(target, dict) else ""+ if backend:+ return backend+ resolved = spec.get("resolved_vibe_agent")+ if isinstance(resolved, dict):+ backend = str(resolved.get("backend") or "").strip()+ if backend:+ return backend+ resolver = getattr(self.controller, "resolve_agent_for_context", None)+ if callable(resolver):+ try:+ return str(resolver(context) or "").strip()+ except Exception:+ logger.debug("Failed to resolve inherited backend for restart drain", exc_info=True)+ service = getattr(self.controller, "agent_service", None)+ return str(getattr(service, "default_agent", "") or "").strip()++ def begin_backend_drain(self, backend: str) -> None:+ self._draining_backends.add(backend)+ self._deferred_restart_sessions.setdefault(backend, set())++ async def end_backend_drain(self, backend: str, *, resume_deferred: bool = True) -> None:+ self._draining_backends.discard(backend)+ session_ids = self._deferred_restart_sessions.pop(backend, set())+ if not resume_deferred:+ return+ for session_id in sorted(session_ids):+ if not self.is_in_flight(session_id):+ await self.flush_queue(session_id)++ def active_session_ids_for_backend(self, backend: str) -> set[str]:+ return {+ session_id+ for session_id, turn in self.in_flight.items()+ if not turn.task.done() and self._context_backend(turn.context) == backend+ }++ def active_runtime_session_ids_for_backend(self, backend: str) -> set[str]:+ """Active Sessions that actually entered the old backend generation."""+ return {+ session_id+ for session_id, turn in self.in_flight.items()+ if not turn.task.done()+ and self._context_backend(turn.context) == backend+ and bool(+ (getattr(turn.context, "platform_specific", None) or {}).get(+ "agent_runtime_turn_token"+ )+ )+ }+@staticmethodasync def _noop_chunk(_envelope: dict) -> None:# Chunks are discarded — the browser renders from ``message.new``.@@ -610,11 +666,15 @@ class SessionTurnManager:await self._run(None, context, text, source=source)return "ran"+ backend = self._context_backend(context)entry = self.in_flight.get(session_id)busy = entry is not None and not entry.task.done()# Enqueue when a turn is running OR a prior Stop left queued rows behind — the# new message must run AFTER them, not jump ahead (Codex P2).- if busy:+ if backend in self._draining_backends:+ should_enqueue = True+ self._deferred_restart_sessions.setdefault(backend, set()).add(session_id)+ elif busy:should_enqueue = Trueelse:with self._sqlite_engine().connect() as conn:@@ -622,7 +682,7 @@ class SessionTurnManager:if should_enqueue:if enqueue is not None:enqueue()- if busy:+ if busy or backend in self._draining_backends:# The row joins the active turn's queue and stays until it drains —# surface the queue growth NOW so the UI reflects it immediately# (the later flush emits its own queue.updated when it pops). This@@ -720,7 +780,10 @@ class SessionTurnManager:(not cancelled and not failed and not (turn is not None and turn.stop_no_flush))or (turn is not None and turn.flush_on_cancel))- if should_flush:+ backend = self._context_backend(context)+ if should_flush and backend in self._draining_backends:+ self._deferred_restart_sessions.setdefault(backend, set()).add(session_id)+ elif should_flush:await self.flush_queue(session_id)task = asyncio.create_task(_runner(), name="internal-dispatch-async")@@ -755,6 +818,18 @@ class SessionTurnManager:if not session_id:return False+ if self._build_context is None:+ logger.error("queue flush: no build_context bound for session=%s", session_id)+ return False+ try:+ context = await asyncio.to_thread(self._build_context, session_id)+ except Exception:+ logger.exception("queue flush: failed to build context for session=%s", session_id)+ return False+ backend = self._context_backend(context)+ if backend in self._draining_backends:+ self._deferred_restart_sessions.setdefault(backend, set()).add(session_id)+ return Falseis_scheduled = Falsescheduled_text = ""@@ -917,17 +992,6 @@ class SessionTurnManager:bus.publish("inbox.session.updated", inbox_row)bus.publish("queue.updated", {"session_id": session_id})- # Rebuild routing from the CURRENT session row so a flushed follow-up uses the- # session's latest agent / model / effort (Codex P2).- if self._build_context is None:- logger.error("queue flush: no build_context bound for session=%s", session_id)- return False- try:- context = await asyncio.to_thread(self._build_context, session_id)- except Exception:- logger.exception("queue flush: failed to build context for session=%s", session_id)- return False-if not is_scheduled:# Carry the queued segment's uploaded files into the merged turn.context.files = file_attachments_from_specs(attachment_specs)@@ -1106,6 +1170,8 @@ class SessionTurnManager:tasks_to_settle.append(turn.task)if self.controller is not None:self.controller.set_agent_status(session_id, "idle")+ if backend in self._draining_backends:+ self._deferred_restart_sessions.setdefault(backend, set()).add(session_id)released += 1if tasks_to_settle:await asyncio.gather(*tasks_to_settle, return_exceptions=True)@@ -1163,6 +1229,10 @@ class SessionTurnManager:bus.publish("turn.end", {"session_id": session_id})if self.controller is not None:self.controller.set_agent_status(session_id, "idle")+ backend = self._context_backend(turn.context)+ deferred = self._deferred_restart_sessions.get(backend)+ if deferred is not None:+ deferred.discard(session_id)return {"ok": True,"session_id": session_id,@@ -1174,6 +1244,10 @@ class SessionTurnManager:# later natural completion can flush normally.turn.stop_no_flush = Falsereturn {"ok": False, "code": "stop_failed", "session_id": session_id, "reason": reason or None}+ backend = self._context_backend(turn.context)+ deferred = self._deferred_restart_sessions.get(backend)+ if deferred is not None:+ deferred.discard(session_id)turn.task.cancel()return {"ok": True, "session_id": session_id, "status": "cancel_requested"}diff --git a/docs/plans/backend-rolling-restart.md b/docs/plans/backend-rolling-restart.mdnew file mode 100644index 000000000..f921ca3d0--- /dev/null+++ b/docs/plans/backend-rolling-restart.md@@ -0,0 +1,82 @@+# Backend Rolling Restart++## Goal++Restart Claude, Codex, and OpenCode runtime state without destabilizing the+Avibe service, Web UI, tunnel, or Session context. A restart must never allow+two turns to work on the same Session concurrently.++## Contract++The shared runtime owns a backend restart barrier with four states:++`READY -> DRAINING -> SWITCHING -> READY`++- `READY`: new turns may start.+- `DRAINING`: turns accepted before the barrier continue. New turns wait. A+ Workbench message for a busy Session remains in its durable queue.+- `SWITCHING`: no new turn can enter while the old runtime is terminated and+ refreshed configuration is activated.+- `READY`: queued work resumes through the normal Session gate.++The Session FSM remains the authority. A Session changes generation only after+its active turn reaches IDLE. Stop and send-now use the existing interruption+path; after the old turn settles, the queued message resumes on the new runtime.+Backend-native background Activities are a second, orthogonal liveness axis:+the drain also waits for active Activities and their pending output to settle.++## Why the barrier is shared++Claude, Codex, and OpenCode have different process models, but the safety+invariants are identical. Keeping the barrier in `AgentService` and the durable+queue interaction in `SessionTurnManager` avoids backend-specific queue and+locking rules.++The first implementation uses a single-writer cutover for every backend.+OpenCode must not run two servers against the same local state concurrently.+Codex and Claude may later prepare a new generation during DRAINING, but only if+their adapters can prove isolated ownership. That optimization does not change+the Session protocol.++## Timeout++Draining is bounded. At the deadline, the coordinator:++1. cancels matching Workbench waiters without flushing them onto the old+ runtime;+2. marks remaining backend Activities killed and settles their owning Runs;+3. force-refreshes the backend runtime, which terminates the old process tree;+4. releases stale runtime-turn tokens;+5. reopens the backend barrier and flushes queued Sessions.++The default drain timeout is five minutes and can be overridden for operations+and tests with `AVIBE_BACKEND_RESTART_DRAIN_TIMEOUT_SECONDS`.++## Invariants++- At most one active turn per Session and runtime key.+- Restart coordination never stops the Avibe service, UI, or tunnel.+- A failed refresh reopens the barrier; it cannot deadlock future turns.+- Concurrent restart requests for one backend coalesce into one operation.+- Queue rows are claimed only by the existing Session queue transaction.+- Old-turn completion and timeout force-cutover are idempotent races.++## Scenarios++- `BRR-001`: idle backend refreshes immediately and accepts the next turn.+- `BRR-002`: active Session drains; its new message remains queued until IDLE.+- `BRR-003`: another Session cannot enter the switching window.+- `BRR-004`: Stop/send-now settles the old turn and advances cutover.+- `BRR-005`: drain timeout cancels the old waiter, force-refreshes, then flushes.+- `BRR-006`: refresh failure reopens the barrier and preserves queued input.+- `BRR-007`: concurrent restart requests coalesce without duplicate process kills.+- `BRR-008`: backend restart does not touch service, UI, or tunnel lifecycle.++## Service restart boundary++This protocol is also the prerequisite for a future service-process handoff,+but it does not claim that a SIGTERM of the current Avibe process can preserve+an in-memory receiver. A true service rolling restart additionally needs an+external supervisor and cross-process ownership handoff. Until that exists,+backend restarts use this protocol; service restart remains crash-recovery+semantics and must not pretend to be seamless.diff --git a/modules/agents/catalog.py b/modules/agents/catalog.pyindex e8db3fc20..6842daa26 100644--- a/modules/agents/catalog.py+++ b/modules/agents/catalog.py@@ -82,9 +82,9 @@ WEB_OAUTH_BACKENDS: Final[frozenset[str]] = frozenset()_RUNTIME_REFRESH_SUCCESS_MESSAGES: Final[dict[str, str]] = {- "opencode": "OpenCode server refreshed; it will respawn on next request.",- "claude": "Claude runtime refreshed; sessions will reconnect on next request.",- "codex": "Codex runtime refreshed; transports will respawn on next request.",+ "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.",}@@ -161,5 +161,5 @@ 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} runtime refreshed; next request will use current settings.",+ f"{name} restart accepted; active turns will drain before runtime refresh.",)diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex 1399bbf34..9b1cdead8 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -69,7 +69,17 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):async def _get_server(self) -> OpenCodeServerManager:return await self._client_manager.get_server()- async def refresh_runtime_config(self, opencode_config) -> None:+ async def prepare_runtime_restart(self) -> None:+ """Adopt persisted server state before the shared drain snapshot."""+ await self._get_server()++ def runtime_has_active_turns(self) -> bool:+ if any(not task.done() for task in self._active_requests.values()):+ return True+ server = self._client_manager._server_manager+ return bool(server is not None and server.runtime_has_active_turns())++ async def refresh_runtime_config(self, opencode_config, *, force: bool = False) -> None:"""Reload runtime config and refresh the shared server.OpenCode caches opencode.json provider/model config in the serve@@ -78,7 +88,6 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):processes; fall back to restart for older OpenCode versions."""previous_server = await self._client_manager.reset_config(opencode_config)- adopted_uncached_server = Falseif previous_server is None:previous_server = await OpenCodeServerManager.get_instance_if_managed_server_exists(binary=self.opencode_config.binary,@@ -86,7 +95,6 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):request_timeout_seconds=self.opencode_config.request_timeout_seconds,resource_governor=governor_from_controller(self.controller),)- adopted_uncached_server = previous_server is not Noneself.opencode_config = opencode_configself.controller.config.opencode = opencode_configif previous_server is not None:@@ -97,20 +105,24 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):and previous_server.request_timeout_seconds == opencode_config.request_timeout_seconds)refresh_global_config = getattr(previous_server, "refresh_global_config", None)- if runtime_unchanged and callable(refresh_global_config):+ if not force and runtime_unchanged and callable(refresh_global_config):try:refreshed = bool(await refresh_global_config())except Exception:logger.warning("OpenCode global config refresh failed; falling back to restart", exc_info=True)refreshed = Falseif not refreshed:- if adopted_uncached_server and runtime_unchanged:- returndetach = getattr(previous_server, "detach_after_deferred_refresh", None)if callable(detach):- await detach()+ if force:+ await detach(force=True)+ else:+ await detach()elif hasattr(previous_server, "restart_for_auth_refresh"):- await previous_server.restart_for_auth_refresh()+ if force:+ await previous_server.restart_for_auth_refresh(force=True)+ else:+ await previous_server.restart_for_auth_refresh()reload_config = getattr(previous_server, "reload_runtime_config", None)if callable(reload_config):await reload_config(diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.pyindex 207995bb1..8b6cbd002 100644--- a/modules/agents/opencode/server.py+++ b/modules/agents/opencode/server.py@@ -10,6 +10,7 @@ import loggingimport osfrom pathlib import Pathimport re+import signalimport socketimport subprocessimport time@@ -272,10 +273,12 @@ class OpenCodeServerManager:self._auth_refresh_pending_port = Noneself._apply_pending_runtime_config_locked()- async def detach_after_deferred_refresh(self) -> None:+ async def detach_after_deferred_refresh(self, *, force: bool = False) -> None:"""Drop cached client state when a refresh must wait for active runs."""async with self._get_lock():- if self._active_requests > 0 or self._has_active_run_sessions():+ if force:+ self._active_run_sessions.clear()+ if not force and (self._active_requests > 0 or self._has_active_run_sessions()):self._auth_refresh_pending = Trueself._auth_refresh_pending_port = self.portlogger.info(@@ -354,6 +357,18 @@ class OpenCodeServerManager:def _has_active_run_sessions(self) -> bool:return bool(self._active_run_sessions)+ def runtime_has_active_turns(self) -> bool:+ if self._active_requests > 0 or self._has_active_run_sessions():+ return True+ info = self._read_pid_file()+ if not self._pid_file_references_current_server(info):+ return False+ pid = info.get("pid") if isinstance(info, dict) else None+ if not isinstance(pid, int) or not self._pid_exists(pid):+ return False+ active = info.get("active_run_sessions") if isinstance(info, dict) else None+ return isinstance(active, list) and bool(active)+async def mark_run_active(self, session_id: str) -> None:async with self._get_lock():self._active_run_sessions.add(session_id)@@ -449,10 +464,14 @@ class OpenCodeServerManager:pid = info.get("pid")if not isinstance(pid, int):return False- if info.get("port") == self.port:- return True+ if info.get("port") != self.port:+ return Falsecmd = self._get_pid_command(pid)- return bool(cmd and self._is_opencode_serve_cmd(cmd, self.port))+ if cmd:+ return self._is_opencode_serve_cmd(cmd, self.port)+ if self._pid_owns_listening_port(pid, self.port):+ return True+ return Falsedef _pid_file_has_caller_context_binding(self, info: Optional[Dict[str, Any]]) -> bool:if not self._pid_file_references_current_server(info):@@ -923,9 +942,55 @@ class OpenCodeServerManager:async def _terminate_pid(self, pid: int, reason: str) -> None:logger.info(f"Stopping OpenCode server pid={pid} ({reason})")- if not runtime.stop_pid(pid, timeout=5) and self._pid_exists(pid):+ stopped = await asyncio.to_thread(self._terminate_pid_tree_sync, pid)+ if not stopped and self._pid_exists(pid):logger.debug("Failed to terminate OpenCode server pid=%s", pid)+ @staticmethod+ def _terminate_pid_tree_sync(pid: int, timeout: float = 5.0) -> bool:+ """Stop the dedicated OpenCode process group, including tool children."""+ if os.name == "nt":+ return runtime.stop_pid(pid, timeout=timeout)+ try:+ pgid = os.getpgid(pid)+ except (ProcessLookupError, PermissionError):+ return not runtime.pid_alive(pid)+ if pgid != pid:+ return runtime.stop_pid(pid, timeout=timeout)++ def group_alive() -> bool:+ try:+ os.killpg(pgid, 0)+ return True+ except ProcessLookupError:+ return False+ except PermissionError:+ return True++ try:+ os.killpg(pgid, signal.SIGTERM)+ except ProcessLookupError:+ return True+ except PermissionError:+ return False+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if not group_alive():+ return True+ time.sleep(0.1)+ try:+ os.killpg(pgid, signal.SIGKILL)+ except ProcessLookupError:+ return True+ except PermissionError:+ return False+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if not group_alive():+ return True+ time.sleep(0.1)+ return not group_alive()+async def _cleanup_orphaned_managed_server(self) -> None:info = self._read_pid_file()if not info:@@ -1160,7 +1225,7 @@ class OpenCodeServerManager:self._process = Noneself._process_loop = None- def stop_sync(self) -> None:+ def _close_http_session_sync(self) -> None:if self._http_session and self._http_session_loop:try:future = asyncio.run_coroutine_threadsafe(self._http_session.close(), self._http_session_loop)@@ -1171,6 +1236,9 @@ class OpenCodeServerManager:self._http_session = Noneself._http_session_loop = None+ def stop_sync(self) -> None:+ self._close_http_session_sync()+# Don't terminate OpenCode server on vibe-remote shutdown.# Let it continue running so the next vibe-remote instance can adopt it.# This prevents interrupting tasks that are still in progress.@@ -1181,10 +1249,62 @@ class OpenCodeServerManager:self._process = Noneself._process_loop = None- async def restart_for_auth_refresh(self) -> None:+ def terminate_sync(self) -> None:+ """Terminate the managed server during an explicit Avibe shutdown."""+ self._close_http_session_sync()+ info = self._read_pid_file()+ pid = info.get("pid") if isinstance(info, dict) else None+ tracked_pid = getattr(self._process, "pid", None)+ stopped = False+ if isinstance(pid, int) and self._pid_exists(pid):+ command = self._get_pid_command(pid)+ trusted_pid_file = bool(command and self._is_opencode_serve_cmd(command, self.port)) or (+ isinstance(info, dict)+ and info.get("port") == self.port+ and self._pid_owns_listening_port(pid, self.port)+ )+ if trusted_pid_file:+ stopped = self._terminate_pid_tree_sync(pid)+ if not stopped and isinstance(tracked_pid, int) and self._pid_exists(tracked_pid):+ tracked_command = self._get_pid_command(tracked_pid)+ if tracked_command and self._is_opencode_serve_cmd(tracked_command, self.port):+ self._terminate_pid_tree_sync(tracked_pid)+ self._clear_pid_file()+ self._base_url = None+ self._process = None+ self._process_loop = None++ @classmethod+ def terminate_instance_sync(cls) -> None:+ if cls._instance is not None:+ cls._instance.terminate_sync()+ return+ pid_file = paths.get_logs_dir() / "opencode_server.json"+ try:+ info = json.loads(pid_file.read_text(encoding="utf-8"))+ except Exception:+ return+ pid = info.get("pid") if isinstance(info, dict) else None+ port = info.get("port") if isinstance(info, dict) else None+ if not isinstance(pid, int) or not isinstance(port, int):+ return+ command = runtime.get_process_command(pid)+ trusted_pid_file = bool(command and cls._is_opencode_serve_cmd(command, port)) or (+ command is None and cls._pid_owns_listening_port(pid, port)+ )+ if trusted_pid_file:+ cls._terminate_pid_tree_sync(pid)+ try:+ pid_file.unlink(missing_ok=True)+ except OSError:+ logger.debug("Failed to clear OpenCode pid file during shutdown", exc_info=True)++ async def restart_for_auth_refresh(self, *, force: bool = False) -> None:"""Terminate the shared server so the next request reloads refreshed auth."""async with self._get_lock():- if self._active_requests > 0 or self._has_active_run_sessions():+ if force:+ self._active_run_sessions.clear()+ if not force and (self._active_requests > 0 or self._has_active_run_sessions()):self._auth_refresh_pending = Truelogger.info("Deferring OpenCode auth refresh restart until %s active request(s) and %s active run(s) finish",diff --git a/modules/agents/service.py b/modules/agents/service.pyindex 9fcfb8121..0328d80b4 100644--- a/modules/agents/service.py+++ b/modules/agents/service.py@@ -31,6 +31,49 @@ class AgentService:# Strong refs to fire-and-forget tasks (e.g. the cancellation tidy) so the# event loop doesn't GC them before they run (asyncio only weak-refs tasks).self._background_tasks: set[asyncio.Task] = set()+ self._backend_ready: dict[str, asyncio.Event] = {}++ def _backend_ready_event(self, backend: str) -> asyncio.Event:+ event = self._backend_ready.get(backend)+ if event is None:+ event = asyncio.Event()+ event.set()+ self._backend_ready[backend] = event+ return event++ def begin_backend_drain(self, backend: str) -> None:+ self._backend_ready_event(backend).clear()++ def end_backend_drain(self, backend: str) -> None:+ self._backend_ready_event(backend).set()++ async def wait_backend_ready(self, backend: str) -> None:+ await self._backend_ready_event(backend).wait()++ async def prepare_backend_restart(self, backend: str) -> None:+ agent = self.agents.get(backend)+ prepare = getattr(agent, "prepare_runtime_restart", None)+ if callable(prepare):+ await prepare()++ def backend_runtime_active(self, backend: str) -> bool:+ if self.activities.has_backend_work(backend):+ return True+ agent = self.agents.get(backend)+ probe = getattr(agent, "runtime_has_active_turns", None)+ if not callable(probe):+ return False+ try:+ return bool(probe())+ except Exception:+ logger.debug("Backend active-runtime probe failed for %s", backend, exc_info=True)+ return True++ def force_end_backend_activities(self, backend: str) -> list[Any]:+ completed = self.activities.end_backend(backend, status="killed")+ for activity in completed:+ self.on_activity_terminal(activity)+ return completeddef register(self, agent: BaseAgent):self.agents[agent.name] = agent@@ -111,9 +154,34 @@ class AgentService:except Exception:logger.debug("Failed to clean up queued reaction on cancel", exc_info=True)raise+ # A restart may have started while this turn waited behind the previous+ # owner of the runtime key. Keep the key lock, wait for cutover, then+ # resolve the current adapter so the queued turn cannot enter the old+ # generation.+ try:+ await self.wait_backend_ready(agent_name)+ agent = self.get(agent_name)+ except BaseException:+ if queued_reaction_task is not None:+ try:+ await queued_reaction_task+ except BaseException:+ pass+ if indicator is not None:+ try:+ await indicator.finish(request)+ except Exception:+ logger.debug("Failed to clean up queued reaction on restart-wait cancel", exc_info=True)+ if gate.lock.locked() and not gate.token:+ gate.lock.release()+ raisegate.token = uuid.uuid4().hexgate.backend = agent.name+ gate.agent = agentgate.runtime_started = False+ gate.task = asyncio.current_task()+ gate.context = request.context+ gate.cancel_tidy_task = Noneself._stamp_runtime_turn(request, runtime_key, gate.token)try:# Register the indicator handle for terminal/cancel cleanup BEFORE the@@ -184,6 +252,7 @@ class AgentService:self.release_runtime_turn(request.context)tidy_task = asyncio.create_task(_tidy_on_cancel())+ gate.cancel_tidy_task = tidy_taskself._background_tasks.add(tidy_task)tidy_task.add_done_callback(self._background_tasks.discard)scheduled = True@@ -244,9 +313,12 @@ class AgentService:self.release_runtime_turn_key(runtime_key, runtime_token)async def handle_stop(self, agent_name: str, request: AgentRequest) -> bool:- agent = self.get(agent_name)- runtime_key = self._runtime_turn_key(agent, request)+ current_agent = self.get(agent_name)+ payload = getattr(request.context, "platform_specific", None) or {}+ stamped_key = str(payload.get(AGENT_RUNTIME_TURN_KEY) or "").strip()+ runtime_key = stamped_key or self._runtime_turn_key(current_agent, request)gate = self._turn_gates.get(runtime_key)+ agent = gate.agent if gate is not None and gate.agent is not None else current_agentif gate is not None and gate.token:self._stamp_runtime_turn(request, runtime_key, gate.token)handled = await agent.handle_stop(request)@@ -399,9 +471,47 @@ class AgentService:gate.token = ""gate.backend = ""gate.runtime_started = False+ gate.agent = None+ gate.task = None+ gate.context = Noneif gate.lock.locked():gate.lock.release()+ async def force_cancel_backend_turns(self, backend: str) -> None:+ """Cancel every foreground owner and emit a terminal outcome before cutover."""+ owned = [+ (runtime_key, gate, gate.token)+ for runtime_key, gate in self._turn_gates.items()+ if gate.backend == backend and gate.token+ ]+ tasks = {+ gate.task+ for _runtime_key, gate, _token in owned+ if gate.task is not None and not gate.task.done()+ }+ for task in tasks:+ task.cancel()+ if tasks:+ await asyncio.wait(tasks, timeout=2.0)+ tidies = {+ gate.cancel_tidy_task+ for _runtime_key, gate, _token in owned+ if gate.cancel_tidy_task is not None and not gate.cancel_tidy_task.done()+ }+ if tidies:+ await asyncio.wait(tidies, timeout=2.0)+ emit = getattr(self.controller, "emit_agent_message", None)+ for runtime_key, gate, token in owned:+ if gate.token != token:+ continue+ context = gate.context+ if context is not None and callable(emit):+ try:+ await emit(context, "result", "", is_error=True, level="silent")+ except Exception:+ logger.debug("Failed to settle forced backend turn %s", runtime_key, exc_info=True)+ self.release_runtime_turn_key(runtime_key, token)+def emit_matches_runtime_turn(self, context: Any) -> bool:payload = getattr(context, "platform_specific", None) or {}runtime_key = str(payload.get(AGENT_RUNTIME_TURN_KEY) or "").strip()@@ -419,7 +529,9 @@ class AgentService:runtime_key = str(payload.get(AGENT_RUNTIME_TURN_KEY) or "").strip()gate = self._turn_gates.get(runtime_key) if runtime_key else Nonebackend = gate.backend if gate else None- agent = self.agents.get(backend) if backend else None+ agent = getattr(gate, "agent", None) if gate is not None else None+ if agent is None and backend:+ agent = self.agents.get(backend)if agent is None:return Noneprobe = getattr(agent, "backend_alive", None)@@ -528,3 +640,7 @@ class _RuntimeTurnGate:token: str = ""backend: str = ""runtime_started: bool = False+ agent: BaseAgent | None = None+ task: asyncio.Task | None = None+ context: Any = None+ cancel_tidy_task: asyncio.Task | None = Nonediff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.pyindex 0e9c6540d..9a89b0677 100644--- a/tests/test_agent_auth_service.py+++ b/tests/test_agent_auth_service.py@@ -1457,6 +1457,45 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsynrequest_timeout_seconds=60,)+ async def test_opencode_agent_force_refresh_restarts_after_global_config_change(self):+ from config.v2_compat import OpenCodeCompatConfig+ from modules.agents.opencode.agent import OpenCodeAgent++ old_config = OpenCodeCompatConfig(+ enabled=True,+ binary="/opencode",+ port=4096,+ request_timeout_seconds=60,+ )+ new_config = OpenCodeCompatConfig(+ enabled=True,+ binary="/opencode",+ port=4096,+ request_timeout_seconds=60,+ )+ previous_server = SimpleNamespace(+ binary="/opencode",+ port=4096,+ request_timeout_seconds=60,+ refresh_global_config=AsyncMock(return_value=True),+ detach_after_deferred_refresh=AsyncMock(),+ reload_runtime_config=AsyncMock(),+ )+ agent = OpenCodeAgent.__new__(OpenCodeAgent)+ agent.opencode_config = old_config+ agent.controller = SimpleNamespace(config=SimpleNamespace(opencode=old_config))+ agent._client_manager = SimpleNamespace(reset_config=AsyncMock(return_value=previous_server))++ await agent.refresh_runtime_config(new_config, force=True)++ previous_server.refresh_global_config.assert_not_awaited()+ previous_server.detach_after_deferred_refresh.assert_awaited_once_with(force=True)+ previous_server.reload_runtime_config.assert_awaited_once_with(+ binary="/opencode",+ port=4096,+ request_timeout_seconds=60,+ )+async def test_opencode_agent_refresh_runtime_config_attaches_uncached_server(self):from config.v2_compat import OpenCodeCompatConfigfrom modules.agents.opencode.agent import OpenCodeAgent@@ -1589,7 +1628,7 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsynself.assertEqual(governor.mode, "enabled")self.assertEqual(governor.config["agent_group_name"], "web-oauth-agents")- async def test_opencode_agent_refresh_runtime_config_does_not_restart_uncached_adopted_server_on_refresh_miss(self):+ async def test_opencode_agent_refresh_runtime_config_restarts_uncached_adopted_server_on_refresh_miss(self):from config.v2_compat import OpenCodeCompatConfigfrom modules.agents.opencode.agent import OpenCodeAgentfrom modules.agents.opencode.server import OpenCodeServerManager@@ -1629,8 +1668,12 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsynawait agent.refresh_runtime_config(new_config)live_server.refresh_global_config.assert_awaited_once()- live_server.detach_after_deferred_refresh.assert_not_awaited()- live_server.reload_runtime_config.assert_not_awaited()+ live_server.detach_after_deferred_refresh.assert_awaited_once()+ live_server.reload_runtime_config.assert_awaited_once_with(+ binary="/opencode",+ port=4096,+ request_timeout_seconds=60,+ )async def test_opencode_agent_refresh_runtime_config_restarts_when_runtime_changes(self):from config.v2_compat import OpenCodeCompatConfigdiff --git a/tests/test_agent_service.py b/tests/test_agent_service.pyindex 5ab521132..d8288a3b8 100644--- a/tests/test_agent_service.py+++ b/tests/test_agent_service.py@@ -4,6 +4,8 @@ import asynciofrom types import SimpleNamespacefrom unittest.mock import AsyncMock, Mock+import pytest+from modules.agents.service import AgentService@@ -248,6 +250,127 @@ def test_agent_service_serializes_same_runtime_until_terminal_release() -> None:asyncio.run(_run())+def test_agent_service_restart_barrier_preserves_same_runtime_fifo() -> None:+ async def _run():+ controller = _Controller()+ service = AgentService(controller=controller)+ controller.agent_service = service+ agent = _RuntimeAgent()+ service.register(agent)+ service.begin_backend_drain("claude")++ first_request = _request("first")+ second_request = _request("second")+ first = asyncio.create_task(service.handle_message("claude", first_request))+ await asyncio.sleep(0)+ second = asyncio.create_task(service.handle_message("claude", second_request))+ await asyncio.sleep(0.01)++ assert agent.started == []+ assert service.runtime_turn_tokens_for_backend("claude") == {}++ service.end_backend_drain("claude")+ await asyncio.sleep(0)+ assert agent.started == ["first"]++ service.release_runtime_turn(first_request.context)+ await asyncio.wait_for(first, timeout=3)+ await asyncio.wait_for(second, timeout=3)+ assert agent.started == ["first", "second"]++ asyncio.run(_run())+++def test_agent_service_restart_wait_releases_gate_when_backend_disappears() -> None:+ async def _run():+ controller = _Controller()+ service = AgentService(controller=controller)+ controller.agent_service = service+ service.register(_RuntimeAgent())+ service.begin_backend_drain("claude")++ request = _request("waiting")+ task = asyncio.create_task(service.handle_message("claude", request))+ await asyncio.sleep(0.01)+ gate = service._turn_gates[request.composite_session_id]+ assert gate.lock.locked() is True+ assert gate.token == ""++ service.agents.pop("claude")+ service.end_backend_drain("claude")+ with pytest.raises(KeyError):+ await task+ assert gate.lock.locked() is False++ asyncio.run(_run())+++def test_force_end_backend_activities_settles_pending_runs() -> None:+ settled = []+ controller = SimpleNamespace(+ scheduled_task_service=SimpleNamespace(settle_activity_runs=settled.append),+ )+ service = AgentService(controller=controller)+ service.activities.start(+ backend="claude",+ runtime_key="runtime-1",+ session_id="ses-1",+ activity_id="task-active",+ kind="background_task",+ run_id="run-active",+ )+ service.activities.start(+ backend="claude",+ runtime_key="runtime-2",+ session_id="ses-2",+ activity_id="task-pending",+ kind="background_task",+ run_id="run-pending",+ )+ service.activities.complete(+ backend="claude",+ runtime_key="runtime-2",+ activity_id="task-pending",+ status="completed",+ expects_output=True,+ )++ service.force_end_backend_activities("claude")++ assert sorted((item.id, item.status) for item in settled) == [+ ("task-active", "killed"),+ ("task-pending", "killed"),+ ]+++def test_force_cancel_backend_turns_emits_terminal_before_release() -> None:+ async def _run():+ controller = _Controller()+ controller.emit_agent_message = AsyncMock()+ service = AgentService(controller=controller)+ controller.agent_service = service+ agent = _RuntimeAgent(asyncio.Event())+ service.register(agent)+ request = _request("first")+ task = asyncio.create_task(service.handle_message("claude", request))+ await asyncio.sleep(0)+ assert service.runtime_turn_tokens_for_backend("claude")++ await service.force_cancel_backend_turns("claude")++ assert task.cancelled()+ controller.emit_agent_message.assert_awaited_once_with(+ request.context,+ "result",+ "",+ is_error=True,+ level="silent",+ )+ assert service.runtime_turn_tokens_for_backend("claude") == {}++ asyncio.run(_run())++class _RecordingIndicator:"""Records the queued/promote/finish reaction calls the gate drives."""diff --git a/tests/test_backend_restart.py b/tests/test_backend_restart.pynew file mode 100644index 000000000..769364d2d--- /dev/null+++ b/tests/test_backend_restart.py@@ -0,0 +1,163 @@+from __future__ import annotations++import asyncio+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock++import pytest++from core.backend_restart import BackendRestartCoordinator+++class _AgentService:+ def __init__(self) -> None:+ self.active = False+ self.runtime_active = False+ self.draining = False++ def begin_backend_drain(self, backend: str) -> None:+ assert backend == "opencode"+ self.draining = True++ def end_backend_drain(self, backend: str) -> None:+ assert backend == "opencode"+ self.draining = False++ async def prepare_backend_restart(self, backend: str) -> None:+ assert backend == "opencode"++ def runtime_turn_tokens_for_backend(self, backend: str) -> dict[str, str]:+ return {"session:key": "token"} if self.active else {}++ def backend_runtime_active(self, backend: str) -> bool:+ return self.runtime_active++ def force_end_backend_activities(self, backend: str) -> list:+ assert backend == "opencode"+ return []++ async def force_cancel_backend_turns(self, backend: str) -> None:+ assert backend == "opencode"+++def _controller(service: _AgentService):+ session_turns = SimpleNamespace(+ begin_backend_drain=Mock(),+ end_backend_drain=AsyncMock(),+ active_session_ids_for_backend=Mock(+ side_effect=lambda _backend: {"ses-1"} if service.active else set()+ ),+ active_runtime_session_ids_for_backend=Mock(+ side_effect=lambda _backend: {"ses-1"} if service.active else set()+ ),+ release_for_backend_refresh=AsyncMock(),+ )+ return SimpleNamespace(agent_service=service, session_turns=session_turns)+++def test_restart_drains_active_turn_before_refresh() -> None:+ async def run() -> None:+ service = _AgentService()+ service.active = True+ controller = _controller(service)+ refresh = AsyncMock()+ coordinator = BackendRestartCoordinator(controller, refresh, drain_timeout=1, poll_interval=0.001)++ assert await coordinator.request_restart("opencode") == "draining"+ assert service.draining is True+ refresh.assert_not_awaited()++ service.active = False+ await coordinator.wait("opencode")++ refresh.assert_awaited_once_with("opencode", False)+ controller.session_turns.release_for_backend_refresh.assert_not_awaited()+ controller.session_turns.end_backend_drain.assert_awaited_once_with("opencode", resume_deferred=True)+ assert service.draining is False++ asyncio.run(run())+++def test_restart_timeout_forces_cutover_and_releases_workbench_turns() -> None:+ async def run() -> None:+ service = _AgentService()+ service.active = True+ service.runtime_active = True+ controller = _controller(service)++ async def refresh(_backend: str, forced: bool) -> None:+ assert forced is True+ service.runtime_active = False++ coordinator = BackendRestartCoordinator(controller, refresh, drain_timeout=0, poll_interval=0.001)++ await coordinator.request_restart("opencode")+ await coordinator.wait("opencode")++ controller.session_turns.release_for_backend_refresh.assert_awaited_once_with(+ backend="opencode",+ base_session_ids={"ses-1"},+ )+ assert service.draining is False++ asyncio.run(run())+++def test_concurrent_restart_requests_coalesce() -> None:+ async def run() -> None:+ service = _AgentService()+ service.active = True+ controller = _controller(service)+ refresh = AsyncMock()+ coordinator = BackendRestartCoordinator(controller, refresh, drain_timeout=1, poll_interval=0.001)++ first, second = await asyncio.gather(+ coordinator.request_restart("opencode"),+ coordinator.request_restart("opencode"),+ )+ assert first == second == "draining"+ controller.session_turns.begin_backend_drain.assert_called_once_with("opencode")++ service.active = False+ await coordinator.wait("opencode")+ refresh.assert_awaited_once()++ asyncio.run(run())+++def test_refresh_failure_reopens_barrier() -> None:+ async def run() -> None:+ service = _AgentService()+ service.active = True+ controller = _controller(service)+ refresh = AsyncMock(side_effect=RuntimeError("refresh failed"))+ coordinator = BackendRestartCoordinator(controller, refresh, drain_timeout=1, poll_interval=0.001)++ await coordinator.request_restart("opencode")+ service.active = False+ with pytest.raises(RuntimeError, match="refresh failed"):+ await coordinator.wait("opencode")++ assert service.draining is False+ controller.session_turns.end_backend_drain.assert_awaited_once_with("opencode", resume_deferred=False)++ asyncio.run(run())+++def test_idle_refresh_failure_is_propagated_before_ack() -> None:+ async def run() -> None:+ service = _AgentService()+ controller = _controller(service)+ refresh = AsyncMock(side_effect=RuntimeError("invalid config"))+ coordinator = BackendRestartCoordinator(controller, refresh, drain_timeout=1)++ with pytest.raises(RuntimeError, match="invalid config"):+ await coordinator.request_restart("opencode")++ assert service.draining is False+ controller.session_turns.end_backend_drain.assert_awaited_once_with(+ "opencode",+ resume_deferred=False,+ )++ asyncio.run(run())diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 7a05d0fc2..f2ed2d3aa 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -21,7 +21,7 @@ import sysimport tempfileimport typesfrom pathlib import Path-from unittest.mock import AsyncMock, MagicMock+from unittest.mock import AsyncMock, MagicMock, Mockimport httpxfrom sqlalchemy import select@@ -994,6 +994,7 @@ def test_release_for_backend_refresh_cancels_matching_turn_and_sets_idle():"agent_session_target": {"agent_backend": "codex"},}manager.in_flight["ses_codex"] = session_turns.Turn(task=task, context=ctx)+ manager.begin_backend_drain("codex")released = await manager.release_for_backend_refresh(backend="codex",@@ -1010,6 +1011,7 @@ def test_release_for_backend_refresh_cancels_matching_turn_and_sets_idle():assert released == 1assert cancelled is Trueassert statuses == [("ses_codex", "idle")]+ assert manager._deferred_restart_sessions == {"codex": {"ses_codex"}}def test_release_for_backend_refresh_leaves_other_backend_turn_running():@@ -1049,6 +1051,102 @@ def test_release_for_backend_refresh_leaves_other_backend_turn_running():assert statuses == []+def test_backend_drain_queues_idle_session_without_dispatching():+ controller = _build_controller_double()+ manager = session_turns.SessionTurnManager(controller)+ enqueue = Mock()+ context = MessageContext(user_id="U", channel_id="ses_codex", platform="avibe")+ context.platform_specific = {+ "agent_session_id": "ses_codex",+ "agent_session_target": {"agent_backend": "codex"},+ }++ async def _go():+ manager.begin_backend_drain("codex")+ return await manager.submit("ses_codex", context, "next", enqueue=enqueue)++ result = asyncio.run(_go())++ assert result == "enqueued"+ enqueue.assert_called_once_with()+ assert manager.is_in_flight("ses_codex") is False+ assert manager._deferred_restart_sessions == {"codex": {"ses_codex"}}+++def test_backend_drain_resolves_inherited_default_agent_backend():+ controller = _build_controller_double()+ controller.resolve_agent_for_context = Mock(return_value="codex")+ manager = session_turns.SessionTurnManager(controller)+ enqueue = Mock()+ context = MessageContext(user_id="U", channel_id="ses_default", platform="avibe")+ context.platform_specific = {+ "agent_session_id": "ses_default",+ "agent_session_target": {"agent_name": None, "agent_backend": None},+ }++ async def _go():+ manager.begin_backend_drain("codex")+ return await manager.submit("ses_default", context, "next", enqueue=enqueue)++ assert asyncio.run(_go()) == "enqueued"+ enqueue.assert_called_once_with()+ controller.resolve_agent_for_context.assert_called_once_with(context)+ assert manager._deferred_restart_sessions == {"codex": {"ses_default"}}+++def test_backend_drain_flushes_deferred_session_after_cutover():+ controller = _build_controller_double()+ manager = session_turns.SessionTurnManager(controller)+ manager.flush_queue = AsyncMock(return_value=True)+ manager.begin_backend_drain("codex")+ manager._deferred_restart_sessions["codex"].add("ses_codex")++ asyncio.run(manager.end_backend_drain("codex"))++ manager.flush_queue.assert_awaited_once_with("ses_codex")+ assert "codex" not in manager._draining_backends+++def test_backend_drain_blocks_direct_queue_flush():+ controller = _build_controller_double()+ context = MessageContext(user_id="U", channel_id="ses_codex", platform="avibe")+ context.platform_specific = {+ "agent_session_id": "ses_codex",+ "agent_session_target": {"agent_backend": "codex"},+ }+ manager = session_turns.SessionTurnManager(controller, build_context=lambda _session_id: context)+ manager._run = AsyncMock() # type: ignore[method-assign]+ manager.begin_backend_drain("codex")++ assert asyncio.run(manager.flush_queue("ses_codex")) is False+ manager._run.assert_not_awaited()+ assert manager._deferred_restart_sessions == {"codex": {"ses_codex"}}+++def test_stop_during_backend_drain_keeps_existing_queue_parked():+ controller = _build_controller_double()+ manager = session_turns.SessionTurnManager(controller)+ context = MessageContext(user_id="U", channel_id="ses_codex", platform="avibe")+ context.platform_specific = {+ "agent_session_id": "ses_codex",+ "agent_session_target": {"agent_backend": "codex"},+ }++ async def _go():+ task = asyncio.create_task(asyncio.sleep(60))+ manager.in_flight["ses_codex"] = session_turns.Turn(task=task, context=context)+ manager.begin_backend_drain("codex")+ manager._deferred_restart_sessions["codex"].add("ses_codex")+ result = await manager.cancel("ses_codex")+ await asyncio.gather(task, return_exceptions=True)+ return result++ result = asyncio.run(_go())++ assert result["status"] == "cancel_requested"+ assert manager._deferred_restart_sessions == {"codex": set()}++# ---------------------------------------------------------------------# Dispatcher hook contract# ---------------------------------------------------------------------diff --git a/tests/test_opencode_server.py b/tests/test_opencode_server.pyindex 598494abe..1faf94178 100644--- a/tests/test_opencode_server.py+++ b/tests/test_opencode_server.py@@ -7,7 +7,7 @@ import tempfileimport typesimport unittestfrom pathlib import Path-from unittest.mock import AsyncMock, patch+from unittest.mock import AsyncMock, Mock, patchsys.path.insert(0, str(Path(__file__).resolve().parents[1]))@@ -117,6 +117,51 @@ class _FakeSession:class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):+ def test_terminate_instance_sync_stops_unadopted_managed_server(self):+ with tempfile.TemporaryDirectory() as tmp_dir:+ pid_file = Path(tmp_dir) / "opencode_server.json"+ pid_file.write_text(json.dumps({"pid": 4321, "port": 4096}), encoding="utf-8")+ terminate = Mock(return_value=True)+ previous = OpenCodeServerManager._instance+ OpenCodeServerManager._instance = None+ try:+ with (+ patch.object(SERVER_MODULE.paths, "get_logs_dir", return_value=Path(tmp_dir)),+ patch.object(+ SERVER_MODULE.runtime,+ "get_process_command",+ return_value="opencode serve --port=4096",+ ),+ patch.object(OpenCodeServerManager, "_terminate_pid_tree_sync", terminate),+ ):+ OpenCodeServerManager.terminate_instance_sync()+ finally:+ OpenCodeServerManager._instance = previous++ terminate.assert_called_once_with(4321)+ self.assertFalse(pid_file.exists())++ def test_terminate_instance_sync_trusts_pid_file_port_owner_without_command(self):+ with tempfile.TemporaryDirectory() as tmp_dir:+ pid_file = Path(tmp_dir) / "opencode_server.json"+ pid_file.write_text(json.dumps({"pid": 4321, "port": 4096}), encoding="utf-8")+ terminate = Mock(return_value=True)+ previous = OpenCodeServerManager._instance+ OpenCodeServerManager._instance = None+ try:+ with (+ patch.object(SERVER_MODULE.paths, "get_logs_dir", return_value=Path(tmp_dir)),+ patch.object(SERVER_MODULE.runtime, "get_process_command", return_value=None),+ patch.object(OpenCodeServerManager, "_pid_owns_listening_port", return_value=True),+ patch.object(OpenCodeServerManager, "_terminate_pid_tree_sync", terminate),+ ):+ OpenCodeServerManager.terminate_instance_sync()+ finally:+ OpenCodeServerManager._instance = previous++ terminate.assert_called_once_with(4321)+ self.assertFalse(pid_file.exists())+def test_percent_encode_path_preserves_round_trip_sensitive_paths(self):self.assertEqual(SERVER_MODULE._percent_encode_path("/tmp/小说"),@@ -140,6 +185,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):manager._restart_for_auth_refresh_locked = AsyncMock(side_effect=lambda: restarted.append(True)) # type: ignore[method-assign]manager._start_server = AsyncMock(side_effect=lambda: started.append(True)) # type: ignore[method-assign]manager._read_pid_file = lambda: {"pid": 123, "port": 4096, "caller_context_path": manager._caller_context_path(), "owner_pid": SERVER_MODULE._CURRENT_OWNER_PID} # type: ignore[method-assign]+ manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]with patch.object(SERVER_MODULE,@@ -161,6 +207,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]manager._start_server = AsyncMock() # type: ignore[method-assign]manager._read_pid_file = lambda: {"pid": 123, "port": 4096, "caller_context_path": manager._caller_context_path(), "owner_pid": SERVER_MODULE._CURRENT_OWNER_PID} # type: ignore[method-assign]+ manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]with patch.object(SERVER_MODULE,@@ -183,6 +230,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):manager._restart_for_auth_refresh_locked = AsyncMock(side_effect=lambda: restarted.append(True)) # type: ignore[method-assign]manager._start_server = AsyncMock(side_effect=lambda: started.append(True)) # type: ignore[method-assign]manager._read_pid_file = lambda: {"pid": 123, "port": 4096, "active_run_sessions": []} # type: ignore[method-assign]+ manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]with patch.object(SERVER_MODULE,@@ -203,6 +251,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]manager._start_server = AsyncMock() # type: ignore[method-assign]manager._read_pid_file = lambda: {"pid": 123, "port": 4096, "active_run_sessions": ["ses-active"]} # type: ignore[method-assign]+ manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]with patch.object(SERVER_MODULE,@@ -223,6 +272,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]manager._start_server = AsyncMock() # type: ignore[method-assign]manager._read_pid_file = lambda: {"pid": 123, "port": 4096} # type: ignore[method-assign]+ manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]with patch.object(SERVER_MODULE,@@ -240,6 +290,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):manager = OpenCodeServerManager(binary="opencode", port=4096)with tempfile.TemporaryDirectory() as tmp_dir:manager._pid_file = Path(tmp_dir) / "opencode_server.json"+ manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]manager._write_pid_file(123)await manager.mark_run_active("ses-active")@@ -1292,6 +1343,83 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):self.assertIsNotNone(manager._process)self.assertEqual(manager._base_url, "http://127.0.0.1:4096")+ async def test_restart_for_auth_refresh_force_clears_stale_activity(self):+ manager = OpenCodeServerManager(binary="opencode", port=4096)+ manager._active_requests = 2+ manager._active_run_sessions.add("sess-stale")+ manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]++ await manager.restart_for_auth_refresh(force=True)++ self.assertEqual(manager._active_requests, 2)+ self.assertEqual(manager._active_run_sessions, set())+ manager._restart_for_auth_refresh_locked.assert_awaited_once()++ def test_runtime_has_active_turns_reads_adopted_pid_state(self):+ manager = OpenCodeServerManager(binary="opencode", port=4096)+ manager._read_pid_file = lambda: { # type: ignore[method-assign]+ "pid": 321,+ "port": 4096,+ "active_run_sessions": ["sess-live"],+ }+ manager._pid_exists = lambda pid: pid == 321 # type: ignore[method-assign]+ manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]++ self.assertTrue(manager.runtime_has_active_turns())++ def test_runtime_ignores_active_runs_from_reused_pid(self):+ manager = OpenCodeServerManager(binary="opencode", port=4096)+ manager._read_pid_file = lambda: { # type: ignore[method-assign]+ "pid": 321,+ "port": 4096,+ "active_run_sessions": ["sess-stale"],+ }+ manager._pid_exists = lambda pid: pid == 321 # type: ignore[method-assign]+ manager._get_pid_command = lambda pid: "python unrelated.py" # type: ignore[method-assign]++ self.assertFalse(manager.runtime_has_active_turns())++ def test_terminate_sync_falls_back_to_tracked_process_without_pid_file(self):+ manager = OpenCodeServerManager(binary="opencode", port=4096)+ manager._process = types.SimpleNamespace(pid=654, returncode=None)+ manager._read_pid_file = lambda: None # type: ignore[method-assign]+ manager._pid_exists = lambda pid: pid == 654 # type: ignore[method-assign]+ manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]+ manager._clear_pid_file = Mock() # type: ignore[method-assign]+ manager._terminate_pid_tree_sync = Mock(return_value=True) # type: ignore[method-assign]++ manager.terminate_sync()++ manager._terminate_pid_tree_sync.assert_called_once_with(654)+ self.assertIsNone(manager._process)++ def test_terminate_sync_does_not_kill_reused_tracked_pid(self):+ manager = OpenCodeServerManager(binary="opencode", port=4096)+ manager._process = types.SimpleNamespace(pid=654, returncode=None)+ manager._read_pid_file = lambda: None # type: ignore[method-assign]+ manager._pid_exists = lambda pid: pid == 654 # type: ignore[method-assign]+ manager._get_pid_command = lambda pid: "python unrelated.py" # type: ignore[method-assign]+ manager._clear_pid_file = Mock() # type: ignore[method-assign]+ manager._terminate_pid_tree_sync = Mock(return_value=True) # type: ignore[method-assign]++ manager.terminate_sync()++ manager._terminate_pid_tree_sync.assert_not_called()+ self.assertIsNone(manager._process)++ def test_terminate_sync_trusts_pid_file_port_owner_without_command(self):+ manager = OpenCodeServerManager(binary="opencode", port=4096)+ manager._read_pid_file = lambda: {"pid": 654, "port": 4096} # type: ignore[method-assign]+ manager._pid_exists = lambda pid: pid == 654 # type: ignore[method-assign]+ manager._get_pid_command = lambda pid: None # type: ignore[method-assign]+ manager._pid_owns_listening_port = lambda pid, port: pid == 654 and port == 4096 # type: ignore[method-assign]+ manager._clear_pid_file = Mock() # type: ignore[method-assign]+ manager._terminate_pid_tree_sync = Mock(return_value=True) # type: ignore[method-assign]++ manager.terminate_sync()++ manager._terminate_pid_tree_sync.assert_called_once_with(654)+async def test_request_scope_does_not_restart_pending_auth_refresh_while_run_active(self):manager = OpenCodeServerManager(binary="opencode", port=4096)manager._auth_refresh_pending = Truediff --git a/tests/test_session_activities.py b/tests/test_session_activities.pyindex 41a01e4a4..5b418b4b4 100644--- a/tests/test_session_activities.py+++ b/tests/test_session_activities.py@@ -178,3 +178,38 @@ def test_only_owned_non_detached_activities_block_run_completion():status="completed",)assert registry.has_blocking_run_activity("run-1") is False+++def test_force_end_backend_settles_active_and_discards_pending_output():+ registry = SessionActivityRegistry()+ registry.start(+ backend="claude",+ runtime_key="runtime-1",+ session_id="ses-1",+ activity_id="task-active",+ kind="background_task",+ )+ registry.start(+ backend="claude",+ runtime_key="runtime-2",+ session_id="ses-2",+ activity_id="task-complete",+ kind="background_task",+ )+ registry.complete(+ backend="claude",+ runtime_key="runtime-2",+ activity_id="task-complete",+ status="completed",+ expects_output=True,+ )++ assert registry.has_backend_work("claude") is True+ completed = registry.end_backend("claude", status="killed")++ assert sorted((item.id, item.status) for item in completed) == [+ ("task-active", "killed"),+ ("task-complete", "killed"),+ ]+ assert registry.has_backend_work("claude") is False+ assert registry.claim_completed_output("claude", "runtime-2") is None