Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(runtime): harden service restart ownership

cyh6ea3c2e5eb10
diff --git a/config/paths.py b/config/paths.py
index 1b241cffb..427e5d0f9 100644
--- a/config/paths.py
+++ b/config/paths.py
@@ -41,6 +41,14 @@ def get_runtime_pid_path() -> Path:
return get_runtime_dir() / "vibe.pid"
+def get_runtime_service_lock_path() -> Path:
+ return get_runtime_dir() / "service.lock"
+
+
+def get_runtime_restart_status_path() -> Path:
+ return get_runtime_dir() / "restart_status.json"
+
+
def get_runtime_ui_pid_path() -> Path:
return get_runtime_dir() / "vibe-ui.pid"
diff --git a/docs/plans/restart-orphan-bug.md b/docs/plans/restart-orphan-bug.md
new file mode 100644
index 000000000..a9206cea9
--- /dev/null
+++ b/docs/plans/restart-orphan-bug.md
@@ -0,0 +1,442 @@
+# Restart Orphan Bug — Vibe Service Survives `vibe restart`
+
+> Status: **Reviewed and implemented in this branch.** The design shifted from
+> orphan scanning to a data-dir scoped single-service lock plus a restart
+> supervisor job.
+> Owner: TBD. Triaged on 2026-05-24.
+
+## 1. Background
+
+The `vibe restart` family of commands (CLI direct, CLI delayed, Web UI
+`/control` action, and `do_upgrade` auto-restart) **can leave the previous
+`service_main.py` process alive while spawning a new one**. From that point
+on, the install is in a stable "two services for the same data dir" state
+that is invisible to the user:
+
+- Web UI reports "Service running" — but the PID it reports is the *new*
+ service.
+- `vibe.pid` only records the new service. Subsequent `vibe stop` /
+ `vibe restart` therefore only target the new service; the orphan never
+ gets killed.
+- Both services race to handle inbound IM events from the same Slack /
+ Discord / Lark workspace. Whichever wins a given event is non-deterministic.
+
+The user-visible symptom that surfaced this bug:
+
+- The system-prompt injection added in `feat(show): list show pages` (PR
+ #331, merged 2026-05-24) shipped a new `## Show Pages` section.
+- The user's running service (PID 60609, started 2026-05-20 12:21) was
+ spawned **before** that code reached disk and was therefore serving the
+ *old* prompt template (numbered sections, `vibe hook send`).
+- The user upgraded vibe and ran `vibe restart --delay-seconds 60` via an
+ Agent. PID 70784 was spawned at 2026-05-24 04:12:05 — but PID 60609 was
+ never killed. Both processes have been alive since.
+- Slack messages in the same Vibe Remote session were sometimes routed
+ through PID 60609 (Agent saw the old prompt, no Show Pages) and sometimes
+ through PID 70784 (Agent saw the new prompt). The Agent looked like it
+ was randomly ignoring a system-level instruction.
+
+This plan captures the full bug surface and proposes a layered fix.
+
+## 2. Evidence
+
+Captured directly from the user's machine on 2026-05-24 18:30~18:50 (UTC+08).
+
+### 2.1 Process state
+
+```
+ps -eo pid,ppid,lstart,command | grep service_main
+60609 1 Wed May 20 12:21:01 2026 Python .../site-packages/vibe/service_main.py
+70784 1 Sun May 24 04:12:05 2026 Python .../site-packages/vibe/service_main.py
+70785 1 Sun May 24 04:12:05 2026 Python -c from vibe.ui_server import run_ui_server; run_ui_server('0.0.0.0', 5100)
+```
+
+Both `service_main.py` processes are alive, both have `PPID=1` (launchd
+adopted after the spawning parent exited).
+
+### 2.2 Pid files
+
+```
+~/.vibe_remote/runtime/vibe.pid → 70784
+~/.vibe_remote/runtime/vibe-ui.pid → 70785
+```
+
+The pidfile only references the new service. PID 60609 is no longer
+tracked by the runtime even though it is alive.
+
+### 2.3 System-prompt injection mismatch
+
+The user's previous Claude session (PID 36112, parent PID 60609) was
+spawned with this `--append-system-prompt`:
+
+```
+## 1. Send files ← old numbered style
+## 2. Quick-reply buttons
+## 3. Scheduled tasks, watches, and hooks
+ Use `vibe hook send --session-id ... --prompt ...` ← removed CLI verb
+ ...
+ Use `--prompt-file <path>` ← renamed param
+## 4. User Context and Preferences
+
+(no `## Show Pages` section at all)
+```
+
+The current Claude session (PID 48024, parent PID 70784) was spawned with
+the **new** injection (unnumbered sections, `vibe agent run --async`,
+`--message-file`, and the `## Show Pages` block including
+`vibe show path --session-id sesszcbv24wp8`).
+
+Both prompts originated from the same `core/system_prompt_injection.py`
+on disk — the difference is *which long-running Python process built the
+prompt*. PID 60609 still holds the pre-upgrade module in memory.
+
+### 2.4 Disk vs. memory drift
+
+```
+core/system_prompt_injection.py mtime 2026-05-24 03:28:09 (current, has Show Pages)
+core/__pycache__/system_prompt_injection.cpython-313.pyc
+ mtime 2026-05-24 04:12:05 (rebuilt by PID 70784)
+PID 60609 start 2026-05-20 12:21:01 (in-memory: pre-upgrade)
+```
+
+The upgrade reached disk; only the live process did not.
+
+## 3. Root cause — eight defects in the restart path
+
+Severities: **CRIT** breaks the invariant "one service per data dir";
+**HIGH** causes silent or incorrect status reports; **MED** is observability.
+
+### B1 — `stderr=DEVNULL` swallows every failure in delayed restart [CRIT]
+
+`vibe/api.py:118-125` (`_spawn_delayed_restart`):
+
+```python
+subprocess.Popen(
+ helper_cmd,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL, # ← every failure is invisible
+ start_new_session=True,
+ close_fds=True,
+ cwd=cwd,
+)
+```
+
+The helper subprocess and the eventual `vibe restart` it spawns both
+discard their stderr. `ImportError`, `FileNotFoundError`, permission
+errors, uncaught exceptions in `cmd_stop` / `cmd_start` — all silent.
+The caller receives "Restart scheduled in 1 minute" and has no way to
+know whether the delayed work succeeded.
+
+### B2 — `stop_process` unlinks pidfile even when kill fails [CRIT]
+
+`core/runtime.py:390-399`:
+
+```python
+def stop_process(pid_path, timeout=5):
+ if not pid_path.exists():
+ return False
+ pid = int(pid_path.read_text(encoding="utf-8").strip())
+ if not pid_alive(pid):
+ pid_path.unlink(missing_ok=True)
+ return False
+ stopped = stop_pid(pid, timeout=timeout)
+ pid_path.unlink(missing_ok=True) # ← unconditional even when stopped=False
+ return stopped
+```
+
+If `stop_pid` returns `False` (PermissionError, ProcessLookupError, or
+signal-handler hang past timeout that still ate SIGKILL), the pidfile is
+removed regardless. The next `start_service` then sees "no pidfile, no
+service" and unconditionally spawns a fresh one — leaving the original
+process alive and untracked.
+
+**This is the direct mechanism by which PID 60609 and PID 70784 ended up
+coexisting.**
+
+### B3 — `stop_pid` can report success after SIGKILL without re-checking liveness [CRIT]
+
+`core/runtime.py:329-364`:
+
+```python
+try:
+ os.kill(pid, signal.SIGKILL)
+except ProcessLookupError:
+ return True
+except OSError:
+ pass
+return True
+```
+
+After the SIGKILL send succeeds, the function returned `True` without
+confirming that the process actually exited. This means `stop_process`
+could receive a false success and remove the pidfile even when the target
+was still alive. The P1 implementation now polls after SIGKILL and returns
+`False` if the process remains live.
+
+### B4 — `start_service` never scans for orphan vibe processes [CRIT]
+
+`core/runtime.py:474-502`:
+
+```python
+def start_service():
+ with _SERVICE_LOCK:
+ pid_path = paths.get_runtime_pid_path()
+ if pid_path.exists():
+ try:
+ existing_pid = int(pid_path.read_text(...).strip())
+ except Exception:
+ existing_pid = 0
+ if existing_pid and pid_alive(existing_pid):
+ if not _pid_mismatches_service(existing_pid):
+ return existing_pid
+ logger.warning("Ignoring stale service pid file ...")
+ pid_path.unlink(missing_ok=True)
+ main_path = get_service_main_path()
+ return spawn_background([sys.executable, str(main_path)], pid_path, ...)
+```
+
+The pidfile is the sole source of truth. If it lies (B2) or is missing,
+`start_service` happily spawns a duplicate. No `pgrep -f service_main.py`,
+no `psutil`-based scan, no port-in-use probe. Combined with B2, this
+makes "two services for one data dir" a stable state instead of an
+immediate failure.
+
+### B5 — `cmd_stop` ignores return value; `_cmd_restart_with_delay` proceeds anyway [HIGH]
+
+`vibe/cli.py:3407-3416` and `vibe/cli.py:4109-4117`:
+
+```python
+def cmd_stop():
+ runtime.stop_service() # ← return value discarded
+ runtime.stop_ui()
+ ...
+
+def _cmd_restart_with_delay(delay_seconds: float) -> int:
+ if delay_seconds > 0:
+ return _schedule_delayed_restart(delay_seconds)
+ print("Restarting vibe services...")
+ cmd_stop() # ← failure not surfaced
+ print("Waiting 3 seconds...")
+ time.sleep(3)
+ return cmd_start() # ← runs even if stop failed
+```
+
+Restart proceeds even if the prior stop did not actually kill anything.
+
+### B6 — `do_upgrade` returns "Restarting..." before restart attempts to run [HIGH]
+
+`vibe/api.py:1591-1648`:
+
+```python
+if auto_restart:
+ _spawn_delayed_restart( # fire-and-forget, default delay=2s
+ get_restart_invocation_command(vibe_path=current_vibe_path),
+ safe_cwd,
+ env=get_restart_environment(vibe_path=current_vibe_path),
+ )
+ restarting = True
+return {
+ "ok": True,
+ "message": "Upgrade successful." + (" Restarting..." if restarting else " Please restart vibe."),
+ "restarting": restarting, # ← reported as success ~2s before the restart even fires
+}
+```
+
+The HTTP response is constructed and returned before the restart attempt
+runs. Web UI shows green "Restarted" purely on the HTTP 200, independent
+of the actual outcome.
+
+### B7 — Web UI `/control` runs stop+start inside the UI server process [HIGH]
+
+`vibe/ui_server.py:1436-1445`:
+
+```python
+elif action == "restart":
+ runtime.write_status("restarting", ...)
+ runtime.stop_service() # same buggy stop as B2
+ _stop_opencode_server()
+ time.sleep(3)
+ runtime.ensure_config()
+ service_pid = runtime.start_service() # same blind start as B3
+ runtime.write_status("running", "restarted", service_pid, ...)
+```
+
+The UI server is a peer of the vibe service (both orphans with `PPID=1`);
+killing the vibe service does not kill the UI server. The UI server then
+writes `state="running"` and `detail="restarted"` to status, irrespective
+of whether the kill or the start actually succeeded. The Web UI surfaces
+this as a green status.
+
+### B8 — Delayed helper exits immediately; no audit of outcome [MED]
+
+`vibe/api.py:111-117` builds the helper code:
+
+```python
+helper_code = (
+ "import subprocess, time\n"
+ f"time.sleep({delay_seconds!r})\n"
+ f"subprocess.Popen({command!r}, cwd={cwd!r}, env={env!r}, "
+ "stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, close_fds=True)\n"
+)
+```
+
+After the helper's `Popen` returns, the helper exits. Nothing waits for
+or inspects the spawned `vibe restart`. Combined with B1, the entire
+delayed restart path is fire-and-forget with no audit trail.
+
+## 4. Goal
+
+After this fix, the following invariants must hold:
+
+1. At most one `service_main.py` process per `VIBE_REMOTE_HOME` data dir
+ at any time. A second invocation either reuses the existing one or
+ fails loudly.
+2. Every `vibe restart` (CLI direct, CLI delayed, Web UI, `do_upgrade`
+ auto-restart) leaves a durable audit record: timestamp, old PID, new
+ PID, stop result, start result, health-check result.
+3. The HTTP response from `do_upgrade` and `/control` `action=restart`
+ only reports success after the new service has been verified healthy
+ (or returns a "pending" state if verification is still in flight).
+4. An Agent can request a restart through the documented path and
+ receive a verifiable success/failure result in the *next* turn,
+ without crash-killing itself mid-restart.
+
+## 5. Solution
+
+The first-principles boundary is:
+
+> Same `VIBE_REMOTE_HOME` means same service identity. Exactly one process may
+> own that service identity at a time.
+
+Pidfiles are now treated as auxiliary status, not the source of running
+authority. The service process itself owns the runtime lock for its entire
+life. Restart is delegated to an external supervisor job, so a caller inside
+an Agent process does not half-stop its own parent service.
+
+### Implemented architecture
+
+Implemented in this branch:
+
+- `service_main` acquires `runtime/service.lock` before starting the
+ controller and holds it until process exit.
+- `start_service` refuses to spawn a second service when the lock is held
+ without a matching live pidfile.
+- the service writes `vibe.pid` only after it owns the lock; parent
+ processes no longer predeclare pidfile ownership.
+- `stop_pid` verifies liveness after SIGKILL and returns failure if the
+ process survives.
+- `stop_process` preserves pidfiles when a live process fails to stop.
+- `vibe restart`, `vibe restart --delay-seconds`, Web UI `/control`
+ restart, and upgrade auto-restart all schedule the same restart supervisor
+ job.
+- the supervisor writes `runtime/restart_status.json` and
+ `logs/restart-*.log`, then performs stop/start outside the Agent or UI
+ request path.
+- `vibe status` includes the latest restart job status so an Agent can check
+ the result in the next turn.
+
+Follow-up, if desired:
+
+- richer UI display for restart pending/succeeded/failed.
+- optional launchd/systemd integration as a separate product-level service
+ manager migration.
+
+### Why not process scanning as the main fix?
+
+Scanning can be useful for diagnostics, but it is the wrong primary
+boundary. A process list answers "what looks like a service process right
+now?" The product invariant is different: "who owns this data directory?"
+The lock answers the invariant directly and avoids false positives across
+different worktrees, installs, and `VIBE_REMOTE_HOME` values.
+
+## 6. Implementation plan
+
+Implemented as one coherent restart rewrite:
+
+1. Add `runtime/service.lock` and `runtime/restart_status.json` paths.
+2. Add service lifetime lock acquire/release in `main.py`.
+3. Move service pidfile writing into the service process after lock acquire.
+4. Make `start_service` wait for pidfile confirmation after spawning.
+5. Add `vibe/restart_supervisor.py` as the single restart job runner.
+6. Route CLI restart, delayed restart, Web UI restart, and upgrade
+ auto-restart through `schedule_restart`.
+7. Include latest restart job status in `vibe status`.
+
+## 7. Test plan
+
+### 7.1 Unit / contract
+
+- `tests/test_runtime_service_lock.py`
+ - existing live pid is reused.
+ - unrelated pidfile is ignored and replacement waits for service lock
+ confirmation.
+ - lock holder without matching live pidfile raises
+ `ServiceAlreadyRunningError`.
+ - lock acquisition blocks a second holder.
+- `tests/test_restart_supervisor.py`
+ - scheduling creates a restart job, log, detached supervisor, and status.
+ - restart job stops then starts through the stable CLI invocation.
+ - stop failure aborts before start and records a failed job.
+- `tests/test_vibe_cli.py`
+ - delayed restart schedules supervisor work without touching stop/start
+ locally.
+ - direct restart also schedules supervisor work.
+ - stop failure preserves pidfile.
+- `tests/test_ui_server_logs.py`
+ - Web UI restart schedules supervisor work and returns job metadata.
+
+### 7.2 Scenario harness
+
+Future scenario harness candidates under `tests/scenarios/restart_orphan/`:
+
+- `restart_orphan/clean_restart` — happy path; one PID before → one PID after,
+ pidfile points to new PID, logs show stop=ok start=ok.
+- `restart_orphan/double_spawn_recovery` — start a service, simulate the
+ bug by manually leaving a fake service lock holder, call `vibe start` →
+ must raise structured error and not duplicate.
+- `restart_orphan/agent_triggered` — exercise
+ `vibe restart --delay-seconds 60` end-to-end through the regression
+ harness, assert `vibe status` reports the restart job result.
+
+### 7.3 Manual regression
+
+After this branch lands:
+
+1. If an old service is still alive, stop it manually once; old code did
+ not hold `service.lock`.
+2. Start the new service and confirm `runtime/service.lock` and
+ `runtime/vibe.pid` are written by the service process.
+3. From an Agent run, trigger `vibe restart --delay-seconds 60`, then check
+ `vibe status` after the delay; it should show a succeeded restart job
+ and exactly one service PID.
+
+## 8. Risks and open questions
+
+1. **launchd / systemd dependency.** P3.2 is opt-in or required? If
+ required, we break headless installs (Docker, plain Linux). Suggestion:
+ keep the spawn_background path as a fallback when no service-manager
+ integration is registered.
+2. **What counts as "the same install"?** Resolved here: same
+ `VIBE_REMOTE_HOME` means same service identity, regardless of Python
+ install path.
+4. **Stop-grace window.** Some IM backends (Lark websocket reconnect
+ loops, OpenCode server) may need more than 5s to flush. Should
+ `stop_pid` default timeout be raised to 15s? Or expose
+ `VIBE_STOP_TIMEOUT_SECONDS`?
+4. **Old-version orphan cleanup.** A pre-fix orphan cannot hold the new lock.
+ Operators may need to kill it once during rollout. After that, the lock
+ prevents recurrence.
+
+## 9. References
+
+- This bug report and its visual analysis live at the user's Show Page
+ for session `sesszcbv24wp8` (private; URL shared in IM).
+- The merged feature whose absence first surfaced the bug:
+ PR #331 `feat(show): list show pages` (2026-05-24).
+- Root cause file paths (master at time of triage):
+ - `core/runtime.py:329-399` — `stop_pid` / `stop_process`
+ - `core/runtime.py:474-502` — `start_service`
+ - `vibe/restart_supervisor.py` — unified restart job runner
+ - `vibe/api.py:1591-1648` — `do_upgrade`
+ - `vibe/ui_server.py:1416-1446` — `/control` restart endpoint
+ - `vibe/cli.py:3329-3416, 4077-4117` — `cmd_start` / `cmd_stop` / `cmd_restart`
diff --git a/main.py b/main.py
index 7c3b303c5..f1d1db445 100644
--- a/main.py
+++ b/main.py
@@ -10,7 +10,13 @@ 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_sentry
-from vibe.runtime import consume_shutdown_intent, shutdown_intent_required
+from vibe.runtime import (
+ ServiceAlreadyRunningError,
+ acquire_service_instance_lock,
+ consume_shutdown_intent,
+ release_service_instance_lock,
+ shutdown_intent_required,
+)
def _build_logging_handlers(logs_dir: str) -> list[logging.Handler]:
@@ -105,6 +111,7 @@ def main():
# Setup logging
setup_logging(config.runtime.log_level)
logger = logging.getLogger(__name__)
+ acquire_service_instance_lock()
apply_claude_sdk_patches()
init_sentry(config, component="service")
@@ -147,13 +154,21 @@ def main():
controller.cleanup_sync()
except Exception as cleanup_err:
logger.error(f"Cleanup failed: {cleanup_err}")
+ finally:
+ release_service_instance_lock()
raise SystemExit(0)
signal.signal(signal.SIGTERM, _handle_shutdown)
signal.signal(signal.SIGINT, _handle_shutdown)
- controller.run()
+ try:
+ controller.run()
+ finally:
+ release_service_instance_lock()
+ except ServiceAlreadyRunningError as e:
+ logging.error("Failed to start: %s", e)
+ sys.exit(2)
except Exception as e:
logging.error(f"Failed to start: {e}")
sys.exit(1)
diff --git a/tests/test_restart_supervisor.py b/tests/test_restart_supervisor.py
new file mode 100644
index 000000000..5b4e60b8d
--- /dev/null
+++ b/tests/test_restart_supervisor.py
@@ -0,0 +1,91 @@
+from __future__ import annotations
+
+import subprocess
+
+from config import paths
+from vibe import restart_supervisor
+from vibe import runtime
+
+
+def test_schedule_restart_spawns_supervisor_and_records_status(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ paths.get_runtime_pid_path().write_text("12345", encoding="utf-8")
+ calls = {}
+
+ 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: {"PATH": "/bin"})
+ monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))
+ monkeypatch.setattr(restart_supervisor, "_prune_restart_logs", lambda: None)
+
+ def fake_popen(command, **kwargs):
+ calls["command"] = command
+ calls["kwargs"] = kwargs
+
+ class Proc:
+ pid = 45678
+
+ return Proc()
+
+ monkeypatch.setattr(restart_supervisor.subprocess, "Popen", fake_popen)
+
+ result = restart_supervisor.schedule_restart(delay_seconds=60, vibe_path="/bin/vibe", trigger="agent")
+
+ assert result["state"] == "scheduled"
+ assert result["supervisor_pid"] == 45678
+ assert result["old_pid"] == 12345
+ assert calls["command"][:2] == ["/bin/vibe", "__restart-supervisor"]
+ assert calls["command"][calls["command"].index("--delay-seconds") + 1] == "60"
+ assert calls["kwargs"]["start_new_session"] is True
+ assert calls["kwargs"]["env"] == {"PATH": "/bin"}
+ assert runtime.read_json(runtime.get_restart_status_path())["job_id"] == result["job_id"]
+
+
+def test_restart_job_stops_and_starts_service(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_service", lambda: calls.append("stop") 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(runtime, "pid_alive", 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", ("run", ["/bin/vibe", "start"])]
+ status = runtime.read_json(runtime.get_restart_status_path())
+ assert status["ok"] is True
+ assert status["state"] == "succeeded"
+ assert status["old_pid"] == 111
+ assert status["new_pid"] == 222
+
+
+def test_restart_job_aborts_when_stop_fails(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_service", lambda: calls.append("stop") or False)
+ 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"]
+ status = runtime.read_json(runtime.get_restart_status_path())
+ assert status["ok"] is False
+ assert status["state"] == "failed"
+ assert "did not stop" in status["error"]
diff --git a/tests/test_runtime_service_lock.py b/tests/test_runtime_service_lock.py
index e6c4d1a7e..12d2423f0 100644
--- a/tests/test_runtime_service_lock.py
+++ b/tests/test_runtime_service_lock.py
@@ -1,3 +1,4 @@
+import os
import sys
import tempfile
import unittest
@@ -32,19 +33,20 @@ class RuntimeServiceLockTests(unittest.TestCase):
pid_path = Path(tmpdir) / "service.pid"
pid_path.write_text("12345", encoding="utf-8")
- def fake_spawn(args, target_pid_path, stdout_name, stderr_name, env=None):
- target_pid_path.write_text("67890", encoding="utf-8")
+ def fake_spawn(args, stdout_name, stderr_name, env=None):
return 67890
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.spawn_background", side_effect=fake_spawn) as spawn_background:
- pid = runtime.start_service()
+ 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.wait_for_service_pid", return_value=True):
+ pid = runtime.start_service()
self.assertEqual(pid, 67890)
spawn_background.assert_called_once()
- self.assertEqual(pid_path.read_text(encoding="utf-8"), "67890")
+ self.assertFalse(pid_path.exists())
def test_start_service_reuses_live_pid_when_command_is_unreadable(self):
with tempfile.TemporaryDirectory() as tmpdir:
@@ -60,5 +62,49 @@ class RuntimeServiceLockTests(unittest.TestCase):
self.assertEqual(pid, 12345)
spawn_background.assert_not_called()
+ def test_start_service_errors_when_lock_holder_is_not_recorded_pid(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_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 self.assertRaises(runtime.ServiceAlreadyRunningError):
+ runtime.start_service()
+
+ spawn_background.assert_not_called()
+
+ def test_start_service_errors_when_spawned_process_never_acquires_lock(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_instance_lock_available", return_value=(True, None)):
+ with patch("vibe.runtime.spawn_service_background", return_value=67890):
+ with patch("vibe.runtime.wait_for_service_pid", return_value=False):
+ with self.assertRaises(RuntimeError):
+ runtime.start_service()
+
+ def test_service_instance_lock_blocks_second_holder(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ runtime_dir = Path(tmpdir) / "runtime"
+ runtime_dir.mkdir(parents=True)
+ lock_path = runtime_dir / "service.lock"
+ pid_path = runtime_dir / "vibe.pid"
+
+ with patch("vibe.runtime.paths.get_runtime_service_lock_path", return_value=lock_path):
+ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
+ with patch("vibe.runtime.paths.ensure_data_dirs", return_value=None):
+ runtime.acquire_service_instance_lock()
+ try:
+ available, holder_pid = runtime.service_instance_lock_available()
+ finally:
+ runtime.release_service_instance_lock()
+
+ self.assertFalse(available)
+ self.assertEqual(holder_pid, os.getpid())
+ self.assertFalse(pid_path.exists())
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_ui_server_logs.py b/tests/test_ui_server_logs.py
index 624e13bd6..ff5f6ed38 100644
--- a/tests/test_ui_server_logs.py
+++ b/tests/test_ui_server_logs.py
@@ -247,3 +247,29 @@ def test_control_start_reuses_running_service_without_stop(monkeypatch, tmp_path
assert calls == ["ensure_config", "start_service"]
payload = response.get_json()
assert payload["status"]["service_pid"] == 12345
+
+
+def test_control_restart_schedules_restart_job(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ runtime.write_status("running", detail="running", service_pid=12345, ui_pid=67890)
+ paths.get_runtime_pid_path().write_text("12345", encoding="utf-8")
+ calls = []
+
+ import vibe.restart_supervisor as restart_supervisor
+
+ monkeypatch.setattr(
+ restart_supervisor,
+ "schedule_restart",
+ lambda **kwargs: calls.append(kwargs) or {"job_id": "job123", "state": "scheduled"},
+ )
+
+ client = app.test_client()
+ response = client.post("/control", json={"action": "restart"}, headers=csrf_headers(client))
+
+ assert response.status_code == 200
+ payload = response.get_json()
+ assert payload["ok"] is True
+ assert payload["restart"]["job_id"] == "job123"
+ assert runtime.read_status()["state"] == "restarting"
+ assert calls == [{"delay_seconds": 0.0, "trigger": "web-ui"}]
diff --git a/tests/test_upgrade_flow.py b/tests/test_upgrade_flow.py
index 7e9338dec..cf8d88ece 100644
--- a/tests/test_upgrade_flow.py
+++ b/tests/test_upgrade_flow.py
@@ -324,26 +324,14 @@ def test_do_upgrade_uses_upgrade_plan_env_and_restarts(monkeypatch):
monkeypatch.setattr(api, "build_upgrade_plan", lambda **kwargs: plan)
monkeypatch.setattr(api, "get_running_vibe_path", lambda: "/custom/bin/vibe")
- monkeypatch.setattr(api, "get_restart_invocation_command", lambda **kwargs: ["/custom/bin/vibe", "restart"])
- monkeypatch.setattr(api, "get_restart_environment", lambda **kwargs: None)
- monkeypatch.setattr(api, "_delayed_restart_helper_command", lambda: ["/usr/bin/python3"])
+ monkeypatch.setattr(api, "schedule_restart", lambda **kwargs: calls.setdefault("restart_kwargs", kwargs))
def fake_run(cmd, **kwargs):
calls["run_cmd"] = cmd
calls["run_kwargs"] = kwargs
return subprocess.CompletedProcess(cmd, 0, stdout="done", stderr="")
- def fake_popen(cmd, **kwargs):
- calls["popen_cmd"] = cmd
- calls["popen_kwargs"] = kwargs
-
- class _Proc:
- pass
-
- return _Proc()
-
monkeypatch.setattr(api.subprocess, "run", fake_run)
- monkeypatch.setattr(api.subprocess, "Popen", fake_popen)
result = api.do_upgrade(auto_restart=True)
assert result["ok"] is True
@@ -355,36 +343,7 @@ def test_do_upgrade_uses_upgrade_plan_env_and_restarts(monkeypatch):
assert calls["run_kwargs"]["env"] == plan.env
safe_cwd = calls["run_kwargs"].get("cwd")
assert safe_cwd and os.path.isabs(safe_cwd), f"subprocess.run cwd must be an absolute path, got {safe_cwd!r}"
- assert calls["popen_cmd"][0] == "/usr/bin/python3"
- assert calls["popen_cmd"][1] == "-c"
- assert "time.sleep(2.0)" in calls["popen_cmd"][2]
- assert "/custom/bin/vibe" in calls["popen_cmd"][2]
- assert "['/custom/bin/vibe', 'restart']" in calls["popen_cmd"][2]
- assert calls["popen_kwargs"]["start_new_session"] is True
- popen_cwd = calls["popen_kwargs"].get("cwd")
- assert popen_cwd and os.path.isabs(popen_cwd), f"Popen cwd must be an absolute path, got {popen_cwd!r}"
-
-
-def test_delayed_restart_helper_prefers_stable_launcher_over_sys_executable(monkeypatch):
- monkeypatch.setattr(api.os, "name", "posix", raising=False)
- monkeypatch.setattr(api.shutil, "which", lambda binary: f"/usr/bin/{binary}" if binary == "python3" else None)
- monkeypatch.setattr(api.sys, "executable", "/volatile/.venv/bin/python", raising=False)
-
- monkeypatch.setattr(api.os.path, "exists", lambda path: path == "/volatile/.venv/bin/python")
- monkeypatch.setattr(api.os, "access", lambda path, mode: path == "/volatile/.venv/bin/python")
-
- assert api._delayed_restart_helper_command() == ["/volatile/.venv/bin/python"]
-
-
-def test_delayed_restart_helper_skips_missing_sys_executable_on_windows(monkeypatch):
- monkeypatch.setattr(api.os, "name", "nt", raising=False)
- monkeypatch.setattr(api.sys, "executable", "C:\\missing\\python.exe", raising=False)
- monkeypatch.setattr(api.os.path, "isabs", lambda path: path.startswith("C:\\"))
- monkeypatch.setattr(api.os.path, "exists", lambda path: False)
- monkeypatch.setattr(api.os, "access", lambda path, mode: False)
- monkeypatch.setattr(api.shutil, "which", lambda binary: "C:\\Python311\\python.exe" if binary == "python" else None)
-
- assert api._delayed_restart_helper_command() == ["C:\\Python311\\python.exe"]
+ assert calls["restart_kwargs"] == {"delay_seconds": 2.0, "vibe_path": "/custom/bin/vibe", "trigger": "upgrade"}
def test_cmd_upgrade_uses_upgrade_plan_env(monkeypatch):
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index 82a54db9e..4cc19846c 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -75,6 +75,34 @@ def test_stop_process_delegates_to_windows_terminator(tmp_path, monkeypatch):
assert not pid_path.exists()
+def test_stop_process_preserves_pidfile_when_stop_fails(tmp_path, monkeypatch):
+ pid_path = tmp_path / "service.pid"
+ pid_path.write_text("12345", encoding="utf-8")
+
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 12345)
+ monkeypatch.setattr(runtime, "stop_pid", lambda pid, timeout=5: False)
+
+ assert runtime.stop_process(pid_path) is False
+ assert pid_path.exists()
+ assert pid_path.read_text(encoding="utf-8") == "12345"
+
+
+def test_stop_pid_reports_failure_when_sigkill_does_not_terminate(monkeypatch):
+ monkeypatch.setattr(runtime.os, "name", "posix", raising=False)
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: True)
+ monkeypatch.setattr(runtime, "write_shutdown_intent", lambda *args, **kwargs: None)
+ monkeypatch.setattr(runtime.time, "sleep", lambda _seconds: None)
+ calls = []
+
+ def _kill(pid, sig):
+ calls.append((pid, sig))
+
+ monkeypatch.setattr(runtime.os, "kill", _kill)
+
+ assert runtime.stop_pid(12345, timeout=0) is False
+ assert calls == [(12345, signal.SIGTERM), (12345, signal.SIGKILL)]
+
+
def test_cli_stop_process_reuses_runtime_impl(tmp_path, monkeypatch):
pid_path = tmp_path / "service.pid"
pid_path.write_text("123", encoding="utf-8")
@@ -109,71 +137,81 @@ def test_cmd_restart_schedules_delayed_restart(monkeypatch, capsys):
start_called = []
monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: "/usr/local/bin/vibe")
- monkeypatch.setattr(cli, "get_restart_invocation_command", lambda vibe_path=None: [vibe_path or "vibe", "restart"])
- monkeypatch.setattr(cli, "get_restart_environment", lambda vibe_path=None: None)
- monkeypatch.setattr(cli, "get_safe_cwd", lambda: "/tmp")
monkeypatch.setattr(
cli.api,
- "_spawn_delayed_restart",
- lambda command, cwd, delay_seconds=2.0, env=None: scheduled.update(
- {"command": command, "cwd": cwd, "delay_seconds": delay_seconds, "env": env}
- ),
+ "schedule_restart",
+ lambda **kwargs: scheduled.update(kwargs) or {"job_id": "job123"},
+ raising=False,
)
+ monkeypatch.setattr(cli, "schedule_restart", lambda **kwargs: scheduled.update(kwargs) or {"job_id": "job123"})
monkeypatch.setattr(cli, "cmd_stop", lambda: stop_called.append(True))
monkeypatch.setattr(cli, "cmd_vibe", lambda: start_called.append(True))
assert cli._cmd_restart_with_delay(60) == 0
assert scheduled == {
- "command": ["/usr/local/bin/vibe", "restart"],
- "cwd": "/tmp",
"delay_seconds": 60,
- "env": None,
+ "vibe_path": "/usr/local/bin/vibe",
+ "trigger": "cli",
}
assert stop_called == []
assert start_called == []
output = capsys.readouterr().out
assert "Restart scheduled in 1 minute." in output
- assert "delayed restart will run in the background" in output
+ assert "Job ID: job123" in output
+ assert "restart supervisor will run in the background" in output
-def test_cmd_restart_schedules_delayed_restart_with_import_env(monkeypatch):
+def test_cmd_restart_schedules_delayed_restart_without_cached_vibe(monkeypatch):
scheduled = {}
monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: None)
- monkeypatch.setattr(
- cli,
- "get_restart_invocation_command",
- lambda vibe_path=None: [sys.executable, "-c", "from vibe.cli import main; main()", "restart"],
- )
- monkeypatch.setattr(cli, "get_restart_environment", lambda vibe_path=None: {"PYTHONPATH": "/repo"})
- monkeypatch.setattr(cli, "get_safe_cwd", lambda: "/tmp")
- monkeypatch.setattr(
- cli.api,
- "_spawn_delayed_restart",
- lambda command, cwd, delay_seconds=2.0, env=None: scheduled.update(
- {"command": command, "cwd": cwd, "delay_seconds": delay_seconds, "env": env}
- ),
- )
+ monkeypatch.setattr(cli, "schedule_restart", lambda **kwargs: scheduled.update(kwargs) or {"job_id": "job456"})
assert cli._cmd_restart_with_delay(5) == 0
assert scheduled == {
- "command": [sys.executable, "-c", "from vibe.cli import main; main()", "restart"],
- "cwd": "/tmp",
"delay_seconds": 5,
- "env": {"PYTHONPATH": "/repo"},
+ "vibe_path": None,
+ "trigger": "cli",
}
-def test_cmd_restart_runs_synchronously_by_default(monkeypatch):
+def test_cmd_restart_schedules_supervisor_by_default(monkeypatch):
calls = []
- monkeypatch.setattr(cli, "cmd_stop", lambda: calls.append("stop") or 0)
- monkeypatch.setattr(cli, "cmd_start", lambda: calls.append("start") or 0)
- monkeypatch.setattr(cli.time, "sleep", lambda seconds: calls.append(("sleep", seconds)))
+ monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: "/usr/local/bin/vibe")
+ monkeypatch.setattr(cli, "schedule_restart", lambda **kwargs: calls.append(kwargs) or {"job_id": "job789"})
assert cli._cmd_restart_with_delay(0) == 0
- assert calls == ["stop", ("sleep", 3), "start"]
+ assert calls == [{"delay_seconds": 0.0, "vibe_path": "/usr/local/bin/vibe", "trigger": "cli"}]
+
+
+def test_cmd_stop_ignores_absent_services(monkeypatch):
+ status = []
+
+ monkeypatch.setattr(cli, "_pid_file_points_to_live_process", lambda path: False)
+ monkeypatch.setattr(runtime, "stop_service", lambda: False)
+ monkeypatch.setattr(runtime, "stop_ui", lambda: False)
+ monkeypatch.setattr(cli, "_stop_opencode_server", lambda: False)
+ monkeypatch.setattr(cli, "_write_status", lambda state, detail=None: status.append((state, detail)))
+
+ assert cli.cmd_stop() == 0
+ assert status == [("stopped", None)]
+
+
+def test_cmd_stop_fails_when_live_service_survives(monkeypatch, capsys):
+ status = []
+ service_pid = paths.get_runtime_pid_path()
+
+ monkeypatch.setattr(cli, "_pid_file_points_to_live_process", lambda path: path == service_pid)
+ monkeypatch.setattr(runtime, "stop_service", lambda: False)
+ monkeypatch.setattr(runtime, "stop_ui", lambda: False)
+ monkeypatch.setattr(cli, "_stop_opencode_server", lambda: False)
+ monkeypatch.setattr(cli, "_write_status", lambda state, detail=None: status.append((state, detail)))
+
+ assert cli.cmd_stop() == 2
+ assert status == [("error", "service stop failed")]
+ assert "Vibe service did not stop" in capsys.readouterr().err
def test_cmd_vibe_uses_restart_compatibility_default(monkeypatch):
diff --git a/vibe/api.py b/vibe/api.py
index 2665eb39b..73e5617f5 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -6,7 +6,6 @@ import re
import shutil
import ssl
import subprocess
-import sys
import threading
import time
import urllib.parse
@@ -39,11 +38,10 @@ from vibe.opencode_config import (
from vibe.upgrade import (
build_upgrade_plan,
get_latest_version_info,
- get_restart_environment,
- get_restart_invocation_command,
get_running_vibe_path,
get_safe_cwd,
)
+from vibe.restart_supervisor import schedule_restart
from vibe.claude_model_catalog import DEFAULT_CLAUDE_MODEL_ALIASES, load_catalog_models
from modules.agents.catalog import (
agent_backend_catalog_payload,
@@ -69,7 +67,6 @@ logger = logging.getLogger(__name__)
_OPENCODE_OPTIONS_CACHE: dict[str, dict] = {}
_OPENCODE_OPTIONS_TTL_SECONDS = 30.0
-
def _parse_agent_import_file(path: Path, *, backend: str):
try:
return parse_agent_file(path, backend=backend)
@@ -77,54 +74,6 @@ def _parse_agent_import_file(path: Path, *, backend: str):
raise ValueError(f"Unable to read or parse agent import file: {exc}") from exc
-def _delayed_restart_helper_command() -> list[str]:
- candidates: list[list[str]] = []
- current = sys.executable
-
- if current and os.path.isabs(current) and os.path.exists(current) and os.access(current, os.X_OK):
- candidates.append([current])
-
- if os.name == "nt":
- candidates.extend((["py", "-3"], ["python"], ["python3"]))
- else:
- candidates.extend((["python3"], ["python"]))
-
- for candidate in candidates:
- binary = candidate[0]
- if os.path.isabs(binary):
- if os.path.exists(binary) and os.access(binary, os.X_OK):
- return candidate
- continue
- resolved = shutil.which(binary)
- if resolved:
- return [resolved, *candidate[1:]]
-
- raise FileNotFoundError("No stable Python launcher available for delayed restart helper")
-
-
-def _spawn_delayed_restart(
- command: list[str],
- cwd: str,
- delay_seconds: float = 2.0,
- env: dict[str, str] | None = None,
-) -> None:
- helper_code = (
- "import subprocess, time\n"
- f"time.sleep({delay_seconds!r})\n"
- f"subprocess.Popen({command!r}, cwd={cwd!r}, env={env!r}, stdout=subprocess.DEVNULL, "
- "stderr=subprocess.DEVNULL, close_fds=True)\n"
- )
- helper_cmd = [*_delayed_restart_helper_command(), "-c", helper_code]
- subprocess.Popen(
- helper_cmd,
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- start_new_session=True,
- close_fds=True,
- cwd=cwd,
- )
-
-
def _is_executable_file(path: Path) -> bool:
return path.exists() and path.is_file() and os.access(path, os.X_OK)
@@ -1617,11 +1566,7 @@ def do_upgrade(auto_restart: bool = True) -> dict:
if result.returncode == 0:
restarting = False
if auto_restart:
- _spawn_delayed_restart(
- get_restart_invocation_command(vibe_path=current_vibe_path),
- safe_cwd,
- env=get_restart_environment(vibe_path=current_vibe_path),
- )
+ schedule_restart(delay_seconds=2.0, vibe_path=current_vibe_path, trigger="upgrade")
restarting = True
return {
diff --git a/vibe/cli.py b/vibe/cli.py
index e8c4b5a37..e045dc93d 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -48,13 +48,12 @@ from core.watches import (
WatchRuntimeStateStore,
)
from vibe import __version__, api, runtime
+from vibe.restart_supervisor import schedule_restart
from vibe.screenshot import ScreenshotError, capture_screenshot
from vibe.upgrade import (
build_upgrade_plan,
cache_running_vibe_path,
get_latest_version_info,
- get_restart_environment,
- get_restart_invocation_command,
get_safe_cwd,
)
from storage.db import create_sqlite_engine
@@ -3404,14 +3403,35 @@ def _stop_opencode_server():
return False
+def _pid_file_points_to_live_process(pid_path: Path) -> bool:
+ try:
+ raw_pid = pid_path.read_text(encoding="utf-8").strip()
+ pid = int(raw_pid)
+ except (OSError, ValueError):
+ return False
+ return _pid_alive(pid)
+
+
def cmd_stop():
- runtime.stop_service()
- runtime.stop_ui()
+ service_was_running = _pid_file_points_to_live_process(paths.get_runtime_pid_path())
+ ui_was_running = _pid_file_points_to_live_process(paths.get_runtime_ui_pid_path())
+
+ service_stopped = runtime.stop_service()
+ ui_stopped = runtime.stop_ui()
# Also terminate OpenCode server on full stop
if _stop_opencode_server():
print("OpenCode server stopped")
+ if service_was_running and service_stopped is False:
+ print("ERROR: Vibe service did not stop; preserving pidfile and aborting.", file=sys.stderr)
+ _write_status("error", "service stop failed")
+ return 2
+ if ui_was_running and ui_stopped is False:
+ print("ERROR: Vibe UI did not stop; preserving pidfile and aborting.", file=sys.stderr)
+ _write_status("error", "ui stop failed")
+ return 2
+
_write_status("stopped")
return 0
@@ -4095,14 +4115,10 @@ def _format_restart_delay(delay_seconds: float) -> str:
def _schedule_delayed_restart(delay_seconds: float) -> int:
current_vibe_path = cache_running_vibe_path()
- api._spawn_delayed_restart(
- get_restart_invocation_command(vibe_path=current_vibe_path),
- get_safe_cwd(),
- delay_seconds=delay_seconds,
- env=get_restart_environment(vibe_path=current_vibe_path),
- )
+ result = schedule_restart(delay_seconds=delay_seconds, vibe_path=current_vibe_path, trigger="cli")
print(f"Restart scheduled in {_format_restart_delay(delay_seconds)}.")
- print("This command exits immediately; the delayed restart will run in the background.")
+ print(f"Job ID: {result['job_id']}")
+ print("This command exits immediately; the restart supervisor will run in the background.")
return 0
@@ -4110,11 +4126,11 @@ def _cmd_restart_with_delay(delay_seconds: float) -> int:
if delay_seconds > 0:
return _schedule_delayed_restart(delay_seconds)
- print("Restarting vibe services...")
- cmd_stop()
- print("Waiting 3 seconds...")
- time.sleep(3)
- return cmd_start()
+ result = schedule_restart(delay_seconds=0.0, vibe_path=cache_running_vibe_path(), trigger="cli")
+ print("Restart scheduled.")
+ print(f"Job ID: {result['job_id']}")
+ print("Run `vibe status` to inspect the restart result.")
+ return 0
def build_parser():
@@ -4130,6 +4146,11 @@ def build_parser():
default=0,
help="Schedule the restart to run asynchronously after N seconds, then exit immediately.",
)
+ supervisor_parser = subparsers.add_parser("__restart-supervisor", help=argparse.SUPPRESS)
+ supervisor_parser.add_argument("--job-id", required=True)
+ supervisor_parser.add_argument("--delay-seconds", type=_non_negative_float, default=0)
+ supervisor_parser.add_argument("--trigger", default="cli")
+ supervisor_parser.add_argument("--vibe-path")
subparsers.add_parser("status", help="Show service status")
subparsers.add_parser("doctor", help="Run diagnostics")
subparsers.add_parser("version", help="Show version")
@@ -4882,6 +4903,22 @@ def main():
sys.exit(cmd_start())
if args.command == "restart":
sys.exit(_cmd_restart_with_delay(args.delay_seconds))
+ if args.command == "__restart-supervisor":
+ from vibe.restart_supervisor import main as restart_supervisor_main
+
+ sys.exit(
+ restart_supervisor_main(
+ [
+ "--job-id",
+ args.job_id,
+ "--delay-seconds",
+ str(args.delay_seconds),
+ "--trigger",
+ args.trigger,
+ *(["--vibe-path", args.vibe_path] if args.vibe_path else []),
+ ]
+ )
+ )
if args.command == "status":
sys.exit(cmd_status())
if args.command == "doctor":
diff --git a/vibe/restart_supervisor.py b/vibe/restart_supervisor.py
new file mode 100644
index 000000000..3a3edcd79
--- /dev/null
+++ b/vibe/restart_supervisor.py
@@ -0,0 +1,208 @@
+from __future__ import annotations
+
+import argparse
+import json
+import logging
+import os
+import subprocess
+import sys
+import time
+import uuid
+from pathlib import Path
+
+from config import paths
+from vibe import runtime
+from vibe.upgrade import get_restart_environment, get_restart_invocation_command, get_safe_cwd
+
+
+logger = logging.getLogger(__name__)
+_RESTART_LOG_RETENTION = 10
+
+
+def _now_iso() -> str:
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
+
+
+def _restart_log_path(job_id: str) -> Path:
+ paths.get_logs_dir().mkdir(parents=True, exist_ok=True)
+ timestamp = time.strftime("%Y%m%d-%H%M%S", time.localtime())
+ return paths.get_logs_dir() / f"restart-{timestamp}-{job_id}.log"
+
+
+def _prune_restart_logs(limit: int = _RESTART_LOG_RETENTION) -> None:
+ try:
+ logs = sorted(
+ paths.get_logs_dir().glob("restart-*.log"),
+ key=lambda path: path.stat().st_mtime,
+ reverse=True,
+ )
+ except OSError:
+ logger.debug("Failed to list restart audit logs", exc_info=True)
+ return
+ for path in logs[limit:]:
+ try:
+ path.unlink()
+ except OSError:
+ logger.debug("Failed to prune restart audit log %s", path, exc_info=True)
+
+
+def _write_status(payload: dict) -> None:
+ status = {**payload, "updated_at": _now_iso()}
+ path = runtime.get_restart_status_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ runtime.write_json(path, status)
+
+
+def _read_recorded_pid() -> int | None:
+ pid_path = paths.get_runtime_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 _run_restart_job(
+ *,
+ job_id: str,
+ delay_seconds: float,
+ vibe_path: str | None,
+ trigger: str,
+) -> int:
+ log_path = _restart_log_path(job_id)
+ safe_cwd = get_safe_cwd()
+ _prune_restart_logs()
+
+ with log_path.open("a", encoding="utf-8") as log:
+ def write(message: str) -> None:
+ log.write(f"{_now_iso()} {message}\n")
+ log.flush()
+
+ old_pid = _read_recorded_pid()
+ payload = {
+ "ok": None,
+ "job_id": job_id,
+ "state": "scheduled" if delay_seconds > 0 else "running",
+ "trigger": trigger,
+ "delay_seconds": delay_seconds,
+ "old_pid": old_pid,
+ "new_pid": None,
+ "log_path": str(log_path),
+ "error": None,
+ "created_at": _now_iso(),
+ }
+ _write_status(payload)
+ write(f"restart job scheduled trigger={trigger!r} delay_seconds={delay_seconds!r} old_pid={old_pid!r}")
+
+ if delay_seconds > 0:
+ time.sleep(delay_seconds)
+ payload["state"] = "running"
+ _write_status(payload)
+ write("restart job started after delay")
+
+ write("stopping service")
+ stopped = runtime.stop_service()
+ if old_pid and stopped is False:
+ payload.update(ok=False, state="failed", error=f"service pid {old_pid} did not stop")
+ _write_status(payload)
+ write(payload["error"])
+ return 2
+
+ 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"]
+ result = subprocess.run(
+ start_command,
+ cwd=safe_cwd,
+ env=env,
+ stdout=log,
+ stderr=subprocess.STDOUT,
+ text=True,
+ check=False,
+ timeout=30,
+ )
+ if result.returncode != 0:
+ payload.update(ok=False, state="failed", error=f"start command failed with exit code {result.returncode}")
+ _write_status(payload)
+ write(payload["error"])
+ return result.returncode or 1
+
+ new_pid = _read_recorded_pid()
+ if not new_pid or not runtime.pid_alive(new_pid):
+ payload.update(ok=False, state="failed", error="start command completed but service pid is not alive")
+ _write_status(payload)
+ write(payload["error"])
+ return 3
+
+ payload.update(ok=True, state="succeeded", new_pid=new_pid, error=None)
+ _write_status(payload)
+ write(f"restart job succeeded new_pid={new_pid}")
+ return 0
+
+
+def schedule_restart(
+ *,
+ delay_seconds: float = 0.0,
+ vibe_path: str | None = None,
+ trigger: str = "cli",
+) -> dict:
+ job_id = uuid.uuid4().hex[:12]
+ invocation = get_restart_invocation_command(vibe_path=vibe_path)
+ command = [*invocation[:-1], "__restart-supervisor"] if invocation and invocation[-1] == "restart" else [
+ *(invocation or ["vibe"]),
+ "__restart-supervisor",
+ ]
+ command.extend(["--job-id", job_id, "--delay-seconds", str(delay_seconds), "--trigger", trigger])
+ if vibe_path:
+ command.extend(["--vibe-path", vibe_path])
+ env = get_restart_environment(vibe_path=vibe_path)
+ log_path = _restart_log_path(job_id)
+ log_path.parent.mkdir(parents=True, exist_ok=True)
+ with log_path.open("a", encoding="utf-8") as log:
+ log.write(f"{_now_iso()} spawning restart supervisor job_id={job_id} delay_seconds={delay_seconds!r}\n")
+ log.flush()
+ process = subprocess.Popen(
+ command,
+ stdout=log,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ close_fds=True,
+ cwd=get_safe_cwd(),
+ env=env,
+ )
+ payload = {
+ "ok": None,
+ "job_id": job_id,
+ "state": "scheduled",
+ "trigger": trigger,
+ "delay_seconds": delay_seconds,
+ "supervisor_pid": process.pid,
+ "old_pid": _read_recorded_pid(),
+ "new_pid": None,
+ "log_path": str(log_path),
+ "error": None,
+ "created_at": _now_iso(),
+ }
+ _write_status(payload)
+ _prune_restart_logs()
+ return payload
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--job-id", required=True)
+ parser.add_argument("--delay-seconds", type=float, default=0.0)
+ parser.add_argument("--trigger", default="cli")
+ parser.add_argument("--vibe-path")
+ args = parser.parse_args(argv)
+ return _run_restart_job(
+ job_id=args.job_id,
+ delay_seconds=max(0.0, args.delay_seconds),
+ vibe_path=args.vibe_path,
+ trigger=args.trigger,
+ )
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/vibe/runtime.py b/vibe/runtime.py
index ec3c82fa7..424e0420b 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -87,6 +87,17 @@ def get_working_dir() -> Path:
ROOT_DIR = get_project_root() # For backward compatibility
MAIN_PATH = get_service_main_path()
_SERVICE_LOCK = threading.Lock()
+_SERVICE_INSTANCE_LOCK_HANDLE = None
+
+
+class ServiceAlreadyRunningError(RuntimeError):
+ def __init__(self, *, lock_path: Path, holder_pid: int | None = None):
+ self.lock_path = lock_path
+ self.holder_pid = holder_pid
+ detail = f"Vibe service is already running for this data directory: {lock_path}"
+ if holder_pid:
+ detail = f"{detail} (pid={holder_pid})"
+ super().__init__(detail)
def ensure_dirs():
@@ -133,6 +144,134 @@ def read_json(path):
return None
+def get_restart_status_path() -> Path:
+ return paths.get_runtime_restart_status_path()
+
+
+def get_service_lock_path() -> Path:
+ return paths.get_runtime_service_lock_path()
+
+
+def _lock_file_pid(lock_file) -> int | None:
+ try:
+ lock_file.seek(0)
+ payload = json.loads(lock_file.read() or "{}")
+ except (OSError, json.JSONDecodeError, TypeError):
+ return None
+ pid = payload.get("pid") if isinstance(payload, dict) else None
+ return pid if isinstance(pid, int) and pid > 0 else None
+
+
+def _try_lock_file(lock_file) -> bool:
+ if os.name == "nt":
+ import msvcrt
+
+ try:
+ lock_file.seek(0)
+ msvcrt.locking(lock_file.fileno(), msvcrt.LK_NBLCK, 1)
+ return True
+ except OSError:
+ return False
+
+ import fcntl
+
+ try:
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
+ return True
+ except OSError:
+ return False
+
+
+def _unlock_file(lock_file) -> None:
+ if os.name == "nt":
+ import msvcrt
+
+ try:
+ lock_file.seek(0)
+ msvcrt.locking(lock_file.fileno(), msvcrt.LK_UNLCK, 1)
+ except OSError:
+ logger.debug("Failed to unlock service instance lock", exc_info=True)
+ return
+
+ import fcntl
+
+ try:
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
+ except OSError:
+ logger.debug("Failed to unlock service instance lock", exc_info=True)
+
+
+def acquire_service_instance_lock() -> None:
+ """Acquire the data-dir scoped service runtime lock for this process lifetime."""
+ global _SERVICE_INSTANCE_LOCK_HANDLE
+ if _SERVICE_INSTANCE_LOCK_HANDLE is not None:
+ return
+ paths.ensure_data_dirs()
+ lock_path = get_service_lock_path()
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
+ lock_file = lock_path.open("a+", encoding="utf-8")
+ if not _try_lock_file(lock_file):
+ holder_pid = _lock_file_pid(lock_file)
+ lock_file.close()
+ raise ServiceAlreadyRunningError(lock_path=lock_path, holder_pid=holder_pid)
+ lock_file.seek(0)
+ lock_file.truncate()
+ lock_file.write(
+ json.dumps(
+ {
+ "pid": os.getpid(),
+ "created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
+ "command": get_process_command(os.getpid()),
+ },
+ indent=2,
+ )
+ )
+ lock_file.flush()
+ try:
+ os.fsync(lock_file.fileno())
+ except OSError:
+ logger.debug("Failed to fsync service instance lock", exc_info=True)
+ paths.get_runtime_pid_path().write_text(str(os.getpid()), encoding="utf-8")
+ _SERVICE_INSTANCE_LOCK_HANDLE = lock_file
+
+
+def release_service_instance_lock() -> None:
+ global _SERVICE_INSTANCE_LOCK_HANDLE
+ lock_file = _SERVICE_INSTANCE_LOCK_HANDLE
+ if lock_file is None:
+ return
+ _SERVICE_INSTANCE_LOCK_HANDLE = None
+ try:
+ try:
+ paths.get_runtime_pid_path().unlink(missing_ok=True)
+ except OSError:
+ logger.debug("Failed to remove service pid file while releasing lock", exc_info=True)
+ try:
+ lock_file.seek(0)
+ lock_file.truncate()
+ lock_file.flush()
+ except OSError:
+ logger.debug("Failed to truncate service instance lock", exc_info=True)
+ _unlock_file(lock_file)
+ finally:
+ lock_file.close()
+
+
+def service_instance_lock_available() -> tuple[bool, int | None]:
+ """Return whether the data-dir scoped service lock can be acquired."""
+ paths.ensure_data_dirs()
+ 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 True, None
+ return False, _lock_file_pid(lock_file)
+ finally:
+ lock_file.close()
+
+
def get_shutdown_intent_path() -> Path:
return paths.get_runtime_dir() / "shutdown_intent.json"
@@ -358,8 +497,14 @@ def stop_pid(pid: int, timeout: float = 5) -> bool:
except ProcessLookupError:
return True
except OSError:
- pass
- return True
+ return False
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if not pid_alive(pid):
+ return True
+ time.sleep(0.2)
+ logger.error("Managed SIGKILL did not terminate pid=%s command=%s", pid, get_process_command(pid))
+ return False
def _log_path(name: str) -> Path:
@@ -387,15 +532,66 @@ def spawn_background(args, pid_path, stdout_name: str, stderr_name: str, env: di
return process.pid
+def spawn_service_background(args, stdout_name: str, stderr_name: str, env: dict[str, str] | None = None) -> int:
+ stdout_path = _log_path(stdout_name)
+ stderr_path = _log_path(stderr_name)
+ stdout_path.parent.mkdir(parents=True, exist_ok=True)
+ stdout = stdout_path.open("ab")
+ stderr = stderr_path.open("ab")
+ try:
+ process = subprocess.Popen(
+ args,
+ stdout=stdout,
+ stderr=stderr,
+ start_new_session=True,
+ cwd=str(get_working_dir()),
+ close_fds=True,
+ env=env,
+ )
+ finally:
+ stdout.close()
+ stderr.close()
+ return process.pid
+
+
+def wait_for_service_pid(pid: int, timeout: float = 5.0) -> bool:
+ deadline = time.monotonic() + timeout
+ pid_path = paths.get_runtime_pid_path()
+ while 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):
+ return True
+ if not pid_alive(pid):
+ return False
+ time.sleep(0.1)
+ return False
+
+
def stop_process(pid_path, timeout=5):
if not pid_path.exists():
return False
- pid = int(pid_path.read_text(encoding="utf-8").strip())
+ try:
+ pid = int(pid_path.read_text(encoding="utf-8").strip())
+ except (OSError, ValueError):
+ pid_path.unlink(missing_ok=True)
+ return False
if not pid_alive(pid):
pid_path.unlink(missing_ok=True)
return False
stopped = stop_pid(pid, timeout=timeout)
- pid_path.unlink(missing_ok=True)
+ if stopped:
+ pid_path.unlink(missing_ok=True)
+ else:
+ logger.error(
+ "Failed to stop pid=%s from %s; preserving pid file so future starts do not orphan it",
+ pid,
+ pid_path,
+ )
return stopped
@@ -468,12 +664,16 @@ def render_status():
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(get_restart_status_path())
+ if restart_status:
+ status["restart"] = restart_status
return json.dumps(status, indent=2)
def start_service():
with _SERVICE_LOCK:
pid_path = paths.get_runtime_pid_path()
+ existing_pid = 0
if pid_path.exists():
try:
existing_pid = int(pid_path.read_text(encoding="utf-8").strip())
@@ -488,10 +688,15 @@ def start_service():
)
pid_path.unlink(missing_ok=True)
+ lock_available, lock_holder_pid = service_instance_lock_available()
+ if not lock_available:
+ if lock_holder_pid and lock_holder_pid == existing_pid and pid_alive(lock_holder_pid):
+ return lock_holder_pid
+ raise ServiceAlreadyRunningError(lock_path=get_service_lock_path(), holder_pid=lock_holder_pid)
+
main_path = get_service_main_path()
- return spawn_background(
+ pid = spawn_service_background(
[sys.executable, str(main_path)],
- pid_path,
"service_stdout.log",
"service_stderr.log",
env={
@@ -500,6 +705,9 @@ 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")
+ return pid
def _ui_health_url(host: str, port: int) -> str:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 496a414de..fa845a7dd 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -106,6 +106,27 @@ def _serialize_log_entries(entries: list[dict[str, Any]]) -> list[dict[str, str]
]
+def _runtime_pid_file_points_to_live_process(pid_path: Path) -> bool:
+ from vibe import runtime
+
+ try:
+ raw_pid = pid_path.read_text(encoding="utf-8").strip()
+ pid = int(raw_pid)
+ except (OSError, ValueError):
+ return False
+ return runtime.pid_alive(pid)
+
+
+def _stop_runtime_process_or_error(pid_path: Path, label: str) -> tuple[bool, str | None]:
+ from vibe import runtime
+
+ was_running = _runtime_pid_file_points_to_live_process(pid_path)
+ stopped = runtime.stop_process(pid_path)
+ if was_running and stopped is False:
+ return False, f"{label} did not stop"
+ return True, None
+
+
def _new_csrf_token() -> str:
return secrets.token_urlsafe(32)
@@ -1419,6 +1440,7 @@ def version():
def control():
from vibe import runtime
from vibe.cli import _stop_opencode_server
+ from vibe.restart_supervisor import schedule_restart
payload = request.json or {}
action = payload.get("action")
@@ -1430,19 +1452,16 @@ def control():
runtime.write_status("running", "started", service_pid, status.get("ui_pid"))
elif action == "stop":
runtime.write_status("stopping", "stopping", status.get("service_pid"), status.get("ui_pid"))
- runtime.stop_service()
+ stopped, error = _stop_runtime_process_or_error(paths.get_runtime_pid_path(), "Vibe service")
+ if not stopped:
+ runtime.write_status("error", error, status.get("service_pid"), status.get("ui_pid"))
+ return jsonify({"ok": False, "action": action, "error": error, "status": runtime.read_status()}), 500
_stop_opencode_server()
runtime.write_status("stopped", "stopped", None, status.get("ui_pid"))
elif action == "restart":
- import time
-
runtime.write_status("restarting", "restarting", status.get("service_pid"), status.get("ui_pid"))
- runtime.stop_service()
- _stop_opencode_server()
- time.sleep(3)
- runtime.ensure_config()
- service_pid = runtime.start_service()
- runtime.write_status("running", "restarted", service_pid, status.get("ui_pid"))
+ result = schedule_restart(delay_seconds=0.0, trigger="web-ui")
+ return jsonify({"ok": True, "action": action, "restart": result, "status": runtime.read_status()})
return jsonify({"ok": True, "action": action, "status": runtime.read_status()})