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): start the Web UI again when it dies under a running service (#2374)

Call White8159227f08e3
diff --git a/Dockerfile b/Dockerfile
index 575f815f8..ada79f092 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -46,6 +46,9 @@ RUN SETUPTOOLS_SCM_PRETEND_VERSION=${SETUPTOOLS_SCM_PRETEND_VERSION} \
# Runtime config
ENV AVIBE_HOME=/data/avibe
ENV PYTHONUNBUFFERED=1
+# The entrypoint supervises the Web UI here, including while the service is
+# stopped, so the service leaves UI recovery to it (core/web_ui_watchdog.py).
+ENV AVIBE_WEB_UI_SUPERVISOR=docker-entrypoint
EXPOSE 5123
diff --git a/core/controller.py b/core/controller.py
index d7463fbf6..e55b98b47 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -45,10 +45,11 @@ from core.scheduled_tasks import ScheduledTaskService
from core.show_git import ShowGitCheckpointService
from core.update_checker import UpdateChecker
from core.watches import ManagedWatchService
+from core.web_ui_watchdog import watch_web_ui
from core.vibe_agents import VibeAgent, VibeAgentStore
from core.blocking import run_blocking
from vibe.i18n import get_supported_languages, t as i18n_t
-from vibe.runtime import mark_service_instance_started
+from vibe.runtime import current_process_owns_service_instance, mark_service_instance_started
if TYPE_CHECKING:
pass
@@ -317,6 +318,7 @@ class Controller:
# Background task for cleanup
self.cleanup_task: Optional[asyncio.Task] = None
self.trace_retention_task: Optional[asyncio.Task] = None
+ self.web_ui_watchdog_task: Optional[asyncio.Task] = None
self._trace_retention_executor: Optional[Any] = None
self._trace_retention_cancel_event: Optional[threading.Event] = None
self._trace_retention_future: Optional[Any] = None
@@ -1165,6 +1167,15 @@ class Controller:
self.trace_retention_task = asyncio.create_task(self._agent_events_retention_loop())
except Exception as e:
logger.error("Failed to start agent trace-event retention: %s", e, exc_info=True)
+ try:
+ # Only the service process owns the runtime's Web UI; a controller
+ # embedded in a test or tool must never start one.
+ if current_process_owns_service_instance() and (
+ self.web_ui_watchdog_task is None or self.web_ui_watchdog_task.done()
+ ):
+ self.web_ui_watchdog_task = asyncio.create_task(watch_web_ui(lambda: self.shutdown_requested))
+ except Exception as e:
+ logger.error("Failed to start the Web UI watchdog: %s", e, exc_info=True)
async def _recover_runtime_owners(self) -> None:
"""Restore durable execution owners before any producer can admit work."""
@@ -2309,6 +2320,16 @@ class Controller:
pass
self.cleanup_task = None
+ async def _cancel_web_ui_watchdog_task() -> None:
+ task = self.web_ui_watchdog_task
+ if task and not task.done():
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ self.web_ui_watchdog_task = None
+
async def _cancel_trace_retention_task() -> None:
cancel_event = getattr(self, "_trace_retention_cancel_event", None)
if cancel_event is not None:
@@ -2353,6 +2374,7 @@ class Controller:
logger.debug(f"Internal dispatch server status write skipped: {e}")
_stop_loop_coroutine(_cancel_cleanup_task(), "Idle cleanup task")
+ _stop_loop_coroutine(_cancel_web_ui_watchdog_task(), "Web UI watchdog task")
# Retention cancellation is cooperative at a delete-batch boundary;
# wait for that bounded join instead of abandoning the worker after
# the generic five-second cleanup timeout.
diff --git a/core/web_ui_watchdog.py b/core/web_ui_watchdog.py
new file mode 100644
index 000000000..73b37f662
--- /dev/null
+++ b/core/web_ui_watchdog.py
@@ -0,0 +1,134 @@
+"""Start the Web UI again when its process dies under a running service.
+
+`vibe`, the restart job, the desktop host and the regression supervisor each
+start the service and the Web UI as sibling processes, and the local ones then
+return. Nothing was left to notice the UI dying on its own: a UI that crashed or
+was killed stayed down, taking the local Web UI and the Avibe Cloud origin with
+it, while the service kept serving IM, until someone ran `vibe` again. The
+service is the long-lived owner of the runtime, so it keeps its Web surface up.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import os
+import time
+from collections.abc import Callable
+
+from core.services.settings import load_config_or_default
+from vibe import runtime
+from vibe.upgrade import RestartState, restart_record_is_pending
+
+logger = logging.getLogger(__name__)
+
+CHECK_INTERVAL_SECONDS = 10.0
+MAX_RETRY_DELAY_SECONDS = 600.0
+# Names the process that supervises the Web UI where one outlives the service,
+# such as the Docker image's entrypoint. It stays the UI's only recovery owner.
+UI_SUPERVISOR_ENV = "AVIBE_WEB_UI_SUPERVISOR"
+
+
+def _restart_job_replacing_the_runtime() -> bool:
+ """Whether a restart job is stopping and starting the runtime right now.
+
+ A job still waiting out its delay has touched nothing yet, so a UI that dies
+ meanwhile is not the job's to bring back.
+ """
+
+ path = runtime.get_restart_status_path()
+ record = runtime.read_json(path)
+ return (
+ isinstance(record, dict)
+ and record.get("state") == RestartState.RUNNING.value
+ and restart_record_is_pending(record, path)
+ )
+
+
+class WebUiWatchdog:
+ """Decides, one observation at a time, when the service starts its Web UI again."""
+
+ def __init__(self, *, stopping: Callable[[], bool]) -> None:
+ self._stopping = stopping
+ self._gone_checks = 0
+ self._attempts_without_recovery = 0
+ self._retry_delay = CHECK_INTERVAL_SECONDS
+ self._retry_at = 0.0
+ self._unrecorded_ui_reported = False
+
+ def _owns_recovery(self) -> bool:
+ # Every deliberate stop takes the service down with the UI, and a
+ # restart job brings the UI back itself.
+ return not (
+ self._stopping()
+ or not runtime.current_process_owns_service_instance()
+ or _restart_job_replacing_the_runtime()
+ )
+
+ def check(self, now: float) -> int | None:
+ """Observe the UI once; return the pid of a UI this check started."""
+
+ if not runtime.recorded_ui_is_gone():
+ self._gone_checks = 0
+ self._attempts_without_recovery = 0
+ self._retry_delay = CHECK_INTERVAL_SECONDS
+ self._retry_at = 0.0
+ self._unrecorded_ui_reported = False
+ return None
+ # A stop, a restart, and a start replacing a stale UI each pass through
+ # a moment with no live UI recorded. A UI gone at two consecutive checks
+ # is gone; one gone at a single check may be in transit.
+ self._gone_checks += 1
+ if self._gone_checks < 2 or now < self._retry_at:
+ return None
+ self._gone_checks = 0
+
+ config = load_config_or_default()
+ host, port = runtime.effective_ui_bind_host(config), config.ui.setup_port
+ if runtime.ui_server_compatible(host, port):
+ # An Avibe UI, ready or not, holds the port without being the
+ # recorded one. Another would only die on the port, and its pid
+ # record would then name the dead replacement instead of it. No
+ # start was attempted, so the retry delay stays where it was.
+ if not self._unrecorded_ui_reported:
+ logger.warning("Web UI on port %s is serving but is not the recorded UI process; leaving it", port)
+ self._unrecorded_ui_reported = True
+ return None
+ # Asked last, after the probe that can take seconds, so a stop or a
+ # restart that began meanwhile is seen before anything is started.
+ if not self._owns_recovery():
+ return None
+
+ self._attempts_without_recovery += 1
+ # A UI that keeps dying is retried less and less often instead of
+ # being respawned every few seconds for as long as the service runs.
+ self._retry_delay = min(self._retry_delay * 2, MAX_RETRY_DELAY_SECONDS)
+ self._retry_at = now + self._retry_delay
+ logger.warning(
+ "Web UI is not running; starting it again (attempt %s since it was last seen running)",
+ self._attempts_without_recovery,
+ )
+ pid = runtime.start_ui(host, port)
+ if pid is None:
+ logger.error("Web UI could not be started again")
+ return None
+ status = runtime.read_status()
+ runtime.write_status(status.get("state", "running"), status.get("detail"), status.get("service_pid"), pid)
+ logger.info("Web UI started again pid=%s", pid)
+ return pid
+
+
+async def watch_web_ui(stopping: Callable[[], bool], *, interval: float = CHECK_INTERVAL_SECONDS) -> None:
+ """Keep the Web UI running until the service stops."""
+
+ supervisor = os.environ.get(UI_SUPERVISOR_ENV)
+ if supervisor:
+ logger.info("Web UI recovery is left to its supervisor: %s", supervisor)
+ return
+ watchdog = WebUiWatchdog(stopping=stopping)
+ while not stopping():
+ await asyncio.sleep(interval)
+ try:
+ await asyncio.to_thread(watchdog.check, time.monotonic())
+ except Exception:
+ logger.error("Web UI watchdog check failed", exc_info=True)
diff --git a/scripts/incus_regression_supervisor.py b/scripts/incus_regression_supervisor.py
index 7fdfe5f37..fe6bced15 100644
--- a/scripts/incus_regression_supervisor.py
+++ b/scripts/incus_regression_supervisor.py
@@ -151,16 +151,11 @@ def main() -> int:
_reap_child(service_pid)
service_pid = current_service_pid
+ # The service starts a UI that died again (core/web_ui_watchdog.py), as
+ # it does outside Incus; this loop only reaps the one it started itself.
current_ui_pid = _read_pid_file(paths.get_runtime_ui_pid_path()) or ui_pid
if not current_ui_pid or not runtime.pid_alive(current_ui_pid):
_reap_child(current_ui_pid)
- if not _restart_in_progress():
- config = _config()
- ui_pid = runtime.start_ui(
- runtime.effective_ui_bind_host(config),
- config.ui.setup_port,
- )
- runtime.write_status("running", "ui restarted in incus regression", service_pid, ui_pid)
elif current_ui_pid != ui_pid:
ui_pid = current_ui_pid
diff --git a/tests/test_desktop_runtime.py b/tests/test_desktop_runtime.py
index 5129107ba..eb76f657f 100644
--- a/tests/test_desktop_runtime.py
+++ b/tests/test_desktop_runtime.py
@@ -768,7 +768,7 @@ def test_ui_server_compatibility_accepts_versioned_not_ready_identity(monkeypatc
monkeypatch.setattr(runtime.urllib.request, "urlopen", fake_urlopen)
assert runtime.ui_server_healthy("100.97.103.112", 5123) is False
- assert runtime._ui_server_compatible("100.97.103.112", 5123) is True
+ assert runtime.ui_server_compatible("100.97.103.112", 5123) is True
@pytest.mark.parametrize(
@@ -814,7 +814,7 @@ def test_ui_server_compatibility_rejects_invalid_not_ready_identity(monkeypatch,
monkeypatch.setattr(runtime.urllib.request, "urlopen", fake_urlopen)
- assert runtime._ui_server_compatible("100.97.103.112", 5123) is False
+ assert runtime.ui_server_compatible("100.97.103.112", 5123) is False
def test_ui_server_compatibility_rejects_a_valid_runtime_identity_invalid_response(monkeypatch):
@@ -850,7 +850,7 @@ def test_ui_server_compatibility_rejects_a_valid_runtime_identity_invalid_respon
monkeypatch.setattr(runtime.urllib.request, "urlopen", fake_urlopen)
- assert runtime._ui_server_compatible("100.97.103.112", 5123) is False
+ assert runtime.ui_server_compatible("100.97.103.112", 5123) is False
def test_start_ui_replaces_a_ui_with_an_invalid_runtime_identity(tmp_path, monkeypatch):
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index ff1c7e981..6dc2eec3d 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -1373,7 +1373,7 @@ def start_runtime(monkeypatch):
monkeypatch.setattr(runtime.psutil, "Process", fake_process)
monkeypatch.setattr(runtime, "_pid_mismatches_service", lambda pid: False)
monkeypatch.setattr(runtime, "_pid_matches_ui_server", lambda pid: True)
- monkeypatch.setattr(runtime, "_ui_server_compatible", lambda host, port: True)
+ monkeypatch.setattr(runtime, "ui_server_compatible", lambda host, port: True)
monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: True)
monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout: pid)
monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (True, None))
@@ -1624,7 +1624,7 @@ def test_cmd_start_reuses_independent_ui_or_recovers_only_unhealthy_ui(monkeypat
monkeypatch.setattr(runtime, "ui_server_healthy", lambda *args: ui_state == "healthy")
# This tree adopts a UI through its identity-checked readiness probe; stub it
# like the health probe so no real loopback listener is consulted.
- monkeypatch.setattr(runtime, "_ui_server_compatible", lambda *args, **kwargs: ui_state == "healthy")
+ monkeypatch.setattr(runtime, "ui_server_compatible", lambda *args, **kwargs: ui_state == "healthy")
monkeypatch.setattr(runtime, "process_create_time", lambda pid: 1789010100.0 + pid)
monkeypatch.setattr(runtime, "wait_for_ui_server", lambda *args: True)
monkeypatch.setattr(runtime, "current_service_launcher", lambda: SimpleNamespace(python="test-owned-python"))
@@ -4521,7 +4521,7 @@ def test_start_ui_reuses_existing_live_pid(tmp_path, monkeypatch):
monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 12345)
monkeypatch.setattr(
runtime,
- "_ui_server_compatible",
+ "ui_server_compatible",
lambda host, port: host == "127.0.0.1" and port == 5123,
)
monkeypatch.setattr(
@@ -4574,10 +4574,10 @@ def test_start_ui_replaces_stale_live_pid_when_health_check_fails(tmp_path, monk
stopped = []
monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 12345)
- # Adoption is decided by `_ui_server_compatible`, which probes the real
+ # Adoption is decided by `ui_server_compatible`, which probes the real
# listener. Stubbing only `ui_server_healthy` let this test reach whatever
# answers on 127.0.0.1:5123 -- a developer's own running UI -- and adopt it.
- monkeypatch.setattr(runtime, "_ui_server_compatible", lambda host, port: False)
+ monkeypatch.setattr(runtime, "ui_server_compatible", lambda host, port: False)
monkeypatch.setattr(
runtime,
"get_process_command",
diff --git a/tests/test_web_ui_watchdog.py b/tests/test_web_ui_watchdog.py
new file mode 100644
index 000000000..a4b67419a
--- /dev/null
+++ b/tests/test_web_ui_watchdog.py
@@ -0,0 +1,220 @@
+from __future__ import annotations
+
+import asyncio
+import os
+
+import pytest
+
+from config import paths
+from config.v2_config import V2Config
+from core.web_ui_watchdog import CHECK_INTERVAL_SECONDS, UI_SUPERVISOR_ENV, WebUiWatchdog, watch_web_ui
+from vibe import runtime
+
+UI_COMMAND = "python3 -c from vibe.ui_server import run_ui_server; run_ui_server('127.0.0.1', 5199)"
+
+
+class Processes:
+ """The processes the host reports: pid -> command, or None when unreadable."""
+
+ def __init__(self) -> None:
+ self.commands: dict[int, str | None] = {}
+ self.serving = False
+ self.starts: list[tuple[str, int]] = []
+
+ def start_ui(self, host, port, **kwargs):
+ # Like the real start: the new pid is recorded before it returns.
+ pid = 300 + len(self.starts) + 1
+ self.starts.append((host, port))
+ self.commands[pid] = UI_COMMAND
+ paths.get_runtime_ui_pid_path().write_text(str(pid), encoding="utf-8")
+ return pid
+
+ def kill(self, pid: int) -> None:
+ self.commands.pop(pid, None)
+
+
+def host(monkeypatch, tmp_path):
+ """A home whose service runs and whose recorded Web UI, pid 200, has died."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ config = V2Config.default()
+ config.ui.setup_host = "127.0.0.1"
+ config.ui.setup_port = 5199
+ config.save(paths.get_config_path())
+ runtime.write_status("running", "pid=100", 100, 200)
+ paths.get_runtime_ui_pid_path().write_text("200", encoding="utf-8")
+
+ processes = Processes()
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid in processes.commands)
+ monkeypatch.setattr(runtime, "get_process_command", lambda pid: processes.commands.get(pid))
+ monkeypatch.setattr(runtime, "ui_server_compatible", lambda host, port, **kwargs: processes.serving)
+ monkeypatch.setattr(runtime, "current_process_owns_service_instance", lambda: True)
+ monkeypatch.setattr(runtime, "start_ui", processes.start_ui)
+ return processes
+
+
+def test_a_ui_gone_for_two_checks_is_started_again_with_the_status_kept(host) -> None:
+ """The 2026-10-06 outage: the UI was killed and nothing started it while the service ran."""
+
+ started_at = runtime.read_status()["started_at"]
+ watchdog = WebUiWatchdog(stopping=lambda: False)
+
+ assert watchdog.check(0.0) is None
+ assert host.starts == []
+ assert watchdog.check(CHECK_INTERVAL_SECONDS) == 301
+
+ assert host.starts == [("127.0.0.1", 5199)]
+ status = runtime.read_status()
+ assert (status["state"], status["detail"], status["service_pid"], status["ui_pid"]) == (
+ "running",
+ "pid=100",
+ 100,
+ 301,
+ )
+ assert status["started_at"] == started_at
+
+
+ ("recorded", "command", "started"),
+ [
+ pytest.param("200", None, True, id="recorded-pid-dead"),
+ pytest.param(None, None, True, id="no-record"),
+ pytest.param("200", "/usr/bin/some-other-program", True, id="pid-reused-by-another-program"),
+ pytest.param("200", UI_COMMAND, False, id="ui-running"),
+ # A command the host will not show: the UI may be running, and a second
+ # one would die on its port with the record pointing at it.
+ pytest.param("200", "", False, id="live-pid-command-unreadable"),
+ ],
+)
+def test_only_a_ui_known_to_be_gone_is_started_again(host, recorded, command, started) -> None:
+ if recorded is None:
+ paths.get_runtime_ui_pid_path().unlink()
+ if command is not None:
+ host.commands[200] = command or None
+ watchdog = WebUiWatchdog(stopping=lambda: False)
+
+ watchdog.check(0.0)
+ watchdog.check(CHECK_INTERVAL_SECONDS)
+
+ assert bool(host.starts) is started
+
+
+def _restart_job(state: str) -> None:
+ runtime.write_json(
+ runtime.get_restart_status_path(),
+ {
+ "ok": None,
+ "state": state,
+ "supervisor_pid": os.getpid(),
+ "supervisor_started_at": runtime.process_create_time(os.getpid()),
+ },
+ )
+
+
+ ("stopping", "owner", "restart_job", "serving"),
+ [
+ pytest.param(True, True, False, False, id="service-stopping"),
+ pytest.param(False, False, False, False, id="no-longer-the-service"),
+ pytest.param(False, True, True, False, id="restart-job-owns-the-ui"),
+ # An Avibe UI holds the port, ready or not, without being recorded.
+ pytest.param(False, True, False, True, id="port-already-held"),
+ ],
+)
+def test_no_ui_is_started_where_it_would_fight_another_owner(
+ monkeypatch, host, stopping, owner, restart_job, serving
+) -> None:
+ monkeypatch.setattr(runtime, "current_process_owns_service_instance", lambda: owner)
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == os.getpid() or pid in host.commands)
+ if restart_job:
+ _restart_job("running")
+ host.serving = serving
+ watchdog = WebUiWatchdog(stopping=lambda: stopping)
+
+ for tick in range(4):
+ assert watchdog.check(tick * CHECK_INTERVAL_SECONDS) is None
+
+ assert host.starts == []
+
+
[email protected]("begins", ["stop", "owner-lost", "restart"])
+def test_a_stop_or_restart_that_begins_during_the_port_probe_starts_nothing(monkeypatch, host, begins) -> None:
+ state = {"stopping": False, "owner": True}
+ monkeypatch.setattr(runtime, "current_process_owns_service_instance", lambda: state["owner"])
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == os.getpid() or pid in host.commands)
+
+ def probe(host_, port, **kwargs):
+ # The probe takes seconds; the lifecycle change lands inside it.
+ if begins == "stop":
+ state["stopping"] = True
+ elif begins == "owner-lost":
+ state["owner"] = False
+ else:
+ _restart_job("running")
+ return False
+
+ monkeypatch.setattr(runtime, "ui_server_compatible", probe)
+ watchdog = WebUiWatchdog(stopping=lambda: state["stopping"])
+
+ watchdog.check(0.0)
+ assert watchdog.check(CHECK_INTERVAL_SECONDS) is None
+
+ assert host.starts == []
+
+
+def test_an_unrecorded_ui_holding_the_port_does_not_delay_recovery_once_it_exits(host) -> None:
+ host.serving = True
+ watchdog = WebUiWatchdog(stopping=lambda: False)
+ for tick in range(60):
+ assert watchdog.check(tick * CHECK_INTERVAL_SECONDS) is None
+
+ host.serving = False
+ now = 60 * CHECK_INTERVAL_SECONDS
+ watchdog.check(now)
+
+ assert watchdog.check(now + CHECK_INTERVAL_SECONDS) == 301
+
+
+def test_a_restart_still_waiting_out_its_delay_does_not_hold_the_ui_down(monkeypatch, host) -> None:
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == os.getpid() or pid in host.commands)
+ _restart_job("scheduled")
+ watchdog = WebUiWatchdog(stopping=lambda: False)
+
+ watchdog.check(0.0)
+
+ assert watchdog.check(CHECK_INTERVAL_SECONDS) == 301
+
+
+def test_a_ui_that_keeps_dying_is_retried_less_often_until_it_stays_up(host) -> None:
+ watchdog = WebUiWatchdog(stopping=lambda: False)
+
+ def tick(now: float) -> int | None:
+ started = watchdog.check(now)
+ if started is not None:
+ # Each replacement dies before the next check sees it.
+ host.kill(started)
+ return started
+
+ started = [now for now in range(0, 200, 10) if tick(float(now)) is not None]
+ assert started == [10, 30, 70, 150]
+
+ host.commands[999] = UI_COMMAND
+ paths.get_runtime_ui_pid_path().write_text("999", encoding="utf-8")
+ assert watchdog.check(200.0) is None
+ host.kill(999)
+ watchdog.check(210.0)
+ assert watchdog.check(220.0) is not None
+
+
+def test_a_ui_with_its_own_supervisor_is_left_to_it(monkeypatch, host) -> None:
+ """The Docker entrypoint restarts its UI on its own address, even with the service stopped."""
+
+ monkeypatch.setenv(UI_SUPERVISOR_ENV, "docker-entrypoint")
+ checks: list[float] = []
+ monkeypatch.setattr(WebUiWatchdog, "check", lambda self, now: checks.append(now))
+
+ asyncio.run(asyncio.wait_for(watch_web_ui(lambda: False, interval=0), timeout=1))
+
+ assert checks == []
diff --git a/vibe/runtime.py b/vibe/runtime.py
index c97e76cfc..33e49629c 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -2327,7 +2327,7 @@ def ui_server_healthy(host: str, port: int, timeout: float = 0.5) -> bool:
return _ui_server_readiness(host, port, timeout=timeout) is True
-def _ui_server_compatible(
+def ui_server_compatible(
host: str,
port: int,
timeout: float = UI_ADOPTION_PROBE_TIMEOUT_SECONDS,
@@ -2360,6 +2360,21 @@ def ui_pid_file_points_to_running_ui(pid_path: Path | None = None) -> bool:
return bool(pid and pid_alive(pid) and _pid_matches_ui_server(pid))
+def recorded_ui_is_gone(pid_path: Path | None = None) -> bool:
+ """Whether no UI runs under the recorded pid, as far as can be known.
+
+ Gone means no record, a dead pid, or a pid now running another program. A
+ live pid whose command cannot be read is not gone: it may be the UI, and one
+ started beside it would only die on its port.
+ """
+
+ pid = _read_pid_file(pid_path or paths.get_runtime_ui_pid_path())
+ if not pid or not pid_alive(pid):
+ return True
+ command = get_process_command(pid)
+ return command is not None and not _is_ui_server_command(command)
+
+
def resolve_localhost_family() -> str:
"""Return the loopback family ``localhost`` actually maps to on this host.
@@ -2446,7 +2461,7 @@ def start_ui(
existing_pid = 0
if existing_pid and pid_alive(existing_pid):
is_ui_server = _claim_recorded_ui(existing_pid)
- if is_ui_server and _ui_server_compatible(host, port):
+ if is_ui_server and ui_server_compatible(host, port):
if start_info is not None:
start_info.capture(existing_pid, reused=True)
return existing_pid