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): tolerate slow service startup (#501)
Call White3340f42bb28f
diff --git a/main.py b/main.pyindex f1d1db445..0067e939b 100644--- a/main.py+++ b/main.py@@ -1,15 +1,13 @@#!/usr/bin/env python3+from __future__ import annotations+import osimport signalimport sysimport logging-import asyncio+from typing import Any+from config.paths import ensure_data_dirs, get_logs_dir-from config.v2_config import V2Config-from core.controller import Controller-from core.process_diagnostics import log_process_snapshot-from storage.importer import ensure_sqlite_state-from vibe.sentry_integration import init_sentryfrom vibe.runtime import (ServiceAlreadyRunningError,acquire_service_instance_lock,@@ -70,7 +68,19 @@ def apply_claude_sdk_patches():)-def prepare_sqlite_state(config: V2Config):+def load_config() -> Any:+ from config.v2_config import V2Config++ return V2Config.load()+++def ensure_sqlite_state(*args, **kwargs):+ from storage.importer import ensure_sqlite_state as _ensure_sqlite_state++ return _ensure_sqlite_state(*args, **kwargs)+++def prepare_sqlite_state(config: Any):"""Run safe SQLite state migrations before the service starts."""return ensure_sqlite_state(primary_platform=config.platform)@@ -104,16 +114,21 @@ def _log_shutdown_intent(logger: logging.Logger, signum: int) -> None:def main():"""Main entry point"""+ lock_acquired = Falsetry:+ acquire_service_instance_lock()+ lock_acquired = True+# Load configuration- config = V2Config.load()+ config = load_config()# Setup loggingsetup_logging(config.runtime.log_level)logger = logging.getLogger(__name__)- acquire_service_instance_lock()apply_claude_sdk_patches()+ from vibe.sentry_integration import init_sentry+init_sentry(config, component="service")logger.info("Starting vibe-remote service...")@@ -123,6 +138,8 @@ def main():shutdown_intent_required(),os.environ.get("VIBE_REQUIRE_SHUTDOWN_INTENT"),)+ from core.process_diagnostics import log_process_snapshot+log_process_snapshot(logger, "service-start")report = prepare_sqlite_state(config)logger.info(@@ -133,6 +150,7 @@ def main():)# Create and run controller+ from core.controller import Controllerfrom config.v2_compat import to_app_configcontroller = Controller(to_app_config(config))@@ -170,6 +188,8 @@ def main():logging.error("Failed to start: %s", e)sys.exit(2)except Exception as e:+ if lock_acquired:+ release_service_instance_lock()logging.error(f"Failed to start: {e}")sys.exit(1)diff --git a/tests/test_cli_setup_status.py b/tests/test_cli_setup_status.pyindex 2728ee876..353c8c3d3 100644--- a/tests/test_cli_setup_status.py+++ b/tests/test_cli_setup_status.py@@ -24,6 +24,7 @@ def test_cmd_vibe_marks_setup_when_no_enabled_platform_has_credentials(capsys) -patch("vibe.cli.runtime.stop_ui") as stop_ui,patch("vibe.cli.runtime.start_service", return_value=101),patch("vibe.cli.runtime.start_ui", return_value=202),+ patch("vibe.cli.runtime.service_pid_recorded", return_value=True),patch("vibe.cli.runtime.write_status"),patch("vibe.cli._write_status") as write_status,):@@ -47,6 +48,7 @@ def test_cmd_vibe_marks_starting_when_non_slack_platform_is_configured() -> Nonepatch("vibe.cli.runtime.stop_ui") as stop_ui,patch("vibe.cli.runtime.start_service", return_value=101),patch("vibe.cli.runtime.start_ui", return_value=202),+ patch("vibe.cli.runtime.service_pid_recorded", return_value=True),patch("vibe.cli.runtime.write_status"),patch("vibe.cli._write_status") as write_status,):diff --git a/tests/test_restart_supervisor.py b/tests/test_restart_supervisor.pyindex 6e170062f..8373f9f80 100644--- a/tests/test_restart_supervisor.py+++ b/tests/test_restart_supervisor.py@@ -86,6 +86,7 @@ def test_restart_job_stops_and_starts_service(monkeypatch, tmp_path):monkeypatch.setattr(restart_supervisor.subprocess, "run", fake_run)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")@@ -119,6 +120,7 @@ def test_restart_job_prepares_show_runtime_after_service_start(monkeypatch, tmp_monkeypatch.setattr(restart_supervisor.subprocess, "run", fake_run)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="jobruntime",@@ -179,6 +181,7 @@ def test_restart_job_continues_when_old_pid_already_exited(monkeypatch, tmp_pathmonkeypatch.setattr(restart_supervisor.subprocess, "run", fake_run)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")@@ -187,6 +190,47 @@ def test_restart_job_continues_when_old_pid_already_exited(monkeypatch, tmp_pathassert runtime.read_json(runtime.get_restart_status_path())["state"] == "succeeded"+def test_restart_job_adopts_slow_starting_service_pid(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")+ 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.+ 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)++ monkeypatch.setattr(restart_supervisor.subprocess, "run", fake_run)+ 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)++ rc = restart_supervisor._run_restart_job(job_id="jobslow", delay_seconds=0, vibe_path="/bin/vibe", trigger="test")++ assert rc == 0+ status = runtime.read_json(runtime.get_restart_status_path())+ assert status["ok"] is True+ assert status["state"] == "succeeded"+ assert status["new_pid"] == 222+ service_status = runtime.read_status()+ assert service_status["state"] == "running"+ assert service_status["service_pid"] == 222+ assert service_status["ui_pid"] == 333++def test_restart_job_marks_start_timeout_failed(monkeypatch, tmp_path):monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))paths.ensure_data_dirs()diff --git a/tests/test_runtime_service_lock.py b/tests/test_runtime_service_lock.pyindex 12d2423f0..acbd76938 100644--- a/tests/test_runtime_service_lock.py+++ b/tests/test_runtime_service_lock.py@@ -3,6 +3,7 @@ import sysimport tempfileimport unittestfrom pathlib import Path+from types import SimpleNamespacefrom unittest.mock import patchsys.path.insert(0, str(Path(__file__).resolve().parents[1]))@@ -22,8 +23,9 @@ class RuntimeServiceLockTests(unittest.TestCase):"vibe.runtime.get_process_command",return_value=f"{sys.executable} {runtime.get_service_main_path()}",):- with patch("vibe.runtime.spawn_background") as spawn_background:- pid = runtime.start_service()+ with patch("vibe.runtime.service_pid_recorded", return_value=True):+ with patch("vibe.runtime.spawn_service_background_process") as spawn_background:+ pid = runtime.start_service()self.assertEqual(pid, 12345)spawn_background.assert_not_called()@@ -34,19 +36,21 @@ class RuntimeServiceLockTests(unittest.TestCase):pid_path.write_text("12345", encoding="utf-8")def fake_spawn(args, stdout_name, stderr_name, env=None):- return 67890+ return SimpleNamespace(pid=67890, poll=lambda: None)with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):with patch("vibe.runtime.pid_alive", return_value=True):with patch("vibe.runtime.get_process_command", return_value="/usr/bin/unrelated --work"):with patch("vibe.runtime.service_instance_lock_available", return_value=(True, None)):- with patch("vibe.runtime.spawn_service_background", side_effect=fake_spawn) as spawn_background:+ with patch(+ "vibe.runtime.spawn_service_background_process", side_effect=fake_spawn+ ) as spawn_background:with patch("vibe.runtime.wait_for_service_pid", return_value=True):pid = runtime.start_service()self.assertEqual(pid, 67890)spawn_background.assert_called_once()- self.assertFalse(pid_path.exists())+ self.assertEqual(pid_path.read_text(encoding="utf-8"), "67890")def test_start_service_reuses_live_pid_when_command_is_unreadable(self):with tempfile.TemporaryDirectory() as tmpdir:@@ -56,8 +60,9 @@ class RuntimeServiceLockTests(unittest.TestCase):with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):with patch("vibe.runtime.pid_alive", return_value=True):with patch("vibe.runtime.get_process_command", return_value=None):- with patch("vibe.runtime.spawn_background") as spawn_background:- pid = runtime.start_service()+ with patch("vibe.runtime.service_pid_recorded", return_value=True):+ with patch("vibe.runtime.spawn_service_background_process") as spawn_background:+ pid = runtime.start_service()self.assertEqual(pid, 12345)spawn_background.assert_not_called()@@ -69,22 +74,116 @@ class RuntimeServiceLockTests(unittest.TestCase):with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):with patch("vibe.runtime.service_instance_lock_available", return_value=(False, 12345)):with patch("vibe.runtime.pid_alive", return_value=True):- with patch("vibe.runtime.spawn_service_background") as spawn_background:+ with patch("vibe.runtime.spawn_service_background_process") as spawn_background:with self.assertRaises(runtime.ServiceAlreadyRunningError):runtime.start_service()spawn_background.assert_not_called()- def test_start_service_errors_when_spawned_process_never_acquires_lock(self):+ def test_start_service_returns_live_pid_when_lock_write_is_slow(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", return_value=67890):+ with patch("vibe.runtime.spawn_service_background_process", return_value=process):with patch("vibe.runtime.wait_for_service_pid", return_value=False):- with self.assertRaises(RuntimeError):- runtime.start_service()+ with patch("vibe.runtime.pid_alive", return_value=True):+ pid = runtime.start_service(wait_for_ready=False)++ self.assertEqual(pid, 67890)+ 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"+ process = SimpleNamespace(pid=67890, poll=lambda: 1)++ 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=False):+ with patch("vibe.runtime.pid_alive", return_value=True):+ with self.assertRaises(RuntimeError):+ runtime.start_service()++ self.assertFalse(pid_path.exists())++ def test_start_service_waits_for_readiness_by_default(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", side_effect=[False, True]) as wait_for_pid:+ with patch("vibe.runtime.pid_alive", return_value=True):+ pid = runtime.start_service()++ self.assertEqual(pid, 67890)+ self.assertEqual(wait_for_pid.call_count, 2)++ def test_start_service_reuses_pending_reservation_without_spawning_second_worker(self):+ with tempfile.TemporaryDirectory() as tmpdir:+ pid_path = Path(tmpdir) / "service.pid"+ pid_path.write_text("67890", encoding="utf-8")++ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):+ with patch("vibe.runtime.pid_alive", return_value=True):+ with patch(+ "vibe.runtime.get_process_command",+ return_value=f"{sys.executable} {runtime.get_service_main_path()}",+ ):+ with patch("vibe.runtime.service_pid_recorded", return_value=False):+ with patch("vibe.runtime.spawn_service_background_process") as spawn_background:+ pid = runtime.start_service(wait_for_ready=False)++ self.assertEqual(pid, 67890)+ spawn_background.assert_not_called()++ def test_stop_service_stops_pending_pid_reservation(self):+ with tempfile.TemporaryDirectory() as tmpdir:+ pid_path = Path(tmpdir) / "service.pid"+ pid_path.write_text("67890", encoding="utf-8")++ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):+ with patch("vibe.runtime.pid_alive", return_value=True):+ with patch("vibe.runtime.stop_pid", return_value=True) as stop_pid:+ self.assertTrue(runtime.stop_service())++ stop_pid.assert_called_once_with(67890, timeout=5)+ self.assertFalse(pid_path.exists())++ def test_wait_for_service_pid_adopts_slow_pid_file_write(self):+ with tempfile.TemporaryDirectory() as tmpdir:+ pid_path = Path(tmpdir) / "service.pid"+ calls = []++ def fake_service_pid_recorded(pid):+ calls.append(pid)+ if len(calls) == 2:+ pid_path.write_text(str(pid), encoding="utf-8")+ return True+ return False++ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):+ with patch("vibe.runtime.service_pid_recorded", side_effect=fake_service_pid_recorded):+ with patch("vibe.runtime.pid_alive", return_value=True):+ with patch("vibe.runtime.time.sleep", return_value=None):+ self.assertTrue(runtime.wait_for_service_pid(67890, timeout=1.0))++ self.assertEqual(calls, [67890, 67890])++ def test_wait_for_service_pid_fails_only_when_worker_dies(self):+ with tempfile.TemporaryDirectory() as tmpdir:+ pid_path = Path(tmpdir) / "service.pid"++ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):+ with patch("vibe.runtime.service_pid_recorded", return_value=False):+ with patch("vibe.runtime.pid_alive", return_value=False):+ self.assertFalse(runtime.wait_for_service_pid(67890, timeout=1.0))def test_service_instance_lock_blocks_second_holder(self):with tempfile.TemporaryDirectory() as tmpdir:diff --git a/tests/test_service_logging_handlers.py b/tests/test_service_logging_handlers.pyindex f7ec08295..aa4ca2e65 100644--- a/tests/test_service_logging_handlers.py+++ b/tests/test_service_logging_handlers.py@@ -2,9 +2,12 @@ from __future__ import annotationsimport loggingimport signal+import subprocess+import sysfrom pathlib import Pathimport main+import pytestfrom vibe import runtime@@ -35,19 +38,18 @@ def test_start_service_disables_stdout_logging_for_background_process(monkeypatcmonkeypatch.setattr(runtime, "pid_alive", lambda pid: False)monkeypatch.setattr(runtime, "get_service_main_path", lambda: Path("/tmp/main.py"))monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (True, 0))- # Stub the real spawn (start_service calls spawn_service_background, not- # spawn_background) so we never fork a real vibe service, and short-circuit the- # post-spawn lock wait. This captures the env start_service would launch with.+ # Stub the real spawn so we never fork a real vibe service, and short-circuit+ # the post-spawn lock wait. This captures the env start_service would launch with.monkeypatch.setattr(runtime, "wait_for_service_pid", lambda pid, *args, **kwargs: True)- def fake_spawn_service_background(args, stdout_name, stderr_name, env=None):+ def fake_spawn_service_background_process(args, stdout_name, stderr_name, env=None):captured["args"] = argscaptured["stdout_name"] = stdout_namecaptured["stderr_name"] = stderr_namecaptured["env"] = env- return 12345+ return type("Process", (), {"pid": 12345, "poll": lambda self: None})()- monkeypatch.setattr(runtime, "spawn_service_background", fake_spawn_service_background)+ monkeypatch.setattr(runtime, "spawn_service_background_process", fake_spawn_service_background_process)pid = runtime.start_service()@@ -58,6 +60,27 @@ def test_start_service_disables_stdout_logging_for_background_process(monkeypatcassert captured["env"]["VIBE_DISABLE_STDOUT_LOGGING"] == "1"+def test_main_import_does_not_load_controller() -> None:+ code = "import sys; import main; raise SystemExit(1 if 'core.controller' in sys.modules else 0)"+ result = subprocess.run([sys.executable, "-c", code], cwd=Path(__file__).resolve().parents[1], check=False)++ assert result.returncode == 0+++def test_main_acquires_lock_before_loading_config(monkeypatch):+ events = []++ monkeypatch.setattr(main, "acquire_service_instance_lock", lambda: events.append("lock"))+ monkeypatch.setattr(main, "load_config", lambda: events.append("load_config") or (_ for _ in ()).throw(RuntimeError("stop")))+ monkeypatch.setattr(main, "release_service_instance_lock", lambda: events.append("release"))++ with pytest.raises(SystemExit) as exc:+ main.main()++ assert exc.value.code == 1+ assert events == ["lock", "load_config", "release"]++def test_shutdown_intent_missing_is_logged_not_ignored(monkeypatch, caplog):monkeypatch.setattr(main, "shutdown_intent_required", lambda: True)monkeypatch.setattr(main, "consume_shutdown_intent", lambda pid, signum: None)diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.pyindex 2afb27fc6..d10fe3b22 100644--- a/tests/test_vibe_cli.py+++ b/tests/test_vibe_cli.py@@ -507,18 +507,68 @@ def test_cmd_start_ensures_services_without_stopping(monkeypatch):monkeypatch.setattr(cli.paths, "ensure_data_dirs", lambda: None)monkeypatch.setattr(cli, "_ensure_config", lambda: config)monkeypatch.setattr(cli, "_write_status", lambda *args, **kwargs: calls.append(("status", args)))- monkeypatch.setattr(cli.runtime, "start_service", lambda: calls.append("start_service") or 1234)+ monkeypatch.setattr(cli.runtime, "start_service", lambda **kwargs: calls.append(("start_service", kwargs)) or 1234)monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda cfg: "127.0.0.1")monkeypatch.setattr(cli.runtime, "start_ui", lambda host, port: calls.append(("start_ui", host, port)) or 5678)+ monkeypatch.setattr(cli.runtime, "service_pid_recorded", lambda pid: True)monkeypatch.setattr(cli.runtime, "write_status", lambda *args: calls.append(("runtime_status", args)))assert cli.cmd_start() == 0- assert "start_service" in calls+ assert ("start_service", {"wait_for_ready": False}) in callsassert ("start_ui", "127.0.0.1", 5123) in callsassert not any(call == "stop" for call in calls)+def test_cmd_start_keeps_ui_up_while_service_lock_is_slow(monkeypatch):+ calls = []+ config = SimpleNamespace(+ has_configured_platform_credentials=lambda: True,+ ui=SimpleNamespace(setup_host="127.0.0.1", setup_port=5123, open_browser=False),+ )++ monkeypatch.setattr(cli.paths, "ensure_data_dirs", lambda: None)+ monkeypatch.setattr(cli, "_ensure_config", lambda: config)+ monkeypatch.setattr(cli, "_write_status", lambda *args, **kwargs: calls.append(("status", args)))+ monkeypatch.setattr(cli.runtime, "start_service", lambda **kwargs: calls.append(("start_service", kwargs)) or 1234)+ monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda cfg: "127.0.0.1")+ monkeypatch.setattr(cli.runtime, "start_ui", lambda host, port: calls.append(("start_ui", host, port)) or 5678)+ monkeypatch.setattr(cli.runtime, "service_pid_recorded", lambda pid: False)+ monkeypatch.setattr(cli.runtime, "wait_for_service_pid", lambda pid, timeout: False)+ monkeypatch.setattr(cli.runtime, "pid_alive", lambda pid: pid == 1234)+ monkeypatch.setattr(cli.runtime, "write_status", lambda *args: calls.append(("runtime_status", args)))++ assert cli.cmd_start() == 0++ assert calls.index(("start_service", {"wait_for_ready": False})) < calls.index(("start_ui", "127.0.0.1", 5123))+ assert ("runtime_status", ("starting", "waiting for service process", 1234, 5678)) in calls+ assert ("runtime_status", ("starting", "service process is still starting", 1234, 5678)) in calls+++def test_cmd_start_fails_only_when_slow_service_exits(monkeypatch):+ config = SimpleNamespace(+ has_configured_platform_credentials=lambda: True,+ ui=SimpleNamespace(setup_host="127.0.0.1", setup_port=5123, open_browser=False),+ )+ statuses = []++ monkeypatch.setattr(cli.paths, "ensure_data_dirs", lambda: None)+ monkeypatch.setattr(cli, "_ensure_config", lambda: config)+ monkeypatch.setattr(cli, "_write_status", lambda *args, **kwargs: None)+ monkeypatch.setattr(cli.runtime, "start_service", lambda **kwargs: 1234)+ monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda cfg: "127.0.0.1")+ monkeypatch.setattr(cli.runtime, "start_ui", lambda host, port: 5678)+ monkeypatch.setattr(cli.runtime, "service_pid_recorded", lambda pid: False)+ monkeypatch.setattr(cli.runtime, "wait_for_service_pid", lambda pid, timeout: False)+ monkeypatch.setattr(cli.runtime, "pid_alive", lambda pid: False)+ monkeypatch.setattr(cli.runtime, "write_status", lambda *args: statuses.append(args))++ with pytest.raises(RuntimeError):+ cli.cmd_start()++ assert ("error", "service process exited before startup completed", 1234, 5678) in statuses++def test_restart_parser_accepts_delay_seconds():parser = cli.build_parser()args = parser.parse_args(["restart", "--delay-seconds", "60"])diff --git a/vibe/cli.py b/vibe/cli.pyindex 536845597..e4788fca2 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -739,16 +739,7 @@ def _stop_process(pid_path):def _render_status():- status = _read_json(paths.get_runtime_status_path()) or {}- pid_path = paths.get_runtime_pid_path()- pid = pid_path.read_text(encoding="utf-8").strip() if pid_path.exists() else None- running = bool(pid and pid.isdigit() and _pid_alive(int(pid)))- status["running"] = running- status["pid"] = int(pid) if pid and pid.isdigit() else None- restart_status = _read_json(runtime.get_restart_status_path())- if restart_status:- status["restart"] = restart_status- return json.dumps(status, indent=2)+ return runtime.render_status()def _default_timezone_name() -> str:@@ -3988,10 +3979,23 @@ def cmd_start():else:_write_status("starting")- service_pid = runtime.start_service()+ service_pid = runtime.start_service(wait_for_ready=False)bind_host = runtime.effective_ui_bind_host(config)ui_pid = runtime.start_ui(bind_host, config.ui.setup_port)- runtime.write_status("running", "pid={}".format(service_pid), service_pid, ui_pid)+ service_ready = runtime.service_pid_recorded(service_pid)+ if not service_ready:+ runtime.write_status("starting", "waiting for service process", service_pid, ui_pid)+ service_ready = runtime.wait_for_service_pid(+ service_pid,+ timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS,+ )+ if service_ready:+ runtime.write_status("running", "pid={}".format(service_pid), service_pid, ui_pid)+ elif runtime.pid_alive(service_pid):+ runtime.write_status("starting", "service process is still starting", 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")ui_url = "http://{}:{}".format(config.ui.setup_host, config.ui.setup_port)diff --git a/vibe/restart_supervisor.py b/vibe/restart_supervisor.pyindex f603425f9..977e97cd2 100644--- a/vibe/restart_supervisor.py+++ b/vibe/restart_supervisor.py@@ -62,6 +62,25 @@ def _read_recorded_pid() -> int | None:return pid if pid > 0 else None+def _read_starting_service_status() -> dict | None:+ status = runtime.read_status()+ if status.get("state") != "starting":+ return 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+ pid = status.get("service_pid")+ return pid if isinstance(pid, int) and pid > 0 else None++def _fail(payload: dict, error: str, log, return_code: int) -> int:payload.update(ok=False, state="failed", error=error)_write_status(payload)@@ -137,18 +156,33 @@ def _run_restart_job(stderr=subprocess.STDOUT,text=True,check=False,- timeout=30,+ timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS + 30,)except subprocess.TimeoutExpired:- return _fail(payload, "start command timed out after 30 seconds", log, 4)+ return _fail(+ payload,+ f"start command timed out after {runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS + 30:.0f} seconds",+ log,+ 4,+ )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)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)+ if not runtime.service_pid_recorded(new_pid):+ write(f"start command returned while service pid={new_pid} is still acquiring its lock")+ 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)payload.update(ok=True, state="succeeded", new_pid=new_pid, error=None)_write_status(payload)diff --git a/vibe/runtime.py b/vibe/runtime.pyindex 424e0420b..0dbb7c20d 100644--- a/vibe/runtime.py+++ b/vibe/runtime.py@@ -27,6 +27,8 @@ from config.v2_config import (logger = logging.getLogger(__name__)SHUTDOWN_INTENT_TTL_SECONDS = 30SHUTDOWN_INTENT_ENV = "VIBE_REQUIRE_SHUTDOWN_INTENT"+SERVICE_LOCK_READY_TIMEOUT_SECONDS = 5.0+SERVICE_SLOW_START_TIMEOUT_SECONDS = 120.0def get_package_root() -> Path:@@ -88,6 +90,7 @@ ROOT_DIR = get_project_root() # For backward compatibilityMAIN_PATH = get_service_main_path()_SERVICE_LOCK = threading.Lock()_SERVICE_INSTANCE_LOCK_HANDLE = None+_SERVICE_START_PROCESSES: dict[int, subprocess.Popen] = {}class ServiceAlreadyRunningError(RuntimeError):@@ -532,7 +535,12 @@ def spawn_background(args, pid_path, stdout_name: str, stderr_name: str, env: direturn process.pid-def spawn_service_background(args, stdout_name: str, stderr_name: str, env: dict[str, str] | None = None) -> int:+def spawn_service_background_process(+ args,+ stdout_name: str,+ stderr_name: str,+ env: dict[str, str] | None = None,+) -> subprocess.Popen:stdout_path = _log_path(stdout_name)stderr_path = _log_path(stderr_name)stdout_path.parent.mkdir(parents=True, exist_ok=True)@@ -551,25 +559,83 @@ def spawn_service_background(args, stdout_name: str, stderr_name: str, env: dictfinally:stdout.close()stderr.close()- return process.pid+ return process-def wait_for_service_pid(pid: int, timeout: float = 5.0) -> bool:- deadline = time.monotonic() + timeout+def spawn_service_background(args, stdout_name: str, stderr_name: str, env: dict[str, str] | None = None) -> int:+ return spawn_service_background_process(args, stdout_name, stderr_name, env=env).pid+++def _record_service_pid_reservation(pid: int) -> None:+ pid_path = paths.get_runtime_pid_path()+ pid_path.parent.mkdir(parents=True, exist_ok=True)+ pid_path.write_text(str(pid), encoding="utf-8")+++def _clear_service_pid_reservation(pid: int) -> None:+ _SERVICE_START_PROCESSES.pop(pid, None)+ pid_path = paths.get_runtime_pid_path()+ try:+ recorded_pid = int(pid_path.read_text(encoding="utf-8").strip())+ except (OSError, ValueError):+ return+ if recorded_pid == pid:+ pid_path.unlink(missing_ok=True)+++def service_lock_held_by(pid: int) -> bool:+ lock_path = get_service_lock_path()+ lock_path.parent.mkdir(parents=True, exist_ok=True)+ lock_file = lock_path.open("a+", encoding="utf-8")+ try:+ if _try_lock_file(lock_file):+ _unlock_file(lock_file)+ return False+ return _lock_file_pid(lock_file) == pid+ finally:+ lock_file.close()+++def _service_start_exit_code(pid: int) -> int | None:+ process = _SERVICE_START_PROCESSES.get(pid)+ if process is None:+ return None+ exit_code = process.poll()+ if exit_code is None:+ return None+ _clear_service_pid_reservation(pid)+ return exit_code+++def service_pid_recorded(pid: int) -> bool:pid_path = paths.get_runtime_pid_path()+ if not pid_path.exists():+ return False+ try:+ recorded_pid = int(pid_path.read_text(encoding="utf-8").strip())+ except (OSError, ValueError):+ return False+ return recorded_pid == pid and pid_alive(pid) and service_lock_held_by(pid)+++def wait_for_service_pid(pid: int, timeout: float = SERVICE_LOCK_READY_TIMEOUT_SECONDS) -> bool:+ deadline = time.monotonic() + timeoutwhile time.monotonic() < deadline:- recorded_pid = 0- if pid_path.exists():- try:- recorded_pid = int(pid_path.read_text(encoding="utf-8").strip())- except (OSError, ValueError):- recorded_pid = 0- if recorded_pid == pid and pid_alive(pid):+ if service_pid_recorded(pid):+ _SERVICE_START_PROCESSES.pop(pid, None)return True+ if _service_start_exit_code(pid) is not None:+ return Falseif not pid_alive(pid):+ _clear_service_pid_reservation(pid)return Falsetime.sleep(0.1)- return False+ ready = service_pid_recorded(pid)+ if ready:+ _SERVICE_START_PROCESSES.pop(pid, None)+ elif _service_start_exit_code(pid) is not None:+ return False+ return readydef stop_process(pid_path, timeout=5):@@ -661,7 +727,7 @@ def render_status():status = read_status()pid_path = paths.get_runtime_pid_path()pid = pid_path.read_text(encoding="utf-8").strip() if pid_path.exists() else None- running = bool(pid and pid.isdigit() and pid_alive(int(pid)))+ running = bool(pid and pid.isdigit() and service_pid_recorded(int(pid)))status["running"] = runningstatus["pid"] = int(pid) if pid and pid.isdigit() else Nonerestart_status = read_json(get_restart_status_path())@@ -670,7 +736,16 @@ def render_status():return json.dumps(status, indent=2)-def start_service():+def _raise_service_start_not_ready(pid: int, *, timeout: float) -> None:+ if pid_alive(pid):+ raise RuntimeError(+ f"Vibe service process pid={pid} did not acquire the service lock within {timeout:.0f} seconds"+ )+ _clear_service_pid_reservation(pid)+ raise RuntimeError(f"Vibe service process pid={pid} did not acquire the service lock")+++def start_service(*, wait_for_ready: bool = True):with _SERVICE_LOCK:pid_path = paths.get_runtime_pid_path()existing_pid = 0@@ -681,7 +756,13 @@ def start_service():existing_pid = 0if existing_pid and pid_alive(existing_pid):if not _pid_mismatches_service(existing_pid):- return existing_pid+ if service_pid_recorded(existing_pid):+ return existing_pid+ if not wait_for_ready:+ return existing_pid+ if wait_for_service_pid(existing_pid, timeout=SERVICE_SLOW_START_TIMEOUT_SECONDS):+ return existing_pid+ _raise_service_start_not_ready(existing_pid, timeout=SERVICE_SLOW_START_TIMEOUT_SECONDS)logger.warning("Ignoring stale service pid file pid=%s because it does not match the Vibe service",existing_pid,@@ -695,7 +776,7 @@ def start_service():raise ServiceAlreadyRunningError(lock_path=get_service_lock_path(), holder_pid=lock_holder_pid)main_path = get_service_main_path()- pid = spawn_service_background(+ process = spawn_service_background_process([sys.executable, str(main_path)],"service_stdout.log","service_stderr.log",@@ -705,8 +786,32 @@ def start_service():SHUTDOWN_INTENT_ENV: "1",},)- if not wait_for_service_pid(pid):- raise RuntimeError(f"Vibe service process pid={pid} did not acquire the service lock")+ 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):+ return pid+ exit_code = _service_start_exit_code(pid)+ if exit_code is not None:+ raise RuntimeError(+ f"Vibe service process pid={pid} exited with code {exit_code} before acquiring the service lock"+ )+ if pid_alive(pid) and not wait_for_ready:+ logger.warning(+ "Vibe service process pid=%s has not acquired the service lock after %.1fs; "+ "continuing while it finishes startup",+ pid,+ SERVICE_LOCK_READY_TIMEOUT_SECONDS,+ )+ return pid+ if wait_for_service_pid(pid, timeout=SERVICE_SLOW_START_TIMEOUT_SECONDS):+ return pid+ exit_code = _service_start_exit_code(pid)+ if exit_code is not None:+ raise RuntimeError(+ f"Vibe service process pid={pid} exited with code {exit_code} before acquiring the service lock"+ )+ _raise_service_start_not_ready(pid, timeout=SERVICE_SLOW_START_TIMEOUT_SECONDS)return piddiff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 1aaf24aad..0bfce7cc1 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -1353,7 +1353,7 @@ def status():pid_path = paths.get_runtime_pid_path()pid = pid_path.read_text(encoding="utf-8").strip() if pid_path.exists() else Nonetry:- running = bool(pid and pid.isdigit() and runtime.pid_alive(int(pid)))+ running = bool(pid and pid.isdigit() and runtime.service_pid_recorded(int(pid)))except Exception as exc:logger.warning("Failed to inspect service pid %s: %s", pid, exc)running = False