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(restart): serialize overlap guard, expire stale pid-less status, retry instead of false-success

cyh4b909b595cc2
diff --git a/tests/test_ui_server_logs.py b/tests/test_ui_server_logs.py
index 79c09e270..fe8041d5c 100644
--- a/tests/test_ui_server_logs.py
+++ b/tests/test_ui_server_logs.py
@@ -328,3 +328,65 @@ def test_control_restart_rejects_overlapping_restart(monkeypatch, tmp_path):
assert response.status_code == 409
assert response.get_json()["code"] == "restart_in_progress"
assert calls == [] # no second job scheduled
+
+
+def test_control_restart_ignores_dead_supervisor(monkeypatch, tmp_path):
+ """A 'running' status whose supervisor pid is dead is stale and must NOT
+ block a new restart."""
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ from vibe.ui_server import app
+ import vibe.restart_supervisor as restart_supervisor
+
+ paths.ensure_data_dirs()
+ dead_pid = 2_000_000_000 # not a live process
+ runtime.write_json(
+ runtime.get_restart_status_path(),
+ {"state": "running", "supervisor_pid": dead_pid, "job_id": "stale"},
+ )
+ calls = []
+ monkeypatch.setattr(
+ restart_supervisor,
+ "schedule_restart",
+ lambda **kwargs: calls.append(kwargs) or {"job_id": "x", "state": "scheduled"},
+ )
+
+ client = app.test_client()
+ response = client.post("/api/control", json={"action": "restart"}, headers=csrf_headers(client))
+
+ assert response.status_code == 200
+ assert len(calls) == 1 # the stale status did not block
+
+
+def test_control_restart_ignores_stale_pidless_seed(monkeypatch, tmp_path):
+ """A pid-less 'scheduled' seed older than the grace window (the supervisor
+ died before recording its pid) is stale and must NOT block restarts forever;
+ a FRESH pid-less seed still blocks (the child is just starting)."""
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ import time as _time
+
+ from vibe.ui_server import app
+ import vibe.restart_supervisor as restart_supervisor
+
+ paths.ensure_data_dirs()
+ status_path = runtime.get_restart_status_path()
+ runtime.write_json(status_path, {"state": "scheduled", "supervisor_pid": None, "job_id": "seed"})
+
+ calls = []
+ monkeypatch.setattr(
+ restart_supervisor,
+ "schedule_restart",
+ lambda **kwargs: calls.append(kwargs) or {"job_id": "x", "state": "scheduled"},
+ )
+ client = app.test_client()
+
+ # Fresh seed → blocks.
+ resp_fresh = client.post("/api/control", json={"action": "restart"}, headers=csrf_headers(client))
+ assert resp_fresh.status_code == 409
+ assert calls == []
+
+ # Age the seed past the grace window → no longer blocks.
+ old = _time.time() - 120
+ os.utime(status_path, (old, old))
+ resp_stale = client.post("/api/control", json={"action": "restart"}, headers=csrf_headers(client))
+ assert resp_stale.status_code == 200
+ assert len(calls) == 1
diff --git a/ui/src/components/settings/SettingsPlatformsPage.tsx b/ui/src/components/settings/SettingsPlatformsPage.tsx
index 5ad3df53d..c6f9bb674 100644
--- a/ui/src/components/settings/SettingsPlatformsPage.tsx
+++ b/ui/src/components/settings/SettingsPlatformsPage.tsx
@@ -108,22 +108,27 @@ export const SettingsPlatformsPage: React.FC = () => {
// the backend normalizes it from ``enabled`` (first enabled, or the workbench
// when empty), so the UI never chooses or sends one.
// Restart only the service (scope:'service') so the open Web UI survives the
- // config change. A "restart_in_progress" rejection is NOT a failure: the
- // config is already saved and the in-flight restart will pick it up, so show
- // a neutral notice. Returns true when the change is applied or queued.
+ // config change. If a prior restart is still in flight, the change is saved
+ // but the running restart may have already read the OLD config — so don't
+ // claim success; retry until this save gets its OWN dedicated restart
+ // (service-only restarts are quick, so a few short retries cover it). Only if
+ // it stays busy do we tell the user it's saved while a restart runs.
const requestServiceRestart = async (): Promise<boolean> => {
- try {
- await control('restart', { scope: 'service' });
- showToast(t('platform.restartedSuccess'), 'success');
- return true;
- } catch (e) {
- if ((e as { code?: string })?.code === 'restart_in_progress') {
- showToast(t('platform.restartInProgress'), 'warning');
+ for (let attempt = 0; attempt < 5; attempt += 1) {
+ try {
+ await control('restart', { scope: 'service' });
+ showToast(t('platform.restartedSuccess'), 'success');
return true;
+ } catch (e) {
+ if ((e as { code?: string })?.code !== 'restart_in_progress') {
+ showToast(t('platform.restartFailed'), 'error');
+ return false;
+ }
+ await new Promise((resolve) => setTimeout(resolve, 1500));
}
- showToast(t('platform.restartFailed'), 'error');
- return false;
}
+ showToast(t('platform.restartInProgress'), 'warning');
+ return false;
};
const persistEnabled = async (nextEnabled: string[]) => {
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 8f5345fe5..dc3992ff2 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2156,6 +2156,37 @@ def version():
# =============================================================================
+# Serializes the restart in-flight check + scheduling below. The UI server runs
+# requests concurrently, so without this two near-simultaneous restart requests
+# could both pass the check before either seeds restart_status.json, scheduling
+# two supervisors that race on the same pid files + lock.
+_RESTART_CONTROL_LOCK = threading.Lock()
+# How long a just-seeded, pid-less "scheduled" status is treated as in flight
+# (its supervisor is still starting up). Past this, a pid-less status is stale
+# (the supervisor died before recording its pid) and must NOT block restarts.
+_RESTART_SEED_GRACE_SECONDS = 60.0
+
+
+def _restart_in_flight() -> bool:
+ """True only when a restart is genuinely still running, so a stale status
+ can never permanently block Web restarts."""
+ from vibe import runtime
+
+ status = runtime.read_json(runtime.get_restart_status_path()) or {}
+ if status.get("state") not in ("scheduled", "running"):
+ return False
+ sup_pid = status.get("supervisor_pid")
+ if isinstance(sup_pid, int):
+ return bool(runtime.pid_alive(sup_pid))
+ # No supervisor pid recorded yet: in flight only while the seed is fresh
+ # (the child is still starting). An older pid-less status is stale.
+ try:
+ age = time.time() - runtime.get_restart_status_path().stat().st_mtime
+ except OSError:
+ return False
+ return age < _RESTART_SEED_GRACE_SECONDS
+
+
@app.route("/api/control", methods=["POST"])
def control():
from vibe import runtime
@@ -2187,27 +2218,24 @@ def control():
# Reject overlapping restarts: a service-only restart leaves the Web UI
# up, so a user (or another tab) could fire a second restart while the
# first supervisor is still bouncing the service — two jobs would race
- # on the same pid files + lock. Block while one is genuinely in flight
- # (a stale status whose supervisor pid is dead does NOT block).
- restart_status = runtime.read_json(runtime.get_restart_status_path()) or {}
- sup_pid = restart_status.get("supervisor_pid")
- if restart_status.get("state") in ("scheduled", "running") and (
- sup_pid is None or runtime.pid_alive(sup_pid)
- ):
- return (
- jsonify(
- {
- "ok": False,
- "action": action,
- "error": "a restart is already in progress",
- "code": "restart_in_progress",
- "status": runtime.read_status(),
- }
- ),
- 409,
- )
- runtime.write_status("restarting", "restarting", status.get("service_pid"), status.get("ui_pid"))
- result = schedule_restart(delay_seconds=0.0, trigger="web-ui", scope=scope)
+ # on the same pid files + lock. The check + schedule are held under one
+ # process lock so two concurrent requests can't both slip through.
+ with _RESTART_CONTROL_LOCK:
+ if _restart_in_flight():
+ return (
+ jsonify(
+ {
+ "ok": False,
+ "action": action,
+ "error": "a restart is already in progress",
+ "code": "restart_in_progress",
+ "status": runtime.read_status(),
+ }
+ ),
+ 409,
+ )
+ runtime.write_status("restarting", "restarting", status.get("service_pid"), status.get("ui_pid"))
+ result = schedule_restart(delay_seconds=0.0, trigger="web-ui", scope=scope)
return jsonify({"ok": True, "action": action, "restart": result, "status": runtime.read_status()})
return jsonify({"ok": True, "action": action, "status": runtime.read_status()})