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): optimize restart timing and tunnel continuity (#519)
Call White4d91d35a899b
diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.pyindex baa421b51..b700e135d 100644--- a/tests/test_remote_access_vibe_cloud.py+++ b/tests/test_remote_access_vibe_cloud.py@@ -586,12 +586,34 @@ def test_status_heartbeat_can_retry_after_thread_start_failure(monkeypatch) -> Ndef test_stop_ui_continues_when_remote_access_stop_fails(monkeypatch, tmp_path) -> None:monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))stop_calls = []+ timings = {}monkeypatch.setattr(remote_access, "stop", lambda: {"ok": False, "error": "cloudflared_stop_failed"})monkeypatch.setattr(runtime, "stop_process", lambda pid_path: stop_calls.append(pid_path) or True)- assert runtime.stop_ui() is False+ assert runtime.stop_ui(timings) is Falseassert stop_calls == [paths.get_runtime_ui_pid_path()]+ assert "stop_remote_access_seconds" in timings+ assert "stop_ui_process_seconds" in timings+ assert "stop_ui_seconds" in timings+++def test_stop_ui_can_skip_remote_access_stop(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ stop_calls = []+ timings = {}++ monkeypatch.setattr(+ remote_access,+ "stop",+ lambda: (_ for _ in ()).throw(AssertionError("remote access should stay running")),+ )+ monkeypatch.setattr(runtime, "stop_process", lambda pid_path: stop_calls.append(pid_path) or True)++ assert runtime.stop_ui(timings, stop_remote_access=False) is True+ assert stop_calls == [paths.get_runtime_ui_pid_path()]+ assert timings["stop_remote_access_seconds"] == 0.0+ assert timings["stop_remote_access_skipped"] is Truedef test_cloudflared_pid_detection_handles_quoted_paths_with_spaces(monkeypatch) -> None:diff --git a/tests/test_restart_supervisor.py b/tests/test_restart_supervisor.pyindex 8373f9f80..6649ccaed 100644--- a/tests/test_restart_supervisor.py+++ b/tests/test_restart_supervisor.py@@ -1,12 +1,31 @@from __future__ import annotations-import subprocess+import threading+from types import SimpleNamespacefrom config import pathsfrom vibe import restart_supervisorfrom vibe import runtime+def _fake_start_runtime(calls, service_pid: int = 222, ui_pid: int = 333):+ calls.append("start_runtime")+ runtime.write_status("running", f"pid={service_pid}", service_pid, ui_pid)+ return service_pid, ui_pid+++def _fake_stop_runtime(calls, *, ui_stopped=True, ui_pid=None, service_stopped=True):+ calls.append("stop_runtime")+ return (+ ui_stopped,+ {"stop_remote_access_seconds": 0.01, "stop_remote_access_skipped": True},+ 0.02,+ ui_pid,+ service_stopped,+ 0.03,+ )++def test_schedule_restart_spawns_supervisor_and_records_status(monkeypatch, tmp_path):monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))paths.ensure_data_dirs()@@ -73,30 +92,27 @@ def test_restart_job_stops_and_starts_service(monkeypatch, tmp_path):paths.get_runtime_pid_path().write_text("111", encoding="utf-8")calls = []- monkeypatch.setattr(runtime, "stop_ui", lambda: calls.append("stop_ui") or True)- monkeypatch.setattr(runtime, "stop_service", lambda: calls.append("stop_service") or True)- monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))- monkeypatch.setattr(restart_supervisor, "get_restart_invocation_command", lambda vibe_path=None: ["/bin/vibe", "restart"])- monkeypatch.setattr(restart_supervisor, "get_restart_environment", lambda vibe_path=None: None)-- def fake_run(command, **kwargs):- calls.append(("run", command))- paths.get_runtime_pid_path().write_text("222", encoding="utf-8")- return subprocess.CompletedProcess(command, 0)-- monkeypatch.setattr(restart_supervisor.subprocess, "run", fake_run)+ monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda: _fake_stop_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda: _fake_start_runtime(calls))monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)rc = restart_supervisor._run_restart_job(job_id="jobabc", delay_seconds=0, vibe_path="/bin/vibe", trigger="test")assert rc == 0- assert calls == ["stop_ui", "stop_service", ("run", ["/bin/vibe", "start"])]+ assert calls == ["stop_runtime", "start_runtime"]status = runtime.read_json(runtime.get_restart_status_path())assert status["ok"] is Trueassert status["state"] == "succeeded"assert status["old_pid"] == 111assert status["new_pid"] == 222+ assert status["stage_durations"]["stop_remote_access_seconds"] == 0.01+ assert status["stage_durations"]["stop_remote_access_skipped"] is True+ assert "stop_ui_total_seconds" in status["stage_durations"]+ assert "stop_service_seconds" in status["stage_durations"]+ assert "stop_runtime_seconds" in status["stage_durations"]+ assert "start_runtime_seconds" in status["stage_durations"]+ assert "restart_total_seconds" in status["stage_durations"]def test_restart_job_prepares_show_runtime_after_service_start(monkeypatch, tmp_path):@@ -105,18 +121,15 @@ def test_restart_job_prepares_show_runtime_after_service_start(monkeypatch, tmp_paths.get_runtime_pid_path().write_text("111", encoding="utf-8")calls = []- monkeypatch.setattr(runtime, "stop_ui", lambda: calls.append("stop_ui") or True)- monkeypatch.setattr(runtime, "stop_service", lambda: calls.append("stop_service") or True)+ monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda: _fake_stop_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda: _fake_start_runtime(calls))monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))- monkeypatch.setattr(restart_supervisor, "get_restart_invocation_command", lambda vibe_path=None: ["/bin/vibe", "restart"])monkeypatch.setattr(restart_supervisor, "get_restart_command", lambda vibe_path=None: ["/bin/vibe"])monkeypatch.setattr(restart_supervisor, "get_restart_environment", lambda vibe_path=None: None)def fake_run(command, **kwargs):calls.append(("run", command))- if command == ["/bin/vibe", "start"]:- paths.get_runtime_pid_path().write_text("222", encoding="utf-8")- return subprocess.CompletedProcess(command, 0)+ return SimpleNamespace(returncode=0)monkeypatch.setattr(restart_supervisor.subprocess, "run", fake_run)monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)@@ -132,9 +145,8 @@ def test_restart_job_prepares_show_runtime_after_service_start(monkeypatch, tmp_assert rc == 0assert calls == [- "stop_ui",- "stop_service",- ("run", ["/bin/vibe", "start"]),+ "stop_runtime",+ "start_runtime",("run", ["/bin/vibe", "runtime", "prepare", "--strict"]),]assert runtime.read_json(runtime.get_restart_status_path())["state"] == "succeeded"@@ -146,16 +158,18 @@ def test_restart_job_aborts_when_stop_fails(monkeypatch, tmp_path):paths.get_runtime_pid_path().write_text("111", encoding="utf-8")calls = []- monkeypatch.setattr(runtime, "stop_ui", lambda: calls.append("stop_ui") or True)- monkeypatch.setattr(runtime, "stop_service", lambda: calls.append("stop_service") or False)+ monkeypatch.setattr(+ restart_supervisor,+ "_stop_runtime_for_restart",+ lambda: _fake_stop_runtime(calls, service_stopped=False),+ )monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 111)- monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))monkeypatch.setattr(restart_supervisor.subprocess, "run", lambda *args, **kwargs: calls.append("run"))rc = restart_supervisor._run_restart_job(job_id="jobdef", delay_seconds=0, vibe_path="/bin/vibe", trigger="test")assert rc == 2- assert calls == ["stop_ui", "stop_service"]+ assert calls == ["stop_runtime"]status = runtime.read_json(runtime.get_restart_status_path())assert status["ok"] is Falseassert status["state"] == "failed"@@ -168,25 +182,19 @@ def test_restart_job_continues_when_old_pid_already_exited(monkeypatch, tmp_pathpaths.get_runtime_pid_path().write_text("111", encoding="utf-8")calls = []- monkeypatch.setattr(runtime, "stop_ui", lambda: calls.append("stop_ui") or True)- monkeypatch.setattr(runtime, "stop_service", lambda: calls.append("stop_service") or False)- monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))- monkeypatch.setattr(restart_supervisor, "get_restart_invocation_command", lambda vibe_path=None: ["/bin/vibe", "restart"])- monkeypatch.setattr(restart_supervisor, "get_restart_environment", lambda vibe_path=None: None)-- def fake_run(command, **kwargs):- calls.append(("run", command))- paths.get_runtime_pid_path().write_text("222", encoding="utf-8")- return subprocess.CompletedProcess(command, 0)-- monkeypatch.setattr(restart_supervisor.subprocess, "run", fake_run)+ monkeypatch.setattr(+ restart_supervisor,+ "_stop_runtime_for_restart",+ lambda: _fake_stop_runtime(calls, service_stopped=False),+ )+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda: _fake_start_runtime(calls))monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)rc = restart_supervisor._run_restart_job(job_id="joboldgone", delay_seconds=0, vibe_path="/bin/vibe", trigger="test")assert rc == 0- assert calls == ["stop_ui", "stop_service", ("run", ["/bin/vibe", "start"])]+ assert calls == ["stop_runtime", "start_runtime"]assert runtime.read_json(runtime.get_restart_status_path())["state"] == "succeeded"@@ -196,24 +204,17 @@ def test_restart_job_adopts_slow_starting_service_pid(monkeypatch, tmp_path):paths.get_runtime_pid_path().write_text("111", encoding="utf-8")calls = []- monkeypatch.setattr(runtime, "stop_ui", lambda: calls.append("stop_ui") or True)- monkeypatch.setattr(runtime, "stop_service", lambda: calls.append("stop_service") or True)- monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))- monkeypatch.setattr(restart_supervisor, "get_restart_invocation_command", lambda vibe_path=None: ["/bin/vibe", "restart"])- monkeypatch.setattr(restart_supervisor, "get_restart_environment", lambda vibe_path=None: None)-- def fake_run(command, **kwargs):- calls.append(("run", command))- # Simulate `vibe start` returning while the worker is alive but has not- # yet written runtime/vibe.pid.+ monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda: _fake_stop_runtime(calls))+ def slow_start_runtime():+ calls.append("start_runtime")runtime.write_status("starting", "service process is still starting", 222, 333)try:paths.get_runtime_pid_path().unlink()except FileNotFoundError:pass- return subprocess.CompletedProcess(command, 0)+ return 222, 333- monkeypatch.setattr(restart_supervisor.subprocess, "run", fake_run)+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", slow_start_runtime)monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: False)monkeypatch.setattr(runtime, "wait_for_service_pid", lambda pid, timeout: pid == 222)@@ -231,26 +232,112 @@ def test_restart_job_adopts_slow_starting_service_pid(monkeypatch, tmp_path):assert service_status["ui_pid"] == 333-def test_restart_job_marks_start_timeout_failed(monkeypatch, tmp_path):+def test_restart_job_marks_start_runtime_failed(monkeypatch, tmp_path):monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))paths.ensure_data_dirs()paths.get_runtime_pid_path().write_text("111", encoding="utf-8")- monkeypatch.setattr(runtime, "stop_ui", lambda: True)- monkeypatch.setattr(runtime, "stop_service", lambda: True)- monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))- monkeypatch.setattr(restart_supervisor, "get_restart_invocation_command", lambda vibe_path=None: ["/bin/vibe", "restart"])- monkeypatch.setattr(restart_supervisor, "get_restart_environment", lambda vibe_path=None: None)+ monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda: _fake_stop_runtime([]))monkeypatch.setattr(- restart_supervisor.subprocess,- "run",- lambda command, **kwargs: (_ for _ in ()).throw(subprocess.TimeoutExpired(command, 30)),+ restart_supervisor,+ "_start_runtime_processes",+ lambda: (_ for _ in ()).throw(RuntimeError("service refused to start")),)rc = restart_supervisor._run_restart_job(job_id="jobtimeout", delay_seconds=0, vibe_path="/bin/vibe", trigger="test")- assert rc == 4+ assert rc == 1status = runtime.read_json(runtime.get_restart_status_path())assert status["ok"] is Falseassert status["state"] == "failed"- assert "timed out" in status["error"]+ assert "start runtime failed: service refused to start" in status["error"]+ assert "restart_total_seconds" in status["stage_durations"]+++def test_start_runtime_processes_starts_service_and_ui(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ calls = []+ config = SimpleNamespace(+ ui=SimpleNamespace(setup_port=5123),+ has_configured_platform_credentials=lambda: True,+ )++ from core.services import settings as settings_service++ def fake_ensure_data_dirs():+ calls.append("ensure_data_dirs")+ paths.get_runtime_dir().mkdir(parents=True, exist_ok=True)++ monkeypatch.setattr(paths, "ensure_data_dirs", fake_ensure_data_dirs)+ monkeypatch.setattr(settings_service, "load_config", lambda default_factory=None: calls.append("load_config") or config)+ monkeypatch.setattr(+ runtime,+ "start_service",+ lambda wait_for_ready=True, initial_ready_timeout=5.0: calls.append(+ ("start_service", wait_for_ready, initial_ready_timeout)+ )+ or 222,+ )+ monkeypatch.setattr(runtime, "effective_ui_bind_host", lambda cfg: calls.append(("bind_host", cfg)) or "0.0.0.0")+ monkeypatch.setattr(+ runtime,+ "start_ui",+ lambda host, port, wait_for_ready=True: calls.append(("start_ui", host, port, wait_for_ready)) or 333,+ )+ monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)++ service_pid, ui_pid = restart_supervisor._start_runtime_processes()++ assert service_pid == 222+ assert ui_pid == 333+ assert calls == [+ "ensure_data_dirs",+ "load_config",+ ("start_service", False, 0),+ ("bind_host", config),+ ("start_ui", "0.0.0.0", 5123, False),+ ]+ status = runtime.read_status()+ assert status["state"] == "running"+ assert status["service_pid"] == 222+ assert status["ui_pid"] == 333+++def test_stop_runtime_for_restart_stops_ui_and_service(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ calls = []+ ui_entered = threading.Event()+ service_entered = threading.Event()++ def stop_ui(timings=None, *, stop_remote_access=True):+ assert stop_remote_access is False+ calls.append("stop_ui")+ ui_entered.set()+ assert service_entered.wait(timeout=1.0)+ if timings is not None:+ timings["stop_remote_access_seconds"] = 0.01+ return True++ monkeypatch.setattr(runtime, "stop_ui", stop_ui)++ def stop_service():+ calls.append("stop_service")+ service_entered.set()+ assert ui_entered.wait(timeout=1.0)+ return True++ monkeypatch.setattr(runtime, "stop_service", stop_service)++ ui_stopped, timings, stop_ui_seconds, ui_pid, service_stopped, stop_service_seconds = (+ restart_supervisor._stop_runtime_for_restart()+ )++ assert ui_stopped is True+ assert service_stopped is True+ assert timings["stop_remote_access_seconds"] == 0.01+ assert stop_ui_seconds >= 0+ assert stop_service_seconds >= 0+ assert ui_pid is None+ assert sorted(calls) == ["stop_service", "stop_ui"]diff --git a/tests/test_runtime_service_lock.py b/tests/test_runtime_service_lock.pyindex acbd76938..e3e355a3b 100644--- a/tests/test_runtime_service_lock.py+++ b/tests/test_runtime_service_lock.py@@ -95,6 +95,22 @@ class RuntimeServiceLockTests(unittest.TestCase):self.assertEqual(pid, 67890)self.assertEqual(pid_path.read_text(encoding="utf-8"), "67890")+ def test_start_service_can_skip_initial_ready_wait(self):+ with tempfile.TemporaryDirectory() as tmpdir:+ pid_path = Path(tmpdir) / "service.pid"+ process = SimpleNamespace(pid=67890, poll=lambda: None)++ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):+ with patch("vibe.runtime.service_instance_lock_available", return_value=(True, None)):+ with patch("vibe.runtime.spawn_service_background_process", return_value=process):+ with patch("vibe.runtime.wait_for_service_pid", return_value=True) as wait_for_pid:+ with patch("vibe.runtime.pid_alive", return_value=True):+ pid = runtime.start_service(wait_for_ready=False, initial_ready_timeout=0)++ self.assertEqual(pid, 67890)+ wait_for_pid.assert_not_called()+ self.assertEqual(pid_path.read_text(encoding="utf-8"), "67890")+def test_start_service_errors_when_spawned_process_dies_before_lock(self):with tempfile.TemporaryDirectory() as tmpdir:pid_path = Path(tmpdir) / "service.pid"diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.pyindex d10fe3b22..e82692a66 100644--- a/tests/test_vibe_cli.py+++ b/tests/test_vibe_cli.py@@ -930,6 +930,19 @@ def test_start_ui_waits_for_replacement_health(tmp_path, monkeypatch):assert waited == [("127.0.0.1", 5123)]+def test_start_ui_can_skip_replacement_health_wait(tmp_path, monkeypatch):+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")+ runtime.ensure_dirs()++ def fail_wait(host, port):+ raise AssertionError(f"start_ui should not wait for health: {host}:{port}")++ monkeypatch.setattr(runtime, "wait_for_ui_server", fail_wait)+ monkeypatch.setattr(runtime, "spawn_background", lambda *args, **kwargs: 67890)++ assert runtime.start_ui("127.0.0.1", 5123, wait_for_ready=False) == 67890++def test_ui_health_url_uses_loopback_for_wildcard_bind():assert runtime._ui_health_url("0.0.0.0", 5100) == "http://127.0.0.1:5100/health"assert runtime._ui_health_url("::", 5100) == "http://[::1]:5100/health"diff --git a/vibe/restart_supervisor.py b/vibe/restart_supervisor.pyindex 977e97cd2..3c9723dd2 100644--- a/vibe/restart_supervisor.py+++ b/vibe/restart_supervisor.py@@ -5,9 +5,9 @@ import jsonimport loggingimport osimport subprocess-import sysimport timeimport uuid+from concurrent.futures import ThreadPoolExecutorfrom pathlib import Pathfrom config import paths@@ -62,6 +62,15 @@ def _read_recorded_pid() -> int | None:return pid if pid > 0 else None+def _read_recorded_ui_pid() -> int | None:+ pid_path = paths.get_runtime_ui_pid_path()+ try:+ pid = int(pid_path.read_text(encoding="utf-8").strip())+ except (OSError, ValueError):+ return None+ return pid if pid > 0 else None++def _read_starting_service_status() -> dict | None:status = runtime.read_status()if status.get("state") != "starting":@@ -69,11 +78,6 @@ def _read_starting_service_status() -> dict | None:return status-def _read_starting_service_pid() -> int | None:- status = _read_starting_service_status()- return _service_pid_from_status(status)--def _service_pid_from_status(status: dict | None) -> int | None:if status is None:return None@@ -81,7 +85,15 @@ def _service_pid_from_status(status: dict | None) -> int | None:return pid if isinstance(pid, int) and pid > 0 else None-def _fail(payload: dict, error: str, log, return_code: int) -> int:+def _rounded_seconds(seconds: float) -> float:+ return round(max(0.0, seconds), 3)+++def _fail(payload: dict, error: str, log, return_code: int, *, started_at: float | None = None) -> int:+ if started_at is not None:+ durations = dict(payload.get("stage_durations") or {})+ durations["restart_total_seconds"] = _rounded_seconds(time.monotonic() - started_at)+ payload["stage_durations"] = durationspayload.update(ok=False, state="failed", error=error)_write_status(payload)log.write(f"{_now_iso()} {error}\n")@@ -89,6 +101,61 @@ def _fail(payload: dict, error: str, log, return_code: int) -> int:return return_code+def _runtime_ready_for_config(config) -> bool:+ has_configured_platform_credentials = getattr(config, "has_configured_platform_credentials", None)+ if callable(has_configured_platform_credentials):+ return bool(has_configured_platform_credentials())+ return bool(getattr(getattr(config, "slack", None), "bot_token", ""))+++def _start_runtime_processes() -> tuple[int, int | None]:+ from core.services import settings as settings_service++ paths.ensure_data_dirs()+ config = settings_service.load_config(default_factory=settings_service.default_config)++ if _runtime_ready_for_config(config):+ runtime.write_status("starting")+ else:+ runtime.write_status("setup", "missing platform credentials")++ service_pid = runtime.start_service(wait_for_ready=False, initial_ready_timeout=0)+ bind_host = runtime.effective_ui_bind_host(config)+ ui_pid = runtime.start_ui(bind_host, config.ui.setup_port, wait_for_ready=False)++ if runtime.service_pid_recorded(service_pid):+ runtime.write_status("running", f"pid={service_pid}", service_pid, ui_pid)+ elif runtime.pid_alive(service_pid):+ runtime.write_status("starting", "waiting for service process", service_pid, ui_pid)+ else:+ runtime.write_status("error", "service process exited before startup completed", service_pid, ui_pid)+ raise RuntimeError(f"Vibe service process pid={service_pid} exited before acquiring the service lock")++ return service_pid, ui_pid+++def _stop_ui_for_restart() -> tuple[bool, dict[str, float | bool], float, int | None]:+ timings: dict[str, float | bool] = {}+ started_at = time.monotonic()+ stopped = runtime.stop_ui(timings, stop_remote_access=False)+ return bool(stopped), timings, _rounded_seconds(time.monotonic() - started_at), _read_recorded_ui_pid()+++def _stop_service_for_restart() -> tuple[bool, float]:+ started_at = time.monotonic()+ stopped = runtime.stop_service()+ return bool(stopped), _rounded_seconds(time.monotonic() - started_at)+++def _stop_runtime_for_restart() -> tuple[bool, dict[str, float | bool], float, int | None, bool, float]:+ with ThreadPoolExecutor(max_workers=2, thread_name_prefix="avibe-restart-stop") as executor:+ ui_future = executor.submit(_stop_ui_for_restart)+ service_future = executor.submit(_stop_service_for_restart)+ ui_stopped, ui_timings, stop_ui_seconds, ui_pid = ui_future.result()+ service_stopped, stop_service_seconds = service_future.result()+ return ui_stopped, ui_timings, stop_ui_seconds, ui_pid, service_stopped, stop_service_seconds++def _run_restart_job(*,job_id: str,@@ -106,6 +173,18 @@ def _run_restart_job(log.write(f"{_now_iso()} {message}\n")log.flush()+ stage_durations: dict[str, float | bool] = {}++ def record_duration(name: str, duration: float) -> float:+ stage_durations[name] = duration+ payload["stage_durations"] = dict(stage_durations)+ _write_status(payload)+ write(f"{name} completed in {duration:.3f}s")+ return duration++ def mark_duration(name: str, started_at: float) -> float:+ return record_duration(name, _rounded_seconds(time.monotonic() - started_at))+old_pid = _read_recorded_pid()payload = {"ok": None,@@ -118,77 +197,73 @@ def _run_restart_job("log_path": str(log_path),"error": None,"created_at": _now_iso(),+ "stage_durations": stage_durations,}_write_status(payload)+ restart_started_at = time.monotonic()write(f"restart job scheduled trigger={trigger!r} delay_seconds={delay_seconds!r} old_pid={old_pid!r}")if delay_seconds > 0:+ delay_started_at = time.monotonic()time.sleep(delay_seconds)+ mark_duration("delay_seconds_actual", delay_started_at)payload["state"] = "running"_write_status(payload)write("restart job started after delay")+ restart_started_at = time.monotonic()- write("stopping UI")- ui_stopped = runtime.stop_ui()- ui_pid = None+ write("stopping UI and service")+ stop_runtime_started_at = time.monotonic()try:- ui_pid = int(paths.get_runtime_ui_pid_path().read_text(encoding="utf-8").strip())- except (OSError, ValueError):- pass+ ui_stopped, ui_timings, stop_ui_seconds, ui_pid, stopped, stop_service_seconds = _stop_runtime_for_restart()+ except Exception as exc:+ return _fail(payload, f"stop runtime failed: {exc}", log, 2, started_at=restart_started_at)+ stage_durations.update(ui_timings)+ record_duration("stop_ui_total_seconds", stop_ui_seconds)+ record_duration("stop_service_seconds", stop_service_seconds)+ mark_duration("stop_runtime_seconds", stop_runtime_started_at)if ui_pid and ui_stopped is False and runtime.pid_alive(ui_pid):- return _fail(payload, f"UI pid {ui_pid} did not stop", log, 2)-- write("stopping service")- stopped = runtime.stop_service()+ return _fail(payload, f"UI pid {ui_pid} did not stop", log, 2, started_at=restart_started_at)if old_pid and stopped is False and runtime.pid_alive(old_pid):- return _fail(payload, f"service pid {old_pid} did not stop", log, 2)+ return _fail(payload, f"service pid {old_pid} did not stop", log, 2, started_at=restart_started_at)write("starting service")- command = get_restart_invocation_command(vibe_path=vibe_path)- env = get_restart_environment(vibe_path=vibe_path)- start_command = [*command[:-1], "start"] if command and command[-1] == "restart" else [*(command or ["vibe"]), "start"]+ start_runtime_started_at = time.monotonic()try:- result = subprocess.run(- start_command,- cwd=safe_cwd,- env=env,- stdout=log,- stderr=subprocess.STDOUT,- text=True,- check=False,- timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS + 30,- )- except subprocess.TimeoutExpired:- return _fail(- payload,- f"start command timed out after {runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS + 30:.0f} seconds",- log,- 4,- )+ new_pid, ui_pid = _start_runtime_processes()except Exception as exc:- return _fail(payload, f"start command failed: {exc}", log, 1)- if result.returncode != 0:- return _fail(payload, f"start command failed with exit code {result.returncode}", log, result.returncode or 1)+ return _fail(payload, f"start runtime failed: {exc}", log, 1, started_at=restart_started_at)+ mark_duration("start_runtime_seconds", start_runtime_started_at)- new_pid = _read_recorded_pid()service_status = runtime.read_status()if not new_pid:new_pid = _service_pid_from_status(_read_starting_service_status())service_status = runtime.read_status()if not new_pid or not runtime.pid_alive(new_pid):- return _fail(payload, "start command completed but service pid is not alive", log, 3)+ return _fail(payload, "start runtime completed but service pid is not alive", log, 3, started_at=restart_started_at)if not runtime.service_pid_recorded(new_pid):- write(f"start command returned while service pid={new_pid} is still acquiring its lock")+ write(f"start runtime returned while service pid={new_pid} is still acquiring its lock")+ wait_lock_started_at = time.monotonic()if not runtime.wait_for_service_pid(new_pid, timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS):- return _fail(payload, f"service pid {new_pid} did not acquire the service lock", log, 3)- ui_pid = service_status.get("ui_pid") if service_status else None- runtime.write_status("running", f"pid={new_pid}", new_pid, ui_pid if isinstance(ui_pid, int) else None)+ mark_duration("wait_service_lock_seconds", wait_lock_started_at)+ return _fail(+ payload,+ f"service pid {new_pid} did not acquire the service lock",+ log,+ 3,+ started_at=restart_started_at,+ )+ mark_duration("wait_service_lock_seconds", wait_lock_started_at)+ recorded_ui_pid = service_status.get("ui_pid") if service_status else ui_pid+ runtime.write_status("running", f"pid={new_pid}", new_pid, recorded_ui_pid if isinstance(recorded_ui_pid, int) else None)+ mark_duration("restart_total_seconds", restart_started_at)payload.update(ok=True, state="succeeded", new_pid=new_pid, error=None)_write_status(payload)write(f"restart job succeeded new_pid={new_pid}")if prepare_show_runtime:+ env = get_restart_environment(vibe_path=vibe_path)prepare_command = [*get_restart_command(vibe_path=vibe_path),"runtime",@@ -196,6 +271,7 @@ def _run_restart_job("--strict",]write("preparing Show Runtime after service restart")+ prepare_started_at = time.monotonic()try:prepare_result = subprocess.run(prepare_command,@@ -215,6 +291,8 @@ def _run_restart_job(write("Show Runtime preparation timed out after 300 seconds")except Exception as exc:write(f"Show Runtime preparation skipped: {exc}")+ finally:+ mark_duration("prepare_show_runtime_seconds", prepare_started_at)return 0diff --git a/vibe/runtime.py b/vibe/runtime.pyindex 0dbb7c20d..0adebef60 100644--- a/vibe/runtime.py+++ b/vibe/runtime.py@@ -93,6 +93,10 @@ _SERVICE_INSTANCE_LOCK_HANDLE = None_SERVICE_START_PROCESSES: dict[int, subprocess.Popen] = {}+def _rounded_seconds(seconds: float) -> float:+ return round(max(0.0, seconds), 3)++class ServiceAlreadyRunningError(RuntimeError):def __init__(self, *, lock_path: Path, holder_pid: int | None = None):self.lock_path = lock_path@@ -745,7 +749,11 @@ def _raise_service_start_not_ready(pid: int, *, timeout: float) -> None:raise RuntimeError(f"Vibe service process pid={pid} did not acquire the service lock")-def start_service(*, wait_for_ready: bool = True):+def start_service(+ *,+ wait_for_ready: bool = True,+ initial_ready_timeout: float = SERVICE_LOCK_READY_TIMEOUT_SECONDS,+):with _SERVICE_LOCK:pid_path = paths.get_runtime_pid_path()existing_pid = 0@@ -789,7 +797,7 @@ def start_service(*, wait_for_ready: bool = True):pid = process.pid_SERVICE_START_PROCESSES[pid] = process_record_service_pid_reservation(pid)- if wait_for_service_pid(pid, timeout=SERVICE_LOCK_READY_TIMEOUT_SECONDS):+ if initial_ready_timeout > 0 and wait_for_service_pid(pid, timeout=initial_ready_timeout):return pidexit_code = _service_start_exit_code(pid)if exit_code is not None:@@ -801,7 +809,7 @@ def start_service(*, wait_for_ready: bool = True):"Vibe service process pid=%s has not acquired the service lock after %.1fs; ""continuing while it finishes startup",pid,- SERVICE_LOCK_READY_TIMEOUT_SECONDS,+ initial_ready_timeout,)return pidif wait_for_service_pid(pid, timeout=SERVICE_SLOW_START_TIMEOUT_SECONDS):@@ -913,7 +921,7 @@ def effective_ui_bind_host(config: V2Config, requested_host: str | None = None)return setup_host-def start_ui(host, port):+def start_ui(host, port, *, wait_for_ready: bool = True):pid_path = paths.get_runtime_ui_pid_path()if pid_path.exists():try:@@ -944,7 +952,7 @@ def start_ui(host, port):"ui_stdout.log","ui_stderr.log",)- if not wait_for_ui_server(host, port):+ if wait_for_ready and not wait_for_ui_server(host, port):logger.warning("Started UI pid=%s but health check did not pass for %s", pid, _ui_health_url(host, port))return pid@@ -954,17 +962,31 @@ def stop_service():return stop_process(paths.get_runtime_pid_path())-def stop_ui():+def stop_ui(timings: dict[str, float | bool] | None = None, *, stop_remote_access: bool = True):remote_access_stopped = True- try:- from vibe import remote_access-- result = remote_access.stop()- if isinstance(result, dict) and result.get("ok") is False:- logger.warning("Failed to stop remote access before UI stop: %s", result.get("error"))+ started_at = time.monotonic()+ if stop_remote_access:+ remote_access_started_at = time.monotonic()+ try:+ from vibe import remote_access++ result = remote_access.stop()+ if timings is not None:+ timings["stop_remote_access_seconds"] = _rounded_seconds(time.monotonic() - remote_access_started_at)+ if isinstance(result, dict) and result.get("ok") is False:+ logger.warning("Failed to stop remote access before UI stop: %s", result.get("error"))+ remote_access_stopped = False+ except Exception:+ if timings is not None and "stop_remote_access_seconds" not in timings:+ timings["stop_remote_access_seconds"] = _rounded_seconds(time.monotonic() - remote_access_started_at)+ logger.warning("Failed to stop remote access before UI stop", exc_info=True)remote_access_stopped = False- except Exception:- logger.warning("Failed to stop remote access before UI stop", exc_info=True)- remote_access_stopped = False+ elif timings is not None:+ timings["stop_remote_access_seconds"] = 0.0+ timings["stop_remote_access_skipped"] = True+ ui_started_at = time.monotonic()ui_stopped = stop_process(paths.get_runtime_ui_pid_path())+ if timings is not None:+ timings["stop_ui_process_seconds"] = _rounded_seconds(time.monotonic() - ui_started_at)+ timings["stop_ui_seconds"] = _rounded_seconds(time.monotonic() - started_at)return bool(ui_stopped and remote_access_stopped)